Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

maps: fix map cloning #22576

Merged
merged 1 commit into from
Oct 19, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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}}"
}
Loading