snappy_test.go 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704
  1. // Copyright 2011 The Snappy-Go Authors. All rights reserved.
  2. // Use of this source code is governed by a BSD-style
  3. // license that can be found in the LICENSE file.
  4. package snappy
  5. import (
  6. "bytes"
  7. "flag"
  8. "fmt"
  9. "io"
  10. "io/ioutil"
  11. "math/rand"
  12. "net/http"
  13. "os"
  14. "path/filepath"
  15. "strings"
  16. "testing"
  17. )
  18. var (
  19. download = flag.Bool("download", false, "If true, download any missing files before running benchmarks")
  20. testdata = flag.String("testdata", "testdata", "Directory containing the test data")
  21. )
  22. func TestMaxEncodedLenOfMaxUncompressedChunkLen(t *testing.T) {
  23. got := maxEncodedLenOfMaxUncompressedChunkLen
  24. want := MaxEncodedLen(maxUncompressedChunkLen)
  25. if got != want {
  26. t.Fatalf("got %d, want %d", got, want)
  27. }
  28. }
  29. func roundtrip(b, ebuf, dbuf []byte) error {
  30. d, err := Decode(dbuf, Encode(ebuf, b))
  31. if err != nil {
  32. return fmt.Errorf("decoding error: %v", err)
  33. }
  34. if !bytes.Equal(b, d) {
  35. return fmt.Errorf("roundtrip mismatch:\n\twant %v\n\tgot %v", b, d)
  36. }
  37. return nil
  38. }
  39. func TestEmpty(t *testing.T) {
  40. if err := roundtrip(nil, nil, nil); err != nil {
  41. t.Fatal(err)
  42. }
  43. }
  44. func TestSmallCopy(t *testing.T) {
  45. for _, ebuf := range [][]byte{nil, make([]byte, 20), make([]byte, 64)} {
  46. for _, dbuf := range [][]byte{nil, make([]byte, 20), make([]byte, 64)} {
  47. for i := 0; i < 32; i++ {
  48. s := "aaaa" + strings.Repeat("b", i) + "aaaabbbb"
  49. if err := roundtrip([]byte(s), ebuf, dbuf); err != nil {
  50. t.Errorf("len(ebuf)=%d, len(dbuf)=%d, i=%d: %v", len(ebuf), len(dbuf), i, err)
  51. }
  52. }
  53. }
  54. }
  55. }
  56. func TestSmallRand(t *testing.T) {
  57. rng := rand.New(rand.NewSource(1))
  58. for n := 1; n < 20000; n += 23 {
  59. b := make([]byte, n)
  60. for i := range b {
  61. b[i] = uint8(rng.Uint32())
  62. }
  63. if err := roundtrip(b, nil, nil); err != nil {
  64. t.Fatal(err)
  65. }
  66. }
  67. }
  68. func TestSmallRegular(t *testing.T) {
  69. for n := 1; n < 20000; n += 23 {
  70. b := make([]byte, n)
  71. for i := range b {
  72. b[i] = uint8(i%10 + 'a')
  73. }
  74. if err := roundtrip(b, nil, nil); err != nil {
  75. t.Fatal(err)
  76. }
  77. }
  78. }
  79. func TestInvalidVarint(t *testing.T) {
  80. data := []byte("\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\x00")
  81. if _, err := DecodedLen(data); err != ErrCorrupt {
  82. t.Errorf("DecodedLen: got %v, want ErrCorrupt", err)
  83. }
  84. if _, err := Decode(nil, data); err != ErrCorrupt {
  85. t.Errorf("Decode: got %v, want ErrCorrupt", err)
  86. }
  87. // The encoded varint overflows 32 bits
  88. data = []byte("\xff\xff\xff\xff\xff\x00")
  89. if _, err := DecodedLen(data); err != ErrCorrupt {
  90. t.Errorf("DecodedLen: got %v, want ErrCorrupt", err)
  91. }
  92. if _, err := Decode(nil, data); err != ErrCorrupt {
  93. t.Errorf("Decode: got %v, want ErrCorrupt", err)
  94. }
  95. }
  96. func TestDecode(t *testing.T) {
  97. testCases := []struct {
  98. desc string
  99. input string
  100. want string
  101. wantErr error
  102. }{{
  103. `decodedLen=0x100000000 is too long`,
  104. "\x80\x80\x80\x80\x10" + "\x00\x41",
  105. "",
  106. ErrCorrupt,
  107. }, {
  108. `decodedLen=3; tagLiteral, 0-byte length; length=3; valid input`,
  109. "\x03" + "\x08\xff\xff\xff",
  110. "\xff\xff\xff",
  111. nil,
  112. }, {
  113. `decodedLen=1; tagLiteral, 1-byte length; not enough length bytes`,
  114. "\x01" + "\xf0",
  115. "",
  116. ErrCorrupt,
  117. }, {
  118. `decodedLen=3; tagLiteral, 1-byte length; length=3; valid input`,
  119. "\x03" + "\xf0\x02\xff\xff\xff",
  120. "\xff\xff\xff",
  121. nil,
  122. }, {
  123. `decodedLen=1; tagLiteral, 2-byte length; not enough length bytes`,
  124. "\x01" + "\xf4\x00",
  125. "",
  126. ErrCorrupt,
  127. }, {
  128. `decodedLen=3; tagLiteral, 2-byte length; length=3; valid input`,
  129. "\x03" + "\xf4\x02\x00\xff\xff\xff",
  130. "\xff\xff\xff",
  131. nil,
  132. }, {
  133. `decodedLen=1; tagLiteral, 3-byte length; not enough length bytes`,
  134. "\x01" + "\xf8\x00\x00",
  135. "",
  136. ErrCorrupt,
  137. }, {
  138. `decodedLen=3; tagLiteral, 3-byte length; length=3; valid input`,
  139. "\x03" + "\xf8\x02\x00\x00\xff\xff\xff",
  140. "\xff\xff\xff",
  141. nil,
  142. }, {
  143. `decodedLen=1; tagLiteral, 4-byte length; not enough length bytes`,
  144. "\x01" + "\xfc\x00\x00\x00",
  145. "",
  146. ErrCorrupt,
  147. }, {
  148. `decodedLen=1; tagLiteral, 4-byte length; length=3; not enough dst bytes`,
  149. "\x01" + "\xfc\x02\x00\x00\x00\xff\xff\xff",
  150. "",
  151. ErrCorrupt,
  152. }, {
  153. `decodedLen=4; tagLiteral, 4-byte length; length=3; not enough src bytes`,
  154. "\x04" + "\xfc\x02\x00\x00\x00\xff",
  155. "",
  156. ErrCorrupt,
  157. }, {
  158. `decodedLen=3; tagLiteral, 4-byte length; length=3; valid input`,
  159. "\x03" + "\xfc\x02\x00\x00\x00\xff\xff\xff",
  160. "\xff\xff\xff",
  161. nil,
  162. }, {
  163. `decodedLen=4; tagCopy1, 1 extra length|offset byte; not enough extra bytes`,
  164. "\x04" + "\x01",
  165. "",
  166. ErrCorrupt,
  167. }, {
  168. `decodedLen=4; tagCopy2, 2 extra length|offset bytes; not enough extra bytes`,
  169. "\x04" + "\x02\x00",
  170. "",
  171. ErrCorrupt,
  172. }, {
  173. `decodedLen=4; tagCopy4; unsupported COPY_4 tag`,
  174. "\x04" + "\x03\x00\x00\x00\x00",
  175. "",
  176. errUnsupportedCopy4Tag,
  177. }, {
  178. `decodedLen=4; tagLiteral (4 bytes "abcd"); valid input`,
  179. "\x04" + "\x0cabcd",
  180. "abcd",
  181. nil,
  182. }, {
  183. `decodedLen=8; tagLiteral (4 bytes "abcd"); tagCopy1; length=4 offset=4; valid input`,
  184. "\x08" + "\x0cabcd" + "\x01\x04",
  185. "abcdabcd",
  186. nil,
  187. }, {
  188. `decodedLen=8; tagLiteral (4 bytes "abcd"); tagCopy1; length=4 offset=2; valid input`,
  189. "\x08" + "\x0cabcd" + "\x01\x02",
  190. "abcdcdcd",
  191. nil,
  192. }, {
  193. `decodedLen=8; tagLiteral (4 bytes "abcd"); tagCopy1; length=4 offset=1; valid input`,
  194. "\x08" + "\x0cabcd" + "\x01\x01",
  195. "abcddddd",
  196. nil,
  197. }, {
  198. `decodedLen=8; tagLiteral (4 bytes "abcd"); tagCopy1; length=4 offset=0; zero offset`,
  199. "\x08" + "\x0cabcd" + "\x01\x00",
  200. "",
  201. ErrCorrupt,
  202. }, {
  203. `decodedLen=9; tagLiteral (4 bytes "abcd"); tagCopy1; length=4 offset=4; inconsistent dLen`,
  204. "\x09" + "\x0cabcd" + "\x01\x04",
  205. "",
  206. ErrCorrupt,
  207. }, {
  208. `decodedLen=8; tagLiteral (4 bytes "abcd"); tagCopy1; length=4 offset=5; offset too large`,
  209. "\x08" + "\x0cabcd" + "\x01\x05",
  210. "",
  211. ErrCorrupt,
  212. }, {
  213. `decodedLen=7; tagLiteral (4 bytes "abcd"); tagCopy1; length=4 offset=4; length too large`,
  214. "\x07" + "\x0cabcd" + "\x01\x04",
  215. "",
  216. ErrCorrupt,
  217. }}
  218. for _, tc := range testCases {
  219. g, gotErr := Decode(nil, []byte(tc.input))
  220. if got := string(g); got != tc.want || gotErr != tc.wantErr {
  221. t.Errorf("%s:\ngot %q, %v\nwant %q, %v", tc.desc, got, gotErr, tc.want, tc.wantErr)
  222. }
  223. }
  224. }
  225. func cmp(a, b []byte) error {
  226. if len(a) != len(b) {
  227. return fmt.Errorf("got %d bytes, want %d", len(a), len(b))
  228. }
  229. for i := range a {
  230. if a[i] != b[i] {
  231. return fmt.Errorf("byte #%d: got 0x%02x, want 0x%02x", i, a[i], b[i])
  232. }
  233. }
  234. return nil
  235. }
  236. func TestFramingFormat(t *testing.T) {
  237. // src is comprised of alternating 1e5-sized sequences of random
  238. // (incompressible) bytes and repeated (compressible) bytes. 1e5 was chosen
  239. // because it is larger than maxUncompressedChunkLen (64k).
  240. src := make([]byte, 1e6)
  241. rng := rand.New(rand.NewSource(1))
  242. for i := 0; i < 10; i++ {
  243. if i%2 == 0 {
  244. for j := 0; j < 1e5; j++ {
  245. src[1e5*i+j] = uint8(rng.Intn(256))
  246. }
  247. } else {
  248. for j := 0; j < 1e5; j++ {
  249. src[1e5*i+j] = uint8(i)
  250. }
  251. }
  252. }
  253. buf := new(bytes.Buffer)
  254. if _, err := NewWriter(buf).Write(src); err != nil {
  255. t.Fatalf("Write: encoding: %v", err)
  256. }
  257. dst, err := ioutil.ReadAll(NewReader(buf))
  258. if err != nil {
  259. t.Fatalf("ReadAll: decoding: %v", err)
  260. }
  261. if err := cmp(dst, src); err != nil {
  262. t.Fatal(err)
  263. }
  264. }
  265. func TestWriterGoldenOutput(t *testing.T) {
  266. buf := new(bytes.Buffer)
  267. w := NewBufferedWriter(buf)
  268. defer w.Close()
  269. w.Write([]byte("abcd")) // Not compressible.
  270. w.Flush()
  271. w.Write(bytes.Repeat([]byte{'A'}, 100)) // Compressible.
  272. w.Flush()
  273. got := buf.String()
  274. want := strings.Join([]string{
  275. magicChunk,
  276. "\x01\x08\x00\x00", // Uncompressed chunk, 8 bytes long (including 4 byte checksum).
  277. "\x68\x10\xe6\xb6", // Checksum.
  278. "\x61\x62\x63\x64", // Uncompressed payload: "abcd".
  279. "\x00\x0d\x00\x00", // Compressed chunk, 13 bytes long (including 4 byte checksum).
  280. "\x37\xcb\xbc\x9d", // Checksum.
  281. "\x64", // Compressed payload: Uncompressed length (varint encoded): 100.
  282. "\x00\x41", // Compressed payload: tagLiteral, length=1, "A".
  283. "\xfe\x01\x00", // Compressed payload: tagCopy2, length=64, offset=1.
  284. "\x8a\x01\x00", // Compressed payload: tagCopy2, length=35, offset=1.
  285. }, "")
  286. if got != want {
  287. t.Fatalf("\ngot: % x\nwant: % x", got, want)
  288. }
  289. }
  290. func TestNewBufferedWriter(t *testing.T) {
  291. // Test all 32 possible sub-sequences of these 5 input slices.
  292. //
  293. // Their lengths sum to 400,000, which is over 6 times the Writer ibuf
  294. // capacity: 6 * maxUncompressedChunkLen is 393,216.
  295. inputs := [][]byte{
  296. bytes.Repeat([]byte{'a'}, 40000),
  297. bytes.Repeat([]byte{'b'}, 150000),
  298. bytes.Repeat([]byte{'c'}, 60000),
  299. bytes.Repeat([]byte{'d'}, 120000),
  300. bytes.Repeat([]byte{'e'}, 30000),
  301. }
  302. loop:
  303. for i := 0; i < 1<<uint(len(inputs)); i++ {
  304. var want []byte
  305. buf := new(bytes.Buffer)
  306. w := NewBufferedWriter(buf)
  307. for j, input := range inputs {
  308. if i&(1<<uint(j)) == 0 {
  309. continue
  310. }
  311. if _, err := w.Write(input); err != nil {
  312. t.Errorf("i=%#02x: j=%d: Write: %v", i, j, err)
  313. continue loop
  314. }
  315. want = append(want, input...)
  316. }
  317. if err := w.Close(); err != nil {
  318. t.Errorf("i=%#02x: Close: %v", i, err)
  319. continue
  320. }
  321. got, err := ioutil.ReadAll(NewReader(buf))
  322. if err != nil {
  323. t.Errorf("i=%#02x: ReadAll: %v", i, err)
  324. continue
  325. }
  326. if err := cmp(got, want); err != nil {
  327. t.Errorf("i=%#02x: %v", i, err)
  328. continue
  329. }
  330. }
  331. }
  332. func TestFlush(t *testing.T) {
  333. buf := new(bytes.Buffer)
  334. w := NewBufferedWriter(buf)
  335. defer w.Close()
  336. if _, err := w.Write(bytes.Repeat([]byte{'x'}, 20)); err != nil {
  337. t.Fatalf("Write: %v", err)
  338. }
  339. if n := buf.Len(); n != 0 {
  340. t.Fatalf("before Flush: %d bytes were written to the underlying io.Writer, want 0", n)
  341. }
  342. if err := w.Flush(); err != nil {
  343. t.Fatalf("Flush: %v", err)
  344. }
  345. if n := buf.Len(); n == 0 {
  346. t.Fatalf("after Flush: %d bytes were written to the underlying io.Writer, want non-0", n)
  347. }
  348. }
  349. func TestReaderReset(t *testing.T) {
  350. gold := bytes.Repeat([]byte("All that is gold does not glitter,\n"), 10000)
  351. buf := new(bytes.Buffer)
  352. if _, err := NewWriter(buf).Write(gold); err != nil {
  353. t.Fatalf("Write: %v", err)
  354. }
  355. encoded, invalid, partial := buf.String(), "invalid", "partial"
  356. r := NewReader(nil)
  357. for i, s := range []string{encoded, invalid, partial, encoded, partial, invalid, encoded, encoded} {
  358. if s == partial {
  359. r.Reset(strings.NewReader(encoded))
  360. if _, err := r.Read(make([]byte, 101)); err != nil {
  361. t.Errorf("#%d: %v", i, err)
  362. continue
  363. }
  364. continue
  365. }
  366. r.Reset(strings.NewReader(s))
  367. got, err := ioutil.ReadAll(r)
  368. switch s {
  369. case encoded:
  370. if err != nil {
  371. t.Errorf("#%d: %v", i, err)
  372. continue
  373. }
  374. if err := cmp(got, gold); err != nil {
  375. t.Errorf("#%d: %v", i, err)
  376. continue
  377. }
  378. case invalid:
  379. if err == nil {
  380. t.Errorf("#%d: got nil error, want non-nil", i)
  381. continue
  382. }
  383. }
  384. }
  385. }
  386. func TestWriterReset(t *testing.T) {
  387. gold := bytes.Repeat([]byte("Not all those who wander are lost;\n"), 10000)
  388. const n = 20
  389. for _, buffered := range []bool{false, true} {
  390. var w *Writer
  391. if buffered {
  392. w = NewBufferedWriter(nil)
  393. defer w.Close()
  394. } else {
  395. w = NewWriter(nil)
  396. }
  397. var gots, wants [][]byte
  398. failed := false
  399. for i := 0; i <= n; i++ {
  400. buf := new(bytes.Buffer)
  401. w.Reset(buf)
  402. want := gold[:len(gold)*i/n]
  403. if _, err := w.Write(want); err != nil {
  404. t.Errorf("#%d: Write: %v", i, err)
  405. failed = true
  406. continue
  407. }
  408. if buffered {
  409. if err := w.Flush(); err != nil {
  410. t.Errorf("#%d: Flush: %v", i, err)
  411. failed = true
  412. continue
  413. }
  414. }
  415. got, err := ioutil.ReadAll(NewReader(buf))
  416. if err != nil {
  417. t.Errorf("#%d: ReadAll: %v", i, err)
  418. failed = true
  419. continue
  420. }
  421. gots = append(gots, got)
  422. wants = append(wants, want)
  423. }
  424. if failed {
  425. continue
  426. }
  427. for i := range gots {
  428. if err := cmp(gots[i], wants[i]); err != nil {
  429. t.Errorf("#%d: %v", i, err)
  430. }
  431. }
  432. }
  433. }
  434. func TestWriterResetWithoutFlush(t *testing.T) {
  435. buf0 := new(bytes.Buffer)
  436. buf1 := new(bytes.Buffer)
  437. w := NewBufferedWriter(buf0)
  438. if _, err := w.Write([]byte("xxx")); err != nil {
  439. t.Fatalf("Write #0: %v", err)
  440. }
  441. // Note that we don't Flush the Writer before calling Reset.
  442. w.Reset(buf1)
  443. if _, err := w.Write([]byte("yyy")); err != nil {
  444. t.Fatalf("Write #1: %v", err)
  445. }
  446. if err := w.Flush(); err != nil {
  447. t.Fatalf("Flush: %v", err)
  448. }
  449. got, err := ioutil.ReadAll(NewReader(buf1))
  450. if err != nil {
  451. t.Fatalf("ReadAll: %v", err)
  452. }
  453. if err := cmp(got, []byte("yyy")); err != nil {
  454. t.Fatal(err)
  455. }
  456. }
  457. type writeCounter int
  458. func (c *writeCounter) Write(p []byte) (int, error) {
  459. *c++
  460. return len(p), nil
  461. }
  462. // TestNumUnderlyingWrites tests that each Writer flush only makes one or two
  463. // Write calls on its underlying io.Writer, depending on whether or not the
  464. // flushed buffer was compressible.
  465. func TestNumUnderlyingWrites(t *testing.T) {
  466. testCases := []struct {
  467. input []byte
  468. want int
  469. }{
  470. {bytes.Repeat([]byte{'x'}, 100), 1},
  471. {bytes.Repeat([]byte{'y'}, 100), 1},
  472. {[]byte("ABCDEFGHIJKLMNOPQRST"), 2},
  473. }
  474. var c writeCounter
  475. w := NewBufferedWriter(&c)
  476. defer w.Close()
  477. for i, tc := range testCases {
  478. c = 0
  479. if _, err := w.Write(tc.input); err != nil {
  480. t.Errorf("#%d: Write: %v", i, err)
  481. continue
  482. }
  483. if err := w.Flush(); err != nil {
  484. t.Errorf("#%d: Flush: %v", i, err)
  485. continue
  486. }
  487. if int(c) != tc.want {
  488. t.Errorf("#%d: got %d underlying writes, want %d", i, c, tc.want)
  489. continue
  490. }
  491. }
  492. }
  493. func benchDecode(b *testing.B, src []byte) {
  494. encoded := Encode(nil, src)
  495. // Bandwidth is in amount of uncompressed data.
  496. b.SetBytes(int64(len(src)))
  497. b.ResetTimer()
  498. for i := 0; i < b.N; i++ {
  499. Decode(src, encoded)
  500. }
  501. }
  502. func benchEncode(b *testing.B, src []byte) {
  503. // Bandwidth is in amount of uncompressed data.
  504. b.SetBytes(int64(len(src)))
  505. dst := make([]byte, MaxEncodedLen(len(src)))
  506. b.ResetTimer()
  507. for i := 0; i < b.N; i++ {
  508. Encode(dst, src)
  509. }
  510. }
  511. func readFile(b testing.TB, filename string) []byte {
  512. src, err := ioutil.ReadFile(filename)
  513. if err != nil {
  514. b.Skipf("skipping benchmark: %v", err)
  515. }
  516. if len(src) == 0 {
  517. b.Fatalf("%s has zero length", filename)
  518. }
  519. return src
  520. }
  521. // expand returns a slice of length n containing repeated copies of src.
  522. func expand(src []byte, n int) []byte {
  523. dst := make([]byte, n)
  524. for x := dst; len(x) > 0; {
  525. i := copy(x, src)
  526. x = x[i:]
  527. }
  528. return dst
  529. }
  530. func benchWords(b *testing.B, n int, decode bool) {
  531. // Note: the file is OS-language dependent so the resulting values are not
  532. // directly comparable for non-US-English OS installations.
  533. data := expand(readFile(b, "/usr/share/dict/words"), n)
  534. if decode {
  535. benchDecode(b, data)
  536. } else {
  537. benchEncode(b, data)
  538. }
  539. }
  540. func BenchmarkWordsDecode1e1(b *testing.B) { benchWords(b, 1e1, true) }
  541. func BenchmarkWordsDecode1e2(b *testing.B) { benchWords(b, 1e2, true) }
  542. func BenchmarkWordsDecode1e3(b *testing.B) { benchWords(b, 1e3, true) }
  543. func BenchmarkWordsDecode1e4(b *testing.B) { benchWords(b, 1e4, true) }
  544. func BenchmarkWordsDecode1e5(b *testing.B) { benchWords(b, 1e5, true) }
  545. func BenchmarkWordsDecode1e6(b *testing.B) { benchWords(b, 1e6, true) }
  546. func BenchmarkWordsEncode1e1(b *testing.B) { benchWords(b, 1e1, false) }
  547. func BenchmarkWordsEncode1e2(b *testing.B) { benchWords(b, 1e2, false) }
  548. func BenchmarkWordsEncode1e3(b *testing.B) { benchWords(b, 1e3, false) }
  549. func BenchmarkWordsEncode1e4(b *testing.B) { benchWords(b, 1e4, false) }
  550. func BenchmarkWordsEncode1e5(b *testing.B) { benchWords(b, 1e5, false) }
  551. func BenchmarkWordsEncode1e6(b *testing.B) { benchWords(b, 1e6, false) }
  552. func BenchmarkRandomEncode(b *testing.B) {
  553. rng := rand.New(rand.NewSource(1))
  554. data := make([]byte, 1<<20)
  555. for i := range data {
  556. data[i] = uint8(rng.Intn(256))
  557. }
  558. benchEncode(b, data)
  559. }
  560. // testFiles' values are copied directly from
  561. // https://raw.githubusercontent.com/google/snappy/master/snappy_unittest.cc
  562. // The label field is unused in snappy-go.
  563. //
  564. // If this list changes (due to the upstream C++ list changing), remember to
  565. // update the .gitignore file in this repository.
  566. var testFiles = []struct {
  567. label string
  568. filename string
  569. sizeLimit int
  570. }{
  571. {"html", "html", 0},
  572. {"urls", "urls.10K", 0},
  573. {"jpg", "fireworks.jpeg", 0},
  574. {"jpg_200", "fireworks.jpeg", 200},
  575. {"pdf", "paper-100k.pdf", 0},
  576. {"html4", "html_x_4", 0},
  577. {"txt1", "alice29.txt", 0},
  578. {"txt2", "asyoulik.txt", 0},
  579. {"txt3", "lcet10.txt", 0},
  580. {"txt4", "plrabn12.txt", 0},
  581. {"pb", "geo.protodata", 0},
  582. {"gaviota", "kppkn.gtb", 0},
  583. }
  584. // The test data files are present at this canonical URL.
  585. const baseURL = "https://raw.githubusercontent.com/google/snappy/master/testdata/"
  586. func downloadTestdata(b *testing.B, basename string) (errRet error) {
  587. filename := filepath.Join(*testdata, basename)
  588. if stat, err := os.Stat(filename); err == nil && stat.Size() != 0 {
  589. return nil
  590. }
  591. if !*download {
  592. b.Skipf("test data not found; skipping benchmark without the -download flag")
  593. }
  594. // Download the official snappy C++ implementation reference test data
  595. // files for benchmarking.
  596. if err := os.Mkdir(*testdata, 0777); err != nil && !os.IsExist(err) {
  597. return fmt.Errorf("failed to create testdata: %s", err)
  598. }
  599. f, err := os.Create(filename)
  600. if err != nil {
  601. return fmt.Errorf("failed to create %s: %s", filename, err)
  602. }
  603. defer f.Close()
  604. defer func() {
  605. if errRet != nil {
  606. os.Remove(filename)
  607. }
  608. }()
  609. url := baseURL + basename
  610. resp, err := http.Get(url)
  611. if err != nil {
  612. return fmt.Errorf("failed to download %s: %s", url, err)
  613. }
  614. defer resp.Body.Close()
  615. if s := resp.StatusCode; s != http.StatusOK {
  616. return fmt.Errorf("downloading %s: HTTP status code %d (%s)", url, s, http.StatusText(s))
  617. }
  618. _, err = io.Copy(f, resp.Body)
  619. if err != nil {
  620. return fmt.Errorf("failed to download %s to %s: %s", url, filename, err)
  621. }
  622. return nil
  623. }
  624. func benchFile(b *testing.B, n int, decode bool) {
  625. if err := downloadTestdata(b, testFiles[n].filename); err != nil {
  626. b.Fatalf("failed to download testdata: %s", err)
  627. }
  628. data := readFile(b, filepath.Join(*testdata, testFiles[n].filename))
  629. if n := testFiles[n].sizeLimit; 0 < n && n < len(data) {
  630. data = data[:n]
  631. }
  632. if decode {
  633. benchDecode(b, data)
  634. } else {
  635. benchEncode(b, data)
  636. }
  637. }
  638. // Naming convention is kept similar to what snappy's C++ implementation uses.
  639. func Benchmark_UFlat0(b *testing.B) { benchFile(b, 0, true) }
  640. func Benchmark_UFlat1(b *testing.B) { benchFile(b, 1, true) }
  641. func Benchmark_UFlat2(b *testing.B) { benchFile(b, 2, true) }
  642. func Benchmark_UFlat3(b *testing.B) { benchFile(b, 3, true) }
  643. func Benchmark_UFlat4(b *testing.B) { benchFile(b, 4, true) }
  644. func Benchmark_UFlat5(b *testing.B) { benchFile(b, 5, true) }
  645. func Benchmark_UFlat6(b *testing.B) { benchFile(b, 6, true) }
  646. func Benchmark_UFlat7(b *testing.B) { benchFile(b, 7, true) }
  647. func Benchmark_UFlat8(b *testing.B) { benchFile(b, 8, true) }
  648. func Benchmark_UFlat9(b *testing.B) { benchFile(b, 9, true) }
  649. func Benchmark_UFlat10(b *testing.B) { benchFile(b, 10, true) }
  650. func Benchmark_UFlat11(b *testing.B) { benchFile(b, 11, true) }
  651. func Benchmark_ZFlat0(b *testing.B) { benchFile(b, 0, false) }
  652. func Benchmark_ZFlat1(b *testing.B) { benchFile(b, 1, false) }
  653. func Benchmark_ZFlat2(b *testing.B) { benchFile(b, 2, false) }
  654. func Benchmark_ZFlat3(b *testing.B) { benchFile(b, 3, false) }
  655. func Benchmark_ZFlat4(b *testing.B) { benchFile(b, 4, false) }
  656. func Benchmark_ZFlat5(b *testing.B) { benchFile(b, 5, false) }
  657. func Benchmark_ZFlat6(b *testing.B) { benchFile(b, 6, false) }
  658. func Benchmark_ZFlat7(b *testing.B) { benchFile(b, 7, false) }
  659. func Benchmark_ZFlat8(b *testing.B) { benchFile(b, 8, false) }
  660. func Benchmark_ZFlat9(b *testing.B) { benchFile(b, 9, false) }
  661. func Benchmark_ZFlat10(b *testing.B) { benchFile(b, 10, false) }
  662. func Benchmark_ZFlat11(b *testing.B) { benchFile(b, 11, false) }