From 46b0257cf1cd7acfbf22284786f5273301d2b6f7 Mon Sep 17 00:00:00 2001 From: Misa Date: Sun, 7 Feb 2021 13:09:47 -0800 Subject: [PATCH] Refactor ss_toi() to not use stringstreams Apart from the std::string, this function no longer uses the STL. ss_toi() is a simple function - it converts the input into an int, taking as many digits as possible until it reaches a non-digit character, at which point it stops. It's trivial to implement this without the STL. I could've used Int() here, but that would've required copying the string to a temporary buffer to insert a null-terminator (we can't just use a pointer-and-length data type either, the string functions don't operate like that - one disadvantage of C strings!). Instead, I decided to implement my own conversion to int here, because I don't think the way we humans write our Arabic numerals is going to change anytime soon. Also, the std::string input is now passed by const reference, instead of making a copy - cutting down on unnecessary memory operations. --- desktop_version/src/UtilityClass.cpp | 39 ++++++++++++++++++++++++---- desktop_version/src/UtilityClass.h | 2 +- 2 files changed, 35 insertions(+), 6 deletions(-) diff --git a/desktop_version/src/UtilityClass.cpp b/desktop_version/src/UtilityClass.cpp index 31b571cf..c472583d 100644 --- a/desktop_version/src/UtilityClass.cpp +++ b/desktop_version/src/UtilityClass.cpp @@ -36,12 +36,41 @@ static const char* GCChar(const SDL_GameControllerButton button) } } -int ss_toi( std::string _s ) +int ss_toi(const std::string& str) { - std::istringstream i(_s); - int x = 0; - i >> x; - return x; + int retval = 0; + int place = 1; + bool negative = false; + const int radix = 10; + + for (size_t i = 0; i < str.size(); ++i) + { + const char chr = str[i]; + + if (i == 0 && chr == '-') + { + negative = true; + continue; + } + + if (SDL_isdigit(chr)) + { + retval *= place; + retval += chr - '0'; + place *= radix; + } + else + { + break; + } + } + + if (negative) + { + return -retval; + } + + return retval; } std::vector split( const std::string &s, char delim, std::vector &elems ) diff --git a/desktop_version/src/UtilityClass.h b/desktop_version/src/UtilityClass.h index a24a7dbd..1f9c2c51 100644 --- a/desktop_version/src/UtilityClass.h +++ b/desktop_version/src/UtilityClass.h @@ -5,7 +5,7 @@ #include #include -int ss_toi(std::string _s); +int ss_toi(const std::string& str); std::vector split(const std::string &s, char delim, std::vector &elems);