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, 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


🔄 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
@austinderek austinderek force-pushed the master branch 29 times, most recently from 34fec51 to c37e118 Compare November 4, 2025 06:04
@austinderek austinderek force-pushed the master branch 2 times, most recently from 0e1bd8b to c37e118 Compare November 5, 2025 04:04
@austinderek austinderek force-pushed the master branch 26 times, most recently from 9f3a108 to c37e118 Compare November 5, 2025 17:03
@austinderek austinderek closed this Nov 5, 2025
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