1
Fork 0
mirror of https://github.com/RGBCube/serenity synced 2025-07-25 19:27:44 +00:00

AK: Move to_int(), to_uint() implementations to StringUtils (#1338)

Provide wrappers in String and StringView. Add some tests for the
implementations.
This commit is contained in:
howar6hill 2020-03-02 21:19:33 +08:00 committed by GitHub
parent 918ebabf60
commit d75fa80a7b
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
7 changed files with 141 additions and 73 deletions

View file

@ -59,6 +59,63 @@ namespace StringUtils {
return (mask_ptr == mask_end) && string_ptr == string_end;
}
int convert_to_int(const StringView& str, bool& ok)
{
if (str.is_empty()) {
ok = false;
return 0;
}
bool negative = false;
size_t i = 0;
const auto characters = str.characters_without_null_termination();
if (characters[0] == '-' || characters[0] == '+') {
if (str.length() == 1) {
ok = false;
return 0;
}
i++;
negative = (characters[0] == '-');
}
int value = 0;
for (; i < str.length(); i++) {
if (characters[i] < '0' || characters[i] > '9') {
ok = false;
return 0;
}
value = value * 10;
value += characters[i] - '0';
}
ok = true;
return negative ? -value : value;
}
unsigned convert_to_uint(const StringView& str, bool& ok)
{
if (str.is_empty()) {
ok = false;
return 0;
}
unsigned value = 0;
const auto characters = str.characters_without_null_termination();
for (size_t i = 0; i < str.length(); i++) {
if (characters[i] < '0' || characters[i] > '9') {
ok = false;
return 0;
}
value = value * 10;
value += characters[i] - '0';
}
ok = true;
return value;
}
}
}