number.h 1.2 KB

1234567891011121314151617181920212223242526272829303132333435
  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 <cmath>
  11. #include <limits>
  12. namespace jvalidate::detail {
  13. /**
  14. * @brief Determine if a floating point number is actually an integer (in the
  15. * mathematical sense).
  16. */
  17. inline bool is_json_integer(double number) { return std::floor(number) == number; }
  18. /**
  19. * @brief Determine if a floating point number is actually an integer, and
  20. * actually fits in the 64-bit integer type that we use for JSON Integer.
  21. */
  22. inline bool fits_in_integer(double number) {
  23. static constexpr double g_int_max = std::numeric_limits<int64_t>::max();
  24. static constexpr double g_int_min = std::numeric_limits<int64_t>::min();
  25. return is_json_integer(number) && number <= g_int_max && number >= g_int_min;
  26. }
  27. /**
  28. * @brief Determine if an unsigned integer fits into a signed integer
  29. */
  30. inline bool fits_in_integer(uint64_t number) { return (number & 0x8000'0000'0000'0000) == 0; }
  31. }