From 8d9afa5a4abdbaa4f88df5bc4ad19225e44468a9 Mon Sep 17 00:00:00 2001 From: A Thousand Ships <96648715+AThousandShips@users.noreply.github.com> Date: Mon, 18 Mar 2024 17:21:40 +0100 Subject: [PATCH] [Core] Add `Dictionary.set` for read-only enforcing assignments Matches the one on `Array`, otherwise functions like the `[]` operator --- core/variant/dictionary.cpp | 7 +++++++ core/variant/dictionary.h | 1 + tests/core/variant/test_dictionary.h | 4 ++++ 3 files changed, 12 insertions(+) diff --git a/core/variant/dictionary.cpp b/core/variant/dictionary.cpp index 0513051c6989..61e739a43098 100644 --- a/core/variant/dictionary.cpp +++ b/core/variant/dictionary.cpp @@ -152,6 +152,13 @@ Variant *Dictionary::getptr(const Variant &p_key) { } } +void Dictionary::set(const Variant &p_key, const Variant &p_value) { + ERR_FAIL_COND_MSG(_p->read_only, "Dictionary is in read-only state."); + Variant key = p_key; + ERR_FAIL_COND(!_p->typed_key.validate(key, "set")); + operator[](key) = p_value; +} + Variant Dictionary::get_valid(const Variant &p_key) const { Variant key = p_key; ERR_FAIL_COND_V(!_p->typed_key.validate(key, "get_valid"), Variant()); diff --git a/core/variant/dictionary.h b/core/variant/dictionary.h index bbfb5b30837d..6cfabdcda822 100644 --- a/core/variant/dictionary.h +++ b/core/variant/dictionary.h @@ -56,6 +56,7 @@ class Dictionary { const Variant *getptr(const Variant &p_key) const; Variant *getptr(const Variant &p_key); + void set(const Variant &p_key, const Variant &p_value); Variant get_valid(const Variant &p_key) const; Variant get(const Variant &p_key, const Variant &p_default) const; Variant get_or_add(const Variant &p_key, const Variant &p_default); diff --git a/tests/core/variant/test_dictionary.h b/tests/core/variant/test_dictionary.h index a8f5e2ff0500..350fe04079f8 100644 --- a/tests/core/variant/test_dictionary.h +++ b/tests/core/variant/test_dictionary.h @@ -97,6 +97,10 @@ TEST_CASE("[Dictionary] Assignment using bracket notation ([])") { ERR_PRINT_OFF; CHECK(int(map.get_or_add("This key does not exist", String()).get_type()) == Variant::NIL); CHECK(map.size() == length); + + map.set("This key does not exist", String()); + CHECK_FALSE(map.has("This key does not exist")); + CHECK(map.size() == length); ERR_PRINT_ON; }