Skip to content

Instantly share code, notes, and snippets.

Last active November 29, 2018 09:30
  • Star 2 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
Star You must be signed in to star a gist
What would you like to do?
// RingBuffer reads messages from in and writes them to out.
// Whenever out is full, it will remove the oldest message to make room.
// Adapted from
func RingBuffer(in <-chan Message, size int) <-chan Message {
out := make(chan Message, size)
go func() {
defer close(out)
for m := range in {
select {
case out <- m:
// If out is full, read a message from the end to make room.
select {
case <-out:
// Avoid a deadlock in case the buffer has since been drained.
out <- m
return out
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment