rangereader.go 855 B

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