1
0
mirror of https://github.com/golang/go synced 2024-11-26 05:07:59 -07:00

io: add an Err field to LimitedReader

Fixes #51115

Change-Id: I3c5296e4adc71c1c1b1808a45abd4801ae43465a
GitHub-Last-Rev: 4c197acd51
GitHub-Pull-Request: golang/go#51990
Reviewed-on: https://go-review.googlesource.com/c/go/+/396215
Reviewed-by: Dmitri Shuralyov <dmitshur@google.com>
TryBot-Result: Gopher Robot <gobot@golang.org>
Run-TryBot: Ian Lance Taylor <iant@google.com>
Run-TryBot: Ian Lance Taylor <iant@golang.org>
Auto-Submit: Ian Lance Taylor <iant@google.com>
Reviewed-by: Ian Lance Taylor <iant@google.com>
This commit is contained in:
Carl Johnson 2022-03-28 18:49:05 +00:00 committed by Gopher Robot
parent 037b209ae3
commit fd6ef06296
3 changed files with 26 additions and 5 deletions

1
api/next/51115.txt Normal file
View File

@ -0,0 +1 @@
pkg io, type LimitedReader struct, Err error #51115

View File

@ -6,6 +6,7 @@ package io_test
import (
"bytes"
"errors"
"fmt"
"io"
"log"
@ -283,3 +284,16 @@ func ExampleReadAll() {
// Output:
// Go is a general-purpose language designed with systems programming in mind.
}
func ExampleLimitedReader() {
r := strings.NewReader("some io.Reader stream to be read\n")
sentinel := errors.New("reached read limit")
lr := &io.LimitedReader{R: r, N: 4, Err: sentinel}
if _, err := io.Copy(os.Stdout, lr); err != sentinel {
log.Fatal(err)
}
// Output:
// some
}

View File

@ -455,20 +455,26 @@ func copyBuffer(dst Writer, src Reader, buf []byte) (written int64, err error) {
// LimitReader returns a Reader that reads from r
// but stops with EOF after n bytes.
// The underlying implementation is a *LimitedReader.
func LimitReader(r Reader, n int64) Reader { return &LimitedReader{r, n} }
func LimitReader(r Reader, n int64) Reader { return &LimitedReader{r, n, nil} }
// A LimitedReader reads from R but limits the amount of
// data returned to just N bytes. Each call to Read
// updates N to reflect the new amount remaining.
// Read returns EOF when N <= 0 or when the underlying R returns EOF.
// Read returns Err when N <= 0.
// If Err is nil, it returns EOF instead.
type LimitedReader struct {
R Reader // underlying reader
N int64 // max bytes remaining
R Reader // underlying reader
N int64 // max bytes remaining
Err error // error to return on reaching the limit
}
func (l *LimitedReader) Read(p []byte) (n int, err error) {
if l.N <= 0 {
return 0, EOF
err := l.Err
if err == nil {
err = EOF
}
return 0, err
}
if int64(len(p)) > l.N {
p = p[0:l.N]