From fc31b44399a116d8ad3bbf50cb9aa812d9e9f12d Mon Sep 17 00:00:00 2001 From: Delyan Angelov Date: Sun, 1 Sep 2024 17:27:28 +0300 Subject: [PATCH] builtin: fix incomplete m.clear(), allowing the map to have a duplicated entry for its first key (fix #22143) (#22144) --- vlib/builtin/map.v | 3 +- vlib/builtin/map_issue_22143_clear_test.v | 37 +++++++++++++++++++++++ 2 files changed, 39 insertions(+), 1 deletion(-) create mode 100644 vlib/builtin/map_issue_22143_clear_test.v diff --git a/vlib/builtin/map.v b/vlib/builtin/map.v index 2ed6e4de81da42..9d50ffbaec602c 100644 --- a/vlib/builtin/map.v +++ b/vlib/builtin/map.v @@ -315,12 +315,13 @@ pub fn (mut m map) move() map { // Example: a.clear() // `a.len` and `a.key_values.len` is now 0 pub fn (mut m map) clear() { m.len = 0 - m.even_index = 0 + m.even_index = init_even_index m.key_values.len = 0 m.key_values.deletes = 0 unsafe { if m.key_values.all_deleted != 0 { free(m.key_values.all_deleted) + m.key_values.all_deleted = nil } vmemset(m.key_values.keys, 0, m.key_values.key_bytes * m.key_values.cap) vmemset(m.metas, 0, sizeof(u32) * (m.even_index + 2 + m.extra_metas)) diff --git a/vlib/builtin/map_issue_22143_clear_test.v b/vlib/builtin/map_issue_22143_clear_test.v new file mode 100644 index 00000000000000..ddc87c84166214 --- /dev/null +++ b/vlib/builtin/map_issue_22143_clear_test.v @@ -0,0 +1,37 @@ +fn add(mut m map[int]int, k int, v int) { + m[k] = v + dump('${m.len} ${m}') + // for x, y in m { println(' > m key: ${x} | value: ${y}') } +} + +fn test_map_clear_there_should_not_be_doble_entries_after_clear() { + mut ints := map[int]int{} + add(mut ints, 20, 120) + add(mut ints, 34, 134) + add(mut ints, 20, 150) // no double entry! + assert ints.len == 2 + assert ints[34] == 134 + assert ints[20] == 150 + for i in 0 .. 3 { + println('>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>> ints.clear(), i: ${i}') + ints.clear() + assert ints.len == 0 + add(mut ints, 20, 2000 + i) + assert ints[20] == 2000 + i + add(mut ints, 34, 34) + assert ints[34] == 34 + add(mut ints, 50, 50) + assert ints[50] == 50 + assert ints.len == 3 + add(mut ints, 20, 100) // try setting the first key again + assert ints.len == 3 + assert ints[20] == 100 + add(mut ints, 34, 55) // try setting the second key again + assert ints.len == 3 + assert ints[34] == 55 + add(mut ints, 20, 200 + i) // try setting the third key again + assert ints.len == 3 + assert ints[20] == 200 + i + } + assert ints.len == 3 +}