Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

push is now threadsafe #3

Open
wants to merge 1 commit into
base: main
Choose a base branch
from
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
17 changes: 9 additions & 8 deletions collections/ringbuffer/ringbuffer.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,16 +2,17 @@ package ringbuffer

import (
"fmt"
"sync/atomic"

armath "github.com/asymmetric-research/go-commons/math"
)

type T[C any] struct {
buflen uint
buflen uint64
buf []C

// head points to the next free slot
head uint
head uint64
}

func New[C any](size int) (*T[C], error) {
Expand All @@ -26,16 +27,16 @@ func NewInto[C any](dst *T[C], buf []C) error {
return fmt.Errorf("backing buffer must have a greater than zero")
}
*dst = T[C]{
buflen: uint(len(buf)),
buflen: uint64(len(buf)),
buf: buf,
head: 0,
}
return nil
}

func (r *T[C]) Push(item C) {
r.buf[r.head%r.buflen] = item
r.head += 1
off := atomic.AddUint64(&r.head, 1)
r.buf[(off-1)%r.buflen] = item
}

func (r *T[C]) Last(dst []C) int {
Expand Down Expand Up @@ -80,7 +81,7 @@ func (r *T[C]) Last(dst []C) int {
return n
}

func (r *T[C]) Len() uint {
func (r *T[C]) Len() uint64 {
used := armath.Min(r.buflen, r.head)
return used
}
Expand All @@ -92,8 +93,8 @@ const (
SEQ_MODE_FILO
)

func (r *T[C]) Seq(seqMode SeqMode) func(yield func(uint, C) bool) {
return func(yield func(uint, C) bool) {
func (r *T[C]) Seq(seqMode SeqMode) func(yield func(uint64, C) bool) {
return func(yield func(uint64, C) bool) {
if r.buflen == 0 {
return
}
Expand Down
Loading