Skip to content

Commit

Permalink
maps: use explicit map value cloning in maps.merge_in_place and `ma…
Browse files Browse the repository at this point in the history
…ps.merge` (fx #22564) (#22576)
  • Loading branch information
felipensp authored Oct 19, 2024
1 parent 380500a commit 136bdfe
Show file tree
Hide file tree
Showing 2 changed files with 46 additions and 2 deletions.
12 changes: 10 additions & 2 deletions vlib/maps/maps.v
Original file line number Diff line number Diff line change
Expand Up @@ -75,7 +75,11 @@ pub fn from_array[T](array []T) map[int]T {
// Note that this function modifes `m1`, while `m2` will not be.
pub fn merge_in_place[K, V](mut m1 map[K]V, m2 map[K]V) {
for k, v in m2 {
m1[k] = v
$if v is $map {
m1[k] = v.clone()
} $else {
m1[k] = v
}
}
}

Expand All @@ -86,7 +90,11 @@ pub fn merge_in_place[K, V](mut m1 map[K]V, m2 map[K]V) {
pub fn merge[K, V](m1 map[K]V, m2 map[K]V) map[K]V {
mut res := m1.clone()
for k, v in m2 {
res[k] = v
$if v is $map {
res[k] = v.clone()
} $else {
res[k] = v
}
}
return res
}
36 changes: 36 additions & 0 deletions vlib/maps/maps_clone_test.v
Original file line number Diff line number Diff line change
@@ -0,0 +1,36 @@
import maps

fn test_main() {
// mmm map declaration as mutable
mut mmm := map[string]map[string]int{}

// adding values to the map mmm
mmm['greet'] = {
'hello': 0
}
mmm['place'] = {
'world': 1
}
mmm['color']['orange'] = 2

// printing the map mmm
assert mmm.str() == "{'greet': {'hello': 0}, 'place': {'world': 1}, 'color': {'orange': 2}}"

// mmm2 map declaration as const
mmm2 := {
'name': {
'Diego': 3
}
}

// printing the map mmm2
assert mmm2.str() == "{'name': {'Diego': 3}}"

// Using the maps module functions
// use of maps.merge is commented but its behavior is the same as merge_in_place
// mmm = maps.merge(mmm, mmm2)
maps.merge_in_place(mut mmm, mmm2)

// printing again mmm to the standard output
assert mmm.str() == "{'greet': {'hello': 0}, 'place': {'world': 1}, 'color': {'orange': 2}, 'name': {'Diego': 3}}"
}

0 comments on commit 136bdfe

Please sign in to comment.