| 1 |
# lzw |
| 2 |
|
| 3 |
This is a drop-in replacement for the standard library [`compress/lzw`](https://pkg.go.dev/compress/lzw) package, |
| 4 |
with a **decompressor 1.4-4x faster** and a **compressor 1.1-2.7x faster**, depending on the data. See the |
| 5 |
[measurements](#performance) for where in those ranges a given kind of input falls. |
| 6 |
|
| 7 |
Both are exactly compatible: decoding produces byte-for-byte identical output and reports the same errors for |
| 8 |
corrupt or truncated input, and encoding produces byte-for-byte identical compressed streams, so the |
| 9 |
compression ratio is unchanged. |
| 10 |
|
| 11 |
One difference to be aware of: `Read` writes codes out eight bytes at a time, so it may modify up to seven |
| 12 |
bytes of the buffer you pass it beyond the count it returns. It never writes beyond the length of that |
| 13 |
buffer, so `Read(buf[:k])` will not disturb `buf[k:]`. |
| 14 |
|
| 15 |
* [Godoc documentation](https://pkg.go.dev/github.com/klauspost/compress/lzw) |
| 16 |
|
| 17 |
# usage |
| 18 |
|
| 19 |
Replace imports of `compress/lzw` with `github.com/klauspost/compress/lzw`. Nothing else has to change: |
| 20 |
the package has the same API, including `Order`, `LSB`, `MSB`, `NewReader`, `NewWriter` and the `Reset` |
| 21 |
methods. |
| 22 |
|
| 23 |
Decompressing: |
| 24 |
|
| 25 |
```Go |
| 26 |
r := lzw.NewReader(src, lzw.LSB, 8) |
| 27 |
defer r.Close() |
| 28 |
|
| 29 |
if _, err := io.Copy(dst, r); err != nil { |
| 30 |
return err |
| 31 |
} |
| 32 |
``` |
| 33 |
|
| 34 |
Compressing: |
| 35 |
|
| 36 |
```Go |
| 37 |
w := lzw.NewWriter(dst, lzw.LSB, 8) |
| 38 |
if _, err := w.Write(data); err != nil { |
| 39 |
return err |
| 40 |
} |
| 41 |
// Close flushes the final codes. It does not close dst. |
| 42 |
return w.Close() |
| 43 |
``` |
| 44 |
|
| 45 |
Use `LSB` with a literal width of 8 for GIF, and `MSB` for PDF. The literal width must be the same as the |
| 46 |
one used when compressing. |
| 47 |
|
| 48 |
# performance |
| 49 |
|
| 50 |
Single core, AMD Ryzen 9 9950X. Decompression is measured decoding to a 64KB buffer. |
| 51 |
|
| 52 |
Decompression: |
| 53 |
|
| 54 |
| Input | `compress/lzw` | this package | speedup | |
| 55 |
|------------------------------|---------------:|-------------:|--------:| |
| 56 |
| `Mark.Twain-Tom.Sawyer.txt` | 213 MB/s | 821 MB/s | 3.86x | |
| 57 |
| `html.txt` | 240 MB/s | 818 MB/s | 3.41x | |
| 58 |
| `e.txt` (digits) | 307 MB/s | 881 MB/s | 2.87x | |
| 59 |
| `pngdata.bin` (binary) | 558 MB/s | 1842 MB/s | 3.30x | |
| 60 |
| Tom Sawyer, `MSB` order | 214 MB/s | 844 MB/s | 3.95x | |
| 61 |
| Tom Sawyer, litWidth 5 | 219 MB/s | 875 MB/s | 3.99x | |
| 62 |
| 1KB streams | 332 MB/s | 559 MB/s | 1.69x | |
| 63 |
| `sharnd.out` (random data) | 238 MB/s | 329 MB/s | 1.38x | |
| 64 |
|
| 65 |
Compression: |
| 66 |
|
| 67 |
| Input | `compress/lzw` | this package | speedup | |
| 68 |
|------------------------------|---------------:|-------------:|--------:| |
| 69 |
| `e.txt` (digits) | 130 MB/s | 356 MB/s | 2.73x | |
| 70 |
| 1KB streams | 248 MB/s | 478 MB/s | 1.92x | |
| 71 |
| Tom Sawyer, litWidth 5 | 108 MB/s | 194 MB/s | 1.80x | |
| 72 |
| `html.txt` | 143 MB/s | 230 MB/s | 1.60x | |
| 73 |
| `sharnd.out` (random data) | 160 MB/s | 255 MB/s | 1.60x | |
| 74 |
| `Mark.Twain-Tom.Sawyer.txt` | 132 MB/s | 194 MB/s | 1.48x | |
| 75 |
| Tom Sawyer, `MSB` order | 136 MB/s | 191 MB/s | 1.41x | |
| 76 |
| `pngdata.bin` (binary) | 397 MB/s | 431 MB/s | 1.09x | |
| 77 |
|
| 78 |
Decoding gains most on the compressible data LZW is normally used for; incompressible input, which LZW |
| 79 |
expands rather than compresses, gains the least since almost every code is a single literal byte. Encoding |
| 80 |
gains most on input drawn from few distinct byte values, such as digits or a small colour palette, and least |
| 81 |
on input made of long repeats, where it emits few codes to begin with. |
| 82 |
|
| 83 |
Neither the reader nor the writer allocates while encoding or decoding, and reusing either with `Reset` does |
| 84 |
not allocate at all — except that a source which is not an `io.ByteReader` is wrapped in a `bufio.Reader` on |
| 85 |
each `Reset`, as it is in the standard library. |
| 86 |
|
| 87 |
Run `go test -bench='Decode|Encode' -benchtime=500ms -count=10 .` in this directory to compare on your own |
| 88 |
machine; `BenchmarkDecodeStd` and `BenchmarkEncodeStd` measure `compress/lzw` in the same process for a fair |
| 89 |
comparison. |
| 90 |
|
| 91 |
# getting the best speed |
| 92 |
|
| 93 |
None of these are required for correct use, but each affects how fast the package runs. |
| 94 |
|
| 95 |
**Decoding: read into a buffer of at least 8KB.** Given that much room the reader expands codes straight into |
| 96 |
your buffer; with less it has to decode into an internal buffer and copy from it. `io.Copy` passes 32KB and so |
| 97 |
needs no help, but note that a `bufio.Reader` wrapped *around* the reader defaults to 4KB. |
| 98 |
|
| 99 |
**Decoding: prefer a source that can be read a machine word at a time.** The reader is careful never to |
| 100 |
consume more of the source than the code stream needs, which is what makes it usable for embedded streams such |
| 101 |
as the image data in a GIF. How it achieves that depends on the type passed to `NewReader`: |
| 102 |
|
| 103 |
| Source | How it is read | |
| 104 |
|----------------------------------------------------------------------------------------------------------|--------------------------------------| |
| 105 |
| any `io.Reader` that is not an `io.ByteReader`, e.g. `*os.File` or a network connection | wrapped in a `bufio.Reader`, fast | |
| 106 |
| `*bufio.Reader`, or anything with `Peek`/`Discard`/`Buffered` | peeked, then discarded, fast | |
| 107 |
| `*bytes.Reader`, `*strings.Reader`, or any `io.ByteReader` that is also an `io.ReaderAt` and `io.Seeker` | read at an offset, then seeked, fast | |
| 108 |
| anything else implementing `io.ByteReader` | one byte at a time, slower | |
| 109 |
|
| 110 |
The last row is the only slow case. It covers types such as `*bytes.Buffer`, and the block readers that |
| 111 |
container formats often use. Wrapping such a source in a `bufio.Reader` is only safe if reading ahead of the |
| 112 |
compressed stream is acceptable, since a `bufio.Reader` will consume whatever follows it. |
| 113 |
|
| 114 |
**Either direction: reuse readers and writers with `Reset`.** Both hold their dictionary inline — a `Reader` is |
| 115 |
around 56KB and a `Writer` around 68KB — so reusing one across streams, as when handling the frames of an |
| 116 |
animated GIF, avoids repeated allocation. `Reset` on a `Reader` does not have to clear its tables, so it is |
| 117 |
very cheap; on a `Writer` it clears the hash table, which is still far cheaper than allocating. |
| 118 |
|
| 119 |
```Go |
| 120 |
r := lzw.NewReader(frames[0], lzw.LSB, 8).(*lzw.Reader) |
| 121 |
defer r.Close() |
| 122 |
|
| 123 |
for _, frame := range frames { |
| 124 |
r.Reset(frame, lzw.LSB, 8) |
| 125 |
// ... read from r ... |
| 126 |
} |
| 127 |
``` |
| 128 |
|
| 129 |
## TIFF and PDF: the Aldus variant |
| 130 |
|
| 131 |
TIFF uses a variant of LZW that increases the code width one code early — the "off by one" that Aldus |
| 132 |
implemented and that libtiff keeps for compatibility. PDF's `LZWDecode` filter specifies the same variant by |
| 133 |
default, through its `/EarlyChange` value of `1`. Decoding either needs one extra call: |
| 134 |
|
| 135 |
```Go |
| 136 |
r := lzw.NewReader(src, lzw.MSB, 8).(*lzw.Reader) |
| 137 |
r.SetAldusCompatible(true) |
| 138 |
defer r.Close() |
| 139 |
``` |
| 140 |
|
| 141 |
Set it before the first `Read`. It is configuration rather than stream state, so it survives `Reset` and a |
| 142 |
pooled reader keeps it. |
| 143 |
|
| 144 |
The two variants are decoded by separate code, so leaving the setting off costs the default path nothing — |
| 145 |
literally nothing on arm64, where `decode` compiles to the same bytes either way. The flip side is that the |
| 146 |
Aldus path is the plain implementation rather than the tuned one: around 284 MB/s on Tom Sawyer where the |
| 147 |
default path manages 848, still somewhat ahead of `compress/lzw`. Folding the variant into the tuned loop was |
| 148 |
measured instead, and cost the default MSB path 7%, which was not a good trade for an opt-in. |
| 149 |
|
| 150 |
Only the reader supports this so far — `Writer` always produces standard streams, which is what GIF wants and |
| 151 |
what PDF accepts with `/EarlyChange 0`. |
| 152 |
|
| 153 |
# testing |
| 154 |
|
| 155 |
Both halves are tested by comparison with `compress/lzw` over every test input, both bit orders and all |
| 156 |
literal widths. |
| 157 |
|
| 158 |
Decoding must agree on the decoded bytes, on the error returned and on how many bytes of the source were |
| 159 |
consumed, for each kind of source and a range of read sizes. Encoding must produce identical bytes, whatever |
| 160 |
sizes the input is written in. |
| 161 |
|
| 162 |
`FuzzReader` fuzzes the decoder comparison, including for corrupt and truncated input, `FuzzWriter` the |
| 163 |
encoder comparison, and `FuzzRoundtrip` checks that what the writer produces decodes back to the input. |