Skip to content

Commit

Permalink
fix encode binary data, add length
Browse files Browse the repository at this point in the history
  • Loading branch information
negasus committed May 19, 2023
1 parent 9a8c9fb commit 6bdf2f4
Show file tree
Hide file tree
Showing 2 changed files with 20 additions and 12 deletions.
23 changes: 15 additions & 8 deletions typeddata/typeddata.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,10 +2,11 @@ package typeddata

import (
"fmt"
"github.com/negasus/haproxy-spoe-go/varint"
"net"
"reflect"

"github.com/negasus/haproxy-spoe-go/varint"

"github.com/pkg/errors"
)

Expand All @@ -32,14 +33,14 @@ const (
TypeBinary byte = 9
)

//ErrEmptyBuffer describe error, if passed empty buffer for decoding
// ErrEmptyBuffer describe error, if passed empty buffer for decoding
var ErrEmptyBuffer = errors.New("empty buffer for decode")

//ErrDecodingBufferTooSmall describe error for too small decoding buffer
// ErrDecodingBufferTooSmall describe error for too small decoding buffer
var ErrDecodingBufferTooSmall = errors.New("decoding buffer too small")

//Encode variable to TypedData value
//returns filled buffer, count of bytes and error
// Encode variable to TypedData value
// returns filled buffer, count of bytes and error
func Encode(data interface{}, buf []byte) ([]byte, int, error) {
var n int

Expand Down Expand Up @@ -110,16 +111,22 @@ func Encode(data interface{}, buf []byte) ([]byte, int, error) {
return buf, n, nil

case []byte:
n = 1
buf = append(buf, TypeBinary)
b := make([]byte, 8)
i := varint.PutUvarint(b, uint64(len(v)))
n += i
n += len(v)
buf = append(buf, b[:i]...)
buf = append(buf, v...)
return buf, len(v) + 1, nil
return buf, n, nil
}

return nil, 0, fmt.Errorf("type not supported for encode to TypedData: %s", reflect.TypeOf(data).String())
}

//Decode TypedData value
//Returns decoded variable, bytes count and error
// Decode TypedData value
// Returns decoded variable, bytes count and error
func Decode(buf []byte) (data interface{}, n int, err error) {
if len(buf) == 0 {
err = ErrEmptyBuffer
Expand Down
9 changes: 5 additions & 4 deletions typeddata/typeddata_test.go
Original file line number Diff line number Diff line change
@@ -1,8 +1,9 @@
package typeddata

import (
"github.com/stretchr/testify/assert"
"testing"

"github.com/stretchr/testify/assert"
)

func TestEncode_Nil(t *testing.T) {
Expand Down Expand Up @@ -38,9 +39,9 @@ func TestEncode_Int32(t *testing.T) {
func TestEncode_Binary(t *testing.T) {
buf, n, err := Encode([]byte{0x10, 0x20, 0x30}, make([]byte, 0))
assert.Nil(t, err)
assert.Equal(t, 4, n)
assert.Equal(t, 4, len(buf))
assert.Equal(t, []byte{0x09, 0x10, 0x20, 0x30}, buf)
assert.Equal(t, 5, n)
assert.Equal(t, 5, len(buf))
assert.Equal(t, []byte{0x09, 0x03, 0x10, 0x20, 0x30}, buf)
}

// todo: tests

0 comments on commit 6bdf2f4

Please sign in to comment.