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.
5 // Package lzw implements the Lempel-Ziv-Welch compressed data format,
6 // described in T. A. Welch, ``A Technique for High-Performance Data
7 // Compression'', Computer, 17(6) (June 1984), pp 8-19.
9 // In particular, it implements LZW as used by the GIF and PDF file
10 // formats, which means variable-width codes up to 12 bits and the first
11 // two non-literal codes are a clear code and an EOF code.
13 // The TIFF file format uses a similar but incompatible version of the LZW
14 // algorithm. See the golang.org/x/image/tiff/lzw package for an
18 // TODO(nigeltao): check that PDF uses LZW in the same way as GIF,
19 // modulo LSB/MSB packing order.
28 // Order specifies the bit ordering in an LZW data stream.
32 // LSB means Least Significant Bits first, as used in the GIF file format.
34 // MSB means Most Significant Bits first, as used in the TIFF and PDF
41 decoderInvalidCode
= 0xffff
42 flushBuffer
= 1 << maxWidth
45 // Reader is an io.Reader which can be used to read compressed data in the
52 read
func(*Reader
) (uint16, error
) // readLSB or readMSB
53 litWidth
int // width in bits of literal codes
56 // The first 1<<litWidth codes are literal codes.
57 // The next two codes mean clear and EOF.
58 // Other valid codes are in the range [lo, hi] where lo := clear + 2,
59 // with the upper bound incrementing on each code seen.
61 // overflow is the code at which hi overflows the code width. It always
64 // last is the most recently seen code, or decoderInvalidCode.
66 // An invariant is that hi < overflow.
67 clear
, eof
, hi
, overflow
, last
uint16
69 // Each code c in [lo, hi] expands to two or more bytes. For c != hi:
70 // suffix[c] is the last of these bytes.
71 // prefix[c] is the code for all but the last byte.
72 // This code can either be a literal code or another code in [lo, c).
73 // The c == hi case is a special case.
74 suffix
[1 << maxWidth
]uint8
75 prefix
[1 << maxWidth
]uint16
77 // output is the temporary output buffer.
78 // Literal codes are accumulated from the start of the buffer.
79 // Non-literal codes decode to a sequence of suffixes that are first
80 // written right-to-left from the end of the buffer before being copied
81 // to the start of the buffer.
82 // It is flushed when it contains >= 1<<maxWidth bytes,
83 // so that there is always room to decode an entire code.
84 output
[2 * 1 << maxWidth
]byte
85 o
int // write index into output
86 toRead
[]byte // bytes to return from Read
89 // readLSB returns the next code for "Least Significant Bits first" data.
90 func (r
*Reader
) readLSB() (uint16, error
) {
91 for r
.nBits
< r
.width
{
92 x
, err
:= r
.r
.ReadByte()
96 r
.bits |
= uint32(x
) << r
.nBits
99 code
:= uint16(r
.bits
& (1<<r
.width
- 1))
105 // readMSB returns the next code for "Most Significant Bits first" data.
106 func (r
*Reader
) readMSB() (uint16, error
) {
107 for r
.nBits
< r
.width
{
108 x
, err
:= r
.r
.ReadByte()
112 r
.bits |
= uint32(x
) << (24 - r
.nBits
)
115 code
:= uint16(r
.bits
>> (32 - r
.width
))
121 // Read implements io.Reader, reading uncompressed bytes from its underlying Reader.
122 func (r
*Reader
) Read(b
[]byte) (int, error
) {
124 if len(r
.toRead
) > 0 {
125 n
:= copy(b
, r
.toRead
)
126 r
.toRead
= r
.toRead
[n
:]
136 // decode decompresses bytes from r and leaves them in d.toRead.
137 // read specifies how to decode bytes into codes.
138 // litWidth is the width in bits of literal codes.
139 func (r
*Reader
) decode() {
140 // Loop over the code stream, converting codes into decompressed bytes.
143 code
, err
:= r
.read(r
)
146 err
= io
.ErrUnexpectedEOF
153 // We have a literal code.
154 r
.output
[r
.o
] = uint8(code
)
156 if r
.last
!= decoderInvalidCode
{
157 // Save what the hi code expands to.
158 r
.suffix
[r
.hi
] = uint8(code
)
159 r
.prefix
[r
.hi
] = r
.last
161 case code
== r
.clear
:
162 r
.width
= 1 + uint(r
.litWidth
)
164 r
.overflow
= 1 << r
.width
165 r
.last
= decoderInvalidCode
171 c
, i
:= code
, len(r
.output
)-1
172 if code
== r
.hi
&& r
.last
!= decoderInvalidCode
{
173 // code == hi is a special case which expands to the last expansion
174 // followed by the head of the last expansion. To find the head, we walk
175 // the prefix chain until we find a literal code.
180 r
.output
[i
] = uint8(c
)
184 // Copy the suffix chain into output and then write that to w.
186 r
.output
[i
] = r
.suffix
[c
]
190 r
.output
[i
] = uint8(c
)
191 r
.o
+= copy(r
.output
[r
.o
:], r
.output
[i
:])
192 if r
.last
!= decoderInvalidCode
{
193 // Save what the hi code expands to.
194 r
.suffix
[r
.hi
] = uint8(c
)
195 r
.prefix
[r
.hi
] = r
.last
198 r
.err
= errors
.New("lzw: invalid code")
201 r
.last
, r
.hi
= code
, r
.hi
+1
202 if r
.hi
>= r
.overflow
{
203 if r
.hi
> r
.overflow
{
206 if r
.width
== maxWidth
{
207 r
.last
= decoderInvalidCode
208 // Undo the d.hi++ a few lines above, so that (1) we maintain
209 // the invariant that d.hi < d.overflow, and (2) d.hi does not
210 // eventually overflow a uint16.
214 r
.overflow
= 1 << r
.width
217 if r
.o
>= flushBuffer
{
221 // Flush pending output.
222 r
.toRead
= r
.output
[:r
.o
]
226 var errClosed
= errors
.New("lzw: reader/writer is closed")
228 // Close closes the Reader and returns an error for any future read operation.
229 // It does not close the underlying io.Reader.
230 func (r
*Reader
) Close() error
{
231 r
.err
= errClosed
// in case any Reads come along
235 // Reset clears the Reader's state and allows it to be reused again
237 func (r
*Reader
) Reset(src io
.Reader
, order Order
, litWidth
int) {
239 r
.init(src
, order
, litWidth
)
242 // NewReader creates a new io.ReadCloser.
243 // Reads from the returned io.ReadCloser read and decompress data from r.
244 // If r does not also implement io.ByteReader,
245 // the decompressor may read more data than necessary from r.
246 // It is the caller's responsibility to call Close on the ReadCloser when
248 // The number of bits to use for literal codes, litWidth, must be in the
249 // range [2,8] and is typically 8. It must equal the litWidth
250 // used during compression.
252 // It is guaranteed that the underlying type of the returned io.ReadCloser
254 func NewReader(r io
.Reader
, order Order
, litWidth
int) io
.ReadCloser
{
255 return newReader(r
, order
, litWidth
)
258 func newReader(src io
.Reader
, order Order
, litWidth
int) *Reader
{
260 r
.init(src
, order
, litWidth
)
264 func (r
*Reader
) init(src io
.Reader
, order Order
, litWidth
int) {
267 r
.read
= (*Reader
).readLSB
269 r
.read
= (*Reader
).readMSB
271 r
.err
= errors
.New("lzw: unknown order")
274 if litWidth
< 2 ||
8 < litWidth
{
275 r
.err
= fmt
.Errorf("lzw: litWidth %d out of range", litWidth
)
279 br
, ok
:= src
.(io
.ByteReader
)
280 if !ok
&& src
!= nil {
281 br
= bufio
.NewReader(src
)
284 r
.litWidth
= litWidth
285 r
.width
= 1 + uint(litWidth
)
286 r
.clear
= uint16(1) << uint(litWidth
)
287 r
.eof
, r
.hi
= r
.clear
+1, r
.clear
+1
288 r
.overflow
= uint16(1) << r
.width
289 r
.last
= decoderInvalidCode