snappy_test.go 21 KB

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