From 12a31310e47fabe24b9d91474c6e59bd3f41c277 Mon Sep 17 00:00:00 2001 From: lennart6443 <28091310+lennart6443@users.noreply.github.com> Date: Mon, 25 Sep 2023 14:52:40 +0200 Subject: [PATCH] Fix MarshalJSON not working for values --- bitset.go | 2 +- bitset_test.go | 58 +++++++++++++++++++++++++++++++++++--------------- 2 files changed, 42 insertions(+), 18 deletions(-) diff --git a/bitset.go b/bitset.go index 4eb1733..a87435b 100644 --- a/bitset.go +++ b/bitset.go @@ -1019,7 +1019,7 @@ func (b *BitSet) UnmarshalBinary(data []byte) error { } // MarshalJSON marshals a BitSet as a JSON structure -func (b *BitSet) MarshalJSON() ([]byte, error) { +func (b BitSet) MarshalJSON() ([]byte, error) { buffer := bytes.NewBuffer(make([]byte, 0, b.BinaryStorageSize())) _, err := b.WriteTo(buffer) if err != nil { diff --git a/bitset_test.go b/bitset_test.go index b8c682f..f9534e2 100644 --- a/bitset_test.go +++ b/bitset_test.go @@ -1297,25 +1297,49 @@ func copyBinary(t *testing.T, from encoding.BinaryMarshaler, to encoding.BinaryU } func TestMarshalUnmarshalJSON(t *testing.T) { - a := New(1010).Set(10).Set(1001) - data, err := json.Marshal(a) - if err != nil { - t.Errorf(err.Error()) - return - } + t.Run("value", func(t *testing.T) { + a := BitSet{} + a.Set(10).Set(1001) + data, err := json.Marshal(a) + if err != nil { + t.Errorf(err.Error()) + return + } - b := new(BitSet) - err = json.Unmarshal(data, b) - if err != nil { - t.Errorf(err.Error()) - return - } + b := new(BitSet) + err = json.Unmarshal(data, b) + if err != nil { + t.Errorf(err.Error()) + return + } - // Bitsets must be equal after marshalling and unmarshalling - if !a.Equal(b) { - t.Error("Bitsets are not equal:\n\t", a.DumpAsBits(), "\n\t", b.DumpAsBits()) - return - } + // Bitsets must be equal after marshalling and unmarshalling + if !a.Equal(b) { + t.Error("Bitsets are not equal:\n\t", a.DumpAsBits(), "\n\t", b.DumpAsBits()) + return + } + }) + t.Run("pointer", func(t *testing.T) { + a := New(1010).Set(10).Set(1001) + data, err := json.Marshal(a) + if err != nil { + t.Errorf(err.Error()) + return + } + + b := new(BitSet) + err = json.Unmarshal(data, b) + if err != nil { + t.Errorf(err.Error()) + return + } + + // Bitsets must be equal after marshalling and unmarshalling + if !a.Equal(b) { + t.Error("Bitsets are not equal:\n\t", a.DumpAsBits(), "\n\t", b.DumpAsBits()) + return + } + }) } func TestMarshalUnmarshalJSONWithTrailingData(t *testing.T) {