Last active
November 29, 2018 09:30
-
-
Save edrex/5d4d15775318ce46e79fbf8f27eb085b to your computer and use it in GitHub Desktop.
This file contains 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
// 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