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.
This commit is contained in:
Misa
2021-02-07 13:09:47 -08:00
committed by Ethan Lee
parent e1ae25b29b
commit 46b0257cf1
2 changed files with 35 additions and 6 deletions

View File

@@ -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<std::string> split( const std::string &s, char delim, std::vector<std::string> &elems )