Serenity Operating System

AK: Add equals method to JsonValue to semantically compare two values.

This patchsets adds the semantic check of two values. One first approach
was to compare the (generated) json strings of the two values. This works
out in the most cases, but not with numbers, where "1.0" and "1" in JSON
format are semantically the same. Therefore, this patch adds deep (recursive)
check of two JsonValues.

authored by

Emanuel Sprung and committed by
Andreas Kling
b995a499 c27e8a25

+42
+40
AK/JsonValue.cpp
··· 89 89 return *this; 90 90 } 91 91 92 + bool JsonValue::equals(const JsonValue& other) const 93 + { 94 + if (is_null() && other.is_null()) 95 + return true; 96 + 97 + if (is_bool() && other.is_bool() && as_bool() == other.as_bool()) 98 + return true; 99 + 100 + if (is_string() && other.is_string() && as_string() == other.as_string()) 101 + return true; 102 + 103 + #if !defined(KERNEL) && !defined(BOOTSTRAPPER) 104 + if (is_number() && other.is_number() && to_number<double>() == other.to_number<double>()) { 105 + return true; 106 + } 107 + #else 108 + if (is_number() && other.is_number() && to_number<i64>() == other.to_number<i64>()) { 109 + return true; 110 + } 111 + #endif 112 + 113 + if (is_array() && other.is_array() && as_array().size() == other.as_array().size()) { 114 + bool result = true; 115 + for (int i = 0; i < as_array().size(); ++i) { 116 + result &= as_array().at(i).equals(other.as_array().at(i)); 117 + } 118 + return result; 119 + } 120 + 121 + if (is_object() && other.is_object() && as_object().size() == other.as_object().size()) { 122 + bool result = true; 123 + as_object().for_each_member([&](auto& key, auto& value) { 124 + result &= value.equals(other.as_object().get(key)); 125 + }); 126 + return result; 127 + } 128 + 129 + return false; 130 + } 131 + 92 132 JsonValue::JsonValue(i32 value) 93 133 : m_type(Type::Int32) 94 134 {
+2
AK/JsonValue.h
··· 238 238 return default_value; 239 239 } 240 240 241 + bool equals(const JsonValue& other) const; 242 + 241 243 private: 242 244 void clear(); 243 245 void copy_from(const JsonValue&);