File: limitread.go

package info (click to toggle)
golang-github-hlandau-goutils 0.0~git20160722.0.0cdb66a-2
  • links: PTS, VCS
  • area: main
  • in suites: stretch, stretch-backports
  • size: 156 kB
  • ctags: 107
  • sloc: makefile: 2
file content (39 lines) | stat: -rw-r--r-- 922 bytes parent folder | download | duplicates (4)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
package net

import (
	"errors"
	"io"
)

type limitReader struct {
	r         io.Reader
	remaining int
}

// Error returned if the number of bytes read from a LimitReader exceeds the
// limit.
var ErrLimitExceeded = errors.New("reader size limit exceeded")

func (lr *limitReader) Read(b []byte) (int, error) {
	n, err := lr.r.Read(b)
	lr.remaining = lr.remaining - n
	if lr.remaining < 0 {
		err = ErrLimitExceeded
	}

	return n, err
}

// Creates a limit reader. This is similar to io.LimitReader, except that if
// more than limit bytes are read from the stream, an error is returned rather
// than EOF. Thus, accidental truncation of oversized byte streams is avoided
// in favour of a hard error.
//
// Returns ErrLimitExceeded once more than limit bytes are read. The read
// operation still occurs.
func LimitReader(r io.Reader, limit int) io.Reader {
	return &limitReader{
		r:         r,
		remaining: limit,
	}
}