allow setting the key again on the same node default tip

Sat, 20 Sep 2025 12:30:07 +0200

author
Mike Becker <universe@uap-core.de>
date
Sat, 20 Sep 2025 12:30:07 +0200
changeset 1383
3db28cb1e5ec
parent 1382
f61119884dcd

allow setting the key again on the same node

relates to #461

src/kv_list.c file | annotate | diff | comparison | revisions
tests/test_kv_list.c file | annotate | diff | comparison | revisions
--- a/src/kv_list.c	Sat Sep 20 12:27:36 2025 +0200
+++ b/src/kv_list.c	Sat Sep 20 12:30:07 2025 +0200
@@ -471,8 +471,12 @@
     }
 
     // check if the key is already assigned
-    if (kv_list->map_methods->get(&kv_list->map->map_base.base, key) != NULL) {
-        // key is already assigned, we disallow re-assignment
+    void *existing = kv_list->map_methods->get(&kv_list->map->map_base.base, key);
+    if (existing == node_data) {
+        return 0; // nothing to do
+    }
+    if (existing != NULL) {
+        // the key is already assigned to another node, we disallow re-assignment
         return 1;
     }
 
--- a/tests/test_kv_list.c	Sat Sep 20 12:27:36 2025 +0200
+++ b/tests/test_kv_list.c	Sat Sep 20 12:30:07 2025 +0200
@@ -457,6 +457,33 @@
     cxListFree(list);
 }
 
+CX_TEST(test_kv_list_set_key_again) {
+    CxList *list = cxKvListCreateSimple(sizeof(int));
+    int x;
+    CX_TEST_DO {
+        x = 47;
+        cxListAdd(list, &x);
+        x = 11;
+        cxListAdd(list, &x);
+        CX_TEST_ASSERT(0 == cxKvListSetKey(list, 1, "xyz"));
+        // calling it twice is also okay!
+        CX_TEST_ASSERT(0 == cxKvListSetKey(list, 1, "xyz"));
+
+        CxMap *map = cxKvListAsMap(list);
+
+        CX_TEST_ASSERT(cxMapSize(map) == 1);
+
+        int *y = cxMapGet(map, "xyz");
+        CX_TEST_ASSERT(y != NULL);
+        CX_TEST_ASSERT(*y == 11);
+
+        CX_TEST_ASSERT(0 == cxMapRemove(map, "xyz"));
+        CX_TEST_ASSERT(cxMapGet(map, "xyz") == NULL);
+        CX_TEST_ASSERT(cxListSize(list) == 1);
+    }
+    cxListFree(list);
+}
+
 CX_TEST(test_kv_list_remove_key) {
     CxList *list = cxKvListCreateSimple(sizeof(int));
     int x;
@@ -799,6 +826,7 @@
     cx_test_register(suite, test_kv_list_map_remove_and_get);
     cx_test_register(suite, test_kv_list_set_key);
     cx_test_register(suite, test_kv_list_set_key_already_exists);
+    cx_test_register(suite, test_kv_list_set_key_again);
     cx_test_register(suite, test_kv_list_remove_key);
     cx_test_register(suite, test_kv_list_insert_with_key);
     cx_test_register(suite, test_kv_list_insert_ptr_with_key);

mercurial