76 lines
1.3 KiB
Go
76 lines
1.3 KiB
Go
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)
|
|
}
|