From 4779bc830a4407f94935285f17fb41d30ae81779 Mon Sep 17 00:00:00 2001 From: Connor McLaughlin Date: Mon, 11 Apr 2022 23:52:05 +1000 Subject: [PATCH] StringUtil: Add more whitespace cleaners and ParseAssignmentString --- common/StringUtil.cpp | 40 ++++++++++++++++++++++++++++++++++++++++ common/StringUtil.h | 4 ++++ 2 files changed, 44 insertions(+) diff --git a/common/StringUtil.cpp b/common/StringUtil.cpp index 33f0bc32d5..7e2c6c2187 100644 --- a/common/StringUtil.cpp +++ b/common/StringUtil.cpp @@ -251,6 +251,27 @@ namespace StringUtil return str.substr(start, end - start + 1); } + void StripWhitespace(std::string* str) + { + { + const char* cstr = str->c_str(); + std::string_view::size_type start = 0; + while (start < str->size() && std::isspace(cstr[start])) + start++; + if (start != 0) + str->erase(0, start); + } + + { + const char* cstr = str->c_str(); + std::string_view::size_type start = str->size(); + while (start > 0 && std::isspace(cstr[start - 1])) + start--; + if (start != str->size()) + str->erase(start); + } + } + std::vector SplitString(const std::string_view& str, char delimiter, bool skip_empty /*= true*/) { std::vector res; @@ -275,6 +296,25 @@ namespace StringUtil return res; } + bool ParseAssignmentString(const std::string_view& str, std::string_view* key, std::string_view* value) + { + const std::string_view::size_type pos = str.find('='); + if (pos == std::string_view::npos) + { + *key = std::string_view(); + *value = std::string_view(); + return false; + } + + *key = StripWhitespace(str.substr(0, pos)); + if (pos != (str.size() - 1)) + *value = StripWhitespace(str.substr(pos + 1)); + else + *value = std::string_view(); + + return true; + } + std::wstring UTF8StringToWideString(const std::string_view& str) { std::wstring ret; diff --git a/common/StringUtil.h b/common/StringUtil.h index f71bd4daaa..f6d085658c 100644 --- a/common/StringUtil.h +++ b/common/StringUtil.h @@ -166,10 +166,14 @@ namespace StringUtil /// Strip whitespace from the start/end of the string. std::string_view StripWhitespace(const std::string_view& str); + void StripWhitespace(std::string* str); /// Splits a string based on a single character delimiter. std::vector SplitString(const std::string_view& str, char delimiter, bool skip_empty = true); + /// Parses an assignment string (Key = Value) into its two components. + bool ParseAssignmentString(const std::string_view& str, std::string_view* key, std::string_view* value); + /// Strided memcpy/memcmp. static inline void StrideMemCpy(void* dst, std::size_t dst_stride, const void* src, std::size_t src_stride, std::size_t copy_size, std::size_t count)