Skip to content

Commit

Permalink
Merge pull request #31 from nicholas-wright-bjss/master
Browse files Browse the repository at this point in the history
Fix for recursive structs
  • Loading branch information
kungfusheep committed Sep 5, 2023
2 parents 293c1dd + 0bc09b4 commit 9e00d89
Show file tree
Hide file tree
Showing 2 changed files with 41 additions and 5 deletions.
36 changes: 32 additions & 4 deletions jingo_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -170,14 +170,44 @@ func Test_StructWithEscapes(t *testing.T) {

// Compare result
if resultJSON != wantJSON {
t.Errorf("Test_StructWithScapes Failed: want JSON:" + wantJSON + " got JSON:" + resultJSON)
t.Errorf("Test_StructWithEscapes Failed: want JSON:" + wantJSON + " got JSON:" + resultJSON)
}

andBackAgain := StructWithEscapes{}
json.Unmarshal([]byte(resultJSON), &andBackAgain)

if !reflect.DeepEqual(es, andBackAgain) {
t.Errorf("Test_StructWithScapes Failed: want: %+v got: %+v", es, andBackAgain)
t.Errorf("Test_StructWithEscapes Failed: want: %+v got: %+v", es, andBackAgain)
}
}

func Test_StructWithRecursion(t *testing.T) {

type structWithRecursion struct {
Name string `json:"name"`
Child *structWithRecursion `json:"child"`
}

v := structWithRecursion{
Name: "A",
Child: &structWithRecursion{
Name: "B",
Child: &structWithRecursion{
Name: "C",
Child: nil,
},
},
}

wantJSON := `{"name":"A","child":{"name":"B","child":{"name":"C","child":null}}}`

var enc = NewStructEncoder(structWithRecursion{})
buf := NewBufferFromPool()
enc.Marshal(&v, buf)

resultJSON := buf.String()
if resultJSON != wantJSON {
t.Errorf("Test_StructWithRecursion Failed: want JSON:" + wantJSON + " got JSON:" + resultJSON)
}
}

Expand Down Expand Up @@ -508,8 +538,6 @@ func BenchmarkSliceStdLib(b *testing.B) {
// var fakeType = LargePayload{}
// var fake = NewLargePayload()

//
//
var s = "test pointer string b"
var fakeType = all{}
var fake = &all{
Expand Down
10 changes: 9 additions & 1 deletion structencoder.go
Original file line number Diff line number Diff line change
Expand Up @@ -346,7 +346,15 @@ func (e *StructEncoder) valueInst(k reflect.Kind, instr func(func(unsafe.Pointer

/// now cater for it being a pointer to a struct
var inf = reflect.New(reflect.TypeOf(e.t).Field(e.i).Type.Elem()).Elem().Interface()
enc := NewStructEncoder(inf)

var enc *StructEncoder
if e.t == inf {
// handle recursive structs by re-using the current encoder
enc = e
} else {
enc = NewStructEncoder(inf)
}

// now create an instruction to marshal the field
f := e.f
e.appendInstructionFun(func(v unsafe.Pointer, w *Buffer) {
Expand Down

0 comments on commit 9e00d89

Please sign in to comment.