Debian Codegraph @

lzw/writer.go

raw
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
5 package lzw
6
7 import (
8 "encoding/binary"
9 "errors"
10 "fmt"
11 "io"
12
13 "github.com/klauspost/compress/internal/regmask"
14 )
15
16 // A writer is a buffered, flushable writer. Such a destination did its own
17 // buffering back when this package wrote to it a byte at a time, and Close
18 // flushes it for compatibility with that.
19 type writer interface {
20 io.ByteWriter
21 Flush() error
22 }
23
24 const (
25 // A code is a 12 bit value, stored as a uint32 when encoding to avoid
26 // type conversions when shifting bits.
27 maxCode = 1<<12 - 1
28 invalidCode = 1<<32 - 1
29 // There are 1<<12 possible codes, which is an upper bound on the number of
30 // valid hash table entries at any given point in time. tableSize is 4x that.
31 tableBits = 12 + 2
32 tableSize = 1 << tableBits
33 tableMask = tableSize - 1
34 // hashMul spreads the 20 bit keys over the table by Fibonacci hashing: the
35 // top tableBits of the product are taken. Folding the key onto itself
36 // instead clusters badly when the input uses few distinct byte values,
37 // since then only a few of the low bits of a key ever vary.
38 hashMul = 0x9E3779B1
39 // A hash table entry is a uint32. Zero is an invalid entry since the
40 // lower 12 bits of a valid entry must be a non-literal code.
41 invalidEntry = 0
42 // outFlush is the number of pending output bytes at which the output buffer
43 // is written out. Codes are added to it eight bytes at a time, so it has
44 // room for that much beyond outFlush.
45 outFlush = 4096
46 outSize = outFlush + 8
47 )
48
49 // Writer is an LZW compressor. It writes the compressed form of the data
50 // to an underlying writer (see [NewWriter]).
51 type Writer struct {
52 // w is the writer that compressed bytes are written to.
53 w io.Writer
54 // litWidth is the width in bits of literal codes.
55 litWidth uint
56 // order, bits, nBits and width are the state for converting a code stream
57 // into a byte stream. bits holds nBits bits not yet written out, at the
58 // bottom of the word for LSB and at the top for MSB.
59 order Order
60 nBits uint
61 width uint
62 bits uint64
63 // hi is the code implied by the next code emission.
64 // overflow is the code at which hi overflows the code width.
65 hi, overflow uint32
66 // savedCode is the accumulated code at the end of the most recent Write
67 // call. It is equal to invalidCode if there was no such call.
68 savedCode uint32
69 // err is the first error encountered during writing. Closing the writer
70 // will make any future Write calls return errClosed
71 err error
72 // n is the number of bytes of out that are pending.
73 n int
74 out [outSize]byte
75 // table is the hash table from 20-bit keys to 12-bit values. Each table
76 // entry contains key<<12|val and collisions resolve by linear probing.
77 // The keys consist of a 12-bit code prefix and an 8-bit byte suffix.
78 // The values are a 12-bit code.
79 table [tableSize]uint32
80 }
81
82 // emit writes the code c to the output buffer, flushing it if it has filled up.
83 func (w *Writer) emit(c uint32) error {
84 // Whole bytes are taken from the accumulator into out. The store always
85 // writes eight bytes, of which only the whole bytes are kept: the rest are
86 // overwritten by the next code.
87 if w.order == MSB {
88 w.bits |= uint64(c) << ((64 - w.width - w.nBits) & regmask.Shift64ByUint)
89 w.nBits += w.width
90 binary.BigEndian.PutUint64(w.out[w.n:], w.bits)
91 w.bits <<= (w.nBits & ^uint(7)) & regmask.Shift64ByUint
92 } else {
93 w.bits |= uint64(c) << (w.nBits & regmask.Shift64ByUint)
94 w.nBits += w.width
95 binary.LittleEndian.PutUint64(w.out[w.n:], w.bits)
96 w.bits >>= (w.nBits & ^uint(7)) & regmask.Shift64ByUint
97 }
98 w.n += int(w.nBits >> 3)
99 w.nBits &= 7
100 if w.n < outFlush {
101 return nil
102 }
103 return w.flush()
104 }
105
106 // flush writes the pending output to the underlying writer.
107 func (w *Writer) flush() error {
108 if w.n == 0 {
109 return nil
110 }
111 n, err := w.w.Write(w.out[:w.n])
112 if err == nil && n < w.n {
113 err = io.ErrShortWrite
114 }
115 w.n = 0
116 return err
117 }
118
119 // errOutOfCodes is an internal error that means that the writer has run out
120 // of unused codes and a clear code needs to be sent next.
121 var errOutOfCodes = errors.New("lzw: out of codes")
122
123 // incHi increments e.hi and checks for both overflow and running out of
124 // unused codes. In the latter case, incHi sends a clear code, resets the
125 // writer state and returns errOutOfCodes.
126 func (w *Writer) incHi() error {
127 w.hi++
128 if w.hi == w.overflow {
129 w.width++
130 w.overflow <<= 1
131 }
132 if w.hi == maxCode {
133 return w.sendClear()
134 }
135 return nil
136 }
137
138 // sendClear sends a clear code and resets the writer state. It always returns
139 // an error, errOutOfCodes if the clear code was sent successfully.
140 func (w *Writer) sendClear() error {
141 clearCode := uint32(1) << w.litWidth
142 if err := w.emit(clearCode); err != nil {
143 return err
144 }
145 w.width = w.litWidth + 1
146 w.hi = clearCode + 1
147 w.overflow = clearCode << 1
148 clear(w.table[:])
149 return errOutOfCodes
150 }
151
152 // Write writes a compressed representation of p to w's underlying writer.
153 func (w *Writer) Write(p []byte) (n int, err error) {
154 if w.err != nil {
155 return 0, w.err
156 }
157 if len(p) == 0 {
158 return 0, nil
159 }
160 if maxLit := uint8(1<<w.litWidth - 1); maxLit != 0xff {
161 for _, x := range p {
162 if x > maxLit {
163 w.err = errors.New("lzw: input byte too large for the litWidth")
164 return 0, w.err
165 }
166 }
167 }
168 n = len(p)
169 code := w.savedCode
170 if code == invalidCode {
171 // This is the first write; send a clear code.
172 // https://www.w3.org/Graphics/GIF/spec-gif89a.txt Appendix F
173 // "Variable-Length-Code LZW Compression" says that "Encoders should
174 // output a Clear code as the first code of each image data stream".
175 //
176 // LZW compression isn't only used by GIF, but it's cheap to follow
177 // that directive unconditionally.
178 clear := uint32(1) << w.litWidth
179 if err := w.emit(clear); err != nil {
180 return 0, err
181 }
182 // After the starting clear code, the next code sent (for non-empty
183 // input) is always a literal code.
184 code, p = uint32(p[0]), p[1:]
185 }
186 loop:
187 for _, x := range p {
188 literal := uint32(x)
189 key := code<<8 | literal
190 // If there is a hash table hit for this key then we continue the loop
191 // and do not emit a code yet.
192 h := (key * hashMul) >> (32 - tableBits)
193 for t := w.table[h]; t != invalidEntry; t = w.table[h] {
194 if key == t>>12 {
195 code = t & maxCode
196 continue loop
197 }
198 h = (h + 1) & tableMask
199 }
200 // Otherwise, write the current code, and literal becomes the start of
201 // the next emitted code. h indexes the free entry that the probe above
202 // stopped at, which is where key belongs.
203 if w.err = w.emit(code); w.err != nil {
204 return 0, w.err
205 }
206 code = literal
207 // Increment w.hi, the next implied code. If we run out of codes, reset
208 // the writer state (including clearing the hash table) and continue.
209 w.hi++
210 if w.hi == w.overflow {
211 w.width++
212 w.overflow <<= 1
213 }
214 if w.hi == maxCode {
215 if err1 := w.sendClear(); err1 != errOutOfCodes {
216 w.err = err1
217 return 0, w.err
218 }
219 continue
220 }
221 // Otherwise, insert key -> w.hi into the map that w.table represents.
222 w.table[h] = key<<12 | w.hi
223 }
224 w.savedCode = code
225 return n, nil
226 }
227
228 // Close closes the [Writer], flushing any pending output. It does not close
229 // w's underlying writer.
230 func (w *Writer) Close() error {
231 if w.err != nil {
232 if w.err == errClosed {
233 return nil
234 }
235 return w.err
236 }
237 // Make any future calls to Write return errClosed.
238 w.err = errClosed
239 // Write the savedCode if valid.
240 if w.savedCode != invalidCode {
241 if err := w.emit(w.savedCode); err != nil {
242 return err
243 }
244 if err := w.incHi(); err != nil && err != errOutOfCodes {
245 return err
246 }
247 } else {
248 // Write the starting clear code, as w.Write did not.
249 clear := uint32(1) << w.litWidth
250 if err := w.emit(clear); err != nil {
251 return err
252 }
253 }
254 // Write the eof code.
255 eof := uint32(1)<<w.litWidth + 1
256 if err := w.emit(eof); err != nil {
257 return err
258 }
259 // Write the final bits.
260 if w.nBits > 0 {
261 if w.order == MSB {
262 w.out[w.n] = uint8(w.bits >> 56)
263 } else {
264 w.out[w.n] = uint8(w.bits)
265 }
266 w.n++
267 }
268 if err := w.flush(); err != nil {
269 return err
270 }
271 if bw, ok := w.w.(writer); ok {
272 return bw.Flush()
273 }
274 return nil
275 }
276
277 // Reset clears the [Writer]'s state and allows it to be reused again
278 // as a new [Writer].
279 func (w *Writer) Reset(dst io.Writer, order Order, litWidth int) {
280 w.w = nil
281 w.bits, w.nBits, w.n = 0, 0, 0
282 w.err = nil
283 clear(w.table[:])
284 w.init(dst, order, litWidth)
285 }
286
287 // NewWriter creates a new [io.WriteCloser].
288 // Writes to the returned [io.WriteCloser] are compressed and written to w.
289 // It is the caller's responsibility to call Close on the WriteCloser when
290 // finished writing.
291 // The number of bits to use for literal codes, litWidth, must be in the
292 // range [2,8] and is typically 8. Input bytes must be less than 1<<litWidth.
293 //
294 // It is guaranteed that the underlying type of the returned [io.WriteCloser]
295 // is a *[Writer].
296 func NewWriter(w io.Writer, order Order, litWidth int) io.WriteCloser {
297 return newWriter(w, order, litWidth)
298 }
299
300 func newWriter(dst io.Writer, order Order, litWidth int) *Writer {
301 w := new(Writer)
302 w.init(dst, order, litWidth)
303 return w
304 }
305
306 func (w *Writer) init(dst io.Writer, order Order, litWidth int) {
307 if order != LSB && order != MSB {
308 w.err = errors.New("lzw: unknown order")
309 return
310 }
311 if litWidth < 2 || 8 < litWidth {
312 w.err = fmt.Errorf("lzw: litWidth %d out of range", litWidth)
313 return
314 }
315 w.w = dst
316 lw := uint(litWidth)
317 w.order = order
318 w.width = 1 + lw
319 w.litWidth = lw
320 w.hi = 1<<lw + 1
321 w.overflow = 1 << (lw + 1)
322 w.savedCode = invalidCode
323 }