Debian Codegraph @

lzw/aldus_test.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_test
6
7 import (
8 "bytes"
9 stdlzw "compress/lzw"
10 "io"
11 "math/rand"
12 "os"
13 "testing"
14
15 "github.com/klauspost/compress/lzw"
16 )
17
18 // TestRefOrderValues checks the assumption that lets the reference decoder in
19 // ref_aldus_test.go be driven with an order value taken from this package.
20 func TestRefOrderValues(t *testing.T) {
21 if int(lzw.LSB) != int(LSB) || int(lzw.MSB) != int(MSB) {
22 t.Fatalf("order values differ: LSB %d/%d, MSB %d/%d", lzw.LSB, LSB, lzw.MSB, MSB)
23 }
24 }
25
26 // refEncode compresses raw with a deliberately simple LZW encoder. When aldus is
27 // true it grows the code width one code early, the variant that
28 // Reader.SetAldusCompatible selects. It exists to produce streams for the
29 // decoder tests without using this package's own Writer, and is written for
30 // clarity rather than speed.
31 func refEncode(raw []byte, order lzw.Order, litWidth int, aldus bool) []byte {
32 const maxCodeWidth = 12
33 const maxCode = 1<<maxCodeWidth - 1
34 var out []byte
35 var bits uint32
36 var nBits uint
37 width := uint(litWidth) + 1
38
39 emit := func(code uint32) {
40 if order == lzw.MSB {
41 bits |= code << (32 - width - nBits)
42 nBits += width
43 for nBits >= 8 {
44 out = append(out, byte(bits>>24))
45 bits <<= 8
46 nBits -= 8
47 }
48 return
49 }
50 bits |= code << nBits
51 nBits += width
52 for nBits >= 8 {
53 out = append(out, byte(bits))
54 bits >>= 8
55 nBits -= 8
56 }
57 }
58
59 clear := uint32(1) << litWidth
60 eof := clear + 1
61 hi, overflow := clear+1, uint32(1)<<width
62 table := map[uint32]uint32{}
63
64 // bumpHi advances the implied next code exactly as the decoder advances its
65 // own, reporting whether the table filled up and a clear code was sent.
66 bumpHi := func() bool {
67 hi++
68 grow := hi == overflow
69 if aldus {
70 grow = hi+1 == overflow
71 }
72 // The width never grows past the maximum: at that point the table is
73 // simply full until a clear code is sent.
74 if grow && width < maxCodeWidth {
75 width++
76 overflow <<= 1
77 }
78 if hi == maxCode {
79 emit(clear)
80 width = uint(litWidth) + 1
81 hi, overflow = clear+1, uint32(1)<<width
82 table = map[uint32]uint32{}
83 return true
84 }
85 return false
86 }
87
88 emit(clear)
89 if len(raw) > 0 {
90 cur := uint32(raw[0])
91 for _, b := range raw[1:] {
92 key := cur<<8 | uint32(b)
93 if c, ok := table[key]; ok {
94 cur = c
95 continue
96 }
97 emit(cur)
98 cur = uint32(b)
99 if bumpHi() {
100 continue
101 }
102 table[key] = hi
103 }
104 emit(cur)
105 bumpHi()
106 }
107 emit(eof)
108 if nBits > 0 {
109 if order == lzw.MSB {
110 out = append(out, byte(bits>>24))
111 } else {
112 out = append(out, byte(bits))
113 }
114 }
115 return out
116 }
117
118 func drainAll(r io.Reader) ([]byte, error) {
119 var out []byte
120 buf := make([]byte, 4096)
121 for {
122 n, err := r.Read(buf)
123 out = append(out, buf[:n]...)
124 if err != nil {
125 return out, err
126 }
127 if n == 0 {
128 return out, io.ErrNoProgress
129 }
130 }
131 }
132
133 func ourReader(in []byte, order lzw.Order, litWidth int, aldus bool) io.ReadCloser {
134 r := lzw.NewReader(bytes.NewReader(in), order, litWidth).(*lzw.Reader)
135 r.SetAldusCompatible(aldus)
136 return r
137 }
138
139 func testFiles(tb testing.TB) map[string][]byte {
140 tb.Helper()
141 out := map[string][]byte{}
142 for _, name := range []string{"gettysburg.txt", "e.txt", "html.txt", "Mark.Twain-Tom.Sawyer.txt", "pngdata.bin"} {
143 b, err := os.ReadFile("../testdata/" + name)
144 if err != nil {
145 tb.Fatal(err)
146 }
147 out[name] = b
148 }
149 rng := rand.New(rand.NewSource(11))
150 random := make([]byte, 1<<18)
151 rng.Read(random)
152 out["random"] = random
153 out["empty"] = nil
154 out["one"] = []byte{3}
155 out["runs"] = bytes.Repeat([]byte{1, 1, 1, 2, 2, 3}, 40000)
156 return out
157 }
158
159 func mask(raw []byte, litWidth int) []byte {
160 out := make([]byte, len(raw))
161 for i, v := range raw {
162 out[i] = v & byte(1<<litWidth-1)
163 }
164 return out
165 }
166
167 // TestRefEncoderIsValidLZW checks refEncode itself: with the standard width rule
168 // its output must decode correctly with compress/lzw, so that a failure of the
169 // Aldus tests below can be attributed to the Aldus rule rather than to the
170 // reference encoder being wrong.
171 func TestRefEncoderIsValidLZW(t *testing.T) {
172 for name, file := range testFiles(t) {
173 for _, order := range []lzw.Order{lzw.LSB, lzw.MSB} {
174 for litWidth := 2; litWidth <= 8; litWidth++ {
175 raw := mask(file, litWidth)
176 in := refEncode(raw, order, litWidth, false)
177 got, err := drainAll(stdlzw.NewReader(bytes.NewReader(in), stdlzw.Order(order), litWidth))
178 if err != io.EOF || !bytes.Equal(got, raw) {
179 t.Fatalf("%s order=%d litWidth=%d: compress/lzw got %d bytes (%v), want %d",
180 name, order, litWidth, len(got), err, len(raw))
181 }
182 }
183 }
184 }
185 }
186
187 // TestAldusMatchesReference decodes Aldus streams with both the reference
188 // decoder copied from x/image and this package's, and requires that both
189 // reproduce the input.
190 func TestAldusMatchesReference(t *testing.T) {
191 for name, file := range testFiles(t) {
192 for _, order := range []lzw.Order{lzw.LSB, lzw.MSB} {
193 for litWidth := 2; litWidth <= 8; litWidth++ {
194 raw := mask(file, litWidth)
195 in := refEncode(raw, order, litWidth, true)
196
197 ref, err := drainAll(NewReader(bytes.NewReader(in), Order(order), litWidth))
198 if err != io.EOF || !bytes.Equal(ref, raw) {
199 t.Fatalf("%s order=%d litWidth=%d: reference decoder got %d bytes (%v), want %d",
200 name, order, litWidth, len(ref), err, len(raw))
201 }
202 got, err := drainAll(ourReader(in, order, litWidth, true))
203 if err != io.EOF || !bytes.Equal(got, raw) {
204 t.Fatalf("%s order=%d litWidth=%d: got %d bytes (%v), want %d",
205 name, order, litWidth, len(got), err, len(raw))
206 }
207 }
208 }
209 }
210 }
211
212 // TestAldusIsNotStandard checks that the flag actually selects a different
213 // dialect, so that the tests above are not passing for a trivial reason.
214 func TestAldusIsNotStandard(t *testing.T) {
215 // Long enough to reach the first width change at code 511.
216 raw := mask([]byte(bytes.Repeat([]byte("Aldus and standard LZW diverge here. "), 400)), 8)
217 aldusIn := refEncode(raw, lzw.MSB, 8, true)
218 stdIn := refEncode(raw, lzw.MSB, 8, false)
219 if bytes.Equal(aldusIn, stdIn) {
220 t.Fatal("the two variants encoded to the same bytes")
221 }
222 got, err := drainAll(ourReader(aldusIn, lzw.MSB, 8, false))
223 if err == io.EOF && bytes.Equal(got, raw) {
224 t.Fatal("decoded an Aldus stream as standard LZW without noticing")
225 }
226 got, err = drainAll(ourReader(stdIn, lzw.MSB, 8, true))
227 if err == io.EOF && bytes.Equal(got, raw) {
228 t.Fatal("decoded a standard stream as Aldus without noticing")
229 }
230 }
231
232 // TestAldusSurvivesReset checks the documented lifetime of the setting.
233 func TestAldusSurvivesReset(t *testing.T) {
234 raw := mask([]byte(bytes.Repeat([]byte("reset keeps the dialect "), 500)), 8)
235 in := refEncode(raw, lzw.MSB, 8, true)
236
237 r := lzw.NewReader(bytes.NewReader(in), lzw.MSB, 8).(*lzw.Reader)
238 r.SetAldusCompatible(true)
239 for i := range 3 {
240 r.Reset(bytes.NewReader(in), lzw.MSB, 8)
241 got, err := drainAll(r)
242 if err != io.EOF || !bytes.Equal(got, raw) {
243 t.Fatalf("after %d resets: got %d bytes (%v), want %d", i, len(got), err, len(raw))
244 }
245 }
246 r.SetAldusCompatible(false)
247 r.Reset(bytes.NewReader(in), lzw.MSB, 8)
248 if got, err := drainAll(r); err == io.EOF && bytes.Equal(got, raw) {
249 t.Fatal("still decoding as Aldus after the setting was turned off")
250 }
251 }
252
253 // refEmitCodes writes the given codes using the Aldus width schedule, tracking
254 // the width exactly as a decoder does. It is for building streams by hand that
255 // no conforming encoder would produce.
256 func refEmitCodes(codes []uint32, order lzw.Order, litWidth int) []byte {
257 var out []byte
258 var bits uint32
259 var nBits uint
260 width := uint(litWidth) + 1
261 clearCode := uint32(1) << litWidth
262 hi, overflow := clearCode+1, uint32(1)<<width
263
264 for _, c := range codes {
265 if order == lzw.MSB {
266 bits |= c << (32 - width - nBits)
267 nBits += width
268 for nBits >= 8 {
269 out = append(out, byte(bits>>24))
270 bits <<= 8
271 nBits -= 8
272 }
273 } else {
274 bits |= c << nBits
275 nBits += width
276 for nBits >= 8 {
277 out = append(out, byte(bits))
278 bits >>= 8
279 nBits -= 8
280 }
281 }
282 switch {
283 case c == clearCode:
284 width = uint(litWidth) + 1
285 hi, overflow = clearCode+1, uint32(1)<<width
286 case c == clearCode+1: // EOF
287 default:
288 hi++
289 if hi+1 == overflow && width < 12 {
290 width++
291 overflow <<= 1
292 }
293 }
294 }
295 if nBits > 0 {
296 if order == lzw.MSB {
297 out = append(out, byte(bits>>24))
298 } else {
299 out = append(out, byte(bits))
300 }
301 }
302 return out
303 }
304
305 // TestAldusMaxWidthCode covers the one place this decoder deliberately differs
306 // from the reference. With the Aldus rule the table stops growing at code 4094,
307 // so code 4095 is never assigned and a stream using it is corrupt. This decoder
308 // rejects it, which also keeps hi from climbing past the maximum and eventually
309 // wrapping a uint16. The reference lets hi climb instead, so it accepts the code
310 // and expands the entry that was never assigned. Reaching this needs 3838 codes,
311 // far more than FuzzAldus will produce, hence the hand built stream.
312 func TestAldusMaxWidthCode(t *testing.T) {
313 // 254 + 512 + 1024 + 2048 codes take hi from 257 to 4095, the point at which
314 // the table is full.
315 codes := []uint32{256}
316 for range 254 + 512 + 1024 + 2048 {
317 codes = append(codes, 0)
318 }
319 codes = append(codes, 4095, 257)
320 in := refEmitCodes(codes, lzw.MSB, 8)
321
322 got, gotErr := drainAll(ourReader(in, lzw.MSB, 8, true))
323 if gotErr == nil || gotErr.Error() != "lzw: invalid code" {
324 t.Fatalf("got %d bytes, %v; want a rejection of code 4095", len(got), gotErr)
325 }
326 if want := 254 + 512 + 1024 + 2048; len(got) != want {
327 t.Fatalf("decoded %d bytes before the bad code, want %d", len(got), want)
328 }
329 // Recorded for contrast: the reference expands the unassigned entry, whose
330 // zeroed prefix and suffix yield two bytes of nothing, and reports success.
331 ref, refErr := drainAll(NewReader(bytes.NewReader(in), MSB, 8))
332 if refErr != io.EOF || len(ref) != len(got)+2 {
333 t.Logf("reference behaviour changed: %d bytes, %v (ours: %d bytes, %v)",
334 len(ref), refErr, len(got), gotErr)
335 }
336 }
337
338 // FuzzAldus requires that Aldus decoding matches the reference decoder byte for
339 // byte and error for error, including for corrupt and truncated input.
340 func FuzzAldus(f *testing.F) {
341 f.Add(refEncode([]byte("TOBEORNOTTOBEORTOBEORNOT"), lzw.MSB, 8, true), uint8(1))
342 f.Add(refEncode(bytes.Repeat([]byte{7}, 20000), lzw.MSB, 8, true), uint8(1))
343 f.Fuzz(func(t *testing.T, in []byte, cfg uint8) {
344 order, litWidth := lzw.Order(cfg&1), int(cfg>>1)%7+2
345 want, wantErr := drainAll(NewReader(bytes.NewReader(in), Order(order), litWidth))
346 got, gotErr := drainAll(ourReader(in, order, litWidth, true))
347 if !bytes.Equal(got, want) || errText(gotErr) != errText(wantErr) {
348 t.Fatalf("order=%d litWidth=%d: got %d bytes %v, want %d bytes %v\n got: %x\nwant: %x",
349 order, litWidth, len(got), gotErr, len(want), wantErr, head(got), head(want))
350 }
351 })
352 }
353
354 // TestReadFillsBuffer checks that a Read given room to decode into directly
355 // hands back a full buffer while the stream still holds that much. An io.Reader
356 // is not obliged to, but decoding stops a whole maximal expansion short of the
357 // end of the buffer, so returning that count would leave a caller that does not
358 // loop with all but the last few KB of its data — right enough to pass a glance
359 // and wrong at the tail. Buffers too small to decode into directly are excluded:
360 // they are served from the output buffer, and a short read there is as plain as
361 // the one compress/lzw returns.
362 func TestReadFillsBuffer(t *testing.T) {
363 raw := mask(testFiles(t)["Mark.Twain-Tom.Sawyer.txt"], 8)
364 for _, aldus := range []bool{false, true} {
365 in := refEncode(raw, lzw.MSB, 8, aldus)
366 for _, size := range []int{8192, 1 << 15, 100000, len(raw) + 1000} {
367 r := ourReader(in, lzw.MSB, 8, aldus)
368 buf := make([]byte, size)
369 for off := 0; off < len(raw); {
370 n, err := r.Read(buf)
371 if want := min(size, len(raw)-off); n != want {
372 t.Fatalf("aldus=%v size=%d off=%d: read %d bytes (%v), want %d",
373 aldus, size, off, n, err, want)
374 }
375 if !bytes.Equal(buf[:n], raw[off:off+n]) {
376 t.Fatalf("aldus=%v size=%d off=%d: wrong bytes", aldus, size, off)
377 }
378 off += n
379 if err != nil {
380 break
381 }
382 }
383 }
384 }
385 }
386
387 func errText(err error) string {
388 if err == nil {
389 return ""
390 }
391 return err.Error()
392 }
393
394 func head(b []byte) []byte {
395 if len(b) > 48 {
396 return b[:48]
397 }
398 return b
399 }
400
401 func BenchmarkDecodeAldus(b *testing.B) {
402 raw, err := os.ReadFile("../testdata/Mark.Twain-Tom.Sawyer.txt")
403 if err != nil {
404 b.Fatal(err)
405 }
406 for _, aldus := range []bool{false, true} {
407 name := "standard"
408 if aldus {
409 name = "aldus"
410 }
411 b.Run(name, func(b *testing.B) {
412 in := refEncode(raw, lzw.MSB, 8, aldus)
413 dst := make([]byte, 64<<10)
414 src := bytes.NewReader(in)
415 r := lzw.NewReader(src, lzw.MSB, 8).(*lzw.Reader)
416 r.SetAldusCompatible(aldus)
417 b.SetBytes(int64(len(raw)))
418 b.ReportAllocs()
419 b.ResetTimer()
420 for i := 0; i < b.N; i++ {
421 src.Reset(in)
422 r.Reset(src, lzw.MSB, 8)
423 total := 0
424 for {
425 got, err := r.Read(dst)
426 total += got
427 if err != nil {
428 if err != io.EOF {
429 b.Fatal(err)
430 }
431 break
432 }
433 }
434 if total != len(raw) {
435 b.Fatalf("decoded %d bytes, want %d", total, len(raw))
436 }
437 }
438 })
439 }
440 }