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
23 #ifndef ABSL_STRINGS_NUMBERS_H_
24 #define ABSL_STRINGS_NUMBERS_H_
25
26 #ifdef __SSSE3__
27 #include <tmmintrin.h>
28 #endif
29
30 #ifdef _MSC_VER
31 #include <intrin.h>
32 #endif
33
34 #include <cstddef>
35 #include <cstdlib>
36 #include <cstring>
37 #include <ctime>
38 #include <limits>
39 #include <string>
40 #include <type_traits>
41
42 #include "third_party/abseil-cpp/absl/base/config.h"
43 #include "third_party/abseil-cpp/absl/base/internal/endian.h"
44 #include "third_party/abseil-cpp/absl/base/macros.h"
45 #include "third_party/abseil-cpp/absl/base/nullability.h"
46 #include "third_party/abseil-cpp/absl/base/port.h"
47 #include "third_party/abseil-cpp/absl/numeric/bits.h"
48 #include "third_party/abseil-cpp/absl/numeric/int128.h"
49 #include "third_party/abseil-cpp/absl/strings/ascii.h" // absl:google3-only(Only used by SimpleItoaWithCommas, moving back to //strings)
50 #include "third_party/abseil-cpp/absl/strings/string_view.h"
51
52 namespace absl {
53 ABSL_NAMESPACE_BEGIN
54
55 // SimpleAtoi()
56 //
57 // Converts the given string (optionally followed or preceded by ASCII
58 // whitespace) into an integer value, returning `true` if successful. The string
59 // must reflect a base-10 integer whose value falls within the range of the
60 // integer type (optionally preceded by a `+` or `-`). If any errors are
61 // encountered, this function returns `false`, leaving `out` in an unspecified
62 // state.
63 template <typename int_type>
64 ABSL_MUST_USE_RESULT bool SimpleAtoi(absl::string_view str,
65 absl::Nonnull<int_type*> out);
66
67 // SimpleAtof()
68 //
69 // Converts the given string (optionally followed or preceded by ASCII
70 // whitespace) into a float, which may be rounded on overflow or underflow,
71 // returning `true` if successful.
72 // See https://en.cppreference.com/w/c/string/byte/strtof for details about the
73 // allowed formats for `str`, except SimpleAtof() is locale-independent and will
74 // always use the "C" locale. If any errors are encountered, this function
75 // returns `false`, leaving `out` in an unspecified state.
76 ABSL_MUST_USE_RESULT bool SimpleAtof(absl::string_view str,
77 absl::Nonnull<float*> out);
78
79 // SimpleAtod()
80 //
81 // Converts the given string (optionally followed or preceded by ASCII
82 // whitespace) into a double, which may be rounded on overflow or underflow,
83 // returning `true` if successful.
84 // See https://en.cppreference.com/w/c/string/byte/strtof for details about the
85 // allowed formats for `str`, except SimpleAtod is locale-independent and will
86 // always use the "C" locale. If any errors are encountered, this function
87 // returns `false`, leaving `out` in an unspecified state.
88 ABSL_MUST_USE_RESULT bool SimpleAtod(absl::string_view str,
89 absl::Nonnull<double*> out);
90
91 // SimpleAtob()
92 //
93 // Converts the given string into a boolean, returning `true` if successful.
94 // The following case-insensitive strings are interpreted as boolean `true`:
95 // "true", "t", "yes", "y", "1". The following case-insensitive strings
96 // are interpreted as boolean `false`: "false", "f", "no", "n", "0". If any
97 // errors are encountered, this function returns `false`, leaving `out` in an
98 // unspecified state.
99 ABSL_MUST_USE_RESULT bool SimpleAtob(absl::string_view str,
100 absl::Nonnull<bool*> out);
101
102 // SimpleHexAtoi()
103 //
104 // Converts a hexadecimal string (optionally followed or preceded by ASCII
105 // whitespace) to an integer, returning `true` if successful. Only valid base-16
106 // hexadecimal integers whose value falls within the range of the integer type
107 // (optionally preceded by a `+` or `-`) can be converted. A valid hexadecimal
108 // value may include both upper and lowercase character symbols, and may
109 // optionally include a leading "0x" (or "0X") number prefix, which is ignored
110 // by this function. If any errors are encountered, this function returns
111 // `false`, leaving `out` in an unspecified state.
112 template <typename int_type>
113 ABSL_MUST_USE_RESULT bool SimpleHexAtoi(absl::string_view str,
114 absl::Nonnull<int_type*> out);
115
116 // Overloads of SimpleHexAtoi() for 128 bit integers.
117 ABSL_MUST_USE_RESULT inline bool SimpleHexAtoi(
118 absl::string_view str, absl::Nonnull<absl::int128*> out);
119 ABSL_MUST_USE_RESULT inline bool SimpleHexAtoi(
120 absl::string_view str, absl::Nonnull<absl::uint128*> out);
121
122 ABSL_NAMESPACE_END
123 } // namespace absl
124
125 // End of public API. Implementation details follow.
126
127 namespace absl {
128 ABSL_NAMESPACE_BEGIN
129 namespace numbers_internal {
130
131 // Digit conversion.
132 ABSL_DLL extern const char kHexChar[17]; // 0123456789abcdef
133 ABSL_DLL extern const char
134 kHexTable[513]; // 000102030405060708090a0b0c0d0e0f1011...
135
136 // Writes a two-character representation of 'i' to 'buf'. 'i' must be in the
137 // range 0 <= i < 100, and buf must have space for two characters. Example:
138 // char buf[2];
139 // PutTwoDigits(42, buf);
140 // // buf[0] == '4'
141 // // buf[1] == '2'
142 void PutTwoDigits(uint32_t i, absl::Nonnull<char*> buf);
143
144 // safe_strto?() functions for implementing SimpleAtoi()
145
146 // absl:google3-begin(Internal comment)
147 // google3 callers should prefer `absl::SimpleAtoi()` for parsing base 10,
148 // `absl::SimpleHexAtoi()` for parsing base 16, and the family of
149 // `strings::safe_strto.*_base()` functions from google3/strings/numbers.h for
150 // parsing arbitrary bases.
151 // absl:google3-end
152 bool safe_strto32_base(absl::string_view text, absl::Nonnull<int32_t*> value,
153 int base);
154 bool safe_strto64_base(absl::string_view text, absl::Nonnull<int64_t*> value,
155 int base);
156 bool safe_strto128_base(absl::string_view text,
157 absl::Nonnull<absl::int128*> value, int base);
158 bool safe_strtou32_base(absl::string_view text, absl::Nonnull<uint32_t*> value,
159 int base);
160 bool safe_strtou64_base(absl::string_view text, absl::Nonnull<uint64_t*> value,
161 int base);
162 bool safe_strtou128_base(absl::string_view text,
163 absl::Nonnull<absl::uint128*> value, int base);
164
165 static const int kFastToBufferSize = 32;
166 static const int kSixDigitsToBufferSize = 16;
167
168 // absl:google3-begin(Legacy API)
169 absl::Nonnull<char*> RoundTripDoubleToBuffer(double d,
170 absl::Nonnull<char*> buffer);
171 absl::Nonnull<char*> RoundTripFloatToBuffer(float f,
172 absl::Nonnull<char*> buffer);
173 // absl:google3-end
174
175 // Helper function for fast formatting of floating-point values.
176 // The result is the same as printf's "%g", a.k.a. "%.6g"; that is, six
177 // significant digits are returned, trailing zeros are removed, and numbers
178 // outside the range 0.0001-999999 are output using scientific notation
179 // (1.23456e+06). This routine is heavily optimized.
180 // Required buffer size is `kSixDigitsToBufferSize`.
181 size_t SixDigitsToBuffer(double d, absl::Nonnull<char*> buffer);
182
183 // WARNING: These functions may write more characters than necessary, because
184 // they are intended for speed. All functions take an output buffer
185 // as an argument and return a pointer to the last byte they wrote, which is the
186 // terminating '\0'. At most `kFastToBufferSize` bytes are written.
187 absl::Nonnull<char*> FastIntToBuffer(int32_t i, absl::Nonnull<char*> buffer)
188 ABSL_INTERNAL_NEED_MIN_SIZE(buffer, kFastToBufferSize);
189 absl::Nonnull<char*> FastIntToBuffer(uint32_t n, absl::Nonnull<char*> out_str)
190 ABSL_INTERNAL_NEED_MIN_SIZE(out_str, kFastToBufferSize);
191 absl::Nonnull<char*> FastIntToBuffer(int64_t i, absl::Nonnull<char*> buffer)
192 ABSL_INTERNAL_NEED_MIN_SIZE(buffer, kFastToBufferSize);
193 absl::Nonnull<char*> FastIntToBuffer(uint64_t i, absl::Nonnull<char*> buffer)
194 ABSL_INTERNAL_NEED_MIN_SIZE(buffer, kFastToBufferSize);
195
196 // For enums and integer types that are not an exact match for the types above,
197 // use templates to call the appropriate one of the four overloads above.
198 template <typename int_type>
FastIntToBuffer(int_type i,absl::Nonnull<char * > buffer)199 absl::Nonnull<char*> FastIntToBuffer(int_type i, absl::Nonnull<char*> buffer)
200 ABSL_INTERNAL_NEED_MIN_SIZE(buffer, kFastToBufferSize) {
201 static_assert(sizeof(i) <= 64 / 8,
202 "FastIntToBuffer works only with 64-bit-or-less integers.");
203 // TODO(jorg): This signed-ness check is used because it works correctly
204 // with enums, and it also serves to check that int_type is not a pointer.
205 // If one day something like std::is_signed<enum E> works, switch to it.
206 // These conditions are constexpr bools to suppress MSVC warning C4127.
207 constexpr bool kIsSigned = static_cast<int_type>(1) - 2 < 0;
208 constexpr bool kUse64Bit = sizeof(i) > 32 / 8;
209 if (kIsSigned) {
210 if (kUse64Bit) {
211 return FastIntToBuffer(static_cast<int64_t>(i), buffer);
212 } else {
213 return FastIntToBuffer(static_cast<int32_t>(i), buffer);
214 }
215 } else {
216 if (kUse64Bit) {
217 return FastIntToBuffer(static_cast<uint64_t>(i), buffer);
218 } else {
219 return FastIntToBuffer(static_cast<uint32_t>(i), buffer);
220 }
221 }
222 }
223
224 // Implementation of SimpleAtoi, generalized to support arbitrary base (used
225 // with base different from 10 elsewhere in Abseil implementation).
226 template <typename int_type>
safe_strtoi_base(absl::string_view s,absl::Nonnull<int_type * > out,int base)227 ABSL_MUST_USE_RESULT bool safe_strtoi_base(absl::string_view s,
228 absl::Nonnull<int_type*> out,
229 int base) {
230 static_assert(sizeof(*out) == 4 || sizeof(*out) == 8,
231 "SimpleAtoi works only with 32-bit or 64-bit integers.");
232 static_assert(!std::is_floating_point<int_type>::value,
233 "Use SimpleAtof or SimpleAtod instead.");
234 bool parsed;
235 // TODO(jorg): This signed-ness check is used because it works correctly
236 // with enums, and it also serves to check that int_type is not a pointer.
237 // If one day something like std::is_signed<enum E> works, switch to it.
238 // These conditions are constexpr bools to suppress MSVC warning C4127.
239 constexpr bool kIsSigned = static_cast<int_type>(1) - 2 < 0;
240 constexpr bool kUse64Bit = sizeof(*out) == 64 / 8;
241 if (kIsSigned) {
242 if (kUse64Bit) {
243 int64_t val;
244 parsed = numbers_internal::safe_strto64_base(s, &val, base);
245 *out = static_cast<int_type>(val);
246 } else {
247 int32_t val;
248 parsed = numbers_internal::safe_strto32_base(s, &val, base);
249 *out = static_cast<int_type>(val);
250 }
251 } else {
252 if (kUse64Bit) {
253 uint64_t val;
254 parsed = numbers_internal::safe_strtou64_base(s, &val, base);
255 *out = static_cast<int_type>(val);
256 } else {
257 uint32_t val;
258 parsed = numbers_internal::safe_strtou32_base(s, &val, base);
259 *out = static_cast<int_type>(val);
260 }
261 }
262 return parsed;
263 }
264
265 // FastHexToBufferZeroPad16()
266 //
267 // Outputs `val` into `out` as if by `snprintf(out, 17, "%016x", val)` but
268 // without the terminating null character. Thus `out` must be of length >= 16.
269 // Returns the number of non-pad digits of the output (it can never be zero
270 // since 0 has one digit).
FastHexToBufferZeroPad16(uint64_t val,absl::Nonnull<char * > out)271 inline size_t FastHexToBufferZeroPad16(uint64_t val, absl::Nonnull<char*> out) {
272 #ifdef ABSL_INTERNAL_HAVE_SSSE3
273 uint64_t be = absl::big_endian::FromHost64(val);
274 const auto kNibbleMask = _mm_set1_epi8(0xf);
275 const auto kHexDigits = _mm_setr_epi8('0', '1', '2', '3', '4', '5', '6', '7',
276 '8', '9', 'a', 'b', 'c', 'd', 'e', 'f');
277 auto v = _mm_loadl_epi64(reinterpret_cast<__m128i*>(&be)); // load lo dword
278 auto v4 = _mm_srli_epi64(v, 4); // shift 4 right
279 auto il = _mm_unpacklo_epi8(v4, v); // interleave bytes
280 auto m = _mm_and_si128(il, kNibbleMask); // mask out nibbles
281 auto hexchars = _mm_shuffle_epi8(kHexDigits, m); // hex chars
282 _mm_storeu_si128(reinterpret_cast<__m128i*>(out), hexchars);
283 #else
284 for (int i = 0; i < 8; ++i) {
285 auto byte = (val >> (56 - 8 * i)) & 0xFF;
286 auto* hex = &absl::numbers_internal::kHexTable[byte * 2];
287 std::memcpy(out + 2 * i, hex, 2);
288 }
289 #endif
290 // | 0x1 so that even 0 has 1 digit.
291 return 16 - static_cast<size_t>(countl_zero(val | 0x1) / 4);
292 }
293
294 } // namespace numbers_internal
295
296 template <typename int_type>
SimpleAtoi(absl::string_view str,absl::Nonnull<int_type * > out)297 ABSL_MUST_USE_RESULT bool SimpleAtoi(absl::string_view str,
298 absl::Nonnull<int_type*> out) {
299 return numbers_internal::safe_strtoi_base(str, out, 10);
300 }
301
SimpleAtoi(absl::string_view str,absl::Nonnull<absl::int128 * > out)302 ABSL_MUST_USE_RESULT inline bool SimpleAtoi(absl::string_view str,
303 absl::Nonnull<absl::int128*> out) {
304 return numbers_internal::safe_strto128_base(str, out, 10);
305 }
306
SimpleAtoi(absl::string_view str,absl::Nonnull<absl::uint128 * > out)307 ABSL_MUST_USE_RESULT inline bool SimpleAtoi(absl::string_view str,
308 absl::Nonnull<absl::uint128*> out) {
309 return numbers_internal::safe_strtou128_base(str, out, 10);
310 }
311
312 template <typename int_type>
SimpleHexAtoi(absl::string_view str,absl::Nonnull<int_type * > out)313 ABSL_MUST_USE_RESULT bool SimpleHexAtoi(absl::string_view str,
314 absl::Nonnull<int_type*> out) {
315 return numbers_internal::safe_strtoi_base(str, out, 16);
316 }
317
SimpleHexAtoi(absl::string_view str,absl::Nonnull<absl::int128 * > out)318 ABSL_MUST_USE_RESULT inline bool SimpleHexAtoi(
319 absl::string_view str, absl::Nonnull<absl::int128*> out) {
320 return numbers_internal::safe_strto128_base(str, out, 16);
321 }
322
SimpleHexAtoi(absl::string_view str,absl::Nonnull<absl::uint128 * > out)323 ABSL_MUST_USE_RESULT inline bool SimpleHexAtoi(
324 absl::string_view str, absl::Nonnull<absl::uint128*> out) {
325 return numbers_internal::safe_strtou128_base(str, out, 16);
326 }
327
328 ABSL_NAMESPACE_END
329 } // namespace absl
330
331 #endif // THIRD_PARTY_ABSL_STRINGS_NUMBERS_H_