nettools/data_structures/cbuf.go

59 lines
1.2 KiB
Go

package dsUtils
// ICBuf is a basic Circular buffer interface
type ICBuf[T any] interface {
Push(item T)
Get() []T
}
// CBuf is the implementation of ICBuf interface
// Simplest circular buffer implementation
// If thread safety is needed -- use CBufSync
//
// WARNING: It's not thread-safe by default,
// use it with a lock
type CBuf[T any] struct {
ICBuf[T]
Buffer []T
Cursor int
Capacity int
}
// NewCBuf creates a new CBuf instance
func NewCBuf[T any](capacity int) *CBuf[T] {
return &CBuf[T]{
Buffer: make([]T, capacity),
Capacity: capacity,
}
}
func (cbuf *CBuf[T]) Push(item T) {
cbuf.Buffer[cbuf.Cursor] = item
cbuf.Cursor++
if cbuf.Cursor >= cbuf.Capacity {
cbuf.Cursor = 0
}
println(cbuf.Cursor)
}
// This method isn't a part of ICBuf interface
//
// It pushes item to the "buffer start"
// (Right before the cursor)
// removing item from back
func (cbuf *CBuf[T]) PushFront(item T) {
cbuf.Buffer = append(
append(cbuf.Buffer[cbuf.Cursor+1:], cbuf.Buffer[:cbuf.Cursor]...),
item,
)
cbuf.Cursor = 0
}
// Get returns the whole buffer in the correct order
func (cbuf *CBuf[T]) Get() []T {
out := make([]T, 0, cbuf.Capacity)
copy(out, cbuf.Buffer[cbuf.Cursor:])
out = append(out, cbuf.Buffer[:cbuf.Cursor]...)
return out
}