snappy_test.go 25 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906
  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. // notPresent is a byte value that is not present in either the input or
  271. // the output. It is written to dBuf to check that Decode does not write
  272. // bytes past the end of dBuf[:dLen].
  273. const notPresent = 0xfe
  274. var dBuf [100]byte
  275. loop:
  276. for i, tc := range testCases {
  277. input := []byte(tc.input)
  278. for _, x := range input {
  279. if x == notPresent {
  280. t.Errorf("#%d (%s): input shouldn't contain byte value %#02x", i, tc.desc, notPresent)
  281. continue loop
  282. }
  283. }
  284. dLen, n := binary.Uvarint(input)
  285. if n <= 0 {
  286. t.Errorf("#%d (%s): invalid varint-encoded dLen", i, tc.desc)
  287. continue
  288. }
  289. if dLen > uint64(len(dBuf)) {
  290. t.Errorf("#%d (%s): dLen %d is too large", i, tc.desc, dLen)
  291. continue
  292. }
  293. for j := range dBuf {
  294. dBuf[j] = notPresent
  295. }
  296. g, gotErr := Decode(dBuf[:], input)
  297. if got := string(g); got != tc.want || gotErr != tc.wantErr {
  298. t.Errorf("#%d (%s):\ngot %q, %v\nwant %q, %v",
  299. i, tc.desc, got, gotErr, tc.want, tc.wantErr)
  300. continue
  301. }
  302. for _, x := range dBuf[dLen:] {
  303. if x != notPresent {
  304. t.Errorf("#%d (%s): dBuf[dLen:] should all be byte value %#02x", i, tc.desc, notPresent)
  305. continue loop
  306. }
  307. }
  308. }
  309. }
  310. // TestDecodeLengthOffset tests decoding an encoding of the form literal +
  311. // copy-length-offset + literal. For example: "abcdefghijkl" + "efghij" + "AB".
  312. func TestDecodeLengthOffset(t *testing.T) {
  313. const (
  314. prefix = "abcdefghijklmnopqr"
  315. suffix = "ABCDEFGHIJKLMNOPQR"
  316. // notPresent is a byte value that is not present in either the input
  317. // or the output. It is written to gotBuf to check that Decode does not
  318. // write bytes past the end of gotBuf[:totalLen].
  319. notPresent = 0xfe
  320. )
  321. var gotBuf, wantBuf, inputBuf [256]byte
  322. for length := 1; length <= 18; length++ {
  323. for offset := 1; offset <= 18; offset++ {
  324. loop:
  325. for suffixLen := 0; suffixLen <= 18; suffixLen++ {
  326. totalLen := uint64(len(prefix) + length + suffixLen)
  327. inputLen := binary.PutUvarint(inputBuf[:], totalLen)
  328. inputBuf[inputLen] = tagLiteral + 4*byte(len(prefix)-1)
  329. inputLen++
  330. inputLen += copy(inputBuf[inputLen:], prefix)
  331. inputBuf[inputLen+0] = tagCopy2 + 4*byte(length-1)
  332. inputBuf[inputLen+1] = byte(offset)
  333. inputBuf[inputLen+2] = 0x00
  334. inputLen += 3
  335. if suffixLen > 0 {
  336. inputBuf[inputLen] = tagLiteral + 4*byte(suffixLen-1)
  337. inputLen++
  338. inputLen += copy(inputBuf[inputLen:], suffix[:suffixLen])
  339. }
  340. input := inputBuf[:inputLen]
  341. for i := range gotBuf {
  342. gotBuf[i] = notPresent
  343. }
  344. got, err := Decode(gotBuf[:], input)
  345. if err != nil {
  346. t.Errorf("length=%d, offset=%d; suffixLen=%d: %v", length, offset, suffixLen, err)
  347. continue
  348. }
  349. wantLen := 0
  350. wantLen += copy(wantBuf[wantLen:], prefix)
  351. for i := 0; i < length; i++ {
  352. wantBuf[wantLen] = wantBuf[wantLen-offset]
  353. wantLen++
  354. }
  355. wantLen += copy(wantBuf[wantLen:], suffix[:suffixLen])
  356. want := wantBuf[:wantLen]
  357. for _, x := range input {
  358. if x == notPresent {
  359. t.Errorf("length=%d, offset=%d; suffixLen=%d: input shouldn't contain byte value %#02x",
  360. length, offset, suffixLen, notPresent)
  361. continue loop
  362. }
  363. }
  364. for _, x := range gotBuf[totalLen:] {
  365. if x != notPresent {
  366. t.Errorf("length=%d, offset=%d; suffixLen=%d: gotBuf[totalLen:] should all be byte value %#02x",
  367. length, offset, suffixLen, notPresent)
  368. continue loop
  369. }
  370. }
  371. for _, x := range want {
  372. if x == notPresent {
  373. t.Errorf("length=%d, offset=%d; suffixLen=%d: want shouldn't contain byte value %#02x",
  374. length, offset, suffixLen, notPresent)
  375. continue loop
  376. }
  377. }
  378. if !bytes.Equal(got, want) {
  379. t.Errorf("length=%d, offset=%d; suffixLen=%d:\ninput % x\ngot % x\nwant % x",
  380. length, offset, suffixLen, input, got, want)
  381. continue
  382. }
  383. }
  384. }
  385. }
  386. }
  387. func TestDecodeGoldenInput(t *testing.T) {
  388. src, err := ioutil.ReadFile("testdata/pi.txt.rawsnappy")
  389. if err != nil {
  390. t.Fatalf("ReadFile: %v", err)
  391. }
  392. got, err := Decode(nil, src)
  393. if err != nil {
  394. t.Fatalf("Decode: %v", err)
  395. }
  396. want, err := ioutil.ReadFile("testdata/pi.txt")
  397. if err != nil {
  398. t.Fatalf("ReadFile: %v", err)
  399. }
  400. if err := cmp(got, want); err != nil {
  401. t.Fatal(err)
  402. }
  403. }
  404. // TestEncodeNoiseThenRepeats encodes input for which the first half is very
  405. // incompressible and the second half is very compressible. The encoded form's
  406. // length should be closer to 50% of the original length than 100%.
  407. func TestEncodeNoiseThenRepeats(t *testing.T) {
  408. for _, origLen := range []int{32 * 1024, 256 * 1024, 2048 * 1024} {
  409. src := make([]byte, origLen)
  410. rng := rand.New(rand.NewSource(1))
  411. firstHalf, secondHalf := src[:origLen/2], src[origLen/2:]
  412. for i := range firstHalf {
  413. firstHalf[i] = uint8(rng.Intn(256))
  414. }
  415. for i := range secondHalf {
  416. secondHalf[i] = uint8(i >> 8)
  417. }
  418. dst := Encode(nil, src)
  419. if got, want := len(dst), origLen*3/4; got >= want {
  420. t.Errorf("origLen=%d: got %d encoded bytes, want less than %d", origLen, got, want)
  421. }
  422. }
  423. }
  424. func TestFramingFormat(t *testing.T) {
  425. // src is comprised of alternating 1e5-sized sequences of random
  426. // (incompressible) bytes and repeated (compressible) bytes. 1e5 was chosen
  427. // because it is larger than maxBlockSize (64k).
  428. src := make([]byte, 1e6)
  429. rng := rand.New(rand.NewSource(1))
  430. for i := 0; i < 10; i++ {
  431. if i%2 == 0 {
  432. for j := 0; j < 1e5; j++ {
  433. src[1e5*i+j] = uint8(rng.Intn(256))
  434. }
  435. } else {
  436. for j := 0; j < 1e5; j++ {
  437. src[1e5*i+j] = uint8(i)
  438. }
  439. }
  440. }
  441. buf := new(bytes.Buffer)
  442. if _, err := NewWriter(buf).Write(src); err != nil {
  443. t.Fatalf("Write: encoding: %v", err)
  444. }
  445. dst, err := ioutil.ReadAll(NewReader(buf))
  446. if err != nil {
  447. t.Fatalf("ReadAll: decoding: %v", err)
  448. }
  449. if err := cmp(dst, src); err != nil {
  450. t.Fatal(err)
  451. }
  452. }
  453. func TestWriterGoldenOutput(t *testing.T) {
  454. buf := new(bytes.Buffer)
  455. w := NewBufferedWriter(buf)
  456. defer w.Close()
  457. w.Write([]byte("abcd")) // Not compressible.
  458. w.Flush()
  459. w.Write(bytes.Repeat([]byte{'A'}, 100)) // Compressible.
  460. w.Flush()
  461. got := buf.String()
  462. want := strings.Join([]string{
  463. magicChunk,
  464. "\x01\x08\x00\x00", // Uncompressed chunk, 8 bytes long (including 4 byte checksum).
  465. "\x68\x10\xe6\xb6", // Checksum.
  466. "\x61\x62\x63\x64", // Uncompressed payload: "abcd".
  467. "\x00\x0d\x00\x00", // Compressed chunk, 13 bytes long (including 4 byte checksum).
  468. "\x37\xcb\xbc\x9d", // Checksum.
  469. "\x64", // Compressed payload: Uncompressed length (varint encoded): 100.
  470. "\x00\x41", // Compressed payload: tagLiteral, length=1, "A".
  471. "\xfe\x01\x00", // Compressed payload: tagCopy2, length=64, offset=1.
  472. "\x8a\x01\x00", // Compressed payload: tagCopy2, length=35, offset=1.
  473. }, "")
  474. if got != want {
  475. t.Fatalf("\ngot: % x\nwant: % x", got, want)
  476. }
  477. }
  478. func TestNewBufferedWriter(t *testing.T) {
  479. // Test all 32 possible sub-sequences of these 5 input slices.
  480. //
  481. // Their lengths sum to 400,000, which is over 6 times the Writer ibuf
  482. // capacity: 6 * maxBlockSize is 393,216.
  483. inputs := [][]byte{
  484. bytes.Repeat([]byte{'a'}, 40000),
  485. bytes.Repeat([]byte{'b'}, 150000),
  486. bytes.Repeat([]byte{'c'}, 60000),
  487. bytes.Repeat([]byte{'d'}, 120000),
  488. bytes.Repeat([]byte{'e'}, 30000),
  489. }
  490. loop:
  491. for i := 0; i < 1<<uint(len(inputs)); i++ {
  492. var want []byte
  493. buf := new(bytes.Buffer)
  494. w := NewBufferedWriter(buf)
  495. for j, input := range inputs {
  496. if i&(1<<uint(j)) == 0 {
  497. continue
  498. }
  499. if _, err := w.Write(input); err != nil {
  500. t.Errorf("i=%#02x: j=%d: Write: %v", i, j, err)
  501. continue loop
  502. }
  503. want = append(want, input...)
  504. }
  505. if err := w.Close(); err != nil {
  506. t.Errorf("i=%#02x: Close: %v", i, err)
  507. continue
  508. }
  509. got, err := ioutil.ReadAll(NewReader(buf))
  510. if err != nil {
  511. t.Errorf("i=%#02x: ReadAll: %v", i, err)
  512. continue
  513. }
  514. if err := cmp(got, want); err != nil {
  515. t.Errorf("i=%#02x: %v", i, err)
  516. continue
  517. }
  518. }
  519. }
  520. func TestFlush(t *testing.T) {
  521. buf := new(bytes.Buffer)
  522. w := NewBufferedWriter(buf)
  523. defer w.Close()
  524. if _, err := w.Write(bytes.Repeat([]byte{'x'}, 20)); err != nil {
  525. t.Fatalf("Write: %v", err)
  526. }
  527. if n := buf.Len(); n != 0 {
  528. t.Fatalf("before Flush: %d bytes were written to the underlying io.Writer, want 0", n)
  529. }
  530. if err := w.Flush(); err != nil {
  531. t.Fatalf("Flush: %v", err)
  532. }
  533. if n := buf.Len(); n == 0 {
  534. t.Fatalf("after Flush: %d bytes were written to the underlying io.Writer, want non-0", n)
  535. }
  536. }
  537. func TestReaderReset(t *testing.T) {
  538. gold := bytes.Repeat([]byte("All that is gold does not glitter,\n"), 10000)
  539. buf := new(bytes.Buffer)
  540. if _, err := NewWriter(buf).Write(gold); err != nil {
  541. t.Fatalf("Write: %v", err)
  542. }
  543. encoded, invalid, partial := buf.String(), "invalid", "partial"
  544. r := NewReader(nil)
  545. for i, s := range []string{encoded, invalid, partial, encoded, partial, invalid, encoded, encoded} {
  546. if s == partial {
  547. r.Reset(strings.NewReader(encoded))
  548. if _, err := r.Read(make([]byte, 101)); err != nil {
  549. t.Errorf("#%d: %v", i, err)
  550. continue
  551. }
  552. continue
  553. }
  554. r.Reset(strings.NewReader(s))
  555. got, err := ioutil.ReadAll(r)
  556. switch s {
  557. case encoded:
  558. if err != nil {
  559. t.Errorf("#%d: %v", i, err)
  560. continue
  561. }
  562. if err := cmp(got, gold); err != nil {
  563. t.Errorf("#%d: %v", i, err)
  564. continue
  565. }
  566. case invalid:
  567. if err == nil {
  568. t.Errorf("#%d: got nil error, want non-nil", i)
  569. continue
  570. }
  571. }
  572. }
  573. }
  574. func TestWriterReset(t *testing.T) {
  575. gold := bytes.Repeat([]byte("Not all those who wander are lost;\n"), 10000)
  576. const n = 20
  577. for _, buffered := range []bool{false, true} {
  578. var w *Writer
  579. if buffered {
  580. w = NewBufferedWriter(nil)
  581. defer w.Close()
  582. } else {
  583. w = NewWriter(nil)
  584. }
  585. var gots, wants [][]byte
  586. failed := false
  587. for i := 0; i <= n; i++ {
  588. buf := new(bytes.Buffer)
  589. w.Reset(buf)
  590. want := gold[:len(gold)*i/n]
  591. if _, err := w.Write(want); err != nil {
  592. t.Errorf("#%d: Write: %v", i, err)
  593. failed = true
  594. continue
  595. }
  596. if buffered {
  597. if err := w.Flush(); err != nil {
  598. t.Errorf("#%d: Flush: %v", i, err)
  599. failed = true
  600. continue
  601. }
  602. }
  603. got, err := ioutil.ReadAll(NewReader(buf))
  604. if err != nil {
  605. t.Errorf("#%d: ReadAll: %v", i, err)
  606. failed = true
  607. continue
  608. }
  609. gots = append(gots, got)
  610. wants = append(wants, want)
  611. }
  612. if failed {
  613. continue
  614. }
  615. for i := range gots {
  616. if err := cmp(gots[i], wants[i]); err != nil {
  617. t.Errorf("#%d: %v", i, err)
  618. }
  619. }
  620. }
  621. }
  622. func TestWriterResetWithoutFlush(t *testing.T) {
  623. buf0 := new(bytes.Buffer)
  624. buf1 := new(bytes.Buffer)
  625. w := NewBufferedWriter(buf0)
  626. if _, err := w.Write([]byte("xxx")); err != nil {
  627. t.Fatalf("Write #0: %v", err)
  628. }
  629. // Note that we don't Flush the Writer before calling Reset.
  630. w.Reset(buf1)
  631. if _, err := w.Write([]byte("yyy")); err != nil {
  632. t.Fatalf("Write #1: %v", err)
  633. }
  634. if err := w.Flush(); err != nil {
  635. t.Fatalf("Flush: %v", err)
  636. }
  637. got, err := ioutil.ReadAll(NewReader(buf1))
  638. if err != nil {
  639. t.Fatalf("ReadAll: %v", err)
  640. }
  641. if err := cmp(got, []byte("yyy")); err != nil {
  642. t.Fatal(err)
  643. }
  644. }
  645. type writeCounter int
  646. func (c *writeCounter) Write(p []byte) (int, error) {
  647. *c++
  648. return len(p), nil
  649. }
  650. // TestNumUnderlyingWrites tests that each Writer flush only makes one or two
  651. // Write calls on its underlying io.Writer, depending on whether or not the
  652. // flushed buffer was compressible.
  653. func TestNumUnderlyingWrites(t *testing.T) {
  654. testCases := []struct {
  655. input []byte
  656. want int
  657. }{
  658. {bytes.Repeat([]byte{'x'}, 100), 1},
  659. {bytes.Repeat([]byte{'y'}, 100), 1},
  660. {[]byte("ABCDEFGHIJKLMNOPQRST"), 2},
  661. }
  662. var c writeCounter
  663. w := NewBufferedWriter(&c)
  664. defer w.Close()
  665. for i, tc := range testCases {
  666. c = 0
  667. if _, err := w.Write(tc.input); err != nil {
  668. t.Errorf("#%d: Write: %v", i, err)
  669. continue
  670. }
  671. if err := w.Flush(); err != nil {
  672. t.Errorf("#%d: Flush: %v", i, err)
  673. continue
  674. }
  675. if int(c) != tc.want {
  676. t.Errorf("#%d: got %d underlying writes, want %d", i, c, tc.want)
  677. continue
  678. }
  679. }
  680. }
  681. func benchDecode(b *testing.B, src []byte) {
  682. encoded := Encode(nil, src)
  683. // Bandwidth is in amount of uncompressed data.
  684. b.SetBytes(int64(len(src)))
  685. b.ResetTimer()
  686. for i := 0; i < b.N; i++ {
  687. Decode(src, encoded)
  688. }
  689. }
  690. func benchEncode(b *testing.B, src []byte) {
  691. // Bandwidth is in amount of uncompressed data.
  692. b.SetBytes(int64(len(src)))
  693. dst := make([]byte, MaxEncodedLen(len(src)))
  694. b.ResetTimer()
  695. for i := 0; i < b.N; i++ {
  696. Encode(dst, src)
  697. }
  698. }
  699. func readFile(b testing.TB, filename string) []byte {
  700. src, err := ioutil.ReadFile(filename)
  701. if err != nil {
  702. b.Skipf("skipping benchmark: %v", err)
  703. }
  704. if len(src) == 0 {
  705. b.Fatalf("%s has zero length", filename)
  706. }
  707. return src
  708. }
  709. // expand returns a slice of length n containing repeated copies of src.
  710. func expand(src []byte, n int) []byte {
  711. dst := make([]byte, n)
  712. for x := dst; len(x) > 0; {
  713. i := copy(x, src)
  714. x = x[i:]
  715. }
  716. return dst
  717. }
  718. func benchWords(b *testing.B, n int, decode bool) {
  719. // Note: the file is OS-language dependent so the resulting values are not
  720. // directly comparable for non-US-English OS installations.
  721. data := expand(readFile(b, "/usr/share/dict/words"), n)
  722. if decode {
  723. benchDecode(b, data)
  724. } else {
  725. benchEncode(b, data)
  726. }
  727. }
  728. func BenchmarkWordsDecode1e1(b *testing.B) { benchWords(b, 1e1, true) }
  729. func BenchmarkWordsDecode1e2(b *testing.B) { benchWords(b, 1e2, true) }
  730. func BenchmarkWordsDecode1e3(b *testing.B) { benchWords(b, 1e3, true) }
  731. func BenchmarkWordsDecode1e4(b *testing.B) { benchWords(b, 1e4, true) }
  732. func BenchmarkWordsDecode1e5(b *testing.B) { benchWords(b, 1e5, true) }
  733. func BenchmarkWordsDecode1e6(b *testing.B) { benchWords(b, 1e6, true) }
  734. func BenchmarkWordsEncode1e1(b *testing.B) { benchWords(b, 1e1, false) }
  735. func BenchmarkWordsEncode1e2(b *testing.B) { benchWords(b, 1e2, false) }
  736. func BenchmarkWordsEncode1e3(b *testing.B) { benchWords(b, 1e3, false) }
  737. func BenchmarkWordsEncode1e4(b *testing.B) { benchWords(b, 1e4, false) }
  738. func BenchmarkWordsEncode1e5(b *testing.B) { benchWords(b, 1e5, false) }
  739. func BenchmarkWordsEncode1e6(b *testing.B) { benchWords(b, 1e6, false) }
  740. func BenchmarkRandomEncode(b *testing.B) {
  741. rng := rand.New(rand.NewSource(1))
  742. data := make([]byte, 1<<20)
  743. for i := range data {
  744. data[i] = uint8(rng.Intn(256))
  745. }
  746. benchEncode(b, data)
  747. }
  748. // testFiles' values are copied directly from
  749. // https://raw.githubusercontent.com/google/snappy/master/snappy_unittest.cc
  750. // The label field is unused in snappy-go.
  751. var testFiles = []struct {
  752. label string
  753. filename string
  754. sizeLimit int
  755. }{
  756. {"html", "html", 0},
  757. {"urls", "urls.10K", 0},
  758. {"jpg", "fireworks.jpeg", 0},
  759. {"jpg_200", "fireworks.jpeg", 200},
  760. {"pdf", "paper-100k.pdf", 0},
  761. {"html4", "html_x_4", 0},
  762. {"txt1", "alice29.txt", 0},
  763. {"txt2", "asyoulik.txt", 0},
  764. {"txt3", "lcet10.txt", 0},
  765. {"txt4", "plrabn12.txt", 0},
  766. {"pb", "geo.protodata", 0},
  767. {"gaviota", "kppkn.gtb", 0},
  768. }
  769. const (
  770. // The benchmark data files are at this canonical URL.
  771. benchURL = "https://raw.githubusercontent.com/google/snappy/master/testdata/"
  772. // They are copied to this local directory.
  773. benchDir = "testdata/bench"
  774. )
  775. func downloadBenchmarkFiles(b *testing.B, basename string) (errRet error) {
  776. filename := filepath.Join(benchDir, basename)
  777. if stat, err := os.Stat(filename); err == nil && stat.Size() != 0 {
  778. return nil
  779. }
  780. if !*download {
  781. b.Skipf("test data not found; skipping benchmark without the -download flag")
  782. }
  783. // Download the official snappy C++ implementation reference test data
  784. // files for benchmarking.
  785. if err := os.MkdirAll(benchDir, 0777); err != nil && !os.IsExist(err) {
  786. return fmt.Errorf("failed to create %s: %s", benchDir, err)
  787. }
  788. f, err := os.Create(filename)
  789. if err != nil {
  790. return fmt.Errorf("failed to create %s: %s", filename, err)
  791. }
  792. defer f.Close()
  793. defer func() {
  794. if errRet != nil {
  795. os.Remove(filename)
  796. }
  797. }()
  798. url := benchURL + basename
  799. resp, err := http.Get(url)
  800. if err != nil {
  801. return fmt.Errorf("failed to download %s: %s", url, err)
  802. }
  803. defer resp.Body.Close()
  804. if s := resp.StatusCode; s != http.StatusOK {
  805. return fmt.Errorf("downloading %s: HTTP status code %d (%s)", url, s, http.StatusText(s))
  806. }
  807. _, err = io.Copy(f, resp.Body)
  808. if err != nil {
  809. return fmt.Errorf("failed to download %s to %s: %s", url, filename, err)
  810. }
  811. return nil
  812. }
  813. func benchFile(b *testing.B, n int, decode bool) {
  814. if err := downloadBenchmarkFiles(b, testFiles[n].filename); err != nil {
  815. b.Fatalf("failed to download testdata: %s", err)
  816. }
  817. data := readFile(b, filepath.Join(benchDir, testFiles[n].filename))
  818. if n := testFiles[n].sizeLimit; 0 < n && n < len(data) {
  819. data = data[:n]
  820. }
  821. if decode {
  822. benchDecode(b, data)
  823. } else {
  824. benchEncode(b, data)
  825. }
  826. }
  827. // Naming convention is kept similar to what snappy's C++ implementation uses.
  828. func Benchmark_UFlat0(b *testing.B) { benchFile(b, 0, true) }
  829. func Benchmark_UFlat1(b *testing.B) { benchFile(b, 1, true) }
  830. func Benchmark_UFlat2(b *testing.B) { benchFile(b, 2, true) }
  831. func Benchmark_UFlat3(b *testing.B) { benchFile(b, 3, true) }
  832. func Benchmark_UFlat4(b *testing.B) { benchFile(b, 4, true) }
  833. func Benchmark_UFlat5(b *testing.B) { benchFile(b, 5, true) }
  834. func Benchmark_UFlat6(b *testing.B) { benchFile(b, 6, true) }
  835. func Benchmark_UFlat7(b *testing.B) { benchFile(b, 7, true) }
  836. func Benchmark_UFlat8(b *testing.B) { benchFile(b, 8, true) }
  837. func Benchmark_UFlat9(b *testing.B) { benchFile(b, 9, true) }
  838. func Benchmark_UFlat10(b *testing.B) { benchFile(b, 10, true) }
  839. func Benchmark_UFlat11(b *testing.B) { benchFile(b, 11, true) }
  840. func Benchmark_ZFlat0(b *testing.B) { benchFile(b, 0, false) }
  841. func Benchmark_ZFlat1(b *testing.B) { benchFile(b, 1, false) }
  842. func Benchmark_ZFlat2(b *testing.B) { benchFile(b, 2, false) }
  843. func Benchmark_ZFlat3(b *testing.B) { benchFile(b, 3, false) }
  844. func Benchmark_ZFlat4(b *testing.B) { benchFile(b, 4, false) }
  845. func Benchmark_ZFlat5(b *testing.B) { benchFile(b, 5, false) }
  846. func Benchmark_ZFlat6(b *testing.B) { benchFile(b, 6, false) }
  847. func Benchmark_ZFlat7(b *testing.B) { benchFile(b, 7, false) }
  848. func Benchmark_ZFlat8(b *testing.B) { benchFile(b, 8, false) }
  849. func Benchmark_ZFlat9(b *testing.B) { benchFile(b, 9, false) }
  850. func Benchmark_ZFlat10(b *testing.B) { benchFile(b, 10, false) }
  851. func Benchmark_ZFlat11(b *testing.B) { benchFile(b, 11, false) }