Last active
January 18, 2019 02:15
-
-
Save kedarmhaswade/82225310a56028f197c7577dce0b9c60 to your computer and use it in GitHub Desktop.
A naive circular buffer ...
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// A naive circular buffer ... | |
type CircularBuffer struct { | |
buf []int | |
cap, head, tail int | |
} | |
func (q *CircularBuffer) add(d int) error { | |
if q.tail-q.head > q.cap { | |
return errors.New("buffer full") | |
} | |
q.buf[q.tail%q.cap] = d | |
q.tail += 1 | |
return nil | |
} | |
func (q CircularBuffer) remove() (int, error) { | |
if q.tail == q.head { | |
return -1, errors.New("buffer empty") | |
} | |
x := q.buf[q.head%q.cap] | |
q.head += 1 | |
return x, nil | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment