From 208aeac98cdd1e53b0d9d95bd8779008bdf039a2 Mon Sep 17 00:00:00 2001 From: Xie Han <63350856@qq.com> Date: Fri, 22 Dec 2023 19:21:02 +0800 Subject: [PATCH] feat: use JSON type: -1 as placeholder. --- Json.cc | 12 ++++++------ Json.h | 12 ++++++------ test/json_obj_test.cc | 4 ++-- 3 files changed, 14 insertions(+), 14 deletions(-) diff --git a/Json.cc b/Json.cc index 2505a7a..d306d32 100644 --- a/Json.cc +++ b/Json.cc @@ -52,7 +52,7 @@ json_value_t* json_value_copy(const json_value_t* val) // ------------------------ Constructor ------------------------- Json::Json() - : node_(json_value_create(JSON_VALUE_NULL)), parent_(nullptr), + : node_(json_value_create(-1)), parent_(nullptr), allocated_(true) { } @@ -231,7 +231,7 @@ std::string Json::dump(int spaces) const Json Json::operator[](const char* key) { - if (is_null() && is_root()) + if (is_placeholder() && is_root()) { // todo : need is_root here? to_object(); @@ -369,7 +369,7 @@ bool Json::can_obj_push_back() { return true; } - if (is_root() && is_null()) + if (is_root() && is_placeholder()) { to_object(); } @@ -585,7 +585,7 @@ void Json::normal_push_back(const std::string& key, const Json& val) bool Json::can_arr_push_back() { - if (is_root() && is_null()) + if (is_root() && is_placeholder()) { to_array(); } @@ -786,7 +786,7 @@ void Json::clear() bool Json::to_object() { - if (!allocated_ || !is_null()) + if (!allocated_ || !is_placeholder()) { // watcher and non-null type can't change type return false; @@ -799,7 +799,7 @@ bool Json::to_object() bool Json::to_array() { - if (!allocated_ || !is_null()) + if (!allocated_ || !is_placeholder()) { // watcher and non-null type can't change type return false; diff --git a/Json.h b/Json.h index 14a06ae..060261b 100644 --- a/Json.h +++ b/Json.h @@ -175,6 +175,12 @@ class Json return type() == JSON_VALUE_STRING; } + // can convert to any type, just like a placeholder + bool is_placeholder() const + { + return json_value_type(node_) == -1; + } + bool is_valid() const { return node_ != nullptr; @@ -684,12 +690,6 @@ class Json bool can_arr_push_back(); - // can convert to any type, just like a placeholder - bool is_placeholder() const - { - return is_null() && parent_ != nullptr; - } - void destroy_node(json_value_t** node) { if (allocated_) diff --git a/test/json_obj_test.cc b/test/json_obj_test.cc index a197a36..84c0c8f 100644 --- a/test/json_obj_test.cc +++ b/test/json_obj_test.cc @@ -19,9 +19,9 @@ TEST(ObjTest, empty_obj) TEST(ObjTest, one_level) { Json data; - EXPECT_TRUE(data.is_null()); + EXPECT_TRUE(data.is_placeholder()); Json data_tmp = data["test"]; - EXPECT_TRUE(data_tmp.is_null()); + EXPECT_TRUE(data_tmp.is_placeholder()); data["test"] = 1.0; EXPECT_EQ(data.type(), JSON_VALUE_OBJECT); EXPECT_TRUE(data.is_object());