implementing LuxBuffer

This commit is contained in:
mykola2312 2024-12-29 11:06:01 +02:00
parent abfa7260b1
commit ad775cc1ff
2 changed files with 99 additions and 0 deletions

23
tests/lux_data_test.go Normal file
View file

@ -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()
}
}

76
types/lux_data.go Normal file
View file

@ -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)
}