From efe4329f9fe448eb17784d7a9b9e6e519ec4fa57 Mon Sep 17 00:00:00 2001 From: Sam Atkins Date: Wed, 21 Dec 2022 16:07:14 +0000 Subject: 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()` instead determines whether the contained value is an integer and can fit inside T. --- AK/JsonValue.h | 36 ++++++++++++++++++++++++++++++++++++ 1 file changed, 36 insertions(+) (limited to 'AK') 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 + bool is_integer() const + { + switch (m_type) { + case Type::Int32: + return is_within_range(m_value.as_i32); + case Type::UnsignedInt32: + return is_within_range(m_value.as_u32); + case Type::Int64: + return is_within_range(m_value.as_i64); + case Type::UnsignedInt64: + return is_within_range(m_value.as_u64); + default: + return false; + } + } + + template + T as_integer() const + { + VERIFY(is_integer()); + + switch (m_type) { + case Type::Int32: + return static_cast(m_value.as_i32); + case Type::UnsignedInt32: + return static_cast(m_value.as_u32); + case Type::Int64: + return static_cast(m_value.as_i64); + case Type::UnsignedInt64: + return static_cast(m_value.as_u64); + default: + VERIFY_NOT_REACHED(); + } + } + bool equals(JsonValue const& other) const; private: -- cgit v1.2.3