number.h 1.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354
  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 <stdexcept>
  14. #include <string_view>
  15. #include <system_error>
  16. namespace jvalidate::detail {
  17. /**
  18. * @brief Determine if a floating point number is actually an integer (in the
  19. * mathematical sense).
  20. */
  21. inline bool is_json_integer(double number) { return std::floor(number) == number; }
  22. /**
  23. * @brief Determine if a floating point number is actually an integer, and
  24. * actually fits in the 64-bit integer type that we use for JSON Integer.
  25. */
  26. inline bool fits_in_integer(double number) {
  27. static constexpr double g_int_max = std::numeric_limits<int64_t>::max();
  28. static constexpr double g_int_min = std::numeric_limits<int64_t>::min();
  29. return is_json_integer(number) && number <= g_int_max && number >= g_int_min;
  30. }
  31. /**
  32. * @brief Determine if an unsigned integer fits into a signed integer
  33. */
  34. inline bool fits_in_integer(uint64_t number) { return (number & 0x8000'0000'0000'0000) == 0; }
  35. template <std::integral I> I from_str(std::string_view str, int base = 10) {
  36. I rval;
  37. auto [end, ec] = std::from_chars(str.begin(), str.end(), rval, base);
  38. if (ec != std::errc{}) {
  39. throw std::runtime_error(std::make_error_code(ec).message());
  40. }
  41. if (end != str.end()) {
  42. throw std::runtime_error("NaN: " + std::string(str));
  43. }
  44. return rval;
  45. }
  46. }