From e09027425cd91a29cc924b743ed4bbe1e7db8845 Mon Sep 17 00:00:00 2001 From: Masaaki Goshima Date: Wed, 17 Feb 2021 00:03:07 +0900 Subject: [PATCH] Use pre allocated pointer if exists it --- decode_ptr.go | 18 ++++++++++++++---- decode_test.go | 7 +------ 2 files changed, 15 insertions(+), 10 deletions(-) diff --git a/decode_ptr.go b/decode_ptr.go index 590629c..5d90366 100644 --- a/decode_ptr.go +++ b/decode_ptr.go @@ -44,8 +44,13 @@ func (d *ptrDecoder) decodeStream(s *stream, p unsafe.Pointer) error { *(*unsafe.Pointer)(p) = nil return nil } - newptr := unsafe_New(d.typ) - *(*unsafe.Pointer)(p) = newptr + var newptr unsafe.Pointer + if *(*unsafe.Pointer)(p) == nil { + newptr = unsafe_New(d.typ) + *(*unsafe.Pointer)(p) = newptr + } else { + newptr = *(*unsafe.Pointer)(p) + } if err := d.dec.decodeStream(s, newptr); err != nil { return err } @@ -74,8 +79,13 @@ func (d *ptrDecoder) decode(buf []byte, cursor int64, p unsafe.Pointer) (int64, cursor += 4 return cursor, nil } - newptr := unsafe_New(d.typ) - *(*unsafe.Pointer)(p) = newptr + var newptr unsafe.Pointer + if *(*unsafe.Pointer)(p) == nil { + newptr = unsafe_New(d.typ) + *(*unsafe.Pointer)(p) = newptr + } else { + newptr = *(*unsafe.Pointer)(p) + } c, err := d.dec.decode(buf, cursor, newptr) if err != nil { return 0, err diff --git a/decode_test.go b/decode_test.go index 645a852..9aeaa03 100644 --- a/decode_test.go +++ b/decode_test.go @@ -1864,7 +1864,6 @@ func TestUnmarshal(t *testing.T) { } } -/* func TestUnmarshalMarshal(t *testing.T) { initBig() var v interface{} @@ -1881,7 +1880,6 @@ func TestUnmarshalMarshal(t *testing.T) { return } } -*/ var numberTests = []struct { in string @@ -1938,7 +1936,6 @@ type Xint struct { X int } -/* func TestUnmarshalInterface(t *testing.T) { var xint Xint var i interface{} = &xint @@ -1949,8 +1946,7 @@ func TestUnmarshalInterface(t *testing.T) { t.Fatalf("Did not write to xint") } } -*/ -/* + func TestUnmarshalPtrPtr(t *testing.T) { var xint Xint pxint := &xint @@ -1961,7 +1957,6 @@ func TestUnmarshalPtrPtr(t *testing.T) { t.Fatalf("Did not write to xint") } } -*/ func TestEscape(t *testing.T) { const input = `"foobar"` + " [\u2028 \u2029]"