snappy_test.go 27 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973
  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. // TestSlowForwardCopyOverrun tests the "expand the pattern" algorithm
  427. // described in decode_amd64.s and its claim of a 10 byte overrun worst case.
  428. func TestSlowForwardCopyOverrun(t *testing.T) {
  429. const base = 100
  430. for length := 1; length < 18; length++ {
  431. for offset := 1; offset < 18; offset++ {
  432. highWaterMark := base
  433. d := base
  434. l := length
  435. o := offset
  436. // makeOffsetAtLeast8
  437. for o < 8 {
  438. if end := d + 8; highWaterMark < end {
  439. highWaterMark = end
  440. }
  441. l -= o
  442. d += o
  443. o += o
  444. }
  445. // fixUpSlowForwardCopy
  446. a := d
  447. d += l
  448. // finishSlowForwardCopy
  449. for l > 0 {
  450. if end := a + 8; highWaterMark < end {
  451. highWaterMark = end
  452. }
  453. a += 8
  454. l -= 8
  455. }
  456. dWant := base + length
  457. overrun := highWaterMark - dWant
  458. if d != dWant || overrun < 0 || 10 < overrun {
  459. t.Errorf("length=%d, offset=%d: d and overrun: got (%d, %d), want (%d, something in [0, 10])",
  460. length, offset, d, overrun, dWant)
  461. }
  462. }
  463. }
  464. }
  465. // TestEncodeNoiseThenRepeats encodes input for which the first half is very
  466. // incompressible and the second half is very compressible. The encoded form's
  467. // length should be closer to 50% of the original length than 100%.
  468. func TestEncodeNoiseThenRepeats(t *testing.T) {
  469. for _, origLen := range []int{32 * 1024, 256 * 1024, 2048 * 1024} {
  470. src := make([]byte, origLen)
  471. rng := rand.New(rand.NewSource(1))
  472. firstHalf, secondHalf := src[:origLen/2], src[origLen/2:]
  473. for i := range firstHalf {
  474. firstHalf[i] = uint8(rng.Intn(256))
  475. }
  476. for i := range secondHalf {
  477. secondHalf[i] = uint8(i >> 8)
  478. }
  479. dst := Encode(nil, src)
  480. if got, want := len(dst), origLen*3/4; got >= want {
  481. t.Errorf("origLen=%d: got %d encoded bytes, want less than %d", origLen, got, want)
  482. }
  483. }
  484. }
  485. func TestFramingFormat(t *testing.T) {
  486. // src is comprised of alternating 1e5-sized sequences of random
  487. // (incompressible) bytes and repeated (compressible) bytes. 1e5 was chosen
  488. // because it is larger than maxBlockSize (64k).
  489. src := make([]byte, 1e6)
  490. rng := rand.New(rand.NewSource(1))
  491. for i := 0; i < 10; i++ {
  492. if i%2 == 0 {
  493. for j := 0; j < 1e5; j++ {
  494. src[1e5*i+j] = uint8(rng.Intn(256))
  495. }
  496. } else {
  497. for j := 0; j < 1e5; j++ {
  498. src[1e5*i+j] = uint8(i)
  499. }
  500. }
  501. }
  502. buf := new(bytes.Buffer)
  503. if _, err := NewWriter(buf).Write(src); err != nil {
  504. t.Fatalf("Write: encoding: %v", err)
  505. }
  506. dst, err := ioutil.ReadAll(NewReader(buf))
  507. if err != nil {
  508. t.Fatalf("ReadAll: decoding: %v", err)
  509. }
  510. if err := cmp(dst, src); err != nil {
  511. t.Fatal(err)
  512. }
  513. }
  514. func TestWriterGoldenOutput(t *testing.T) {
  515. buf := new(bytes.Buffer)
  516. w := NewBufferedWriter(buf)
  517. defer w.Close()
  518. w.Write([]byte("abcd")) // Not compressible.
  519. w.Flush()
  520. w.Write(bytes.Repeat([]byte{'A'}, 100)) // Compressible.
  521. w.Flush()
  522. got := buf.String()
  523. want := strings.Join([]string{
  524. magicChunk,
  525. "\x01\x08\x00\x00", // Uncompressed chunk, 8 bytes long (including 4 byte checksum).
  526. "\x68\x10\xe6\xb6", // Checksum.
  527. "\x61\x62\x63\x64", // Uncompressed payload: "abcd".
  528. "\x00\x0d\x00\x00", // Compressed chunk, 13 bytes long (including 4 byte checksum).
  529. "\x37\xcb\xbc\x9d", // Checksum.
  530. "\x64", // Compressed payload: Uncompressed length (varint encoded): 100.
  531. "\x00\x41", // Compressed payload: tagLiteral, length=1, "A".
  532. "\xfe\x01\x00", // Compressed payload: tagCopy2, length=64, offset=1.
  533. "\x8a\x01\x00", // Compressed payload: tagCopy2, length=35, offset=1.
  534. }, "")
  535. if got != want {
  536. t.Fatalf("\ngot: % x\nwant: % x", got, want)
  537. }
  538. }
  539. func TestNewBufferedWriter(t *testing.T) {
  540. // Test all 32 possible sub-sequences of these 5 input slices.
  541. //
  542. // Their lengths sum to 400,000, which is over 6 times the Writer ibuf
  543. // capacity: 6 * maxBlockSize is 393,216.
  544. inputs := [][]byte{
  545. bytes.Repeat([]byte{'a'}, 40000),
  546. bytes.Repeat([]byte{'b'}, 150000),
  547. bytes.Repeat([]byte{'c'}, 60000),
  548. bytes.Repeat([]byte{'d'}, 120000),
  549. bytes.Repeat([]byte{'e'}, 30000),
  550. }
  551. loop:
  552. for i := 0; i < 1<<uint(len(inputs)); i++ {
  553. var want []byte
  554. buf := new(bytes.Buffer)
  555. w := NewBufferedWriter(buf)
  556. for j, input := range inputs {
  557. if i&(1<<uint(j)) == 0 {
  558. continue
  559. }
  560. if _, err := w.Write(input); err != nil {
  561. t.Errorf("i=%#02x: j=%d: Write: %v", i, j, err)
  562. continue loop
  563. }
  564. want = append(want, input...)
  565. }
  566. if err := w.Close(); err != nil {
  567. t.Errorf("i=%#02x: Close: %v", i, err)
  568. continue
  569. }
  570. got, err := ioutil.ReadAll(NewReader(buf))
  571. if err != nil {
  572. t.Errorf("i=%#02x: ReadAll: %v", i, err)
  573. continue
  574. }
  575. if err := cmp(got, want); err != nil {
  576. t.Errorf("i=%#02x: %v", i, err)
  577. continue
  578. }
  579. }
  580. }
  581. func TestFlush(t *testing.T) {
  582. buf := new(bytes.Buffer)
  583. w := NewBufferedWriter(buf)
  584. defer w.Close()
  585. if _, err := w.Write(bytes.Repeat([]byte{'x'}, 20)); err != nil {
  586. t.Fatalf("Write: %v", err)
  587. }
  588. if n := buf.Len(); n != 0 {
  589. t.Fatalf("before Flush: %d bytes were written to the underlying io.Writer, want 0", n)
  590. }
  591. if err := w.Flush(); err != nil {
  592. t.Fatalf("Flush: %v", err)
  593. }
  594. if n := buf.Len(); n == 0 {
  595. t.Fatalf("after Flush: %d bytes were written to the underlying io.Writer, want non-0", n)
  596. }
  597. }
  598. func TestReaderReset(t *testing.T) {
  599. gold := bytes.Repeat([]byte("All that is gold does not glitter,\n"), 10000)
  600. buf := new(bytes.Buffer)
  601. if _, err := NewWriter(buf).Write(gold); err != nil {
  602. t.Fatalf("Write: %v", err)
  603. }
  604. encoded, invalid, partial := buf.String(), "invalid", "partial"
  605. r := NewReader(nil)
  606. for i, s := range []string{encoded, invalid, partial, encoded, partial, invalid, encoded, encoded} {
  607. if s == partial {
  608. r.Reset(strings.NewReader(encoded))
  609. if _, err := r.Read(make([]byte, 101)); err != nil {
  610. t.Errorf("#%d: %v", i, err)
  611. continue
  612. }
  613. continue
  614. }
  615. r.Reset(strings.NewReader(s))
  616. got, err := ioutil.ReadAll(r)
  617. switch s {
  618. case encoded:
  619. if err != nil {
  620. t.Errorf("#%d: %v", i, err)
  621. continue
  622. }
  623. if err := cmp(got, gold); err != nil {
  624. t.Errorf("#%d: %v", i, err)
  625. continue
  626. }
  627. case invalid:
  628. if err == nil {
  629. t.Errorf("#%d: got nil error, want non-nil", i)
  630. continue
  631. }
  632. }
  633. }
  634. }
  635. func TestWriterReset(t *testing.T) {
  636. gold := bytes.Repeat([]byte("Not all those who wander are lost;\n"), 10000)
  637. const n = 20
  638. for _, buffered := range []bool{false, true} {
  639. var w *Writer
  640. if buffered {
  641. w = NewBufferedWriter(nil)
  642. defer w.Close()
  643. } else {
  644. w = NewWriter(nil)
  645. }
  646. var gots, wants [][]byte
  647. failed := false
  648. for i := 0; i <= n; i++ {
  649. buf := new(bytes.Buffer)
  650. w.Reset(buf)
  651. want := gold[:len(gold)*i/n]
  652. if _, err := w.Write(want); err != nil {
  653. t.Errorf("#%d: Write: %v", i, err)
  654. failed = true
  655. continue
  656. }
  657. if buffered {
  658. if err := w.Flush(); err != nil {
  659. t.Errorf("#%d: Flush: %v", i, err)
  660. failed = true
  661. continue
  662. }
  663. }
  664. got, err := ioutil.ReadAll(NewReader(buf))
  665. if err != nil {
  666. t.Errorf("#%d: ReadAll: %v", i, err)
  667. failed = true
  668. continue
  669. }
  670. gots = append(gots, got)
  671. wants = append(wants, want)
  672. }
  673. if failed {
  674. continue
  675. }
  676. for i := range gots {
  677. if err := cmp(gots[i], wants[i]); err != nil {
  678. t.Errorf("#%d: %v", i, err)
  679. }
  680. }
  681. }
  682. }
  683. func TestWriterResetWithoutFlush(t *testing.T) {
  684. buf0 := new(bytes.Buffer)
  685. buf1 := new(bytes.Buffer)
  686. w := NewBufferedWriter(buf0)
  687. if _, err := w.Write([]byte("xxx")); err != nil {
  688. t.Fatalf("Write #0: %v", err)
  689. }
  690. // Note that we don't Flush the Writer before calling Reset.
  691. w.Reset(buf1)
  692. if _, err := w.Write([]byte("yyy")); err != nil {
  693. t.Fatalf("Write #1: %v", err)
  694. }
  695. if err := w.Flush(); err != nil {
  696. t.Fatalf("Flush: %v", err)
  697. }
  698. got, err := ioutil.ReadAll(NewReader(buf1))
  699. if err != nil {
  700. t.Fatalf("ReadAll: %v", err)
  701. }
  702. if err := cmp(got, []byte("yyy")); err != nil {
  703. t.Fatal(err)
  704. }
  705. }
  706. type writeCounter int
  707. func (c *writeCounter) Write(p []byte) (int, error) {
  708. *c++
  709. return len(p), nil
  710. }
  711. // TestNumUnderlyingWrites tests that each Writer flush only makes one or two
  712. // Write calls on its underlying io.Writer, depending on whether or not the
  713. // flushed buffer was compressible.
  714. func TestNumUnderlyingWrites(t *testing.T) {
  715. testCases := []struct {
  716. input []byte
  717. want int
  718. }{
  719. {bytes.Repeat([]byte{'x'}, 100), 1},
  720. {bytes.Repeat([]byte{'y'}, 100), 1},
  721. {[]byte("ABCDEFGHIJKLMNOPQRST"), 2},
  722. }
  723. var c writeCounter
  724. w := NewBufferedWriter(&c)
  725. defer w.Close()
  726. for i, tc := range testCases {
  727. c = 0
  728. if _, err := w.Write(tc.input); err != nil {
  729. t.Errorf("#%d: Write: %v", i, err)
  730. continue
  731. }
  732. if err := w.Flush(); err != nil {
  733. t.Errorf("#%d: Flush: %v", i, err)
  734. continue
  735. }
  736. if int(c) != tc.want {
  737. t.Errorf("#%d: got %d underlying writes, want %d", i, c, tc.want)
  738. continue
  739. }
  740. }
  741. }
  742. func benchDecode(b *testing.B, src []byte) {
  743. encoded := Encode(nil, src)
  744. // Bandwidth is in amount of uncompressed data.
  745. b.SetBytes(int64(len(src)))
  746. b.ResetTimer()
  747. for i := 0; i < b.N; i++ {
  748. Decode(src, encoded)
  749. }
  750. }
  751. func benchEncode(b *testing.B, src []byte) {
  752. // Bandwidth is in amount of uncompressed data.
  753. b.SetBytes(int64(len(src)))
  754. dst := make([]byte, MaxEncodedLen(len(src)))
  755. b.ResetTimer()
  756. for i := 0; i < b.N; i++ {
  757. Encode(dst, src)
  758. }
  759. }
  760. func readFile(b testing.TB, filename string) []byte {
  761. src, err := ioutil.ReadFile(filename)
  762. if err != nil {
  763. b.Skipf("skipping benchmark: %v", err)
  764. }
  765. if len(src) == 0 {
  766. b.Fatalf("%s has zero length", filename)
  767. }
  768. return src
  769. }
  770. // expand returns a slice of length n containing repeated copies of src.
  771. func expand(src []byte, n int) []byte {
  772. dst := make([]byte, n)
  773. for x := dst; len(x) > 0; {
  774. i := copy(x, src)
  775. x = x[i:]
  776. }
  777. return dst
  778. }
  779. func benchWords(b *testing.B, n int, decode bool) {
  780. // Note: the file is OS-language dependent so the resulting values are not
  781. // directly comparable for non-US-English OS installations.
  782. data := expand(readFile(b, "/usr/share/dict/words"), n)
  783. if decode {
  784. benchDecode(b, data)
  785. } else {
  786. benchEncode(b, data)
  787. }
  788. }
  789. func BenchmarkWordsDecode1e1(b *testing.B) { benchWords(b, 1e1, true) }
  790. func BenchmarkWordsDecode1e2(b *testing.B) { benchWords(b, 1e2, true) }
  791. func BenchmarkWordsDecode1e3(b *testing.B) { benchWords(b, 1e3, true) }
  792. func BenchmarkWordsDecode1e4(b *testing.B) { benchWords(b, 1e4, true) }
  793. func BenchmarkWordsDecode1e5(b *testing.B) { benchWords(b, 1e5, true) }
  794. func BenchmarkWordsDecode1e6(b *testing.B) { benchWords(b, 1e6, true) }
  795. func BenchmarkWordsEncode1e1(b *testing.B) { benchWords(b, 1e1, false) }
  796. func BenchmarkWordsEncode1e2(b *testing.B) { benchWords(b, 1e2, false) }
  797. func BenchmarkWordsEncode1e3(b *testing.B) { benchWords(b, 1e3, false) }
  798. func BenchmarkWordsEncode1e4(b *testing.B) { benchWords(b, 1e4, false) }
  799. func BenchmarkWordsEncode1e5(b *testing.B) { benchWords(b, 1e5, false) }
  800. func BenchmarkWordsEncode1e6(b *testing.B) { benchWords(b, 1e6, false) }
  801. func BenchmarkRandomEncode(b *testing.B) {
  802. rng := rand.New(rand.NewSource(1))
  803. data := make([]byte, 1<<20)
  804. for i := range data {
  805. data[i] = uint8(rng.Intn(256))
  806. }
  807. benchEncode(b, data)
  808. }
  809. // testFiles' values are copied directly from
  810. // https://raw.githubusercontent.com/google/snappy/master/snappy_unittest.cc
  811. // The label field is unused in snappy-go.
  812. var testFiles = []struct {
  813. label string
  814. filename string
  815. sizeLimit int
  816. }{
  817. {"html", "html", 0},
  818. {"urls", "urls.10K", 0},
  819. {"jpg", "fireworks.jpeg", 0},
  820. {"jpg_200", "fireworks.jpeg", 200},
  821. {"pdf", "paper-100k.pdf", 0},
  822. {"html4", "html_x_4", 0},
  823. {"txt1", "alice29.txt", 0},
  824. {"txt2", "asyoulik.txt", 0},
  825. {"txt3", "lcet10.txt", 0},
  826. {"txt4", "plrabn12.txt", 0},
  827. {"pb", "geo.protodata", 0},
  828. {"gaviota", "kppkn.gtb", 0},
  829. }
  830. const (
  831. // The benchmark data files are at this canonical URL.
  832. benchURL = "https://raw.githubusercontent.com/google/snappy/master/testdata/"
  833. // They are copied to this local directory.
  834. benchDir = "testdata/bench"
  835. )
  836. func downloadBenchmarkFiles(b *testing.B, basename string) (errRet error) {
  837. filename := filepath.Join(benchDir, basename)
  838. if stat, err := os.Stat(filename); err == nil && stat.Size() != 0 {
  839. return nil
  840. }
  841. if !*download {
  842. b.Skipf("test data not found; skipping benchmark without the -download flag")
  843. }
  844. // Download the official snappy C++ implementation reference test data
  845. // files for benchmarking.
  846. if err := os.MkdirAll(benchDir, 0777); err != nil && !os.IsExist(err) {
  847. return fmt.Errorf("failed to create %s: %s", benchDir, err)
  848. }
  849. f, err := os.Create(filename)
  850. if err != nil {
  851. return fmt.Errorf("failed to create %s: %s", filename, err)
  852. }
  853. defer f.Close()
  854. defer func() {
  855. if errRet != nil {
  856. os.Remove(filename)
  857. }
  858. }()
  859. url := benchURL + basename
  860. resp, err := http.Get(url)
  861. if err != nil {
  862. return fmt.Errorf("failed to download %s: %s", url, err)
  863. }
  864. defer resp.Body.Close()
  865. if s := resp.StatusCode; s != http.StatusOK {
  866. return fmt.Errorf("downloading %s: HTTP status code %d (%s)", url, s, http.StatusText(s))
  867. }
  868. _, err = io.Copy(f, resp.Body)
  869. if err != nil {
  870. return fmt.Errorf("failed to download %s to %s: %s", url, filename, err)
  871. }
  872. return nil
  873. }
  874. func benchFile(b *testing.B, n int, decode bool) {
  875. if err := downloadBenchmarkFiles(b, testFiles[n].filename); err != nil {
  876. b.Fatalf("failed to download testdata: %s", err)
  877. }
  878. data := readFile(b, filepath.Join(benchDir, testFiles[n].filename))
  879. if n := testFiles[n].sizeLimit; 0 < n && n < len(data) {
  880. data = data[:n]
  881. }
  882. if decode {
  883. benchDecode(b, data)
  884. } else {
  885. benchEncode(b, data)
  886. }
  887. }
  888. // Naming convention is kept similar to what snappy's C++ implementation uses.
  889. func Benchmark_UFlat0(b *testing.B) { benchFile(b, 0, true) }
  890. func Benchmark_UFlat1(b *testing.B) { benchFile(b, 1, true) }
  891. func Benchmark_UFlat2(b *testing.B) { benchFile(b, 2, true) }
  892. func Benchmark_UFlat3(b *testing.B) { benchFile(b, 3, true) }
  893. func Benchmark_UFlat4(b *testing.B) { benchFile(b, 4, true) }
  894. func Benchmark_UFlat5(b *testing.B) { benchFile(b, 5, true) }
  895. func Benchmark_UFlat6(b *testing.B) { benchFile(b, 6, true) }
  896. func Benchmark_UFlat7(b *testing.B) { benchFile(b, 7, true) }
  897. func Benchmark_UFlat8(b *testing.B) { benchFile(b, 8, true) }
  898. func Benchmark_UFlat9(b *testing.B) { benchFile(b, 9, true) }
  899. func Benchmark_UFlat10(b *testing.B) { benchFile(b, 10, true) }
  900. func Benchmark_UFlat11(b *testing.B) { benchFile(b, 11, true) }
  901. func Benchmark_ZFlat0(b *testing.B) { benchFile(b, 0, false) }
  902. func Benchmark_ZFlat1(b *testing.B) { benchFile(b, 1, false) }
  903. func Benchmark_ZFlat2(b *testing.B) { benchFile(b, 2, false) }
  904. func Benchmark_ZFlat3(b *testing.B) { benchFile(b, 3, false) }
  905. func Benchmark_ZFlat4(b *testing.B) { benchFile(b, 4, false) }
  906. func Benchmark_ZFlat5(b *testing.B) { benchFile(b, 5, false) }
  907. func Benchmark_ZFlat6(b *testing.B) { benchFile(b, 6, false) }
  908. func Benchmark_ZFlat7(b *testing.B) { benchFile(b, 7, false) }
  909. func Benchmark_ZFlat8(b *testing.B) { benchFile(b, 8, false) }
  910. func Benchmark_ZFlat9(b *testing.B) { benchFile(b, 9, false) }
  911. func Benchmark_ZFlat10(b *testing.B) { benchFile(b, 10, false) }
  912. func Benchmark_ZFlat11(b *testing.B) { benchFile(b, 11, false) }