michael@0: // Copyright (c) 2012 The Chromium Authors. All rights reserved. michael@0: // Use of this source code is governed by a BSD-style license that can be michael@0: // found in the LICENSE file. michael@0: michael@0: #include "base/strings/string_number_conversions.h" michael@0: michael@0: #include michael@0: #include michael@0: #include michael@0: #include michael@0: michael@0: #include michael@0: michael@0: #include "base/logging.h" michael@0: #include "base/scoped_clear_errno.h" michael@0: #include "base/strings/utf_string_conversions.h" michael@0: #include "base/third_party/dmg_fp/dmg_fp.h" michael@0: michael@0: namespace base { michael@0: michael@0: namespace { michael@0: michael@0: template michael@0: struct IntToStringT { michael@0: // This is to avoid a compiler warning about unary minus on unsigned type. michael@0: // For example, say you had the following code: michael@0: // template michael@0: // INT abs(INT value) { return value < 0 ? -value : value; } michael@0: // Even though if INT is unsigned, it's impossible for value < 0, so the michael@0: // unary minus will never be taken, the compiler will still generate a michael@0: // warning. We do a little specialization dance... michael@0: template michael@0: struct ToUnsignedT {}; michael@0: michael@0: template michael@0: struct ToUnsignedT { michael@0: static UINT2 ToUnsigned(INT2 value) { michael@0: return static_cast(value); michael@0: } michael@0: }; michael@0: michael@0: template michael@0: struct ToUnsignedT { michael@0: static UINT2 ToUnsigned(INT2 value) { michael@0: return static_cast(value < 0 ? -value : value); michael@0: } michael@0: }; michael@0: michael@0: // This set of templates is very similar to the above templates, but michael@0: // for testing whether an integer is negative. michael@0: template michael@0: struct TestNegT {}; michael@0: template michael@0: struct TestNegT { michael@0: static bool TestNeg(INT2 value) { michael@0: // value is unsigned, and can never be negative. michael@0: return false; michael@0: } michael@0: }; michael@0: template michael@0: struct TestNegT { michael@0: static bool TestNeg(INT2 value) { michael@0: return value < 0; michael@0: } michael@0: }; michael@0: michael@0: static STR IntToString(INT value) { michael@0: // log10(2) ~= 0.3 bytes needed per bit or per byte log10(2**8) ~= 2.4. michael@0: // So round up to allocate 3 output characters per byte, plus 1 for '-'. michael@0: const int kOutputBufSize = 3 * sizeof(INT) + 1; michael@0: michael@0: // Allocate the whole string right away, we will right back to front, and michael@0: // then return the substr of what we ended up using. michael@0: STR outbuf(kOutputBufSize, 0); michael@0: michael@0: bool is_neg = TestNegT::TestNeg(value); michael@0: // Even though is_neg will never be true when INT is parameterized as michael@0: // unsigned, even the presence of the unary operation causes a warning. michael@0: UINT res = ToUnsignedT::ToUnsigned(value); michael@0: michael@0: for (typename STR::iterator it = outbuf.end();;) { michael@0: --it; michael@0: DCHECK(it != outbuf.begin()); michael@0: *it = static_cast((res % 10) + '0'); michael@0: res /= 10; michael@0: michael@0: // We're done.. michael@0: if (res == 0) { michael@0: if (is_neg) { michael@0: --it; michael@0: DCHECK(it != outbuf.begin()); michael@0: *it = static_cast('-'); michael@0: } michael@0: return STR(it, outbuf.end()); michael@0: } michael@0: } michael@0: NOTREACHED(); michael@0: return STR(); michael@0: } michael@0: }; michael@0: michael@0: // Utility to convert a character to a digit in a given base michael@0: template class BaseCharToDigit { michael@0: }; michael@0: michael@0: // Faster specialization for bases <= 10 michael@0: template class BaseCharToDigit { michael@0: public: michael@0: static bool Convert(CHAR c, uint8* digit) { michael@0: if (c >= '0' && c < '0' + BASE) { michael@0: *digit = c - '0'; michael@0: return true; michael@0: } michael@0: return false; michael@0: } michael@0: }; michael@0: michael@0: // Specialization for bases where 10 < base <= 36 michael@0: template class BaseCharToDigit { michael@0: public: michael@0: static bool Convert(CHAR c, uint8* digit) { michael@0: if (c >= '0' && c <= '9') { michael@0: *digit = c - '0'; michael@0: } else if (c >= 'a' && c < 'a' + BASE - 10) { michael@0: *digit = c - 'a' + 10; michael@0: } else if (c >= 'A' && c < 'A' + BASE - 10) { michael@0: *digit = c - 'A' + 10; michael@0: } else { michael@0: return false; michael@0: } michael@0: return true; michael@0: } michael@0: }; michael@0: michael@0: template bool CharToDigit(CHAR c, uint8* digit) { michael@0: return BaseCharToDigit::Convert(c, digit); michael@0: } michael@0: michael@0: // There is an IsWhitespace for wchars defined in string_util.h, but it is michael@0: // locale independent, whereas the functions we are replacing were michael@0: // locale-dependent. TBD what is desired, but for the moment let's not introduce michael@0: // a change in behaviour. michael@0: template class WhitespaceHelper { michael@0: }; michael@0: michael@0: template<> class WhitespaceHelper { michael@0: public: michael@0: static bool Invoke(char c) { michael@0: return 0 != isspace(static_cast(c)); michael@0: } michael@0: }; michael@0: michael@0: template<> class WhitespaceHelper { michael@0: public: michael@0: static bool Invoke(char16 c) { michael@0: return 0 != iswspace(c); michael@0: } michael@0: }; michael@0: michael@0: template bool LocalIsWhitespace(CHAR c) { michael@0: return WhitespaceHelper::Invoke(c); michael@0: } michael@0: michael@0: // IteratorRangeToNumberTraits should provide: michael@0: // - a typedef for iterator_type, the iterator type used as input. michael@0: // - a typedef for value_type, the target numeric type. michael@0: // - static functions min, max (returning the minimum and maximum permitted michael@0: // values) michael@0: // - constant kBase, the base in which to interpret the input michael@0: template michael@0: class IteratorRangeToNumber { michael@0: public: michael@0: typedef IteratorRangeToNumberTraits traits; michael@0: typedef typename traits::iterator_type const_iterator; michael@0: typedef typename traits::value_type value_type; michael@0: michael@0: // Generalized iterator-range-to-number conversion. michael@0: // michael@0: static bool Invoke(const_iterator begin, michael@0: const_iterator end, michael@0: value_type* output) { michael@0: bool valid = true; michael@0: michael@0: while (begin != end && LocalIsWhitespace(*begin)) { michael@0: valid = false; michael@0: ++begin; michael@0: } michael@0: michael@0: if (begin != end && *begin == '-') { michael@0: if (!std::numeric_limits::is_signed) { michael@0: valid = false; michael@0: } else if (!Negative::Invoke(begin + 1, end, output)) { michael@0: valid = false; michael@0: } michael@0: } else { michael@0: if (begin != end && *begin == '+') { michael@0: ++begin; michael@0: } michael@0: if (!Positive::Invoke(begin, end, output)) { michael@0: valid = false; michael@0: } michael@0: } michael@0: michael@0: return valid; michael@0: } michael@0: michael@0: private: michael@0: // Sign provides: michael@0: // - a static function, CheckBounds, that determines whether the next digit michael@0: // causes an overflow/underflow michael@0: // - a static function, Increment, that appends the next digit appropriately michael@0: // according to the sign of the number being parsed. michael@0: template michael@0: class Base { michael@0: public: michael@0: static bool Invoke(const_iterator begin, const_iterator end, michael@0: typename traits::value_type* output) { michael@0: *output = 0; michael@0: michael@0: if (begin == end) { michael@0: return false; michael@0: } michael@0: michael@0: // Note: no performance difference was found when using template michael@0: // specialization to remove this check in bases other than 16 michael@0: if (traits::kBase == 16 && end - begin > 2 && *begin == '0' && michael@0: (*(begin + 1) == 'x' || *(begin + 1) == 'X')) { michael@0: begin += 2; michael@0: } michael@0: michael@0: for (const_iterator current = begin; current != end; ++current) { michael@0: uint8 new_digit = 0; michael@0: michael@0: if (!CharToDigit(*current, &new_digit)) { michael@0: return false; michael@0: } michael@0: michael@0: if (current != begin) { michael@0: if (!Sign::CheckBounds(output, new_digit)) { michael@0: return false; michael@0: } michael@0: *output *= traits::kBase; michael@0: } michael@0: michael@0: Sign::Increment(new_digit, output); michael@0: } michael@0: return true; michael@0: } michael@0: }; michael@0: michael@0: class Positive : public Base { michael@0: public: michael@0: static bool CheckBounds(value_type* output, uint8 new_digit) { michael@0: if (*output > static_cast(traits::max() / traits::kBase) || michael@0: (*output == static_cast(traits::max() / traits::kBase) && michael@0: new_digit > traits::max() % traits::kBase)) { michael@0: *output = traits::max(); michael@0: return false; michael@0: } michael@0: return true; michael@0: } michael@0: static void Increment(uint8 increment, value_type* output) { michael@0: *output += increment; michael@0: } michael@0: }; michael@0: michael@0: class Negative : public Base { michael@0: public: michael@0: static bool CheckBounds(value_type* output, uint8 new_digit) { michael@0: if (*output < traits::min() / traits::kBase || michael@0: (*output == traits::min() / traits::kBase && michael@0: new_digit > 0 - traits::min() % traits::kBase)) { michael@0: *output = traits::min(); michael@0: return false; michael@0: } michael@0: return true; michael@0: } michael@0: static void Increment(uint8 increment, value_type* output) { michael@0: *output -= increment; michael@0: } michael@0: }; michael@0: }; michael@0: michael@0: template michael@0: class BaseIteratorRangeToNumberTraits { michael@0: public: michael@0: typedef ITERATOR iterator_type; michael@0: typedef VALUE value_type; michael@0: static value_type min() { michael@0: return std::numeric_limits::min(); michael@0: } michael@0: static value_type max() { michael@0: return std::numeric_limits::max(); michael@0: } michael@0: static const int kBase = BASE; michael@0: }; michael@0: michael@0: template michael@0: class BaseHexIteratorRangeToIntTraits michael@0: : public BaseIteratorRangeToNumberTraits { michael@0: }; michael@0: michael@0: template michael@0: class BaseHexIteratorRangeToInt64Traits michael@0: : public BaseIteratorRangeToNumberTraits { michael@0: }; michael@0: michael@0: template michael@0: class BaseHexIteratorRangeToUInt64Traits michael@0: : public BaseIteratorRangeToNumberTraits { michael@0: }; michael@0: michael@0: typedef BaseHexIteratorRangeToIntTraits michael@0: HexIteratorRangeToIntTraits; michael@0: michael@0: typedef BaseHexIteratorRangeToInt64Traits michael@0: HexIteratorRangeToInt64Traits; michael@0: michael@0: typedef BaseHexIteratorRangeToUInt64Traits michael@0: HexIteratorRangeToUInt64Traits; michael@0: michael@0: template michael@0: bool HexStringToBytesT(const STR& input, std::vector* output) { michael@0: DCHECK_EQ(output->size(), 0u); michael@0: size_t count = input.size(); michael@0: if (count == 0 || (count % 2) != 0) michael@0: return false; michael@0: for (uintptr_t i = 0; i < count / 2; ++i) { michael@0: uint8 msb = 0; // most significant 4 bits michael@0: uint8 lsb = 0; // least significant 4 bits michael@0: if (!CharToDigit<16>(input[i * 2], &msb) || michael@0: !CharToDigit<16>(input[i * 2 + 1], &lsb)) michael@0: return false; michael@0: output->push_back((msb << 4) | lsb); michael@0: } michael@0: return true; michael@0: } michael@0: michael@0: template michael@0: class StringPieceToNumberTraits michael@0: : public BaseIteratorRangeToNumberTraits { michael@0: }; michael@0: michael@0: template michael@0: bool StringToIntImpl(const StringPiece& input, VALUE* output) { michael@0: return IteratorRangeToNumber >::Invoke( michael@0: input.begin(), input.end(), output); michael@0: } michael@0: michael@0: template michael@0: class StringPiece16ToNumberTraits michael@0: : public BaseIteratorRangeToNumberTraits { michael@0: }; michael@0: michael@0: template michael@0: bool String16ToIntImpl(const StringPiece16& input, VALUE* output) { michael@0: return IteratorRangeToNumber >::Invoke( michael@0: input.begin(), input.end(), output); michael@0: } michael@0: michael@0: } // namespace michael@0: michael@0: std::string IntToString(int value) { michael@0: return IntToStringT:: michael@0: IntToString(value); michael@0: } michael@0: michael@0: string16 IntToString16(int value) { michael@0: return IntToStringT:: michael@0: IntToString(value); michael@0: } michael@0: michael@0: std::string UintToString(unsigned int value) { michael@0: return IntToStringT:: michael@0: IntToString(value); michael@0: } michael@0: michael@0: string16 UintToString16(unsigned int value) { michael@0: return IntToStringT:: michael@0: IntToString(value); michael@0: } michael@0: michael@0: std::string Int64ToString(int64 value) { michael@0: return IntToStringT:: michael@0: IntToString(value); michael@0: } michael@0: michael@0: string16 Int64ToString16(int64 value) { michael@0: return IntToStringT::IntToString(value); michael@0: } michael@0: michael@0: std::string Uint64ToString(uint64 value) { michael@0: return IntToStringT:: michael@0: IntToString(value); michael@0: } michael@0: michael@0: string16 Uint64ToString16(uint64 value) { michael@0: return IntToStringT:: michael@0: IntToString(value); michael@0: } michael@0: michael@0: std::string DoubleToString(double value) { michael@0: // According to g_fmt.cc, it is sufficient to declare a buffer of size 32. michael@0: char buffer[32]; michael@0: dmg_fp::g_fmt(buffer, value); michael@0: return std::string(buffer); michael@0: } michael@0: michael@0: bool StringToInt(const StringPiece& input, int* output) { michael@0: return StringToIntImpl(input, output); michael@0: } michael@0: michael@0: bool StringToInt(const StringPiece16& input, int* output) { michael@0: return String16ToIntImpl(input, output); michael@0: } michael@0: michael@0: bool StringToUint(const StringPiece& input, unsigned* output) { michael@0: return StringToIntImpl(input, output); michael@0: } michael@0: michael@0: bool StringToUint(const StringPiece16& input, unsigned* output) { michael@0: return String16ToIntImpl(input, output); michael@0: } michael@0: michael@0: bool StringToInt64(const StringPiece& input, int64* output) { michael@0: return StringToIntImpl(input, output); michael@0: } michael@0: michael@0: bool StringToInt64(const StringPiece16& input, int64* output) { michael@0: return String16ToIntImpl(input, output); michael@0: } michael@0: michael@0: bool StringToUint64(const StringPiece& input, uint64* output) { michael@0: return StringToIntImpl(input, output); michael@0: } michael@0: michael@0: bool StringToUint64(const StringPiece16& input, uint64* output) { michael@0: return String16ToIntImpl(input, output); michael@0: } michael@0: michael@0: bool StringToSizeT(const StringPiece& input, size_t* output) { michael@0: return StringToIntImpl(input, output); michael@0: } michael@0: michael@0: bool StringToSizeT(const StringPiece16& input, size_t* output) { michael@0: return String16ToIntImpl(input, output); michael@0: } michael@0: michael@0: bool StringToDouble(const std::string& input, double* output) { michael@0: // Thread-safe? It is on at least Mac, Linux, and Windows. michael@0: ScopedClearErrno clear_errno; michael@0: michael@0: char* endptr = NULL; michael@0: *output = dmg_fp::strtod(input.c_str(), &endptr); michael@0: michael@0: // Cases to return false: michael@0: // - If errno is ERANGE, there was an overflow or underflow. michael@0: // - If the input string is empty, there was nothing to parse. michael@0: // - If endptr does not point to the end of the string, there are either michael@0: // characters remaining in the string after a parsed number, or the string michael@0: // does not begin with a parseable number. endptr is compared to the michael@0: // expected end given the string's stated length to correctly catch cases michael@0: // where the string contains embedded NUL characters. michael@0: // - If the first character is a space, there was leading whitespace michael@0: return errno == 0 && michael@0: !input.empty() && michael@0: input.c_str() + input.length() == endptr && michael@0: !isspace(input[0]); michael@0: } michael@0: michael@0: // Note: if you need to add String16ToDouble, first ask yourself if it's michael@0: // really necessary. If it is, probably the best implementation here is to michael@0: // convert to 8-bit and then use the 8-bit version. michael@0: michael@0: // Note: if you need to add an iterator range version of StringToDouble, first michael@0: // ask yourself if it's really necessary. If it is, probably the best michael@0: // implementation here is to instantiate a string and use the string version. michael@0: michael@0: std::string HexEncode(const void* bytes, size_t size) { michael@0: static const char kHexChars[] = "0123456789ABCDEF"; michael@0: michael@0: // Each input byte creates two output hex characters. michael@0: std::string ret(size * 2, '\0'); michael@0: michael@0: for (size_t i = 0; i < size; ++i) { michael@0: char b = reinterpret_cast(bytes)[i]; michael@0: ret[(i * 2)] = kHexChars[(b >> 4) & 0xf]; michael@0: ret[(i * 2) + 1] = kHexChars[b & 0xf]; michael@0: } michael@0: return ret; michael@0: } michael@0: michael@0: bool HexStringToInt(const StringPiece& input, int* output) { michael@0: return IteratorRangeToNumber::Invoke( michael@0: input.begin(), input.end(), output); michael@0: } michael@0: michael@0: bool HexStringToInt64(const StringPiece& input, int64* output) { michael@0: return IteratorRangeToNumber::Invoke( michael@0: input.begin(), input.end(), output); michael@0: } michael@0: michael@0: bool HexStringToUInt64(const StringPiece& input, uint64* output) { michael@0: return IteratorRangeToNumber::Invoke( michael@0: input.begin(), input.end(), output); michael@0: } michael@0: michael@0: bool HexStringToBytes(const std::string& input, std::vector* output) { michael@0: return HexStringToBytesT(input, output); michael@0: } michael@0: michael@0: } // namespace base