General Utility Library for C++17 26.10.0
to_number.h
Go to the documentation of this file.
1
26#ifndef GUL17_TO_NUMBER_H_
27#define GUL17_TO_NUMBER_H_
28
29#include <array>
30#include <cmath>
31#include <cstdint>
32#include <cstdlib>
33#include <exception>
34#include <functional>
35#include <limits>
36#include <optional>
37#include <string_view>
38#include <type_traits>
39
40#include "gul17/internal.h"
42
43namespace gul17 {
44
52namespace detail {
53
54constexpr inline bool is_digit(char c) noexcept
55{
56 return c >= '0' && c <= '9';
57}
58
59constexpr inline bool is_nan_specifier(char c) noexcept
60{
61 if (c >= '0' && c <= '9')
62 return true;
63 if (c >= 'a' && c <= 'z')
64 return true;
65 if (c >= 'A' && c <= 'Z')
66 return true;
67 if (c == '_')
68 return true;
69 return false;
70}
71
72template <typename NumberType, bool count_magnitude = false>
73constexpr inline std::optional<NumberType> to_unsigned_integer(std::string_view str,
74 NumberType* magnitude = nullptr) noexcept
75{
76#ifndef __GNUC__
77 constexpr NumberType max_tenth = std::numeric_limits<NumberType>::max() / 10;
78#endif
79
80 if (str.empty())
81 return std::nullopt;
82
84
85 for (char c : str)
86 {
87 if (!is_digit(c))
88 return std::nullopt;
89
90#ifdef __GNUC__
91 if (__builtin_mul_overflow(result, NumberType{ 10 }, &result)) // NOLINT(cppcoreguidelines-pro-type-vararg)
92 return std::nullopt;
93
94 if (__builtin_add_overflow(result, static_cast<NumberType>(c - '0'), &result)) // NOLINT(cppcoreguidelines-pro-type-vararg)
95 return std::nullopt;
96#else
97 if (result > max_tenth)
98 return std::nullopt;
99
100 result *= 10;
101
102 auto last = result;
103
104 result += c - '0';
105 if (result < last)
106 return std::nullopt;
107#endif
108 if /*constexpr*/ (count_magnitude)
109 *magnitude *= NumberType{ 10 };
110 }
111
112 return result;
113}
114
115/* Parse a signed exponent specifier.
116 * May start with a leading sign ('+' or '-'). The exponent value is limited to
117 * the range of int. The used range with a long double conversion is usually in
118 * the range -5000 to 5000, so this is not really a limitation.
119 */
120constexpr std::optional<int> parse_exponent(std::string_view str) noexcept
121{
122 bool negative = false;
123
124 switch (str.front())
125 {
126 case '+':
127 str.remove_prefix(1);
128 break;
129 case '-':
130 str.remove_prefix(1);
131 negative = true;
132 break;
133 default:
134 break;
135 }
136
138
139 if (!opt_exp)
140 return std::nullopt;
141
142 if (negative)
143 return -*opt_exp;
144 return *opt_exp;
145}
146
147// For some 'long double' types with a big mantissa uint64 is not large enough.
148// We resort to __uint128, which is a non standard extension in GCC and clang.
149// But only if we need to.
150// Note that on some compilers there are no std::numeric_limits<> for the extension
151// type, and then asserts later on will fail. But usually that compilers have small
152// long double types.
153template <typename NumberType>
155 typename std::conditional<
156 (std::numeric_limits<std::uint64_t>::digits10 >= std::numeric_limits<NumberType>::digits10),
157 std::uint64_t,
158 #ifdef __SIZEOF_INT128__ // GCC, clang, intel
160 #else
161 std::uint64_t
162 #endif
163 >::type;
164
181template <typename NumberType>
182constexpr inline std::optional<NumberType> to_normalized_float(std::string_view i1, std::string_view i2) noexcept
183{
184 static_assert(std::numeric_limits<FloatConversionIntType<NumberType>>::digits10
185 >= std::numeric_limits<NumberType>::digits10,
186 "FloatConversionIntType is too small for NumberType");
187
188 i1 = i1.substr(0, std::min(i1.length(),
189 size_t(std::numeric_limits<FloatConversionIntType<NumberType>>::digits10)));
190 i2 = i2.substr(0, std::min(i2.length(),
191 size_t(std::numeric_limits<FloatConversionIntType<NumberType>>::digits10) - i1.length()));
192
194
196
197 if (not i2.empty()) {
199 if (not f2.has_value())
200 return std::nullopt;
201 accu = *f2;
202 }
203 if (not i1.empty()) {
204 auto i2_magnitude = magnitude;
206 if (not f1.has_value())
207 return std::nullopt;
208 accu += (*f1 * i2_magnitude);
209 }
210
211 return static_cast<NumberType>(accu) / static_cast<NumberType>(magnitude / 10); // NOLINT(bugprone-integer-division): Precision loss is not possible with normalized accu
212}
213
214template <typename NumberType>
215struct ParseInfNanResult {
216 bool result_valid;
217 std::optional<NumberType> result;
218};
219
239template <typename NumberType>
240constexpr inline ParseInfNanResult<NumberType> parse_inf_nan(std::string_view str) noexcept
241{
242 auto const strlength = str.length();
243 if (strlength == 0)
244 return { true, {} };
245
246 if (gul17::starts_with_nocase(str, "inf")) {
247 if (strlength == 3 /* strlen("inf") */ )
248 return { true, std::make_optional(std::numeric_limits<NumberType>::infinity()) };
249 if (strlength == 8 /* strlen("infinity") */
250 and gul17::starts_with_nocase(str.substr(3), "inity"))
251 return { true, std::make_optional(std::numeric_limits<NumberType>::infinity()) };
252 return { true, {} };
253 }
254
255 if (gul17::starts_with_nocase(str, "nan")) {
256 if (strlength == 3 /* strlen("nan") */ )
257 return { true, std::make_optional(std::numeric_limits<NumberType>::quiet_NaN()) };
258 if (strlength < 5 /* strlen("nan()") */ or str[3] != '(' or str.back() != ')')
259 return { true, {} };
260 str.remove_prefix(4);
261 str.remove_suffix(1);
262 while (str.length()) {
263 if (not is_nan_specifier(str.front()))
264 return { true, {} };
265 str.remove_prefix(1);
266 }
267 // We do not use the NaN specifier
268 return { true, std::make_optional(std::numeric_limits<NumberType>::quiet_NaN()) };
269 }
270 return { false, {} };
271}
272
284GUL_EXPORT
285long double pow10(int exponent);
286
304template <typename NumberType>
305constexpr inline std::optional<NumberType> to_unsigned_float(std::string_view str) noexcept
306{
308 if (inf_nan.result_valid)
309 return inf_nan.result;
310
311 int exponent = 0;
312 auto e_pos = str.find_first_of("eE");
313 if (e_pos != std::string_view::npos)
314 {
315 if (e_pos + 1 == str.size())
316 return std::nullopt;
317
318 auto str_exponent = str.substr(e_pos + 1);
319
320 str = str.substr(0, e_pos);
321
322 auto opt_exp = detail::parse_exponent(str_exponent);
323
324 if (!opt_exp)
325 return std::nullopt;
326
327 exponent = *opt_exp;
328 }
329
330 std::string_view str_before_point{ str };
331 std::string_view str_after_point;
332
333 auto point_pos = str.find('.');
334 if (point_pos != std::string_view::npos)
335 {
336 str_before_point = str.substr(0, point_pos);
337 str_after_point = str.substr(point_pos + 1);
338 }
339
340 if (str_before_point.empty() && str_after_point.empty())
341 return std::nullopt;
342
343 // Get rid of leading zeros
344 while (!str_before_point.empty() and str_before_point[0] == '0')
345 str_before_point.remove_prefix(1);
346
347 // Normalize the number
348 if (str_before_point.empty()) {
349 auto const old_digits = str_after_point.length();
350 while (!str_after_point.empty() and str_after_point[0] == '0')
351 str_after_point.remove_prefix(1);
352
353 if (str_after_point.empty())
354 return { 0 };
355
356 str_before_point = str_after_point.substr(0, 1);
357 str_after_point.remove_prefix(1);
358 exponent -= static_cast<int>(old_digits - str_after_point.length());
359 } else {
360 exponent += static_cast<int>(str_before_point.length() - 1);
361 }
362
363 // Now the incoming number string is like this:
364 // "s.tr_before_point" "str_after_point" E exponent
365 // ^ ^
366 // | here is the decimal dot, virtually | corrected exponent
367
368 using long_double = long double;
369 using CalcType = std::conditional_t<
370 std::greater<>()(sizeof(NumberType), sizeof(double)),
371 long_double, double>;
372
374 if (not norm_val.has_value())
375 return std::nullopt;
376
377 return static_cast<NumberType>(detail::pow10(exponent) * *norm_val);
378}
379
397template <typename NumberType>
398inline std::optional<NumberType> strtold_wrapper(std::string_view str) noexcept
399{
400 if (str.empty())
401 return std::nullopt;
402
403 try
404 {
405 auto input = std::string{ str };
406 char* process_end;
407 auto value = static_cast<NumberType>(std::strtold(input.c_str(), &process_end));
408
409 if (input.data() + input.size() != process_end) // NOLINT(cppcoreguidelines-pro-bounds-pointer-arithmetic): Pointer arithmetic needed because strtold gives pointer back
410 return std::nullopt;
411 return value;
412 }
413 catch (const std::exception &)
414 {
415 return std::nullopt;
416 }
417}
418
419} // namespace detail
421
422
499// Overload for unsigned integer types.
500template <typename NumberType>
501constexpr inline std::enable_if_t<std::is_integral<NumberType>::value and
502 std::is_unsigned<NumberType>::value,
503 std::optional<NumberType>>
504to_number(std::string_view str) noexcept
505{
506 return detail::to_unsigned_integer<NumberType>(str);
507}
508
509// Overload for signed integer types.
510template <typename NumberType>
511constexpr inline std::enable_if_t<std::is_integral<NumberType>::value and
512 std::is_signed<NumberType>::value,
513 std::optional<NumberType>>
514to_number(std::string_view str) noexcept
515{
516 if (str.empty())
517 return std::nullopt;
518
519 if (str.front() == '-')
520 {
521 using UnsignedT = std::make_unsigned_t<NumberType>;
522 constexpr auto max_abs_negative_value =
523 static_cast<UnsignedT>(std::numeric_limits<NumberType>::max()) + 1;
524
525 str.remove_prefix(1);
526
527 auto result = detail::to_unsigned_integer<UnsignedT>(str);
528 if (!result)
529 return std::nullopt;
530
532 return std::numeric_limits<NumberType>::lowest();
533 else if (*result > max_abs_negative_value)
534 return std::nullopt;
535
536 return static_cast<NumberType>(-static_cast<NumberType>(*result));
537 }
538
539 return detail::to_unsigned_integer<NumberType>(str);
540}
541
542// Overload for floating-point types.
543template <typename NumberType>
544constexpr inline std::enable_if_t<std::is_floating_point<NumberType>::value,
545 std::optional<NumberType>>
546to_number(std::string_view str) noexcept
547{
548 if (str.empty())
549 return std::nullopt;
550
551 if (
554# pragma warning( disable: 4127 ) // conditional expression is constant
555#endif
558#ifdef _MSC_VER
559# pragma warning( pop )
560#endif
561 // Too big for our approach. Resort to non-constexpr functionality.
562 // This actually never happenes with the currently supported platforms / compilers.
563 // (Except long double on Darwin)
564 return detail::strtold_wrapper<NumberType>(str);
565 }
566
567 if (str.front() == '-')
568 {
569 str.remove_prefix(1);
570 auto result = detail::to_unsigned_float<NumberType>(str);
571 if (!result)
572 return std::nullopt;
573 return -*result;
574 }
575
576 return detail::to_unsigned_float<NumberType>(str);
577}
578
579// Overload for bool
580template<>
581constexpr inline std::optional<bool> to_number<bool>(std::string_view str) noexcept
582{
583 if (str.length() == 1) {
584 if (str[0] == '1')
585 return true;
586 if (str[0] == '0')
587 return false;
588 return std::nullopt;
589 }
590 if (equals_nocase(str, "true"))
591 return true;
592
593 if (equals_nocase(str, "false"))
594 return false;
595
596 return std::nullopt;
597}
598
600
601} // namespace gul17
602
603#endif
604
605// vi:ts=4:sw=4:et:sts=4
auto constexpr bit_set(unsigned bit) noexcept -> ReturnT
Set a bit in an integral type.
Definition bit_manip.h:124
constexpr bool equals_nocase(std::string_view str1, std::string_view str2) noexcept
Determine whether a string is equal to another one, making no distinction between upper and lower cas...
Definition substring_checks.h:169
constexpr bool starts_with_nocase(std::string_view str, std::string_view prefix) noexcept
Determine whether a string starts with another string.
Definition substring_checks.h:317
constexpr std::enable_if_t< std::is_integral< NumberType >::value and std::is_unsigned< NumberType >::value, std::optional< NumberType > > to_number(std::string_view str) noexcept
Convert an ASCII std::string_view into a number.
Definition to_number.h:504
Definition of macros used internally by GUL.
Namespace gul17 contains all functions and classes of the General Utility Library.
Definition doxygen.h:29
Definition of contains(), ends_with(), and starts_with().