Skip to content

Commit

Permalink
Add string and byte slice (#5)
Browse files Browse the repository at this point in the history
  • Loading branch information
cristaloleg authored Aug 15, 2023
1 parent 9b7270a commit a53b7f5
Show file tree
Hide file tree
Showing 2 changed files with 46 additions and 0 deletions.
14 changes: 14 additions & 0 deletions encode.go
Original file line number Diff line number Diff line change
Expand Up @@ -40,6 +40,20 @@ func (e *Encoder) marshal(v any) error {
}
e.buf.Write(raw)

case []byte:
var b [4]byte
binary.LittleEndian.PutUint32(b[:], uint32(len(v)+1))
e.buf.Write(b[:])
e.buf.WriteByte(0x80) // TODO(cristaloleg): better binary type?
e.buf.Write(v)

case string:
var b [4]byte
binary.LittleEndian.PutUint32(b[:], uint32(len(v)+1))
e.buf.Write(b[:])
e.buf.Write([]byte(v))
e.buf.WriteByte(0)

case int32:
var b [4]byte
binary.LittleEndian.PutUint32(b[:], uint32(v))
Expand Down
32 changes: 32 additions & 0 deletions encode_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -24,3 +24,35 @@ func TestEncode(t *testing.T) {
wantBytes(t, buf.Bytes(), "01")
buf.Reset()
}

func TestEncodeBytes(t *testing.T) {
var err error
var buf bytes.Buffer
enc := NewEncoder(&buf)

err = enc.Encode([]byte("foo"))
mustOk(t, err)
wantBytes(t, buf.Bytes(), "0400000080666f6f")
buf.Reset()

err = enc.Encode([]byte{0x00})
mustOk(t, err)
wantBytes(t, buf.Bytes(), "020000008000")
buf.Reset()
}

func TestEncodeString(t *testing.T) {
var err error
var buf bytes.Buffer
enc := NewEncoder(&buf)

err = enc.Encode("foo")
mustOk(t, err)
wantBytes(t, buf.Bytes(), "04000000666f6f00")
buf.Reset()

err = enc.Encode("")
mustOk(t, err)
wantBytes(t, buf.Bytes(), "0100000000")
buf.Reset()
}

0 comments on commit a53b7f5

Please sign in to comment.