diff options
author | Andreas Kling <awesomekling@gmail.com> | 2019-08-04 11:44:20 +0200 |
---|---|---|
committer | Andreas Kling <awesomekling@gmail.com> | 2019-08-04 11:44:20 +0200 |
commit | cce2ea9bb018f39b0e41b865b35a9b66e55075b2 (patch) | |
tree | 2f3b580a1d44eb05a42ea60853a861a11837777d /AK | |
parent | c55129e5735ebecbb6ba9d55f71b49884109e5d2 (diff) | |
download | serenity-cce2ea9bb018f39b0e41b865b35a9b66e55075b2.zip |
AK: Add StringView::to_int()
This is a shameless copy-paste of String::to_int(). We should find some
way to share this code between String and StringView instead of having
two duplicate copies like this.
Diffstat (limited to 'AK')
-rwxr-xr-x | AK/AKString.h | 1 | ||||
-rw-r--r-- | AK/StringView.cpp | 28 | ||||
-rw-r--r-- | AK/StringView.h | 3 |
3 files changed, 32 insertions, 0 deletions
diff --git a/AK/AKString.h b/AK/AKString.h index bec22ec886..8606d2934e 100755 --- a/AK/AKString.h +++ b/AK/AKString.h @@ -92,6 +92,7 @@ public: static String repeated(char, int count); bool matches(const StringView& pattern, CaseSensitivity = CaseSensitivity::CaseInsensitive) const; + // FIXME: These should be shared between String and StringView somehow! int to_int(bool& ok) const; unsigned to_uint(bool& ok) const; diff --git a/AK/StringView.cpp b/AK/StringView.cpp index 14a26c7f18..2e33eb9645 100644 --- a/AK/StringView.cpp +++ b/AK/StringView.cpp @@ -66,6 +66,34 @@ StringView StringView::substring_view_starting_after_substring(const StringView& return { remaining_characters, remaining_length }; } +int StringView::to_int(bool& ok) const +{ + bool negative = false; + int value = 0; + int i = 0; + + if (is_empty()) { + ok = false; + return 0; + } + + if (characters_without_null_termination()[0] == '-') { + i++; + negative = true; + } + for (; i < length(); i++) { + if (characters_without_null_termination()[i] < '0' || characters_without_null_termination()[i] > '9') { + ok = false; + return 0; + } + value = value * 10; + value += characters_without_null_termination()[i] - '0'; + } + ok = true; + + return negative ? -value : value; +} + unsigned StringView::to_uint(bool& ok) const { unsigned value = 0; diff --git a/AK/StringView.h b/AK/StringView.h index b36cf40db2..7d5d50a99f 100644 --- a/AK/StringView.h +++ b/AK/StringView.h @@ -41,7 +41,10 @@ public: StringView substring_view(int start, int length) const; Vector<StringView> split_view(char) const; + + // FIXME: These should be shared between String and StringView somehow! unsigned to_uint(bool& ok) const; + int to_int(bool& ok) const; // Create a new substring view of this string view, starting either at the beginning of // the given substring view, or after its end, and continuing until the end of this string |