Skip to content

Commit

Permalink
builtin: fix incomplete m.clear(), allowing the map to have a duplica…
Browse files Browse the repository at this point in the history
…ted entry for its first key (fix #22143) (#22144)
  • Loading branch information
spytheman authored Sep 1, 2024
1 parent 673ac0a commit fc31b44
Show file tree
Hide file tree
Showing 2 changed files with 39 additions and 1 deletion.
3 changes: 2 additions & 1 deletion vlib/builtin/map.v
Original file line number Diff line number Diff line change
Expand Up @@ -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))
Expand Down
37 changes: 37 additions & 0 deletions vlib/builtin/map_issue_22143_clear_test.v
Original file line number Diff line number Diff line change
@@ -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
}

0 comments on commit fc31b44

Please sign in to comment.