numbers.h 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300
  1. // Copyright 2017 The Abseil Authors.
  2. //
  3. // Licensed under the Apache License, Version 2.0 (the "License");
  4. // you may not use this file except in compliance with the License.
  5. // You may obtain a copy of the License at
  6. //
  7. // https://www.apache.org/licenses/LICENSE-2.0
  8. //
  9. // Unless required by applicable law or agreed to in writing, software
  10. // distributed under the License is distributed on an "AS IS" BASIS,
  11. // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12. // See the License for the specific language governing permissions and
  13. // limitations under the License.
  14. //
  15. // -----------------------------------------------------------------------------
  16. // File: numbers.h
  17. // -----------------------------------------------------------------------------
  18. //
  19. // This package contains functions for converting strings to numbers. For
  20. // converting numbers to strings, use `StrCat()` or `StrAppend()` in str_cat.h,
  21. // which automatically detect and convert most number values appropriately.
  22. #ifndef ABSL_STRINGS_NUMBERS_H_
  23. #define ABSL_STRINGS_NUMBERS_H_
  24. #ifdef __SSE4_2__
  25. #include <x86intrin.h>
  26. #endif
  27. #include <cstddef>
  28. #include <cstdlib>
  29. #include <cstring>
  30. #include <ctime>
  31. #include <limits>
  32. #include <string>
  33. #include <type_traits>
  34. #include "absl/base/config.h"
  35. #ifdef __SSE4_2__
  36. // TODO(jorg): Remove this when we figure out the right way
  37. // to swap bytes on SSE 4.2 that works with the compilers
  38. // we claim to support. Also, add tests for the compiler
  39. // that doesn't support the Intel _bswap64 intrinsic but
  40. // does support all the SSE 4.2 intrinsics
  41. #include "absl/base/internal/endian.h"
  42. #endif
  43. #include "absl/base/macros.h"
  44. #include "absl/base/port.h"
  45. #include "absl/numeric/bits.h"
  46. #include "absl/numeric/int128.h"
  47. #include "absl/strings/string_view.h"
  48. namespace absl {
  49. ABSL_NAMESPACE_BEGIN
  50. // SimpleAtoi()
  51. //
  52. // Converts the given string (optionally followed or preceded by ASCII
  53. // whitespace) into an integer value, returning `true` if successful. The string
  54. // must reflect a base-10 integer whose value falls within the range of the
  55. // integer type (optionally preceded by a `+` or `-`). If any errors are
  56. // encountered, this function returns `false`, leaving `out` in an unspecified
  57. // state.
  58. template <typename int_type>
  59. ABSL_MUST_USE_RESULT bool SimpleAtoi(absl::string_view str, int_type* out);
  60. // SimpleAtof()
  61. //
  62. // Converts the given string (optionally followed or preceded by ASCII
  63. // whitespace) into a float, which may be rounded on overflow or underflow,
  64. // returning `true` if successful.
  65. // See https://en.cppreference.com/w/c/string/byte/strtof for details about the
  66. // allowed formats for `str`, except SimpleAtof() is locale-independent and will
  67. // always use the "C" locale. If any errors are encountered, this function
  68. // returns `false`, leaving `out` in an unspecified state.
  69. ABSL_MUST_USE_RESULT bool SimpleAtof(absl::string_view str, float* out);
  70. // SimpleAtod()
  71. //
  72. // Converts the given string (optionally followed or preceded by ASCII
  73. // whitespace) into a double, which may be rounded on overflow or underflow,
  74. // returning `true` if successful.
  75. // See https://en.cppreference.com/w/c/string/byte/strtof for details about the
  76. // allowed formats for `str`, except SimpleAtod is locale-independent and will
  77. // always use the "C" locale. If any errors are encountered, this function
  78. // returns `false`, leaving `out` in an unspecified state.
  79. ABSL_MUST_USE_RESULT bool SimpleAtod(absl::string_view str, double* out);
  80. // SimpleAtob()
  81. //
  82. // Converts the given string into a boolean, returning `true` if successful.
  83. // The following case-insensitive strings are interpreted as boolean `true`:
  84. // "true", "t", "yes", "y", "1". The following case-insensitive strings
  85. // are interpreted as boolean `false`: "false", "f", "no", "n", "0". If any
  86. // errors are encountered, this function returns `false`, leaving `out` in an
  87. // unspecified state.
  88. ABSL_MUST_USE_RESULT bool SimpleAtob(absl::string_view str, bool* out);
  89. // SimpleHexAtoi()
  90. //
  91. // Converts a hexadecimal string (optionally followed or preceded by ASCII
  92. // whitespace) to an integer, returning `true` if successful. Only valid base-16
  93. // hexadecimal integers whose value falls within the range of the integer type
  94. // (optionally preceded by a `+` or `-`) can be converted. A valid hexadecimal
  95. // value may include both upper and lowercase character symbols, and may
  96. // optionally include a leading "0x" (or "0X") number prefix, which is ignored
  97. // by this function. If any errors are encountered, this function returns
  98. // `false`, leaving `out` in an unspecified state.
  99. template <typename int_type>
  100. ABSL_MUST_USE_RESULT bool SimpleHexAtoi(absl::string_view str, int_type* out);
  101. // Overloads of SimpleHexAtoi() for 128 bit integers.
  102. ABSL_MUST_USE_RESULT inline bool SimpleHexAtoi(absl::string_view str,
  103. absl::int128* out);
  104. ABSL_MUST_USE_RESULT inline bool SimpleHexAtoi(absl::string_view str,
  105. absl::uint128* out);
  106. ABSL_NAMESPACE_END
  107. } // namespace absl
  108. // End of public API. Implementation details follow.
  109. namespace absl {
  110. ABSL_NAMESPACE_BEGIN
  111. namespace numbers_internal {
  112. // Digit conversion.
  113. ABSL_DLL extern const char kHexChar[17]; // 0123456789abcdef
  114. ABSL_DLL extern const char
  115. kHexTable[513]; // 000102030405060708090a0b0c0d0e0f1011...
  116. ABSL_DLL extern const char
  117. two_ASCII_digits[100][2]; // 00, 01, 02, 03...
  118. // Writes a two-character representation of 'i' to 'buf'. 'i' must be in the
  119. // range 0 <= i < 100, and buf must have space for two characters. Example:
  120. // char buf[2];
  121. // PutTwoDigits(42, buf);
  122. // // buf[0] == '4'
  123. // // buf[1] == '2'
  124. inline void PutTwoDigits(size_t i, char* buf) {
  125. assert(i < 100);
  126. memcpy(buf, two_ASCII_digits[i], 2);
  127. }
  128. // safe_strto?() functions for implementing SimpleAtoi()
  129. bool safe_strto32_base(absl::string_view text, int32_t* value, int base);
  130. bool safe_strto64_base(absl::string_view text, int64_t* value, int base);
  131. bool safe_strto128_base(absl::string_view text, absl::int128* value,
  132. int base);
  133. bool safe_strtou32_base(absl::string_view text, uint32_t* value, int base);
  134. bool safe_strtou64_base(absl::string_view text, uint64_t* value, int base);
  135. bool safe_strtou128_base(absl::string_view text, absl::uint128* value,
  136. int base);
  137. static const int kFastToBufferSize = 32;
  138. static const int kSixDigitsToBufferSize = 16;
  139. // Helper function for fast formatting of floating-point values.
  140. // The result is the same as printf's "%g", a.k.a. "%.6g"; that is, six
  141. // significant digits are returned, trailing zeros are removed, and numbers
  142. // outside the range 0.0001-999999 are output using scientific notation
  143. // (1.23456e+06). This routine is heavily optimized.
  144. // Required buffer size is `kSixDigitsToBufferSize`.
  145. size_t SixDigitsToBuffer(double d, char* buffer);
  146. // These functions are intended for speed. All functions take an output buffer
  147. // as an argument and return a pointer to the last byte they wrote, which is the
  148. // terminating '\0'. At most `kFastToBufferSize` bytes are written.
  149. char* FastIntToBuffer(int32_t, char*);
  150. char* FastIntToBuffer(uint32_t, char*);
  151. char* FastIntToBuffer(int64_t, char*);
  152. char* FastIntToBuffer(uint64_t, char*);
  153. // For enums and integer types that are not an exact match for the types above,
  154. // use templates to call the appropriate one of the four overloads above.
  155. template <typename int_type>
  156. char* FastIntToBuffer(int_type i, char* buffer) {
  157. static_assert(sizeof(i) <= 64 / 8,
  158. "FastIntToBuffer works only with 64-bit-or-less integers.");
  159. // TODO(jorg): This signed-ness check is used because it works correctly
  160. // with enums, and it also serves to check that int_type is not a pointer.
  161. // If one day something like std::is_signed<enum E> works, switch to it.
  162. if (static_cast<int_type>(1) - 2 < 0) { // Signed
  163. if (sizeof(i) > 32 / 8) { // 33-bit to 64-bit
  164. return FastIntToBuffer(static_cast<int64_t>(i), buffer);
  165. } else { // 32-bit or less
  166. return FastIntToBuffer(static_cast<int32_t>(i), buffer);
  167. }
  168. } else { // Unsigned
  169. if (sizeof(i) > 32 / 8) { // 33-bit to 64-bit
  170. return FastIntToBuffer(static_cast<uint64_t>(i), buffer);
  171. } else { // 32-bit or less
  172. return FastIntToBuffer(static_cast<uint32_t>(i), buffer);
  173. }
  174. }
  175. }
  176. // Implementation of SimpleAtoi, generalized to support arbitrary base (used
  177. // with base different from 10 elsewhere in Abseil implementation).
  178. template <typename int_type>
  179. ABSL_MUST_USE_RESULT bool safe_strtoi_base(absl::string_view s, int_type* out,
  180. int base) {
  181. static_assert(sizeof(*out) == 4 || sizeof(*out) == 8,
  182. "SimpleAtoi works only with 32-bit or 64-bit integers.");
  183. static_assert(!std::is_floating_point<int_type>::value,
  184. "Use SimpleAtof or SimpleAtod instead.");
  185. bool parsed;
  186. // TODO(jorg): This signed-ness check is used because it works correctly
  187. // with enums, and it also serves to check that int_type is not a pointer.
  188. // If one day something like std::is_signed<enum E> works, switch to it.
  189. if (static_cast<int_type>(1) - 2 < 0) { // Signed
  190. if (sizeof(*out) == 64 / 8) { // 64-bit
  191. int64_t val;
  192. parsed = numbers_internal::safe_strto64_base(s, &val, base);
  193. *out = static_cast<int_type>(val);
  194. } else { // 32-bit
  195. int32_t val;
  196. parsed = numbers_internal::safe_strto32_base(s, &val, base);
  197. *out = static_cast<int_type>(val);
  198. }
  199. } else { // Unsigned
  200. if (sizeof(*out) == 64 / 8) { // 64-bit
  201. uint64_t val;
  202. parsed = numbers_internal::safe_strtou64_base(s, &val, base);
  203. *out = static_cast<int_type>(val);
  204. } else { // 32-bit
  205. uint32_t val;
  206. parsed = numbers_internal::safe_strtou32_base(s, &val, base);
  207. *out = static_cast<int_type>(val);
  208. }
  209. }
  210. return parsed;
  211. }
  212. // FastHexToBufferZeroPad16()
  213. //
  214. // Outputs `val` into `out` as if by `snprintf(out, 17, "%016x", val)` but
  215. // without the terminating null character. Thus `out` must be of length >= 16.
  216. // Returns the number of non-pad digits of the output (it can never be zero
  217. // since 0 has one digit).
  218. inline size_t FastHexToBufferZeroPad16(uint64_t val, char* out) {
  219. #ifdef __SSE4_2__
  220. uint64_t be = absl::big_endian::FromHost64(val);
  221. const auto kNibbleMask = _mm_set1_epi8(0xf);
  222. const auto kHexDigits = _mm_setr_epi8('0', '1', '2', '3', '4', '5', '6', '7',
  223. '8', '9', 'a', 'b', 'c', 'd', 'e', 'f');
  224. auto v = _mm_loadl_epi64(reinterpret_cast<__m128i*>(&be)); // load lo dword
  225. auto v4 = _mm_srli_epi64(v, 4); // shift 4 right
  226. auto il = _mm_unpacklo_epi8(v4, v); // interleave bytes
  227. auto m = _mm_and_si128(il, kNibbleMask); // mask out nibbles
  228. auto hexchars = _mm_shuffle_epi8(kHexDigits, m); // hex chars
  229. _mm_storeu_si128(reinterpret_cast<__m128i*>(out), hexchars);
  230. #else
  231. for (int i = 0; i < 8; ++i) {
  232. auto byte = (val >> (56 - 8 * i)) & 0xFF;
  233. auto* hex = &absl::numbers_internal::kHexTable[byte * 2];
  234. std::memcpy(out + 2 * i, hex, 2);
  235. }
  236. #endif
  237. // | 0x1 so that even 0 has 1 digit.
  238. return 16 - countl_zero(val | 0x1) / 4;
  239. }
  240. } // namespace numbers_internal
  241. template <typename int_type>
  242. ABSL_MUST_USE_RESULT bool SimpleAtoi(absl::string_view str, int_type* out) {
  243. return numbers_internal::safe_strtoi_base(str, out, 10);
  244. }
  245. ABSL_MUST_USE_RESULT inline bool SimpleAtoi(absl::string_view str,
  246. absl::int128* out) {
  247. return numbers_internal::safe_strto128_base(str, out, 10);
  248. }
  249. ABSL_MUST_USE_RESULT inline bool SimpleAtoi(absl::string_view str,
  250. absl::uint128* out) {
  251. return numbers_internal::safe_strtou128_base(str, out, 10);
  252. }
  253. template <typename int_type>
  254. ABSL_MUST_USE_RESULT bool SimpleHexAtoi(absl::string_view str, int_type* out) {
  255. return numbers_internal::safe_strtoi_base(str, out, 16);
  256. }
  257. ABSL_MUST_USE_RESULT inline bool SimpleHexAtoi(absl::string_view str,
  258. absl::int128* out) {
  259. return numbers_internal::safe_strto128_base(str, out, 16);
  260. }
  261. ABSL_MUST_USE_RESULT inline bool SimpleHexAtoi(absl::string_view str,
  262. absl::uint128* out) {
  263. return numbers_internal::safe_strtou128_base(str, out, 16);
  264. }
  265. ABSL_NAMESPACE_END
  266. } // namespace absl
  267. #endif // ABSL_STRINGS_NUMBERS_H_