github.com/djordje200179/extendedlibrary/datastructures@v1.7.1-0.20240227175559-d09520a92dd4/seqs/bbuffer/buffer.go (about) 1 package bbuffer 2 3 // Buffer is a bounded buffer, which is a queue with a fixed size. 4 // Operations are blocking if the buffer is full or empty. 5 type Buffer[T any] chan T 6 7 // New creates a new bounded buffer with the given size. 8 func New[T any](size int) Buffer[T] { 9 return make(chan T, size) 10 } 11 12 // FromChannel creates a bounded buffer from the given channel. 13 func FromChannel[T any](channel chan T) Buffer[T] { 14 return channel 15 } 16 17 // Empty returns true if the buffer is empty. 18 func (buffer Buffer[T]) Empty() bool { 19 return len(buffer) == 0 20 } 21 22 // PushBack adds the given value to the back of the buffer. 23 // If the buffer is full, the operation blocks until there is space available. 24 func (buffer Buffer[T]) PushBack(value T) { 25 buffer <- value 26 } 27 28 // PopFront removes and returns the value at the front of the buffer. 29 // If the buffer is empty, the operation blocks until there is a value available. 30 func (buffer Buffer[T]) PopFront() T { 31 return <-buffer 32 }