xref: /aosp_15_r20/external/cronet/base/strings/string_number_conversions_internal.h (revision 6777b5387eb2ff775bb5750e3f5d96f37fb7352b)
1 // Copyright 2020 The Chromium Authors
2 // Use of this source code is governed by a BSD-style license that can be
3 // found in the LICENSE file.
4 
5 #ifndef BASE_STRINGS_STRING_NUMBER_CONVERSIONS_INTERNAL_H_
6 #define BASE_STRINGS_STRING_NUMBER_CONVERSIONS_INTERNAL_H_
7 
8 #include <errno.h>
9 #include <stdlib.h>
10 
11 #include <limits>
12 #include <optional>
13 #include <string_view>
14 
15 #include "base/check.h"
16 #include "base/logging.h"
17 #include "base/numerics/safe_math.h"
18 #include "base/strings/string_util.h"
19 #include "base/third_party/double_conversion/double-conversion/double-conversion.h"
20 
21 namespace base {
22 
23 namespace internal {
24 
25 template <typename STR, typename INT>
IntToStringT(INT value)26 static STR IntToStringT(INT value) {
27   // log10(2) ~= 0.3 bytes needed per bit or per byte log10(2**8) ~= 2.4.
28   // So round up to allocate 3 output characters per byte, plus 1 for '-'.
29   const size_t kOutputBufSize =
30       3 * sizeof(INT) + std::numeric_limits<INT>::is_signed;
31 
32   // Create the string in a temporary buffer, write it back to front, and
33   // then return the substr of what we ended up using.
34   using CHR = typename STR::value_type;
35   CHR outbuf[kOutputBufSize];
36 
37   // The ValueOrDie call below can never fail, because UnsignedAbs is valid
38   // for all valid inputs.
39   std::make_unsigned_t<INT> res =
40       CheckedNumeric<INT>(value).UnsignedAbs().ValueOrDie();
41 
42   CHR* end = outbuf + kOutputBufSize;
43   CHR* i = end;
44   do {
45     --i;
46     DCHECK(i != outbuf);
47     *i = static_cast<CHR>((res % 10) + '0');
48     res /= 10;
49   } while (res != 0);
50   if (IsValueNegative(value)) {
51     --i;
52     DCHECK(i != outbuf);
53     *i = static_cast<CHR>('-');
54   }
55   return STR(i, end);
56 }
57 
58 // Utility to convert a character to a digit in a given base
59 template <int BASE, typename CHAR>
CharToDigit(CHAR c)60 std::optional<uint8_t> CharToDigit(CHAR c) {
61   static_assert(1 <= BASE && BASE <= 36, "BASE needs to be in [1, 36]");
62   if (c >= '0' && c < '0' + std::min(BASE, 10))
63     return static_cast<uint8_t>(c - '0');
64 
65   if (c >= 'a' && c < 'a' + BASE - 10)
66     return static_cast<uint8_t>(c - 'a' + 10);
67 
68   if (c >= 'A' && c < 'A' + BASE - 10)
69     return static_cast<uint8_t>(c - 'A' + 10);
70 
71   return std::nullopt;
72 }
73 
74 template <typename Number, int kBase>
75 class StringToNumberParser {
76  public:
77   struct Result {
78     Number value = 0;
79     bool valid = false;
80   };
81 
82   static constexpr Number kMin = std::numeric_limits<Number>::min();
83   static constexpr Number kMax = std::numeric_limits<Number>::max();
84 
85   // Sign provides:
86   //  - a static function, CheckBounds, that determines whether the next digit
87   //    causes an overflow/underflow
88   //  - a static function, Increment, that appends the next digit appropriately
89   //    according to the sign of the number being parsed.
90   template <typename Sign>
91   class Base {
92    public:
93     template <typename Iter>
Invoke(Iter begin,Iter end)94     static Result Invoke(Iter begin, Iter end) {
95       Number value = 0;
96 
97       if (begin == end) {
98         return {value, false};
99       }
100 
101       // Note: no performance difference was found when using template
102       // specialization to remove this check in bases other than 16
103       if (kBase == 16 && end - begin > 2 && *begin == '0' &&
104           (*(begin + 1) == 'x' || *(begin + 1) == 'X')) {
105         begin += 2;
106       }
107 
108       for (Iter current = begin; current != end; ++current) {
109         std::optional<uint8_t> new_digit = CharToDigit<kBase>(*current);
110 
111         if (!new_digit) {
112           return {value, false};
113         }
114 
115         if (current != begin) {
116           Result result = Sign::CheckBounds(value, *new_digit);
117           if (!result.valid)
118             return result;
119 
120           value *= kBase;
121         }
122 
123         value = Sign::Increment(value, *new_digit);
124       }
125       return {value, true};
126     }
127   };
128 
129   class Positive : public Base<Positive> {
130    public:
CheckBounds(Number value,uint8_t new_digit)131     static Result CheckBounds(Number value, uint8_t new_digit) {
132       if (value > static_cast<Number>(kMax / kBase) ||
133           (value == static_cast<Number>(kMax / kBase) &&
134            new_digit > kMax % kBase)) {
135         return {kMax, false};
136       }
137       return {value, true};
138     }
Increment(Number lhs,uint8_t rhs)139     static Number Increment(Number lhs, uint8_t rhs) { return lhs + rhs; }
140   };
141 
142   class Negative : public Base<Negative> {
143    public:
CheckBounds(Number value,uint8_t new_digit)144     static Result CheckBounds(Number value, uint8_t new_digit) {
145       if (value < kMin / kBase ||
146           (value == kMin / kBase && new_digit > 0 - kMin % kBase)) {
147         return {kMin, false};
148       }
149       return {value, true};
150     }
Increment(Number lhs,uint8_t rhs)151     static Number Increment(Number lhs, uint8_t rhs) { return lhs - rhs; }
152   };
153 };
154 
155 template <typename Number, int kBase, typename CharT>
StringToNumber(std::basic_string_view<CharT> input)156 auto StringToNumber(std::basic_string_view<CharT> input) {
157   using Parser = StringToNumberParser<Number, kBase>;
158   using Result = typename Parser::Result;
159 
160   bool has_leading_whitespace = false;
161   auto begin = input.begin();
162   auto end = input.end();
163 
164   while (begin != end && IsAsciiWhitespace(*begin)) {
165     has_leading_whitespace = true;
166     ++begin;
167   }
168 
169   if (begin != end && *begin == '-') {
170     if (!std::numeric_limits<Number>::is_signed) {
171       return Result{0, false};
172     }
173 
174     Result result = Parser::Negative::Invoke(begin + 1, end);
175     result.valid &= !has_leading_whitespace;
176     return result;
177   }
178 
179   if (begin != end && *begin == '+') {
180     ++begin;
181   }
182 
183   Result result = Parser::Positive::Invoke(begin, end);
184   result.valid &= !has_leading_whitespace;
185   return result;
186 }
187 
188 template <typename T, typename VALUE, typename CharT = typename T::value_type>
StringToIntImpl(T input,VALUE & output)189 bool StringToIntImpl(T input, VALUE& output) {
190   auto result = StringToNumber<VALUE, 10, CharT>(input);
191   output = result.value;
192   return result.valid;
193 }
194 
195 template <typename T, typename VALUE, typename CharT = typename T::value_type>
HexStringToIntImpl(T input,VALUE & output)196 bool HexStringToIntImpl(T input, VALUE& output) {
197   auto result = StringToNumber<VALUE, 16, CharT>(input);
198   output = result.value;
199   return result.valid;
200 }
201 
202 static const double_conversion::DoubleToStringConverter*
GetDoubleToStringConverter()203 GetDoubleToStringConverter() {
204   static double_conversion::DoubleToStringConverter converter(
205       double_conversion::DoubleToStringConverter::EMIT_POSITIVE_EXPONENT_SIGN,
206       nullptr, nullptr, 'e', -6, 12, 0, 0);
207   return &converter;
208 }
209 
210 // Converts a given (data, size) pair to a desired string type. For
211 // performance reasons, this dispatches to a different constructor if the
212 // passed-in data matches the string's value_type.
213 template <typename StringT>
ToString(const typename StringT::value_type * data,size_t size)214 StringT ToString(const typename StringT::value_type* data, size_t size) {
215   return StringT(data, size);
216 }
217 
218 template <typename StringT, typename CharT>
ToString(const CharT * data,size_t size)219 StringT ToString(const CharT* data, size_t size) {
220   return StringT(data, data + size);
221 }
222 
223 template <typename StringT>
DoubleToStringT(double value)224 StringT DoubleToStringT(double value) {
225   char buffer[32];
226   double_conversion::StringBuilder builder(buffer, sizeof(buffer));
227   GetDoubleToStringConverter()->ToShortest(value, &builder);
228   return ToString<StringT>(buffer, static_cast<size_t>(builder.position()));
229 }
230 
231 template <typename STRING, typename CHAR>
StringToDoubleImpl(STRING input,const CHAR * data,double & output)232 bool StringToDoubleImpl(STRING input, const CHAR* data, double& output) {
233   static double_conversion::StringToDoubleConverter converter(
234       double_conversion::StringToDoubleConverter::ALLOW_LEADING_SPACES |
235           double_conversion::StringToDoubleConverter::ALLOW_TRAILING_JUNK,
236       0.0, 0, nullptr, nullptr);
237 
238   int processed_characters_count;
239   output = converter.StringToDouble(data, checked_cast<int>(input.size()),
240                                     &processed_characters_count);
241 
242   // Cases to return false:
243   //  - If the input string is empty, there was nothing to parse.
244   //  - If the value saturated to HUGE_VAL.
245   //  - If the entire string was not processed, there are either characters
246   //    remaining in the string after a parsed number, or the string does not
247   //    begin with a parseable number.
248   //  - If the first character is a space, there was leading whitespace. Note
249   //    that this checks using IsWhitespace(), which behaves differently for
250   //    wide and narrow characters -- that is intentional and matches the
251   //    behavior of the double_conversion library's whitespace-skipping
252   //    algorithm.
253   return !input.empty() && output != HUGE_VAL && output != -HUGE_VAL &&
254          static_cast<size_t>(processed_characters_count) == input.size() &&
255          !IsWhitespace(input[0]);
256 }
257 
258 template <typename Char, typename OutIter>
HexStringToByteContainer(StringPiece input,OutIter output)259 static bool HexStringToByteContainer(StringPiece input, OutIter output) {
260   size_t count = input.size();
261   if (count == 0 || (count % 2) != 0)
262     return false;
263   for (uintptr_t i = 0; i < count / 2; ++i) {
264     // most significant 4 bits
265     std::optional<uint8_t> msb = CharToDigit<16>(input[i * 2]);
266     // least significant 4 bits
267     std::optional<uint8_t> lsb = CharToDigit<16>(input[i * 2 + 1]);
268     if (!msb || !lsb) {
269       return false;
270     }
271     *(output++) = static_cast<Char>((*msb << 4) | *lsb);
272   }
273   return true;
274 }
275 
276 }  // namespace internal
277 
278 }  // namespace base
279 
280 #endif  // BASE_STRINGS_STRING_NUMBER_CONVERSIONS_INTERNAL_H_
281