Skip to content

Commit

Permalink
Add mapping.Dup() to create a dereferenced clone (#2)
Browse files Browse the repository at this point in the history
* Add mapping.Dup() to create a dereferenced clone

* Linter suggested optimization
  • Loading branch information
kke authored Aug 16, 2021
1 parent e1d195d commit bcae5d9
Show file tree
Hide file tree
Showing 2 changed files with 81 additions and 0 deletions.
40 changes: 40 additions & 0 deletions mapping.go
Original file line number Diff line number Diff line change
Expand Up @@ -70,6 +70,46 @@ func (m *Mapping) DigMapping(keys ...string) Mapping {
}
}

// Dup creates a dereferenced copy of the Mapping
func (m *Mapping) Dup() Mapping {
new := make(Mapping, len(*m))
for k, v := range *m {
switch vt := v.(type) {
case Mapping:
new[k] = vt.Dup()
case *Mapping:
new[k] = vt.Dup()
case []Mapping:
var ns []Mapping
for _, sv := range vt {
ns = append(ns, sv.Dup())
}
new[k] = ns
case []*Mapping:
var ns []Mapping
for _, sv := range vt {
ns = append(ns, sv.Dup())
}
new[k] = ns
case []string:
var ns []string
ns = append(ns, vt...)
new[k] = ns
case []int:
var ns []int
ns = append(ns, vt...)
new[k] = ns
case []bool:
var ns []bool
ns = append(ns, vt...)
new[k] = ns
default:
new[k] = vt
}
}
return new
}

// Cleans up a slice of interfaces into slice of actual values
func cleanUpInterfaceArray(in []interface{}) []interface{} {
result := make([]interface{}, len(in))
Expand Down
41 changes: 41 additions & 0 deletions mapping_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -51,6 +51,47 @@ func TestDigMapping(t *testing.T) {
assert.Equal(t, "hello", m.Dig("foo", "bar", "baz"))
}

func TestDup(t *testing.T) {
m := Mapping{
"foo": Mapping{
"bar": "foobar",
},
"array": []string{
"hello",
},
"mappingarray": []Mapping{
{"bar": "foobar"},
{"foo": "barfoo"},
},
}

dup := m.Dup()

m.DigMapping("foo")["bar"] = "barbar"
arr := m.Dig("array").([]string)
arr = append(arr, "world")
m["array"] = arr

ma := m["mappingarray"].([]Mapping)
maa := ma[0]
maa["bar"] = "barbar"

assert.Equal(t, "barbar", m.Dig("foo", "bar"))
assert.Equal(t, "foobar", dup.Dig("foo", "bar"))

a := m.Dig("array").([]string)
b := dup.Dig("array").([]string)

assert.Len(t, a, 2)
assert.Len(t, b, 1)

am := m.Dig("mappingarray").([]Mapping)
bm := dup.Dig("mappingarray").([]Mapping)

assert.Equal(t, "barbar", am[0]["bar"])
assert.Equal(t, "foobar", bm[0]["bar"])
}

func TestUnmarshalYamlWithNil(t *testing.T) {
data := `foo: null`
var m Mapping
Expand Down

0 comments on commit bcae5d9

Please sign in to comment.