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

mapstr: fix M.Clone behaviour for arrays of M #262

Open
wants to merge 1 commit into
base: main
Choose a base branch
from
Open
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
41 changes: 33 additions & 8 deletions mapstr/mapstr.go
Original file line number Diff line number Diff line change
Expand Up @@ -154,19 +154,44 @@ func (m M) CopyFieldsTo(to M, key string) error {
}

// Clone returns a copy of the M. It recursively makes copies of inner
// maps.
// maps. Nested arrays and non-map types are not cloned.
func (m M) Clone() M {
result := make(M, len(m))
cloneMap(result, m)
return result
}

for k := range m {
if innerMap, ok := tryToMapStr(m[k]); ok {
result[k] = innerMap.Clone()
} else {
result[k] = m[k]
func cloneMap(dst, src M) {
for k, v := range src {
switch v := v.(type) {
case M:
d := make(M, len(v))
dst[k] = d
cloneMap(d, v)
case map[string]interface{}:
d := make(map[string]interface{}, len(v))
dst[k] = d
cloneMap(d, v)
case []M:
a := make([]M, 0, len(v))
for _, m := range v {
d := make(M, len(m))
cloneMap(d, m)
a = append(a, d)
}
dst[k] = a
case []map[string]interface{}:
a := make([]map[string]interface{}, 0, len(v))
for _, m := range v {
d := make(map[string]interface{}, len(m))
cloneMap(d, m)
a = append(a, d)
}
dst[k] = a
default:
dst[k] = v
}
}

return result
}

// HasKey returns true if the key exist. If an error occurs then false is
Expand Down
6 changes: 6 additions & 0 deletions mapstr/mapstr_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -350,6 +350,7 @@ func TestClone(t *testing.T) {
"c31": 1,
"c32": 2,
},
"c4": []M{{"c41": 1}},
}

// Clone the original mapstr and then increment every value in it. Ensures the test will fail if
Expand All @@ -366,6 +367,7 @@ func TestClone(t *testing.T) {
"c31": 1,
"c32": 2,
},
"c4": []M{{"c41": 1}},
},
cloned,
)
Expand All @@ -379,6 +381,10 @@ func incrementMapstrValues(m M) {
m[k] = v + 1
case M:
incrementMapstrValues(m[k].(M))
case []M:
for _, c := range v {
incrementMapstrValues(c)
}
}

}
Expand Down
Loading