From edb663db73a478adb90131e3e27af919b0a4ac37 Mon Sep 17 00:00:00 2001 From: Federico Igne Date: Tue, 5 Dec 2023 20:21:12 +0100 Subject: feat(cpp): add common utils --- 2023/include/util.h | 92 +++++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 92 insertions(+) create mode 100644 2023/include/util.h (limited to '2023/include/util.h') diff --git a/2023/include/util.h b/2023/include/util.h new file mode 100644 index 0000000..1b5f1c5 --- /dev/null +++ b/2023/include/util.h @@ -0,0 +1,92 @@ +#ifndef UTIL_H +#define UTIL_H + +#include +#include +#include +#include + +namespace util +{ + +/* TODO */ +constexpr char SPACE[] = " "; +constexpr char COLON[] = ":"; +constexpr char SEMICOLON[] = ";"; + +inline void trim(std::string& str) +{ + 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()); +} + +template +void accumulate(const std::string& str, Accumulate acc) +{ + size_t pos{}; + std::string elem; + + while ((pos = str.find(delim)) != std::string::npos) { + auto sub = str.substr(0, pos); + trim(sub); + acc(sub); + pos += std::strlen(delim); + } +} +/* ---- */ + +/** @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 -- cgit v1.2.3