snappy_test.go 37 KB

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