number.h 1.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657
  1. /**
  2. * Utility functions for managing numeric types - such as converting between
  3. * floating-point and integer types.
  4. *
  5. * None of these are particularly complex functions, but storing them in a
  6. * single header with descriptive names helps the reader quickly recognize what
  7. * is being done.
  8. */
  9. #pragma once
  10. #include <charconv>
  11. #include <cmath>
  12. #include <limits>
  13. #include <string_view>
  14. #include <system_error>
  15. #include <jvalidate/compat/expected.h>
  16. #include <jvalidate/detail/out.h>
  17. namespace jvalidate::detail {
  18. /**
  19. * @brief Determine if a floating point number is actually an integer (in the
  20. * mathematical sense).
  21. */
  22. inline bool is_json_integer(double number) { return std::floor(number) == number; }
  23. /**
  24. * @brief Determine if a floating point number is actually an integer, and
  25. * actually fits in the 64-bit integer type that we use for JSON Integer.
  26. */
  27. inline bool fits_in_integer(double number) {
  28. static constexpr double g_int_max = std::numeric_limits<int64_t>::max();
  29. static constexpr double g_int_min = std::numeric_limits<int64_t>::min();
  30. return is_json_integer(number) && number <= g_int_max && number >= g_int_min;
  31. }
  32. /**
  33. * @brief Determine if an unsigned integer fits into a signed integer
  34. */
  35. inline bool fits_in_integer(uint64_t number) { return (number & 0x8000'0000'0000'0000) == 0; }
  36. struct parse_integer_args {
  37. int base = 10;
  38. out<size_t> read = discard_out;
  39. };
  40. template <std::integral T>
  41. static expected<T, std::errc> parse_integer(std::string_view in, parse_integer_args args = {}) {
  42. T rval = 0;
  43. auto [ptr, ec] = std::from_chars(in.begin(), in.end(), rval, args.base);
  44. args.read = ptr - in.begin();
  45. if (ec != std::errc{}) {
  46. return unexpected(ec);
  47. }
  48. return rval;
  49. }
  50. }