1 // Copyright (c) 2012 The Chromium Authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style license that can be
3 // found in the LICENSE file.
4
5 #include "base/strings/string_number_conversions.h"
6
7 #include <ctype.h>
8 #include <errno.h>
9 #include <stdlib.h>
10 #include <wctype.h>
11
12 #include <limits>
13 #include <type_traits>
14
15 #include "base/logging.h"
16 #include "base/numerics/safe_math.h"
17 #include "base/scoped_clear_errno.h"
18 #include "base/strings/utf_string_conversions.h"
19
20 namespace base {
21
22 namespace {
23
24 template <typename STR, typename INT>
25 struct IntToStringT {
IntToStringbase::__anon28376e0d0111::IntToStringT26 static STR IntToString(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 typename std::make_unsigned<INT>::type 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
59 // Utility to convert a character to a digit in a given base
60 template <typename CHAR, int BASE, bool BASE_LTE_10>
61 class BaseCharToDigit {};
62
63 // Faster specialization for bases <= 10
64 template <typename CHAR, int BASE>
65 class BaseCharToDigit<CHAR, BASE, true> {
66 public:
Convert(CHAR c,uint8_t * digit)67 static bool Convert(CHAR c, uint8_t* digit) {
68 if (c >= '0' && c < '0' + BASE) {
69 *digit = static_cast<uint8_t>(c - '0');
70 return true;
71 }
72 return false;
73 }
74 };
75
76 // Specialization for bases where 10 < base <= 36
77 template <typename CHAR, int BASE>
78 class BaseCharToDigit<CHAR, BASE, false> {
79 public:
Convert(CHAR c,uint8_t * digit)80 static bool Convert(CHAR c, uint8_t* digit) {
81 if (c >= '0' && c <= '9') {
82 *digit = c - '0';
83 } else if (c >= 'a' && c < 'a' + BASE - 10) {
84 *digit = c - 'a' + 10;
85 } else if (c >= 'A' && c < 'A' + BASE - 10) {
86 *digit = c - 'A' + 10;
87 } else {
88 return false;
89 }
90 return true;
91 }
92 };
93
94 template <int BASE, typename CHAR>
CharToDigit(CHAR c,uint8_t * digit)95 bool CharToDigit(CHAR c, uint8_t* digit) {
96 return BaseCharToDigit<CHAR, BASE, BASE <= 10>::Convert(c, digit);
97 }
98
99 // There is an IsUnicodeWhitespace for wchars defined in string_util.h, but it
100 // is locale independent, whereas the functions we are replacing were
101 // locale-dependent. TBD what is desired, but for the moment let's not
102 // introduce a change in behaviour.
103 template <typename CHAR>
104 class WhitespaceHelper {};
105
106 template <>
107 class WhitespaceHelper<char> {
108 public:
Invoke(char c)109 static bool Invoke(char c) {
110 return 0 != isspace(static_cast<unsigned char>(c));
111 }
112 };
113
114 template <>
115 class WhitespaceHelper<char16_t> {
116 public:
Invoke(char16_t c)117 static bool Invoke(char16_t c) { return 0 != iswspace(c); }
118 };
119
120 template <typename CHAR>
LocalIsWhitespace(CHAR c)121 bool LocalIsWhitespace(CHAR c) {
122 return WhitespaceHelper<CHAR>::Invoke(c);
123 }
124
125 // IteratorRangeToNumberTraits should provide:
126 // - a typedef for iterator_type, the iterator type used as input.
127 // - a typedef for value_type, the target numeric type.
128 // - static functions min, max (returning the minimum and maximum permitted
129 // values)
130 // - constant kBase, the base in which to interpret the input
131 template <typename IteratorRangeToNumberTraits>
132 class IteratorRangeToNumber {
133 public:
134 typedef IteratorRangeToNumberTraits traits;
135 typedef typename traits::iterator_type const_iterator;
136 typedef typename traits::value_type value_type;
137
138 // Generalized iterator-range-to-number conversion.
139 //
Invoke(const_iterator begin,const_iterator end,value_type * output)140 static bool Invoke(const_iterator begin,
141 const_iterator end,
142 value_type* output) {
143 bool valid = true;
144
145 while (begin != end && LocalIsWhitespace(*begin)) {
146 valid = false;
147 ++begin;
148 }
149
150 if (begin != end && *begin == '-') {
151 if (!std::numeric_limits<value_type>::is_signed) {
152 *output = 0;
153 valid = false;
154 } else if (!Negative::Invoke(begin + 1, end, output)) {
155 valid = false;
156 }
157 } else {
158 if (begin != end && *begin == '+') {
159 ++begin;
160 }
161 if (!Positive::Invoke(begin, end, output)) {
162 valid = false;
163 }
164 }
165
166 return valid;
167 }
168
169 private:
170 // Sign provides:
171 // - a static function, CheckBounds, that determines whether the next digit
172 // causes an overflow/underflow
173 // - a static function, Increment, that appends the next digit appropriately
174 // according to the sign of the number being parsed.
175 template <typename Sign>
176 class Base {
177 public:
Invoke(const_iterator begin,const_iterator end,typename traits::value_type * output)178 static bool Invoke(const_iterator begin,
179 const_iterator end,
180 typename traits::value_type* output) {
181 *output = 0;
182
183 if (begin == end) {
184 return false;
185 }
186
187 // Note: no performance difference was found when using template
188 // specialization to remove this check in bases other than 16
189 if (traits::kBase == 16 && end - begin > 2 && *begin == '0' &&
190 (*(begin + 1) == 'x' || *(begin + 1) == 'X')) {
191 begin += 2;
192 }
193
194 for (const_iterator current = begin; current != end; ++current) {
195 uint8_t new_digit = 0;
196
197 if (!CharToDigit<traits::kBase>(*current, &new_digit)) {
198 return false;
199 }
200
201 if (current != begin) {
202 if (!Sign::CheckBounds(output, new_digit)) {
203 return false;
204 }
205 *output *= traits::kBase;
206 }
207
208 Sign::Increment(new_digit, output);
209 }
210 return true;
211 }
212 };
213
214 class Positive : public Base<Positive> {
215 public:
CheckBounds(value_type * output,uint8_t new_digit)216 static bool CheckBounds(value_type* output, uint8_t new_digit) {
217 if (*output > static_cast<value_type>(traits::max() / traits::kBase) ||
218 (*output == static_cast<value_type>(traits::max() / traits::kBase) &&
219 new_digit > traits::max() % traits::kBase)) {
220 *output = traits::max();
221 return false;
222 }
223 return true;
224 }
Increment(uint8_t increment,value_type * output)225 static void Increment(uint8_t increment, value_type* output) {
226 *output += increment;
227 }
228 };
229
230 class Negative : public Base<Negative> {
231 public:
CheckBounds(value_type * output,uint8_t new_digit)232 static bool CheckBounds(value_type* output, uint8_t new_digit) {
233 if (*output < traits::min() / traits::kBase ||
234 (*output == traits::min() / traits::kBase &&
235 new_digit > 0 - traits::min() % traits::kBase)) {
236 *output = traits::min();
237 return false;
238 }
239 return true;
240 }
Increment(uint8_t increment,value_type * output)241 static void Increment(uint8_t increment, value_type* output) {
242 *output -= increment;
243 }
244 };
245 };
246
247 template <typename ITERATOR, typename VALUE, int BASE>
248 class BaseIteratorRangeToNumberTraits {
249 public:
250 typedef ITERATOR iterator_type;
251 typedef VALUE value_type;
min()252 static value_type min() { return std::numeric_limits<value_type>::min(); }
max()253 static value_type max() { return std::numeric_limits<value_type>::max(); }
254 static const int kBase = BASE;
255 };
256
257 template <typename ITERATOR>
258 class BaseHexIteratorRangeToIntTraits
259 : public BaseIteratorRangeToNumberTraits<ITERATOR, int, 16> {};
260
261 template <typename ITERATOR>
262 class BaseHexIteratorRangeToUIntTraits
263 : public BaseIteratorRangeToNumberTraits<ITERATOR, uint32_t, 16> {};
264
265 template <typename ITERATOR>
266 class BaseHexIteratorRangeToInt64Traits
267 : public BaseIteratorRangeToNumberTraits<ITERATOR, int64_t, 16> {};
268
269 template <typename ITERATOR>
270 class BaseHexIteratorRangeToUInt64Traits
271 : public BaseIteratorRangeToNumberTraits<ITERATOR, uint64_t, 16> {};
272
273 typedef BaseHexIteratorRangeToIntTraits<std::string_view::const_iterator>
274 HexIteratorRangeToIntTraits;
275
276 typedef BaseHexIteratorRangeToUIntTraits<std::string_view::const_iterator>
277 HexIteratorRangeToUIntTraits;
278
279 typedef BaseHexIteratorRangeToInt64Traits<std::string_view::const_iterator>
280 HexIteratorRangeToInt64Traits;
281
282 typedef BaseHexIteratorRangeToUInt64Traits<std::string_view::const_iterator>
283 HexIteratorRangeToUInt64Traits;
284
285 template <typename VALUE, int BASE>
286 class StringPieceToNumberTraits
287 : public BaseIteratorRangeToNumberTraits<std::string_view::const_iterator,
288 VALUE,
289 BASE> {};
290
291 template <typename VALUE>
StringToIntImpl(std::string_view input,VALUE * output)292 bool StringToIntImpl(std::string_view input, VALUE* output) {
293 return IteratorRangeToNumber<StringPieceToNumberTraits<VALUE, 10>>::Invoke(
294 input.begin(), input.end(), output);
295 }
296
297 template <typename VALUE, int BASE>
298 class StringPiece16ToNumberTraits : public BaseIteratorRangeToNumberTraits<
299 std::u16string_view::const_iterator,
300 VALUE,
301 BASE> {};
302
303 template <typename VALUE>
String16ToIntImpl(std::u16string_view input,VALUE * output)304 bool String16ToIntImpl(std::u16string_view input, VALUE* output) {
305 return IteratorRangeToNumber<StringPiece16ToNumberTraits<VALUE, 10>>::Invoke(
306 input.begin(), input.end(), output);
307 }
308
309 } // namespace
310
NumberToString(int value)311 std::string NumberToString(int value) {
312 return IntToStringT<std::string, int>::IntToString(value);
313 }
314
NumberToString16(int value)315 std::u16string NumberToString16(int value) {
316 return IntToStringT<std::u16string, int>::IntToString(value);
317 }
318
NumberToString(unsigned value)319 std::string NumberToString(unsigned value) {
320 return IntToStringT<std::string, unsigned>::IntToString(value);
321 }
322
NumberToString16(unsigned value)323 std::u16string NumberToString16(unsigned value) {
324 return IntToStringT<std::u16string, unsigned>::IntToString(value);
325 }
326
NumberToString(long value)327 std::string NumberToString(long value) {
328 return IntToStringT<std::string, long>::IntToString(value);
329 }
330
NumberToString16(long value)331 std::u16string NumberToString16(long value) {
332 return IntToStringT<std::u16string, long>::IntToString(value);
333 }
334
NumberToString(unsigned long value)335 std::string NumberToString(unsigned long value) {
336 return IntToStringT<std::string, unsigned long>::IntToString(value);
337 }
338
NumberToString16(unsigned long value)339 std::u16string NumberToString16(unsigned long value) {
340 return IntToStringT<std::u16string, unsigned long>::IntToString(value);
341 }
342
NumberToString(long long value)343 std::string NumberToString(long long value) {
344 return IntToStringT<std::string, long long>::IntToString(value);
345 }
346
NumberToString16(long long value)347 std::u16string NumberToString16(long long value) {
348 return IntToStringT<std::u16string, long long>::IntToString(value);
349 }
350
NumberToString(unsigned long long value)351 std::string NumberToString(unsigned long long value) {
352 return IntToStringT<std::string, unsigned long long>::IntToString(value);
353 }
354
NumberToString16(unsigned long long value)355 std::u16string NumberToString16(unsigned long long value) {
356 return IntToStringT<std::u16string, unsigned long long>::IntToString(value);
357 }
358
StringToInt(std::string_view input,int * output)359 bool StringToInt(std::string_view input, int* output) {
360 return StringToIntImpl(input, output);
361 }
362
StringToInt(std::u16string_view input,int * output)363 bool StringToInt(std::u16string_view input, int* output) {
364 return String16ToIntImpl(input, output);
365 }
366
StringToUint(std::string_view input,unsigned * output)367 bool StringToUint(std::string_view input, unsigned* output) {
368 return StringToIntImpl(input, output);
369 }
370
StringToUint(std::u16string_view input,unsigned * output)371 bool StringToUint(std::u16string_view input, unsigned* output) {
372 return String16ToIntImpl(input, output);
373 }
374
StringToInt64(std::string_view input,int64_t * output)375 bool StringToInt64(std::string_view input, int64_t* output) {
376 return StringToIntImpl(input, output);
377 }
378
StringToInt64(std::u16string_view input,int64_t * output)379 bool StringToInt64(std::u16string_view input, int64_t* output) {
380 return String16ToIntImpl(input, output);
381 }
382
StringToUint64(std::string_view input,uint64_t * output)383 bool StringToUint64(std::string_view input, uint64_t* output) {
384 return StringToIntImpl(input, output);
385 }
386
StringToUint64(std::u16string_view input,uint64_t * output)387 bool StringToUint64(std::u16string_view input, uint64_t* output) {
388 return String16ToIntImpl(input, output);
389 }
390
StringToSizeT(std::string_view input,size_t * output)391 bool StringToSizeT(std::string_view input, size_t* output) {
392 return StringToIntImpl(input, output);
393 }
394
StringToSizeT(std::u16string_view input,size_t * output)395 bool StringToSizeT(std::u16string_view input, size_t* output) {
396 return String16ToIntImpl(input, output);
397 }
398
399 // Note: if you need to add String16ToDouble, first ask yourself if it's
400 // really necessary. If it is, probably the best implementation here is to
401 // convert to 8-bit and then use the 8-bit version.
402
403 // Note: if you need to add an iterator range version of StringToDouble, first
404 // ask yourself if it's really necessary. If it is, probably the best
405 // implementation here is to instantiate a string and use the string version.
406
HexEncode(const void * bytes,size_t size)407 std::string HexEncode(const void* bytes, size_t size) {
408 static const char kHexChars[] = "0123456789ABCDEF";
409
410 // Each input byte creates two output hex characters.
411 std::string ret(size * 2, '\0');
412
413 for (size_t i = 0; i < size; ++i) {
414 char b = reinterpret_cast<const char*>(bytes)[i];
415 ret[(i * 2)] = kHexChars[(b >> 4) & 0xf];
416 ret[(i * 2) + 1] = kHexChars[b & 0xf];
417 }
418 return ret;
419 }
420
HexStringToInt(std::string_view input,int * output)421 bool HexStringToInt(std::string_view input, int* output) {
422 return IteratorRangeToNumber<HexIteratorRangeToIntTraits>::Invoke(
423 input.begin(), input.end(), output);
424 }
425
HexStringToUInt(std::string_view input,uint32_t * output)426 bool HexStringToUInt(std::string_view input, uint32_t* output) {
427 return IteratorRangeToNumber<HexIteratorRangeToUIntTraits>::Invoke(
428 input.begin(), input.end(), output);
429 }
430
HexStringToInt64(std::string_view input,int64_t * output)431 bool HexStringToInt64(std::string_view input, int64_t* output) {
432 return IteratorRangeToNumber<HexIteratorRangeToInt64Traits>::Invoke(
433 input.begin(), input.end(), output);
434 }
435
HexStringToUInt64(std::string_view input,uint64_t * output)436 bool HexStringToUInt64(std::string_view input, uint64_t* output) {
437 return IteratorRangeToNumber<HexIteratorRangeToUInt64Traits>::Invoke(
438 input.begin(), input.end(), output);
439 }
440
HexStringToBytes(std::string_view input,std::vector<uint8_t> * output)441 bool HexStringToBytes(std::string_view input, std::vector<uint8_t>* output) {
442 DCHECK_EQ(output->size(), 0u);
443 size_t count = input.size();
444 if (count == 0 || (count % 2) != 0)
445 return false;
446 for (uintptr_t i = 0; i < count / 2; ++i) {
447 uint8_t msb = 0; // most significant 4 bits
448 uint8_t lsb = 0; // least significant 4 bits
449 if (!CharToDigit<16>(input[i * 2], &msb) ||
450 !CharToDigit<16>(input[i * 2 + 1], &lsb)) {
451 return false;
452 }
453 output->push_back((msb << 4) | lsb);
454 }
455 return true;
456 }
457
458 } // namespace base
459