From 136bdfe93f8830457651f88d4e423e39bc110485 Mon Sep 17 00:00:00 2001 From: Felipe Pena Date: Sat, 19 Oct 2024 05:49:41 -0300 Subject: [PATCH] maps: use explicit map value cloning in `maps.merge_in_place` and `maps.merge` (fx #22564) (#22576) --- vlib/maps/maps.v | 12 ++++++++++-- vlib/maps/maps_clone_test.v | 36 ++++++++++++++++++++++++++++++++++++ 2 files changed, 46 insertions(+), 2 deletions(-) create mode 100644 vlib/maps/maps_clone_test.v diff --git a/vlib/maps/maps.v b/vlib/maps/maps.v index f28804aceac813..4d18730093b964 100644 --- a/vlib/maps/maps.v +++ b/vlib/maps/maps.v @@ -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 + } } } @@ -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 } diff --git a/vlib/maps/maps_clone_test.v b/vlib/maps/maps_clone_test.v new file mode 100644 index 00000000000000..edc407a6b0fcc2 --- /dev/null +++ b/vlib/maps/maps_clone_test.v @@ -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}}" +}