Debian Codegraph @

lzw/compat_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
6
7 import (
8 "bufio"
9 "bytes"
10 stdlzw "compress/lzw"
11 "fmt"
12 "io"
13 "math/rand"
14 "testing"
15 )
16
17 // readAll reads r in chunks of the given size, returning what was decoded and
18 // the terminating error.
19 func readAll(r io.Reader, chunk int) ([]byte, error) {
20 var out []byte
21 buf := make([]byte, chunk)
22 for {
23 n, err := r.Read(buf)
24 out = append(out, buf[:n]...)
25 if err != nil {
26 return out, err
27 }
28 if n == 0 {
29 return out, io.ErrNoProgress
30 }
31 }
32 }
33
34 // chunkSizes exercise the intermediate output buffer (small) and decoding
35 // straight into the caller's buffer (large).
36 var chunkSizes = []int{1, 3, 100, 4096, 8192, 1 << 16}
37
38 // checkAgainstStd decodes in with both this package and compress/lzw and
39 // requires that the decoded bytes and the terminating error match.
40 func checkAgainstStd(t *testing.T, name string, in []byte, order Order, litWidth int) {
41 t.Helper()
42 want, wantErr := readAll(stdlzw.NewReader(bytes.NewReader(in), stdlzw.Order(order), litWidth), 4096)
43 for _, chunk := range chunkSizes {
44 got, gotErr := readAll(NewReader(bytes.NewReader(in), order, litWidth), chunk)
45 if !bytes.Equal(got, want) {
46 t.Fatalf("%s (order=%d litWidth=%d chunk=%d): got %d bytes, want %d bytes\n got: %x\nwant: %x",
47 name, order, litWidth, chunk, len(got), len(want), trunc(got), trunc(want))
48 }
49 if errString(gotErr) != errString(wantErr) {
50 t.Fatalf("%s (order=%d litWidth=%d chunk=%d): error %v, want %v",
51 name, order, litWidth, chunk, gotErr, wantErr)
52 }
53 }
54 }
55
56 // errString is used for comparison: compress/lzw allocates a fresh error for
57 // an invalid code, so the values are never identical.
58 func errString(err error) string {
59 if err == nil {
60 return ""
61 }
62 return err.Error()
63 }
64
65 func trunc(b []byte) []byte {
66 if len(b) > 64 {
67 return b[:64]
68 }
69 return b
70 }
71
72 func TestStdCompatFiles(t *testing.T) {
73 for _, name := range append([]string{"gettysburg.txt", "pi.txt"}, benchFiles...) {
74 raw := loadFile(t, name)
75 for _, order := range []Order{LSB, MSB} {
76 for litWidth := 2; litWidth <= 8; litWidth++ {
77 masked := make([]byte, len(raw))
78 for i, v := range raw {
79 masked[i] = v & byte(1<<litWidth-1)
80 }
81 in := lzwEncode(t, masked, order, litWidth)
82 checkAgainstStd(t, name, in, order, litWidth)
83 }
84 }
85 }
86 }
87
88 // TestStdCompatSynthetic covers inputs that stress the dictionary: long runs
89 // (maximal expansions and the KwKwK case), repeated clear codes and data that
90 // pushes the code width to its maximum.
91 func TestStdCompatSynthetic(t *testing.T) {
92 rng := rand.New(rand.NewSource(1))
93 inputs := map[string][]byte{
94 "empty": {},
95 "one": {0x42},
96 "zeros": make([]byte, 1<<20),
97 "random": randBytes(rng, 1<<19),
98 "runs": runs(rng, 1<<19),
99 "lowentropy": func() []byte {
100 b := make([]byte, 1<<19)
101 for i := range b {
102 b[i] = byte(rng.Intn(3))
103 }
104 return b
105 }(),
106 }
107 for name, raw := range inputs {
108 for _, order := range []Order{LSB, MSB} {
109 in := lzwEncode(t, raw, order, 8)
110 checkAgainstStd(t, name, in, order, 8)
111 // Truncations exercise the unexpected-EOF paths.
112 for _, cut := range []int{1, 2, 3, len(in) / 3, len(in) / 2, len(in) - 1} {
113 if cut > 0 && cut < len(in) {
114 checkAgainstStd(t, fmt.Sprintf("%s-cut%d", name, cut), in[:cut], order, 8)
115 }
116 }
117 }
118 }
119 }
120
121 func randBytes(rng *rand.Rand, n int) []byte {
122 b := make([]byte, n)
123 rng.Read(b)
124 return b
125 }
126
127 // runs returns data made of long repeats, which produces maximal length
128 // dictionary entries.
129 func runs(rng *rand.Rand, n int) []byte {
130 b := make([]byte, 0, n)
131 for len(b) < n {
132 v := byte(rng.Intn(256))
133 for i := rng.Intn(5000); i >= 0 && len(b) < n; i-- {
134 b = append(b, v)
135 }
136 }
137 return b
138 }
139
140 // TestStdCompatCorrupt feeds arbitrary bytes to both decoders.
141 func TestStdCompatCorrupt(t *testing.T) {
142 rng := rand.New(rand.NewSource(2))
143 for i := range 2000 {
144 in := randBytes(rng, rng.Intn(300))
145 for _, order := range []Order{LSB, MSB} {
146 for _, litWidth := range []int{2, 5, 8} {
147 checkAgainstStd(t, fmt.Sprintf("corrupt%d", i), in, order, litWidth)
148 }
149 }
150 }
151 // Streams of a single repeated byte walk the dictionary in unusual ways.
152 for _, fill := range []byte{0x00, 0x01, 0x7f, 0x80, 0xfe, 0xff} {
153 for _, n := range []int{1, 2, 17, 1000, 100000} {
154 in := bytes.Repeat([]byte{fill}, n)
155 for _, order := range []Order{LSB, MSB} {
156 for _, litWidth := range []int{2, 5, 8} {
157 checkAgainstStd(t, fmt.Sprintf("fill%02x-%d", fill, n), in, order, litWidth)
158 }
159 }
160 }
161 }
162 }
163
164 // FuzzReader requires that decoding matches compress/lzw byte for byte, error
165 // for error and, for every kind of source, in how much of it was consumed.
166 func FuzzReader(f *testing.F) {
167 for _, tt := range lzwTests {
168 f.Add([]byte(tt.compressed))
169 }
170 f.Fuzz(func(t *testing.T, in []byte) {
171 for _, order := range []Order{LSB, MSB} {
172 for litWidth := 2; litWidth <= 8; litWidth++ {
173 ref := bytes.NewReader(in)
174 want, wantErr := readAll(stdlzw.NewReader(ref, stdlzw.Order(order), litWidth), 4096)
175 wantUsed := len(in) - ref.Len()
176
177 for _, chunk := range []int{1, 4096, 1 << 16} {
178 for _, kind := range []string{"bytes", "bufio", "byte"} {
179 var src io.Reader
180 var used func() int
181 switch kind {
182 case "bytes":
183 s := bytes.NewReader(in)
184 src, used = s, func() int { return len(in) - s.Len() }
185 case "bufio":
186 s := bytes.NewReader(in)
187 b := bufio.NewReader(s)
188 src, used = b, func() int { return len(in) - s.Len() - b.Buffered() }
189 case "byte":
190 s := &byteReader{b: in}
191 src, used = s, func() int { return s.i }
192 }
193 got, gotErr := readAll(NewReader(src, order, litWidth), chunk)
194 if !bytes.Equal(got, want) || errString(gotErr) != errString(wantErr) {
195 t.Fatalf("order=%d litWidth=%d chunk=%d src=%s: got %d bytes %v, want %d bytes %v",
196 order, litWidth, chunk, kind, len(got), gotErr, len(want), wantErr)
197 }
198 if u := used(); u != wantUsed {
199 t.Fatalf("order=%d litWidth=%d chunk=%d src=%s: consumed %d bytes, want %d",
200 order, litWidth, chunk, kind, u, wantUsed)
201 }
202 }
203 }
204 }
205 }
206 })
207 }
208
209 // stdEncode compresses raw with compress/lzw, writing it in the given chunk
210 // sizes.
211 func stdEncode(tb testing.TB, raw []byte, order Order, litWidth int, chunk int) []byte {
212 tb.Helper()
213 var buf bytes.Buffer
214 w := stdlzw.NewWriter(&buf, stdlzw.Order(order), litWidth)
215 for len(raw) > 0 {
216 n := min(chunk, len(raw))
217 if _, err := w.Write(raw[:n]); err != nil {
218 tb.Fatal(err)
219 }
220 raw = raw[n:]
221 }
222 if err := w.Close(); err != nil {
223 tb.Fatal(err)
224 }
225 return buf.Bytes()
226 }
227
228 func lzwEncodeChunked(tb testing.TB, raw []byte, order Order, litWidth int, chunk int) []byte {
229 tb.Helper()
230 var buf bytes.Buffer
231 w := NewWriter(&buf, order, litWidth)
232 for len(raw) > 0 {
233 n := min(chunk, len(raw))
234 if _, err := w.Write(raw[:n]); err != nil {
235 tb.Fatal(err)
236 }
237 raw = raw[n:]
238 }
239 if err := w.Close(); err != nil {
240 tb.Fatal(err)
241 }
242 return buf.Bytes()
243 }
244
245 // TestWriterMatchesStd requires that compression produces exactly the same
246 // bytes as compress/lzw, whatever sizes the input arrives in.
247 func TestWriterMatchesStd(t *testing.T) {
248 for _, name := range append([]string{"gettysburg.txt", "pi.txt"}, benchFiles...) {
249 raw := loadFile(t, name)
250 for _, order := range []Order{LSB, MSB} {
251 for litWidth := 2; litWidth <= 8; litWidth++ {
252 masked := make([]byte, len(raw))
253 for i, v := range raw {
254 masked[i] = v & byte(1<<litWidth-1)
255 }
256 want := stdEncode(t, masked, order, litWidth, len(masked)+1)
257 for _, chunk := range []int{1, 7, 1000, len(masked) + 1} {
258 got := lzwEncodeChunked(t, masked, order, litWidth, chunk)
259 if !bytes.Equal(got, want) {
260 t.Fatalf("%s (order=%d litWidth=%d chunk=%d): %d bytes, want %d",
261 name, order, litWidth, chunk, len(got), len(want))
262 }
263 }
264 }
265 }
266 }
267 }
268
269 // TestWriterFlushesBufferedDestination checks that Close still flushes a
270 // destination that does its own buffering, and reaches a plain one.
271 func TestWriterFlushesBufferedDestination(t *testing.T) {
272 data := bytes.Repeat([]byte("flush me "), 2000)
273 want := lzwEncode(t, data, LSB, 8)
274
275 var sink bytes.Buffer
276 bw := bufio.NewWriter(&sink)
277 w := NewWriter(bw, LSB, 8)
278 if _, err := w.Write(data); err != nil {
279 t.Fatal(err)
280 }
281 if err := w.Close(); err != nil {
282 t.Fatal(err)
283 }
284 if !bytes.Equal(sink.Bytes(), want) {
285 t.Errorf("bufio.Writer: got %d bytes, want %d", sink.Len(), len(want))
286 }
287
288 // io.Discard is neither a byte writer nor flushable.
289 if err := NewWriter(io.Discard, LSB, 8).Close(); err != nil {
290 t.Errorf("io.Discard: %v", err)
291 }
292 }
293
294 // TestWriterShortWrite checks that a destination that cannot take everything is
295 // reported rather than silently dropped.
296 func TestWriterShortWrite(t *testing.T) {
297 w := NewWriter(shortWriter{}, LSB, 8)
298 _, err1 := w.Write(bytes.Repeat([]byte("abcdefghij"), 5000))
299 err2 := w.Close()
300 if err1 == nil && err2 == nil {
301 t.Fatal("got nil errors, want a write error")
302 }
303 }
304
305 type shortWriter struct{}
306
307 func (shortWriter) Write(p []byte) (int, error) { return len(p) / 2, nil }
308
309 // FuzzWriter requires that compression matches compress/lzw byte for byte and
310 // that what it produces decodes back to the input.
311 func FuzzWriter(f *testing.F) {
312 f.Add([]byte("TOBEORNOTTOBEORTOBEORNOT"), uint8(0), uint8(3))
313 f.Add(bytes.Repeat([]byte{1, 2}, 5000), uint8(1), uint8(200))
314 f.Fuzz(func(t *testing.T, raw []byte, cfg uint8, chunk uint8) {
315 order, litWidth := Order(cfg&1), int(cfg>>1)%7+2
316 masked := make([]byte, len(raw))
317 for i, v := range raw {
318 masked[i] = v & byte(1<<litWidth-1)
319 }
320 want := stdEncode(t, masked, order, litWidth, len(masked)+1)
321 got := lzwEncodeChunked(t, masked, order, litWidth, int(chunk)+1)
322 if !bytes.Equal(got, want) {
323 t.Fatalf("order=%d litWidth=%d chunk=%d: %d bytes, want %d",
324 order, litWidth, chunk, len(got), len(want))
325 }
326 back, err := readAll(NewReader(bytes.NewReader(got), order, litWidth), 4096)
327 if err != io.EOF || !bytes.Equal(back, masked) {
328 t.Fatalf("roundtrip: %d bytes, %v, want %d bytes", len(back), err, len(masked))
329 }
330 })
331 }
332
333 // FuzzRoundtrip reaches the decoder paths that only well formed streams take,
334 // such as maximal expansions and repeated clear codes.
335 func FuzzRoundtrip(f *testing.F) {
336 f.Add([]byte("TOBEORNOTTOBEORTOBEORNOT"), uint8(0))
337 f.Add(bytes.Repeat([]byte{7}, 10000), uint8(1))
338 f.Fuzz(func(t *testing.T, raw []byte, cfg uint8) {
339 order, litWidth := Order(cfg&1), int(cfg>>1)%7+2
340 masked := make([]byte, len(raw))
341 for i, v := range raw {
342 masked[i] = v & byte(1<<litWidth-1)
343 }
344 var buf bytes.Buffer
345 w := NewWriter(&buf, order, litWidth)
346 if _, err := w.Write(masked); err != nil {
347 t.Fatal(err)
348 }
349 if err := w.Close(); err != nil {
350 t.Fatal(err)
351 }
352 for _, chunk := range []int{1, 9000, 1 << 17} {
353 got, err := readAll(NewReader(bytes.NewReader(buf.Bytes()), order, litWidth), chunk)
354 if err != io.EOF {
355 t.Fatalf("chunk=%d: %v", chunk, err)
356 }
357 if !bytes.Equal(got, masked) {
358 t.Fatalf("chunk=%d: got %d bytes, want %d", chunk, len(got), len(masked))
359 }
360 }
361 })
362 }