diff --git a/src/string.cc b/src/string.cc index ae454264..a9840d45 100644 --- a/src/string.cc +++ b/src/string.cc @@ -100,10 +100,19 @@ String indent(StringView str, StringView indent) int str_to_int(StringView str) { - int res = 0; - if (sscanf(str.zstr(), "%i", &res) != 1) - throw runtime_error(str + "is not a number"); - return res; + unsigned int res = 0; + bool negative = false; + for (auto it = str.begin(), end = str.end(); it != end; ++it) + { + const char c = *it; + if (it == str.begin() and c == '-') + negative = true; + else if (c >= '0' and c <= '9') + res = res * 10 + c - '0'; + else + throw runtime_error(str + "is not a number"); + } + return negative ? -(int)res : (int)res; } String to_string(int val) diff --git a/src/unit_tests.cc b/src/unit_tests.cc index 9fb1bae2..5c43c848 100644 --- a/src/unit_tests.cc +++ b/src/unit_tests.cc @@ -139,6 +139,12 @@ void test_string() kak_assert(not subsequence_match("tchou kanaky", "tchou kanaky")); kak_assert(format("Youhou {1} {} {0} \\{}", 10, "hehe", 5) == "Youhou hehe 5 10 {}"); + + kak_assert(str_to_int("5") == 5); + kak_assert(str_to_int(to_string(INT_MAX)) == INT_MAX); + kak_assert(str_to_int(to_string(INT_MIN)) == INT_MIN); + kak_assert(str_to_int("00") == 0); + kak_assert(str_to_int("-0") == 0); } void test_keys()