Open
Description
Proposal Details
Add a Peek
method to bytes.Buffer
to avoid unnecessary wrapping when passing a buffer to image.Decode
.
package bytes
// Peek returns the next n bytes without advancing the buffer.
// If there are fewer than n bytes in the buffer, it returns error [io.EOF].
// The slice is only valid until the next buffer modification.
func (b *Buffer) Peek(n int) ([]byte, error)
See:
Metadata
Metadata
Assignees
Labels
Type
Projects
Status
Incoming
Activity
bytes: add Buffer.Peek
gopherbot commentedon May 20, 2025
Change https://go.dev/cl/674415 mentions this issue:
bytes: add Buffer.Peek
gabyhelp commentedon May 20, 2025
Related Issues
Related Code Changes
(Emoji vote if this was helpful or unhelpful; more detailed feedback welcome in this discussion.)
bytes: add Buffer.Peek
CAFxX commentedon May 20, 2025
Or maybe we can just add something like this?
bufio already imports bytes anyway.
Alternatively you could just do the same when passing the *bytes.Buffer...
apparentlymart commentedon May 20, 2025
I think this functionality makes sense, but I was initially confused between this and the existing
Buffer.AvailableBuffer
method, since the noun "buffer" is representing all sorts of different things here!In retrospect I guess I might've named
Buffer.AvailableBuffer
asBuffer.ExtraCapacity
instead, to distinguish more strongly between the active part of the buffer and its tail of unused additional capacity.But since that ship has already sailed, perhaps this can be addressed with just some careful wording in the documentation, possibly including an analogy to
Buffer.Read
.Thinking down that path made me also wonder about a slightly different behavior:
n
bytes of the buffer or the entire buffer (whichever is shortest) and no error.io.EOF
.This definition makes it more directly analogous to
Read
, such that it could potentially be defined as "Like Buffer.Read, except that it does not advance the buffer's read position.".That would make it slightly different than the current
reader.Peek
inpackage image
, but it seems like the code that uses it would tolerate a "short peek" already:go/src/image/format.go
Lines 59 to 69 in c8bf388
(the
if len(magic) != len(b)
branch handles that case)icholy commentedon Jun 2, 2025
Related to: #63548
dsnet commentedon Jun 3, 2025
A user could inject the
Peek
method themselves, but I think this is pointing to the fact that we should codify something like #63548. TIL I learned that the "image" package had functionality done that.