simplify string utilities
This commit is contained in:
+35
-10
@@ -2,10 +2,12 @@
|
||||
|
||||
#include <random>
|
||||
|
||||
#include "boost/algorithm/string/trim.hpp"
|
||||
|
||||
namespace webcc {
|
||||
|
||||
// Ref: https://stackoverflow.com/a/24586587
|
||||
std::string random_string(std::size_t length) {
|
||||
std::string RandomString(std::size_t length) {
|
||||
static const char chrs[] =
|
||||
"0123456789"
|
||||
"abcdefghijklmnopqrstuvwxyz"
|
||||
@@ -13,7 +15,7 @@ std::string random_string(std::size_t length) {
|
||||
|
||||
thread_local static std::mt19937 rg{ std::random_device{}() };
|
||||
thread_local static std::uniform_int_distribution<std::string::size_type>
|
||||
pick(0, sizeof(chrs) - 2);
|
||||
pick{ 0, sizeof(chrs) - 2 };
|
||||
|
||||
std::string s;
|
||||
s.reserve(length);
|
||||
@@ -25,7 +27,7 @@ std::string random_string(std::size_t length) {
|
||||
return s;
|
||||
}
|
||||
|
||||
bool to_size_t(const std::string& str, int base, std::size_t* size) {
|
||||
bool ToSizeT(const std::string& str, int base, std::size_t* size) {
|
||||
try {
|
||||
*size = static_cast<std::size_t>(std::stoul(str, 0, base));
|
||||
} catch (const std::exception&) {
|
||||
@@ -34,19 +36,42 @@ bool to_size_t(const std::string& str, int base, std::size_t* size) {
|
||||
return true;
|
||||
}
|
||||
|
||||
bool split_kv(std::string& key, std::string& value, const std::string& str,
|
||||
char delim, bool trim_spaces) {
|
||||
std::size_t pos = str.find(delim);
|
||||
void Split(boost::string_view input, char delim, bool compress_token,
|
||||
std::vector<boost::string_view>* output) {
|
||||
std::size_t i = 0;
|
||||
std::size_t p = 0;
|
||||
|
||||
i = input.find(delim);
|
||||
|
||||
while (i != boost::string_view::npos) {
|
||||
output->emplace_back(input.substr(p, i - p));
|
||||
p = i + 1;
|
||||
|
||||
if (compress_token) {
|
||||
while (input[p] == delim) {
|
||||
++p;
|
||||
}
|
||||
}
|
||||
|
||||
i = input.find(delim, p);
|
||||
}
|
||||
|
||||
output->emplace_back(input.substr(p, i - p));
|
||||
}
|
||||
|
||||
bool SplitKV(const std::string& input, char delim, bool trim_spaces,
|
||||
std::string* key, std::string* value) {
|
||||
std::size_t pos = input.find(delim);
|
||||
if (pos == std::string::npos) {
|
||||
return false;
|
||||
}
|
||||
|
||||
key = str.substr(0, pos);
|
||||
value = str.substr(pos + 1);
|
||||
*key = input.substr(0, pos);
|
||||
*value = input.substr(pos + 1);
|
||||
|
||||
if (trim_spaces) {
|
||||
trim(key);
|
||||
trim(value);
|
||||
boost::trim(*key);
|
||||
boost::trim(*value);
|
||||
}
|
||||
|
||||
return true;
|
||||
|
||||
Reference in New Issue
Block a user