Skip to content

Commit

Permalink
Merge pull request #137 from lennart6443/json_marshal_value_receiver
Browse files Browse the repository at this point in the history
Fix MarshalJSON not working for values
  • Loading branch information
lemire authored Sep 25, 2023
2 parents ce529ed + 12a3131 commit 7689058
Show file tree
Hide file tree
Showing 2 changed files with 42 additions and 18 deletions.
2 changes: 1 addition & 1 deletion bitset.go
Original file line number Diff line number Diff line change
Expand Up @@ -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 {
Expand Down
58 changes: 41 additions & 17 deletions bitset_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -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) {
Expand Down

0 comments on commit 7689058

Please sign in to comment.