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.
25 download = flag.Bool("download", false, "If true, download any missing files before running benchmarks")
26 testdataDir = flag.String("testdataDir", "testdata", "Directory containing the test data")
27 benchdataDir = flag.String("benchdataDir", "testdata/bench", "Directory containing the benchmark data")
30 // goEncoderShouldMatchCppEncoder is whether to test that the algorithm used by
31 // Go's encoder matches byte-for-byte what the C++ snappy encoder produces, on
32 // this GOARCH. There is more than one valid encoding of any given input, and
33 // there is more than one good algorithm along the frontier of trading off
34 // throughput for output size. Nonetheless, we presume that the C++ encoder's
35 // algorithm is a good one and has been tested on a wide range of inputs, so
36 // matching that exactly should mean that the Go encoder's algorithm is also
37 // good, without needing to gather our own corpus of test data.
39 // The exact algorithm used by the C++ code is potentially endian dependent, as
40 // it puns a byte pointer to a uint32 pointer to load, hash and compare 4 bytes
41 // at a time. The Go implementation is endian agnostic, in that its output is
42 // the same (as little-endian C++ code), regardless of the CPU's endianness.
44 // Thus, when comparing Go's output to C++ output generated beforehand, such as
45 // the "testdata/pi.txt.rawsnappy" file generated by C++ code on a little-
46 // endian system, we can run that test regardless of the runtime.GOARCH value.
48 // When comparing Go's output to dynamically generated C++ output, i.e. the
49 // result of fork/exec'ing a C++ program, we can run that test only on
50 // little-endian systems, because the C++ output might be different on
51 // big-endian systems. The runtime package doesn't export endianness per se,
52 // but we can restrict this match-C++ test to common little-endian systems.
53 const goEncoderShouldMatchCppEncoder = runtime.GOARCH == "386" || runtime.GOARCH == "amd64" || runtime.GOARCH == "arm"
55 func TestMaxEncodedLenOfMaxBlockSize(t *testing.T) {
56 got := maxEncodedLenOfMaxBlockSize
57 want := MaxEncodedLen(maxBlockSize)
59 t.Fatalf("got %d, want %d", got, want)
63 func cmp(a, b []byte) error {
64 if bytes.Equal(a, b) {
68 return fmt.Errorf("got %d bytes, want %d", len(a), len(b))
72 return fmt.Errorf("byte #%d: got 0x%02x, want 0x%02x", i, a[i], b[i])
78 func roundtrip(b, ebuf, dbuf []byte) error {
79 d, err := Decode(dbuf, Encode(ebuf, b))
81 return fmt.Errorf("decoding error: %v", err)
83 if err := cmp(d, b); err != nil {
84 return fmt.Errorf("roundtrip mismatch: %v", err)
89 func TestEmpty(t *testing.T) {
90 if err := roundtrip(nil, nil, nil); err != nil {
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 := 0; i < 32; i++ {
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)
108 func TestSmallRand(t *testing.T) {
109 rng := rand.New(rand.NewSource(1))
110 for n := 1; n < 20000; n += 23 {
113 b[i] = uint8(rng.Intn(256))
115 if err := roundtrip(b, nil, nil); err != nil {
121 func TestSmallRegular(t *testing.T) {
122 for n := 1; n < 20000; n += 23 {
125 b[i] = uint8(i%10 + 'a')
127 if err := roundtrip(b, nil, nil); err != nil {
133 func TestInvalidVarint(t *testing.T) {
134 testCases := []struct {
138 "invalid varint, final byte has continuation bit set",
141 "invalid varint, value overflows uint64",
142 "\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\x00",
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",
151 for _, tc := range testCases {
152 input := []byte(tc.input)
153 if _, err := DecodedLen(input); err != ErrCorrupt {
154 t.Errorf("%s: DecodedLen: got %v, want ErrCorrupt", tc.desc, err)
156 if _, err := Decode(nil, input); err != ErrCorrupt {
157 t.Errorf("%s: Decode: got %v, want ErrCorrupt", tc.desc, err)
162 func TestDecode(t *testing.T) {
163 lit40Bytes := make([]byte, 40)
164 for i := range lit40Bytes {
165 lit40Bytes[i] = byte(i)
167 lit40 := string(lit40Bytes)
169 testCases := []struct {
175 `decodedLen=0; valid input`,
180 `decodedLen=3; tagLiteral, 0-byte length; length=3; valid input`,
181 "\x03" + "\x08\xff\xff\xff",
185 `decodedLen=2; tagLiteral, 0-byte length; length=3; not enough dst bytes`,
186 "\x02" + "\x08\xff\xff\xff",
190 `decodedLen=3; tagLiteral, 0-byte length; length=3; not enough src bytes`,
191 "\x03" + "\x08\xff\xff",
195 `decodedLen=40; tagLiteral, 0-byte length; length=40; valid input`,
196 "\x28" + "\x9c" + lit40,
200 `decodedLen=1; tagLiteral, 1-byte length; not enough length bytes`,
205 `decodedLen=3; tagLiteral, 1-byte length; length=3; valid input`,
206 "\x03" + "\xf0\x02\xff\xff\xff",
210 `decodedLen=1; tagLiteral, 2-byte length; not enough length bytes`,
215 `decodedLen=3; tagLiteral, 2-byte length; length=3; valid input`,
216 "\x03" + "\xf4\x02\x00\xff\xff\xff",
220 `decodedLen=1; tagLiteral, 3-byte length; not enough length bytes`,
221 "\x01" + "\xf8\x00\x00",
225 `decodedLen=3; tagLiteral, 3-byte length; length=3; valid input`,
226 "\x03" + "\xf8\x02\x00\x00\xff\xff\xff",
230 `decodedLen=1; tagLiteral, 4-byte length; not enough length bytes`,
231 "\x01" + "\xfc\x00\x00\x00",
235 `decodedLen=1; tagLiteral, 4-byte length; length=3; not enough dst bytes`,
236 "\x01" + "\xfc\x02\x00\x00\x00\xff\xff\xff",
240 `decodedLen=4; tagLiteral, 4-byte length; length=3; not enough src bytes`,
241 "\x04" + "\xfc\x02\x00\x00\x00\xff",
245 `decodedLen=3; tagLiteral, 4-byte length; length=3; valid input`,
246 "\x03" + "\xfc\x02\x00\x00\x00\xff\xff\xff",
250 `decodedLen=4; tagCopy1, 1 extra length|offset byte; not enough extra bytes`,
255 `decodedLen=4; tagCopy2, 2 extra length|offset bytes; not enough extra bytes`,
260 `decodedLen=4; tagCopy4, 4 extra length|offset bytes; not enough extra bytes`,
261 "\x04" + "\x03\x00\x00\x00",
265 `decodedLen=4; tagLiteral (4 bytes "abcd"); valid input`,
270 `decodedLen=13; tagLiteral (4 bytes "abcd"); tagCopy1; length=9 offset=4; valid input`,
271 "\x0d" + "\x0cabcd" + "\x15\x04",
275 `decodedLen=8; tagLiteral (4 bytes "abcd"); tagCopy1; length=4 offset=4; valid input`,
276 "\x08" + "\x0cabcd" + "\x01\x04",
280 `decodedLen=8; tagLiteral (4 bytes "abcd"); tagCopy1; length=4 offset=2; valid input`,
281 "\x08" + "\x0cabcd" + "\x01\x02",
285 `decodedLen=8; tagLiteral (4 bytes "abcd"); tagCopy1; length=4 offset=1; valid input`,
286 "\x08" + "\x0cabcd" + "\x01\x01",
290 `decodedLen=8; tagLiteral (4 bytes "abcd"); tagCopy1; length=4 offset=0; zero offset`,
291 "\x08" + "\x0cabcd" + "\x01\x00",
295 `decodedLen=9; tagLiteral (4 bytes "abcd"); tagCopy1; length=4 offset=4; inconsistent dLen`,
296 "\x09" + "\x0cabcd" + "\x01\x04",
300 `decodedLen=8; tagLiteral (4 bytes "abcd"); tagCopy1; length=4 offset=5; offset too large`,
301 "\x08" + "\x0cabcd" + "\x01\x05",
305 `decodedLen=7; tagLiteral (4 bytes "abcd"); tagCopy1; length=4 offset=4; length too large`,
306 "\x07" + "\x0cabcd" + "\x01\x04",
310 `decodedLen=6; tagLiteral (4 bytes "abcd"); tagCopy2; length=2 offset=3; valid input`,
311 "\x06" + "\x0cabcd" + "\x06\x03\x00",
315 `decodedLen=6; tagLiteral (4 bytes "abcd"); tagCopy4; length=2 offset=3; valid input`,
316 "\x06" + "\x0cabcd" + "\x07\x03\x00\x00\x00",
322 // notPresentXxx defines a range of byte values [0xa0, 0xc5) that are
323 // not present in either the input or the output. It is written to dBuf
324 // to check that Decode does not write bytes past the end of
327 // The magic number 37 was chosen because it is prime. A more 'natural'
328 // number like 32 might lead to a false negative if, for example, a
329 // byte was incorrectly copied 4*8 bytes later.
330 notPresentBase = 0xa0
336 for i, tc := range testCases {
337 input := []byte(tc.input)
338 for _, x := range input {
339 if notPresentBase <= x && x < notPresentBase+notPresentLen {
340 t.Errorf("#%d (%s): input shouldn't contain %#02x\ninput: % x", i, tc.desc, x, input)
345 dLen, n := binary.Uvarint(input)
347 t.Errorf("#%d (%s): invalid varint-encoded dLen", i, tc.desc)
350 if dLen > uint64(len(dBuf)) {
351 t.Errorf("#%d (%s): dLen %d is too large", i, tc.desc, dLen)
355 for j := range dBuf {
356 dBuf[j] = byte(notPresentBase + j%notPresentLen)
358 g, gotErr := Decode(dBuf[:], input)
359 if got := string(g); got != tc.want || gotErr != tc.wantErr {
360 t.Errorf("#%d (%s):\ngot %q, %v\nwant %q, %v",
361 i, tc.desc, got, gotErr, tc.want, tc.wantErr)
364 for j, x := range dBuf {
365 if uint64(j) < dLen {
368 if w := byte(notPresentBase + j%notPresentLen); x != w {
369 t.Errorf("#%d (%s): Decode overrun: dBuf[%d] was modified: got %#02x, want %#02x\ndBuf: % x",
370 i, tc.desc, j, x, w, dBuf)
377 func TestDecodeCopy4(t *testing.T) {
378 dots := strings.Repeat(".", 65536)
380 input := strings.Join([]string{
381 "\x89\x80\x04", // decodedLen = 65545.
382 "\x0cpqrs", // 4-byte literal "pqrs".
383 "\xf4\xff\xff" + dots, // 65536-byte literal dots.
384 "\x13\x04\x00\x01\x00", // tagCopy4; length=5 offset=65540.
387 gotBytes, err := Decode(nil, []byte(input))
391 got := string(gotBytes)
392 want := "pqrs" + dots + "pqrs."
393 if len(got) != len(want) {
394 t.Fatalf("got %d bytes, want %d", len(got), len(want))
397 for i := 0; i < len(got); i++ {
398 if g, w := got[i], want[i]; g != w {
399 t.Fatalf("byte #%d: got %#02x, want %#02x", i, g, w)
405 // TestDecodeLengthOffset tests decoding an encoding of the form literal +
406 // copy-length-offset + literal. For example: "abcdefghijkl" + "efghij" + "AB".
407 func TestDecodeLengthOffset(t *testing.T) {
409 prefix = "abcdefghijklmnopqr"
410 suffix = "ABCDEFGHIJKLMNOPQR"
412 // notPresentXxx defines a range of byte values [0xa0, 0xc5) that are
413 // not present in either the input or the output. It is written to
414 // gotBuf to check that Decode does not write bytes past the end of
415 // gotBuf[:totalLen].
417 // The magic number 37 was chosen because it is prime. A more 'natural'
418 // number like 32 might lead to a false negative if, for example, a
419 // byte was incorrectly copied 4*8 bytes later.
420 notPresentBase = 0xa0
423 var gotBuf, wantBuf, inputBuf [128]byte
424 for length := 1; length <= 18; length++ {
425 for offset := 1; offset <= 18; offset++ {
427 for suffixLen := 0; suffixLen <= 18; suffixLen++ {
428 totalLen := len(prefix) + length + suffixLen
430 inputLen := binary.PutUvarint(inputBuf[:], uint64(totalLen))
431 inputBuf[inputLen] = tagLiteral + 4*byte(len(prefix)-1)
433 inputLen += copy(inputBuf[inputLen:], prefix)
434 inputBuf[inputLen+0] = tagCopy2 + 4*byte(length-1)
435 inputBuf[inputLen+1] = byte(offset)
436 inputBuf[inputLen+2] = 0x00
439 inputBuf[inputLen] = tagLiteral + 4*byte(suffixLen-1)
441 inputLen += copy(inputBuf[inputLen:], suffix[:suffixLen])
443 input := inputBuf[:inputLen]
445 for i := range gotBuf {
446 gotBuf[i] = byte(notPresentBase + i%notPresentLen)
448 got, err := Decode(gotBuf[:], input)
450 t.Errorf("length=%d, offset=%d; suffixLen=%d: %v", length, offset, suffixLen, err)
455 wantLen += copy(wantBuf[wantLen:], prefix)
456 for i := 0; i < length; i++ {
457 wantBuf[wantLen] = wantBuf[wantLen-offset]
460 wantLen += copy(wantBuf[wantLen:], suffix[:suffixLen])
461 want := wantBuf[:wantLen]
463 for _, x := range input {
464 if notPresentBase <= x && x < notPresentBase+notPresentLen {
465 t.Errorf("length=%d, offset=%d; suffixLen=%d: input shouldn't contain %#02x\ninput: % x",
466 length, offset, suffixLen, x, input)
470 for i, x := range gotBuf {
474 if w := byte(notPresentBase + i%notPresentLen); x != w {
475 t.Errorf("length=%d, offset=%d; suffixLen=%d; totalLen=%d: "+
476 "Decode overrun: gotBuf[%d] was modified: got %#02x, want %#02x\ngotBuf: % x",
477 length, offset, suffixLen, totalLen, i, x, w, gotBuf)
481 for _, x := range want {
482 if notPresentBase <= x && x < notPresentBase+notPresentLen {
483 t.Errorf("length=%d, offset=%d; suffixLen=%d: want shouldn't contain %#02x\nwant: % x",
484 length, offset, suffixLen, x, want)
489 if !bytes.Equal(got, want) {
490 t.Errorf("length=%d, offset=%d; suffixLen=%d:\ninput % x\ngot % x\nwant % x",
491 length, offset, suffixLen, input, got, want)
500 goldenText = "Mark.Twain-Tom.Sawyer.txt"
501 goldenCompressed = goldenText + ".rawsnappy"
504 func TestDecodeGoldenInput(t *testing.T) {
505 tDir := filepath.FromSlash(*testdataDir)
506 src, err := ioutil.ReadFile(filepath.Join(tDir, goldenCompressed))
508 t.Fatalf("ReadFile: %v", err)
510 got, err := Decode(nil, src)
512 t.Fatalf("Decode: %v", err)
514 want, err := ioutil.ReadFile(filepath.Join(tDir, goldenText))
516 t.Fatalf("ReadFile: %v", err)
518 if err := cmp(got, want); err != nil {
523 func TestEncodeGoldenInput(t *testing.T) {
524 tDir := filepath.FromSlash(*testdataDir)
525 src, err := ioutil.ReadFile(filepath.Join(tDir, goldenText))
527 t.Fatalf("ReadFile: %v", err)
529 got := Encode(nil, src)
530 want, err := ioutil.ReadFile(filepath.Join(tDir, goldenCompressed))
532 t.Fatalf("ReadFile: %v", err)
534 if err := cmp(got, want); err != nil {
539 func TestExtendMatchGoldenInput(t *testing.T) {
540 tDir := filepath.FromSlash(*testdataDir)
541 src, err := ioutil.ReadFile(filepath.Join(tDir, goldenText))
543 t.Fatalf("ReadFile: %v", err)
545 for i, tc := range extendMatchGoldenTestCases {
546 got := extendMatch(src, tc.i, tc.j)
548 t.Errorf("test #%d: i, j = %5d, %5d: got %5d (= j + %6d), want %5d (= j + %6d)",
549 i, tc.i, tc.j, got, got-tc.j, tc.want, tc.want-tc.j)
554 func TestExtendMatch(t *testing.T) {
555 // ref is a simple, reference implementation of extendMatch.
556 ref := func(src []byte, i, j int) int {
557 for ; j < len(src) && src[i] == src[j]; i, j = i+1, j+1 {
562 nums := []int{0, 1, 2, 7, 8, 9, 29, 30, 31, 32, 33, 34, 38, 39, 40}
563 for yIndex := 40; yIndex > 30; yIndex-- {
564 xxx := bytes.Repeat([]byte("x"), 40)
565 if yIndex < len(xxx) {
568 for _, i := range nums {
569 for _, j := range nums {
573 got := extendMatch(xxx, i, j)
574 want := ref(xxx, i, j)
576 t.Errorf("yIndex=%d, i=%d, j=%d: got %d, want %d", yIndex, i, j, got, want)
583 const snappytoolCmdName = "cmd/snappytool/snappytool"
585 func skipTestSameEncodingAsCpp() (msg string) {
586 if !goEncoderShouldMatchCppEncoder {
587 return fmt.Sprintf("skipping testing that the encoding is byte-for-byte identical to C++: GOARCH=%s", runtime.GOARCH)
589 if _, err := os.Stat(snappytoolCmdName); err != nil {
590 return fmt.Sprintf("could not find snappytool: %v", err)
595 func runTestSameEncodingAsCpp(src []byte) error {
596 got := Encode(nil, src)
598 cmd := exec.Command(snappytoolCmdName, "-e")
599 cmd.Stdin = bytes.NewReader(src)
600 want, err := cmd.Output()
602 return fmt.Errorf("could not run snappytool: %v", err)
604 return cmp(got, want)
607 func TestSameEncodingAsCppShortCopies(t *testing.T) {
608 if msg := skipTestSameEncodingAsCpp(); msg != "" {
611 src := bytes.Repeat([]byte{'a'}, 20)
612 for i := 0; i <= len(src); i++ {
613 if err := runTestSameEncodingAsCpp(src[:i]); err != nil {
614 t.Errorf("i=%d: %v", i, err)
619 func TestSameEncodingAsCppLongFiles(t *testing.T) {
620 if msg := skipTestSameEncodingAsCpp(); msg != "" {
623 bDir := filepath.FromSlash(*benchdataDir)
625 for i, tf := range testFiles {
626 if err := downloadBenchmarkFiles(t, tf.filename); err != nil {
627 t.Fatalf("failed to download testdata: %s", err)
629 data := readFile(t, filepath.Join(bDir, tf.filename))
630 if n := tf.sizeLimit; 0 < n && n < len(data) {
633 if err := runTestSameEncodingAsCpp(data); err != nil {
634 t.Errorf("i=%d: %v", i, err)
639 t.Errorf("was the snappytool program built against the C++ snappy library version " +
640 "d53de187 or later, commited on 2016-04-05? See " +
641 "https://github.com/google/snappy/commit/d53de18799418e113e44444252a39b12a0e4e0cc")
645 // TestSlowForwardCopyOverrun tests the "expand the pattern" algorithm
646 // described in decode_amd64.s and its claim of a 10 byte overrun worst case.
647 func TestSlowForwardCopyOverrun(t *testing.T) {
650 for length := 1; length < 18; length++ {
651 for offset := 1; offset < 18; offset++ {
652 highWaterMark := base
657 // makeOffsetAtLeast8
659 if end := d + 8; highWaterMark < end {
667 // fixUpSlowForwardCopy
671 // finishSlowForwardCopy
673 if end := a + 8; highWaterMark < end {
680 dWant := base + length
681 overrun := highWaterMark - dWant
682 if d != dWant || overrun < 0 || 10 < overrun {
683 t.Errorf("length=%d, offset=%d: d and overrun: got (%d, %d), want (%d, something in [0, 10])",
684 length, offset, d, overrun, dWant)
690 // TestEncodeNoiseThenRepeats encodes input for which the first half is very
691 // incompressible and the second half is very compressible. The encoded form's
692 // length should be closer to 50% of the original length than 100%.
693 func TestEncodeNoiseThenRepeats(t *testing.T) {
694 for _, origLen := range []int{256 * 1024, 2048 * 1024} {
695 src := make([]byte, origLen)
696 rng := rand.New(rand.NewSource(1))
697 firstHalf, secondHalf := src[:origLen/2], src[origLen/2:]
698 for i := range firstHalf {
699 firstHalf[i] = uint8(rng.Intn(256))
701 for i := range secondHalf {
702 secondHalf[i] = uint8(i >> 8)
704 dst := Encode(nil, src)
705 if got, want := len(dst), origLen*3/4; got >= want {
706 t.Errorf("origLen=%d: got %d encoded bytes, want less than %d", origLen, got, want)
711 func TestFramingFormat(t *testing.T) {
712 // src is comprised of alternating 1e5-sized sequences of random
713 // (incompressible) bytes and repeated (compressible) bytes. 1e5 was chosen
714 // because it is larger than maxBlockSize (64k).
715 src := make([]byte, 1e6)
716 rng := rand.New(rand.NewSource(1))
717 for i := 0; i < 10; i++ {
719 for j := 0; j < 1e5; j++ {
720 src[1e5*i+j] = uint8(rng.Intn(256))
723 for j := 0; j < 1e5; j++ {
724 src[1e5*i+j] = uint8(i)
729 buf := new(bytes.Buffer)
730 if _, err := NewWriter(buf).Write(src); err != nil {
731 t.Fatalf("Write: encoding: %v", err)
733 dst, err := ioutil.ReadAll(NewReader(buf))
735 t.Fatalf("ReadAll: decoding: %v", err)
737 if err := cmp(dst, src); err != nil {
742 func TestWriterGoldenOutput(t *testing.T) {
743 buf := new(bytes.Buffer)
744 w := NewBufferedWriter(buf)
746 w.Write([]byte("abcd")) // Not compressible.
748 w.Write(bytes.Repeat([]byte{'A'}, 150)) // Compressible.
750 // The next chunk is also compressible, but a naive, greedy encoding of the
751 // overall length 67 copy as a length 64 copy (the longest expressible as a
752 // tagCopy1 or tagCopy2) plus a length 3 remainder would be two 3-byte
753 // tagCopy2 tags (6 bytes), since the minimum length for a tagCopy1 is 4
754 // bytes. Instead, we could do it shorter, in 5 bytes: a 3-byte tagCopy2
755 // (of length 60) and a 2-byte tagCopy1 (of length 7).
756 w.Write(bytes.Repeat([]byte{'B'}, 68))
757 w.Write([]byte("efC")) // Not compressible.
758 w.Write(bytes.Repeat([]byte{'C'}, 20)) // Compressible.
759 w.Write(bytes.Repeat([]byte{'B'}, 20)) // Compressible.
760 w.Write([]byte("g")) // Not compressible.
764 want := strings.Join([]string{
766 "\x01\x08\x00\x00", // Uncompressed chunk, 8 bytes long (including 4 byte checksum).
767 "\x68\x10\xe6\xb6", // Checksum.
768 "\x61\x62\x63\x64", // Uncompressed payload: "abcd".
769 "\x00\x11\x00\x00", // Compressed chunk, 17 bytes long (including 4 byte checksum).
770 "\x5f\xeb\xf2\x10", // Checksum.
771 "\x96\x01", // Compressed payload: Uncompressed length (varint encoded): 150.
772 "\x00\x41", // Compressed payload: tagLiteral, length=1, "A".
773 "\xfe\x01\x00", // Compressed payload: tagCopy2, length=64, offset=1.
774 "\xfe\x01\x00", // Compressed payload: tagCopy2, length=64, offset=1.
775 "\x52\x01\x00", // Compressed payload: tagCopy2, length=21, offset=1.
776 "\x00\x18\x00\x00", // Compressed chunk, 24 bytes long (including 4 byte checksum).
777 "\x30\x85\x69\xeb", // Checksum.
778 "\x70", // Compressed payload: Uncompressed length (varint encoded): 112.
779 "\x00\x42", // Compressed payload: tagLiteral, length=1, "B".
780 "\xee\x01\x00", // Compressed payload: tagCopy2, length=60, offset=1.
781 "\x0d\x01", // Compressed payload: tagCopy1, length=7, offset=1.
782 "\x08\x65\x66\x43", // Compressed payload: tagLiteral, length=3, "efC".
783 "\x4e\x01\x00", // Compressed payload: tagCopy2, length=20, offset=1.
784 "\x4e\x5a\x00", // Compressed payload: tagCopy2, length=20, offset=90.
785 "\x00\x67", // Compressed payload: tagLiteral, length=1, "g".
788 t.Fatalf("\ngot: % x\nwant: % x", got, want)
792 func TestEmitLiteral(t *testing.T) {
793 testCases := []struct {
806 {257, "\xf4\x00\x01"},
807 {65534, "\xf4\xfd\xff"},
808 {65535, "\xf4\xfe\xff"},
809 {65536, "\xf4\xff\xff"},
812 dst := make([]byte, 70000)
813 nines := bytes.Repeat([]byte{0x99}, 65536)
814 for _, tc := range testCases {
815 lit := nines[:tc.length]
816 n := emitLiteral(dst, lit)
817 if !bytes.HasSuffix(dst[:n], lit) {
818 t.Errorf("length=%d: did not end with that many literal bytes", tc.length)
821 got := string(dst[:n-tc.length])
823 t.Errorf("length=%d:\ngot % x\nwant % x", tc.length, got, tc.want)
829 func TestEmitCopy(t *testing.T) {
830 testCases := []struct {
837 {8, 12, "\x2e\x08\x00"},
838 {8, 13, "\x32\x08\x00"},
839 {8, 59, "\xea\x08\x00"},
840 {8, 60, "\xee\x08\x00"},
841 {8, 61, "\xf2\x08\x00"},
842 {8, 62, "\xf6\x08\x00"},
843 {8, 63, "\xfa\x08\x00"},
844 {8, 64, "\xfe\x08\x00"},
845 {8, 65, "\xee\x08\x00\x05\x08"},
846 {8, 66, "\xee\x08\x00\x09\x08"},
847 {8, 67, "\xee\x08\x00\x0d\x08"},
848 {8, 68, "\xfe\x08\x00\x01\x08"},
849 {8, 69, "\xfe\x08\x00\x05\x08"},
850 {8, 80, "\xfe\x08\x00\x3e\x08\x00"},
852 {256, 04, "\x21\x00"},
853 {256, 11, "\x3d\x00"},
854 {256, 12, "\x2e\x00\x01"},
855 {256, 13, "\x32\x00\x01"},
856 {256, 59, "\xea\x00\x01"},
857 {256, 60, "\xee\x00\x01"},
858 {256, 61, "\xf2\x00\x01"},
859 {256, 62, "\xf6\x00\x01"},
860 {256, 63, "\xfa\x00\x01"},
861 {256, 64, "\xfe\x00\x01"},
862 {256, 65, "\xee\x00\x01\x25\x00"},
863 {256, 66, "\xee\x00\x01\x29\x00"},
864 {256, 67, "\xee\x00\x01\x2d\x00"},
865 {256, 68, "\xfe\x00\x01\x21\x00"},
866 {256, 69, "\xfe\x00\x01\x25\x00"},
867 {256, 80, "\xfe\x00\x01\x3e\x00\x01"},
869 {2048, 04, "\x0e\x00\x08"},
870 {2048, 11, "\x2a\x00\x08"},
871 {2048, 12, "\x2e\x00\x08"},
872 {2048, 13, "\x32\x00\x08"},
873 {2048, 59, "\xea\x00\x08"},
874 {2048, 60, "\xee\x00\x08"},
875 {2048, 61, "\xf2\x00\x08"},
876 {2048, 62, "\xf6\x00\x08"},
877 {2048, 63, "\xfa\x00\x08"},
878 {2048, 64, "\xfe\x00\x08"},
879 {2048, 65, "\xee\x00\x08\x12\x00\x08"},
880 {2048, 66, "\xee\x00\x08\x16\x00\x08"},
881 {2048, 67, "\xee\x00\x08\x1a\x00\x08"},
882 {2048, 68, "\xfe\x00\x08\x0e\x00\x08"},
883 {2048, 69, "\xfe\x00\x08\x12\x00\x08"},
884 {2048, 80, "\xfe\x00\x08\x3e\x00\x08"},
887 dst := make([]byte, 1024)
888 for _, tc := range testCases {
889 n := emitCopy(dst, tc.offset, tc.length)
890 got := string(dst[:n])
892 t.Errorf("offset=%d, length=%d:\ngot % x\nwant % x", tc.offset, tc.length, got, tc.want)
897 func TestNewBufferedWriter(t *testing.T) {
898 // Test all 32 possible sub-sequences of these 5 input slices.
900 // Their lengths sum to 400,000, which is over 6 times the Writer ibuf
901 // capacity: 6 * maxBlockSize is 393,216.
903 bytes.Repeat([]byte{'a'}, 40000),
904 bytes.Repeat([]byte{'b'}, 150000),
905 bytes.Repeat([]byte{'c'}, 60000),
906 bytes.Repeat([]byte{'d'}, 120000),
907 bytes.Repeat([]byte{'e'}, 30000),
910 for i := 0; i < 1<<uint(len(inputs)); i++ {
912 buf := new(bytes.Buffer)
913 w := NewBufferedWriter(buf)
914 for j, input := range inputs {
915 if i&(1<<uint(j)) == 0 {
918 if _, err := w.Write(input); err != nil {
919 t.Errorf("i=%#02x: j=%d: Write: %v", i, j, err)
922 want = append(want, input...)
924 if err := w.Close(); err != nil {
925 t.Errorf("i=%#02x: Close: %v", i, err)
928 got, err := ioutil.ReadAll(NewReader(buf))
930 t.Errorf("i=%#02x: ReadAll: %v", i, err)
933 if err := cmp(got, want); err != nil {
934 t.Errorf("i=%#02x: %v", i, err)
940 func TestFlush(t *testing.T) {
941 buf := new(bytes.Buffer)
942 w := NewBufferedWriter(buf)
944 if _, err := w.Write(bytes.Repeat([]byte{'x'}, 20)); err != nil {
945 t.Fatalf("Write: %v", err)
947 if n := buf.Len(); n != 0 {
948 t.Fatalf("before Flush: %d bytes were written to the underlying io.Writer, want 0", n)
950 if err := w.Flush(); err != nil {
951 t.Fatalf("Flush: %v", err)
953 if n := buf.Len(); n == 0 {
954 t.Fatalf("after Flush: %d bytes were written to the underlying io.Writer, want non-0", n)
958 func TestReaderUncompressedDataOK(t *testing.T) {
959 r := NewReader(strings.NewReader(magicChunk +
960 "\x01\x08\x00\x00" + // Uncompressed chunk, 8 bytes long (including 4 byte checksum).
961 "\x68\x10\xe6\xb6" + // Checksum.
962 "\x61\x62\x63\x64", // Uncompressed payload: "abcd".
964 g, err := ioutil.ReadAll(r)
968 if got, want := string(g), "abcd"; got != want {
969 t.Fatalf("got %q, want %q", got, want)
973 func TestReaderUncompressedDataNoPayload(t *testing.T) {
974 r := NewReader(strings.NewReader(magicChunk +
975 "\x01\x04\x00\x00" + // Uncompressed chunk, 4 bytes long.
976 "", // No payload; corrupt input.
978 if _, err := ioutil.ReadAll(r); err != ErrCorrupt {
979 t.Fatalf("got %v, want %v", err, ErrCorrupt)
983 func TestReaderUncompressedDataTooLong(t *testing.T) {
984 // https://github.com/google/snappy/blob/master/framing_format.txt section
985 // 4.3 says that "the maximum legal chunk length... is 65540", or 0x10004.
988 r := NewReader(strings.NewReader(magicChunk +
989 "\x01\x05\x00\x01" + // Uncompressed chunk, n bytes long.
990 strings.Repeat("\x00", n),
992 if _, err := ioutil.ReadAll(r); err != ErrCorrupt {
993 t.Fatalf("got %v, want %v", err, ErrCorrupt)
997 func TestReaderReset(t *testing.T) {
998 gold := bytes.Repeat([]byte("All that is gold does not glitter,\n"), 10000)
999 buf := new(bytes.Buffer)
1000 if _, err := NewWriter(buf).Write(gold); err != nil {
1001 t.Fatalf("Write: %v", err)
1003 encoded, invalid, partial := buf.String(), "invalid", "partial"
1005 for i, s := range []string{encoded, invalid, partial, encoded, partial, invalid, encoded, encoded} {
1007 r.Reset(strings.NewReader(encoded))
1008 if _, err := r.Read(make([]byte, 101)); err != nil {
1009 t.Errorf("#%d: %v", i, err)
1014 r.Reset(strings.NewReader(s))
1015 got, err := ioutil.ReadAll(r)
1019 t.Errorf("#%d: %v", i, err)
1022 if err := cmp(got, gold); err != nil {
1023 t.Errorf("#%d: %v", i, err)
1028 t.Errorf("#%d: got nil error, want non-nil", i)
1035 func TestWriterReset(t *testing.T) {
1036 gold := bytes.Repeat([]byte("Not all those who wander are lost;\n"), 10000)
1038 for _, buffered := range []bool{false, true} {
1041 w = NewBufferedWriter(nil)
1047 var gots, wants [][]byte
1049 for i := 0; i <= n; i++ {
1050 buf := new(bytes.Buffer)
1052 want := gold[:len(gold)*i/n]
1053 if _, err := w.Write(want); err != nil {
1054 t.Errorf("#%d: Write: %v", i, err)
1059 if err := w.Flush(); err != nil {
1060 t.Errorf("#%d: Flush: %v", i, err)
1065 got, err := ioutil.ReadAll(NewReader(buf))
1067 t.Errorf("#%d: ReadAll: %v", i, err)
1071 gots = append(gots, got)
1072 wants = append(wants, want)
1077 for i := range gots {
1078 if err := cmp(gots[i], wants[i]); err != nil {
1079 t.Errorf("#%d: %v", i, err)
1085 func TestWriterResetWithoutFlush(t *testing.T) {
1086 buf0 := new(bytes.Buffer)
1087 buf1 := new(bytes.Buffer)
1088 w := NewBufferedWriter(buf0)
1089 if _, err := w.Write([]byte("xxx")); err != nil {
1090 t.Fatalf("Write #0: %v", err)
1092 // Note that we don't Flush the Writer before calling Reset.
1094 if _, err := w.Write([]byte("yyy")); err != nil {
1095 t.Fatalf("Write #1: %v", err)
1097 if err := w.Flush(); err != nil {
1098 t.Fatalf("Flush: %v", err)
1100 got, err := ioutil.ReadAll(NewReader(buf1))
1102 t.Fatalf("ReadAll: %v", err)
1104 if err := cmp(got, []byte("yyy")); err != nil {
1109 type writeCounter int
1111 func (c *writeCounter) Write(p []byte) (int, error) {
1116 // TestNumUnderlyingWrites tests that each Writer flush only makes one or two
1117 // Write calls on its underlying io.Writer, depending on whether or not the
1118 // flushed buffer was compressible.
1119 func TestNumUnderlyingWrites(t *testing.T) {
1120 testCases := []struct {
1124 {bytes.Repeat([]byte{'x'}, 100), 1},
1125 {bytes.Repeat([]byte{'y'}, 100), 1},
1126 {[]byte("ABCDEFGHIJKLMNOPQRST"), 2},
1130 w := NewBufferedWriter(&c)
1132 for i, tc := range testCases {
1134 if _, err := w.Write(tc.input); err != nil {
1135 t.Errorf("#%d: Write: %v", i, err)
1138 if err := w.Flush(); err != nil {
1139 t.Errorf("#%d: Flush: %v", i, err)
1142 if int(c) != tc.want {
1143 t.Errorf("#%d: got %d underlying writes, want %d", i, c, tc.want)
1149 func benchDecode(b *testing.B, src []byte) {
1150 encoded := Encode(nil, src)
1151 // Bandwidth is in amount of uncompressed data.
1152 b.SetBytes(int64(len(src)))
1154 for i := 0; i < b.N; i++ {
1155 Decode(src, encoded)
1159 func benchEncode(b *testing.B, src []byte) {
1160 // Bandwidth is in amount of uncompressed data.
1161 b.SetBytes(int64(len(src)))
1162 dst := make([]byte, MaxEncodedLen(len(src)))
1164 for i := 0; i < b.N; i++ {
1169 func testOrBenchmark(b testing.TB) string {
1170 if _, ok := b.(*testing.B); ok {
1176 func readFile(b testing.TB, filename string) []byte {
1177 src, err := ioutil.ReadFile(filename)
1179 b.Skipf("skipping %s: %v", testOrBenchmark(b), err)
1182 b.Fatalf("%s has zero length", filename)
1187 // expand returns a slice of length n containing repeated copies of src.
1188 func expand(src []byte, n int) []byte {
1189 dst := make([]byte, n)
1190 for x := dst; len(x) > 0; {
1197 func benchWords(b *testing.B, n int, decode bool) {
1198 // Note: the file is OS-language dependent so the resulting values are not
1199 // directly comparable for non-US-English OS installations.
1200 data := expand(readFile(b, "/usr/share/dict/words"), n)
1202 benchDecode(b, data)
1204 benchEncode(b, data)
1208 func BenchmarkWordsDecode1e1(b *testing.B) { benchWords(b, 1e1, true) }
1209 func BenchmarkWordsDecode1e2(b *testing.B) { benchWords(b, 1e2, true) }
1210 func BenchmarkWordsDecode1e3(b *testing.B) { benchWords(b, 1e3, true) }
1211 func BenchmarkWordsDecode1e4(b *testing.B) { benchWords(b, 1e4, true) }
1212 func BenchmarkWordsDecode1e5(b *testing.B) { benchWords(b, 1e5, true) }
1213 func BenchmarkWordsDecode1e6(b *testing.B) { benchWords(b, 1e6, true) }
1214 func BenchmarkWordsEncode1e1(b *testing.B) { benchWords(b, 1e1, false) }
1215 func BenchmarkWordsEncode1e2(b *testing.B) { benchWords(b, 1e2, false) }
1216 func BenchmarkWordsEncode1e3(b *testing.B) { benchWords(b, 1e3, false) }
1217 func BenchmarkWordsEncode1e4(b *testing.B) { benchWords(b, 1e4, false) }
1218 func BenchmarkWordsEncode1e5(b *testing.B) { benchWords(b, 1e5, false) }
1219 func BenchmarkWordsEncode1e6(b *testing.B) { benchWords(b, 1e6, false) }
1221 func BenchmarkRandomEncode(b *testing.B) {
1222 rng := rand.New(rand.NewSource(1))
1223 data := make([]byte, 1<<20)
1224 for i := range data {
1225 data[i] = uint8(rng.Intn(256))
1227 benchEncode(b, data)
1230 // testFiles' values are copied directly from
1231 // https://raw.githubusercontent.com/google/snappy/master/snappy_unittest.cc
1232 // The label field is unused in snappy-go.
1233 var testFiles = []struct {
1238 {"html", "html", 0},
1239 {"urls", "urls.10K", 0},
1240 {"jpg", "fireworks.jpeg", 0},
1241 {"jpg_200", "fireworks.jpeg", 200},
1242 {"pdf", "paper-100k.pdf", 0},
1243 {"html4", "html_x_4", 0},
1244 {"txt1", "alice29.txt", 0},
1245 {"txt2", "asyoulik.txt", 0},
1246 {"txt3", "lcet10.txt", 0},
1247 {"txt4", "plrabn12.txt", 0},
1248 {"pb", "geo.protodata", 0},
1249 {"gaviota", "kppkn.gtb", 0},
1253 // The benchmark data files are at this canonical URL.
1254 benchURL = "https://raw.githubusercontent.com/google/snappy/master/testdata/"
1257 func downloadBenchmarkFiles(b testing.TB, basename string) (errRet error) {
1258 bDir := filepath.FromSlash(*benchdataDir)
1259 filename := filepath.Join(bDir, basename)
1260 if stat, err := os.Stat(filename); err == nil && stat.Size() != 0 {
1265 b.Skipf("test data not found; skipping %s without the -download flag", testOrBenchmark(b))
1267 // Download the official snappy C++ implementation reference test data
1268 // files for benchmarking.
1269 if err := os.MkdirAll(bDir, 0777); err != nil && !os.IsExist(err) {
1270 return fmt.Errorf("failed to create %s: %s", bDir, err)
1273 f, err := os.Create(filename)
1275 return fmt.Errorf("failed to create %s: %s", filename, err)
1283 url := benchURL + basename
1284 resp, err := http.Get(url)
1286 return fmt.Errorf("failed to download %s: %s", url, err)
1288 defer resp.Body.Close()
1289 if s := resp.StatusCode; s != http.StatusOK {
1290 return fmt.Errorf("downloading %s: HTTP status code %d (%s)", url, s, http.StatusText(s))
1292 _, err = io.Copy(f, resp.Body)
1294 return fmt.Errorf("failed to download %s to %s: %s", url, filename, err)
1299 func benchFile(b *testing.B, i int, decode bool) {
1300 if err := downloadBenchmarkFiles(b, testFiles[i].filename); err != nil {
1301 b.Fatalf("failed to download testdata: %s", err)
1303 bDir := filepath.FromSlash(*benchdataDir)
1304 data := readFile(b, filepath.Join(bDir, testFiles[i].filename))
1305 if n := testFiles[i].sizeLimit; 0 < n && n < len(data) {
1309 benchDecode(b, data)
1311 benchEncode(b, data)
1315 // Naming convention is kept similar to what snappy's C++ implementation uses.
1316 func Benchmark_UFlat0(b *testing.B) { benchFile(b, 0, true) }
1317 func Benchmark_UFlat1(b *testing.B) { benchFile(b, 1, true) }
1318 func Benchmark_UFlat2(b *testing.B) { benchFile(b, 2, true) }
1319 func Benchmark_UFlat3(b *testing.B) { benchFile(b, 3, true) }
1320 func Benchmark_UFlat4(b *testing.B) { benchFile(b, 4, true) }
1321 func Benchmark_UFlat5(b *testing.B) { benchFile(b, 5, true) }
1322 func Benchmark_UFlat6(b *testing.B) { benchFile(b, 6, true) }
1323 func Benchmark_UFlat7(b *testing.B) { benchFile(b, 7, true) }
1324 func Benchmark_UFlat8(b *testing.B) { benchFile(b, 8, true) }
1325 func Benchmark_UFlat9(b *testing.B) { benchFile(b, 9, true) }
1326 func Benchmark_UFlat10(b *testing.B) { benchFile(b, 10, true) }
1327 func Benchmark_UFlat11(b *testing.B) { benchFile(b, 11, true) }
1328 func Benchmark_ZFlat0(b *testing.B) { benchFile(b, 0, false) }
1329 func Benchmark_ZFlat1(b *testing.B) { benchFile(b, 1, false) }
1330 func Benchmark_ZFlat2(b *testing.B) { benchFile(b, 2, false) }
1331 func Benchmark_ZFlat3(b *testing.B) { benchFile(b, 3, false) }
1332 func Benchmark_ZFlat4(b *testing.B) { benchFile(b, 4, false) }
1333 func Benchmark_ZFlat5(b *testing.B) { benchFile(b, 5, false) }
1334 func Benchmark_ZFlat6(b *testing.B) { benchFile(b, 6, false) }
1335 func Benchmark_ZFlat7(b *testing.B) { benchFile(b, 7, false) }
1336 func Benchmark_ZFlat8(b *testing.B) { benchFile(b, 8, false) }
1337 func Benchmark_ZFlat9(b *testing.B) { benchFile(b, 9, false) }
1338 func Benchmark_ZFlat10(b *testing.B) { benchFile(b, 10, false) }
1339 func Benchmark_ZFlat11(b *testing.B) { benchFile(b, 11, false) }
1341 func BenchmarkExtendMatch(b *testing.B) {
1342 tDir := filepath.FromSlash(*testdataDir)
1343 src, err := ioutil.ReadFile(filepath.Join(tDir, goldenText))
1345 b.Fatalf("ReadFile: %v", err)
1348 for i := 0; i < b.N; i++ {
1349 for _, tc := range extendMatchGoldenTestCases {
1350 extendMatch(src, tc.i, tc.j)