1
Fork 0
mirror of https://github.com/RGBCube/serenity synced 2025-07-27 06:07:34 +00:00

AK: Add JsonValue::{is,as}_integer() methods

The existing `is_i32()` and friends only check if `i32` is their
internal type, but a value such as `0` could be literally any integer
type internally. `is_integer<T>()` instead determines whether the
contained value is an integer and can fit inside T.
This commit is contained in:
Sam Atkins 2022-12-21 16:07:14 +00:00 committed by Tim Flynn
parent 6d93947212
commit efe4329f9f
2 changed files with 95 additions and 0 deletions

View file

@ -261,6 +261,42 @@ public:
return default_value;
}
template<Integral T>
bool is_integer() const
{
switch (m_type) {
case Type::Int32:
return is_within_range<T>(m_value.as_i32);
case Type::UnsignedInt32:
return is_within_range<T>(m_value.as_u32);
case Type::Int64:
return is_within_range<T>(m_value.as_i64);
case Type::UnsignedInt64:
return is_within_range<T>(m_value.as_u64);
default:
return false;
}
}
template<Integral T>
T as_integer() const
{
VERIFY(is_integer<T>());
switch (m_type) {
case Type::Int32:
return static_cast<T>(m_value.as_i32);
case Type::UnsignedInt32:
return static_cast<T>(m_value.as_u32);
case Type::Int64:
return static_cast<T>(m_value.as_i64);
case Type::UnsignedInt64:
return static_cast<T>(m_value.as_u64);
default:
VERIFY_NOT_REACHED();
}
}
bool equals(JsonValue const& other) const;
private: