// Copyright 2011 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.

package tiff

import (
	
	
)

type byteReader interface {
	io.Reader
	io.ByteReader
}

// unpackBits decodes the PackBits-compressed data in src and returns the
// uncompressed data. The output size is limited to lim bytes to prevent
// decompression bombs.
//
// The PackBits compression format is described in section 9 (p. 42)
// of the TIFF spec.
func unpackBits( io.Reader,  int64) ([]byte, error) {
	 := make([]byte, 128)
	 := make([]byte, 0, 1024)
	,  := .(byteReader)
	if ! {
		 = bufio.NewReader()
	}

	for {
		,  := .ReadByte()
		if  != nil {
			if  == io.EOF {
				return , nil
			}
			return nil, 
		}
		 := int(int8())
		switch {
		case  >= 0:
			,  := io.ReadFull(, [:+1])
			if  != nil {
				return nil, 
			}
			 = append(, [:]...)
		case  == -128:
			// No-op.
		default:
			if ,  = .ReadByte();  != nil {
				return nil, 
			}
			for  := 0;  < 1-; ++ {
				[] = 
			}
			 = append(, [:1-]...)
		}
		if int64(len()) >  {
			return nil, FormatError("PackBits: decompressed data too large")
		}
	}
}