Skip to content

Conversation

@austinderek
Copy link

Add an Err field to LimitedReader that allows callers to return a
custom error when the read limit is exceeded, instead of always
returning EOF.

When Err is set to a non-nil, and the limit is reached,
LimitedReader.Read probes the underlying reader with a 1-byte
read to distinguish two cases: stream had exactly N bytes
(returns EOF), or stream has more data. The probe result is cached
using negative N values to avoid repeated reads.

When Err is nil, Read returns EOF, maintaining backward compatibility.
Zero-length reads return (0, nil) without side effects when we
reached end of Reader.

Fixes golang#51115


🔄 This is a mirror of upstream PR golang#76156

Add an Err field to LimitedReader that allows callers to return a
custom error when the read limit is exceeded, instead of always
returning EOF.

When Err is set to a non-nil, non-EOF value, and the limit is
reached, LimitedReader.Read probes the underlying reader with a
1-byte read to distinguish two cases: stream had exactly N bytes
(returns EOF), or stream has more data (returns the custom Err).
The probe result is cached using negative N values to avoid
repeated reads.

When Err is nil or EOF, Read returns EOF, maintaining backward
compatibility. Zero-length reads return (0, nil) without side
effects.

Fixes golang#51115
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants