#ifndef UTIL_H #define UTIL_H #include #include #include #include #include namespace util { namespace separators { constexpr char SPACE[] = " "; constexpr char COLON[] = ":"; constexpr char SEMICOLON[] = ";"; constexpr char COMMA[] = ","; } /** @brief Trims a string view. * * @param the string view. */ inline void trim(std::string_view& view) { 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(std::string_view& view, Accumulate acc) { size_t from{}, to; std::string elem; 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); } } /** @brief Discard element from stream by type. * * @tparam T the type of the element to discard. * @param stream the input stream. * * @return the input stream. */ template std::basic_istream& skip(std::basic_istream& stream) { T discard; return stream >> discard; } /** @brief Skip token in stream. * * @tparam keyword the token to skip. * @param stream the input stream. * * @return the input stream. * * @note The token needs to be declared as a `const char[]`, but normally, * string literals are `const char*`. * * ```cpp * constexpr char RESULT[] = "Result:"; * * int main(int argc, char* argv[]) * { * int res; * std::istringstream in{ "Result: 42"} * in >> skip >> res; * * // ... * * return 0 * } * ``` */ template std::basic_istream& skip(std::basic_istream& stream) { std::string word; stream >> word; if (word != keyword) { throw std::invalid_argument("Malformed input"); } return stream; } } // namespace util #endif //UTIL_H