compress.go 1.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758
  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 (
  6. "bufio"
  7. "io"
  8. )
  9. type byteReader interface {
  10. io.Reader
  11. io.ByteReader
  12. }
  13. // unpackBits decodes the PackBits-compressed data in src and returns the
  14. // uncompressed data.
  15. //
  16. // The PackBits compression format is described in section 9 (p. 42)
  17. // of the TIFF spec.
  18. func unpackBits(r io.Reader) ([]byte, error) {
  19. buf := make([]byte, 128)
  20. dst := make([]byte, 0, 1024)
  21. br, ok := r.(byteReader)
  22. if !ok {
  23. br = bufio.NewReader(r)
  24. }
  25. for {
  26. b, err := br.ReadByte()
  27. if err != nil {
  28. if err == io.EOF {
  29. return dst, nil
  30. }
  31. return nil, err
  32. }
  33. code := int(int8(b))
  34. switch {
  35. case code >= 0:
  36. n, err := io.ReadFull(br, buf[:code+1])
  37. if err != nil {
  38. return nil, err
  39. }
  40. dst = append(dst, buf[:n]...)
  41. case code == -128:
  42. // No-op.
  43. default:
  44. if b, err = br.ReadByte(); err != nil {
  45. return nil, err
  46. }
  47. for j := 0; j < 1-code; j++ {
  48. buf[j] = b
  49. }
  50. dst = append(dst, buf[:1-code]...)
  51. }
  52. }
  53. }