Skip to content

Commit

Permalink
Add Write/Read Range
Browse files Browse the repository at this point in the history
  • Loading branch information
kelindar committed Dec 19, 2021
1 parent e9db3e8 commit d5396fa
Show file tree
Hide file tree
Showing 3 changed files with 63 additions and 0 deletions.
16 changes: 16 additions & 0 deletions reader.go
Expand Up @@ -215,6 +215,22 @@ func (r *Reader) ReadBytes() (out []byte, err error) {

// --------------------------- Other Types ---------------------------

// ReadRange reads the length of the array from the underlying stream and
// calls a callback function on each element of that array.
func (r *Reader) ReadRange(fn func(i int, r *Reader) error) error {
length, err := r.ReadUvarint()
if err != nil {
return err
}

for i := 0; i < int(length); i++ {
if err := fn(i, r); err != nil {
return err
}
}
return nil
}

// ReadBool reads a single boolean value from the slice.
func (r *Reader) ReadBool() (bool, error) {
b, err := r.src.ReadByte()
Expand Down
16 changes: 16 additions & 0 deletions writer.go
Expand Up @@ -223,6 +223,22 @@ func (w *Writer) WriteBytes(v []byte) error {

// --------------------------- Other Types ---------------------------

// WriteRange writes a specified length of an array and for each element of that
// array calls the callback function with its index.
func (w *Writer) WriteRange(length int, fn func(i int, w *Writer) error) error {
if err := w.WriteUvarint(uint64(length)); err != nil {
return err
}

for i := 0; i < length; i++ {
if err := fn(i, w); err != nil {
return err
}
}

return nil
}

// WriteBool writes a single boolean value into the buffer
func (w *Writer) WriteBool(v bool) error {
w.scratch[0] = 0
Expand Down
31 changes: 31 additions & 0 deletions writer_test.go
Expand Up @@ -158,6 +158,29 @@ var Fixtures = map[string]struct {
Buffer: []byte{0x5, 0x52, 0x6f, 0x6d, 0x61, 0x6e},
Value: person{Name: "Roman"},
},
"range": {
Encode: func(w *Writer) error {
v := []person{{Name: "Roman"}, {Name: "Florimond"}}
return w.WriteRange(len(v), func(i int, w *Writer) error {
return w.WriteSelf(&v[i])
})
},
Decode: func(r *Reader) (interface{}, error) {
var arr []person
err := r.ReadRange(func(i int, r *Reader) error {
var out person
if err := r.ReadSelf(&out); err != nil {
return err
}

arr = append(arr, out)
return nil
})
return arr, err
},
Buffer: []byte{0x2, 0x5, 0x52, 0x6f, 0x6d, 0x61, 0x6e, 0x9, 0x46, 0x6c, 0x6f, 0x72, 0x69, 0x6d, 0x6f, 0x6e, 0x64},
Value: []person{{Name: "Roman"}, {Name: "Florimond"}},
},
}

func TestWrite(t *testing.T) {
Expand All @@ -176,6 +199,14 @@ func TestWriteFailuresString(t *testing.T) {
}, nil, 0)
}

func TestWriteFailures(t *testing.T) {
for n, tc := range Fixtures {
for x := 0; x < int(len(tc.Buffer))-1; x++ {
assertWriteN(t, n, tc.Encode, nil, x)
}
}
}

func TestWriteMethod(t *testing.T) {
w := NewWriter(bytes.NewBuffer(nil))
_, err := w.Write(nil)
Expand Down

0 comments on commit d5396fa

Please sign in to comment.