diff options
author | Sam Atkins <atkinssj@serenityos.org> | 2022-12-21 16:07:14 +0000 |
---|---|---|
committer | Tim Flynn <trflynn89@pm.me> | 2023-01-17 19:52:52 -0500 |
commit | efe4329f9fe448eb17784d7a9b9e6e519ec4fa57 (patch) | |
tree | 25fb369c28dc3749c8cb462f0dbb63667a2aeeca /AK | |
parent | 6d939472123951b1a5867ae2f32a11338a0ac88e (diff) | |
download | serenity-efe4329f9fe448eb17784d7a9b9e6e519ec4fa57.zip |
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.
Diffstat (limited to 'AK')
-rw-r--r-- | AK/JsonValue.h | 36 |
1 files changed, 36 insertions, 0 deletions
diff --git a/AK/JsonValue.h b/AK/JsonValue.h index 905483ee23..f01e38d595 100644 --- a/AK/JsonValue.h +++ b/AK/JsonValue.h @@ -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: |