blob: 9148def07c10f515484e490136e8f1faf0b9d595 [file] [log] [blame]
[email protected]d2d0b6b2012-01-26 00:27:291// Copyright (c) 2012 The Chromium Authors. All rights reserved.
[email protected]528c56d2010-07-30 19:28:442// Use of this source code is governed by a BSD-style license that can be
3// found in the LICENSE file.
4
[email protected]dfa049e2013-02-07 02:57:225#include "base/strings/string_number_conversions.h"
[email protected]528c56d2010-07-30 19:28:446
[email protected]3132e35c2011-07-07 20:46:507#include <ctype.h>
[email protected]528c56d2010-07-30 19:28:448#include <errno.h>
9#include <stdlib.h>
[email protected]e7972d12011-06-18 11:53:1410#include <wctype.h>
[email protected]528c56d2010-07-30 19:28:4411
[email protected]cfcf2da2010-10-21 14:05:3812#include <limits>
jschuh2f220382016-12-02 18:08:4513#include <type_traits>
[email protected]cfcf2da2010-10-21 14:05:3814
[email protected]528c56d2010-07-30 19:28:4415#include "base/logging.h"
jschuh7aa19b92015-09-24 23:48:3916#include "base/numerics/safe_math.h"
[email protected]34d58a22013-05-02 23:06:2617#include "base/scoped_clear_errno.h"
[email protected]528c56d2010-07-30 19:28:4418#include "base/third_party/dmg_fp/dmg_fp.h"
[email protected]528c56d2010-07-30 19:28:4419
20namespace base {
21
22namespace {
23
jschuh7aa19b92015-09-24 23:48:3924template <typename STR, typename INT>
[email protected]528c56d2010-07-30 19:28:4425struct IntToStringT {
[email protected]528c56d2010-07-30 19:28:4426 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 '-'.
riceaad547d82015-09-25 19:27:5029 const size_t kOutputBufSize =
jschuh7aa19b92015-09-24 23:48:3930 3 * sizeof(INT) + std::numeric_limits<INT>::is_signed;
[email protected]528c56d2010-07-30 19:28:4431
riceaad547d82015-09-25 19:27:5032 // Create the string in a temporary buffer, write it back to front, and
[email protected]528c56d2010-07-30 19:28:4433 // then return the substr of what we ended up using.
riceaad547d82015-09-25 19:27:5034 using CHR = typename STR::value_type;
35 CHR outbuf[kOutputBufSize];
[email protected]528c56d2010-07-30 19:28:4436
jschuh7aa19b92015-09-24 23:48:3937 // The ValueOrDie call below can never fail, because UnsignedAbs is valid
38 // for all valid inputs.
jschuh2f220382016-12-02 18:08:4539 typename std::make_unsigned<INT>::type res =
jschuh565f9c72016-11-30 08:38:2440 CheckedNumeric<INT>(value).UnsignedAbs().ValueOrDie();
[email protected]528c56d2010-07-30 19:28:4441
riceaad547d82015-09-25 19:27:5042 CHR* end = outbuf + kOutputBufSize;
43 CHR* i = end;
[email protected]30de3a32014-03-14 18:25:4844 do {
riceaad547d82015-09-25 19:27:5045 --i;
46 DCHECK(i != outbuf);
47 *i = static_cast<CHR>((res % 10) + '0');
[email protected]528c56d2010-07-30 19:28:4448 res /= 10;
[email protected]30de3a32014-03-14 18:25:4849 } while (res != 0);
jschuh7aa19b92015-09-24 23:48:3950 if (IsValueNegative(value)) {
riceaad547d82015-09-25 19:27:5051 --i;
52 DCHECK(i != outbuf);
53 *i = static_cast<CHR>('-');
[email protected]528c56d2010-07-30 19:28:4454 }
riceaad547d82015-09-25 19:27:5055 return STR(i, end);
[email protected]528c56d2010-07-30 19:28:4456 }
57};
58
[email protected]cfcf2da2010-10-21 14:05:3859// Utility to convert a character to a digit in a given base
60template<typename CHAR, int BASE, bool BASE_LTE_10> class BaseCharToDigit {
[email protected]528c56d2010-07-30 19:28:4461};
62
[email protected]cfcf2da2010-10-21 14:05:3863// Faster specialization for bases <= 10
64template<typename CHAR, int BASE> class BaseCharToDigit<CHAR, BASE, true> {
[email protected]528c56d2010-07-30 19:28:4465 public:
avi84f37e12015-12-25 09:31:4266 static bool Convert(CHAR c, uint8_t* digit) {
[email protected]cfcf2da2010-10-21 14:05:3867 if (c >= '0' && c < '0' + BASE) {
avi84f37e12015-12-25 09:31:4268 *digit = static_cast<uint8_t>(c - '0');
[email protected]cfcf2da2010-10-21 14:05:3869 return true;
[email protected]528c56d2010-07-30 19:28:4470 }
[email protected]528c56d2010-07-30 19:28:4471 return false;
[email protected]cfcf2da2010-10-21 14:05:3872 }
73};
74
75// Specialization for bases where 10 < base <= 36
76template<typename CHAR, int BASE> class BaseCharToDigit<CHAR, BASE, false> {
77 public:
avi84f37e12015-12-25 09:31:4278 static bool Convert(CHAR c, uint8_t* digit) {
[email protected]cfcf2da2010-10-21 14:05:3879 if (c >= '0' && c <= '9') {
80 *digit = c - '0';
81 } else if (c >= 'a' && c < 'a' + BASE - 10) {
82 *digit = c - 'a' + 10;
83 } else if (c >= 'A' && c < 'A' + BASE - 10) {
84 *digit = c - 'A' + 10;
85 } else {
86 return false;
87 }
88 return true;
89 }
90};
91
avi84f37e12015-12-25 09:31:4292template <int BASE, typename CHAR>
93bool CharToDigit(CHAR c, uint8_t* digit) {
[email protected]cfcf2da2010-10-21 14:05:3894 return BaseCharToDigit<CHAR, BASE, BASE <= 10>::Convert(c, digit);
[email protected]528c56d2010-07-30 19:28:4495}
96
brettwb3413062015-06-24 00:39:0297// There is an IsUnicodeWhitespace for wchars defined in string_util.h, but it
98// is locale independent, whereas the functions we are replacing were
99// locale-dependent. TBD what is desired, but for the moment let's not
100// introduce a change in behaviour.
[email protected]cfcf2da2010-10-21 14:05:38101template<typename CHAR> class WhitespaceHelper {
102};
103
104template<> class WhitespaceHelper<char> {
105 public:
106 static bool Invoke(char c) {
[email protected]eae2a822010-11-02 19:30:02107 return 0 != isspace(static_cast<unsigned char>(c));
[email protected]cfcf2da2010-10-21 14:05:38108 }
109};
110
111template<> class WhitespaceHelper<char16> {
112 public:
113 static bool Invoke(char16 c) {
114 return 0 != iswspace(c);
115 }
116};
117
118template<typename CHAR> bool LocalIsWhitespace(CHAR c) {
119 return WhitespaceHelper<CHAR>::Invoke(c);
120}
121
122// IteratorRangeToNumberTraits should provide:
123// - a typedef for iterator_type, the iterator type used as input.
124// - a typedef for value_type, the target numeric type.
125// - static functions min, max (returning the minimum and maximum permitted
126// values)
127// - constant kBase, the base in which to interpret the input
128template<typename IteratorRangeToNumberTraits>
129class IteratorRangeToNumber {
130 public:
131 typedef IteratorRangeToNumberTraits traits;
132 typedef typename traits::iterator_type const_iterator;
133 typedef typename traits::value_type value_type;
134
135 // Generalized iterator-range-to-number conversion.
136 //
137 static bool Invoke(const_iterator begin,
138 const_iterator end,
139 value_type* output) {
140 bool valid = true;
141
142 while (begin != end && LocalIsWhitespace(*begin)) {
143 valid = false;
144 ++begin;
145 }
146
147 if (begin != end && *begin == '-') {
[email protected]2482a1952013-05-01 14:22:16148 if (!std::numeric_limits<value_type>::is_signed) {
davidben301864e2016-02-27 01:31:11149 *output = 0;
[email protected]2482a1952013-05-01 14:22:16150 valid = false;
151 } else if (!Negative::Invoke(begin + 1, end, output)) {
[email protected]cfcf2da2010-10-21 14:05:38152 valid = false;
153 }
154 } else {
155 if (begin != end && *begin == '+') {
156 ++begin;
157 }
158 if (!Positive::Invoke(begin, end, output)) {
159 valid = false;
160 }
161 }
162
163 return valid;
164 }
165
166 private:
167 // Sign provides:
168 // - a static function, CheckBounds, that determines whether the next digit
169 // causes an overflow/underflow
170 // - a static function, Increment, that appends the next digit appropriately
171 // according to the sign of the number being parsed.
172 template<typename Sign>
173 class Base {
174 public:
175 static bool Invoke(const_iterator begin, const_iterator end,
176 typename traits::value_type* output) {
177 *output = 0;
178
179 if (begin == end) {
180 return false;
181 }
182
183 // Note: no performance difference was found when using template
184 // specialization to remove this check in bases other than 16
[email protected]331580b2011-08-12 20:13:20185 if (traits::kBase == 16 && end - begin > 2 && *begin == '0' &&
[email protected]cfcf2da2010-10-21 14:05:38186 (*(begin + 1) == 'x' || *(begin + 1) == 'X')) {
187 begin += 2;
188 }
189
190 for (const_iterator current = begin; current != end; ++current) {
avi84f37e12015-12-25 09:31:42191 uint8_t new_digit = 0;
[email protected]cfcf2da2010-10-21 14:05:38192
193 if (!CharToDigit<traits::kBase>(*current, &new_digit)) {
194 return false;
195 }
196
197 if (current != begin) {
198 if (!Sign::CheckBounds(output, new_digit)) {
199 return false;
200 }
201 *output *= traits::kBase;
202 }
203
204 Sign::Increment(new_digit, output);
205 }
206 return true;
207 }
208 };
209
210 class Positive : public Base<Positive> {
211 public:
avi84f37e12015-12-25 09:31:42212 static bool CheckBounds(value_type* output, uint8_t new_digit) {
[email protected]cfcf2da2010-10-21 14:05:38213 if (*output > static_cast<value_type>(traits::max() / traits::kBase) ||
214 (*output == static_cast<value_type>(traits::max() / traits::kBase) &&
215 new_digit > traits::max() % traits::kBase)) {
216 *output = traits::max();
217 return false;
218 }
219 return true;
220 }
avi84f37e12015-12-25 09:31:42221 static void Increment(uint8_t increment, value_type* output) {
[email protected]cfcf2da2010-10-21 14:05:38222 *output += increment;
223 }
224 };
225
226 class Negative : public Base<Negative> {
227 public:
avi84f37e12015-12-25 09:31:42228 static bool CheckBounds(value_type* output, uint8_t new_digit) {
[email protected]cfcf2da2010-10-21 14:05:38229 if (*output < traits::min() / traits::kBase ||
230 (*output == traits::min() / traits::kBase &&
231 new_digit > 0 - traits::min() % traits::kBase)) {
232 *output = traits::min();
233 return false;
234 }
235 return true;
236 }
avi84f37e12015-12-25 09:31:42237 static void Increment(uint8_t increment, value_type* output) {
[email protected]cfcf2da2010-10-21 14:05:38238 *output -= increment;
239 }
240 };
241};
242
243template<typename ITERATOR, typename VALUE, int BASE>
244class BaseIteratorRangeToNumberTraits {
245 public:
246 typedef ITERATOR iterator_type;
247 typedef VALUE value_type;
248 static value_type min() {
249 return std::numeric_limits<value_type>::min();
250 }
251 static value_type max() {
252 return std::numeric_limits<value_type>::max();
253 }
254 static const int kBase = BASE;
255};
256
[email protected]cfcf2da2010-10-21 14:05:38257template<typename ITERATOR>
258class BaseHexIteratorRangeToIntTraits
259 : public BaseIteratorRangeToNumberTraits<ITERATOR, int, 16> {
[email protected]ce63d6b2012-12-20 02:46:28260};
261
avi84f37e12015-12-25 09:31:42262template <typename ITERATOR>
[email protected]3fb01692013-10-23 13:37:04263class BaseHexIteratorRangeToUIntTraits
avi84f37e12015-12-25 09:31:42264 : public BaseIteratorRangeToNumberTraits<ITERATOR, uint32_t, 16> {};
[email protected]3fb01692013-10-23 13:37:04265
avi84f37e12015-12-25 09:31:42266template <typename ITERATOR>
[email protected]ce63d6b2012-12-20 02:46:28267class BaseHexIteratorRangeToInt64Traits
avi84f37e12015-12-25 09:31:42268 : public BaseIteratorRangeToNumberTraits<ITERATOR, int64_t, 16> {};
[email protected]cfcf2da2010-10-21 14:05:38269
avi84f37e12015-12-25 09:31:42270template <typename ITERATOR>
[email protected]ba4cd522013-04-12 14:38:11271class BaseHexIteratorRangeToUInt64Traits
avi84f37e12015-12-25 09:31:42272 : public BaseIteratorRangeToNumberTraits<ITERATOR, uint64_t, 16> {};
[email protected]ba4cd522013-04-12 14:38:11273
[email protected]eb72b272011-12-19 16:10:55274typedef BaseHexIteratorRangeToIntTraits<StringPiece::const_iterator>
[email protected]cfcf2da2010-10-21 14:05:38275 HexIteratorRangeToIntTraits;
[email protected]cfcf2da2010-10-21 14:05:38276
[email protected]3fb01692013-10-23 13:37:04277typedef BaseHexIteratorRangeToUIntTraits<StringPiece::const_iterator>
278 HexIteratorRangeToUIntTraits;
279
[email protected]ce63d6b2012-12-20 02:46:28280typedef BaseHexIteratorRangeToInt64Traits<StringPiece::const_iterator>
281 HexIteratorRangeToInt64Traits;
282
[email protected]ba4cd522013-04-12 14:38:11283typedef BaseHexIteratorRangeToUInt64Traits<StringPiece::const_iterator>
284 HexIteratorRangeToUInt64Traits;
285
avi84f37e12015-12-25 09:31:42286template <typename STR>
287bool HexStringToBytesT(const STR& input, std::vector<uint8_t>* output) {
[email protected]cfcf2da2010-10-21 14:05:38288 DCHECK_EQ(output->size(), 0u);
[email protected]528c56d2010-07-30 19:28:44289 size_t count = input.size();
290 if (count == 0 || (count % 2) != 0)
291 return false;
292 for (uintptr_t i = 0; i < count / 2; ++i) {
avi84f37e12015-12-25 09:31:42293 uint8_t msb = 0; // most significant 4 bits
294 uint8_t lsb = 0; // least significant 4 bits
[email protected]cfcf2da2010-10-21 14:05:38295 if (!CharToDigit<16>(input[i * 2], &msb) ||
296 !CharToDigit<16>(input[i * 2 + 1], &lsb))
[email protected]528c56d2010-07-30 19:28:44297 return false;
298 output->push_back((msb << 4) | lsb);
299 }
300 return true;
301}
302
[email protected]eb72b272011-12-19 16:10:55303template <typename VALUE, int BASE>
304class StringPieceToNumberTraits
305 : public BaseIteratorRangeToNumberTraits<StringPiece::const_iterator,
306 VALUE,
[email protected]ce63d6b2012-12-20 02:46:28307 BASE> {
308};
[email protected]eb72b272011-12-19 16:10:55309
310template <typename VALUE>
311bool StringToIntImpl(const StringPiece& input, VALUE* output) {
312 return IteratorRangeToNumber<StringPieceToNumberTraits<VALUE, 10> >::Invoke(
313 input.begin(), input.end(), output);
314}
315
316template <typename VALUE, int BASE>
317class StringPiece16ToNumberTraits
318 : public BaseIteratorRangeToNumberTraits<StringPiece16::const_iterator,
319 VALUE,
[email protected]ce63d6b2012-12-20 02:46:28320 BASE> {
321};
[email protected]eb72b272011-12-19 16:10:55322
323template <typename VALUE>
324bool String16ToIntImpl(const StringPiece16& input, VALUE* output) {
325 return IteratorRangeToNumber<StringPiece16ToNumberTraits<VALUE, 10> >::Invoke(
326 input.begin(), input.end(), output);
327}
328
[email protected]528c56d2010-07-30 19:28:44329} // namespace
330
331std::string IntToString(int value) {
jschuh7aa19b92015-09-24 23:48:39332 return IntToStringT<std::string, int>::IntToString(value);
[email protected]528c56d2010-07-30 19:28:44333}
334
335string16 IntToString16(int value) {
jschuh7aa19b92015-09-24 23:48:39336 return IntToStringT<string16, int>::IntToString(value);
[email protected]528c56d2010-07-30 19:28:44337}
338
339std::string UintToString(unsigned int value) {
jschuh7aa19b92015-09-24 23:48:39340 return IntToStringT<std::string, unsigned int>::IntToString(value);
[email protected]528c56d2010-07-30 19:28:44341}
342
343string16 UintToString16(unsigned int value) {
jschuh7aa19b92015-09-24 23:48:39344 return IntToStringT<string16, unsigned int>::IntToString(value);
[email protected]528c56d2010-07-30 19:28:44345}
346
avi84f37e12015-12-25 09:31:42347std::string Int64ToString(int64_t value) {
348 return IntToStringT<std::string, int64_t>::IntToString(value);
[email protected]528c56d2010-07-30 19:28:44349}
350
avi84f37e12015-12-25 09:31:42351string16 Int64ToString16(int64_t value) {
352 return IntToStringT<string16, int64_t>::IntToString(value);
[email protected]528c56d2010-07-30 19:28:44353}
354
avi84f37e12015-12-25 09:31:42355std::string Uint64ToString(uint64_t value) {
356 return IntToStringT<std::string, uint64_t>::IntToString(value);
[email protected]528c56d2010-07-30 19:28:44357}
358
avi84f37e12015-12-25 09:31:42359string16 Uint64ToString16(uint64_t value) {
360 return IntToStringT<string16, uint64_t>::IntToString(value);
[email protected]1c0fb252014-06-27 19:10:38361}
362
363std::string SizeTToString(size_t value) {
jschuh7aa19b92015-09-24 23:48:39364 return IntToStringT<std::string, size_t>::IntToString(value);
[email protected]1c0fb252014-06-27 19:10:38365}
366
367string16 SizeTToString16(size_t value) {
jschuh7aa19b92015-09-24 23:48:39368 return IntToStringT<string16, size_t>::IntToString(value);
[email protected]528c56d2010-07-30 19:28:44369}
370
371std::string DoubleToString(double value) {
372 // According to g_fmt.cc, it is sufficient to declare a buffer of size 32.
373 char buffer[32];
374 dmg_fp::g_fmt(buffer, value);
375 return std::string(buffer);
376}
377
[email protected]eb72b272011-12-19 16:10:55378bool StringToInt(const StringPiece& input, int* output) {
379 return StringToIntImpl(input, output);
[email protected]cfcf2da2010-10-21 14:05:38380}
381
[email protected]eb72b272011-12-19 16:10:55382bool StringToInt(const StringPiece16& input, int* output) {
383 return String16ToIntImpl(input, output);
[email protected]cfcf2da2010-10-21 14:05:38384}
385
[email protected]d1bafad2012-01-28 01:02:17386bool StringToUint(const StringPiece& input, unsigned* output) {
387 return StringToIntImpl(input, output);
388}
389
390bool StringToUint(const StringPiece16& input, unsigned* output) {
391 return String16ToIntImpl(input, output);
392}
393
avi84f37e12015-12-25 09:31:42394bool StringToInt64(const StringPiece& input, int64_t* output) {
[email protected]eb72b272011-12-19 16:10:55395 return StringToIntImpl(input, output);
[email protected]cfcf2da2010-10-21 14:05:38396}
397
avi84f37e12015-12-25 09:31:42398bool StringToInt64(const StringPiece16& input, int64_t* output) {
[email protected]eb72b272011-12-19 16:10:55399 return String16ToIntImpl(input, output);
[email protected]cfcf2da2010-10-21 14:05:38400}
401
avi84f37e12015-12-25 09:31:42402bool StringToUint64(const StringPiece& input, uint64_t* output) {
[email protected]d2d0b6b2012-01-26 00:27:29403 return StringToIntImpl(input, output);
404}
405
avi84f37e12015-12-25 09:31:42406bool StringToUint64(const StringPiece16& input, uint64_t* output) {
[email protected]d2d0b6b2012-01-26 00:27:29407 return String16ToIntImpl(input, output);
408}
409
[email protected]4420d93272012-01-28 03:30:17410bool StringToSizeT(const StringPiece& input, size_t* output) {
411 return StringToIntImpl(input, output);
412}
413
414bool StringToSizeT(const StringPiece16& input, size_t* output) {
415 return String16ToIntImpl(input, output);
416}
417
[email protected]528c56d2010-07-30 19:28:44418bool StringToDouble(const std::string& input, double* output) {
[email protected]34d58a22013-05-02 23:06:26419 // Thread-safe? It is on at least Mac, Linux, and Windows.
420 ScopedClearErrno clear_errno;
421
[email protected]cfcf2da2010-10-21 14:05:38422 char* endptr = NULL;
423 *output = dmg_fp::strtod(input.c_str(), &endptr);
424
425 // Cases to return false:
426 // - If errno is ERANGE, there was an overflow or underflow.
427 // - If the input string is empty, there was nothing to parse.
428 // - If endptr does not point to the end of the string, there are either
429 // characters remaining in the string after a parsed number, or the string
430 // does not begin with a parseable number. endptr is compared to the
431 // expected end given the string's stated length to correctly catch cases
432 // where the string contains embedded NUL characters.
433 // - If the first character is a space, there was leading whitespace
434 return errno == 0 &&
435 !input.empty() &&
436 input.c_str() + input.length() == endptr &&
437 !isspace(input[0]);
[email protected]528c56d2010-07-30 19:28:44438}
439
440// Note: if you need to add String16ToDouble, first ask yourself if it's
441// really necessary. If it is, probably the best implementation here is to
442// convert to 8-bit and then use the 8-bit version.
443
[email protected]cfcf2da2010-10-21 14:05:38444// Note: if you need to add an iterator range version of StringToDouble, first
445// ask yourself if it's really necessary. If it is, probably the best
446// implementation here is to instantiate a string and use the string version.
447
[email protected]528c56d2010-07-30 19:28:44448std::string HexEncode(const void* bytes, size_t size) {
449 static const char kHexChars[] = "0123456789ABCDEF";
450
451 // Each input byte creates two output hex characters.
452 std::string ret(size * 2, '\0');
453
454 for (size_t i = 0; i < size; ++i) {
455 char b = reinterpret_cast<const char*>(bytes)[i];
456 ret[(i * 2)] = kHexChars[(b >> 4) & 0xf];
457 ret[(i * 2) + 1] = kHexChars[b & 0xf];
458 }
459 return ret;
460}
461
[email protected]eb72b272011-12-19 16:10:55462bool HexStringToInt(const StringPiece& input, int* output) {
[email protected]cfcf2da2010-10-21 14:05:38463 return IteratorRangeToNumber<HexIteratorRangeToIntTraits>::Invoke(
464 input.begin(), input.end(), output);
465}
466
avi84f37e12015-12-25 09:31:42467bool HexStringToUInt(const StringPiece& input, uint32_t* output) {
[email protected]3fb01692013-10-23 13:37:04468 return IteratorRangeToNumber<HexIteratorRangeToUIntTraits>::Invoke(
469 input.begin(), input.end(), output);
470}
471
avi84f37e12015-12-25 09:31:42472bool HexStringToInt64(const StringPiece& input, int64_t* output) {
[email protected]ce63d6b2012-12-20 02:46:28473 return IteratorRangeToNumber<HexIteratorRangeToInt64Traits>::Invoke(
474 input.begin(), input.end(), output);
475}
476
avi84f37e12015-12-25 09:31:42477bool HexStringToUInt64(const StringPiece& input, uint64_t* output) {
[email protected]ba4cd522013-04-12 14:38:11478 return IteratorRangeToNumber<HexIteratorRangeToUInt64Traits>::Invoke(
479 input.begin(), input.end(), output);
480}
481
avi84f37e12015-12-25 09:31:42482bool HexStringToBytes(const std::string& input, std::vector<uint8_t>* output) {
[email protected]528c56d2010-07-30 19:28:44483 return HexStringToBytesT(input, output);
484}
485
486} // namespace base