Skip to content

Instantly share code, notes, and snippets.

@taion809
Created April 20, 2023 04:35
Show Gist options
  • Save taion809/7ad1edb9b1b8111c849f7482e629ee2e to your computer and use it in GitHub Desktop.
Save taion809/7ad1edb9b1b8111c849f7482e629ee2e to your computer and use it in GitHub Desktop.
Simple ring buffer
package main
import (
"fmt"
"strings"
)
type Ring struct {
buffer []string
size int
readPtr int
writePtr int
}
func NewRing(size int) (*Ring, error) {
if size < 1 {
return nil, fmt.Errorf("Buffer size must be greater than 0")
}
return &Ring{buffer: make([]string, size), size: size}, nil
}
func (r *Ring) Add(c string) {
writePtr := r.writePtr
r.buffer[writePtr] = c
writePtr++
r.writePtr = writePtr % r.size
}
func (r *Ring) Read() string {
readPtr := r.readPtr
c := r.buffer[readPtr]
readPtr++
r.readPtr = readPtr % r.size
return c
}
func (r *Ring) Debug() string {
return fmt.Sprintf("buf: %v\nsize: %d\nread: %d\nwrite: %d\n", r.buffer, r.size, r.readPtr, r.writePtr)
}
func main() {
fmt.Println("Ring Buffer!")
ring, err := NewRing(32)
if err != nil {
fmt.Println(err)
return
}
str := strings.Split("Hello World!", "")
for _, s := range str {
ring.Add(s)
}
c := ring.Read()
buf := []string{}
for i := 0; i < 12; i++ {
buf = append(buf, c)
c = ring.Read()
}
fmt.Println(strings.Join(buf, ""))
fmt.Println(ring.Debug())
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment