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 over-reading while de-serializing #107

Merged
merged 1 commit into from
Sep 7, 2022
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
6 changes: 2 additions & 4 deletions bitset.go
Original file line number Diff line number Diff line change
Expand Up @@ -945,11 +945,9 @@ func (b *BitSet) ReadFrom(stream io.Reader) (int64, error) {
// binary.Read for large set
reader := bufio.NewReader(stream)
var item = make([]byte, binary.Size(uint64(0))) // one uint64
for i := uint64(0); i < length; i++ {
nWords := uint64(wordsNeeded(uint(length)))
for i := uint64(0); i < nWords; i++ {
if _, err := reader.Read(item); err != nil {
if err == io.EOF {
break // done
}
return 0, err
}
newset.set[i] = binaryOrder.Uint64(item)
Expand Down
27 changes: 27 additions & 0 deletions bitset_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -1270,6 +1270,33 @@ func TestMarshalUnmarshalJSON(t *testing.T) {
}
}

func TestMarshalUnmarshalJSONWithTrailingData(t *testing.T) {
a := New(1010).Set(10).Set(1001)
data, err := json.Marshal(a)
if err != nil {
t.Errorf(err.Error())
return
}

// appending some noise
data = data[:len(data) - 3] // remove "
data = append(data, []byte(`AAAAAAAAAA"`)...)

b := new(BitSet)
err = json.Unmarshal(data, b)
if err != nil {
t.Errorf(err.Error())
return
}

// Bitsets must be equal after marshalling and unmarshalling
// Do not over-reading when unmarshalling
if !a.Equal(b) {
t.Error("Bitsets are not equal:\n\t", a.DumpAsBits(), "\n\t", b.DumpAsBits())
return
}
}

func TestMarshalUnmarshalJSONByStdEncoding(t *testing.T) {
Base64StdEncoding()
a := New(1010).Set(10).Set(1001)
Expand Down