Created
April 4, 2025 01:03
-
-
Save caelifer/c2351c1b67a9172de3a94b104930a46c to your computer and use it in GitHub Desktop.
Ring buffer implementation in Go
This file contains hidden or 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 | |
import ( | |
"fmt" | |
"log" | |
) | |
var ( | |
ErrClosedBuffer = fmt.Errorf("attempted to read from closed buffer") | |
) | |
type Ring struct { | |
queue chan byte | |
size int | |
} | |
func New(size int) *Ring { | |
return &Ring{ | |
queue: make(chan byte, size), | |
size: size, | |
} | |
} | |
func NewBuffer(buf []byte) *Ring { | |
rb := New(len(buf)) | |
for _, c := range buf { | |
rb.queue <- c | |
} | |
return rb | |
} | |
func (rb *Ring) Write(data []byte) (int, error) { | |
for _, c := range data { | |
rb.queue <- c | |
log.Printf("write: %q", string(c)) | |
} | |
return len(data), nil | |
} | |
func (rb *Ring) Read(data []byte) (int, error) { | |
l := len(data) | |
for i := 0; i < l; i++ { | |
select { | |
case c, ok := <-rb.queue: | |
if !ok { | |
return i, ErrClosedBuffer | |
} | |
data[i] = c | |
log.Printf("read: %q", string(c)) | |
default: | |
// Partial read | |
return i, nil | |
} | |
} | |
// Full read | |
return l, nil | |
} | |
func main() { | |
sig := make(chan any) | |
rb := New(8) | |
go func() { | |
rb.Write([]byte(text)) | |
}() | |
go func() { | |
var buf [256]byte | |
nText := len(text) | |
for { | |
n, err := rb.Read(buf[:]) | |
if err != nil { | |
log.Fatal(err) | |
} | |
nText -= n | |
if nText <= 0 { | |
break | |
} | |
} | |
close(sig) | |
}() | |
<-sig | |
} | |
var text = `Lorem ipsum dolor sit amet consectetur adipiscing elit. Quisque faucibus ex sapien vitae pellentesque sem placerat. In | |
id cursus mi pretium tellus duis convallis. Tempus leo eu aenean sed diam urna tempor. Pulvinar vivamus fringilla lacus nec metus | |
bibendum egestas. Iaculis massa nisl malesuada lacinia integer nunc posuere. Ut hendrerit semper vel class aptent taciti sociosqu. | |
Ad litora torquent per conubia nostra inceptos himenaeos.` |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
https://go.dev/play/p/SLDPNreDq3S
Output: