32 lines
917 B
C++
32 lines
917 B
C++
#pragma once
|
|
|
|
#include <Void/Data/Json.hpp>
|
|
|
|
#include <cmath>
|
|
#include <cstdint>
|
|
#include <optional>
|
|
#include <string_view>
|
|
|
|
namespace Echoion::Core::Detail
|
|
{
|
|
[[nodiscard]] inline std::optional<std::uint64_t>
|
|
uintField(const Void::Json::Value& object, std::string_view key)
|
|
{
|
|
const auto* value = object.find(key);
|
|
if (!value || !value->is_number()) {
|
|
return std::nullopt;
|
|
}
|
|
|
|
const auto number = value->as_number();
|
|
// A double equal to 2^64 is what uint64_t::max() rounds to, so use
|
|
// an exclusive 2^64 bound before converting. Floating-to-integer
|
|
// conversion outside the destination range is undefined behavior.
|
|
constexpr double kUint64Limit = 18446744073709551616.0;
|
|
if (!std::isfinite(number) || number < 0.0 ||
|
|
std::trunc(number) != number || number >= kUint64Limit) {
|
|
return std::nullopt;
|
|
}
|
|
return static_cast<std::uint64_t>(number);
|
|
}
|
|
} // namespace Echoion::Core::Detail
|