Debian Codegraph @

snappy/snappy_test.go

raw
1 // Copyright 2011 The Snappy-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 snappy
6
7 import (
8 "bytes"
9 "encoding/binary"
10 "flag"
11 "fmt"
12 "io"
13 "math/rand"
14 "net/http"
15 "os"
16 "path/filepath"
17 "strings"
18 "testing"
19
20 "github.com/klauspost/compress/s2"
21 )
22
23 var (
24 download = flag.Bool("download", false, "If true, download any missing files before running benchmarks")
25 testdataDir = flag.String("testdataDir", "testdata", "Directory containing the test data")
26 benchdataDir = flag.String("benchdataDir", "testdata/bench", "Directory containing the benchmark data")
27 )
28
29 const (
30 tagLiteral = 0x00
31 tagCopy1 = 0x01
32 tagCopy2 = 0x02
33 tagCopy4 = 0x03
34 )
35
36 const (
37 checksumSize = 4
38 chunkHeaderSize = 4
39 magicChunk = "\xff\x06\x00\x00" + magicBody
40 magicBody = "sNaPpY"
41
42 obufHeaderLen = len(magicChunk) + checksumSize + chunkHeaderSize
43 )
44
45 const (
46 chunkTypeCompressedData = 0x00
47 chunkTypeUncompressedData = 0x01
48 chunkTypePadding = 0xfe
49 chunkTypeStreamIdentifier = 0xff
50 )
51
52 const goEncoderShouldMatchCppEncoder = false
53
54 func TestMaxEncodedLenOfMaxBlockSize(t *testing.T) {
55 maxEncodedLenOfMaxBlockSize := s2.MaxEncodedLen(maxBlockSize)
56 got := maxEncodedLenOfMaxBlockSize
57 want := MaxEncodedLen(maxBlockSize)
58 if got != want {
59 t.Fatalf("got %d, want %d", got, want)
60 }
61 }
62
63 func cmp(a, b []byte) error {
64 if bytes.Equal(a, b) {
65 return nil
66 }
67 if len(a) != len(b) {
68 return fmt.Errorf("got %d bytes, want %d", len(a), len(b))
69 }
70 for i := range a {
71 if a[i] != b[i] {
72 return fmt.Errorf("byte #%d: got 0x%02x, want 0x%02x", i, a[i], b[i])
73 }
74 }
75 return nil
76 }
77
78 func roundtrip(b, ebuf, dbuf []byte) error {
79 d, err := Decode(dbuf, Encode(ebuf, b))
80 if err != nil {
81 return fmt.Errorf("decoding error: %v", err)
82 }
83 if err := cmp(d, b); err != nil {
84 return fmt.Errorf("roundtrip mismatch: %v", err)
85 }
86 return nil
87 }
88
89 func TestEmpty(t *testing.T) {
90 if err := roundtrip(nil, nil, nil); err != nil {
91 t.Fatal(err)
92 }
93 }
94
95 func TestSmallCopy(t *testing.T) {
96 for _, ebuf := range [][]byte{nil, make([]byte, 20), make([]byte, 64)} {
97 for _, dbuf := range [][]byte{nil, make([]byte, 20), make([]byte, 64)} {
98 for i := range 32 {
99 s := "aaaa" + strings.Repeat("b", i) + "aaaabbbb"
100 if err := roundtrip([]byte(s), ebuf, dbuf); err != nil {
101 t.Errorf("len(ebuf)=%d, len(dbuf)=%d, i=%d: %v", len(ebuf), len(dbuf), i, err)
102 }
103 }
104 }
105 }
106 }
107
108 func TestSmallRand(t *testing.T) {
109 rng := rand.New(rand.NewSource(1))
110 for n := 1; n < 20000; n += 23 {
111 b := make([]byte, n)
112 for i := range b {
113 b[i] = uint8(rng.Intn(256))
114 }
115 if err := roundtrip(b, nil, nil); err != nil {
116 t.Fatal(err)
117 }
118 }
119 }
120
121 func TestSmallRegular(t *testing.T) {
122 for n := 1; n < 20000; n += 23 {
123 b := make([]byte, n)
124 for i := range b {
125 b[i] = uint8(i%10 + 'a')
126 }
127 if err := roundtrip(b, nil, nil); err != nil {
128 t.Fatal(err)
129 }
130 }
131 }
132
133 func TestInvalidVarint(t *testing.T) {
134 testCases := []struct {
135 desc string
136 input string
137 }{{
138 "invalid varint, final byte has continuation bit set",
139 "\xff",
140 }, {
141 "invalid varint, value overflows uint64",
142 "\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\x00",
143 }, {
144 // https://github.com/google/snappy/blob/master/format_description.txt
145 // says that "the stream starts with the uncompressed length [as a
146 // varint] (up to a maximum of 2^32 - 1)".
147 "valid varint (as uint64), but value overflows uint32",
148 "\x80\x80\x80\x80\x10",
149 }, {
150 // 8-byte overlong varint encoding value 4. The format spec limits
151 // the varint preamble to 5 bytes. binary.Uvarint accepts up to 10
152 // bytes so this decodes to a valid uint32 value (4), but the
153 // overlong encoding must be rejected.
154 "overlong varint (8 bytes encoding value 4), exceeds 5-byte max",
155 "\x84\x80\x80\x80\x80\x80\x80\x00" +
156 "\x00\x00\x00\x00\x00\x00\x00" +
157 "\x30",
158 }}
159
160 for _, tc := range testCases {
161 input := []byte(tc.input)
162 if _, err := DecodedLen(input); err != ErrCorrupt {
163 t.Errorf("%s: DecodedLen: got %v, want ErrCorrupt", tc.desc, err)
164 }
165 if _, err := Decode(nil, input); err != ErrCorrupt {
166 t.Errorf("%s: Decode: got %v, want ErrCorrupt", tc.desc, err)
167 }
168 }
169 }
170
171 func TestDecode(t *testing.T) {
172 lit40Bytes := make([]byte, 40)
173 for i := range lit40Bytes {
174 lit40Bytes[i] = byte(i)
175 }
176 lit40 := string(lit40Bytes)
177
178 testCases := []struct {
179 desc string
180 input string
181 want string
182 wantErr error
183 }{{
184 `decodedLen=0; valid input`,
185 "\x00",
186 "",
187 nil,
188 }, {
189 `decodedLen=3; tagLiteral, 0-byte length; length=3; valid input`,
190 "\x03" + "\x08\xff\xff\xff",
191 "\xff\xff\xff",
192 nil,
193 }, {
194 `decodedLen=2; tagLiteral, 0-byte length; length=3; not enough dst bytes`,
195 "\x02" + "\x08\xff\xff\xff",
196 "",
197 ErrCorrupt,
198 }, {
199 `decodedLen=3; tagLiteral, 0-byte length; length=3; not enough src bytes`,
200 "\x03" + "\x08\xff\xff",
201 "",
202 ErrCorrupt,
203 }, {
204 `decodedLen=40; tagLiteral, 0-byte length; length=40; valid input`,
205 "\x28" + "\x9c" + lit40,
206 lit40,
207 nil,
208 }, {
209 `decodedLen=1; tagLiteral, 1-byte length; not enough length bytes`,
210 "\x01" + "\xf0",
211 "",
212 ErrCorrupt,
213 }, {
214 `decodedLen=3; tagLiteral, 1-byte length; length=3; valid input`,
215 "\x03" + "\xf0\x02\xff\xff\xff",
216 "\xff\xff\xff",
217 nil,
218 }, {
219 `decodedLen=1; tagLiteral, 2-byte length; not enough length bytes`,
220 "\x01" + "\xf4\x00",
221 "",
222 ErrCorrupt,
223 }, {
224 `decodedLen=3; tagLiteral, 2-byte length; length=3; valid input`,
225 "\x03" + "\xf4\x02\x00\xff\xff\xff",
226 "\xff\xff\xff",
227 nil,
228 }, {
229 `decodedLen=1; tagLiteral, 3-byte length; not enough length bytes`,
230 "\x01" + "\xf8\x00\x00",
231 "",
232 ErrCorrupt,
233 }, {
234 `decodedLen=3; tagLiteral, 3-byte length; length=3; valid input`,
235 "\x03" + "\xf8\x02\x00\x00\xff\xff\xff",
236 "\xff\xff\xff",
237 nil,
238 }, {
239 `decodedLen=1; tagLiteral, 4-byte length; not enough length bytes`,
240 "\x01" + "\xfc\x00\x00\x00",
241 "",
242 ErrCorrupt,
243 }, {
244 `decodedLen=1; tagLiteral, 4-byte length; length=3; not enough dst bytes`,
245 "\x01" + "\xfc\x02\x00\x00\x00\xff\xff\xff",
246 "",
247 ErrCorrupt,
248 }, {
249 `decodedLen=4; tagLiteral, 4-byte length; length=3; not enough src bytes`,
250 "\x04" + "\xfc\x02\x00\x00\x00\xff",
251 "",
252 ErrCorrupt,
253 }, {
254 `decodedLen=3; tagLiteral, 4-byte length; length=3; valid input`,
255 "\x03" + "\xfc\x02\x00\x00\x00\xff\xff\xff",
256 "\xff\xff\xff",
257 nil,
258 }, {
259 `decodedLen=4; tagCopy1, 1 extra length|offset byte; not enough extra bytes`,
260 "\x04" + "\x01",
261 "",
262 ErrCorrupt,
263 }, {
264 `decodedLen=4; tagCopy2, 2 extra length|offset bytes; not enough extra bytes`,
265 "\x04" + "\x02\x00",
266 "",
267 ErrCorrupt,
268 }, {
269 `decodedLen=4; tagCopy4, 4 extra length|offset bytes; not enough extra bytes`,
270 "\x04" + "\x03\x00\x00\x00",
271 "",
272 ErrCorrupt,
273 }, {
274 `decodedLen=4; tagLiteral (4 bytes "abcd"); valid input`,
275 "\x04" + "\x0cabcd",
276 "abcd",
277 nil,
278 }, {
279 `decodedLen=13; tagLiteral (4 bytes "abcd"); tagCopy1; length=9 offset=4; valid input`,
280 "\x0d" + "\x0cabcd" + "\x15\x04",
281 "abcdabcdabcda",
282 nil,
283 }, {
284 `decodedLen=8; tagLiteral (4 bytes "abcd"); tagCopy1; length=4 offset=4; valid input`,
285 "\x08" + "\x0cabcd" + "\x01\x04",
286 "abcdabcd",
287 nil,
288 }, {
289 `decodedLen=8; tagLiteral (4 bytes "abcd"); tagCopy1; length=4 offset=2; valid input`,
290 "\x08" + "\x0cabcd" + "\x01\x02",
291 "abcdcdcd",
292 nil,
293 }, {
294 `decodedLen=8; tagLiteral (4 bytes "abcd"); tagCopy1; length=4 offset=1; valid input`,
295 "\x08" + "\x0cabcd" + "\x01\x01",
296 "abcddddd",
297 nil,
298 }, {
299 `decodedLen=8; tagLiteral (4 bytes "abcd"); tagCopy1; length=4 offset=0; zero offset`,
300 "\x08" + "\x0cabcd" + "\x01\x00",
301 "",
302 ErrCorrupt,
303 }, {
304 `decodedLen=9; tagLiteral (4 bytes "abcd"); tagCopy1; length=4 offset=4; inconsistent dLen`,
305 "\x09" + "\x0cabcd" + "\x01\x04",
306 "",
307 ErrCorrupt,
308 }, {
309 `decodedLen=8; tagLiteral (4 bytes "abcd"); tagCopy1; length=4 offset=5; offset too large`,
310 "\x08" + "\x0cabcd" + "\x01\x05",
311 "",
312 ErrCorrupt,
313 }, {
314 `decodedLen=7; tagLiteral (4 bytes "abcd"); tagCopy1; length=4 offset=4; length too large`,
315 "\x07" + "\x0cabcd" + "\x01\x04",
316 "",
317 ErrCorrupt,
318 }, {
319 `decodedLen=6; tagLiteral (4 bytes "abcd"); tagCopy2; length=2 offset=3; valid input`,
320 "\x06" + "\x0cabcd" + "\x06\x03\x00",
321 "abcdbc",
322 nil,
323 }, {
324 `decodedLen=6; tagLiteral (4 bytes "abcd"); tagCopy4; length=2 offset=3; valid input`,
325 "\x06" + "\x0cabcd" + "\x07\x03\x00\x00\x00",
326 "abcdbc",
327 nil,
328 }, {
329 `decodedLen=0; tagCopy4, 4 extra length|offset bytes; with msb set (0x93); discovered by go-fuzz`,
330 "\x00\xfc000\x93",
331 "",
332 ErrCorrupt,
333 }}
334
335 const (
336 // notPresentXxx defines a range of byte values [0xa0, 0xc5) that are
337 // not present in either the input or the output. It is written to dBuf
338 // to check that Decode does not write bytes past the end of
339 // dBuf[:dLen].
340 //
341 // The magic number 37 was chosen because it is prime. A more 'natural'
342 // number like 32 might lead to a false negative if, for example, a
343 // byte was incorrectly copied 4*8 bytes later.
344 notPresentBase = 0xa0
345 notPresentLen = 37
346 )
347
348 var dBuf [100]byte
349 loop:
350 for i, tc := range testCases {
351 input := []byte(tc.input)
352 for _, x := range input {
353 if notPresentBase <= x && x < notPresentBase+notPresentLen {
354 t.Errorf("#%d (%s): input shouldn't contain %#02x\ninput: % x", i, tc.desc, x, input)
355 continue loop
356 }
357 }
358
359 dLen, n := binary.Uvarint(input)
360 if n <= 0 {
361 t.Errorf("#%d (%s): invalid varint-encoded dLen", i, tc.desc)
362 continue
363 }
364 if dLen > uint64(len(dBuf)) {
365 t.Errorf("#%d (%s): dLen %d is too large", i, tc.desc, dLen)
366 continue
367 }
368
369 for j := range dBuf {
370 dBuf[j] = byte(notPresentBase + j%notPresentLen)
371 }
372 g, gotErr := Decode(dBuf[:], input)
373 if got := string(g); got != tc.want || gotErr != tc.wantErr {
374 t.Errorf("#%d (%s):\ngot %q, %v\nwant %q, %v",
375 i, tc.desc, got, gotErr, tc.want, tc.wantErr)
376 continue
377 }
378 for j, x := range dBuf {
379 if uint64(j) < dLen {
380 continue
381 }
382 if w := byte(notPresentBase + j%notPresentLen); x != w {
383 t.Errorf("#%d (%s): Decode overrun: dBuf[%d] was modified: got %#02x, want %#02x\ndBuf: % x",
384 i, tc.desc, j, x, w, dBuf)
385 continue loop
386 }
387 }
388 }
389 }
390
391 func TestDecodeCopy4(t *testing.T) {
392 dots := strings.Repeat(".", 65536)
393
394 input := strings.Join([]string{
395 "\x89\x80\x04", // decodedLen = 65545.
396 "\x0cpqrs", // 4-byte literal "pqrs".
397 "\xf4\xff\xff" + dots, // 65536-byte literal dots.
398 "\x13\x04\x00\x01\x00", // tagCopy4; length=5 offset=65540.
399 }, "")
400
401 gotBytes, err := Decode(nil, []byte(input))
402 if err != nil {
403 t.Fatal(err)
404 }
405 got := string(gotBytes)
406 want := "pqrs" + dots + "pqrs."
407 if len(got) != len(want) {
408 t.Fatalf("got %d bytes, want %d", len(got), len(want))
409 }
410 if got != want {
411 for i := 0; i < len(got); i++ {
412 if g, w := got[i], want[i]; g != w {
413 t.Fatalf("byte #%d: got %#02x, want %#02x", i, g, w)
414 }
415 }
416 }
417 }
418
419 // TestDecodeLengthOffset tests decoding an encoding of the form literal +
420 // copy-length-offset + literal. For example: "abcdefghijkl" + "efghij" + "AB".
421 func TestDecodeLengthOffset(t *testing.T) {
422 const (
423 prefix = "abcdefghijklmnopqr"
424 suffix = "ABCDEFGHIJKLMNOPQR"
425
426 // notPresentXxx defines a range of byte values [0xa0, 0xc5) that are
427 // not present in either the input or the output. It is written to
428 // gotBuf to check that Decode does not write bytes past the end of
429 // gotBuf[:totalLen].
430 //
431 // The magic number 37 was chosen because it is prime. A more 'natural'
432 // number like 32 might lead to a false negative if, for example, a
433 // byte was incorrectly copied 4*8 bytes later.
434 notPresentBase = 0xa0
435 notPresentLen = 37
436 )
437 var gotBuf, wantBuf, inputBuf [128]byte
438 for length := 1; length <= 18; length++ {
439 for offset := 1; offset <= 18; offset++ {
440 loop:
441 for suffixLen := 0; suffixLen <= 18; suffixLen++ {
442 totalLen := len(prefix) + length + suffixLen
443
444 inputLen := binary.PutUvarint(inputBuf[:], uint64(totalLen))
445 inputBuf[inputLen] = tagLiteral + 4*byte(len(prefix)-1)
446 inputLen++
447 inputLen += copy(inputBuf[inputLen:], prefix)
448 inputBuf[inputLen+0] = tagCopy2 + 4*byte(length-1)
449 inputBuf[inputLen+1] = byte(offset)
450 inputBuf[inputLen+2] = 0x00
451 inputLen += 3
452 if suffixLen > 0 {
453 inputBuf[inputLen] = tagLiteral + 4*byte(suffixLen-1)
454 inputLen++
455 inputLen += copy(inputBuf[inputLen:], suffix[:suffixLen])
456 }
457 input := inputBuf[:inputLen]
458
459 for i := range gotBuf {
460 gotBuf[i] = byte(notPresentBase + i%notPresentLen)
461 }
462 got, err := Decode(gotBuf[:], input)
463 if err != nil {
464 t.Errorf("length=%d, offset=%d; suffixLen=%d: %v", length, offset, suffixLen, err)
465 continue
466 }
467
468 wantLen := 0
469 wantLen += copy(wantBuf[wantLen:], prefix)
470 for i := 0; i < length; i++ {
471 wantBuf[wantLen] = wantBuf[wantLen-offset]
472 wantLen++
473 }
474 wantLen += copy(wantBuf[wantLen:], suffix[:suffixLen])
475 want := wantBuf[:wantLen]
476
477 for _, x := range input {
478 if notPresentBase <= x && x < notPresentBase+notPresentLen {
479 t.Errorf("length=%d, offset=%d; suffixLen=%d: input shouldn't contain %#02x\ninput: % x",
480 length, offset, suffixLen, x, input)
481 continue loop
482 }
483 }
484 for i, x := range gotBuf {
485 if i < totalLen {
486 continue
487 }
488 if w := byte(notPresentBase + i%notPresentLen); x != w {
489 t.Errorf("length=%d, offset=%d; suffixLen=%d; totalLen=%d: "+
490 "Decode overrun: gotBuf[%d] was modified: got %#02x, want %#02x\ngotBuf: % x",
491 length, offset, suffixLen, totalLen, i, x, w, gotBuf)
492 continue loop
493 }
494 }
495 for _, x := range want {
496 if notPresentBase <= x && x < notPresentBase+notPresentLen {
497 t.Errorf("length=%d, offset=%d; suffixLen=%d: want shouldn't contain %#02x\nwant: % x",
498 length, offset, suffixLen, x, want)
499 continue loop
500 }
501 }
502
503 if !bytes.Equal(got, want) {
504 t.Errorf("length=%d, offset=%d; suffixLen=%d:\ninput % x\ngot % x\nwant % x",
505 length, offset, suffixLen, input, got, want)
506 continue
507 }
508 }
509 }
510 }
511 }
512
513 const (
514 goldenText = "Isaac.Newton-Opticks.txt"
515 goldenCompressed = goldenText + ".rawsnappy"
516 )
517
518 func TestDecodeGoldenInput(t *testing.T) {
519 tDir := filepath.FromSlash(*testdataDir)
520 src, err := os.ReadFile(filepath.Join(tDir, goldenCompressed))
521 if err != nil {
522 t.Fatalf("ReadFile: %v", err)
523 }
524 got, err := Decode(nil, src)
525 if err != nil {
526 t.Fatalf("Decode: %v", err)
527 }
528 want, err := os.ReadFile(filepath.Join(tDir, goldenText))
529 if err != nil {
530 t.Fatalf("ReadFile: %v", err)
531 }
532 if err := cmp(got, want); err != nil {
533 t.Fatal(err)
534 }
535 }
536
537 // TestSlowForwardCopyOverrun tests the "expand the pattern" algorithm
538 // described in decode_amd64.s and its claim of a 10 byte overrun worst case.
539 func TestSlowForwardCopyOverrun(t *testing.T) {
540 const base = 100
541
542 for length := 1; length < 18; length++ {
543 for offset := 1; offset < 18; offset++ {
544 highWaterMark := base
545 d := base
546 l := length
547 o := offset
548
549 // makeOffsetAtLeast8
550 for o < 8 {
551 if end := d + 8; highWaterMark < end {
552 highWaterMark = end
553 }
554 l -= o
555 d += o
556 o += o
557 }
558
559 // fixUpSlowForwardCopy
560 a := d
561 d += l
562
563 // finishSlowForwardCopy
564 for l > 0 {
565 if end := a + 8; highWaterMark < end {
566 highWaterMark = end
567 }
568 a += 8
569 l -= 8
570 }
571
572 dWant := base + length
573 overrun := highWaterMark - dWant
574 if d != dWant || overrun < 0 || 10 < overrun {
575 t.Errorf("length=%d, offset=%d: d and overrun: got (%d, %d), want (%d, something in [0, 10])",
576 length, offset, d, overrun, dWant)
577 }
578 }
579 }
580 }
581
582 // TestEncodeNoiseThenRepeats encodes input for which the first half is very
583 // incompressible and the second half is very compressible. The encoded form's
584 // length should be closer to 50% of the original length than 100%.
585 func TestEncodeNoiseThenRepeats(t *testing.T) {
586 for _, origLen := range []int{256 * 1024, 2048 * 1024} {
587 src := make([]byte, origLen)
588 rng := rand.New(rand.NewSource(1))
589 firstHalf, secondHalf := src[:origLen/2], src[origLen/2:]
590 for i := range firstHalf {
591 firstHalf[i] = uint8(rng.Intn(256))
592 }
593 for i := range secondHalf {
594 secondHalf[i] = uint8(i >> 8)
595 }
596 dst := Encode(nil, src)
597 t.Log(origLen, "->", len(dst))
598 if got, want := len(dst), origLen*3/4; got >= want {
599 t.Errorf("origLen=%d: got %d encoded bytes, want less than %d", origLen, got, want)
600 }
601 }
602 }
603
604 func TestFramingFormat(t *testing.T) {
605 // src is comprised of alternating 1e5-sized sequences of random
606 // (incompressible) bytes and repeated (compressible) bytes. 1e5 was chosen
607 // because it is larger than maxBlockSize (64k).
608 src := make([]byte, 1e6)
609 rng := rand.New(rand.NewSource(1))
610 for i := range 10 {
611 if i%2 == 0 {
612 for j := range int(1e5) {
613 src[1e5*i+j] = uint8(rng.Intn(256))
614 }
615 } else {
616 for j := range int(1e5) {
617 src[1e5*i+j] = uint8(i)
618 }
619 }
620 }
621
622 buf := new(bytes.Buffer)
623 if _, err := NewWriter(buf).Write(src); err != nil {
624 t.Fatalf("Write: encoding: %v", err)
625 }
626 dst, err := io.ReadAll(NewReader(buf))
627 if err != nil {
628 t.Fatalf("ReadAll: decoding: %v", err)
629 }
630 if err := cmp(dst, src); err != nil {
631 t.Fatal(err)
632 }
633 }
634
635 func TestWriterGoldenOutput(t *testing.T) {
636 buf := new(bytes.Buffer)
637 w := NewBufferedWriter(buf)
638 defer w.Close()
639 w.Write([]byte("abcd")) // Not compressible.
640 w.Flush()
641 w.Write(bytes.Repeat([]byte{'A'}, 150)) // Compressible.
642 w.Flush()
643 // The next chunk is also compressible, but a naive, greedy encoding of the
644 // overall length 67 copy as a length 64 copy (the longest expressible as a
645 // tagCopy1 or tagCopy2) plus a length 3 remainder would be two 3-byte
646 // tagCopy2 tags (6 bytes), since the minimum length for a tagCopy1 is 4
647 // bytes. Instead, we could do it shorter, in 5 bytes: a 3-byte tagCopy2
648 // (of length 60) and a 2-byte tagCopy1 (of length 7).
649 w.Write(bytes.Repeat([]byte{'B'}, 68))
650 w.Write([]byte("efC")) // Not compressible.
651 w.Write(bytes.Repeat([]byte{'C'}, 20)) // Compressible.
652 w.Write(bytes.Repeat([]byte{'B'}, 20)) // Compressible.
653 w.Write([]byte("g")) // Not compressible.
654 w.Flush()
655
656 got := buf.String()
657 want := strings.Join([]string{
658 magicChunk,
659 "\x01\x08\x00\x00", // Uncompressed chunk, 8 bytes long (including 4 byte checksum).
660 "\x68\x10\xe6\xb6", // Checksum.
661 "\x61\x62\x63\x64", // Uncompressed payload: "abcd".
662 "\x00\x11\x00\x00", // Compressed chunk, 17 bytes long (including 4 byte checksum).
663 "\x5f\xeb\xf2\x10", // Checksum.
664 "\x96\x01", // Compressed payload: Uncompressed length (varint encoded): 150.
665 "\x00\x41", // Compressed payload: tagLiteral, length=1, "A".
666 "\xee\x01\x00", // Compressed payload: tagCopy2, length=60, offset=1.
667 "\xee\x01\x00", // Compressed payload: tagCopy2, length=60, offset=1.
668 "\x72\x01\x00", // Compressed payload: tagCopy2, length=29, offset=1.
669 "\x00\x18\x00\x00", // Compressed chunk, 24 bytes long (including 4 byte checksum).
670 "\x30\x85\x69\xeb", // Checksum.
671 "\x70", // Compressed payload: Uncompressed length (varint encoded): 112.
672 "\x00\x42", // Compressed payload: tagLiteral, length=1, "B".
673 "\xee\x01\x00", // Compressed payload: tagCopy2, length=60, offset=1.
674 "\x0d\x01", // Compressed payload: tagCopy1, length=7, offset=1.
675 "\x08\x65\x66\x43", // Compressed payload: tagLiteral, length=3, "efC".
676 "\x4e\x01\x00", // Compressed payload: tagCopy2, length=20, offset=1.
677 "\x4e\x3a\x00", // Compressed payload: tagCopy2, length=20, offset=58.
678 "\x00\x67", // Compressed payload: tagLiteral, length=1, "g".
679 }, "")
680 if got != want {
681 dec := NewReader(bytes.NewBuffer(buf.Bytes()))
682 var buf bytes.Buffer
683 io.Copy(&buf, dec)
684 t.Fatalf("\ngot: % x\nwant: % x", got, want)
685 }
686 }
687
688 func TestNewBufferedWriter(t *testing.T) {
689 // Test all 32 possible sub-sequences of these 5 input slices.
690 //
691 // Their lengths sum to 400,000, which is over 6 times the Writer ibuf
692 // capacity: 6 * maxBlockSize is 393,216.
693 inputs := [][]byte{
694 bytes.Repeat([]byte{'a'}, 40000),
695 bytes.Repeat([]byte{'b'}, 150000),
696 bytes.Repeat([]byte{'c'}, 60000),
697 bytes.Repeat([]byte{'d'}, 120000),
698 bytes.Repeat([]byte{'e'}, 30000),
699 }
700 loop:
701 for i := 0; i < 1<<uint(len(inputs)); i++ {
702 var want []byte
703 buf := new(bytes.Buffer)
704 w := NewBufferedWriter(buf)
705 for j, input := range inputs {
706 if i&(1<<uint(j)) == 0 {
707 continue
708 }
709 if _, err := w.Write(input); err != nil {
710 t.Errorf("i=%#02x: j=%d: Write: %v", i, j, err)
711 continue loop
712 }
713 want = append(want, input...)
714 }
715 if err := w.Close(); err != nil {
716 t.Errorf("i=%#02x: Close: %v", i, err)
717 continue
718 }
719 got, err := io.ReadAll(NewReader(buf))
720 if err != nil {
721 t.Errorf("i=%#02x: ReadAll: %v", i, err)
722 continue
723 }
724 if err := cmp(got, want); err != nil {
725 t.Errorf("i=%#02x: %v", i, err)
726 continue
727 }
728 }
729 }
730
731 func TestFlush(t *testing.T) {
732 buf := new(bytes.Buffer)
733 w := NewBufferedWriter(buf)
734 defer w.Close()
735 if _, err := w.Write(bytes.Repeat([]byte{'x'}, 20)); err != nil {
736 t.Fatalf("Write: %v", err)
737 }
738 if n := buf.Len(); n != 0 {
739 t.Fatalf("before Flush: %d bytes were written to the underlying io.Writer, want 0", n)
740 }
741 if err := w.Flush(); err != nil {
742 t.Fatalf("Flush: %v", err)
743 }
744 if n := buf.Len(); n == 0 {
745 t.Fatalf("after Flush: %d bytes were written to the underlying io.Writer, want non-0", n)
746 }
747 }
748
749 func TestReaderUncompressedDataOK(t *testing.T) {
750 r := NewReader(strings.NewReader(magicChunk +
751 "\x01\x08\x00\x00" + // Uncompressed chunk, 8 bytes long (including 4 byte checksum).
752 "\x68\x10\xe6\xb6" + // Checksum.
753 "\x61\x62\x63\x64", // Uncompressed payload: "abcd".
754 ))
755 g, err := io.ReadAll(r)
756 if err != nil {
757 t.Fatal(err)
758 }
759 if got, want := string(g), "abcd"; got != want {
760 t.Fatalf("got %q, want %q", got, want)
761 }
762 }
763
764 func TestReaderUncompressedDataNoPayload(t *testing.T) {
765 r := NewReader(strings.NewReader(magicChunk +
766 "\x01\x04\x00\x00" + // Uncompressed chunk, 4 bytes long.
767 "", // No payload; corrupt input.
768 ))
769 if _, err := io.ReadAll(r); err != ErrCorrupt {
770 t.Fatalf("got %v, want %v", err, ErrCorrupt)
771 }
772 }
773
774 func TestReaderUncompressedDataTooLong(t *testing.T) {
775 // https://github.com/google/snappy/blob/master/framing_format.txt section
776 // 4.3 says that "the maximum legal chunk length... is 65540", or 0x10004.
777 const n = 0x10005
778
779 r := NewReader(strings.NewReader(magicChunk +
780 "\x01\x05\x00\x01" + // Uncompressed chunk, n bytes long.
781 strings.Repeat("\x00", n),
782 ))
783 if _, err := io.ReadAll(r); err != ErrCorrupt {
784 t.Fatalf("got %v, want %v", err, ErrCorrupt)
785 }
786 }
787
788 func TestReaderReset(t *testing.T) {
789 gold := bytes.Repeat([]byte("All that is gold does not glitter,\n"), 10000)
790 buf := new(bytes.Buffer)
791 if _, err := NewWriter(buf).Write(gold); err != nil {
792 t.Fatalf("Write: %v", err)
793 }
794 encoded, invalid, partial := buf.String(), "invalid", "partial"
795 r := NewReader(nil)
796 for i, s := range []string{encoded, invalid, partial, encoded, partial, invalid, encoded, encoded} {
797 if s == partial {
798 r.Reset(strings.NewReader(encoded))
799 if _, err := r.Read(make([]byte, 101)); err != nil {
800 t.Errorf("#%d: %v", i, err)
801 continue
802 }
803 continue
804 }
805 r.Reset(strings.NewReader(s))
806 got, err := io.ReadAll(r)
807 switch s {
808 case encoded:
809 if err != nil {
810 t.Errorf("#%d: %v", i, err)
811 continue
812 }
813 if err := cmp(got, gold); err != nil {
814 t.Errorf("#%d: %v", i, err)
815 continue
816 }
817 case invalid:
818 if err == nil {
819 t.Errorf("#%d: got nil error, want non-nil", i)
820 continue
821 }
822 }
823 }
824 }
825
826 func TestReaderReadByte(t *testing.T) {
827 // Test all 32 possible sub-sequences of these 5 input slices prefixed by
828 // their size encoded as a uvarint.
829 //
830 // Their lengths sum to 400,000, which is over 6 times the Writer ibuf
831 // capacity: 6 * maxBlockSize is 393,216.
832 inputs := [][]byte{
833 bytes.Repeat([]byte{'a'}, 40000),
834 bytes.Repeat([]byte{'b'}, 150000),
835 bytes.Repeat([]byte{'c'}, 60000),
836 bytes.Repeat([]byte{'d'}, 120000),
837 bytes.Repeat([]byte{'e'}, 30000),
838 }
839 loop:
840 for i := 0; i < 1<<uint(len(inputs)); i++ {
841 var want []int
842 buf := new(bytes.Buffer)
843 w := NewBufferedWriter(buf)
844 p := make([]byte, binary.MaxVarintLen64)
845 for j, input := range inputs {
846 if i&(1<<uint(j)) == 0 {
847 continue
848 }
849 n := binary.PutUvarint(p, uint64(len(input)))
850 if _, err := w.Write(p[:n]); err != nil {
851 t.Errorf("i=%#02x: j=%d: Write Uvarint: %v", i, j, err)
852 continue loop
853 }
854 if _, err := w.Write(input); err != nil {
855 t.Errorf("i=%#02x: j=%d: Write: %v", i, j, err)
856 continue loop
857 }
858 want = append(want, j)
859 }
860 if err := w.Close(); err != nil {
861 t.Errorf("i=%#02x: Close: %v", i, err)
862 continue
863 }
864 r := NewReader(buf)
865 for _, j := range want {
866 size, err := binary.ReadUvarint(r)
867 if err != nil {
868 t.Errorf("i=%#02x: ReadUvarint: %v", i, err)
869 continue loop
870 }
871 if wantedSize := uint64(len(inputs[j])); size != wantedSize {
872 t.Errorf("i=%#02x: expected size %d, got %d", i, wantedSize, size)
873 continue loop
874 }
875 got := make([]byte, size)
876 if _, err := io.ReadFull(r, got); err != nil {
877 t.Errorf("i=%#02x: ReadFull: %v", i, err)
878 continue loop
879 }
880 if err := cmp(got, inputs[j]); err != nil {
881 t.Errorf("i=%#02x: %v", i, err)
882 continue
883 }
884 }
885 if _, err := r.ReadByte(); err != io.EOF {
886 t.Errorf("i=%#02x: expected size EOF, got %v", i, err)
887 }
888 }
889 }
890
891 func TestWriterReset(t *testing.T) {
892 gold := bytes.Repeat([]byte("Not all those who wander are lost;\n"), 10000)
893 const n = 20
894 for _, buffered := range []bool{false, true} {
895 var w *Writer
896 if buffered {
897 w = NewBufferedWriter(nil)
898 defer w.Close()
899 } else {
900 w = NewWriter(nil)
901 }
902
903 var gots, wants [][]byte
904 failed := false
905 for i := 0; i <= n; i++ {
906 buf := new(bytes.Buffer)
907 w.Reset(buf)
908 want := gold[:len(gold)*i/n]
909 if _, err := w.Write(want); err != nil {
910 t.Errorf("#%d: Write: %v", i, err)
911 failed = true
912 continue
913 }
914 if buffered {
915 if err := w.Flush(); err != nil {
916 t.Errorf("#%d: Flush: %v", i, err)
917 failed = true
918 continue
919 }
920 }
921 got, err := io.ReadAll(NewReader(buf))
922 if err != nil {
923 t.Errorf("#%d: ReadAll: %v", i, err)
924 failed = true
925 continue
926 }
927 gots = append(gots, got)
928 wants = append(wants, want)
929 }
930 if failed {
931 continue
932 }
933 for i := range gots {
934 if err := cmp(gots[i], wants[i]); err != nil {
935 t.Errorf("#%d: %v", i, err)
936 }
937 }
938 }
939 }
940
941 func TestWriterResetWithoutFlush(t *testing.T) {
942 buf0 := new(bytes.Buffer)
943 buf1 := new(bytes.Buffer)
944 w := NewBufferedWriter(buf0)
945 if _, err := w.Write([]byte("xxx")); err != nil {
946 t.Fatalf("Write #0: %v", err)
947 }
948 // Note that we don't Flush the Writer before calling Reset.
949 w.Reset(buf1)
950 if _, err := w.Write([]byte("yyy")); err != nil {
951 t.Fatalf("Write #1: %v", err)
952 }
953 if err := w.Flush(); err != nil {
954 t.Fatalf("Flush: %v", err)
955 }
956 got, err := io.ReadAll(NewReader(buf1))
957 if err != nil {
958 t.Fatalf("ReadAll: %v", err)
959 }
960 if err := cmp(got, []byte("yyy")); err != nil {
961 t.Fatal(err)
962 }
963 }
964
965 type writeCounter int
966
967 func (c *writeCounter) Write(p []byte) (int, error) {
968 *c++
969 return len(p), nil
970 }
971
972 // TestNumUnderlyingWrites tests that each Writer flush only makes one or two
973 // Write calls on its underlying io.Writer, depending on whether or not the
974 // flushed buffer was compressible.
975 func TestNumUnderlyingWrites(t *testing.T) {
976 testCases := []struct {
977 input []byte
978 max int
979 }{
980 {bytes.Repeat([]byte{'x'}, 100), 2}, // Frame header + block...
981 {bytes.Repeat([]byte{'y'}, 100), 2},
982 {[]byte("ABCDEFGHIJKLMNOPQRST"), 2},
983 }
984
985 var c writeCounter
986 w := NewBufferedWriter(&c)
987 defer w.Close()
988 for i, tc := range testCases {
989 c = 0
990 if _, err := w.Write(tc.input); err != nil {
991 t.Errorf("#%d: Write: %v", i, err)
992 continue
993 }
994 if err := w.Flush(); err != nil {
995 t.Errorf("#%d: Flush: %v", i, err)
996 continue
997 }
998 if int(c) > tc.max {
999 t.Errorf("#%d: got %d underlying writes, want max %d", i, c, tc.max)
1000 continue
1001 }
1002 }
1003 }
1004
1005 func benchDecode(b *testing.B, src []byte) {
1006 encoded := Encode(nil, src)
1007 // Bandwidth is in amount of uncompressed data.
1008 b.SetBytes(int64(len(src)))
1009 b.ResetTimer()
1010 for i := 0; i < b.N; i++ {
1011 Decode(src, encoded)
1012 }
1013 }
1014
1015 func benchEncode(b *testing.B, src []byte) {
1016 // Bandwidth is in amount of uncompressed data.
1017 b.SetBytes(int64(len(src)))
1018 dst := make([]byte, MaxEncodedLen(len(src)))
1019 b.ResetTimer()
1020 for i := 0; i < b.N; i++ {
1021 Encode(dst, src)
1022 }
1023 }
1024
1025 func testOrBenchmark(b testing.TB) string {
1026 if _, ok := b.(*testing.B); ok {
1027 return "benchmark"
1028 }
1029 return "test"
1030 }
1031
1032 func readFile(b testing.TB, filename string) []byte {
1033 src, err := os.ReadFile(filename)
1034 if err != nil {
1035 b.Skipf("skipping %s: %v", testOrBenchmark(b), err)
1036 }
1037 if len(src) == 0 {
1038 b.Fatalf("%s has zero length", filename)
1039 }
1040 return src
1041 }
1042
1043 // expand returns a slice of length n containing repeated copies of src.
1044 func expand(src []byte, n int) []byte {
1045 dst := make([]byte, n)
1046 for x := dst; len(x) > 0; {
1047 i := copy(x, src)
1048 x = x[i:]
1049 }
1050 return dst
1051 }
1052
1053 func benchWords(b *testing.B, n int, decode bool) {
1054 // Note: the file is OS-language dependent so the resulting values are not
1055 // directly comparable for non-US-English OS installations.
1056 data := expand(readFile(b, "/usr/share/dict/words"), n)
1057 if decode {
1058 benchDecode(b, data)
1059 } else {
1060 benchEncode(b, data)
1061 }
1062 }
1063
1064 func BenchmarkWordsDecode1e1(b *testing.B) { benchWords(b, 1e1, true) }
1065 func BenchmarkWordsDecode1e2(b *testing.B) { benchWords(b, 1e2, true) }
1066 func BenchmarkWordsDecode1e3(b *testing.B) { benchWords(b, 1e3, true) }
1067 func BenchmarkWordsDecode1e4(b *testing.B) { benchWords(b, 1e4, true) }
1068 func BenchmarkWordsDecode1e5(b *testing.B) { benchWords(b, 1e5, true) }
1069 func BenchmarkWordsDecode1e6(b *testing.B) { benchWords(b, 1e6, true) }
1070 func BenchmarkWordsEncode1e1(b *testing.B) { benchWords(b, 1e1, false) }
1071 func BenchmarkWordsEncode1e2(b *testing.B) { benchWords(b, 1e2, false) }
1072 func BenchmarkWordsEncode1e3(b *testing.B) { benchWords(b, 1e3, false) }
1073 func BenchmarkWordsEncode1e4(b *testing.B) { benchWords(b, 1e4, false) }
1074 func BenchmarkWordsEncode1e5(b *testing.B) { benchWords(b, 1e5, false) }
1075 func BenchmarkWordsEncode1e6(b *testing.B) { benchWords(b, 1e6, false) }
1076
1077 func BenchmarkRandomEncode(b *testing.B) {
1078 rng := rand.New(rand.NewSource(1))
1079 data := make([]byte, 1<<20)
1080 for i := range data {
1081 data[i] = uint8(rng.Intn(256))
1082 }
1083 benchEncode(b, data)
1084 }
1085
1086 // testFiles' values are copied directly from
1087 // https://raw.githubusercontent.com/google/snappy/master/snappy_unittest.cc
1088 // The label field is unused in snappy-go.
1089 var testFiles = []struct {
1090 label string
1091 filename string
1092 sizeLimit int
1093 }{
1094 {"html", "html", 0},
1095 {"urls", "urls.10K", 0},
1096 {"jpg", "fireworks.jpeg", 0},
1097 {"jpg_200", "fireworks.jpeg", 200},
1098 {"pdf", "paper-100k.pdf", 0},
1099 {"html4", "html_x_4", 0},
1100 {"txt1", "alice29.txt", 0},
1101 {"txt2", "asyoulik.txt", 0},
1102 {"txt3", "lcet10.txt", 0},
1103 {"txt4", "plrabn12.txt", 0},
1104 {"pb", "geo.protodata", 0},
1105 {"gaviota", "kppkn.gtb", 0},
1106 }
1107
1108 const (
1109 // The benchmark data files are at this canonical URL.
1110 benchURL = "https://raw.githubusercontent.com/google/snappy/master/testdata/"
1111 )
1112
1113 func downloadBenchmarkFiles(b testing.TB, basename string) (errRet error) {
1114 bDir := filepath.FromSlash(*benchdataDir)
1115 filename := filepath.Join(bDir, basename)
1116 if stat, err := os.Stat(filename); err == nil && stat.Size() != 0 {
1117 return nil
1118 }
1119
1120 if !*download {
1121 b.Skipf("test data not found; skipping %s without the -download flag", testOrBenchmark(b))
1122 }
1123 // Download the official snappy C++ implementation reference test data
1124 // files for benchmarking.
1125 if err := os.MkdirAll(bDir, 0777); err != nil && !os.IsExist(err) {
1126 return fmt.Errorf("failed to create %s: %s", bDir, err)
1127 }
1128
1129 f, err := os.Create(filename)
1130 if err != nil {
1131 return fmt.Errorf("failed to create %s: %s", filename, err)
1132 }
1133 defer f.Close()
1134 defer func() {
1135 if errRet != nil {
1136 os.Remove(filename)
1137 }
1138 }()
1139 url := benchURL + basename
1140 resp, err := http.Get(url)
1141 if err != nil {
1142 return fmt.Errorf("failed to download %s: %s", url, err)
1143 }
1144 defer resp.Body.Close()
1145 if s := resp.StatusCode; s != http.StatusOK {
1146 return fmt.Errorf("downloading %s: HTTP status code %d (%s)", url, s, http.StatusText(s))
1147 }
1148 _, err = io.Copy(f, resp.Body)
1149 if err != nil {
1150 return fmt.Errorf("failed to download %s to %s: %s", url, filename, err)
1151 }
1152 return nil
1153 }
1154
1155 func benchFile(b *testing.B, i int, decode bool) {
1156 if err := downloadBenchmarkFiles(b, testFiles[i].filename); err != nil {
1157 b.Fatalf("failed to download testdata: %s", err)
1158 }
1159 bDir := filepath.FromSlash(*benchdataDir)
1160 data := readFile(b, filepath.Join(bDir, testFiles[i].filename))
1161 if n := testFiles[i].sizeLimit; 0 < n && n < len(data) {
1162 data = data[:n]
1163 }
1164 if decode {
1165 benchDecode(b, data)
1166 } else {
1167 benchEncode(b, data)
1168 }
1169 }
1170
1171 // Naming convention is kept similar to what snappy's C++ implementation uses.
1172 func Benchmark_UFlat0(b *testing.B) { benchFile(b, 0, true) }
1173 func Benchmark_UFlat1(b *testing.B) { benchFile(b, 1, true) }
1174 func Benchmark_UFlat2(b *testing.B) { benchFile(b, 2, true) }
1175 func Benchmark_UFlat3(b *testing.B) { benchFile(b, 3, true) }
1176 func Benchmark_UFlat4(b *testing.B) { benchFile(b, 4, true) }
1177 func Benchmark_UFlat5(b *testing.B) { benchFile(b, 5, true) }
1178 func Benchmark_UFlat6(b *testing.B) { benchFile(b, 6, true) }
1179 func Benchmark_UFlat7(b *testing.B) { benchFile(b, 7, true) }
1180 func Benchmark_UFlat8(b *testing.B) { benchFile(b, 8, true) }
1181 func Benchmark_UFlat9(b *testing.B) { benchFile(b, 9, true) }
1182 func Benchmark_UFlat10(b *testing.B) { benchFile(b, 10, true) }
1183 func Benchmark_UFlat11(b *testing.B) { benchFile(b, 11, true) }
1184 func Benchmark_ZFlat0(b *testing.B) { benchFile(b, 0, false) }
1185 func Benchmark_ZFlat1(b *testing.B) { benchFile(b, 1, false) }
1186 func Benchmark_ZFlat2(b *testing.B) { benchFile(b, 2, false) }
1187 func Benchmark_ZFlat3(b *testing.B) { benchFile(b, 3, false) }
1188 func Benchmark_ZFlat4(b *testing.B) { benchFile(b, 4, false) }
1189 func Benchmark_ZFlat5(b *testing.B) { benchFile(b, 5, false) }
1190 func Benchmark_ZFlat6(b *testing.B) { benchFile(b, 6, false) }
1191 func Benchmark_ZFlat7(b *testing.B) { benchFile(b, 7, false) }
1192 func Benchmark_ZFlat8(b *testing.B) { benchFile(b, 8, false) }
1193 func Benchmark_ZFlat9(b *testing.B) { benchFile(b, 9, false) }
1194 func Benchmark_ZFlat10(b *testing.B) { benchFile(b, 10, false) }
1195 func Benchmark_ZFlat11(b *testing.B) { benchFile(b, 11, false) }