package utils

import (
	"agent/defines/derrs"
	"io"
)

func NewStrictLimitReader(r io.Reader, n int64) io.Reader { return &StrictLimitedReader{r, n} }

type StrictLimitedReader struct {
	R io.Reader
	N int64
}

func (r *StrictLimitedReader) Read(p []byte) (n int, err error) {
	if r.N <= 0 {
		return 0, io.EOF
	}
	if int64(len(p)) > r.N {
		p = p[0:r.N]
	}

	n, err = r.R.Read(p)
	r.N -= int64(n)

	if err == io.EOF && r.N > 0 {
		return n, derrs.NewReadError("unexpected EOF")
	}

	return n, err
}
