From 4d3a234f6019d3f725059b063d162e60b7d9ed5d Mon Sep 17 00:00:00 2001 From: assiduous Date: Tue, 21 Jan 2020 14:13:57 -0800 Subject: StringTools: added CountFloatNumberChars function --- Common/interface/StringTools.h | 76 ++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 76 insertions(+) (limited to 'Common/interface') diff --git a/Common/interface/StringTools.h b/Common/interface/StringTools.h index cc6bc7b6..6b775891 100644 --- a/Common/interface/StringTools.h +++ b/Common/interface/StringTools.h @@ -181,4 +181,80 @@ inline std::string StrToLower(std::string str) return str; } +inline bool IsNum(char c) +{ + return c >= '0' && c <= '9'; +} + +/// Returns the number of chararcters at the beginning of the string that form a +/// floating point number. +inline size_t CountFloatNumberChars(const char* str) +{ + if (str == nullptr) + return 0; + + const auto* num_end = str; + const auto* c = str; + if (*c == 0) + return 0; + + if (*c == '+' || *c == '-') + ++c; + + if (*c == 0) + return 0; + + if (*c == '0' && IsNum(*(c + 1))) + { + // 01 is invalid + return c - str + 1; + } + + while (IsNum(*c)) + num_end = ++c; + + if (*c == '.') + { + if (c != str && IsNum(c[-1])) + { + // . as well as +. or -. are not valid numbers, however 0., +0., and -0. are. + num_end = c + 1; + } + + ++c; + while (IsNum(*c)) + num_end = ++c; + + if (*c == 'e' || *c == 'E') + { + if (c - str < 2 || !IsNum(c[-2])) + { + // .e as well as +.e are invalid + return num_end - str; + } + } + } + else if (*c == 'e' || *c == 'E') + { + if (c - str < 1 || !IsNum(c[-1])) + { + // e as well as e+1 are invalid + return num_end - str; + } + } + + if (*c == 'e' || *c == 'E') + { + ++c; + if (*c != '+' && *c != '-') + return num_end - str; + + ++c; + while (IsNum(*c)) + num_end = ++c; + } + + return num_end - str; +} + } // namespace Diligent -- cgit v1.2.3