diff --git a/include/maxscale/utils.hh b/include/maxscale/utils.hh index 916f97e2f..5ed71b844 100644 --- a/include/maxscale/utils.hh +++ b/include/maxscale/utils.hh @@ -30,6 +30,7 @@ #include #include #include +#include namespace maxscale { @@ -44,17 +45,7 @@ namespace maxscale */ inline std::vector strtok(std::string str, const char* delim) { - std::vector rval; - char* save_ptr; - char* tok = strtok_r(&str[0], delim, &save_ptr); - - while (tok) - { - rval.emplace_back(tok); - tok = strtok_r(NULL, delim, &save_ptr); - } - - return rval; + return mxb::strtok(str, delim); } /** diff --git a/maxutils/maxbase/include/maxbase/string.hh b/maxutils/maxbase/include/maxbase/string.hh index 6243d424e..ced610696 100644 --- a/maxutils/maxbase/include/maxbase/string.hh +++ b/maxutils/maxbase/include/maxbase/string.hh @@ -15,6 +15,9 @@ #include #include #include +#include +#include +#include /** * Thread-safe (but not re-entrant) strerror. @@ -143,4 +146,54 @@ inline std::string trimmed_copy(const std::string& original) return s; } +/** + * Tokenize a string + * + * @param str String to tokenize + * @param delim List of delimiters (see strtok(3)) + * + * @return List of tokenized strings + */ +inline std::vector strtok(std::string str, const char* delim) +{ + std::vector rval; + char* save_ptr; + char* tok = strtok_r(&str[0], delim, &save_ptr); + + while (tok) + { + rval.emplace_back(tok); + tok = strtok_r(NULL, delim, &save_ptr); + } + + return rval; +} + +/** + * Join objects into a string delimited by separators + * + * @param container Container that provides iterators, stored value must support writing to ostream with + * operator<< + * @param separator Value used as the separator + * + * @return String created by joining all values and delimiting them with `separator` (no trailing delimiter) + */ +template +std::string join(const T& container, const std::string& separator = ",") +{ + std::stringstream ss; + auto it = begin(container); + + if (it != end(container)) + { + ss << *it++; + + while (it != end(container)) + { + ss << separator << *it++; + } + } + + return ss.str(); +} }