fifobuffer.go 876 B

1234567891011121314151617181920212223242526272829303132333435363738394041424344
  1. package door
  2. import "log"
  3. // A First-In-First-Out buffer using generics.
  4. type FIFOBuffer[T any] struct {
  5. data []T
  6. index int
  7. }
  8. /*
  9. Construct new buffer.
  10. buffer := NewFIFOBuffer[rune](5)
  11. This would construct a buffer that will hold
  12. rune type, with a buffer size of 5.
  13. */
  14. func NewFIFOBuffer[T any](maxsize int) FIFOBuffer[T] {
  15. return FIFOBuffer[T]{data: make([]T, maxsize)}
  16. }
  17. // Is buffer empty?
  18. func (f *FIFOBuffer[T]) Empty() bool {
  19. return f.index == 0
  20. }
  21. // Push item into buffer.
  22. func (f *FIFOBuffer[T]) Push(value T) {
  23. if f.index >= len(f.data) {
  24. log.Panicf("Exceeded FIFOBuffer index %d size %d %#v", f.index, len(f.data), f.data)
  25. }
  26. f.data[f.index] = value
  27. f.index++
  28. }
  29. // Pop element from buffer.
  30. func (f *FIFOBuffer[T]) Pop() T {
  31. if f.index == 0 {
  32. log.Panicf("Pop from empty FIFOBuffer (size %d).", len(f.data))
  33. }
  34. f.index--
  35. return f.data[f.index]
  36. }