snappy_test.go 20 KB

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