Skip to content

Instantly share code, notes, and snippets.

@edrex
Last active November 29, 2018 09:30
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save edrex/5d4d15775318ce46e79fbf8f27eb085b to your computer and use it in GitHub Desktop.
Save edrex/5d4d15775318ce46e79fbf8f27eb085b to your computer and use it in GitHub Desktop.
// 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 https://blog.pivotal.io/labs/labs/a-concurrent-ring-buffer-for-go.
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:
default:
// If out is full, read a message from the end to make room.
select {
case <-out:
default:
// 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