Skip to content

Commit

Permalink
Fix pointer resued in maps key
Browse files Browse the repository at this point in the history
  • Loading branch information
ray2011 authored and atombender committed Mar 14, 2022
1 parent 65e672e commit cfce916
Show file tree
Hide file tree
Showing 4 changed files with 32 additions and 4 deletions.
8 changes: 4 additions & 4 deletions dump.go
Original file line number Diff line number Diff line change
Expand Up @@ -457,10 +457,10 @@ func (s *dumpState) pointerFor(v reflect.Value) (*ptrinfo, bool) {
}

// prepares a new state object for dumping the provided value
func newDumpState(value interface{}, options *Options, writer io.Writer) *dumpState {
func newDumpState(value reflect.Value, options *Options, writer io.Writer) *dumpState {
result := &dumpState{
config: options,
pointers: mapReusedPointers(reflect.ValueOf(value)),
pointers: mapReusedPointers(value),
w: writer,
}

Expand All @@ -484,7 +484,7 @@ func Sdump(value ...interface{}) string {
// Dump a value to stdout according to the options
func (o Options) Dump(values ...interface{}) {
for i, value := range values {
state := newDumpState(value, &o, os.Stdout)
state := newDumpState(reflect.ValueOf(value), &o, os.Stdout)
if i > 0 {
state.write([]byte(o.Separator))
}
Expand All @@ -500,7 +500,7 @@ func (o Options) Sdump(values ...interface{}) string {
if i > 0 {
_, _ = buf.Write([]byte(o.Separator))
}
state := newDumpState(value, &o, buf)
state := newDumpState(reflect.ValueOf(value), &o, buf)
state.dump(value)
}
return buf.String()
Expand Down
15 changes: 15 additions & 0 deletions dump_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -243,6 +243,21 @@ func TestSdump_maps(t *testing.T) {
})
}

func TestSdump_RecursiveMaps(t *testing.T) {
mp := make(map[*RecursiveStruct]*RecursiveStruct)
k1 := &RecursiveStruct{}
k1.Ptr = k1
v1 := &RecursiveStruct{}
v1.Ptr = v1
k2 := &RecursiveStruct{}
k2.Ptr = k2
v2 := &RecursiveStruct{}
v2.Ptr = v2
mp[k1] = v1
mp[k2] = v2
runTests(t, "recursive_maps", mp)
}

var standardCfg = litter.Options{}

func runTestWithCfg(t *testing.T, name string, cfg *litter.Options, cases ...interface{}) {
Expand Down
1 change: 1 addition & 0 deletions pointers.go
Original file line number Diff line number Diff line change
Expand Up @@ -136,6 +136,7 @@ func (pv *pointerVisitor) consider(v reflect.Value) {
options: &Config,
})
for _, key := range keys {
pv.consider(key)
pv.consider(v.MapIndex(key))
}

Expand Down
12 changes: 12 additions & 0 deletions testdata/recursive_maps.dump
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
map[*litter_test.RecursiveStruct]*litter_test.RecursiveStruct{
&litter_test.RecursiveStruct{ // p0
Ptr: p0,
}: &litter_test.RecursiveStruct{ // p1
Ptr: p1,
},
&litter_test.RecursiveStruct{ // p2
Ptr: p2,
}: &litter_test.RecursiveStruct{ // p3
Ptr: p3,
},
}

0 comments on commit cfce916

Please sign in to comment.