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

Add Len and Capacity methods for ring buffer #321

Open
wants to merge 1 commit into
base: master
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
10 changes: 10 additions & 0 deletions buffer/ring_growing.go
Original file line number Diff line number Diff line change
Expand Up @@ -70,3 +70,13 @@ func (r *RingGrowing) WriteOne(data interface{}) {
r.data[(r.readable+r.beg)%r.n] = data
r.readable++
}

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

does anything ever shrink this buffer?

Copy link
Author

@xigang xigang Dec 18, 2024

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@liggitt No, this ring buffer implementation (RingGrowing) only grows and never shrinks. Looking at the code:

  1. The buffer starts with an initialSize specified in NewRingGrowing.
  2. When the buffer becomes full (r.readable == r.n), the WriteOne method doubles the size (newN := r.n * 2).
  3. There are no methods that reduce the size of the buffer.

If shrinking capability is needed, a method can be added to shrink the buffer when it becomes too empty (for example, when readability falls below a certain threshold, such as 25% of the capacity).

Thank you, liggitt, for reviewing the code.:)

// Len returns the number of items in the buffer.
func (r *RingGrowing) Len() int {
return r.readable
}

// Capacity returns the capacity of the buffer.
func (r *RingGrowing) Capacity() int {
return r.n
}