mirror of
https://github.com/AdguardTeam/AdGuardHome.git
synced 2024-11-28 18:08:51 +03:00
ea8950a80d
Squashed commit of the following: commit 5345a14b3565f358c56a37500cafb35b7e397951 Author: Eugene Burkov <E.Burkov@AdGuard.COM> Date: Thu Oct 21 21:13:06 2021 +0300 all: fix windows tests commit 8b9cdbe3e78f43339d21277f04e686bb154f6968 Author: Eugene Burkov <E.Burkov@AdGuard.COM> Date: Thu Oct 21 20:23:55 2021 +0300 all: imp code commit 271fdbe74c29d8ea4b53d7f56d2a36612dfed7b3 Author: Eugene Burkov <E.Burkov@AdGuard.COM> Date: Thu Oct 21 19:43:32 2021 +0300 all: imp testing commit e340f9d48679c57fc8eb579b8b78d4957be111c4 Author: Eugene Burkov <E.Burkov@AdGuard.COM> Date: Thu Oct 21 18:53:51 2021 +0300 all: use testutil
59 lines
1.2 KiB
Go
59 lines
1.2 KiB
Go
// Package aghio contains extensions for io package's types and methods
|
|
package aghio
|
|
|
|
import (
|
|
"fmt"
|
|
"io"
|
|
)
|
|
|
|
// LimitReachedError records the limit and the operation that caused it.
|
|
type LimitReachedError struct {
|
|
Limit int64
|
|
}
|
|
|
|
// Error implements the error interface for LimitReachedError.
|
|
//
|
|
// TODO(a.garipov): Think about error string format.
|
|
func (lre *LimitReachedError) Error() string {
|
|
return fmt.Sprintf("attempted to read more than %d bytes", lre.Limit)
|
|
}
|
|
|
|
// limitedReader is a wrapper for io.Reader with limited reader and dealing with
|
|
// errors package.
|
|
type limitedReader struct {
|
|
r io.Reader
|
|
limit int64
|
|
n int64
|
|
}
|
|
|
|
// Read implements Reader interface.
|
|
func (lr *limitedReader) Read(p []byte) (n int, err error) {
|
|
if lr.n == 0 {
|
|
return 0, &LimitReachedError{
|
|
Limit: lr.limit,
|
|
}
|
|
}
|
|
|
|
if int64(len(p)) > lr.n {
|
|
p = p[0:lr.n]
|
|
}
|
|
|
|
n, err = lr.r.Read(p)
|
|
lr.n -= int64(n)
|
|
|
|
return n, err
|
|
}
|
|
|
|
// LimitReader wraps Reader to make it's Reader stop with ErrLimitReached after
|
|
// n bytes read.
|
|
func LimitReader(r io.Reader, n int64) (limited io.Reader, err error) {
|
|
if n < 0 {
|
|
return nil, fmt.Errorf("aghio: invalid n in LimitReader: %d", n)
|
|
}
|
|
|
|
return &limitedReader{
|
|
r: r,
|
|
limit: n,
|
|
n: n,
|
|
}, nil
|
|
}
|