PageRenderTime 68ms CodeModel.GetById 12ms RepoModel.GetById 0ms app.codeStats 0ms

/external/chromium/base/string_number_conversions.cc

https://gitlab.com/brian0218/rk3066_r-box_android4.2.2_sdk
C++ | 544 lines | 406 code | 78 blank | 60 comment | 62 complexity | 4b5d1a2e91a27a6b926ebbb657488267 MD5 | raw file
  1. // Copyright (c) 2010 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. #include "base/string_number_conversions.h"
  5. #include <errno.h>
  6. #include <stdlib.h>
  7. #include <limits>
  8. #include "base/logging.h"
  9. #include "base/third_party/dmg_fp/dmg_fp.h"
  10. #include "base/utf_string_conversions.h"
  11. namespace base {
  12. namespace {
  13. template <typename STR, typename INT, typename UINT, bool NEG>
  14. struct IntToStringT {
  15. // This is to avoid a compiler warning about unary minus on unsigned type.
  16. // For example, say you had the following code:
  17. // template <typename INT>
  18. // INT abs(INT value) { return value < 0 ? -value : value; }
  19. // Even though if INT is unsigned, it's impossible for value < 0, so the
  20. // unary minus will never be taken, the compiler will still generate a
  21. // warning. We do a little specialization dance...
  22. template <typename INT2, typename UINT2, bool NEG2>
  23. struct ToUnsignedT {};
  24. template <typename INT2, typename UINT2>
  25. struct ToUnsignedT<INT2, UINT2, false> {
  26. static UINT2 ToUnsigned(INT2 value) {
  27. return static_cast<UINT2>(value);
  28. }
  29. };
  30. template <typename INT2, typename UINT2>
  31. struct ToUnsignedT<INT2, UINT2, true> {
  32. static UINT2 ToUnsigned(INT2 value) {
  33. return static_cast<UINT2>(value < 0 ? -value : value);
  34. }
  35. };
  36. // This set of templates is very similar to the above templates, but
  37. // for testing whether an integer is negative.
  38. template <typename INT2, bool NEG2>
  39. struct TestNegT {};
  40. template <typename INT2>
  41. struct TestNegT<INT2, false> {
  42. static bool TestNeg(INT2 value) {
  43. // value is unsigned, and can never be negative.
  44. return false;
  45. }
  46. };
  47. template <typename INT2>
  48. struct TestNegT<INT2, true> {
  49. static bool TestNeg(INT2 value) {
  50. return value < 0;
  51. }
  52. };
  53. static STR IntToString(INT value) {
  54. // log10(2) ~= 0.3 bytes needed per bit or per byte log10(2**8) ~= 2.4.
  55. // So round up to allocate 3 output characters per byte, plus 1 for '-'.
  56. const int kOutputBufSize = 3 * sizeof(INT) + 1;
  57. // Allocate the whole string right away, we will right back to front, and
  58. // then return the substr of what we ended up using.
  59. STR outbuf(kOutputBufSize, 0);
  60. bool is_neg = TestNegT<INT, NEG>::TestNeg(value);
  61. // Even though is_neg will never be true when INT is parameterized as
  62. // unsigned, even the presence of the unary operation causes a warning.
  63. UINT res = ToUnsignedT<INT, UINT, NEG>::ToUnsigned(value);
  64. for (typename STR::iterator it = outbuf.end();;) {
  65. --it;
  66. DCHECK(it != outbuf.begin());
  67. *it = static_cast<typename STR::value_type>((res % 10) + '0');
  68. res /= 10;
  69. // We're done..
  70. if (res == 0) {
  71. if (is_neg) {
  72. --it;
  73. DCHECK(it != outbuf.begin());
  74. *it = static_cast<typename STR::value_type>('-');
  75. }
  76. return STR(it, outbuf.end());
  77. }
  78. }
  79. NOTREACHED();
  80. return STR();
  81. }
  82. };
  83. // Utility to convert a character to a digit in a given base
  84. template<typename CHAR, int BASE, bool BASE_LTE_10> class BaseCharToDigit {
  85. };
  86. // Faster specialization for bases <= 10
  87. template<typename CHAR, int BASE> class BaseCharToDigit<CHAR, BASE, true> {
  88. public:
  89. static bool Convert(CHAR c, uint8* digit) {
  90. if (c >= '0' && c < '0' + BASE) {
  91. *digit = c - '0';
  92. return true;
  93. }
  94. return false;
  95. }
  96. };
  97. // Specialization for bases where 10 < base <= 36
  98. template<typename CHAR, int BASE> class BaseCharToDigit<CHAR, BASE, false> {
  99. public:
  100. static bool Convert(CHAR c, uint8* digit) {
  101. if (c >= '0' && c <= '9') {
  102. *digit = c - '0';
  103. } else if (c >= 'a' && c < 'a' + BASE - 10) {
  104. *digit = c - 'a' + 10;
  105. } else if (c >= 'A' && c < 'A' + BASE - 10) {
  106. *digit = c - 'A' + 10;
  107. } else {
  108. return false;
  109. }
  110. return true;
  111. }
  112. };
  113. template<int BASE, typename CHAR> bool CharToDigit(CHAR c, uint8* digit) {
  114. return BaseCharToDigit<CHAR, BASE, BASE <= 10>::Convert(c, digit);
  115. }
  116. // There is an IsWhitespace for wchars defined in string_util.h, but it is
  117. // locale independent, whereas the functions we are replacing were
  118. // locale-dependent. TBD what is desired, but for the moment let's not introduce
  119. // a change in behaviour.
  120. template<typename CHAR> class WhitespaceHelper {
  121. };
  122. template<> class WhitespaceHelper<char> {
  123. public:
  124. static bool Invoke(char c) {
  125. return 0 != isspace(static_cast<unsigned char>(c));
  126. }
  127. };
  128. template<> class WhitespaceHelper<char16> {
  129. public:
  130. static bool Invoke(char16 c) {
  131. return 0 != iswspace(c);
  132. }
  133. };
  134. template<typename CHAR> bool LocalIsWhitespace(CHAR c) {
  135. return WhitespaceHelper<CHAR>::Invoke(c);
  136. }
  137. // IteratorRangeToNumberTraits should provide:
  138. // - a typedef for iterator_type, the iterator type used as input.
  139. // - a typedef for value_type, the target numeric type.
  140. // - static functions min, max (returning the minimum and maximum permitted
  141. // values)
  142. // - constant kBase, the base in which to interpret the input
  143. template<typename IteratorRangeToNumberTraits>
  144. class IteratorRangeToNumber {
  145. public:
  146. typedef IteratorRangeToNumberTraits traits;
  147. typedef typename traits::iterator_type const_iterator;
  148. typedef typename traits::value_type value_type;
  149. // Generalized iterator-range-to-number conversion.
  150. //
  151. static bool Invoke(const_iterator begin,
  152. const_iterator end,
  153. value_type* output) {
  154. bool valid = true;
  155. while (begin != end && LocalIsWhitespace(*begin)) {
  156. valid = false;
  157. ++begin;
  158. }
  159. if (begin != end && *begin == '-') {
  160. if (!Negative::Invoke(begin + 1, end, output)) {
  161. valid = false;
  162. }
  163. } else {
  164. if (begin != end && *begin == '+') {
  165. ++begin;
  166. }
  167. if (!Positive::Invoke(begin, end, output)) {
  168. valid = false;
  169. }
  170. }
  171. return valid;
  172. }
  173. private:
  174. // Sign provides:
  175. // - a static function, CheckBounds, that determines whether the next digit
  176. // causes an overflow/underflow
  177. // - a static function, Increment, that appends the next digit appropriately
  178. // according to the sign of the number being parsed.
  179. template<typename Sign>
  180. class Base {
  181. public:
  182. static bool Invoke(const_iterator begin, const_iterator end,
  183. typename traits::value_type* output) {
  184. *output = 0;
  185. if (begin == end) {
  186. return false;
  187. }
  188. // Note: no performance difference was found when using template
  189. // specialization to remove this check in bases other than 16
  190. if (traits::kBase == 16 && end - begin >= 2 && *begin == '0' &&
  191. (*(begin + 1) == 'x' || *(begin + 1) == 'X')) {
  192. begin += 2;
  193. }
  194. for (const_iterator current = begin; current != end; ++current) {
  195. uint8 new_digit = 0;
  196. if (!CharToDigit<traits::kBase>(*current, &new_digit)) {
  197. return false;
  198. }
  199. if (current != begin) {
  200. if (!Sign::CheckBounds(output, new_digit)) {
  201. return false;
  202. }
  203. *output *= traits::kBase;
  204. }
  205. Sign::Increment(new_digit, output);
  206. }
  207. return true;
  208. }
  209. };
  210. class Positive : public Base<Positive> {
  211. public:
  212. static bool CheckBounds(value_type* output, uint8 new_digit) {
  213. 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. }
  221. static void Increment(uint8 increment, value_type* output) {
  222. *output += increment;
  223. }
  224. };
  225. class Negative : public Base<Negative> {
  226. public:
  227. static bool CheckBounds(value_type* output, uint8 new_digit) {
  228. if (*output < traits::min() / traits::kBase ||
  229. (*output == traits::min() / traits::kBase &&
  230. new_digit > 0 - traits::min() % traits::kBase)) {
  231. *output = traits::min();
  232. return false;
  233. }
  234. return true;
  235. }
  236. static void Increment(uint8 increment, value_type* output) {
  237. *output -= increment;
  238. }
  239. };
  240. };
  241. template<typename ITERATOR, typename VALUE, int BASE>
  242. class BaseIteratorRangeToNumberTraits {
  243. public:
  244. typedef ITERATOR iterator_type;
  245. typedef VALUE value_type;
  246. static value_type min() {
  247. return std::numeric_limits<value_type>::min();
  248. }
  249. static value_type max() {
  250. return std::numeric_limits<value_type>::max();
  251. }
  252. static const int kBase = BASE;
  253. };
  254. typedef BaseIteratorRangeToNumberTraits<std::string::const_iterator, int, 10>
  255. IteratorRangeToIntTraits;
  256. typedef BaseIteratorRangeToNumberTraits<string16::const_iterator, int, 10>
  257. WideIteratorRangeToIntTraits;
  258. typedef BaseIteratorRangeToNumberTraits<std::string::const_iterator, int64, 10>
  259. IteratorRangeToInt64Traits;
  260. typedef BaseIteratorRangeToNumberTraits<string16::const_iterator, int64, 10>
  261. WideIteratorRangeToInt64Traits;
  262. typedef BaseIteratorRangeToNumberTraits<const char*, int, 10>
  263. CharBufferToIntTraits;
  264. typedef BaseIteratorRangeToNumberTraits<const char16*, int, 10>
  265. WideCharBufferToIntTraits;
  266. typedef BaseIteratorRangeToNumberTraits<const char*, int64, 10>
  267. CharBufferToInt64Traits;
  268. typedef BaseIteratorRangeToNumberTraits<const char16*, int64, 10>
  269. WideCharBufferToInt64Traits;
  270. template<typename ITERATOR>
  271. class BaseHexIteratorRangeToIntTraits
  272. : public BaseIteratorRangeToNumberTraits<ITERATOR, int, 16> {
  273. public:
  274. // Allow parsing of 0xFFFFFFFF, which is technically an overflow
  275. static unsigned int max() {
  276. return std::numeric_limits<unsigned int>::max();
  277. }
  278. };
  279. typedef BaseHexIteratorRangeToIntTraits<std::string::const_iterator>
  280. HexIteratorRangeToIntTraits;
  281. typedef BaseHexIteratorRangeToIntTraits<const char*>
  282. HexCharBufferToIntTraits;
  283. template<typename STR>
  284. bool HexStringToBytesT(const STR& input, std::vector<uint8>* output) {
  285. DCHECK_EQ(output->size(), 0u);
  286. size_t count = input.size();
  287. if (count == 0 || (count % 2) != 0)
  288. return false;
  289. for (uintptr_t i = 0; i < count / 2; ++i) {
  290. uint8 msb = 0; // most significant 4 bits
  291. uint8 lsb = 0; // least significant 4 bits
  292. if (!CharToDigit<16>(input[i * 2], &msb) ||
  293. !CharToDigit<16>(input[i * 2 + 1], &lsb))
  294. return false;
  295. output->push_back((msb << 4) | lsb);
  296. }
  297. return true;
  298. }
  299. } // namespace
  300. std::string IntToString(int value) {
  301. return IntToStringT<std::string, int, unsigned int, true>::
  302. IntToString(value);
  303. }
  304. string16 IntToString16(int value) {
  305. return IntToStringT<string16, int, unsigned int, true>::
  306. IntToString(value);
  307. }
  308. std::string UintToString(unsigned int value) {
  309. return IntToStringT<std::string, unsigned int, unsigned int, false>::
  310. IntToString(value);
  311. }
  312. string16 UintToString16(unsigned int value) {
  313. return IntToStringT<string16, unsigned int, unsigned int, false>::
  314. IntToString(value);
  315. }
  316. std::string Int64ToString(int64 value) {
  317. return IntToStringT<std::string, int64, uint64, true>::
  318. IntToString(value);
  319. }
  320. string16 Int64ToString16(int64 value) {
  321. return IntToStringT<string16, int64, uint64, true>::IntToString(value);
  322. }
  323. std::string Uint64ToString(uint64 value) {
  324. return IntToStringT<std::string, uint64, uint64, false>::
  325. IntToString(value);
  326. }
  327. string16 Uint64ToString16(uint64 value) {
  328. return IntToStringT<string16, uint64, uint64, false>::
  329. IntToString(value);
  330. }
  331. std::string DoubleToString(double value) {
  332. // According to g_fmt.cc, it is sufficient to declare a buffer of size 32.
  333. char buffer[32];
  334. dmg_fp::g_fmt(buffer, value);
  335. return std::string(buffer);
  336. }
  337. bool StringToInt(const std::string& input, int* output) {
  338. return IteratorRangeToNumber<IteratorRangeToIntTraits>::Invoke(input.begin(),
  339. input.end(),
  340. output);
  341. }
  342. #if !defined(ANDROID)
  343. bool StringToInt(std::string::const_iterator begin,
  344. std::string::const_iterator end,
  345. int* output) {
  346. return IteratorRangeToNumber<IteratorRangeToIntTraits>::Invoke(begin,
  347. end,
  348. output);
  349. }
  350. #endif
  351. bool StringToInt(const char* begin, const char* end, int* output) {
  352. return IteratorRangeToNumber<CharBufferToIntTraits>::Invoke(begin,
  353. end,
  354. output);
  355. }
  356. bool StringToInt(const string16& input, int* output) {
  357. return IteratorRangeToNumber<WideIteratorRangeToIntTraits>::Invoke(
  358. input.begin(), input.end(), output);
  359. }
  360. #if !defined(ANDROID)
  361. bool StringToInt(string16::const_iterator begin,
  362. string16::const_iterator end,
  363. int* output) {
  364. return IteratorRangeToNumber<WideIteratorRangeToIntTraits>::Invoke(begin,
  365. end,
  366. output);
  367. }
  368. #endif
  369. bool StringToInt(const char16* begin, const char16* end, int* output) {
  370. return IteratorRangeToNumber<WideCharBufferToIntTraits>::Invoke(begin,
  371. end,
  372. output);
  373. }
  374. bool StringToInt64(const std::string& input, int64* output) {
  375. return IteratorRangeToNumber<IteratorRangeToInt64Traits>::Invoke(
  376. input.begin(), input.end(), output);
  377. }
  378. #if !defined(ANDROID)
  379. bool StringToInt64(std::string::const_iterator begin,
  380. std::string::const_iterator end,
  381. int64* output) {
  382. return IteratorRangeToNumber<IteratorRangeToInt64Traits>::Invoke(begin,
  383. end,
  384. output);
  385. }
  386. #endif
  387. bool StringToInt64(const char* begin, const char* end, int64* output) {
  388. return IteratorRangeToNumber<CharBufferToInt64Traits>::Invoke(begin,
  389. end,
  390. output);
  391. }
  392. bool StringToInt64(const string16& input, int64* output) {
  393. return IteratorRangeToNumber<WideIteratorRangeToInt64Traits>::Invoke(
  394. input.begin(), input.end(), output);
  395. }
  396. #if !defined(ANDROID)
  397. bool StringToInt64(string16::const_iterator begin,
  398. string16::const_iterator end,
  399. int64* output) {
  400. return IteratorRangeToNumber<WideIteratorRangeToInt64Traits>::Invoke(begin,
  401. end,
  402. output);
  403. }
  404. #endif
  405. bool StringToInt64(const char16* begin, const char16* end, int64* output) {
  406. return IteratorRangeToNumber<WideCharBufferToInt64Traits>::Invoke(begin,
  407. end,
  408. output);
  409. }
  410. bool StringToDouble(const std::string& input, double* output) {
  411. errno = 0; // Thread-safe? It is on at least Mac, Linux, and Windows.
  412. char* endptr = NULL;
  413. *output = dmg_fp::strtod(input.c_str(), &endptr);
  414. // Cases to return false:
  415. // - If errno is ERANGE, there was an overflow or underflow.
  416. // - If the input string is empty, there was nothing to parse.
  417. // - If endptr does not point to the end of the string, there are either
  418. // characters remaining in the string after a parsed number, or the string
  419. // does not begin with a parseable number. endptr is compared to the
  420. // expected end given the string's stated length to correctly catch cases
  421. // where the string contains embedded NUL characters.
  422. // - If the first character is a space, there was leading whitespace
  423. return errno == 0 &&
  424. !input.empty() &&
  425. input.c_str() + input.length() == endptr &&
  426. !isspace(input[0]);
  427. }
  428. // Note: if you need to add String16ToDouble, first ask yourself if it's
  429. // really necessary. If it is, probably the best implementation here is to
  430. // convert to 8-bit and then use the 8-bit version.
  431. // Note: if you need to add an iterator range version of StringToDouble, first
  432. // ask yourself if it's really necessary. If it is, probably the best
  433. // implementation here is to instantiate a string and use the string version.
  434. std::string HexEncode(const void* bytes, size_t size) {
  435. static const char kHexChars[] = "0123456789ABCDEF";
  436. // Each input byte creates two output hex characters.
  437. std::string ret(size * 2, '\0');
  438. for (size_t i = 0; i < size; ++i) {
  439. char b = reinterpret_cast<const char*>(bytes)[i];
  440. ret[(i * 2)] = kHexChars[(b >> 4) & 0xf];
  441. ret[(i * 2) + 1] = kHexChars[b & 0xf];
  442. }
  443. return ret;
  444. }
  445. bool HexStringToInt(const std::string& input, int* output) {
  446. return IteratorRangeToNumber<HexIteratorRangeToIntTraits>::Invoke(
  447. input.begin(), input.end(), output);
  448. }
  449. #if !defined(ANDROID)
  450. bool HexStringToInt(std::string::const_iterator begin,
  451. std::string::const_iterator end,
  452. int* output) {
  453. return IteratorRangeToNumber<HexIteratorRangeToIntTraits>::Invoke(begin,
  454. end,
  455. output);
  456. }
  457. #endif
  458. bool HexStringToInt(const char* begin, const char* end, int* output) {
  459. return IteratorRangeToNumber<HexCharBufferToIntTraits>::Invoke(begin,
  460. end,
  461. output);
  462. }
  463. bool HexStringToBytes(const std::string& input, std::vector<uint8>* output) {
  464. return HexStringToBytesT(input, output);
  465. }
  466. } // namespace base