snappy_test.go 26 KB

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