snappy_test.go 30 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065
  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. "os/exec"
  16. "path/filepath"
  17. "runtime"
  18. "strings"
  19. "testing"
  20. )
  21. var download = flag.Bool("download", false, "If true, download any missing files before running benchmarks")
  22. // goEncoderShouldMatchCppEncoder is whether to test that the algorithm used by
  23. // Go's encoder matches byte-for-byte what the C++ snappy encoder produces.
  24. // There is more than one valid encoding of any given input, and there is more
  25. // than one good algorithm along the frontier of trading off throughput for
  26. // output size. Nonetheless, we presume that the C++ encoder's algorithm is a
  27. // good one and has been tested on a wide range of inputs, so matching that
  28. // exactly should mean that the Go encoder's algorithm is also good, without
  29. // needing to gather our own corpus of test data.
  30. //
  31. // The exact algorithm used, though, is endianness-dependent, as it puns a
  32. // byte-pointer to a uint32-pointer to load and compare 4 bytes at a time. For
  33. // example, the "testdata/pi.txt.rawsnappy" file was generated by C++ code on a
  34. // little-endian system. The runtime package doesn't export endianness per se,
  35. // but we can restrict this match-C++ test to common little-endian systems.
  36. const goEncoderShouldMatchCppEncoder = runtime.GOARCH == "386" || runtime.GOARCH == "amd64"
  37. func TestMaxEncodedLenOfMaxBlockSize(t *testing.T) {
  38. got := maxEncodedLenOfMaxBlockSize
  39. want := MaxEncodedLen(maxBlockSize)
  40. if got != want {
  41. t.Fatalf("got %d, want %d", got, want)
  42. }
  43. }
  44. func cmp(a, b []byte) error {
  45. if bytes.Equal(a, b) {
  46. return nil
  47. }
  48. if len(a) != len(b) {
  49. return fmt.Errorf("got %d bytes, want %d", len(a), len(b))
  50. }
  51. for i := range a {
  52. if a[i] != b[i] {
  53. return fmt.Errorf("byte #%d: got 0x%02x, want 0x%02x", i, a[i], b[i])
  54. }
  55. }
  56. return nil
  57. }
  58. func roundtrip(b, ebuf, dbuf []byte) error {
  59. d, err := Decode(dbuf, Encode(ebuf, b))
  60. if err != nil {
  61. return fmt.Errorf("decoding error: %v", err)
  62. }
  63. if err := cmp(d, b); err != nil {
  64. return fmt.Errorf("roundtrip mismatch: %v", err)
  65. }
  66. return nil
  67. }
  68. func TestEmpty(t *testing.T) {
  69. if err := roundtrip(nil, nil, nil); err != nil {
  70. t.Fatal(err)
  71. }
  72. }
  73. func TestSmallCopy(t *testing.T) {
  74. for _, ebuf := range [][]byte{nil, make([]byte, 20), make([]byte, 64)} {
  75. for _, dbuf := range [][]byte{nil, make([]byte, 20), make([]byte, 64)} {
  76. for i := 0; i < 32; i++ {
  77. s := "aaaa" + strings.Repeat("b", i) + "aaaabbbb"
  78. if err := roundtrip([]byte(s), ebuf, dbuf); err != nil {
  79. t.Errorf("len(ebuf)=%d, len(dbuf)=%d, i=%d: %v", len(ebuf), len(dbuf), i, err)
  80. }
  81. }
  82. }
  83. }
  84. }
  85. func TestSmallRand(t *testing.T) {
  86. rng := rand.New(rand.NewSource(1))
  87. for n := 1; n < 20000; n += 23 {
  88. b := make([]byte, n)
  89. for i := range b {
  90. b[i] = uint8(rng.Intn(256))
  91. }
  92. if err := roundtrip(b, nil, nil); err != nil {
  93. t.Fatal(err)
  94. }
  95. }
  96. }
  97. func TestSmallRegular(t *testing.T) {
  98. for n := 1; n < 20000; n += 23 {
  99. b := make([]byte, n)
  100. for i := range b {
  101. b[i] = uint8(i%10 + 'a')
  102. }
  103. if err := roundtrip(b, nil, nil); err != nil {
  104. t.Fatal(err)
  105. }
  106. }
  107. }
  108. func TestInvalidVarint(t *testing.T) {
  109. testCases := []struct {
  110. desc string
  111. input string
  112. }{{
  113. "invalid varint, final byte has continuation bit set",
  114. "\xff",
  115. }, {
  116. "invalid varint, value overflows uint64",
  117. "\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\x00",
  118. }, {
  119. // https://github.com/google/snappy/blob/master/format_description.txt
  120. // says that "the stream starts with the uncompressed length [as a
  121. // varint] (up to a maximum of 2^32 - 1)".
  122. "valid varint (as uint64), but value overflows uint32",
  123. "\x80\x80\x80\x80\x10",
  124. }}
  125. for _, tc := range testCases {
  126. input := []byte(tc.input)
  127. if _, err := DecodedLen(input); err != ErrCorrupt {
  128. t.Errorf("%s: DecodedLen: got %v, want ErrCorrupt", tc.desc, err)
  129. }
  130. if _, err := Decode(nil, input); err != ErrCorrupt {
  131. t.Errorf("%s: Decode: got %v, want ErrCorrupt", tc.desc, err)
  132. }
  133. }
  134. }
  135. func TestDecode(t *testing.T) {
  136. lit40Bytes := make([]byte, 40)
  137. for i := range lit40Bytes {
  138. lit40Bytes[i] = byte(i)
  139. }
  140. lit40 := string(lit40Bytes)
  141. testCases := []struct {
  142. desc string
  143. input string
  144. want string
  145. wantErr error
  146. }{{
  147. `decodedLen=0; valid input`,
  148. "\x00",
  149. "",
  150. nil,
  151. }, {
  152. `decodedLen=3; tagLiteral, 0-byte length; length=3; valid input`,
  153. "\x03" + "\x08\xff\xff\xff",
  154. "\xff\xff\xff",
  155. nil,
  156. }, {
  157. `decodedLen=2; tagLiteral, 0-byte length; length=3; not enough dst bytes`,
  158. "\x02" + "\x08\xff\xff\xff",
  159. "",
  160. ErrCorrupt,
  161. }, {
  162. `decodedLen=3; tagLiteral, 0-byte length; length=3; not enough src bytes`,
  163. "\x03" + "\x08\xff\xff",
  164. "",
  165. ErrCorrupt,
  166. }, {
  167. `decodedLen=40; tagLiteral, 0-byte length; length=40; valid input`,
  168. "\x28" + "\x9c" + lit40,
  169. lit40,
  170. nil,
  171. }, {
  172. `decodedLen=1; tagLiteral, 1-byte length; not enough length bytes`,
  173. "\x01" + "\xf0",
  174. "",
  175. ErrCorrupt,
  176. }, {
  177. `decodedLen=3; tagLiteral, 1-byte length; length=3; valid input`,
  178. "\x03" + "\xf0\x02\xff\xff\xff",
  179. "\xff\xff\xff",
  180. nil,
  181. }, {
  182. `decodedLen=1; tagLiteral, 2-byte length; not enough length bytes`,
  183. "\x01" + "\xf4\x00",
  184. "",
  185. ErrCorrupt,
  186. }, {
  187. `decodedLen=3; tagLiteral, 2-byte length; length=3; valid input`,
  188. "\x03" + "\xf4\x02\x00\xff\xff\xff",
  189. "\xff\xff\xff",
  190. nil,
  191. }, {
  192. `decodedLen=1; tagLiteral, 3-byte length; not enough length bytes`,
  193. "\x01" + "\xf8\x00\x00",
  194. "",
  195. ErrCorrupt,
  196. }, {
  197. `decodedLen=3; tagLiteral, 3-byte length; length=3; valid input`,
  198. "\x03" + "\xf8\x02\x00\x00\xff\xff\xff",
  199. "\xff\xff\xff",
  200. nil,
  201. }, {
  202. `decodedLen=1; tagLiteral, 4-byte length; not enough length bytes`,
  203. "\x01" + "\xfc\x00\x00\x00",
  204. "",
  205. ErrCorrupt,
  206. }, {
  207. `decodedLen=1; tagLiteral, 4-byte length; length=3; not enough dst bytes`,
  208. "\x01" + "\xfc\x02\x00\x00\x00\xff\xff\xff",
  209. "",
  210. ErrCorrupt,
  211. }, {
  212. `decodedLen=4; tagLiteral, 4-byte length; length=3; not enough src bytes`,
  213. "\x04" + "\xfc\x02\x00\x00\x00\xff",
  214. "",
  215. ErrCorrupt,
  216. }, {
  217. `decodedLen=3; tagLiteral, 4-byte length; length=3; valid input`,
  218. "\x03" + "\xfc\x02\x00\x00\x00\xff\xff\xff",
  219. "\xff\xff\xff",
  220. nil,
  221. }, {
  222. `decodedLen=4; tagCopy1, 1 extra length|offset byte; not enough extra bytes`,
  223. "\x04" + "\x01",
  224. "",
  225. ErrCorrupt,
  226. }, {
  227. `decodedLen=4; tagCopy2, 2 extra length|offset bytes; not enough extra bytes`,
  228. "\x04" + "\x02\x00",
  229. "",
  230. ErrCorrupt,
  231. }, {
  232. `decodedLen=4; tagCopy4; unsupported COPY_4 tag`,
  233. "\x04" + "\x03\x00\x00\x00\x00",
  234. "",
  235. errUnsupportedCopy4Tag,
  236. }, {
  237. `decodedLen=4; tagLiteral (4 bytes "abcd"); valid input`,
  238. "\x04" + "\x0cabcd",
  239. "abcd",
  240. nil,
  241. }, {
  242. `decodedLen=13; tagLiteral (4 bytes "abcd"); tagCopy1; length=9 offset=4; valid input`,
  243. "\x0d" + "\x0cabcd" + "\x15\x04",
  244. "abcdabcdabcda",
  245. nil,
  246. }, {
  247. `decodedLen=8; tagLiteral (4 bytes "abcd"); tagCopy1; length=4 offset=4; valid input`,
  248. "\x08" + "\x0cabcd" + "\x01\x04",
  249. "abcdabcd",
  250. nil,
  251. }, {
  252. `decodedLen=8; tagLiteral (4 bytes "abcd"); tagCopy1; length=4 offset=2; valid input`,
  253. "\x08" + "\x0cabcd" + "\x01\x02",
  254. "abcdcdcd",
  255. nil,
  256. }, {
  257. `decodedLen=8; tagLiteral (4 bytes "abcd"); tagCopy1; length=4 offset=1; valid input`,
  258. "\x08" + "\x0cabcd" + "\x01\x01",
  259. "abcddddd",
  260. nil,
  261. }, {
  262. `decodedLen=8; tagLiteral (4 bytes "abcd"); tagCopy1; length=4 offset=0; zero offset`,
  263. "\x08" + "\x0cabcd" + "\x01\x00",
  264. "",
  265. ErrCorrupt,
  266. }, {
  267. `decodedLen=9; tagLiteral (4 bytes "abcd"); tagCopy1; length=4 offset=4; inconsistent dLen`,
  268. "\x09" + "\x0cabcd" + "\x01\x04",
  269. "",
  270. ErrCorrupt,
  271. }, {
  272. `decodedLen=8; tagLiteral (4 bytes "abcd"); tagCopy1; length=4 offset=5; offset too large`,
  273. "\x08" + "\x0cabcd" + "\x01\x05",
  274. "",
  275. ErrCorrupt,
  276. }, {
  277. `decodedLen=7; tagLiteral (4 bytes "abcd"); tagCopy1; length=4 offset=4; length too large`,
  278. "\x07" + "\x0cabcd" + "\x01\x04",
  279. "",
  280. ErrCorrupt,
  281. }, {
  282. `decodedLen=6; tagLiteral (4 bytes "abcd"); tagCopy2; length=2 offset=3; valid input`,
  283. "\x06" + "\x0cabcd" + "\x06\x03\x00",
  284. "abcdbc",
  285. nil,
  286. }}
  287. const (
  288. // notPresentXxx defines a range of byte values [0xa0, 0xc5) that are
  289. // not present in either the input or the output. It is written to dBuf
  290. // to check that Decode does not write bytes past the end of
  291. // dBuf[:dLen].
  292. //
  293. // The magic number 37 was chosen because it is prime. A more 'natural'
  294. // number like 32 might lead to a false negative if, for example, a
  295. // byte was incorrectly copied 4*8 bytes later.
  296. notPresentBase = 0xa0
  297. notPresentLen = 37
  298. )
  299. var dBuf [100]byte
  300. loop:
  301. for i, tc := range testCases {
  302. input := []byte(tc.input)
  303. for _, x := range input {
  304. if notPresentBase <= x && x < notPresentBase+notPresentLen {
  305. t.Errorf("#%d (%s): input shouldn't contain %#02x\ninput: % x", i, tc.desc, x, input)
  306. continue loop
  307. }
  308. }
  309. dLen, n := binary.Uvarint(input)
  310. if n <= 0 {
  311. t.Errorf("#%d (%s): invalid varint-encoded dLen", i, tc.desc)
  312. continue
  313. }
  314. if dLen > uint64(len(dBuf)) {
  315. t.Errorf("#%d (%s): dLen %d is too large", i, tc.desc, dLen)
  316. continue
  317. }
  318. for j := range dBuf {
  319. dBuf[j] = byte(notPresentBase + j%notPresentLen)
  320. }
  321. g, gotErr := Decode(dBuf[:], input)
  322. if got := string(g); got != tc.want || gotErr != tc.wantErr {
  323. t.Errorf("#%d (%s):\ngot %q, %v\nwant %q, %v",
  324. i, tc.desc, got, gotErr, tc.want, tc.wantErr)
  325. continue
  326. }
  327. for j, x := range dBuf {
  328. if uint64(j) < dLen {
  329. continue
  330. }
  331. if w := byte(notPresentBase + j%notPresentLen); x != w {
  332. t.Errorf("#%d (%s): Decode overrun: dBuf[%d] was modified: got %#02x, want %#02x\ndBuf: % x",
  333. i, tc.desc, j, x, w, dBuf)
  334. continue loop
  335. }
  336. }
  337. }
  338. }
  339. // TestDecodeLengthOffset tests decoding an encoding of the form literal +
  340. // copy-length-offset + literal. For example: "abcdefghijkl" + "efghij" + "AB".
  341. func TestDecodeLengthOffset(t *testing.T) {
  342. const (
  343. prefix = "abcdefghijklmnopqr"
  344. suffix = "ABCDEFGHIJKLMNOPQR"
  345. // notPresentXxx defines a range of byte values [0xa0, 0xc5) that are
  346. // not present in either the input or the output. It is written to
  347. // gotBuf to check that Decode does not write bytes past the end of
  348. // gotBuf[:totalLen].
  349. //
  350. // The magic number 37 was chosen because it is prime. A more 'natural'
  351. // number like 32 might lead to a false negative if, for example, a
  352. // byte was incorrectly copied 4*8 bytes later.
  353. notPresentBase = 0xa0
  354. notPresentLen = 37
  355. )
  356. var gotBuf, wantBuf, inputBuf [128]byte
  357. for length := 1; length <= 18; length++ {
  358. for offset := 1; offset <= 18; offset++ {
  359. loop:
  360. for suffixLen := 0; suffixLen <= 18; suffixLen++ {
  361. totalLen := len(prefix) + length + suffixLen
  362. inputLen := binary.PutUvarint(inputBuf[:], uint64(totalLen))
  363. inputBuf[inputLen] = tagLiteral + 4*byte(len(prefix)-1)
  364. inputLen++
  365. inputLen += copy(inputBuf[inputLen:], prefix)
  366. inputBuf[inputLen+0] = tagCopy2 + 4*byte(length-1)
  367. inputBuf[inputLen+1] = byte(offset)
  368. inputBuf[inputLen+2] = 0x00
  369. inputLen += 3
  370. if suffixLen > 0 {
  371. inputBuf[inputLen] = tagLiteral + 4*byte(suffixLen-1)
  372. inputLen++
  373. inputLen += copy(inputBuf[inputLen:], suffix[:suffixLen])
  374. }
  375. input := inputBuf[:inputLen]
  376. for i := range gotBuf {
  377. gotBuf[i] = byte(notPresentBase + i%notPresentLen)
  378. }
  379. got, err := Decode(gotBuf[:], input)
  380. if err != nil {
  381. t.Errorf("length=%d, offset=%d; suffixLen=%d: %v", length, offset, suffixLen, err)
  382. continue
  383. }
  384. wantLen := 0
  385. wantLen += copy(wantBuf[wantLen:], prefix)
  386. for i := 0; i < length; i++ {
  387. wantBuf[wantLen] = wantBuf[wantLen-offset]
  388. wantLen++
  389. }
  390. wantLen += copy(wantBuf[wantLen:], suffix[:suffixLen])
  391. want := wantBuf[:wantLen]
  392. for _, x := range input {
  393. if notPresentBase <= x && x < notPresentBase+notPresentLen {
  394. t.Errorf("length=%d, offset=%d; suffixLen=%d: input shouldn't contain %#02x\ninput: % x",
  395. length, offset, suffixLen, x, input)
  396. continue loop
  397. }
  398. }
  399. for i, x := range gotBuf {
  400. if i < totalLen {
  401. continue
  402. }
  403. if w := byte(notPresentBase + i%notPresentLen); x != w {
  404. t.Errorf("length=%d, offset=%d; suffixLen=%d; totalLen=%d: "+
  405. "Decode overrun: gotBuf[%d] was modified: got %#02x, want %#02x\ngotBuf: % x",
  406. length, offset, suffixLen, totalLen, i, x, w, gotBuf)
  407. continue loop
  408. }
  409. }
  410. for _, x := range want {
  411. if notPresentBase <= x && x < notPresentBase+notPresentLen {
  412. t.Errorf("length=%d, offset=%d; suffixLen=%d: want shouldn't contain %#02x\nwant: % x",
  413. length, offset, suffixLen, x, want)
  414. continue loop
  415. }
  416. }
  417. if !bytes.Equal(got, want) {
  418. t.Errorf("length=%d, offset=%d; suffixLen=%d:\ninput % x\ngot % x\nwant % x",
  419. length, offset, suffixLen, input, got, want)
  420. continue
  421. }
  422. }
  423. }
  424. }
  425. }
  426. func TestDecodeGoldenInput(t *testing.T) {
  427. src, err := ioutil.ReadFile("testdata/pi.txt.rawsnappy")
  428. if err != nil {
  429. t.Fatalf("ReadFile: %v", err)
  430. }
  431. got, err := Decode(nil, src)
  432. if err != nil {
  433. t.Fatalf("Decode: %v", err)
  434. }
  435. want, err := ioutil.ReadFile("testdata/pi.txt")
  436. if err != nil {
  437. t.Fatalf("ReadFile: %v", err)
  438. }
  439. if err := cmp(got, want); err != nil {
  440. t.Fatal(err)
  441. }
  442. }
  443. func TestEncodeGoldenInput(t *testing.T) {
  444. if !goEncoderShouldMatchCppEncoder {
  445. t.Skipf("skipping testing that the encoding is byte-for-byte identical to C++: GOARCH=%s", runtime.GOARCH)
  446. }
  447. src, err := ioutil.ReadFile("testdata/pi.txt")
  448. if err != nil {
  449. t.Fatalf("ReadFile: %v", err)
  450. }
  451. got := Encode(nil, src)
  452. want, err := ioutil.ReadFile("testdata/pi.txt.rawsnappy")
  453. if err != nil {
  454. t.Fatalf("ReadFile: %v", err)
  455. }
  456. if err := cmp(got, want); err != nil {
  457. t.Fatal(err)
  458. }
  459. }
  460. func TestSameEncodingAsCpp(t *testing.T) {
  461. if !goEncoderShouldMatchCppEncoder {
  462. t.Skipf("skipping testing that the encoding is byte-for-byte identical to C++: GOARCH=%s", runtime.GOARCH)
  463. }
  464. const cmdName = "cmd/snappytool/snappytool"
  465. _, err := os.Stat(cmdName)
  466. if err != nil {
  467. t.Skipf("could not find snappytool: %v", err)
  468. }
  469. for i, tf := range testFiles {
  470. if err := downloadBenchmarkFiles(t, tf.filename); err != nil {
  471. t.Fatalf("failed to download testdata: %s", err)
  472. }
  473. data := readFile(t, filepath.Join(benchDir, tf.filename))
  474. if n := tf.sizeLimit; 0 < n && n < len(data) {
  475. data = data[:n]
  476. }
  477. got := Encode(nil, data)
  478. cmd := exec.Command(cmdName, "-e")
  479. cmd.Stdin = bytes.NewReader(data)
  480. want, err := cmd.Output()
  481. if err != nil {
  482. t.Fatalf("could not run snappytool: %v", err)
  483. }
  484. if err := cmp(got, want); err != nil {
  485. t.Errorf("i=%d: %v", i, err)
  486. }
  487. }
  488. }
  489. // TestSlowForwardCopyOverrun tests the "expand the pattern" algorithm
  490. // described in decode_amd64.s and its claim of a 10 byte overrun worst case.
  491. func TestSlowForwardCopyOverrun(t *testing.T) {
  492. const base = 100
  493. for length := 1; length < 18; length++ {
  494. for offset := 1; offset < 18; offset++ {
  495. highWaterMark := base
  496. d := base
  497. l := length
  498. o := offset
  499. // makeOffsetAtLeast8
  500. for o < 8 {
  501. if end := d + 8; highWaterMark < end {
  502. highWaterMark = end
  503. }
  504. l -= o
  505. d += o
  506. o += o
  507. }
  508. // fixUpSlowForwardCopy
  509. a := d
  510. d += l
  511. // finishSlowForwardCopy
  512. for l > 0 {
  513. if end := a + 8; highWaterMark < end {
  514. highWaterMark = end
  515. }
  516. a += 8
  517. l -= 8
  518. }
  519. dWant := base + length
  520. overrun := highWaterMark - dWant
  521. if d != dWant || overrun < 0 || 10 < overrun {
  522. t.Errorf("length=%d, offset=%d: d and overrun: got (%d, %d), want (%d, something in [0, 10])",
  523. length, offset, d, overrun, dWant)
  524. }
  525. }
  526. }
  527. }
  528. // TestEncodeNoiseThenRepeats encodes input for which the first half is very
  529. // incompressible and the second half is very compressible. The encoded form's
  530. // length should be closer to 50% of the original length than 100%.
  531. func TestEncodeNoiseThenRepeats(t *testing.T) {
  532. for _, origLen := range []int{32 * 1024, 256 * 1024, 2048 * 1024} {
  533. src := make([]byte, origLen)
  534. rng := rand.New(rand.NewSource(1))
  535. firstHalf, secondHalf := src[:origLen/2], src[origLen/2:]
  536. for i := range firstHalf {
  537. firstHalf[i] = uint8(rng.Intn(256))
  538. }
  539. for i := range secondHalf {
  540. secondHalf[i] = uint8(i >> 8)
  541. }
  542. dst := Encode(nil, src)
  543. if got, want := len(dst), origLen*3/4; got >= want {
  544. t.Errorf("origLen=%d: got %d encoded bytes, want less than %d", origLen, got, want)
  545. }
  546. }
  547. }
  548. func TestFramingFormat(t *testing.T) {
  549. // src is comprised of alternating 1e5-sized sequences of random
  550. // (incompressible) bytes and repeated (compressible) bytes. 1e5 was chosen
  551. // because it is larger than maxBlockSize (64k).
  552. src := make([]byte, 1e6)
  553. rng := rand.New(rand.NewSource(1))
  554. for i := 0; i < 10; i++ {
  555. if i%2 == 0 {
  556. for j := 0; j < 1e5; j++ {
  557. src[1e5*i+j] = uint8(rng.Intn(256))
  558. }
  559. } else {
  560. for j := 0; j < 1e5; j++ {
  561. src[1e5*i+j] = uint8(i)
  562. }
  563. }
  564. }
  565. buf := new(bytes.Buffer)
  566. if _, err := NewWriter(buf).Write(src); err != nil {
  567. t.Fatalf("Write: encoding: %v", err)
  568. }
  569. dst, err := ioutil.ReadAll(NewReader(buf))
  570. if err != nil {
  571. t.Fatalf("ReadAll: decoding: %v", err)
  572. }
  573. if err := cmp(dst, src); err != nil {
  574. t.Fatal(err)
  575. }
  576. }
  577. func TestWriterGoldenOutput(t *testing.T) {
  578. buf := new(bytes.Buffer)
  579. w := NewBufferedWriter(buf)
  580. defer w.Close()
  581. w.Write([]byte("abcd")) // Not compressible.
  582. w.Flush()
  583. w.Write(bytes.Repeat([]byte{'A'}, 150)) // Compressible.
  584. w.Flush()
  585. // The next chunk is also compressible, but a naive, greedy encoding of the
  586. // overall length 67 copy as a length 64 copy (the longest expressible as a
  587. // tagCopy1 or tagCopy2) plus a length 3 remainder would be two 3-byte
  588. // tagCopy2 tags (6 bytes), since the minimum length for a tagCopy1 is 4
  589. // bytes. Instead, we could do it shorter, in 5 bytes: a 3-byte tagCopy2
  590. // (of length 60) and a 2-byte tagCopy1 (of length 7).
  591. w.Write(bytes.Repeat([]byte{'B'}, 68))
  592. w.Flush()
  593. got := buf.String()
  594. want := strings.Join([]string{
  595. magicChunk,
  596. "\x01\x08\x00\x00", // Uncompressed chunk, 8 bytes long (including 4 byte checksum).
  597. "\x68\x10\xe6\xb6", // Checksum.
  598. "\x61\x62\x63\x64", // Uncompressed payload: "abcd".
  599. "\x00\x11\x00\x00", // Compressed chunk, 17 bytes long (including 4 byte checksum).
  600. "\x5f\xeb\xf2\x10", // Checksum.
  601. "\x96\x01", // Compressed payload: Uncompressed length (varint encoded): 150.
  602. "\x00\x41", // Compressed payload: tagLiteral, length=1, "A".
  603. "\xfe\x01\x00", // Compressed payload: tagCopy2, length=64, offset=1.
  604. "\xfe\x01\x00", // Compressed payload: tagCopy2, length=64, offset=1.
  605. "\x52\x01\x00", // Compressed payload: tagCopy2, length=21, offset=1.
  606. "\x00\x0c\x00\x00", // Compressed chunk, 12 bytes long (including 4 byte checksum).
  607. "\x27\x50\xe4\x4e", // Checksum.
  608. "\x44", // Compressed payload: Uncompressed length (varint encoded): 68.
  609. "\x00\x42", // Compressed payload: tagLiteral, length=1, "B".
  610. "\xee\x01\x00", // Compressed payload: tagCopy2, length=60, offset=1.
  611. "\x0d\x01", // Compressed payload: tagCopy1, length=7, offset=1.
  612. }, "")
  613. if got != want {
  614. t.Fatalf("\ngot: % x\nwant: % x", got, want)
  615. }
  616. }
  617. func TestNewBufferedWriter(t *testing.T) {
  618. // Test all 32 possible sub-sequences of these 5 input slices.
  619. //
  620. // Their lengths sum to 400,000, which is over 6 times the Writer ibuf
  621. // capacity: 6 * maxBlockSize is 393,216.
  622. inputs := [][]byte{
  623. bytes.Repeat([]byte{'a'}, 40000),
  624. bytes.Repeat([]byte{'b'}, 150000),
  625. bytes.Repeat([]byte{'c'}, 60000),
  626. bytes.Repeat([]byte{'d'}, 120000),
  627. bytes.Repeat([]byte{'e'}, 30000),
  628. }
  629. loop:
  630. for i := 0; i < 1<<uint(len(inputs)); i++ {
  631. var want []byte
  632. buf := new(bytes.Buffer)
  633. w := NewBufferedWriter(buf)
  634. for j, input := range inputs {
  635. if i&(1<<uint(j)) == 0 {
  636. continue
  637. }
  638. if _, err := w.Write(input); err != nil {
  639. t.Errorf("i=%#02x: j=%d: Write: %v", i, j, err)
  640. continue loop
  641. }
  642. want = append(want, input...)
  643. }
  644. if err := w.Close(); err != nil {
  645. t.Errorf("i=%#02x: Close: %v", i, err)
  646. continue
  647. }
  648. got, err := ioutil.ReadAll(NewReader(buf))
  649. if err != nil {
  650. t.Errorf("i=%#02x: ReadAll: %v", i, err)
  651. continue
  652. }
  653. if err := cmp(got, want); err != nil {
  654. t.Errorf("i=%#02x: %v", i, err)
  655. continue
  656. }
  657. }
  658. }
  659. func TestFlush(t *testing.T) {
  660. buf := new(bytes.Buffer)
  661. w := NewBufferedWriter(buf)
  662. defer w.Close()
  663. if _, err := w.Write(bytes.Repeat([]byte{'x'}, 20)); err != nil {
  664. t.Fatalf("Write: %v", err)
  665. }
  666. if n := buf.Len(); n != 0 {
  667. t.Fatalf("before Flush: %d bytes were written to the underlying io.Writer, want 0", n)
  668. }
  669. if err := w.Flush(); err != nil {
  670. t.Fatalf("Flush: %v", err)
  671. }
  672. if n := buf.Len(); n == 0 {
  673. t.Fatalf("after Flush: %d bytes were written to the underlying io.Writer, want non-0", n)
  674. }
  675. }
  676. func TestReaderReset(t *testing.T) {
  677. gold := bytes.Repeat([]byte("All that is gold does not glitter,\n"), 10000)
  678. buf := new(bytes.Buffer)
  679. if _, err := NewWriter(buf).Write(gold); err != nil {
  680. t.Fatalf("Write: %v", err)
  681. }
  682. encoded, invalid, partial := buf.String(), "invalid", "partial"
  683. r := NewReader(nil)
  684. for i, s := range []string{encoded, invalid, partial, encoded, partial, invalid, encoded, encoded} {
  685. if s == partial {
  686. r.Reset(strings.NewReader(encoded))
  687. if _, err := r.Read(make([]byte, 101)); err != nil {
  688. t.Errorf("#%d: %v", i, err)
  689. continue
  690. }
  691. continue
  692. }
  693. r.Reset(strings.NewReader(s))
  694. got, err := ioutil.ReadAll(r)
  695. switch s {
  696. case encoded:
  697. if err != nil {
  698. t.Errorf("#%d: %v", i, err)
  699. continue
  700. }
  701. if err := cmp(got, gold); err != nil {
  702. t.Errorf("#%d: %v", i, err)
  703. continue
  704. }
  705. case invalid:
  706. if err == nil {
  707. t.Errorf("#%d: got nil error, want non-nil", i)
  708. continue
  709. }
  710. }
  711. }
  712. }
  713. func TestWriterReset(t *testing.T) {
  714. gold := bytes.Repeat([]byte("Not all those who wander are lost;\n"), 10000)
  715. const n = 20
  716. for _, buffered := range []bool{false, true} {
  717. var w *Writer
  718. if buffered {
  719. w = NewBufferedWriter(nil)
  720. defer w.Close()
  721. } else {
  722. w = NewWriter(nil)
  723. }
  724. var gots, wants [][]byte
  725. failed := false
  726. for i := 0; i <= n; i++ {
  727. buf := new(bytes.Buffer)
  728. w.Reset(buf)
  729. want := gold[:len(gold)*i/n]
  730. if _, err := w.Write(want); err != nil {
  731. t.Errorf("#%d: Write: %v", i, err)
  732. failed = true
  733. continue
  734. }
  735. if buffered {
  736. if err := w.Flush(); err != nil {
  737. t.Errorf("#%d: Flush: %v", i, err)
  738. failed = true
  739. continue
  740. }
  741. }
  742. got, err := ioutil.ReadAll(NewReader(buf))
  743. if err != nil {
  744. t.Errorf("#%d: ReadAll: %v", i, err)
  745. failed = true
  746. continue
  747. }
  748. gots = append(gots, got)
  749. wants = append(wants, want)
  750. }
  751. if failed {
  752. continue
  753. }
  754. for i := range gots {
  755. if err := cmp(gots[i], wants[i]); err != nil {
  756. t.Errorf("#%d: %v", i, err)
  757. }
  758. }
  759. }
  760. }
  761. func TestWriterResetWithoutFlush(t *testing.T) {
  762. buf0 := new(bytes.Buffer)
  763. buf1 := new(bytes.Buffer)
  764. w := NewBufferedWriter(buf0)
  765. if _, err := w.Write([]byte("xxx")); err != nil {
  766. t.Fatalf("Write #0: %v", err)
  767. }
  768. // Note that we don't Flush the Writer before calling Reset.
  769. w.Reset(buf1)
  770. if _, err := w.Write([]byte("yyy")); err != nil {
  771. t.Fatalf("Write #1: %v", err)
  772. }
  773. if err := w.Flush(); err != nil {
  774. t.Fatalf("Flush: %v", err)
  775. }
  776. got, err := ioutil.ReadAll(NewReader(buf1))
  777. if err != nil {
  778. t.Fatalf("ReadAll: %v", err)
  779. }
  780. if err := cmp(got, []byte("yyy")); err != nil {
  781. t.Fatal(err)
  782. }
  783. }
  784. type writeCounter int
  785. func (c *writeCounter) Write(p []byte) (int, error) {
  786. *c++
  787. return len(p), nil
  788. }
  789. // TestNumUnderlyingWrites tests that each Writer flush only makes one or two
  790. // Write calls on its underlying io.Writer, depending on whether or not the
  791. // flushed buffer was compressible.
  792. func TestNumUnderlyingWrites(t *testing.T) {
  793. testCases := []struct {
  794. input []byte
  795. want int
  796. }{
  797. {bytes.Repeat([]byte{'x'}, 100), 1},
  798. {bytes.Repeat([]byte{'y'}, 100), 1},
  799. {[]byte("ABCDEFGHIJKLMNOPQRST"), 2},
  800. }
  801. var c writeCounter
  802. w := NewBufferedWriter(&c)
  803. defer w.Close()
  804. for i, tc := range testCases {
  805. c = 0
  806. if _, err := w.Write(tc.input); err != nil {
  807. t.Errorf("#%d: Write: %v", i, err)
  808. continue
  809. }
  810. if err := w.Flush(); err != nil {
  811. t.Errorf("#%d: Flush: %v", i, err)
  812. continue
  813. }
  814. if int(c) != tc.want {
  815. t.Errorf("#%d: got %d underlying writes, want %d", i, c, tc.want)
  816. continue
  817. }
  818. }
  819. }
  820. func benchDecode(b *testing.B, src []byte) {
  821. encoded := Encode(nil, src)
  822. // Bandwidth is in amount of uncompressed data.
  823. b.SetBytes(int64(len(src)))
  824. b.ResetTimer()
  825. for i := 0; i < b.N; i++ {
  826. Decode(src, encoded)
  827. }
  828. }
  829. func benchEncode(b *testing.B, src []byte) {
  830. // Bandwidth is in amount of uncompressed data.
  831. b.SetBytes(int64(len(src)))
  832. dst := make([]byte, MaxEncodedLen(len(src)))
  833. b.ResetTimer()
  834. for i := 0; i < b.N; i++ {
  835. Encode(dst, src)
  836. }
  837. }
  838. func testOrBenchmark(b testing.TB) string {
  839. if _, ok := b.(*testing.B); ok {
  840. return "benchmark"
  841. }
  842. return "test"
  843. }
  844. func readFile(b testing.TB, filename string) []byte {
  845. src, err := ioutil.ReadFile(filename)
  846. if err != nil {
  847. b.Skipf("skipping %s: %v", testOrBenchmark(b), err)
  848. }
  849. if len(src) == 0 {
  850. b.Fatalf("%s has zero length", filename)
  851. }
  852. return src
  853. }
  854. // expand returns a slice of length n containing repeated copies of src.
  855. func expand(src []byte, n int) []byte {
  856. dst := make([]byte, n)
  857. for x := dst; len(x) > 0; {
  858. i := copy(x, src)
  859. x = x[i:]
  860. }
  861. return dst
  862. }
  863. func benchWords(b *testing.B, n int, decode bool) {
  864. // Note: the file is OS-language dependent so the resulting values are not
  865. // directly comparable for non-US-English OS installations.
  866. data := expand(readFile(b, "/usr/share/dict/words"), n)
  867. if decode {
  868. benchDecode(b, data)
  869. } else {
  870. benchEncode(b, data)
  871. }
  872. }
  873. func BenchmarkWordsDecode1e1(b *testing.B) { benchWords(b, 1e1, true) }
  874. func BenchmarkWordsDecode1e2(b *testing.B) { benchWords(b, 1e2, true) }
  875. func BenchmarkWordsDecode1e3(b *testing.B) { benchWords(b, 1e3, true) }
  876. func BenchmarkWordsDecode1e4(b *testing.B) { benchWords(b, 1e4, true) }
  877. func BenchmarkWordsDecode1e5(b *testing.B) { benchWords(b, 1e5, true) }
  878. func BenchmarkWordsDecode1e6(b *testing.B) { benchWords(b, 1e6, true) }
  879. func BenchmarkWordsEncode1e1(b *testing.B) { benchWords(b, 1e1, false) }
  880. func BenchmarkWordsEncode1e2(b *testing.B) { benchWords(b, 1e2, false) }
  881. func BenchmarkWordsEncode1e3(b *testing.B) { benchWords(b, 1e3, false) }
  882. func BenchmarkWordsEncode1e4(b *testing.B) { benchWords(b, 1e4, false) }
  883. func BenchmarkWordsEncode1e5(b *testing.B) { benchWords(b, 1e5, false) }
  884. func BenchmarkWordsEncode1e6(b *testing.B) { benchWords(b, 1e6, false) }
  885. func BenchmarkRandomEncode(b *testing.B) {
  886. rng := rand.New(rand.NewSource(1))
  887. data := make([]byte, 1<<20)
  888. for i := range data {
  889. data[i] = uint8(rng.Intn(256))
  890. }
  891. benchEncode(b, data)
  892. }
  893. // testFiles' values are copied directly from
  894. // https://raw.githubusercontent.com/google/snappy/master/snappy_unittest.cc
  895. // The label field is unused in snappy-go.
  896. var testFiles = []struct {
  897. label string
  898. filename string
  899. sizeLimit int
  900. }{
  901. {"html", "html", 0},
  902. {"urls", "urls.10K", 0},
  903. {"jpg", "fireworks.jpeg", 0},
  904. {"jpg_200", "fireworks.jpeg", 200},
  905. {"pdf", "paper-100k.pdf", 0},
  906. {"html4", "html_x_4", 0},
  907. {"txt1", "alice29.txt", 0},
  908. {"txt2", "asyoulik.txt", 0},
  909. {"txt3", "lcet10.txt", 0},
  910. {"txt4", "plrabn12.txt", 0},
  911. {"pb", "geo.protodata", 0},
  912. {"gaviota", "kppkn.gtb", 0},
  913. }
  914. const (
  915. // The benchmark data files are at this canonical URL.
  916. benchURL = "https://raw.githubusercontent.com/google/snappy/master/testdata/"
  917. // They are copied to this local directory.
  918. benchDir = "testdata/bench"
  919. )
  920. func downloadBenchmarkFiles(b testing.TB, basename string) (errRet error) {
  921. filename := filepath.Join(benchDir, basename)
  922. if stat, err := os.Stat(filename); err == nil && stat.Size() != 0 {
  923. return nil
  924. }
  925. if !*download {
  926. b.Skipf("test data not found; skipping %s without the -download flag", testOrBenchmark(b))
  927. }
  928. // Download the official snappy C++ implementation reference test data
  929. // files for benchmarking.
  930. if err := os.MkdirAll(benchDir, 0777); err != nil && !os.IsExist(err) {
  931. return fmt.Errorf("failed to create %s: %s", benchDir, err)
  932. }
  933. f, err := os.Create(filename)
  934. if err != nil {
  935. return fmt.Errorf("failed to create %s: %s", filename, err)
  936. }
  937. defer f.Close()
  938. defer func() {
  939. if errRet != nil {
  940. os.Remove(filename)
  941. }
  942. }()
  943. url := benchURL + basename
  944. resp, err := http.Get(url)
  945. if err != nil {
  946. return fmt.Errorf("failed to download %s: %s", url, err)
  947. }
  948. defer resp.Body.Close()
  949. if s := resp.StatusCode; s != http.StatusOK {
  950. return fmt.Errorf("downloading %s: HTTP status code %d (%s)", url, s, http.StatusText(s))
  951. }
  952. _, err = io.Copy(f, resp.Body)
  953. if err != nil {
  954. return fmt.Errorf("failed to download %s to %s: %s", url, filename, err)
  955. }
  956. return nil
  957. }
  958. func benchFile(b *testing.B, i int, decode bool) {
  959. if err := downloadBenchmarkFiles(b, testFiles[i].filename); err != nil {
  960. b.Fatalf("failed to download testdata: %s", err)
  961. }
  962. data := readFile(b, filepath.Join(benchDir, testFiles[i].filename))
  963. if n := testFiles[i].sizeLimit; 0 < n && n < len(data) {
  964. data = data[:n]
  965. }
  966. if decode {
  967. benchDecode(b, data)
  968. } else {
  969. benchEncode(b, data)
  970. }
  971. }
  972. // Naming convention is kept similar to what snappy's C++ implementation uses.
  973. func Benchmark_UFlat0(b *testing.B) { benchFile(b, 0, true) }
  974. func Benchmark_UFlat1(b *testing.B) { benchFile(b, 1, true) }
  975. func Benchmark_UFlat2(b *testing.B) { benchFile(b, 2, true) }
  976. func Benchmark_UFlat3(b *testing.B) { benchFile(b, 3, true) }
  977. func Benchmark_UFlat4(b *testing.B) { benchFile(b, 4, true) }
  978. func Benchmark_UFlat5(b *testing.B) { benchFile(b, 5, true) }
  979. func Benchmark_UFlat6(b *testing.B) { benchFile(b, 6, true) }
  980. func Benchmark_UFlat7(b *testing.B) { benchFile(b, 7, true) }
  981. func Benchmark_UFlat8(b *testing.B) { benchFile(b, 8, true) }
  982. func Benchmark_UFlat9(b *testing.B) { benchFile(b, 9, true) }
  983. func Benchmark_UFlat10(b *testing.B) { benchFile(b, 10, true) }
  984. func Benchmark_UFlat11(b *testing.B) { benchFile(b, 11, true) }
  985. func Benchmark_ZFlat0(b *testing.B) { benchFile(b, 0, false) }
  986. func Benchmark_ZFlat1(b *testing.B) { benchFile(b, 1, false) }
  987. func Benchmark_ZFlat2(b *testing.B) { benchFile(b, 2, false) }
  988. func Benchmark_ZFlat3(b *testing.B) { benchFile(b, 3, false) }
  989. func Benchmark_ZFlat4(b *testing.B) { benchFile(b, 4, false) }
  990. func Benchmark_ZFlat5(b *testing.B) { benchFile(b, 5, false) }
  991. func Benchmark_ZFlat6(b *testing.B) { benchFile(b, 6, false) }
  992. func Benchmark_ZFlat7(b *testing.B) { benchFile(b, 7, false) }
  993. func Benchmark_ZFlat8(b *testing.B) { benchFile(b, 8, false) }
  994. func Benchmark_ZFlat9(b *testing.B) { benchFile(b, 9, false) }
  995. func Benchmark_ZFlat10(b *testing.B) { benchFile(b, 10, false) }
  996. func Benchmark_ZFlat11(b *testing.B) { benchFile(b, 11, false) }