Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Fix MarshalJSON not working for values #137

Merged
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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