From c23733d2882f8d0b47e3685b2ccdf899397511d8 Mon Sep 17 00:00:00 2001 From: Federico Igne Date: Fri, 15 Dec 2023 18:21:49 +0100 Subject: feat(cpp): add 'accumulate' and 'trim' util functions --- 2023/include/util.h | 52 ++++++++++++++++++++++++++++++++++++++++++---------- 1 file changed, 42 insertions(+), 10 deletions(-) diff --git a/2023/include/util.h b/2023/include/util.h index 1b5f1c5..e396e3c 100644 --- a/2023/include/util.h +++ b/2023/include/util.h @@ -5,35 +5,67 @@ #include #include #include +#include namespace util { -/* TODO */ +namespace separators +{ + constexpr char SPACE[] = " "; constexpr char COLON[] = ":"; constexpr char SEMICOLON[] = ";"; +constexpr char COMMA[] = ","; -inline void trim(std::string& str) +} + +/** @brief Trims a string view. + * + * @param the string view. + */ +inline void trim(std::string_view& view) { - str.erase(str.begin(), std::find_if_not(str.cbegin(), str.cend(), ::isspace)); - str.erase(std::find_if_not(str.crbegin(), str.crend(), ::isspace).base(), str.end()); + std::string_view spaces{ " \f\r\n\t\v" }; + if (auto n = view.find_first_not_of(spaces); n != view.npos) + { + view.remove_prefix(n); + } + if (auto n = view.find_last_not_of(spaces); n != view.npos) + { + view.remove_suffix(view.size() - n - 1); + } } +/** @brief Split a string view according to a delimiter. + * + * This function applies a custom callable to all substring of a string + * view generated by splitting it according to a delimiter. + * + * @tparam delim the delimiter to split the string view. + * @tparam Accumulate a callable to call on each substring. + * @param view the string view. + * @param the callable object. + */ template -void accumulate(const std::string& str, Accumulate acc) +void accumulate(std::string_view& view, Accumulate acc) { - size_t pos{}; + size_t from{}, to; std::string elem; - while ((pos = str.find(delim)) != std::string::npos) { - auto sub = str.substr(0, pos); + while ((to = view.find(delim, from)) != std::string_view::npos) { + auto sub = view.substr(from, to - from); + trim(sub); + acc(sub); + from = to + std::strlen(delim); + } + auto sub = view.substr(from); + if (not sub.empty()) + { trim(sub); acc(sub); - pos += std::strlen(delim); } } -/* ---- */ /** @brief Discard element from stream by type. * -- cgit v1.2.3