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

feat: add the ability to encode a byte array #76

Merged
merged 1 commit into from
Oct 21, 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
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