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

proposal: bufio: add (*reader).ResetWithSize to initialize as fields and use with Peek #61146

Open
Jorropo opened this issue Jul 2, 2023 · 1 comment
Labels
Milestone

Comments

@Jorropo
Copy link
Member

Jorropo commented Jul 2, 2023

I would like to embed the bufio as reader in my fields to avoid pointers to pointers, reduce allocations and memory used:

 type mything struct{
  someStuff thisIsSomeStuff
- reader *bufio.Reader
+ reader bufio.Reader
 }

This is doable by calling thing.reader.Reset(r) however I also need to use (*reader).Peek but I can't specify the size.
So instead I write: thing.reader = *bufio.NewReaderWithSize(r, maximumBlockSize) which feels wrong.

Proposal:

// ResetWithSize is like [Reset] but it will allocate a new buffer if the current buffer is smaller than required.
func (*Reader) ResetWithSize(r io.Reader, size int)

Potential implementation:

// ResetWithSize is like [Reset] but it will allocate a new buffer if the current buffer is smaller than required.
func (b *Reader) ResetWithSize(r io.Reader, size int) {
 if len(b.buf) < size {
  b.buf = make([]byte, size)
 }
 b.reset(r)
}
@gopherbot gopherbot added this to the Proposal milestone Jul 2, 2023
@bcmills
Copy link
Contributor

bcmills commented Jul 5, 2023

It does seem strange that Reset allocates a new buffer but hard-codes defaultBufSize. 🤔

I wonder if it would be better to provide a more general Resize(size int) method, with the constraint that the new size must be less than or equal to the number of bytes already buffered (as reported by Buffered). It seems like that would work equally well for this use-case, and may address others as well.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Projects
Status: Incoming
Development

No branches or pull requests

3 participants