Skip to content

Commit

Permalink
zero removed elements
Browse files Browse the repository at this point in the history
  • Loading branch information
vgough committed Jun 10, 2024
1 parent 7354003 commit 5d45cd9
Show file tree
Hide file tree
Showing 2 changed files with 10 additions and 5 deletions.
4 changes: 4 additions & 0 deletions Taskfile.yml
Original file line number Diff line number Diff line change
Expand Up @@ -11,3 +11,7 @@ tasks:
cmds:
- go test -fuzz=Fuzz -fuzztime 30s .

bench:
desc: Run benchmarks.
cmds:
- go test -bench=. -benchmem
11 changes: 6 additions & 5 deletions ring.go
Original file line number Diff line number Diff line change
Expand Up @@ -41,13 +41,14 @@ func (r *Ring[T]) PushBack(e T) bool {
// PopFront removes and returns the first element in the ring.
// If the ring is empty, it returns false.
func (r *Ring[T]) PopFront() (T, bool) {
var zero T
// right-hand side always contains the first element.
if len(r.right) == 0 {
var zero T
return zero, false
}

el := r.right[0]
r.right[0] = zero
r.right = r.right[1:]
if cap(r.right) == 0 {
// right side is exhausted, so what was the left is now the right.
Expand All @@ -68,8 +69,8 @@ func (r *Ring[T]) PopIndex(i int) (T, bool) {
if i == 0 {
return r.PopFront()
}
var zero T
if i < 0 || i >= r.Len() {
var zero T
return zero, false
}

Expand All @@ -79,6 +80,7 @@ func (r *Ring[T]) PopIndex(i int) (T, bool) {
// and the start of the left are adjacent (modulo ring size).
el := r.left[idx]
copy(r.left[idx:], r.left[idx+1:])
r.left[len(r.left)-1] = zero
r.left = r.left[:len(r.left)-1]
return el, true
}
Expand All @@ -89,6 +91,7 @@ func (r *Ring[T]) PopIndex(i int) (T, bool) {
el := r.right[i]
updated := r.right[1:]
copy(updated, r.right[:i])
r.right[0] = zero
r.right = updated
return el, true
}
Expand Down Expand Up @@ -136,10 +139,8 @@ func (r *Ring[T]) Cap() int {
// It returns the number of elements copied.
// This does not consume elements from the ring.
func (r *Ring[T]) Copy(out []T) int {
n := min(len(out), r.Len())
idx := copy(out, r.right)
copy(out[idx:], r.left)
return n
return idx + copy(out[idx:], r.left)
}

// Reset removes all elements from the ring.
Expand Down

0 comments on commit 5d45cd9

Please sign in to comment.