83 lines
2.0 KiB
Go
83 lines
2.0 KiB
Go
package buffers
|
|
|
|
import (
|
|
"fmt"
|
|
"sync"
|
|
)
|
|
|
|
type NamedBinaryBuffer struct {
|
|
mu sync.Mutex
|
|
data map[string][]byte
|
|
limit int
|
|
}
|
|
|
|
func NewNamedBinaryBuffer(limit int) *NamedBinaryBuffer {
|
|
return &NamedBinaryBuffer{
|
|
data: make(map[string][]byte),
|
|
limit: limit,
|
|
}
|
|
}
|
|
|
|
func (b *NamedBinaryBuffer) Put(name string, value []byte) {
|
|
b.mu.Lock()
|
|
defer b.mu.Unlock()
|
|
if _, exists := b.data[name]; !exists {
|
|
b.data[name] = make([]byte, 0, b.limit)
|
|
}
|
|
if len(b.data[name]) <= b.limit {
|
|
b.data[name] = append(b.data[name], value...)
|
|
} else {
|
|
fmt.Printf("Buffer for %s is full, item discarded: %v\n", name, value)
|
|
}
|
|
}
|
|
|
|
func (b *NamedBinaryBuffer) Get(name string) ([]byte, bool) {
|
|
b.mu.Lock()
|
|
defer b.mu.Unlock()
|
|
values, exists := b.data[name]
|
|
if exists {
|
|
delete(b.data, name)
|
|
return values, true
|
|
}
|
|
return nil, false
|
|
}
|
|
|
|
func (b *NamedBinaryBuffer) Size(name string) int {
|
|
b.mu.Lock()
|
|
defer b.mu.Unlock()
|
|
return len(b.data[name])
|
|
}
|
|
|
|
/*
|
|
func main() {
|
|
buffer := NewNamedBinaryBuffer(3)
|
|
wg := &sync.WaitGroup{}
|
|
wg.Add(1)
|
|
go func() {
|
|
defer wg.Done()
|
|
buffer.Put("sensor1", []byte{1, 2, 3})
|
|
buffer.Put("sensor1", []byte{4, 5, 6})
|
|
buffer.Put("sensor1", []byte{7, 8, 9})
|
|
buffer.Put("sensor1", []byte{10, 11, 12})
|
|
}()
|
|
wg.Add(1)
|
|
go func() {
|
|
defer wg.Done()
|
|
buffer.Put("sensor2", []byte{13, 14})
|
|
buffer.Put("sensor2", []byte{15, 16})
|
|
}()
|
|
wg.Wait()
|
|
if values, exists := buffer.Get("sensor1"); exists {
|
|
fmt.Println("Got binary values for sensor1:", values)
|
|
} else {
|
|
fmt.Println("No values for sensor1.")
|
|
}
|
|
if values, exists := buffer.Get("sensor2"); exists {
|
|
fmt.Println("Got binary values for sensor2:", values)
|
|
} else {
|
|
fmt.Println("No values for sensor2.")
|
|
}
|
|
fmt.Println("Size of sensor1 buffer:", buffer.Size("sensor1"))
|
|
fmt.Println("Size of sensor2 buffer:", buffer.Size("sensor2"))
|
|
}*/
|