rangereader.go 658 B

12345678910111213141516171819202122232425262728293031323334353637383940414243
  1. package filex
  2. import (
  3. "errors"
  4. "os"
  5. )
  6. type RangeReader struct {
  7. file *os.File
  8. start int64
  9. stop int64
  10. }
  11. func NewRangeReader(file *os.File, start, stop int64) *RangeReader {
  12. return &RangeReader{
  13. file: file,
  14. start: start,
  15. stop: stop,
  16. }
  17. }
  18. func (rr *RangeReader) Read(p []byte) (n int, err error) {
  19. stat, err := rr.file.Stat()
  20. if err != nil {
  21. return 0, err
  22. }
  23. if rr.stop < rr.start || rr.start >= stat.Size() {
  24. return 0, errors.New("exceed file size")
  25. }
  26. if rr.stop-rr.start < int64(len(p)) {
  27. p = p[:rr.stop-rr.start]
  28. }
  29. n, err = rr.file.ReadAt(p, rr.start)
  30. if err != nil {
  31. return n, err
  32. }
  33. rr.start += int64(n)
  34. return
  35. }