snappy_test.go 22 KB

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