snappy_test.go 21 KB

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