Skip to content

Instantly share code, notes, and snippets.

@tk42
Last active September 9, 2022 07:58
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save tk42/59b950022ff1aebc3740991098f1eb0b to your computer and use it in GitHub Desktop.
Save tk42/59b950022ff1aebc3740991098f1eb0b to your computer and use it in GitHub Desktop.
RingBuffer
package main
type RingBuffer[T any] struct {
inputChannel <-chan T
outputChannel chan T
}
func NewRingBuffer[T any](inputChannel <-chan T, outputChannel chan T) *RingBuffer[T] {
return &RingBuffer[T]{inputChannel, outputChannel}
}
func (r *RingBuffer[T]) Run() {
for v := range r.inputChannel {
select {
case r.outputChannel <- v:
default:
<-r.outputChannel
r.outputChannel <- v
}
}
close(r.outputChannel)
}
func main() {
in := make(chan int)
out := make(chan int, 5)
rb := NewRingBuffer(in, out)
go rb.Run()
for i := 0; i < 10; i++ {
in <- i
}
close(in)
for res := range out {
fmt.Println(res)
}
}
@tk42
Copy link
Author

tk42 commented Sep 7, 2022

Generics Rignbuffer

original from A channel-based ring buffer in Go

Go Playground

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment