Last active
September 9, 2022 07:58
-
-
Save tk42/59b950022ff1aebc3740991098f1eb0b to your computer and use it in GitHub Desktop.
RingBuffer
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
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) | |
} |
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
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) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Generics Rignbuffer
original from A channel-based ring buffer in Go
Go Playground