diff --git a/tests/lux_data_test.go b/tests/lux_data_test.go new file mode 100644 index 0000000..c2cff75 --- /dev/null +++ b/tests/lux_data_test.go @@ -0,0 +1,23 @@ +package tests + +import ( + "bytes" + "lux/types" + "testing" +) + +func TestWriteGrow(t *testing.T) { + first, second := []byte{1, 2, 3, 4}, []byte{5, 6, 7, 8} + must := []byte{1, 2, 3, 4, 5, 6, 7, 8} + + buf := types.NewLuxBuffer(4) + buf.WriteBytes(first) + t.Log(buf.AllBytes()) + + buf.WriteBytes(second) + t.Log(buf.AllBytes()) + + if !bytes.Equal(must, buf.AllBytes()) { + t.Fail() + } +} diff --git a/types/lux_data.go b/types/lux_data.go new file mode 100644 index 0000000..f6b9967 --- /dev/null +++ b/types/lux_data.go @@ -0,0 +1,76 @@ +package types + +import ( + "encoding/binary" +) + +var NO = binary.BigEndian + +const MIN_BUFFER_SIZE = 256 + +type LuxBuffer struct { + data []byte + offset int + len int +} + +func NewLuxBuffer(cap int) *LuxBuffer { + return &LuxBuffer{ + data: make([]byte, cap), + offset: 0, + len: 0, + } +} + +func FromSlice(bytes []byte) *LuxBuffer { + return &LuxBuffer{ + data: bytes, + offset: 0, + len: len(bytes), + } +} + +func (buf *LuxBuffer) Capacity() int { + return len(buf.data) +} + +func (buf *LuxBuffer) Offset() int { + return buf.offset +} + +func (buf *LuxBuffer) Length() int { + return buf.len +} + +func (buf *LuxBuffer) Available() int { + return buf.Capacity() - buf.Length() +} + +func (buf *LuxBuffer) Grow(grow int) { + ocap, ncap := buf.Capacity(), (buf.Capacity()*2 + grow) + odata := buf.data + + buf.data = make([]byte, ncap) + copy(buf.data[:ocap], odata[:]) +} + +// will return byte buffer, sliced to real length +func (buf *LuxBuffer) AllBytes() []byte { + return buf.data[:buf.len] +} + +// ensure capacity for new write, return slice pointing to a place of a new write +func (buf *LuxBuffer) WriteNext(size int) []byte { + if buf.Available() < size { + buf.Grow(size) + } + + next := buf.data[buf.len : buf.len+size] + buf.len += size + + return next +} + +func (buf *LuxBuffer) WriteBytes(bytes []byte) { + copy(buf.WriteNext(len(bytes)), bytes) +}