snappy_test.go 23 KB

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