2022-01-24 23:21:48 +03:00
|
|
|
package bitio
|
|
|
|
|
|
|
|
import (
|
|
|
|
"io"
|
|
|
|
)
|
|
|
|
|
2022-02-09 03:22:51 +03:00
|
|
|
// LimitReader is a bitio.Reader that reads a limited amount of bits from a bitio.Reader.
|
|
|
|
// Similar to bytes.LimitedReader.
|
2022-01-24 23:21:48 +03:00
|
|
|
type LimitReader struct {
|
|
|
|
r Reader
|
|
|
|
n int64
|
|
|
|
}
|
|
|
|
|
2022-02-09 03:22:51 +03:00
|
|
|
// NewLimitReader returns a new bitio.LimitReader.
|
2022-02-05 18:52:22 +03:00
|
|
|
func NewLimitReader(r Reader, n int64) *LimitReader { return &LimitReader{r, n} }
|
|
|
|
|
2022-01-24 23:21:48 +03:00
|
|
|
func (l *LimitReader) ReadBits(p []byte, nBits int64) (n int64, err error) {
|
|
|
|
if l.n <= 0 {
|
|
|
|
return 0, io.EOF
|
|
|
|
}
|
|
|
|
if nBits > l.n {
|
|
|
|
nBits = l.n
|
|
|
|
}
|
|
|
|
n, err = l.r.ReadBits(p, nBits)
|
|
|
|
l.n -= n
|
|
|
|
return n, err
|
|
|
|
}
|
2022-05-28 14:04:04 +03:00
|
|
|
|
|
|
|
func (l *LimitReader) CloneReader() (Reader, error) {
|
|
|
|
rc, err := CloneReader(l.r)
|
|
|
|
if err != nil {
|
|
|
|
return nil, err
|
|
|
|
}
|
|
|
|
return &LimitReader{r: rc, n: l.n}, nil
|
|
|
|
}
|