1
0
mirror of https://github.com/golang/go synced 2024-11-11 19:51:37 -07:00

io: add an Err field to LimitedReader

Fixes #51115
This commit is contained in:
Carl Johnson 2022-03-28 14:17:52 -04:00
parent 0652274c10
commit 4c197acd51
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]