Debian Codegraph @

s2/s2_test.go

raw
1 // Copyright 2011 The Snappy-Go Authors. All rights reserved.
2 // Copyright (c) 2019 Klaus Post. All rights reserved.
3 // Use of this source code is governed by a BSD-style
4 // license that can be found in the LICENSE file.
5
6 package s2
7
8 import (
9 "bytes"
10 "encoding/binary"
11 "flag"
12 "fmt"
13 "io"
14 "math"
15 "math/rand"
16 "net/http"
17 "os"
18 "path/filepath"
19 "runtime"
20 "strings"
21 "testing"
22
23 "github.com/klauspost/compress/internal/snapref"
24 "github.com/klauspost/compress/zip"
25 "github.com/klauspost/compress/zstd"
26 )
27
28 const maxUint = ^uint(0)
29 const maxInt = int(maxUint >> 1)
30
31 var (
32 download = flag.Bool("download", false, "If true, download any missing files before running benchmarks")
33 testdataDir = flag.String("testdataDir", "testdata", "Directory containing the test data")
34 benchdataDir = flag.String("benchdataDir", "testdata/bench", "Directory containing the benchmark data")
35 )
36
37 func TestMaxEncodedLen(t *testing.T) {
38 testSet := []struct {
39 in, out int64
40 }{
41 0: {in: 0, out: 1},
42 1: {in: 1 << 24, out: 1<<24 + int64(binary.PutVarint([]byte{binary.MaxVarintLen32: 0}, int64(1<<24))) + literalExtraSize(1<<24)},
43 2: {in: MaxBlockSize, out: math.MaxUint32},
44 3: {in: math.MaxUint32 - binary.MaxVarintLen32 - literalExtraSize(math.MaxUint32), out: math.MaxUint32},
45 4: {in: math.MaxUint32 - 9, out: -1},
46 5: {in: math.MaxUint32 - 8, out: -1},
47 6: {in: math.MaxUint32 - 7, out: -1},
48 7: {in: math.MaxUint32 - 6, out: -1},
49 8: {in: math.MaxUint32 - 5, out: -1},
50 9: {in: math.MaxUint32 - 4, out: -1},
51 10: {in: math.MaxUint32 - 3, out: -1},
52 11: {in: math.MaxUint32 - 2, out: -1},
53 12: {in: math.MaxUint32 - 1, out: -1},
54 13: {in: math.MaxUint32, out: -1},
55 14: {in: -1, out: -1},
56 15: {in: -2, out: -1},
57 }
58 // 32 bit platforms have a different threshold.
59 if maxInt == math.MaxInt32 {
60 testSet[2].out = math.MaxInt32
61 testSet[3].out = -1
62 }
63 t.Log("Maxblock:", MaxBlockSize, "reduction:", intReduction)
64 // Test all sizes up to maxBlockSize.
65 for i := range int64(maxBlockSize) {
66 testSet = append(testSet, struct{ in, out int64 }{in: i, out: i + int64(binary.PutVarint([]byte{binary.MaxVarintLen32: 0}, i)) + literalExtraSize(i)})
67 }
68 for i := range testSet {
69 tt := testSet[i]
70 want := tt.out
71 got := int64(MaxEncodedLen(int(tt.in)))
72 if got != want {
73 t.Errorf("test %d: input: %d, want: %d, got: %d", i, tt.in, want, got)
74 }
75 }
76 }
77
78 func cmp(got, want []byte) error {
79 if bytes.Equal(got, want) {
80 return nil
81 }
82 if len(got) != len(want) {
83 return fmt.Errorf("got %d bytes, want %d", len(got), len(want))
84 }
85 for i := range got {
86 if got[i] != want[i] {
87 return fmt.Errorf("byte #%d: got 0x%02x, want 0x%02x", i, got[i], want[i])
88 }
89 }
90 return nil
91 }
92
93 func roundtrip(b, ebuf, dbuf []byte) error {
94 bOrg := make([]byte, len(b))
95 copy(bOrg, b)
96 asmEnc := Encode(nil, b)
97 if err := cmp(bOrg, b); err != nil {
98 return fmt.Errorf("src was changed: %v", err)
99 }
100 goEnc := encodeGo(nil, b)
101 if err := cmp(bOrg, b); err != nil {
102 return fmt.Errorf("src was changed: %v", err)
103 }
104
105 //fmt.Println("asm:", len(asmEnc), "go:", len(goEnc))
106 dGo, err := Decode(nil, goEnc)
107 if err != nil {
108 return fmt.Errorf("decoding error: %v", err)
109 }
110
111 if err := cmp(dGo, b); err != nil {
112 return fmt.Errorf("roundtrip mismatch: %v", err)
113 }
114
115 // fmt.Println("decode asm...")
116 d, err := Decode(nil, asmEnc)
117 if err != nil {
118 return fmt.Errorf("decoding error: %v", err)
119 }
120 if err := cmp(d, b); err != nil {
121 return fmt.Errorf("roundtrip mismatch: %v", err)
122 }
123 d, err = Decode(dbuf, EncodeBetter(ebuf, b))
124 if err != nil {
125 return fmt.Errorf("decoding better error: %v", err)
126 }
127 if err := cmp(d, b); err != nil {
128 return fmt.Errorf("roundtrip better mismatch: %v", err)
129 }
130
131 // Test concat with some existing data.
132 dst := []byte("existing")
133 // Add 3 different encodes and a 0 length block.
134 concat, err := ConcatBlocks(dst, Encode(nil, b), EncodeBetter(nil, b), []byte{0}, EncodeSnappy(nil, b))
135 if err != nil {
136 return fmt.Errorf("concat error: %v", err)
137 }
138 if err := cmp(concat[:len(dst)], dst); err != nil {
139 return fmt.Errorf("concat existing mismatch: %v", err)
140 }
141 concat = concat[len(dst):]
142
143 d, _ = Decode(nil, concat)
144 want := append(make([]byte, 0, len(b)*3), b...)
145 want = append(want, b...)
146 want = append(want, b...)
147
148 if err := cmp(d, want); err != nil {
149 return fmt.Errorf("roundtrip concat mismatch: %v", err)
150 }
151
152 return nil
153 }
154
155 func TestEmpty(t *testing.T) {
156 if err := roundtrip(nil, nil, nil); err != nil {
157 t.Fatal(err)
158 }
159 }
160
161 func TestSmallCopy(t *testing.T) {
162 for _, ebuf := range [][]byte{nil, make([]byte, 20), make([]byte, 64)} {
163 for _, dbuf := range [][]byte{nil, make([]byte, 20), make([]byte, 64)} {
164 for i := range 32 {
165 s := "aaaa" + strings.Repeat("b", i) + "aaaabbbb"
166 if err := roundtrip([]byte(s), ebuf, dbuf); err != nil {
167 t.Errorf("len(ebuf)=%d, len(dbuf)=%d, i=%d: %v", len(ebuf), len(dbuf), i, err)
168 }
169 }
170 }
171 }
172 }
173
174 func TestSmallRand(t *testing.T) {
175 rng := rand.New(rand.NewSource(1))
176 for n := 1; n < 20000; n += 23 {
177 b := make([]byte, n)
178 for i := range b {
179 b[i] = uint8(rng.Intn(256))
180 }
181 if err := roundtrip(b, nil, nil); err != nil {
182 t.Fatal(err)
183 }
184 }
185 }
186
187 func TestSmallRegular(t *testing.T) {
188 for n := 1; n < 20000; n += 23 {
189 b := make([]byte, n)
190 for i := range b {
191 b[i] = uint8(i%10 + 'a')
192 }
193 if err := roundtrip(b, nil, nil); err != nil {
194 t.Fatal(err)
195 }
196 }
197 }
198
199 func TestSmallRepeat(t *testing.T) {
200 for n := 1; n < 20000; n += 23 {
201 b := make([]byte, n)
202 for i := range b[:n/2] {
203 b[i] = uint8(i * 255 / n)
204 }
205 for i := range b[n/2:] {
206 b[i+n/2] = uint8(i%10 + 'a')
207 }
208 if err := roundtrip(b, nil, nil); err != nil {
209 t.Fatal(err)
210 }
211 }
212 }
213
214 func TestInvalidVarint(t *testing.T) {
215 testCases := []struct {
216 desc string
217 input string
218 }{{
219 "invalid varint, final byte has continuation bit set",
220 "\xff",
221 }, {
222 "invalid varint, value overflows uint64",
223 "\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\x00",
224 }, {
225 // https://github.com/google/snappy/blob/master/format_description.txt
226 // says that "the stream starts with the uncompressed length [as a
227 // varint] (up to a maximum of 2^32 - 1)".
228 "valid varint (as uint64), but value overflows uint32",
229 "\x80\x80\x80\x80\x10",
230 }, {
231 // 8-byte overlong varint encoding value 4. The format spec limits
232 // the varint preamble to 5 bytes. binary.Uvarint accepts up to 10
233 // bytes so this decodes to a valid uint32 value (4), but the
234 // overlong encoding must be rejected.
235 "overlong varint (8 bytes encoding value 4), exceeds 5-byte max",
236 "\x84\x80\x80\x80\x80\x80\x80\x00" +
237 "\x00\x00\x00\x00\x00\x00\x00" +
238 "\x30",
239 }}
240
241 for _, tc := range testCases {
242 input := []byte(tc.input)
243 if _, err := DecodedLen(input); err != ErrCorrupt {
244 t.Errorf("%s: DecodedLen: got %v, want ErrCorrupt", tc.desc, err)
245 }
246 if _, err := Decode(nil, input); err != ErrCorrupt {
247 t.Errorf("%s: Decode: got %v, want ErrCorrupt", tc.desc, err)
248 }
249 }
250 }
251
252 func TestDecode(t *testing.T) {
253 lit40Bytes := make([]byte, 40)
254 for i := range lit40Bytes {
255 lit40Bytes[i] = byte(i)
256 }
257 lit40 := string(lit40Bytes)
258
259 testCases := []struct {
260 desc string
261 input string
262 want string
263 wantErr error
264 }{{
265 `decodedLen=0; valid input`,
266 "\x00",
267 "",
268 nil,
269 }, {
270 `decodedLen=3; tagLiteral, 0-byte length; length=3; valid input`,
271 "\x03" + "\x08\xff\xff\xff",
272 "\xff\xff\xff",
273 nil,
274 }, {
275 `decodedLen=2; tagLiteral, 0-byte length; length=3; not enough dst bytes`,
276 "\x02" + "\x08\xff\xff\xff",
277 "",
278 ErrCorrupt,
279 }, {
280 `decodedLen=3; tagLiteral, 0-byte length; length=3; not enough src bytes`,
281 "\x03" + "\x08\xff\xff",
282 "",
283 ErrCorrupt,
284 }, {
285 `decodedLen=40; tagLiteral, 0-byte length; length=40; valid input`,
286 "\x28" + "\x9c" + lit40,
287 lit40,
288 nil,
289 }, {
290 `decodedLen=1; tagLiteral, 1-byte length; not enough length bytes`,
291 "\x01" + "\xf0",
292 "",
293 ErrCorrupt,
294 }, {
295 `decodedLen=3; tagLiteral, 1-byte length; length=3; valid input`,
296 "\x03" + "\xf0\x02\xff\xff\xff",
297 "\xff\xff\xff",
298 nil,
299 }, {
300 `decodedLen=1; tagLiteral, 2-byte length; not enough length bytes`,
301 "\x01" + "\xf4\x00",
302 "",
303 ErrCorrupt,
304 }, {
305 `decodedLen=3; tagLiteral, 2-byte length; length=3; valid input`,
306 "\x03" + "\xf4\x02\x00\xff\xff\xff",
307 "\xff\xff\xff",
308 nil,
309 }, {
310 `decodedLen=1; tagLiteral, 3-byte length; not enough length bytes`,
311 "\x01" + "\xf8\x00\x00",
312 "",
313 ErrCorrupt,
314 }, {
315 `decodedLen=3; tagLiteral, 3-byte length; length=3; valid input`,
316 "\x03" + "\xf8\x02\x00\x00\xff\xff\xff",
317 "\xff\xff\xff",
318 nil,
319 }, {
320 `decodedLen=1; tagLiteral, 4-byte length; not enough length bytes`,
321 "\x01" + "\xfc\x00\x00\x00",
322 "",
323 ErrCorrupt,
324 }, {
325 `decodedLen=1; tagLiteral, 4-byte length; length=3; not enough dst bytes`,
326 "\x01" + "\xfc\x02\x00\x00\x00\xff\xff\xff",
327 "",
328 ErrCorrupt,
329 }, {
330 `decodedLen=4; tagLiteral, 4-byte length; length=3; not enough src bytes`,
331 "\x04" + "\xfc\x02\x00\x00\x00\xff",
332 "",
333 ErrCorrupt,
334 }, {
335 `decodedLen=3; tagLiteral, 4-byte length; length=3; valid input`,
336 "\x03" + "\xfc\x02\x00\x00\x00\xff\xff\xff",
337 "\xff\xff\xff",
338 nil,
339 }, {
340 `decodedLen=4; tagCopy1, 1 extra length|offset byte; not enough extra bytes`,
341 "\x04" + "\x01",
342 "",
343 ErrCorrupt,
344 }, {
345 `decodedLen=4; tagCopy2, 2 extra length|offset bytes; not enough extra bytes`,
346 "\x04" + "\x02\x00",
347 "",
348 ErrCorrupt,
349 }, {
350 `decodedLen=4; tagCopy4, 4 extra length|offset bytes; not enough extra bytes`,
351 "\x04" + "\x03\x00\x00\x00",
352 "",
353 ErrCorrupt,
354 }, {
355 `decodedLen=4; tagLiteral (4 bytes "abcd"); valid input`,
356 "\x04" + "\x0cabcd",
357 "abcd",
358 nil,
359 }, {
360 `decodedLen=13; tagLiteral (4 bytes "abcd"); tagCopy1; length=9 offset=4; valid input`,
361 "\x0d" + "\x0cabcd" + "\x15\x04",
362 "abcdabcdabcda",
363 nil,
364 }, {
365 `decodedLen=8; tagLiteral (4 bytes "abcd"); tagCopy1; length=4 offset=4; valid input`,
366 "\x08" + "\x0cabcd" + "\x01\x04",
367 "abcdabcd",
368 nil,
369 }, {
370 `decodedLen=8; tagLiteral (4 bytes "abcd"); tagCopy1; length=4 offset=2; valid input`,
371 "\x08" + "\x0cabcd" + "\x01\x02",
372 "abcdcdcd",
373 nil,
374 }, {
375 `decodedLen=8; tagLiteral (4 bytes "abcd"); tagCopy1; length=4 offset=1; valid input`,
376 "\x08" + "\x0cabcd" + "\x01\x01",
377 "abcddddd",
378 nil,
379 }, {
380 `decodedLen=8; tagLiteral (4 bytes "abcd"); tagCopy1; length=4 offset=0; repeat offset as first match`,
381 "\x08" + "\x0cabcd" + "\x01\x00",
382 "",
383 ErrCorrupt,
384 }, {
385 `decodedLen=13; tagLiteral (4 bytes "abcd"); tagCopy1; length=4 offset=1; literal: 'z'; tagCopy1; length=4 offset=0; repeat offset as second match`,
386 "\x0d" + "\x0cabcd" + "\x01\x01" + "\x00z" + "\x01\x00",
387 "abcdddddzzzzz",
388 nil,
389 }, {
390 `decodedLen=9; tagLiteral (4 bytes "abcd"); tagCopy1; length=4 offset=4; inconsistent dLen`,
391 "\x09" + "\x0cabcd" + "\x01\x04",
392 "",
393 ErrCorrupt,
394 }, {
395 `decodedLen=8; tagLiteral (4 bytes "abcd"); tagCopy1; length=4 offset=5; offset too large`,
396 "\x08" + "\x0cabcd" + "\x01\x05",
397 "",
398 ErrCorrupt,
399 }, {
400 `decodedLen=7; tagLiteral (4 bytes "abcd"); tagCopy1; length=4 offset=4; length too large`,
401 "\x07" + "\x0cabcd" + "\x01\x04",
402 "",
403 ErrCorrupt,
404 }, {
405 `decodedLen=6; tagLiteral (4 bytes "abcd"); tagCopy2; length=2 offset=3; valid input`,
406 "\x06" + "\x0cabcd" + "\x06\x03\x00",
407 "abcdbc",
408 nil,
409 }, {
410 `decodedLen=6; tagLiteral (4 bytes "abcd"); tagCopy4; length=2 offset=3; valid input`,
411 "\x06" + "\x0cabcd" + "\x07\x03\x00\x00\x00",
412 "abcdbc",
413 nil,
414 }}
415
416 const (
417 // notPresentXxx defines a range of byte values [0xa0, 0xc5) that are
418 // not present in either the input or the output. It is written to dBuf
419 // to check that Decode does not write bytes past the end of
420 // dBuf[:dLen].
421 //
422 // The magic number 37 was chosen because it is prime. A more 'natural'
423 // number like 32 might lead to a false negative if, for example, a
424 // byte was incorrectly copied 4*8 bytes later.
425 notPresentBase = 0xa0
426 notPresentLen = 37
427 )
428
429 var dBuf [100]byte
430 loop:
431 for i, tc := range testCases {
432 input := []byte(tc.input)
433 for _, x := range input {
434 if notPresentBase <= x && x < notPresentBase+notPresentLen {
435 t.Errorf("#%d (%s): input shouldn't contain %#02x\ninput: % x", i, tc.desc, x, input)
436 continue loop
437 }
438 }
439
440 dLen, n := binary.Uvarint(input)
441 if n <= 0 {
442 t.Errorf("#%d (%s): invalid varint-encoded dLen", i, tc.desc)
443 continue
444 }
445 if dLen > uint64(len(dBuf)) {
446 t.Errorf("#%d (%s): dLen %d is too large", i, tc.desc, dLen)
447 continue
448 }
449
450 for j := range dBuf {
451 dBuf[j] = byte(notPresentBase + j%notPresentLen)
452 }
453 g, gotErr := Decode(dBuf[:], input)
454 if got := string(g); got != tc.want || gotErr != tc.wantErr {
455 t.Errorf("#%d (%s):\ngot %q, %v\nwant %q, %v",
456 i, tc.desc, got, gotErr, tc.want, tc.wantErr)
457 continue
458 }
459 for j, x := range dBuf {
460 if uint64(j) < dLen {
461 continue
462 }
463 if w := byte(notPresentBase + j%notPresentLen); x != w {
464 t.Errorf("#%d (%s): Decode overrun: dBuf[%d] was modified: got %#02x, want %#02x\ndBuf: % x",
465 i, tc.desc, j, x, w, dBuf)
466 continue loop
467 }
468 }
469 }
470 }
471
472 func TestDecodeCopy4(t *testing.T) {
473 dots := strings.Repeat(".", 65536)
474
475 input := strings.Join([]string{
476 "\x89\x80\x04", // decodedLen = 65545.
477 "\x0cpqrs", // 4-byte literal "pqrs".
478 "\xf4\xff\xff" + dots, // 65536-byte literal dots.
479 "\x13\x04\x00\x01\x00", // tagCopy4; length=5 offset=65540.
480 }, "")
481
482 gotBytes, err := Decode(nil, []byte(input))
483 if err != nil {
484 t.Fatal(err)
485 }
486 got := string(gotBytes)
487 want := "pqrs" + dots + "pqrs."
488 if len(got) != len(want) {
489 t.Fatalf("got %d bytes, want %d", len(got), len(want))
490 }
491 if got != want {
492 for i := 0; i < len(got); i++ {
493 if g, w := got[i], want[i]; g != w {
494 t.Fatalf("byte #%d: got %#02x, want %#02x", i, g, w)
495 }
496 }
497 }
498 }
499
500 // TestDecodeLengthOffset tests decoding an encoding of the form literal +
501 // copy-length-offset + literal. For example: "abcdefghijkl" + "efghij" + "AB".
502 func TestDecodeLengthOffset(t *testing.T) {
503 const (
504 prefix = "abcdefghijklmnopqr"
505 suffix = "ABCDEFGHIJKLMNOPQR"
506
507 // notPresentXxx defines a range of byte values [0xa0, 0xc5) that are
508 // not present in either the input or the output. It is written to
509 // gotBuf to check that Decode does not write bytes past the end of
510 // gotBuf[:totalLen].
511 //
512 // The magic number 37 was chosen because it is prime. A more 'natural'
513 // number like 32 might lead to a false negative if, for example, a
514 // byte was incorrectly copied 4*8 bytes later.
515 notPresentBase = 0xa0
516 notPresentLen = 37
517 )
518 var gotBuf, wantBuf, inputBuf [128]byte
519 for length := 1; length <= 18; length++ {
520 for offset := 1; offset <= 18; offset++ {
521 loop:
522 for suffixLen := 0; suffixLen <= 18; suffixLen++ {
523 totalLen := len(prefix) + length + suffixLen
524
525 inputLen := binary.PutUvarint(inputBuf[:], uint64(totalLen))
526 inputBuf[inputLen] = tagLiteral + 4*byte(len(prefix)-1)
527 inputLen++
528 inputLen += copy(inputBuf[inputLen:], prefix)
529 inputBuf[inputLen+0] = tagCopy2 + 4*byte(length-1)
530 inputBuf[inputLen+1] = byte(offset)
531 inputBuf[inputLen+2] = 0x00
532 inputLen += 3
533 if suffixLen > 0 {
534 inputBuf[inputLen] = tagLiteral + 4*byte(suffixLen-1)
535 inputLen++
536 inputLen += copy(inputBuf[inputLen:], suffix[:suffixLen])
537 }
538 input := inputBuf[:inputLen]
539
540 for i := range gotBuf {
541 gotBuf[i] = byte(notPresentBase + i%notPresentLen)
542 }
543 got, err := Decode(gotBuf[:], input)
544 if err != nil {
545 t.Errorf("length=%d, offset=%d; suffixLen=%d: %v", length, offset, suffixLen, err)
546 continue
547 }
548
549 wantLen := 0
550 wantLen += copy(wantBuf[wantLen:], prefix)
551 for i := 0; i < length; i++ {
552 wantBuf[wantLen] = wantBuf[wantLen-offset]
553 wantLen++
554 }
555 wantLen += copy(wantBuf[wantLen:], suffix[:suffixLen])
556 want := wantBuf[:wantLen]
557
558 for _, x := range input {
559 if notPresentBase <= x && x < notPresentBase+notPresentLen {
560 t.Errorf("length=%d, offset=%d; suffixLen=%d: input shouldn't contain %#02x\ninput: % x",
561 length, offset, suffixLen, x, input)
562 continue loop
563 }
564 }
565 for i, x := range gotBuf {
566 if i < totalLen {
567 continue
568 }
569 if w := byte(notPresentBase + i%notPresentLen); x != w {
570 t.Errorf("length=%d, offset=%d; suffixLen=%d; totalLen=%d: "+
571 "Decode overrun: gotBuf[%d] was modified: got %#02x, want %#02x\ngotBuf: % x",
572 length, offset, suffixLen, totalLen, i, x, w, gotBuf)
573 continue loop
574 }
575 }
576 for _, x := range want {
577 if notPresentBase <= x && x < notPresentBase+notPresentLen {
578 t.Errorf("length=%d, offset=%d; suffixLen=%d: want shouldn't contain %#02x\nwant: % x",
579 length, offset, suffixLen, x, want)
580 continue loop
581 }
582 }
583
584 if !bytes.Equal(got, want) {
585 t.Errorf("length=%d, offset=%d; suffixLen=%d:\ninput % x\ngot % x\nwant % x",
586 length, offset, suffixLen, input, got, want)
587 continue
588 }
589 }
590 }
591 }
592 }
593
594 const (
595 goldenText = "Mark.Twain-Tom.Sawyer.txt"
596 goldenCompressed = goldenText + ".rawsnappy"
597 )
598
599 func TestDecodeGoldenInput(t *testing.T) {
600 tDir := filepath.FromSlash(*testdataDir)
601 src, err := os.ReadFile(filepath.Join(tDir, goldenCompressed))
602 if err != nil {
603 t.Fatalf("ReadFile: %v", err)
604 }
605 got, err := Decode(nil, src)
606 if err != nil {
607 t.Fatalf("Decode: %v", err)
608 }
609 want, err := os.ReadFile(filepath.Join(tDir, goldenText))
610 if err != nil {
611 t.Fatalf("ReadFile: %v", err)
612 }
613 if err := cmp(got, want); err != nil {
614 t.Fatal(err)
615 }
616 }
617
618 // TestSlowForwardCopyOverrun tests the "expand the pattern" algorithm
619 // described in decode_amd64.s and its claim of a 10 byte overrun worst case.
620 func TestSlowForwardCopyOverrun(t *testing.T) {
621 const base = 100
622
623 for length := 1; length < 18; length++ {
624 for offset := 1; offset < 18; offset++ {
625 highWaterMark := base
626 d := base
627 l := length
628 o := offset
629
630 // makeOffsetAtLeast8
631 for o < 8 {
632 if end := d + 8; highWaterMark < end {
633 highWaterMark = end
634 }
635 l -= o
636 d += o
637 o += o
638 }
639
640 // fixUpSlowForwardCopy
641 a := d
642 d += l
643
644 // finishSlowForwardCopy
645 for l > 0 {
646 if end := a + 8; highWaterMark < end {
647 highWaterMark = end
648 }
649 a += 8
650 l -= 8
651 }
652
653 dWant := base + length
654 overrun := highWaterMark - dWant
655 if d != dWant || overrun < 0 || 10 < overrun {
656 t.Errorf("length=%d, offset=%d: d and overrun: got (%d, %d), want (%d, something in [0, 10])",
657 length, offset, d, overrun, dWant)
658 }
659 }
660 }
661 }
662
663 // TestEncoderSkip will test skipping various sizes and block types.
664 func TestEncoderSkip(t *testing.T) {
665 for ti, origLen := range []int{10 << 10, 256 << 10, 2 << 20, 8 << 20} {
666 if testing.Short() && ti > 1 {
667 break
668 }
669 t.Run(fmt.Sprint(origLen), func(t *testing.T) {
670 src := make([]byte, origLen)
671 rng := rand.New(rand.NewSource(1))
672 firstHalf, secondHalf := src[:origLen/2], src[origLen/2:]
673 bonus := secondHalf[len(secondHalf)-origLen/10:]
674 for i := range firstHalf {
675 // Incompressible.
676 firstHalf[i] = uint8(rng.Intn(256))
677 }
678 for i := range secondHalf {
679 // Easy to compress.
680 secondHalf[i] = uint8(i & 32)
681 }
682 for i := range bonus {
683 // Incompressible.
684 bonus[i] = uint8(rng.Intn(256))
685 }
686 var dst bytes.Buffer
687 enc := NewWriter(&dst, WriterBlockSize(64<<10))
688 _, err := io.Copy(enc, bytes.NewBuffer(src))
689 if err != nil {
690 t.Fatal(err)
691 }
692 err = enc.Close()
693 if err != nil {
694 t.Fatal(err)
695 }
696 compressed := dst.Bytes()
697 dec := NewReader(nil)
698 for i := 0; i < len(src); i += len(src)/20 - 17 {
699 t.Run(fmt.Sprint("skip-", i), func(t *testing.T) {
700 want := src[i:]
701 dec.Reset(bytes.NewBuffer(compressed))
702 // Read some of it first
703 read, err := io.CopyN(io.Discard, dec, int64(len(want)/10))
704 if err != nil {
705 t.Fatal(err)
706 }
707 // skip what we just read.
708 want = want[read:]
709 err = dec.Skip(int64(i))
710 if err != nil {
711 t.Fatal(err)
712 }
713 got, err := io.ReadAll(dec)
714 if err != nil {
715 t.Errorf("Skipping %d returned error: %v", i, err)
716 return
717 }
718 if !bytes.Equal(want, got) {
719 t.Log("got len:", len(got))
720 t.Log("want len:", len(want))
721 t.Errorf("Skipping %d did not return correct data (content mismatch)", i)
722 return
723 }
724 })
725 if testing.Short() && i > 0 {
726 return
727 }
728 }
729 })
730 }
731 }
732
733 // TestEncodeNoiseThenRepeats encodes input for which the first half is very
734 // incompressible and the second half is very compressible. The encoded form's
735 // length should be closer to 50% of the original length than 100%.
736 func TestEncodeNoiseThenRepeats(t *testing.T) {
737 for _, origLen := range []int{256 * 1024, 2048 * 1024} {
738 src := make([]byte, origLen)
739 rng := rand.New(rand.NewSource(1))
740 firstHalf, secondHalf := src[:origLen/2], src[origLen/2:]
741 for i := range firstHalf {
742 firstHalf[i] = uint8(rng.Intn(256))
743 }
744 for i := range secondHalf {
745 secondHalf[i] = uint8(i >> 8)
746 }
747 dst := Encode(nil, src)
748 if got, want := len(dst), origLen*3/4; got >= want {
749 t.Fatalf("origLen=%d: got %d encoded bytes, want less than %d", origLen, got, want)
750 }
751 t.Log(len(dst))
752 }
753 }
754
755 func TestFramingFormat(t *testing.T) {
756 // src is comprised of alternating 1e5-sized sequences of random
757 // (incompressible) bytes and repeated (compressible) bytes. 1e5 was chosen
758 // because it is larger than maxBlockSize (64k).
759 src := make([]byte, 1e6)
760 rng := rand.New(rand.NewSource(1))
761 for i := range 10 {
762 if i%2 == 0 {
763 for j := range int(1e5) {
764 src[1e5*i+j] = uint8(rng.Intn(256))
765 }
766 } else {
767 for j := range int(1e5) {
768 src[1e5*i+j] = uint8(i)
769 }
770 }
771 }
772
773 buf := new(bytes.Buffer)
774 bw := NewWriter(buf)
775 if _, err := bw.Write(src); err != nil {
776 t.Fatalf("Write: encoding: %v", err)
777 }
778 err := bw.Close()
779 if err != nil {
780 t.Fatal(err)
781 }
782 dst, err := io.ReadAll(NewReader(buf))
783 if err != nil {
784 t.Fatalf("ReadAll: decoding: %v", err)
785 }
786 if err := cmp(dst, src); err != nil {
787 t.Fatal(err)
788 }
789 }
790
791 func TestFramingFormatBetter(t *testing.T) {
792 // src is comprised of alternating 1e5-sized sequences of random
793 // (incompressible) bytes and repeated (compressible) bytes. 1e5 was chosen
794 // because it is larger than maxBlockSize (64k).
795 src := make([]byte, 1e6)
796 rng := rand.New(rand.NewSource(1))
797 for i := range 10 {
798 if i%2 == 0 {
799 for j := range int(1e5) {
800 src[1e5*i+j] = uint8(rng.Intn(256))
801 }
802 } else {
803 for j := range int(1e5) {
804 src[1e5*i+j] = uint8(i)
805 }
806 }
807 }
808
809 buf := new(bytes.Buffer)
810 bw := NewWriter(buf, WriterBetterCompression())
811 if _, err := bw.Write(src); err != nil {
812 t.Fatalf("Write: encoding: %v", err)
813 }
814 err := bw.Close()
815 if err != nil {
816 t.Fatal(err)
817 }
818 dst, err := io.ReadAll(NewReader(buf))
819 if err != nil {
820 t.Fatalf("ReadAll: decoding: %v", err)
821 }
822 if err := cmp(dst, src); err != nil {
823 t.Fatal(err)
824 }
825 }
826
827 func TestEmitLiteral(t *testing.T) {
828 testCases := []struct {
829 length int
830 want string
831 }{
832 {1, "\x00"},
833 {2, "\x04"},
834 {59, "\xe8"},
835 {60, "\xec"},
836 {61, "\xf0\x3c"},
837 {62, "\xf0\x3d"},
838 {254, "\xf0\xfd"},
839 {255, "\xf0\xfe"},
840 {256, "\xf0\xff"},
841 {257, "\xf4\x00\x01"},
842 {65534, "\xf4\xfd\xff"},
843 {65535, "\xf4\xfe\xff"},
844 {65536, "\xf4\xff\xff"},
845 }
846
847 dst := make([]byte, 70000)
848 nines := bytes.Repeat([]byte{0x99}, 65536)
849 for _, tc := range testCases {
850 lit := nines[:tc.length]
851 n := emitLiteral(dst, lit)
852 if !bytes.HasSuffix(dst[:n], lit) {
853 t.Errorf("length=%d: did not end with that many literal bytes", tc.length)
854 continue
855 }
856 got := string(dst[:n-tc.length])
857 if got != tc.want {
858 t.Errorf("length=%d:\ngot % x\nwant % x", tc.length, got, tc.want)
859 continue
860 }
861 }
862 }
863
864 func TestEmitCopy(t *testing.T) {
865 testCases := []struct {
866 offset int
867 length int
868 want string
869 }{
870 {8, 04, "\x01\x08"},
871 {8, 11, "\x1d\x08"},
872 {8, 12, "\x2e\x08\x00"},
873 {8, 13, "\x32\x08\x00"},
874 {8, 59, "\xea\x08\x00"},
875 {8, 60, "\xee\x08\x00"},
876 {8, 61, "\xf2\x08\x00"},
877 {8, 62, "\xf6\x08\x00"},
878 {8, 63, "\xfa\x08\x00"},
879 {8, 64, "\xfe\x08\x00"},
880 {8, 65, "\x11\b\x15\x001"},
881 {8, 66, "\x11\b\x15\x002"},
882 {8, 67, "\x11\b\x15\x003"},
883 {8, 68, "\x11\b\x15\x004"},
884 {8, 69, "\x11\b\x15\x005"},
885 {8, 80, "\x11\b\x15\x00@"},
886 {8, 800, "\x11\b\x19\x00\x14\x02"},
887 {8, 800000, "\x11\b\x1d\x00\xf44\v"},
888
889 {256, 04, "\x21\x00"},
890 {256, 11, "\x3d\x00"},
891 {256, 12, "\x2e\x00\x01"},
892 {256, 13, "\x32\x00\x01"},
893 {256, 59, "\xea\x00\x01"},
894 {256, 60, "\xee\x00\x01"},
895 {256, 61, "\xf2\x00\x01"},
896 {256, 62, "\xf6\x00\x01"},
897 {256, 63, "\xfa\x00\x01"},
898 {256, 64, "\xfe\x00\x01"},
899 {256, 65, "1\x00\x15\x001"},
900 {256, 66, "1\x00\x15\x002"},
901 {256, 67, "1\x00\x15\x003"},
902 {256, 68, "1\x00\x15\x004"},
903 {256, 69, "1\x00\x15\x005"},
904 {256, 80, "1\x00\x15\x00@"},
905 {256, 800, "1\x00\x19\x00\x14\x02"},
906 {256, 80000, "1\x00\x1d\x00t8\x00"},
907
908 {2048, 04, "\x0e\x00\x08"},
909 {2048, 11, "\x2a\x00\x08"},
910 {2048, 12, "\x2e\x00\x08"},
911 {2048, 13, "\x32\x00\x08"},
912 {2048, 59, "\xea\x00\x08"},
913 {2048, 60, "\xee\x00\x08"},
914 {2048, 61, "\xf2\x00\x08"},
915 {2048, 62, "\xf6\x00\x08"},
916 {2048, 63, "\xfa\x00\x08"},
917 {2048, 64, "\xfe\x00\x08"},
918 {2048, 65, "\xee\x00\x08\x05\x00"},
919 {2048, 66, "\xee\x00\x08\x09\x00"},
920 {2048, 67, "\xee\x00\x08\x0d\x00"},
921 {2048, 68, "\xee\x00\x08\x11\x00"},
922 {2048, 69, "\xee\x00\x08\x15\x00\x01"},
923 {2048, 80, "\xee\x00\x08\x15\x00\x0c"},
924 {2048, 800, "\xee\x00\x08\x19\x00\xe0\x01"},
925 {2048, 80000, "\xee\x00\x08\x1d\x00\x40\x38\x00"},
926
927 {204800, 04, "\x0f\x00\x20\x03\x00"},
928 {204800, 65, "\xff\x00\x20\x03\x00\x03\x00\x20\x03\x00"},
929 {204800, 69, "\xff\x00\x20\x03\x00\x05\x00"},
930 {204800, 800, "\xff\x00\x20\x03\x00\x19\x00\xdc\x01"},
931 {204800, 80000, "\xff\x00\x20\x03\x00\x1d\x00\x3c\x38\x00"},
932 }
933
934 dst := make([]byte, 1024)
935 for _, tc := range testCases {
936 n := emitCopy(dst, tc.offset, tc.length)
937 got := string(dst[:n])
938 if got != tc.want {
939 t.Errorf("offset=%d, length=%d:\ngot %q\nwant %q", tc.offset, tc.length, got, tc.want)
940 }
941 }
942 }
943
944 func TestNewWriter(t *testing.T) {
945 // Test all 32 possible sub-sequences of these 5 input slices.
946 //
947 // Their lengths sum to 400,000, which is over 6 times the Writer ibuf
948 // capacity: 6 * maxBlockSize is 393,216.
949 inputs := [][]byte{
950 bytes.Repeat([]byte{'a'}, 40000),
951 bytes.Repeat([]byte{'b'}, 150000),
952 bytes.Repeat([]byte{'c'}, 60000),
953 bytes.Repeat([]byte{'d'}, 120000),
954 bytes.Repeat([]byte{'e'}, 30000),
955 }
956 loop:
957 for i := 0; i < 1<<uint(len(inputs)); i++ {
958 var want []byte
959 buf := new(bytes.Buffer)
960 w := NewWriter(buf)
961 for j, input := range inputs {
962 if i&(1<<uint(j)) == 0 {
963 continue
964 }
965 if _, err := w.Write(input); err != nil {
966 t.Errorf("i=%#02x: j=%d: Write: %v", i, j, err)
967 continue loop
968 }
969 want = append(want, input...)
970 }
971 if err := w.Close(); err != nil {
972 t.Errorf("i=%#02x: Close: %v", i, err)
973 continue
974 }
975 got, err := io.ReadAll(NewReader(buf))
976 if err != nil {
977 t.Errorf("i=%#02x: ReadAll: %v", i, err)
978 continue
979 }
980 if err := cmp(got, want); err != nil {
981 t.Errorf("i=%#02x: %v", i, err)
982 continue
983 }
984 }
985 }
986
987 func TestFlush(t *testing.T) {
988 buf := new(bytes.Buffer)
989 w := NewWriter(buf)
990 defer w.Close()
991 if _, err := w.Write(bytes.Repeat([]byte{'x'}, 20)); err != nil {
992 t.Fatalf("Write: %v", err)
993 }
994 if n := buf.Len(); n != 0 {
995 t.Fatalf("before Flush: %d bytes were written to the underlying io.Writer, want 0", n)
996 }
997 if err := w.Flush(); err != nil {
998 t.Fatalf("Flush: %v", err)
999 }
1000 if n := buf.Len(); n == 0 {
1001 t.Fatalf("after Flush: %d bytes were written to the underlying io.Writer, want non-0", n)
1002 }
1003 }
1004
1005 func TestReaderUncompressedDataOK(t *testing.T) {
1006 r := NewReader(strings.NewReader(magicChunk +
1007 "\x01\x08\x00\x00" + // Uncompressed chunk, 8 bytes long (including 4 byte checksum).
1008 "\x68\x10\xe6\xb6" + // Checksum.
1009 "\x61\x62\x63\x64", // Uncompressed payload: "abcd".
1010 ))
1011 g, err := io.ReadAll(r)
1012 if err != nil {
1013 t.Fatal(err)
1014 }
1015 if got, want := string(g), "abcd"; got != want {
1016 t.Fatalf("got %q, want %q", got, want)
1017 }
1018 }
1019
1020 func TestReaderUncompressedDataNoPayload(t *testing.T) {
1021 r := NewReader(strings.NewReader(magicChunk +
1022 "\x01\x04\x00\x00" + // Uncompressed chunk, 4 bytes long.
1023 "", // No payload; corrupt input.
1024 ))
1025 if _, err := io.ReadAll(r); err != ErrCorrupt {
1026 t.Fatalf("got %v, want %v", err, ErrCorrupt)
1027 }
1028 }
1029
1030 func TestReaderUncompressedDataTooLong(t *testing.T) {
1031 // The maximum legal chunk length... is 4MB + 4 bytes checksum.
1032 n := maxBlockSize + checksumSize
1033 n32 := uint32(n)
1034 r := NewReader(strings.NewReader(magicChunk +
1035 // Uncompressed chunk, n bytes long.
1036 string([]byte{chunkTypeUncompressedData, uint8(n32), uint8(n32 >> 8), uint8(n32 >> 16)}) +
1037 strings.Repeat("\x00", n),
1038 ))
1039 // CRC is not set, so we should expect that error.
1040 if _, err := io.ReadAll(r); err != ErrCRC {
1041 t.Fatalf("got %v, want %v", err, ErrCRC)
1042 }
1043
1044 // test first invalid.
1045 n++
1046 n32 = uint32(n)
1047 r = NewReader(strings.NewReader(magicChunk +
1048 // Uncompressed chunk, n bytes long.
1049 string([]byte{chunkTypeUncompressedData, uint8(n32), uint8(n32 >> 8), uint8(n32 >> 16)}) +
1050 strings.Repeat("\x00", n),
1051 ))
1052 if _, err := io.ReadAll(r); err != ErrCorrupt {
1053 t.Fatalf("got %v, want %v", err, ErrCorrupt)
1054 }
1055 }
1056
1057 func TestReaderReset(t *testing.T) {
1058 gold := bytes.Repeat([]byte("All that is gold does not glitter,\n"), 10000)
1059 buf := new(bytes.Buffer)
1060 w := NewWriter(buf)
1061 _, err := w.Write(gold)
1062 if err != nil {
1063 t.Fatalf("Write: %v", err)
1064 }
1065 err = w.Close()
1066 if err != nil {
1067 t.Fatalf("Close: %v", err)
1068 }
1069
1070 encoded, invalid, partial := buf.String(), "invalid", "partial"
1071 r := NewReader(nil)
1072 for i, s := range []string{encoded, invalid, partial, encoded, partial, invalid, encoded, encoded} {
1073 if s == partial {
1074 r.Reset(strings.NewReader(encoded))
1075 if _, err := r.Read(make([]byte, 101)); err != nil {
1076 t.Errorf("#%d: %v", i, err)
1077 continue
1078 }
1079 continue
1080 }
1081 r.Reset(strings.NewReader(s))
1082 got, err := io.ReadAll(r)
1083 switch s {
1084 case encoded:
1085 if err != nil {
1086 t.Errorf("#%d: %v", i, err)
1087 continue
1088 }
1089 if err := cmp(got, gold); err != nil {
1090 t.Errorf("#%d: %v", i, err)
1091 continue
1092 }
1093 case invalid:
1094 if err == nil {
1095 t.Errorf("#%d: got nil error, want non-nil", i)
1096 continue
1097 }
1098 }
1099 }
1100 }
1101
1102 func TestWriterReset(t *testing.T) {
1103 gold := bytes.Repeat([]byte("Not all those who wander are lost;\n"), 10000)
1104 const n = 20
1105 w := NewWriter(nil)
1106 defer w.Close()
1107
1108 var gots, wants [][]byte
1109 failed := false
1110 for i := 0; i <= n; i++ {
1111 buf := new(bytes.Buffer)
1112 w.Reset(buf)
1113 want := gold[:len(gold)*i/n]
1114 if _, err := w.Write(want); err != nil {
1115 t.Errorf("#%d: Write: %v", i, err)
1116 failed = true
1117 continue
1118 }
1119 if err := w.Flush(); err != nil {
1120 t.Errorf("#%d: Flush: %v", i, err)
1121 failed = true
1122 got, err := io.ReadAll(NewReader(buf))
1123 if err != nil {
1124 t.Errorf("#%d: ReadAll: %v", i, err)
1125 failed = true
1126 continue
1127 }
1128 gots = append(gots, got)
1129 wants = append(wants, want)
1130 }
1131 if failed {
1132 continue
1133 }
1134 for i := range gots {
1135 if err := cmp(gots[i], wants[i]); err != nil {
1136 t.Errorf("#%d: %v", i, err)
1137 }
1138 }
1139 }
1140 }
1141
1142 func TestWriterResetWithoutFlush(t *testing.T) {
1143 buf0 := new(bytes.Buffer)
1144 buf1 := new(bytes.Buffer)
1145 w := NewWriter(buf0)
1146 if _, err := w.Write([]byte("xxx")); err != nil {
1147 t.Fatalf("Write #0: %v", err)
1148 }
1149 // Note that we don't Flush the Writer before calling Reset.
1150 w.Reset(buf1)
1151 if _, err := w.Write([]byte("yyy")); err != nil {
1152 t.Fatalf("Write #1: %v", err)
1153 }
1154 if err := w.Flush(); err != nil {
1155 t.Fatalf("Flush: %v", err)
1156 }
1157 got, err := io.ReadAll(NewReader(buf1))
1158 if err != nil {
1159 t.Fatalf("ReadAll: %v", err)
1160 }
1161 if err := cmp(got, []byte("yyy")); err != nil {
1162 t.Fatal(err)
1163 }
1164 }
1165
1166 type writeCounter int
1167
1168 func (c *writeCounter) Write(p []byte) (int, error) {
1169 *c++
1170 return len(p), nil
1171 }
1172
1173 // TestNumUnderlyingWrites tests that each Writer flush only makes one or two
1174 // Write calls on its underlying io.Writer, depending on whether or not the
1175 // flushed buffer was compressible.
1176 func TestNumUnderlyingWrites(t *testing.T) {
1177 testCases := []struct {
1178 input []byte
1179 want int
1180 }{
1181 // Magic header + block
1182 {bytes.Repeat([]byte{'x'}, 100), 2},
1183 // One block each:
1184 {bytes.Repeat([]byte{'y'}, 100), 1},
1185 {[]byte("ABCDEFGHIJKLMNOPQRST"), 1},
1186 }
1187
1188 // If we are doing sync writes, we write uncompressed as two writes.
1189 if runtime.GOMAXPROCS(0) == 1 {
1190 testCases[2].want++
1191 }
1192 var c writeCounter
1193 w := NewWriter(&c)
1194 defer w.Close()
1195 for i, tc := range testCases {
1196 c = 0
1197 if _, err := w.Write(tc.input); err != nil {
1198 t.Errorf("#%d: Write: %v", i, err)
1199 continue
1200 }
1201 if err := w.Flush(); err != nil {
1202 t.Errorf("#%d: Flush: %v", i, err)
1203 continue
1204 }
1205 if int(c) != tc.want {
1206 t.Errorf("#%d: got %d underlying writes, want %d", i, c, tc.want)
1207 continue
1208 }
1209 }
1210 }
1211
1212 func testWriterRoundtrip(t *testing.T, src []byte, opts ...WriterOption) {
1213 var buf bytes.Buffer
1214 enc := NewWriter(&buf, opts...)
1215 n, err := enc.Write(src)
1216 if err != nil {
1217 t.Error(err)
1218 return
1219 }
1220 if n != len(src) {
1221 t.Error(io.ErrShortWrite)
1222 return
1223 }
1224 err = enc.Flush()
1225 if err != nil {
1226 t.Error(err)
1227 return
1228 }
1229 // Extra flush and close should be noops.
1230 err = enc.Flush()
1231 if err != nil {
1232 t.Error(err)
1233 return
1234 }
1235 err = enc.Close()
1236 if err != nil {
1237 t.Error(err)
1238 return
1239 }
1240
1241 t.Logf("encoded to %d -> %d bytes", len(src), buf.Len())
1242 dec := NewReader(&buf)
1243 decoded, err := io.ReadAll(dec)
1244 if err != nil {
1245 t.Error(err)
1246 return
1247 }
1248 if len(decoded) != len(src) {
1249 t.Error("decoded len:", len(decoded), "!=", len(src))
1250 return
1251 }
1252 err = cmp(src, decoded)
1253 if err != nil {
1254 t.Error(err)
1255 }
1256 }
1257
1258 func testBlockRoundtrip(t *testing.T, src []byte) {
1259 dst := Encode(nil, src)
1260 t.Logf("encoded to %d -> %d bytes", len(src), len(dst))
1261 decoded, err := Decode(nil, dst)
1262 if err != nil {
1263 t.Error(err)
1264 return
1265 }
1266 if len(decoded) != len(src) {
1267 t.Error("decoded len:", len(decoded), "!=", len(src))
1268 return
1269 }
1270 err = cmp(decoded, src)
1271 if err != nil {
1272 t.Error(err)
1273 }
1274 }
1275
1276 func testBetterBlockRoundtrip(t *testing.T, src []byte) {
1277 dst := EncodeBetter(nil, src)
1278 t.Logf("encoded to %d -> %d bytes", len(src), len(dst))
1279 decoded, err := Decode(nil, dst)
1280 if err != nil {
1281 t.Error(err)
1282 return
1283 }
1284 if len(decoded) != len(src) {
1285 t.Error("decoded len:", len(decoded), "!=", len(src))
1286 return
1287 }
1288 err = cmp(src, decoded)
1289 if err != nil {
1290 t.Error(err)
1291 }
1292 }
1293
1294 func testBestBlockRoundtrip(t *testing.T, src []byte) {
1295 dst := EncodeBest(nil, src)
1296 t.Logf("encoded to %d -> %d bytes", len(src), len(dst))
1297 decoded, err := Decode(nil, dst)
1298 if err != nil {
1299 t.Error(err)
1300 return
1301 }
1302 if len(decoded) != len(src) {
1303 t.Error("decoded len:", len(decoded), "!=", len(src))
1304 return
1305 }
1306 err = cmp(src, decoded)
1307 if err != nil {
1308 t.Error(err)
1309 }
1310 }
1311
1312 func testSnappyBlockRoundtrip(t *testing.T, src []byte) {
1313 // Write with s2, decode with snapref.
1314 t.Run("regular", func(t *testing.T) {
1315 dst := EncodeSnappy(nil, src)
1316 t.Logf("encoded to %d -> %d bytes", len(src), len(dst))
1317 decoded, err := snapref.Decode(nil, dst)
1318 if err != nil {
1319 t.Error(err)
1320 return
1321 }
1322 if len(decoded) != len(src) {
1323 t.Error("decoded len:", len(decoded), "!=", len(src))
1324 return
1325 }
1326 err = cmp(src, decoded)
1327 if err != nil {
1328 t.Error(err)
1329 }
1330 })
1331 t.Run("better", func(t *testing.T) {
1332 dst := EncodeSnappyBetter(nil, src)
1333 t.Logf("encoded to %d -> %d bytes", len(src), len(dst))
1334 decoded, err := snapref.Decode(nil, dst)
1335 if err != nil {
1336 t.Error(err)
1337 return
1338 }
1339 if len(decoded) != len(src) {
1340 t.Error("decoded len:", len(decoded), "!=", len(src))
1341 return
1342 }
1343 err = cmp(src, decoded)
1344 if err != nil {
1345 t.Error(err)
1346 }
1347 })
1348 t.Run("best", func(t *testing.T) {
1349 dst := EncodeSnappyBest(nil, src)
1350 t.Logf("encoded to %d -> %d bytes", len(src), len(dst))
1351 decoded, err := snapref.Decode(nil, dst)
1352 if err != nil {
1353 t.Error(err)
1354 return
1355 }
1356 if len(decoded) != len(src) {
1357 t.Error("decoded len:", len(decoded), "!=", len(src))
1358 return
1359 }
1360 err = cmp(src, decoded)
1361 if err != nil {
1362 t.Error(err)
1363 }
1364 })
1365 }
1366
1367 func testSnappyDecode(t *testing.T, src []byte) {
1368 var buf bytes.Buffer
1369 enc := snapref.NewBufferedWriter(&buf)
1370 n, err := enc.Write(src)
1371 if err != nil {
1372 t.Error(err)
1373 return
1374 }
1375 if n != len(src) {
1376 t.Error(io.ErrShortWrite)
1377 return
1378 }
1379 enc.Close()
1380 t.Logf("encoded to %d -> %d bytes", len(src), buf.Len())
1381 dec := NewReader(&buf)
1382 decoded, err := io.ReadAll(dec)
1383 if err != nil {
1384 t.Error(err)
1385 return
1386 }
1387 if len(decoded) != len(src) {
1388 t.Error("decoded len:", len(decoded), "!=", len(src))
1389 return
1390 }
1391 err = cmp(src, decoded)
1392 if err != nil {
1393 t.Error(err)
1394 }
1395 }
1396
1397 func benchDecode(b *testing.B, src []byte) {
1398 b.Run("default", func(b *testing.B) {
1399 encoded := Encode(nil, src)
1400 buf := make([]byte, 0, len(src))
1401 b.SetBytes(int64(len(src)))
1402 b.ReportAllocs()
1403 b.ResetTimer()
1404 var err error
1405 for i := 0; i < b.N; i++ {
1406 buf, err = Decode(buf[:0], encoded)
1407 if err != nil {
1408 b.Fatal(err)
1409 }
1410 }
1411 b.ReportMetric(100*float64(len(encoded))/float64(len(src)), "pct")
1412 })
1413 b.Run("better", func(b *testing.B) {
1414 encoded := EncodeBetter(nil, src)
1415 buf := make([]byte, 0, len(src))
1416 b.SetBytes(int64(len(src)))
1417 b.ReportAllocs()
1418 b.ResetTimer()
1419 var err error
1420 for i := 0; i < b.N; i++ {
1421 buf, err = Decode(buf[:0], encoded)
1422 if err != nil {
1423 b.Fatal(err)
1424 }
1425 }
1426 b.ReportMetric(100*float64(len(encoded))/float64(len(src)), "pct")
1427 })
1428 b.Run("best", func(b *testing.B) {
1429 encoded := EncodeBest(nil, src)
1430 buf := make([]byte, 0, len(src))
1431 b.SetBytes(int64(len(src)))
1432 b.ReportAllocs()
1433 b.ResetTimer()
1434 var err error
1435 for i := 0; i < b.N; i++ {
1436 buf, err = Decode(buf[:0], encoded)
1437 if err != nil {
1438 b.Fatal(err)
1439 }
1440 }
1441 b.ReportMetric(100*float64(len(encoded))/float64(len(src)), "pct")
1442 })
1443 b.Run("snappy-input", func(b *testing.B) {
1444 encoded := snapref.Encode(nil, src)
1445 buf := make([]byte, 0, len(src))
1446 b.SetBytes(int64(len(src)))
1447 b.ReportAllocs()
1448 b.ResetTimer()
1449 var err error
1450 for i := 0; i < b.N; i++ {
1451 buf, err = Decode(buf[:0], encoded)
1452 if err != nil {
1453 b.Fatal(err)
1454 }
1455 }
1456 b.ReportMetric(100*float64(len(encoded))/float64(len(src)), "pct")
1457 })
1458 }
1459
1460 func benchEncode(b *testing.B, src []byte) {
1461 // Bandwidth is in amount of uncompressed data.
1462 b.Run("default", func(b *testing.B) {
1463 dst := make([]byte, MaxEncodedLen(len(src)))
1464 b.ResetTimer()
1465 b.SetBytes(int64(len(src)))
1466 b.ReportAllocs()
1467 for i := 0; i < b.N; i++ {
1468 dst = Encode(dst[:0], src)
1469 }
1470 b.ReportMetric(100*float64(len(dst))/float64(len(src)), "pct")
1471 })
1472 b.Run("better", func(b *testing.B) {
1473 dst := make([]byte, MaxEncodedLen(len(src)))
1474 b.ResetTimer()
1475 b.SetBytes(int64(len(src)))
1476 b.ReportAllocs()
1477 for i := 0; i < b.N; i++ {
1478 dst = EncodeBetter(dst[:0], src)
1479 }
1480 b.ReportMetric(100*float64(len(dst))/float64(len(src)), "pct")
1481 })
1482 b.Run("best", func(b *testing.B) {
1483 dst := make([]byte, MaxEncodedLen(len(src)))
1484 b.ResetTimer()
1485 b.SetBytes(int64(len(src)))
1486 b.ReportAllocs()
1487 for i := 0; i < b.N; i++ {
1488 dst = EncodeBest(dst[:0], src)
1489 }
1490 b.ReportMetric(100*float64(len(dst))/float64(len(src)), "pct")
1491 })
1492 b.Run("snappy-default", func(b *testing.B) {
1493 dst := make([]byte, MaxEncodedLen(len(src)))
1494 b.SetBytes(int64(len(src)))
1495 b.ReportAllocs()
1496 b.ResetTimer()
1497 for i := 0; i < b.N; i++ {
1498 dst = EncodeSnappy(dst[:0], src)
1499 }
1500 b.ReportMetric(100*float64(len(dst))/float64(len(src)), "pct")
1501 })
1502 b.Run("snappy-better", func(b *testing.B) {
1503 dst := make([]byte, MaxEncodedLen(len(src)))
1504 b.SetBytes(int64(len(src)))
1505 b.ReportAllocs()
1506 b.ResetTimer()
1507 for i := 0; i < b.N; i++ {
1508 dst = EncodeSnappyBetter(dst[:0], src)
1509 }
1510 b.ReportMetric(100*float64(len(dst))/float64(len(src)), "pct")
1511 })
1512 b.Run("snappy-best", func(b *testing.B) {
1513 dst := make([]byte, MaxEncodedLen(len(src)))
1514 b.SetBytes(int64(len(src)))
1515 b.ReportAllocs()
1516 b.ResetTimer()
1517 for i := 0; i < b.N; i++ {
1518 dst = EncodeSnappyBest(dst[:0], src)
1519 }
1520 b.ReportMetric(100*float64(len(dst))/float64(len(src)), "pct")
1521 })
1522 b.Run("snappy-ref-noasm", func(b *testing.B) {
1523 dst := make([]byte, snapref.MaxEncodedLen(len(src)))
1524 b.SetBytes(int64(len(src)))
1525 b.ReportAllocs()
1526 b.ResetTimer()
1527 for i := 0; i < b.N; i++ {
1528 dst = snapref.Encode(dst[:0], src)
1529 }
1530 b.ReportMetric(100*float64(len(dst))/float64(len(src)), "pct")
1531 })
1532 }
1533
1534 func testOrBenchmark(b testing.TB) string {
1535 if _, ok := b.(*testing.B); ok {
1536 return "benchmark"
1537 }
1538 return "test"
1539 }
1540
1541 func readFile(b testing.TB, filename string) []byte {
1542 src, err := os.ReadFile(filename)
1543 if err != nil {
1544 b.Skipf("skipping %s: %v", testOrBenchmark(b), err)
1545 }
1546 if len(src) == 0 {
1547 b.Fatalf("%s has zero length", filename)
1548 }
1549 return src
1550 }
1551
1552 // expand returns a slice of length n containing mutated copies of src.
1553 func expand(src []byte, n int) []byte {
1554 dst := make([]byte, n)
1555 cnt := uint8(0)
1556 for x := dst; len(x) > 0; cnt++ {
1557 idx := copy(x, src)
1558 for i := range x {
1559 if i >= len(src) {
1560 break
1561 }
1562 x[i] = src[i] ^ cnt
1563 }
1564 x = x[idx:]
1565 }
1566 return dst
1567 }
1568
1569 func benchTwain(b *testing.B, n int, decode bool) {
1570 data := expand(readFile(b, "../testdata/Mark.Twain-Tom.Sawyer.txt"), n)
1571 if decode {
1572 benchDecode(b, data)
1573 } else {
1574 benchEncode(b, data)
1575 }
1576 }
1577
1578 func BenchmarkTwainDecode1e1(b *testing.B) { benchTwain(b, 1e1, true) }
1579 func BenchmarkTwainDecode1e2(b *testing.B) { benchTwain(b, 1e2, true) }
1580 func BenchmarkTwainDecode1e3(b *testing.B) { benchTwain(b, 1e3, true) }
1581 func BenchmarkTwainDecode1e4(b *testing.B) { benchTwain(b, 1e4, true) }
1582 func BenchmarkTwainDecode1e5(b *testing.B) { benchTwain(b, 1e5, true) }
1583 func BenchmarkTwainDecode1e6(b *testing.B) { benchTwain(b, 1e6, true) }
1584 func BenchmarkTwainDecode1e7(b *testing.B) { benchTwain(b, 1e7, true) }
1585 func BenchmarkTwainEncode1e1(b *testing.B) { benchTwain(b, 1e1, false) }
1586 func BenchmarkTwainEncode1e2(b *testing.B) { benchTwain(b, 1e2, false) }
1587 func BenchmarkTwainEncode1e3(b *testing.B) { benchTwain(b, 1e3, false) }
1588 func BenchmarkTwainEncode1e4(b *testing.B) { benchTwain(b, 1e4, false) }
1589 func BenchmarkTwainEncode1e5(b *testing.B) { benchTwain(b, 1e5, false) }
1590 func BenchmarkTwainEncode1e6(b *testing.B) { benchTwain(b, 1e6, false) }
1591 func BenchmarkTwainEncode1e7(b *testing.B) { benchTwain(b, 1e7, false) }
1592
1593 func BenchmarkRandomEncodeBlock1MB(b *testing.B) {
1594 rng := rand.New(rand.NewSource(1))
1595 data := make([]byte, 1<<20)
1596 for i := range data {
1597 data[i] = uint8(rng.Intn(256))
1598 }
1599 benchEncode(b, data)
1600 }
1601
1602 func BenchmarkRandomEncodeBetterBlock16MB(b *testing.B) {
1603 rng := rand.New(rand.NewSource(1))
1604 data := make([]byte, 16<<20)
1605 for i := range data {
1606 data[i] = uint8(rng.Intn(256))
1607 }
1608 benchEncode(b, data)
1609 }
1610
1611 // testFiles' values are copied directly from
1612 // https://raw.githubusercontent.com/google/snappy/master/snappy_unittest.cc
1613 // The label field is unused in snappy-go.
1614 var testFiles = []struct {
1615 label string
1616 filename string
1617 sizeLimit int
1618 }{
1619 {"html", "html", 0},
1620 {"urls", "urls.10K", 0},
1621 {"jpg", "fireworks.jpeg", 0},
1622 {"jpg_200b", "fireworks.jpeg", 200},
1623 {"pdf", "paper-100k.pdf", 0},
1624 {"html4", "html_x_4", 0},
1625 {"txt1", "alice29.txt", 0},
1626 {"txt2", "asyoulik.txt", 0},
1627 {"txt3", "lcet10.txt", 0},
1628 {"txt4", "plrabn12.txt", 0},
1629 {"pb", "geo.protodata", 0},
1630 {"gaviota", "kppkn.gtb", 0},
1631 {"txt1_128b", "alice29.txt", 128},
1632 {"txt1_1000b", "alice29.txt", 1000},
1633 {"txt1_10000b", "alice29.txt", 10000},
1634 {"txt1_20000b", "alice29.txt", 20000},
1635 }
1636
1637 const (
1638 // The benchmark data files are at this canonical URL.
1639 benchURL = "https://raw.githubusercontent.com/google/snappy/master/testdata/"
1640 )
1641
1642 func downloadBenchmarkFiles(b testing.TB, basename string) (errRet error) {
1643 bDir := filepath.FromSlash(*benchdataDir)
1644 filename := filepath.Join(bDir, basename)
1645 if stat, err := os.Stat(filename); err == nil && stat.Size() != 0 {
1646 return nil
1647 }
1648
1649 if !*download {
1650 b.Skipf("test data not found; skipping %s without the -download flag", testOrBenchmark(b))
1651 }
1652 // Download the official snappy C++ implementation reference test data
1653 // files for benchmarking.
1654 if err := os.MkdirAll(bDir, 0777); err != nil && !os.IsExist(err) {
1655 return fmt.Errorf("failed to create %s: %s", bDir, err)
1656 }
1657
1658 f, err := os.Create(filename)
1659 if err != nil {
1660 return fmt.Errorf("failed to create %s: %s", filename, err)
1661 }
1662 defer f.Close()
1663 defer func() {
1664 if errRet != nil {
1665 os.Remove(filename)
1666 }
1667 }()
1668 url := benchURL + basename
1669 resp, err := http.Get(url)
1670 if err != nil {
1671 return fmt.Errorf("failed to download %s: %s", url, err)
1672 }
1673 defer resp.Body.Close()
1674 if s := resp.StatusCode; s != http.StatusOK {
1675 return fmt.Errorf("downloading %s: HTTP status code %d (%s)", url, s, http.StatusText(s))
1676 }
1677 _, err = io.Copy(f, resp.Body)
1678 if err != nil {
1679 return fmt.Errorf("failed to download %s to %s: %s", url, filename, err)
1680 }
1681 return nil
1682 }
1683
1684 func TestEstimateBlockSize(t *testing.T) {
1685 var input []byte
1686 for range 100 {
1687 EstimateBlockSize(input)
1688 input = append(input, 0)
1689 }
1690 }
1691
1692 func benchFile(b *testing.B, i int, decode bool) {
1693 if err := downloadBenchmarkFiles(b, testFiles[i].filename); err != nil {
1694 b.Fatalf("failed to download testdata: %s", err)
1695 }
1696 bDir := filepath.FromSlash(*benchdataDir)
1697 data := readFile(b, filepath.Join(bDir, testFiles[i].filename))
1698 if !decode {
1699 b.Run("est-size", func(b *testing.B) {
1700 if n := testFiles[i].sizeLimit; 0 < n && n < len(data) {
1701 data = data[:n]
1702 }
1703 b.SetBytes(int64(len(data)))
1704 b.ReportAllocs()
1705 b.ResetTimer()
1706 b.RunParallel(func(pb *testing.PB) {
1707 for pb.Next() {
1708 _ = EstimateBlockSize(data)
1709 }
1710 })
1711 sz := float64(EstimateBlockSize(data))
1712 if sz > 0 {
1713 b.ReportMetric(100*sz/float64(len(data)), "pct")
1714 b.ReportMetric(sz, "B")
1715 }
1716 })
1717 }
1718 b.Run("block", func(b *testing.B) {
1719 if n := testFiles[i].sizeLimit; 0 < n && n < len(data) {
1720 data = data[:n]
1721 }
1722 if decode {
1723 b.SetBytes(int64(len(data)))
1724 b.ReportAllocs()
1725 b.ResetTimer()
1726 b.RunParallel(func(pb *testing.PB) {
1727 encoded := Encode(nil, data)
1728 tmp := make([]byte, len(data))
1729 for pb.Next() {
1730 var err error
1731 tmp, err = Decode(tmp, encoded)
1732 if err != nil {
1733 b.Fatal(err)
1734 }
1735 }
1736 })
1737 } else {
1738 b.SetBytes(int64(len(data)))
1739 b.ReportAllocs()
1740 b.ResetTimer()
1741 b.RunParallel(func(pb *testing.PB) {
1742 dst := make([]byte, MaxEncodedLen(len(data)))
1743 tmp := make([]byte, len(data))
1744 for pb.Next() {
1745 res := Encode(dst, data)
1746 if len(res) == 0 {
1747 panic(0)
1748 }
1749 if false {
1750 tmp, _ = Decode(tmp, res)
1751 if !bytes.Equal(tmp, data) {
1752 panic("wrong")
1753 }
1754 }
1755 }
1756 })
1757 }
1758 b.ReportMetric(100*float64(len(Encode(nil, data)))/float64(len(data)), "pct")
1759 b.ReportMetric(float64(len(Encode(nil, data))), "B")
1760 })
1761 b.Run("block-better", func(b *testing.B) {
1762 if decode {
1763 b.SetBytes(int64(len(data)))
1764 b.ReportAllocs()
1765 b.ResetTimer()
1766 b.RunParallel(func(pb *testing.PB) {
1767 encoded := EncodeBetter(nil, data)
1768 tmp := make([]byte, len(data))
1769 for pb.Next() {
1770 var err error
1771 tmp, err = Decode(tmp, encoded)
1772 if err != nil {
1773 b.Fatal(err)
1774 }
1775 }
1776 })
1777 } else {
1778 b.SetBytes(int64(len(data)))
1779 b.ReportAllocs()
1780 b.ResetTimer()
1781 b.RunParallel(func(pb *testing.PB) {
1782 dst := make([]byte, MaxEncodedLen(len(data)))
1783 tmp := make([]byte, len(data))
1784 for pb.Next() {
1785 res := EncodeBetter(dst, data)
1786 if len(res) == 0 {
1787 panic(0)
1788 }
1789 if false {
1790 tmp, _ = Decode(tmp, res)
1791 if !bytes.Equal(tmp, data) {
1792 panic("wrong")
1793 }
1794 }
1795 }
1796 })
1797 }
1798 b.ReportMetric(100*float64(len(EncodeBetter(nil, data)))/float64(len(data)), "pct")
1799 b.ReportMetric(float64(len(EncodeBetter(nil, data))), "B")
1800 })
1801
1802 b.Run("block-best", func(b *testing.B) {
1803 if decode {
1804 b.SetBytes(int64(len(data)))
1805 b.ReportAllocs()
1806 b.ResetTimer()
1807 b.RunParallel(func(pb *testing.PB) {
1808 encoded := EncodeBest(nil, data)
1809 tmp := make([]byte, len(data))
1810 for pb.Next() {
1811 var err error
1812 tmp, err = Decode(tmp, encoded)
1813 if err != nil {
1814 b.Fatal(err)
1815 }
1816 }
1817 })
1818 b.ReportMetric(100*float64(len(EncodeBest(nil, data)))/float64(len(data)), "pct")
1819 } else {
1820 b.SetBytes(int64(len(data)))
1821 b.ReportAllocs()
1822 b.ResetTimer()
1823 b.RunParallel(func(pb *testing.PB) {
1824 dst := make([]byte, MaxEncodedLen(len(data)))
1825 tmp := make([]byte, len(data))
1826 for pb.Next() {
1827 res := EncodeBest(dst, data)
1828 if len(res) == 0 {
1829 panic(0)
1830 }
1831 if false {
1832 tmp, _ = Decode(tmp, res)
1833 if !bytes.Equal(tmp, data) {
1834 panic("wrong")
1835 }
1836 }
1837 }
1838 })
1839 b.ReportMetric(100*float64(len(EncodeBest(nil, data)))/float64(len(data)), "pct")
1840 }
1841 b.ReportMetric(float64(len(EncodeBest(nil, data))), "B")
1842 })
1843 }
1844
1845 func benchFileSnappy(b *testing.B, i int, decode bool) {
1846 if err := downloadBenchmarkFiles(b, testFiles[i].filename); err != nil {
1847 b.Fatalf("failed to download testdata: %s", err)
1848 }
1849 bDir := filepath.FromSlash(*benchdataDir)
1850 data := readFile(b, filepath.Join(bDir, testFiles[i].filename))
1851 if n := testFiles[i].sizeLimit; 0 < n && n < len(data) {
1852 data = data[:n]
1853 }
1854
1855 b.Run("s2-snappy", func(b *testing.B) {
1856 if decode {
1857 b.SetBytes(int64(len(data)))
1858 b.ResetTimer()
1859 b.ReportAllocs()
1860 b.RunParallel(func(pb *testing.PB) {
1861 encoded := EncodeSnappy(nil, data)
1862 tmp := make([]byte, len(data))
1863 for pb.Next() {
1864 var err error
1865 tmp, err = Decode(tmp, encoded)
1866 if err != nil {
1867 b.Fatal(err)
1868 }
1869 }
1870 })
1871 b.ReportMetric(100*float64(len(EncodeSnappy(nil, data)))/float64(len(data)), "pct")
1872 } else {
1873 b.SetBytes(int64(len(data)))
1874 b.ReportAllocs()
1875 b.ResetTimer()
1876
1877 b.RunParallel(func(pb *testing.PB) {
1878 dst := make([]byte, MaxEncodedLen(len(data)))
1879 for pb.Next() {
1880 res := EncodeSnappy(dst, data)
1881 if len(res) == 0 {
1882 panic(0)
1883 }
1884 }
1885 })
1886 b.ReportMetric(100*float64(len(EncodeSnappy(nil, data)))/float64(len(data)), "pct")
1887 }
1888 b.ReportMetric(float64(len(EncodeSnappy(nil, data))), "B")
1889 })
1890
1891 b.Run("s2-snappy-better", func(b *testing.B) {
1892 if decode {
1893 b.SetBytes(int64(len(data)))
1894 b.ResetTimer()
1895 b.RunParallel(func(pb *testing.PB) {
1896 encoded := EncodeSnappyBetter(nil, data)
1897 tmp := make([]byte, len(data))
1898 b.ReportAllocs()
1899 b.ResetTimer()
1900
1901 for pb.Next() {
1902 var err error
1903 tmp, err = Decode(tmp, encoded)
1904 if err != nil {
1905 b.Fatal(err)
1906 }
1907 }
1908 })
1909 b.ReportMetric(100*float64(len(EncodeSnappyBetter(nil, data)))/float64(len(data)), "pct")
1910 } else {
1911 b.SetBytes(int64(len(data)))
1912 b.ReportAllocs()
1913 b.ResetTimer()
1914 b.RunParallel(func(pb *testing.PB) {
1915 dst := make([]byte, MaxEncodedLen(len(data)))
1916 tmp := make([]byte, len(data))
1917 for pb.Next() {
1918 res := EncodeSnappyBetter(dst, data)
1919 if len(res) == 0 {
1920 panic(0)
1921 }
1922 if false {
1923 tmp, _ = Decode(tmp, res)
1924 if !bytes.Equal(tmp, data) {
1925 panic("wrong")
1926 }
1927 }
1928 }
1929 })
1930 b.ReportMetric(100*float64(len(EncodeSnappyBetter(nil, data)))/float64(len(data)), "pct")
1931 }
1932 b.ReportMetric(float64(len(EncodeSnappyBetter(nil, data))), "B")
1933 })
1934
1935 b.Run("s2-snappy-best", func(b *testing.B) {
1936 if decode {
1937 b.SetBytes(int64(len(data)))
1938 b.ReportAllocs()
1939 b.ResetTimer()
1940 b.RunParallel(func(pb *testing.PB) {
1941 encoded := EncodeSnappyBest(nil, data)
1942 tmp := make([]byte, len(data))
1943 for pb.Next() {
1944 var err error
1945 tmp, err = Decode(tmp, encoded)
1946 if err != nil {
1947 b.Fatal(err)
1948 }
1949 }
1950 })
1951 b.ReportMetric(100*float64(len(EncodeSnappyBest(nil, data)))/float64(len(data)), "pct")
1952 } else {
1953 b.SetBytes(int64(len(data)))
1954 b.ReportAllocs()
1955 b.ResetTimer()
1956 b.RunParallel(func(pb *testing.PB) {
1957 dst := make([]byte, MaxEncodedLen(len(data)))
1958 tmp := make([]byte, len(data))
1959 for pb.Next() {
1960 res := EncodeSnappyBest(dst, data)
1961 if len(res) == 0 {
1962 panic(0)
1963 }
1964 if false {
1965 tmp, _ = snapref.Decode(tmp, res)
1966 if !bytes.Equal(tmp, data) {
1967 panic("wrong")
1968 }
1969 }
1970 }
1971 })
1972 b.ReportMetric(100*float64(len(EncodeSnappyBest(nil, data)))/float64(len(data)), "pct")
1973 }
1974 b.ReportMetric(float64(len(EncodeSnappyBest(nil, data))), "B")
1975 })
1976 b.Run("snappy-noasm", func(b *testing.B) {
1977 if decode {
1978 b.SetBytes(int64(len(data)))
1979 b.ReportAllocs()
1980 b.ResetTimer()
1981 b.RunParallel(func(pb *testing.PB) {
1982 encoded := snapref.Encode(nil, data)
1983 tmp := make([]byte, len(data))
1984 for pb.Next() {
1985 var err error
1986 tmp, err = snapref.Decode(tmp, encoded)
1987 if err != nil {
1988 b.Fatal(err)
1989 }
1990 }
1991 })
1992 b.ReportMetric(100*float64(len(snapref.Encode(nil, data)))/float64(len(data)), "pct")
1993 } else {
1994 b.SetBytes(int64(len(data)))
1995 b.ReportAllocs()
1996 b.ResetTimer()
1997 b.RunParallel(func(pb *testing.PB) {
1998 dst := make([]byte, snapref.MaxEncodedLen(len(data)))
1999 tmp := make([]byte, len(data))
2000 for pb.Next() {
2001 res := snapref.Encode(dst, data)
2002 if len(res) == 0 {
2003 panic(0)
2004 }
2005 if false {
2006 tmp, _ = snapref.Decode(tmp, res)
2007 if !bytes.Equal(tmp, data) {
2008 panic("wrong")
2009 }
2010 }
2011 }
2012 })
2013 b.ReportMetric(100*float64(len(snapref.Encode(nil, data)))/float64(len(data)), "pct")
2014 }
2015 })
2016 }
2017
2018 func TestRoundtrips(t *testing.T) {
2019 testFile(t, 0, 10)
2020 testFile(t, 1, 10)
2021 testFile(t, 2, 10)
2022 testFile(t, 3, 10)
2023 testFile(t, 4, 10)
2024 testFile(t, 5, 10)
2025 testFile(t, 6, 10)
2026 testFile(t, 7, 10)
2027 testFile(t, 8, 10)
2028 testFile(t, 9, 10)
2029 testFile(t, 10, 10)
2030 testFile(t, 11, 10)
2031 testFile(t, 12, 0)
2032 testFile(t, 13, 0)
2033 testFile(t, 14, 0)
2034 testFile(t, 15, 0)
2035 }
2036
2037 func testFile(t *testing.T, i, repeat int) {
2038 if err := downloadBenchmarkFiles(t, testFiles[i].filename); err != nil {
2039 t.Skipf("failed to download testdata: %s", err)
2040 }
2041
2042 if testing.Short() {
2043 repeat = 0
2044 }
2045 t.Run(fmt.Sprint(i, "-", testFiles[i].label), func(t *testing.T) {
2046 bDir := filepath.FromSlash(*benchdataDir)
2047 data := readFile(t, filepath.Join(bDir, testFiles[i].filename))
2048 if testing.Short() && len(data) > 10000 {
2049 t.SkipNow()
2050 }
2051 oSize := len(data)
2052 for i := 0; i < repeat; i++ {
2053 data = append(data, data[:oSize]...)
2054 }
2055 t.Run("s2", func(t *testing.T) {
2056 testWriterRoundtrip(t, data)
2057 })
2058 t.Run("s2-better", func(t *testing.T) {
2059 testWriterRoundtrip(t, data, WriterBetterCompression())
2060 })
2061 t.Run("s2-best", func(t *testing.T) {
2062 testWriterRoundtrip(t, data, WriterBestCompression())
2063 })
2064 t.Run("s2-uncompressed", func(t *testing.T) {
2065 testWriterRoundtrip(t, data, WriterUncompressed())
2066 })
2067 t.Run("block", func(t *testing.T) {
2068 d := data
2069 testBlockRoundtrip(t, d)
2070 })
2071 t.Run("block-better", func(t *testing.T) {
2072 d := data
2073 testBetterBlockRoundtrip(t, d)
2074 })
2075 t.Run("block-best", func(t *testing.T) {
2076 d := data
2077 testBestBlockRoundtrip(t, d)
2078 })
2079 t.Run("s2-snappy", func(t *testing.T) {
2080 d := data
2081 testSnappyBlockRoundtrip(t, d)
2082 })
2083 t.Run("snappy", func(t *testing.T) {
2084 testSnappyDecode(t, data)
2085 })
2086 })
2087 }
2088
2089 func TestDataRoundtrips(t *testing.T) {
2090 test := func(t *testing.T, data []byte) {
2091 t.Run("s2", func(t *testing.T) {
2092 testWriterRoundtrip(t, data)
2093 })
2094 t.Run("s2-better", func(t *testing.T) {
2095 testWriterRoundtrip(t, data, WriterBetterCompression())
2096 })
2097 t.Run("s2-best", func(t *testing.T) {
2098 testWriterRoundtrip(t, data, WriterBestCompression())
2099 })
2100 t.Run("block", func(t *testing.T) {
2101 d := data
2102 testBlockRoundtrip(t, d)
2103 })
2104 t.Run("block-better", func(t *testing.T) {
2105 d := data
2106 testBetterBlockRoundtrip(t, d)
2107 })
2108 t.Run("block-best", func(t *testing.T) {
2109 d := data
2110 testBestBlockRoundtrip(t, d)
2111 })
2112 t.Run("s2-snappy", func(t *testing.T) {
2113 d := data
2114 testSnappyBlockRoundtrip(t, d)
2115 })
2116 t.Run("snappy", func(t *testing.T) {
2117 testSnappyDecode(t, data)
2118 })
2119 }
2120 t.Run("longblock", func(t *testing.T) {
2121 data := make([]byte, 1<<25)
2122 if testing.Short() {
2123 data = data[:1<<20]
2124 }
2125 test(t, data)
2126 })
2127 t.Run("4f9e1a0", func(t *testing.T) {
2128 comp, _ := os.ReadFile("testdata/4f9e1a0da7915a3d69632f5613ed78bc998a8a23.zst")
2129 dec, _ := zstd.NewReader(bytes.NewBuffer(comp))
2130 data, _ := io.ReadAll(dec)
2131 test(t, data)
2132 })
2133 data, err := os.ReadFile("testdata/enc_regressions.zip")
2134 if err != nil {
2135 t.Fatal(err)
2136 }
2137 zr, err := zip.NewReader(bytes.NewReader(data), int64(len(data)))
2138 if err != nil {
2139 t.Fatal(err)
2140 }
2141 for _, tt := range zr.File {
2142 if !strings.HasSuffix(t.Name(), "") {
2143 continue
2144 }
2145 t.Run(tt.Name, func(t *testing.T) {
2146 r, err := tt.Open()
2147 if err != nil {
2148 t.Error(err)
2149 return
2150 }
2151 b, err := io.ReadAll(r)
2152 if err != nil {
2153 t.Error(err)
2154 return
2155 }
2156 test(t, b[:len(b):len(b)])
2157 })
2158 }
2159
2160 }
2161
2162 func BenchmarkDecodeS2BlockParallel(b *testing.B) {
2163 for i := range testFiles {
2164 b.Run(fmt.Sprint(i, "-", testFiles[i].label), func(b *testing.B) {
2165 benchFile(b, i, true)
2166 })
2167 }
2168 }
2169
2170 func BenchmarkEncodeS2BlockParallel(b *testing.B) {
2171 for i := range testFiles {
2172 b.Run(fmt.Sprint(i, "-", testFiles[i].label), func(b *testing.B) {
2173 benchFile(b, i, false)
2174 })
2175 }
2176 }
2177
2178 func BenchmarkDecodeSnappyBlockParallel(b *testing.B) {
2179 for i := range testFiles {
2180 b.Run(fmt.Sprint(i, "-", testFiles[i].label), func(b *testing.B) {
2181 benchFileSnappy(b, i, true)
2182 })
2183 }
2184 }
2185
2186 func BenchmarkEncodeSnappyBlockParallel(b *testing.B) {
2187 for i := range testFiles {
2188 b.Run(fmt.Sprint(i, "-", testFiles[i].label), func(b *testing.B) {
2189 benchFileSnappy(b, i, false)
2190 })
2191 }
2192 }
2193
2194 func TestMatchLen(t *testing.T) {
2195 // ref is a simple, reference implementation of matchLen.
2196 ref := func(a, b []byte) int {
2197 n := 0
2198 for i := range a {
2199 if a[i] != b[i] {
2200 break
2201 }
2202 n++
2203 }
2204 return n
2205 }
2206
2207 // We allow slightly shorter matches at the end of slices
2208 const maxBelow = 0
2209 nums := []int{0, 1, 2, 7, 8, 9, 16, 20, 29, 30, 31, 32, 33, 34, 38, 39, 40}
2210 for yIndex := 40; yIndex > 30; yIndex-- {
2211 xxx := bytes.Repeat([]byte("x"), 40)
2212 if yIndex < len(xxx) {
2213 xxx[yIndex] = 'y'
2214 }
2215 for _, i := range nums {
2216 for _, j := range nums {
2217 if i >= j {
2218 continue
2219 }
2220 got := matchLen(xxx[j:], xxx[i:])
2221 want := ref(xxx[j:], xxx[i:])
2222 if got > want {
2223 t.Errorf("yIndex=%d, i=%d, j=%d: got %d, want %d", yIndex, i, j, got, want)
2224 continue
2225 }
2226 if got < want-maxBelow {
2227 t.Errorf("yIndex=%d, i=%d, j=%d: got %d, want %d", yIndex, i, j, got, want)
2228 }
2229 }
2230 }
2231 }
2232 }
2233
2234 func BenchmarkDecodeBlockSingle(b *testing.B) {
2235 for i := range testFiles {
2236 b.Run(fmt.Sprint(i, "-", testFiles[i].label), func(b *testing.B) {
2237 if err := downloadBenchmarkFiles(b, testFiles[i].filename); err != nil {
2238 b.Fatalf("failed to download testdata: %s", err)
2239 }
2240 bDir := filepath.FromSlash(*benchdataDir)
2241 data := readFile(b, filepath.Join(bDir, testFiles[i].filename))
2242 if testFiles[i].sizeLimit > 0 && len(data) > testFiles[i].sizeLimit {
2243 data = data[:testFiles[i].sizeLimit]
2244 }
2245 benchDecode(b, data)
2246 })
2247 }
2248 }
2249
2250 func BenchmarkDecodeBlockParallel(b *testing.B) {
2251 for i := range testFiles {
2252 b.Run(fmt.Sprint(i, "-", testFiles[i].label), func(b *testing.B) {
2253 benchFile(b, i, true)
2254 })
2255 }
2256 }
2257
2258 func BenchmarkEncodeBlockSingle(b *testing.B) {
2259 for i := range testFiles {
2260 b.Run(fmt.Sprint(i, "-", testFiles[i].label), func(b *testing.B) {
2261 if err := downloadBenchmarkFiles(b, testFiles[i].filename); err != nil {
2262 b.Fatalf("failed to download testdata: %s", err)
2263 }
2264 bDir := filepath.FromSlash(*benchdataDir)
2265 data := readFile(b, filepath.Join(bDir, testFiles[i].filename))
2266 if testFiles[i].sizeLimit > 0 && len(data) > testFiles[i].sizeLimit {
2267 data = data[:testFiles[i].sizeLimit]
2268 }
2269 benchEncode(b, data)
2270 })
2271 }
2272 }
2273
2274 func BenchmarkEncodeBlockParallel(b *testing.B) {
2275 for i := range testFiles {
2276 b.Run(fmt.Sprint(i, "-", testFiles[i].label), func(b *testing.B) {
2277 benchFile(b, i, false)
2278 })
2279 }
2280 }