1
0

snappy_test.go 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689
  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=9; tagLiteral (4 bytes "abcd"); tagCopy1; length=4 offset=4; inconsistent dLen`,
  189. "\x09" + "\x0cabcd" + "\x01\x04",
  190. "",
  191. ErrCorrupt,
  192. }, {
  193. `decodedLen=8; tagLiteral (4 bytes "abcd"); tagCopy1; length=4 offset=5; offset too large`,
  194. "\x08" + "\x0cabcd" + "\x01\x05",
  195. "",
  196. ErrCorrupt,
  197. }, {
  198. `decodedLen=7; tagLiteral (4 bytes "abcd"); tagCopy1; length=4 offset=4; length too large`,
  199. "\x07" + "\x0cabcd" + "\x01\x04",
  200. "",
  201. ErrCorrupt,
  202. }}
  203. for _, tc := range testCases {
  204. g, gotErr := Decode(nil, []byte(tc.input))
  205. if got := string(g); got != tc.want || gotErr != tc.wantErr {
  206. t.Errorf("%s:\ngot %q, %v\nwant %q, %v", tc.desc, got, gotErr, tc.want, tc.wantErr)
  207. }
  208. }
  209. }
  210. func cmp(a, b []byte) error {
  211. if len(a) != len(b) {
  212. return fmt.Errorf("got %d bytes, want %d", len(a), len(b))
  213. }
  214. for i := range a {
  215. if a[i] != b[i] {
  216. return fmt.Errorf("byte #%d: got 0x%02x, want 0x%02x", i, a[i], b[i])
  217. }
  218. }
  219. return nil
  220. }
  221. func TestFramingFormat(t *testing.T) {
  222. // src is comprised of alternating 1e5-sized sequences of random
  223. // (incompressible) bytes and repeated (compressible) bytes. 1e5 was chosen
  224. // because it is larger than maxUncompressedChunkLen (64k).
  225. src := make([]byte, 1e6)
  226. rng := rand.New(rand.NewSource(1))
  227. for i := 0; i < 10; i++ {
  228. if i%2 == 0 {
  229. for j := 0; j < 1e5; j++ {
  230. src[1e5*i+j] = uint8(rng.Intn(256))
  231. }
  232. } else {
  233. for j := 0; j < 1e5; j++ {
  234. src[1e5*i+j] = uint8(i)
  235. }
  236. }
  237. }
  238. buf := new(bytes.Buffer)
  239. if _, err := NewWriter(buf).Write(src); err != nil {
  240. t.Fatalf("Write: encoding: %v", err)
  241. }
  242. dst, err := ioutil.ReadAll(NewReader(buf))
  243. if err != nil {
  244. t.Fatalf("ReadAll: decoding: %v", err)
  245. }
  246. if err := cmp(dst, src); err != nil {
  247. t.Fatal(err)
  248. }
  249. }
  250. func TestWriterGoldenOutput(t *testing.T) {
  251. buf := new(bytes.Buffer)
  252. w := NewBufferedWriter(buf)
  253. defer w.Close()
  254. w.Write([]byte("abcd")) // Not compressible.
  255. w.Flush()
  256. w.Write(bytes.Repeat([]byte{'A'}, 100)) // Compressible.
  257. w.Flush()
  258. got := buf.String()
  259. want := strings.Join([]string{
  260. magicChunk,
  261. "\x01\x08\x00\x00", // Uncompressed chunk, 8 bytes long (including 4 byte checksum).
  262. "\x68\x10\xe6\xb6", // Checksum.
  263. "\x61\x62\x63\x64", // Uncompressed payload: "abcd".
  264. "\x00\x0d\x00\x00", // Compressed chunk, 13 bytes long (including 4 byte checksum).
  265. "\x37\xcb\xbc\x9d", // Checksum.
  266. "\x64", // Compressed payload: Uncompressed length (varint encoded): 100.
  267. "\x00\x41", // Compressed payload: tagLiteral, length=1, "A".
  268. "\xfe\x01\x00", // Compressed payload: tagCopy2, length=64, offset=1.
  269. "\x8a\x01\x00", // Compressed payload: tagCopy2, length=35, offset=1.
  270. }, "")
  271. if got != want {
  272. t.Fatalf("\ngot: % x\nwant: % x", got, want)
  273. }
  274. }
  275. func TestNewBufferedWriter(t *testing.T) {
  276. // Test all 32 possible sub-sequences of these 5 input slices.
  277. //
  278. // Their lengths sum to 400,000, which is over 6 times the Writer ibuf
  279. // capacity: 6 * maxUncompressedChunkLen is 393,216.
  280. inputs := [][]byte{
  281. bytes.Repeat([]byte{'a'}, 40000),
  282. bytes.Repeat([]byte{'b'}, 150000),
  283. bytes.Repeat([]byte{'c'}, 60000),
  284. bytes.Repeat([]byte{'d'}, 120000),
  285. bytes.Repeat([]byte{'e'}, 30000),
  286. }
  287. loop:
  288. for i := 0; i < 1<<uint(len(inputs)); i++ {
  289. var want []byte
  290. buf := new(bytes.Buffer)
  291. w := NewBufferedWriter(buf)
  292. for j, input := range inputs {
  293. if i&(1<<uint(j)) == 0 {
  294. continue
  295. }
  296. if _, err := w.Write(input); err != nil {
  297. t.Errorf("i=%#02x: j=%d: Write: %v", i, j, err)
  298. continue loop
  299. }
  300. want = append(want, input...)
  301. }
  302. if err := w.Close(); err != nil {
  303. t.Errorf("i=%#02x: Close: %v", i, err)
  304. continue
  305. }
  306. got, err := ioutil.ReadAll(NewReader(buf))
  307. if err != nil {
  308. t.Errorf("i=%#02x: ReadAll: %v", i, err)
  309. continue
  310. }
  311. if err := cmp(got, want); err != nil {
  312. t.Errorf("i=%#02x: %v", i, err)
  313. continue
  314. }
  315. }
  316. }
  317. func TestFlush(t *testing.T) {
  318. buf := new(bytes.Buffer)
  319. w := NewBufferedWriter(buf)
  320. defer w.Close()
  321. if _, err := w.Write(bytes.Repeat([]byte{'x'}, 20)); err != nil {
  322. t.Fatalf("Write: %v", err)
  323. }
  324. if n := buf.Len(); n != 0 {
  325. t.Fatalf("before Flush: %d bytes were written to the underlying io.Writer, want 0", n)
  326. }
  327. if err := w.Flush(); err != nil {
  328. t.Fatalf("Flush: %v", err)
  329. }
  330. if n := buf.Len(); n == 0 {
  331. t.Fatalf("after Flush: %d bytes were written to the underlying io.Writer, want non-0", n)
  332. }
  333. }
  334. func TestReaderReset(t *testing.T) {
  335. gold := bytes.Repeat([]byte("All that is gold does not glitter,\n"), 10000)
  336. buf := new(bytes.Buffer)
  337. if _, err := NewWriter(buf).Write(gold); err != nil {
  338. t.Fatalf("Write: %v", err)
  339. }
  340. encoded, invalid, partial := buf.String(), "invalid", "partial"
  341. r := NewReader(nil)
  342. for i, s := range []string{encoded, invalid, partial, encoded, partial, invalid, encoded, encoded} {
  343. if s == partial {
  344. r.Reset(strings.NewReader(encoded))
  345. if _, err := r.Read(make([]byte, 101)); err != nil {
  346. t.Errorf("#%d: %v", i, err)
  347. continue
  348. }
  349. continue
  350. }
  351. r.Reset(strings.NewReader(s))
  352. got, err := ioutil.ReadAll(r)
  353. switch s {
  354. case encoded:
  355. if err != nil {
  356. t.Errorf("#%d: %v", i, err)
  357. continue
  358. }
  359. if err := cmp(got, gold); err != nil {
  360. t.Errorf("#%d: %v", i, err)
  361. continue
  362. }
  363. case invalid:
  364. if err == nil {
  365. t.Errorf("#%d: got nil error, want non-nil", i)
  366. continue
  367. }
  368. }
  369. }
  370. }
  371. func TestWriterReset(t *testing.T) {
  372. gold := bytes.Repeat([]byte("Not all those who wander are lost;\n"), 10000)
  373. const n = 20
  374. for _, buffered := range []bool{false, true} {
  375. var w *Writer
  376. if buffered {
  377. w = NewBufferedWriter(nil)
  378. defer w.Close()
  379. } else {
  380. w = NewWriter(nil)
  381. }
  382. var gots, wants [][]byte
  383. failed := false
  384. for i := 0; i <= n; i++ {
  385. buf := new(bytes.Buffer)
  386. w.Reset(buf)
  387. want := gold[:len(gold)*i/n]
  388. if _, err := w.Write(want); err != nil {
  389. t.Errorf("#%d: Write: %v", i, err)
  390. failed = true
  391. continue
  392. }
  393. if buffered {
  394. if err := w.Flush(); err != nil {
  395. t.Errorf("#%d: Flush: %v", i, err)
  396. failed = true
  397. continue
  398. }
  399. }
  400. got, err := ioutil.ReadAll(NewReader(buf))
  401. if err != nil {
  402. t.Errorf("#%d: ReadAll: %v", i, err)
  403. failed = true
  404. continue
  405. }
  406. gots = append(gots, got)
  407. wants = append(wants, want)
  408. }
  409. if failed {
  410. continue
  411. }
  412. for i := range gots {
  413. if err := cmp(gots[i], wants[i]); err != nil {
  414. t.Errorf("#%d: %v", i, err)
  415. }
  416. }
  417. }
  418. }
  419. func TestWriterResetWithoutFlush(t *testing.T) {
  420. buf0 := new(bytes.Buffer)
  421. buf1 := new(bytes.Buffer)
  422. w := NewBufferedWriter(buf0)
  423. if _, err := w.Write([]byte("xxx")); err != nil {
  424. t.Fatalf("Write #0: %v", err)
  425. }
  426. // Note that we don't Flush the Writer before calling Reset.
  427. w.Reset(buf1)
  428. if _, err := w.Write([]byte("yyy")); err != nil {
  429. t.Fatalf("Write #1: %v", err)
  430. }
  431. if err := w.Flush(); err != nil {
  432. t.Fatalf("Flush: %v", err)
  433. }
  434. got, err := ioutil.ReadAll(NewReader(buf1))
  435. if err != nil {
  436. t.Fatalf("ReadAll: %v", err)
  437. }
  438. if err := cmp(got, []byte("yyy")); err != nil {
  439. t.Fatal(err)
  440. }
  441. }
  442. type writeCounter int
  443. func (c *writeCounter) Write(p []byte) (int, error) {
  444. *c++
  445. return len(p), nil
  446. }
  447. // TestNumUnderlyingWrites tests that each Writer flush only makes one or two
  448. // Write calls on its underlying io.Writer, depending on whether or not the
  449. // flushed buffer was compressible.
  450. func TestNumUnderlyingWrites(t *testing.T) {
  451. testCases := []struct {
  452. input []byte
  453. want int
  454. }{
  455. {bytes.Repeat([]byte{'x'}, 100), 1},
  456. {bytes.Repeat([]byte{'y'}, 100), 1},
  457. {[]byte("ABCDEFGHIJKLMNOPQRST"), 2},
  458. }
  459. var c writeCounter
  460. w := NewBufferedWriter(&c)
  461. defer w.Close()
  462. for i, tc := range testCases {
  463. c = 0
  464. if _, err := w.Write(tc.input); err != nil {
  465. t.Errorf("#%d: Write: %v", i, err)
  466. continue
  467. }
  468. if err := w.Flush(); err != nil {
  469. t.Errorf("#%d: Flush: %v", i, err)
  470. continue
  471. }
  472. if int(c) != tc.want {
  473. t.Errorf("#%d: got %d underlying writes, want %d", i, c, tc.want)
  474. continue
  475. }
  476. }
  477. }
  478. func benchDecode(b *testing.B, src []byte) {
  479. encoded := Encode(nil, src)
  480. // Bandwidth is in amount of uncompressed data.
  481. b.SetBytes(int64(len(src)))
  482. b.ResetTimer()
  483. for i := 0; i < b.N; i++ {
  484. Decode(src, encoded)
  485. }
  486. }
  487. func benchEncode(b *testing.B, src []byte) {
  488. // Bandwidth is in amount of uncompressed data.
  489. b.SetBytes(int64(len(src)))
  490. dst := make([]byte, MaxEncodedLen(len(src)))
  491. b.ResetTimer()
  492. for i := 0; i < b.N; i++ {
  493. Encode(dst, src)
  494. }
  495. }
  496. func readFile(b testing.TB, filename string) []byte {
  497. src, err := ioutil.ReadFile(filename)
  498. if err != nil {
  499. b.Skipf("skipping benchmark: %v", err)
  500. }
  501. if len(src) == 0 {
  502. b.Fatalf("%s has zero length", filename)
  503. }
  504. return src
  505. }
  506. // expand returns a slice of length n containing repeated copies of src.
  507. func expand(src []byte, n int) []byte {
  508. dst := make([]byte, n)
  509. for x := dst; len(x) > 0; {
  510. i := copy(x, src)
  511. x = x[i:]
  512. }
  513. return dst
  514. }
  515. func benchWords(b *testing.B, n int, decode bool) {
  516. // Note: the file is OS-language dependent so the resulting values are not
  517. // directly comparable for non-US-English OS installations.
  518. data := expand(readFile(b, "/usr/share/dict/words"), n)
  519. if decode {
  520. benchDecode(b, data)
  521. } else {
  522. benchEncode(b, data)
  523. }
  524. }
  525. func BenchmarkWordsDecode1e1(b *testing.B) { benchWords(b, 1e1, true) }
  526. func BenchmarkWordsDecode1e2(b *testing.B) { benchWords(b, 1e2, true) }
  527. func BenchmarkWordsDecode1e3(b *testing.B) { benchWords(b, 1e3, true) }
  528. func BenchmarkWordsDecode1e4(b *testing.B) { benchWords(b, 1e4, true) }
  529. func BenchmarkWordsDecode1e5(b *testing.B) { benchWords(b, 1e5, true) }
  530. func BenchmarkWordsDecode1e6(b *testing.B) { benchWords(b, 1e6, true) }
  531. func BenchmarkWordsEncode1e1(b *testing.B) { benchWords(b, 1e1, false) }
  532. func BenchmarkWordsEncode1e2(b *testing.B) { benchWords(b, 1e2, false) }
  533. func BenchmarkWordsEncode1e3(b *testing.B) { benchWords(b, 1e3, false) }
  534. func BenchmarkWordsEncode1e4(b *testing.B) { benchWords(b, 1e4, false) }
  535. func BenchmarkWordsEncode1e5(b *testing.B) { benchWords(b, 1e5, false) }
  536. func BenchmarkWordsEncode1e6(b *testing.B) { benchWords(b, 1e6, false) }
  537. func BenchmarkRandomEncode(b *testing.B) {
  538. rng := rand.New(rand.NewSource(1))
  539. data := make([]byte, 1<<20)
  540. for i := range data {
  541. data[i] = uint8(rng.Intn(256))
  542. }
  543. benchEncode(b, data)
  544. }
  545. // testFiles' values are copied directly from
  546. // https://raw.githubusercontent.com/google/snappy/master/snappy_unittest.cc
  547. // The label field is unused in snappy-go.
  548. //
  549. // If this list changes (due to the upstream C++ list changing), remember to
  550. // update the .gitignore file in this repository.
  551. var testFiles = []struct {
  552. label string
  553. filename string
  554. sizeLimit int
  555. }{
  556. {"html", "html", 0},
  557. {"urls", "urls.10K", 0},
  558. {"jpg", "fireworks.jpeg", 0},
  559. {"jpg_200", "fireworks.jpeg", 200},
  560. {"pdf", "paper-100k.pdf", 0},
  561. {"html4", "html_x_4", 0},
  562. {"txt1", "alice29.txt", 0},
  563. {"txt2", "asyoulik.txt", 0},
  564. {"txt3", "lcet10.txt", 0},
  565. {"txt4", "plrabn12.txt", 0},
  566. {"pb", "geo.protodata", 0},
  567. {"gaviota", "kppkn.gtb", 0},
  568. }
  569. // The test data files are present at this canonical URL.
  570. const baseURL = "https://raw.githubusercontent.com/google/snappy/master/testdata/"
  571. func downloadTestdata(b *testing.B, basename string) (errRet error) {
  572. filename := filepath.Join(*testdata, basename)
  573. if stat, err := os.Stat(filename); err == nil && stat.Size() != 0 {
  574. return nil
  575. }
  576. if !*download {
  577. b.Skipf("test data not found; skipping benchmark without the -download flag")
  578. }
  579. // Download the official snappy C++ implementation reference test data
  580. // files for benchmarking.
  581. if err := os.Mkdir(*testdata, 0777); err != nil && !os.IsExist(err) {
  582. return fmt.Errorf("failed to create testdata: %s", err)
  583. }
  584. f, err := os.Create(filename)
  585. if err != nil {
  586. return fmt.Errorf("failed to create %s: %s", filename, err)
  587. }
  588. defer f.Close()
  589. defer func() {
  590. if errRet != nil {
  591. os.Remove(filename)
  592. }
  593. }()
  594. url := baseURL + basename
  595. resp, err := http.Get(url)
  596. if err != nil {
  597. return fmt.Errorf("failed to download %s: %s", url, err)
  598. }
  599. defer resp.Body.Close()
  600. if s := resp.StatusCode; s != http.StatusOK {
  601. return fmt.Errorf("downloading %s: HTTP status code %d (%s)", url, s, http.StatusText(s))
  602. }
  603. _, err = io.Copy(f, resp.Body)
  604. if err != nil {
  605. return fmt.Errorf("failed to download %s to %s: %s", url, filename, err)
  606. }
  607. return nil
  608. }
  609. func benchFile(b *testing.B, n int, decode bool) {
  610. if err := downloadTestdata(b, testFiles[n].filename); err != nil {
  611. b.Fatalf("failed to download testdata: %s", err)
  612. }
  613. data := readFile(b, filepath.Join(*testdata, testFiles[n].filename))
  614. if n := testFiles[n].sizeLimit; 0 < n && n < len(data) {
  615. data = data[:n]
  616. }
  617. if decode {
  618. benchDecode(b, data)
  619. } else {
  620. benchEncode(b, data)
  621. }
  622. }
  623. // Naming convention is kept similar to what snappy's C++ implementation uses.
  624. func Benchmark_UFlat0(b *testing.B) { benchFile(b, 0, true) }
  625. func Benchmark_UFlat1(b *testing.B) { benchFile(b, 1, true) }
  626. func Benchmark_UFlat2(b *testing.B) { benchFile(b, 2, true) }
  627. func Benchmark_UFlat3(b *testing.B) { benchFile(b, 3, true) }
  628. func Benchmark_UFlat4(b *testing.B) { benchFile(b, 4, true) }
  629. func Benchmark_UFlat5(b *testing.B) { benchFile(b, 5, true) }
  630. func Benchmark_UFlat6(b *testing.B) { benchFile(b, 6, true) }
  631. func Benchmark_UFlat7(b *testing.B) { benchFile(b, 7, true) }
  632. func Benchmark_UFlat8(b *testing.B) { benchFile(b, 8, true) }
  633. func Benchmark_UFlat9(b *testing.B) { benchFile(b, 9, true) }
  634. func Benchmark_UFlat10(b *testing.B) { benchFile(b, 10, true) }
  635. func Benchmark_UFlat11(b *testing.B) { benchFile(b, 11, true) }
  636. func Benchmark_ZFlat0(b *testing.B) { benchFile(b, 0, false) }
  637. func Benchmark_ZFlat1(b *testing.B) { benchFile(b, 1, false) }
  638. func Benchmark_ZFlat2(b *testing.B) { benchFile(b, 2, false) }
  639. func Benchmark_ZFlat3(b *testing.B) { benchFile(b, 3, false) }
  640. func Benchmark_ZFlat4(b *testing.B) { benchFile(b, 4, false) }
  641. func Benchmark_ZFlat5(b *testing.B) { benchFile(b, 5, false) }
  642. func Benchmark_ZFlat6(b *testing.B) { benchFile(b, 6, false) }
  643. func Benchmark_ZFlat7(b *testing.B) { benchFile(b, 7, false) }
  644. func Benchmark_ZFlat8(b *testing.B) { benchFile(b, 8, false) }
  645. func Benchmark_ZFlat9(b *testing.B) { benchFile(b, 9, false) }
  646. func Benchmark_ZFlat10(b *testing.B) { benchFile(b, 10, false) }
  647. func Benchmark_ZFlat11(b *testing.B) { benchFile(b, 11, false) }