Advertisement
Falexom

Untitled

May 25th, 2024
771
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Go 1.22 KB | None | 0 0
  1. type Frame struct {
  2.     frameId   int
  3.     data      []byte
  4.     untouched bool
  5. }
  6.  
  7. type CircularBuffer struct {
  8.     maxLen int
  9.     buffer []Frame
  10.     head   int
  11.     tail   int
  12. }
  13.  
  14. type CircularBufferAPI interface {
  15.     IsEmpty() bool
  16.     IsFull()
  17.     Enqueue(Frame)
  18.     Dequeue()
  19.     Front() Frame
  20.     Show() []Frame
  21. }
  22.  
  23. func CBInit(maxLen int) *CircularBuffer {
  24.     return &CircularBuffer{
  25.         maxLen: maxLen,
  26.         buffer: make([]Frame, maxLen),
  27.         head:   0,
  28.         tail:   0,
  29.     }
  30. }
  31.  
  32. func (cb *CircularBuffer) IsEmpty() bool {
  33.     return cb.head == cb.tail
  34. }
  35.  
  36. func (cb *CircularBuffer) IsFull() bool {
  37.     return cb.tail == (cb.head-1)%cb.maxLen
  38. }
  39.  
  40. func (cb *CircularBuffer) Enqueue(frame Frame) Frame {
  41.     if !cb.IsFull() {
  42.         item := cb.buffer[cb.tail]
  43.         cb.buffer[cb.tail] = frame
  44.         cb.tail = (cb.tail + 1) % cb.maxLen
  45.         return item
  46.     }
  47.     return Frame{}
  48. }
  49.  
  50. func (cb *CircularBuffer) Dequeue() Frame {
  51.     if !cb.IsEmpty() {
  52.         item := cb.buffer[cb.head]
  53.         hollowFrame := Frame{frameId: 0, data: []byte{}}
  54.         cb.buffer[cb.head] = hollowFrame
  55.         cb.head = (cb.head + 1) % cb.maxLen
  56.         return item
  57.     }
  58.     return Frame{}
  59. }
  60.  
  61. func (cb *CircularBuffer) Front() Frame {
  62.     return cb.buffer[cb.head]
  63. }
  64.  
  65. func (cb *CircularBuffer) Show() []Frame {
  66.     return cb.buffer
  67. }
  68.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement