buffer.go 1.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869
  1. // Copyright 2011 The Go Authors. All rights reserved.
  2. // Use of this source code is governed by a BSD-style
  3. // license that can be found in the LICENSE file.
  4. package tiff
  5. import "io"
  6. // buffer buffers an io.Reader to satisfy io.ReaderAt.
  7. type buffer struct {
  8. r io.Reader
  9. buf []byte
  10. }
  11. // fill reads data from b.r until the buffer contains at least end bytes.
  12. func (b *buffer) fill(end int) error {
  13. m := len(b.buf)
  14. if end > m {
  15. if end > cap(b.buf) {
  16. newcap := 1024
  17. for newcap < end {
  18. newcap *= 2
  19. }
  20. newbuf := make([]byte, end, newcap)
  21. copy(newbuf, b.buf)
  22. b.buf = newbuf
  23. } else {
  24. b.buf = b.buf[:end]
  25. }
  26. if n, err := io.ReadFull(b.r, b.buf[m:end]); err != nil {
  27. end = m + n
  28. b.buf = b.buf[:end]
  29. return err
  30. }
  31. }
  32. return nil
  33. }
  34. func (b *buffer) ReadAt(p []byte, off int64) (int, error) {
  35. o := int(off)
  36. end := o + len(p)
  37. if int64(end) != off+int64(len(p)) {
  38. return 0, io.ErrUnexpectedEOF
  39. }
  40. err := b.fill(end)
  41. return copy(p, b.buf[o:end]), err
  42. }
  43. // Slice returns a slice of the underlying buffer. The slice contains
  44. // n bytes starting at offset off.
  45. func (b *buffer) Slice(off, n int) ([]byte, error) {
  46. end := off + n
  47. if err := b.fill(end); err != nil {
  48. return nil, err
  49. }
  50. return b.buf[off:end], nil
  51. }
  52. // newReaderAt converts an io.Reader into an io.ReaderAt.
  53. func newReaderAt(r io.Reader) io.ReaderAt {
  54. if ra, ok := r.(io.ReaderAt); ok {
  55. return ra
  56. }
  57. return &buffer{
  58. r: r,
  59. buf: make([]byte, 0, 1024),
  60. }
  61. }