github.com/jmigpin/editor@v1.6.0/util/iout/iorw/limitedreader.go (about)

     1  package iorw
     2  
     3  import (
     4  	"fmt"
     5  	"io"
     6  )
     7  
     8  type LimitedReaderAt struct {
     9  	ReaderAt
    10  	min, max int
    11  }
    12  
    13  // min<=max; allows arguments min<0 && max>length
    14  func NewLimitedReaderAt(r ReaderAt, min, max int) *LimitedReaderAt {
    15  	if min > max {
    16  		//panic(fmt.Sprintf("bad min/max: %v>%v", min, max))
    17  		max = min
    18  	}
    19  	return &LimitedReaderAt{r, min, max}
    20  }
    21  
    22  func NewLimitedReaderAtPad(r ReaderAt, min, max, pad int) *LimitedReaderAt {
    23  	return NewLimitedReaderAt(r, min-pad, max+pad)
    24  }
    25  
    26  //----------
    27  
    28  func (r *LimitedReaderAt) ReadFastAt(i, n int) ([]byte, error) {
    29  	if i < r.min {
    30  		return nil, fmt.Errorf("limited index: %v<%v: %w", i, r.min, io.EOF)
    31  	}
    32  	if i+n > r.max {
    33  		if i > r.max {
    34  			return nil, fmt.Errorf("limited index: %v>%v: %w", i, r.max, io.EOF)
    35  		}
    36  		// n>0, there is data to read
    37  		n = r.max - i
    38  	}
    39  	return r.ReaderAt.ReadFastAt(i, n)
    40  }
    41  
    42  func (r *LimitedReaderAt) Min() int {
    43  	u := r.ReaderAt.Min()
    44  	if u > r.min {
    45  		return u
    46  	}
    47  	return r.min
    48  }
    49  
    50  func (r *LimitedReaderAt) Max() int {
    51  	u := r.ReaderAt.Max()
    52  	if u < r.max {
    53  		return u
    54  	}
    55  	return r.max
    56  }