Skip to content

Commit

Permalink
feat: add the ability to encode a byte array
Browse files Browse the repository at this point in the history
We can already _decode_ a raw byte array, but there wasn't a way to
encode one.
  • Loading branch information
Stebalien committed Oct 21, 2022
1 parent f29c37e commit b02fe5f
Show file tree
Hide file tree
Showing 2 changed files with 42 additions and 0 deletions.
12 changes: 12 additions & 0 deletions utils.go
Original file line number Diff line number Diff line change
Expand Up @@ -543,6 +543,18 @@ func ReadByteArray(br io.Reader, maxlen uint64) ([]byte, error) {
return buf, nil
}

// WriteByteArray encodes a byte array as a cbor byte-string.
func WriteByteArray(bw io.Writer, bytes []byte) error {
writer := NewCborWriter(bw)
if err := writer.WriteMajorTypeHeader(MajByteString, uint64(len(bytes))); err != nil {
return err
}
if _, err := writer.Write(bytes); err != nil {
return err
}
return nil
}

var (
CborBoolFalse = []byte{0xf4}
CborBoolTrue = []byte{0xf5}
Expand Down
30 changes: 30 additions & 0 deletions utils_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -83,6 +83,36 @@ func TestDeferredMaxLengthSingle(t *testing.T) {
}
}

func TestByteArray(t *testing.T) {
var buf bytes.Buffer
input := []byte("foobar")
if err := WriteByteArray(&buf, input); err != nil {
t.Fatal("failed to encode byte array")
}

// Exact length should work.
encoded := bytes.NewReader(buf.Bytes())
if out, err := ReadByteArray(encoded, uint64(len(input))); err != nil {
t.Fatal("failed to decode byte array")
} else if string(out) != string(input) {
t.Fatal("bytes failed to round-trip")
}

// Large length should work.
encoded.Seek(0, io.SeekStart)
if out, err := ReadByteArray(encoded, 100); err != nil {
t.Fatal("failed to decode byte array")
} else if string(out) != string(input) {
t.Fatal("bytes failed to round-trip")
}

// Short length should not work.
encoded.Seek(0, io.SeekStart)
if _, err := ReadByteArray(encoded, uint64(len(input)-1)); err == nil {
t.Fatal("should have refused to read too many bytes")
}
}

// TestReadEOFSemantics checks that our helper functions follow this rule when
// dealing with EOF:
// If the reader can't read a single byte because of EOF, it should return err == io.EOF.
Expand Down

0 comments on commit b02fe5f

Please sign in to comment.