snappy_test.go 36 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256
  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. const snappytoolCmdName = "cmd/snappytool/snappytool"
  471. func skipTestSameEncodingAsCpp() (msg string) {
  472. if !goEncoderShouldMatchCppEncoder {
  473. return fmt.Sprintf("skipping testing that the encoding is byte-for-byte identical to C++: GOARCH=%s", runtime.GOARCH)
  474. }
  475. if _, err := os.Stat(snappytoolCmdName); err != nil {
  476. return fmt.Sprintf("could not find snappytool: %v", err)
  477. }
  478. return ""
  479. }
  480. func runTestSameEncodingAsCpp(src []byte) error {
  481. got := Encode(nil, src)
  482. cmd := exec.Command(snappytoolCmdName, "-e")
  483. cmd.Stdin = bytes.NewReader(src)
  484. want, err := cmd.Output()
  485. if err != nil {
  486. return fmt.Errorf("could not run snappytool: %v", err)
  487. }
  488. return cmp(got, want)
  489. }
  490. func TestSameEncodingAsCppShortCopies(t *testing.T) {
  491. if msg := skipTestSameEncodingAsCpp(); msg != "" {
  492. t.Skip(msg)
  493. }
  494. src := bytes.Repeat([]byte{'a'}, 20)
  495. for i := 0; i <= len(src); i++ {
  496. if err := runTestSameEncodingAsCpp(src[:i]); err != nil {
  497. t.Errorf("i=%d: %v", i, err)
  498. }
  499. }
  500. }
  501. func TestSameEncodingAsCppLongFiles(t *testing.T) {
  502. if msg := skipTestSameEncodingAsCpp(); msg != "" {
  503. t.Skip(msg)
  504. }
  505. failed := false
  506. for i, tf := range testFiles {
  507. if err := downloadBenchmarkFiles(t, tf.filename); err != nil {
  508. t.Fatalf("failed to download testdata: %s", err)
  509. }
  510. data := readFile(t, filepath.Join(benchDir, tf.filename))
  511. if n := tf.sizeLimit; 0 < n && n < len(data) {
  512. data = data[:n]
  513. }
  514. if err := runTestSameEncodingAsCpp(data); err != nil {
  515. t.Errorf("i=%d: %v", i, err)
  516. failed = true
  517. }
  518. }
  519. if failed {
  520. t.Errorf("was the snappytool program built against the C++ snappy library version " +
  521. "d53de187 or later, commited on 2016-04-05? See " +
  522. "https://github.com/google/snappy/commit/d53de18799418e113e44444252a39b12a0e4e0cc")
  523. }
  524. }
  525. // TestSlowForwardCopyOverrun tests the "expand the pattern" algorithm
  526. // described in decode_amd64.s and its claim of a 10 byte overrun worst case.
  527. func TestSlowForwardCopyOverrun(t *testing.T) {
  528. const base = 100
  529. for length := 1; length < 18; length++ {
  530. for offset := 1; offset < 18; offset++ {
  531. highWaterMark := base
  532. d := base
  533. l := length
  534. o := offset
  535. // makeOffsetAtLeast8
  536. for o < 8 {
  537. if end := d + 8; highWaterMark < end {
  538. highWaterMark = end
  539. }
  540. l -= o
  541. d += o
  542. o += o
  543. }
  544. // fixUpSlowForwardCopy
  545. a := d
  546. d += l
  547. // finishSlowForwardCopy
  548. for l > 0 {
  549. if end := a + 8; highWaterMark < end {
  550. highWaterMark = end
  551. }
  552. a += 8
  553. l -= 8
  554. }
  555. dWant := base + length
  556. overrun := highWaterMark - dWant
  557. if d != dWant || overrun < 0 || 10 < overrun {
  558. t.Errorf("length=%d, offset=%d: d and overrun: got (%d, %d), want (%d, something in [0, 10])",
  559. length, offset, d, overrun, dWant)
  560. }
  561. }
  562. }
  563. }
  564. // TestEncodeNoiseThenRepeats encodes input for which the first half is very
  565. // incompressible and the second half is very compressible. The encoded form's
  566. // length should be closer to 50% of the original length than 100%.
  567. func TestEncodeNoiseThenRepeats(t *testing.T) {
  568. for _, origLen := range []int{256 * 1024, 2048 * 1024} {
  569. src := make([]byte, origLen)
  570. rng := rand.New(rand.NewSource(1))
  571. firstHalf, secondHalf := src[:origLen/2], src[origLen/2:]
  572. for i := range firstHalf {
  573. firstHalf[i] = uint8(rng.Intn(256))
  574. }
  575. for i := range secondHalf {
  576. secondHalf[i] = uint8(i >> 8)
  577. }
  578. dst := Encode(nil, src)
  579. if got, want := len(dst), origLen*3/4; got >= want {
  580. t.Errorf("origLen=%d: got %d encoded bytes, want less than %d", origLen, got, want)
  581. }
  582. }
  583. }
  584. func TestFramingFormat(t *testing.T) {
  585. // src is comprised of alternating 1e5-sized sequences of random
  586. // (incompressible) bytes and repeated (compressible) bytes. 1e5 was chosen
  587. // because it is larger than maxBlockSize (64k).
  588. src := make([]byte, 1e6)
  589. rng := rand.New(rand.NewSource(1))
  590. for i := 0; i < 10; i++ {
  591. if i%2 == 0 {
  592. for j := 0; j < 1e5; j++ {
  593. src[1e5*i+j] = uint8(rng.Intn(256))
  594. }
  595. } else {
  596. for j := 0; j < 1e5; j++ {
  597. src[1e5*i+j] = uint8(i)
  598. }
  599. }
  600. }
  601. buf := new(bytes.Buffer)
  602. if _, err := NewWriter(buf).Write(src); err != nil {
  603. t.Fatalf("Write: encoding: %v", err)
  604. }
  605. dst, err := ioutil.ReadAll(NewReader(buf))
  606. if err != nil {
  607. t.Fatalf("ReadAll: decoding: %v", err)
  608. }
  609. if err := cmp(dst, src); err != nil {
  610. t.Fatal(err)
  611. }
  612. }
  613. func TestWriterGoldenOutput(t *testing.T) {
  614. buf := new(bytes.Buffer)
  615. w := NewBufferedWriter(buf)
  616. defer w.Close()
  617. w.Write([]byte("abcd")) // Not compressible.
  618. w.Flush()
  619. w.Write(bytes.Repeat([]byte{'A'}, 150)) // Compressible.
  620. w.Flush()
  621. // The next chunk is also compressible, but a naive, greedy encoding of the
  622. // overall length 67 copy as a length 64 copy (the longest expressible as a
  623. // tagCopy1 or tagCopy2) plus a length 3 remainder would be two 3-byte
  624. // tagCopy2 tags (6 bytes), since the minimum length for a tagCopy1 is 4
  625. // bytes. Instead, we could do it shorter, in 5 bytes: a 3-byte tagCopy2
  626. // (of length 60) and a 2-byte tagCopy1 (of length 7).
  627. w.Write(bytes.Repeat([]byte{'B'}, 68))
  628. w.Write([]byte("efC")) // Not compressible.
  629. w.Write(bytes.Repeat([]byte{'C'}, 20)) // Compressible.
  630. w.Write(bytes.Repeat([]byte{'B'}, 20)) // Compressible.
  631. w.Write([]byte("g")) // Not compressible.
  632. w.Flush()
  633. got := buf.String()
  634. want := strings.Join([]string{
  635. magicChunk,
  636. "\x01\x08\x00\x00", // Uncompressed chunk, 8 bytes long (including 4 byte checksum).
  637. "\x68\x10\xe6\xb6", // Checksum.
  638. "\x61\x62\x63\x64", // Uncompressed payload: "abcd".
  639. "\x00\x11\x00\x00", // Compressed chunk, 17 bytes long (including 4 byte checksum).
  640. "\x5f\xeb\xf2\x10", // Checksum.
  641. "\x96\x01", // Compressed payload: Uncompressed length (varint encoded): 150.
  642. "\x00\x41", // Compressed payload: tagLiteral, length=1, "A".
  643. "\xfe\x01\x00", // Compressed payload: tagCopy2, length=64, offset=1.
  644. "\xfe\x01\x00", // Compressed payload: tagCopy2, length=64, offset=1.
  645. "\x52\x01\x00", // Compressed payload: tagCopy2, length=21, offset=1.
  646. "\x00\x18\x00\x00", // Compressed chunk, 24 bytes long (including 4 byte checksum).
  647. "\x30\x85\x69\xeb", // Checksum.
  648. "\x70", // Compressed payload: Uncompressed length (varint encoded): 112.
  649. "\x00\x42", // Compressed payload: tagLiteral, length=1, "B".
  650. "\xee\x01\x00", // Compressed payload: tagCopy2, length=60, offset=1.
  651. "\x0d\x01", // Compressed payload: tagCopy1, length=7, offset=1.
  652. "\x08\x65\x66\x43", // Compressed payload: tagLiteral, length=3, "efC".
  653. "\x4e\x01\x00", // Compressed payload: tagCopy2, length=20, offset=1.
  654. "\x4e\x5a\x00", // Compressed payload: tagCopy2, length=20, offset=90.
  655. "\x00\x67", // Compressed payload: tagLiteral, length=1, "g".
  656. }, "")
  657. if got != want {
  658. t.Fatalf("\ngot: % x\nwant: % x", got, want)
  659. }
  660. }
  661. func TestEmitLiteral(t *testing.T) {
  662. testCases := []struct {
  663. length int
  664. want string
  665. }{
  666. {1, "\x00"},
  667. {2, "\x04"},
  668. {59, "\xe8"},
  669. {60, "\xec"},
  670. {61, "\xf0\x3c"},
  671. {62, "\xf0\x3d"},
  672. {254, "\xf0\xfd"},
  673. {255, "\xf0\xfe"},
  674. {256, "\xf0\xff"},
  675. {257, "\xf4\x00\x01"},
  676. {65534, "\xf4\xfd\xff"},
  677. {65535, "\xf4\xfe\xff"},
  678. {65536, "\xf4\xff\xff"},
  679. }
  680. dst := make([]byte, 70000)
  681. nines := bytes.Repeat([]byte{0x99}, 65536)
  682. for _, tc := range testCases {
  683. lit := nines[:tc.length]
  684. n := emitLiteral(dst, lit)
  685. if !bytes.HasSuffix(dst[:n], lit) {
  686. t.Errorf("length=%d: did not end with that many literal bytes", tc.length)
  687. continue
  688. }
  689. got := string(dst[:n-tc.length])
  690. if got != tc.want {
  691. t.Errorf("length=%d:\ngot % x\nwant % x", tc.length, got, tc.want)
  692. continue
  693. }
  694. }
  695. }
  696. func TestEmitCopy(t *testing.T) {
  697. testCases := []struct {
  698. offset int
  699. length int
  700. want string
  701. }{
  702. {8, 04, "\x01\x08"},
  703. {8, 11, "\x1d\x08"},
  704. {8, 12, "\x2e\x08\x00"},
  705. {8, 13, "\x32\x08\x00"},
  706. {8, 59, "\xea\x08\x00"},
  707. {8, 60, "\xee\x08\x00"},
  708. {8, 61, "\xf2\x08\x00"},
  709. {8, 62, "\xf6\x08\x00"},
  710. {8, 63, "\xfa\x08\x00"},
  711. {8, 64, "\xfe\x08\x00"},
  712. {8, 65, "\xee\x08\x00\x05\x08"},
  713. {8, 66, "\xee\x08\x00\x09\x08"},
  714. {8, 67, "\xee\x08\x00\x0d\x08"},
  715. {8, 68, "\xfe\x08\x00\x01\x08"},
  716. {8, 69, "\xfe\x08\x00\x05\x08"},
  717. {8, 80, "\xfe\x08\x00\x3e\x08\x00"},
  718. {256, 04, "\x21\x00"},
  719. {256, 11, "\x3d\x00"},
  720. {256, 12, "\x2e\x00\x01"},
  721. {256, 13, "\x32\x00\x01"},
  722. {256, 59, "\xea\x00\x01"},
  723. {256, 60, "\xee\x00\x01"},
  724. {256, 61, "\xf2\x00\x01"},
  725. {256, 62, "\xf6\x00\x01"},
  726. {256, 63, "\xfa\x00\x01"},
  727. {256, 64, "\xfe\x00\x01"},
  728. {256, 65, "\xee\x00\x01\x25\x00"},
  729. {256, 66, "\xee\x00\x01\x29\x00"},
  730. {256, 67, "\xee\x00\x01\x2d\x00"},
  731. {256, 68, "\xfe\x00\x01\x21\x00"},
  732. {256, 69, "\xfe\x00\x01\x25\x00"},
  733. {256, 80, "\xfe\x00\x01\x3e\x00\x01"},
  734. {2048, 04, "\x0e\x00\x08"},
  735. {2048, 11, "\x2a\x00\x08"},
  736. {2048, 12, "\x2e\x00\x08"},
  737. {2048, 13, "\x32\x00\x08"},
  738. {2048, 59, "\xea\x00\x08"},
  739. {2048, 60, "\xee\x00\x08"},
  740. {2048, 61, "\xf2\x00\x08"},
  741. {2048, 62, "\xf6\x00\x08"},
  742. {2048, 63, "\xfa\x00\x08"},
  743. {2048, 64, "\xfe\x00\x08"},
  744. {2048, 65, "\xee\x00\x08\x12\x00\x08"},
  745. {2048, 66, "\xee\x00\x08\x16\x00\x08"},
  746. {2048, 67, "\xee\x00\x08\x1a\x00\x08"},
  747. {2048, 68, "\xfe\x00\x08\x0e\x00\x08"},
  748. {2048, 69, "\xfe\x00\x08\x12\x00\x08"},
  749. {2048, 80, "\xfe\x00\x08\x3e\x00\x08"},
  750. }
  751. dst := make([]byte, 1024)
  752. for _, tc := range testCases {
  753. n := emitCopy(dst, tc.offset, tc.length)
  754. got := string(dst[:n])
  755. if got != tc.want {
  756. t.Errorf("offset=%d, length=%d:\ngot % x\nwant % x", tc.offset, tc.length, got, tc.want)
  757. }
  758. }
  759. }
  760. func TestNewBufferedWriter(t *testing.T) {
  761. // Test all 32 possible sub-sequences of these 5 input slices.
  762. //
  763. // Their lengths sum to 400,000, which is over 6 times the Writer ibuf
  764. // capacity: 6 * maxBlockSize is 393,216.
  765. inputs := [][]byte{
  766. bytes.Repeat([]byte{'a'}, 40000),
  767. bytes.Repeat([]byte{'b'}, 150000),
  768. bytes.Repeat([]byte{'c'}, 60000),
  769. bytes.Repeat([]byte{'d'}, 120000),
  770. bytes.Repeat([]byte{'e'}, 30000),
  771. }
  772. loop:
  773. for i := 0; i < 1<<uint(len(inputs)); i++ {
  774. var want []byte
  775. buf := new(bytes.Buffer)
  776. w := NewBufferedWriter(buf)
  777. for j, input := range inputs {
  778. if i&(1<<uint(j)) == 0 {
  779. continue
  780. }
  781. if _, err := w.Write(input); err != nil {
  782. t.Errorf("i=%#02x: j=%d: Write: %v", i, j, err)
  783. continue loop
  784. }
  785. want = append(want, input...)
  786. }
  787. if err := w.Close(); err != nil {
  788. t.Errorf("i=%#02x: Close: %v", i, err)
  789. continue
  790. }
  791. got, err := ioutil.ReadAll(NewReader(buf))
  792. if err != nil {
  793. t.Errorf("i=%#02x: ReadAll: %v", i, err)
  794. continue
  795. }
  796. if err := cmp(got, want); err != nil {
  797. t.Errorf("i=%#02x: %v", i, err)
  798. continue
  799. }
  800. }
  801. }
  802. func TestFlush(t *testing.T) {
  803. buf := new(bytes.Buffer)
  804. w := NewBufferedWriter(buf)
  805. defer w.Close()
  806. if _, err := w.Write(bytes.Repeat([]byte{'x'}, 20)); err != nil {
  807. t.Fatalf("Write: %v", err)
  808. }
  809. if n := buf.Len(); n != 0 {
  810. t.Fatalf("before Flush: %d bytes were written to the underlying io.Writer, want 0", n)
  811. }
  812. if err := w.Flush(); err != nil {
  813. t.Fatalf("Flush: %v", err)
  814. }
  815. if n := buf.Len(); n == 0 {
  816. t.Fatalf("after Flush: %d bytes were written to the underlying io.Writer, want non-0", n)
  817. }
  818. }
  819. func TestReaderUncompressedDataOK(t *testing.T) {
  820. r := NewReader(strings.NewReader(magicChunk +
  821. "\x01\x08\x00\x00" + // Uncompressed chunk, 8 bytes long (including 4 byte checksum).
  822. "\x68\x10\xe6\xb6" + // Checksum.
  823. "\x61\x62\x63\x64", // Uncompressed payload: "abcd".
  824. ))
  825. g, err := ioutil.ReadAll(r)
  826. if err != nil {
  827. t.Fatal(err)
  828. }
  829. if got, want := string(g), "abcd"; got != want {
  830. t.Fatalf("got %q, want %q", got, want)
  831. }
  832. }
  833. func TestReaderUncompressedDataNoPayload(t *testing.T) {
  834. r := NewReader(strings.NewReader(magicChunk +
  835. "\x01\x04\x00\x00" + // Uncompressed chunk, 4 bytes long.
  836. "", // No payload; corrupt input.
  837. ))
  838. if _, err := ioutil.ReadAll(r); err != ErrCorrupt {
  839. t.Fatalf("got %v, want %v", err, ErrCorrupt)
  840. }
  841. }
  842. func TestReaderUncompressedDataTooLong(t *testing.T) {
  843. // https://github.com/google/snappy/blob/master/framing_format.txt section
  844. // 4.3 says that "the maximum legal chunk length... is 65540", or 0x10004.
  845. const n = 0x10005
  846. r := NewReader(strings.NewReader(magicChunk +
  847. "\x01\x05\x00\x01" + // Uncompressed chunk, n bytes long.
  848. strings.Repeat("\x00", n),
  849. ))
  850. if _, err := ioutil.ReadAll(r); err != ErrCorrupt {
  851. t.Fatalf("got %v, want %v", err, ErrCorrupt)
  852. }
  853. }
  854. func TestReaderReset(t *testing.T) {
  855. gold := bytes.Repeat([]byte("All that is gold does not glitter,\n"), 10000)
  856. buf := new(bytes.Buffer)
  857. if _, err := NewWriter(buf).Write(gold); err != nil {
  858. t.Fatalf("Write: %v", err)
  859. }
  860. encoded, invalid, partial := buf.String(), "invalid", "partial"
  861. r := NewReader(nil)
  862. for i, s := range []string{encoded, invalid, partial, encoded, partial, invalid, encoded, encoded} {
  863. if s == partial {
  864. r.Reset(strings.NewReader(encoded))
  865. if _, err := r.Read(make([]byte, 101)); err != nil {
  866. t.Errorf("#%d: %v", i, err)
  867. continue
  868. }
  869. continue
  870. }
  871. r.Reset(strings.NewReader(s))
  872. got, err := ioutil.ReadAll(r)
  873. switch s {
  874. case encoded:
  875. if err != nil {
  876. t.Errorf("#%d: %v", i, err)
  877. continue
  878. }
  879. if err := cmp(got, gold); err != nil {
  880. t.Errorf("#%d: %v", i, err)
  881. continue
  882. }
  883. case invalid:
  884. if err == nil {
  885. t.Errorf("#%d: got nil error, want non-nil", i)
  886. continue
  887. }
  888. }
  889. }
  890. }
  891. func TestWriterReset(t *testing.T) {
  892. gold := bytes.Repeat([]byte("Not all those who wander are lost;\n"), 10000)
  893. const n = 20
  894. for _, buffered := range []bool{false, true} {
  895. var w *Writer
  896. if buffered {
  897. w = NewBufferedWriter(nil)
  898. defer w.Close()
  899. } else {
  900. w = NewWriter(nil)
  901. }
  902. var gots, wants [][]byte
  903. failed := false
  904. for i := 0; i <= n; i++ {
  905. buf := new(bytes.Buffer)
  906. w.Reset(buf)
  907. want := gold[:len(gold)*i/n]
  908. if _, err := w.Write(want); err != nil {
  909. t.Errorf("#%d: Write: %v", i, err)
  910. failed = true
  911. continue
  912. }
  913. if buffered {
  914. if err := w.Flush(); err != nil {
  915. t.Errorf("#%d: Flush: %v", i, err)
  916. failed = true
  917. continue
  918. }
  919. }
  920. got, err := ioutil.ReadAll(NewReader(buf))
  921. if err != nil {
  922. t.Errorf("#%d: ReadAll: %v", i, err)
  923. failed = true
  924. continue
  925. }
  926. gots = append(gots, got)
  927. wants = append(wants, want)
  928. }
  929. if failed {
  930. continue
  931. }
  932. for i := range gots {
  933. if err := cmp(gots[i], wants[i]); err != nil {
  934. t.Errorf("#%d: %v", i, err)
  935. }
  936. }
  937. }
  938. }
  939. func TestWriterResetWithoutFlush(t *testing.T) {
  940. buf0 := new(bytes.Buffer)
  941. buf1 := new(bytes.Buffer)
  942. w := NewBufferedWriter(buf0)
  943. if _, err := w.Write([]byte("xxx")); err != nil {
  944. t.Fatalf("Write #0: %v", err)
  945. }
  946. // Note that we don't Flush the Writer before calling Reset.
  947. w.Reset(buf1)
  948. if _, err := w.Write([]byte("yyy")); err != nil {
  949. t.Fatalf("Write #1: %v", err)
  950. }
  951. if err := w.Flush(); err != nil {
  952. t.Fatalf("Flush: %v", err)
  953. }
  954. got, err := ioutil.ReadAll(NewReader(buf1))
  955. if err != nil {
  956. t.Fatalf("ReadAll: %v", err)
  957. }
  958. if err := cmp(got, []byte("yyy")); err != nil {
  959. t.Fatal(err)
  960. }
  961. }
  962. type writeCounter int
  963. func (c *writeCounter) Write(p []byte) (int, error) {
  964. *c++
  965. return len(p), nil
  966. }
  967. // TestNumUnderlyingWrites tests that each Writer flush only makes one or two
  968. // Write calls on its underlying io.Writer, depending on whether or not the
  969. // flushed buffer was compressible.
  970. func TestNumUnderlyingWrites(t *testing.T) {
  971. testCases := []struct {
  972. input []byte
  973. want int
  974. }{
  975. {bytes.Repeat([]byte{'x'}, 100), 1},
  976. {bytes.Repeat([]byte{'y'}, 100), 1},
  977. {[]byte("ABCDEFGHIJKLMNOPQRST"), 2},
  978. }
  979. var c writeCounter
  980. w := NewBufferedWriter(&c)
  981. defer w.Close()
  982. for i, tc := range testCases {
  983. c = 0
  984. if _, err := w.Write(tc.input); err != nil {
  985. t.Errorf("#%d: Write: %v", i, err)
  986. continue
  987. }
  988. if err := w.Flush(); err != nil {
  989. t.Errorf("#%d: Flush: %v", i, err)
  990. continue
  991. }
  992. if int(c) != tc.want {
  993. t.Errorf("#%d: got %d underlying writes, want %d", i, c, tc.want)
  994. continue
  995. }
  996. }
  997. }
  998. func benchDecode(b *testing.B, src []byte) {
  999. encoded := Encode(nil, src)
  1000. // Bandwidth is in amount of uncompressed data.
  1001. b.SetBytes(int64(len(src)))
  1002. b.ResetTimer()
  1003. for i := 0; i < b.N; i++ {
  1004. Decode(src, encoded)
  1005. }
  1006. }
  1007. func benchEncode(b *testing.B, src []byte) {
  1008. // Bandwidth is in amount of uncompressed data.
  1009. b.SetBytes(int64(len(src)))
  1010. dst := make([]byte, MaxEncodedLen(len(src)))
  1011. b.ResetTimer()
  1012. for i := 0; i < b.N; i++ {
  1013. Encode(dst, src)
  1014. }
  1015. }
  1016. func testOrBenchmark(b testing.TB) string {
  1017. if _, ok := b.(*testing.B); ok {
  1018. return "benchmark"
  1019. }
  1020. return "test"
  1021. }
  1022. func readFile(b testing.TB, filename string) []byte {
  1023. src, err := ioutil.ReadFile(filename)
  1024. if err != nil {
  1025. b.Skipf("skipping %s: %v", testOrBenchmark(b), err)
  1026. }
  1027. if len(src) == 0 {
  1028. b.Fatalf("%s has zero length", filename)
  1029. }
  1030. return src
  1031. }
  1032. // expand returns a slice of length n containing repeated copies of src.
  1033. func expand(src []byte, n int) []byte {
  1034. dst := make([]byte, n)
  1035. for x := dst; len(x) > 0; {
  1036. i := copy(x, src)
  1037. x = x[i:]
  1038. }
  1039. return dst
  1040. }
  1041. func benchWords(b *testing.B, n int, decode bool) {
  1042. // Note: the file is OS-language dependent so the resulting values are not
  1043. // directly comparable for non-US-English OS installations.
  1044. data := expand(readFile(b, "/usr/share/dict/words"), n)
  1045. if decode {
  1046. benchDecode(b, data)
  1047. } else {
  1048. benchEncode(b, data)
  1049. }
  1050. }
  1051. func BenchmarkWordsDecode1e1(b *testing.B) { benchWords(b, 1e1, true) }
  1052. func BenchmarkWordsDecode1e2(b *testing.B) { benchWords(b, 1e2, true) }
  1053. func BenchmarkWordsDecode1e3(b *testing.B) { benchWords(b, 1e3, true) }
  1054. func BenchmarkWordsDecode1e4(b *testing.B) { benchWords(b, 1e4, true) }
  1055. func BenchmarkWordsDecode1e5(b *testing.B) { benchWords(b, 1e5, true) }
  1056. func BenchmarkWordsDecode1e6(b *testing.B) { benchWords(b, 1e6, true) }
  1057. func BenchmarkWordsEncode1e1(b *testing.B) { benchWords(b, 1e1, false) }
  1058. func BenchmarkWordsEncode1e2(b *testing.B) { benchWords(b, 1e2, false) }
  1059. func BenchmarkWordsEncode1e3(b *testing.B) { benchWords(b, 1e3, false) }
  1060. func BenchmarkWordsEncode1e4(b *testing.B) { benchWords(b, 1e4, false) }
  1061. func BenchmarkWordsEncode1e5(b *testing.B) { benchWords(b, 1e5, false) }
  1062. func BenchmarkWordsEncode1e6(b *testing.B) { benchWords(b, 1e6, false) }
  1063. func BenchmarkRandomEncode(b *testing.B) {
  1064. rng := rand.New(rand.NewSource(1))
  1065. data := make([]byte, 1<<20)
  1066. for i := range data {
  1067. data[i] = uint8(rng.Intn(256))
  1068. }
  1069. benchEncode(b, data)
  1070. }
  1071. // testFiles' values are copied directly from
  1072. // https://raw.githubusercontent.com/google/snappy/master/snappy_unittest.cc
  1073. // The label field is unused in snappy-go.
  1074. var testFiles = []struct {
  1075. label string
  1076. filename string
  1077. sizeLimit int
  1078. }{
  1079. {"html", "html", 0},
  1080. {"urls", "urls.10K", 0},
  1081. {"jpg", "fireworks.jpeg", 0},
  1082. {"jpg_200", "fireworks.jpeg", 200},
  1083. {"pdf", "paper-100k.pdf", 0},
  1084. {"html4", "html_x_4", 0},
  1085. {"txt1", "alice29.txt", 0},
  1086. {"txt2", "asyoulik.txt", 0},
  1087. {"txt3", "lcet10.txt", 0},
  1088. {"txt4", "plrabn12.txt", 0},
  1089. {"pb", "geo.protodata", 0},
  1090. {"gaviota", "kppkn.gtb", 0},
  1091. }
  1092. const (
  1093. // The benchmark data files are at this canonical URL.
  1094. benchURL = "https://raw.githubusercontent.com/google/snappy/master/testdata/"
  1095. // They are copied to this local directory.
  1096. benchDir = "testdata/bench"
  1097. )
  1098. func downloadBenchmarkFiles(b testing.TB, basename string) (errRet error) {
  1099. filename := filepath.Join(benchDir, basename)
  1100. if stat, err := os.Stat(filename); err == nil && stat.Size() != 0 {
  1101. return nil
  1102. }
  1103. if !*download {
  1104. b.Skipf("test data not found; skipping %s without the -download flag", testOrBenchmark(b))
  1105. }
  1106. // Download the official snappy C++ implementation reference test data
  1107. // files for benchmarking.
  1108. if err := os.MkdirAll(benchDir, 0777); err != nil && !os.IsExist(err) {
  1109. return fmt.Errorf("failed to create %s: %s", benchDir, err)
  1110. }
  1111. f, err := os.Create(filename)
  1112. if err != nil {
  1113. return fmt.Errorf("failed to create %s: %s", filename, err)
  1114. }
  1115. defer f.Close()
  1116. defer func() {
  1117. if errRet != nil {
  1118. os.Remove(filename)
  1119. }
  1120. }()
  1121. url := benchURL + basename
  1122. resp, err := http.Get(url)
  1123. if err != nil {
  1124. return fmt.Errorf("failed to download %s: %s", url, err)
  1125. }
  1126. defer resp.Body.Close()
  1127. if s := resp.StatusCode; s != http.StatusOK {
  1128. return fmt.Errorf("downloading %s: HTTP status code %d (%s)", url, s, http.StatusText(s))
  1129. }
  1130. _, err = io.Copy(f, resp.Body)
  1131. if err != nil {
  1132. return fmt.Errorf("failed to download %s to %s: %s", url, filename, err)
  1133. }
  1134. return nil
  1135. }
  1136. func benchFile(b *testing.B, i int, decode bool) {
  1137. if err := downloadBenchmarkFiles(b, testFiles[i].filename); err != nil {
  1138. b.Fatalf("failed to download testdata: %s", err)
  1139. }
  1140. data := readFile(b, filepath.Join(benchDir, testFiles[i].filename))
  1141. if n := testFiles[i].sizeLimit; 0 < n && n < len(data) {
  1142. data = data[:n]
  1143. }
  1144. if decode {
  1145. benchDecode(b, data)
  1146. } else {
  1147. benchEncode(b, data)
  1148. }
  1149. }
  1150. // Naming convention is kept similar to what snappy's C++ implementation uses.
  1151. func Benchmark_UFlat0(b *testing.B) { benchFile(b, 0, true) }
  1152. func Benchmark_UFlat1(b *testing.B) { benchFile(b, 1, true) }
  1153. func Benchmark_UFlat2(b *testing.B) { benchFile(b, 2, true) }
  1154. func Benchmark_UFlat3(b *testing.B) { benchFile(b, 3, true) }
  1155. func Benchmark_UFlat4(b *testing.B) { benchFile(b, 4, true) }
  1156. func Benchmark_UFlat5(b *testing.B) { benchFile(b, 5, true) }
  1157. func Benchmark_UFlat6(b *testing.B) { benchFile(b, 6, true) }
  1158. func Benchmark_UFlat7(b *testing.B) { benchFile(b, 7, true) }
  1159. func Benchmark_UFlat8(b *testing.B) { benchFile(b, 8, true) }
  1160. func Benchmark_UFlat9(b *testing.B) { benchFile(b, 9, true) }
  1161. func Benchmark_UFlat10(b *testing.B) { benchFile(b, 10, true) }
  1162. func Benchmark_UFlat11(b *testing.B) { benchFile(b, 11, true) }
  1163. func Benchmark_ZFlat0(b *testing.B) { benchFile(b, 0, false) }
  1164. func Benchmark_ZFlat1(b *testing.B) { benchFile(b, 1, false) }
  1165. func Benchmark_ZFlat2(b *testing.B) { benchFile(b, 2, false) }
  1166. func Benchmark_ZFlat3(b *testing.B) { benchFile(b, 3, false) }
  1167. func Benchmark_ZFlat4(b *testing.B) { benchFile(b, 4, false) }
  1168. func Benchmark_ZFlat5(b *testing.B) { benchFile(b, 5, false) }
  1169. func Benchmark_ZFlat6(b *testing.B) { benchFile(b, 6, false) }
  1170. func Benchmark_ZFlat7(b *testing.B) { benchFile(b, 7, false) }
  1171. func Benchmark_ZFlat8(b *testing.B) { benchFile(b, 8, false) }
  1172. func Benchmark_ZFlat9(b *testing.B) { benchFile(b, 9, false) }
  1173. func Benchmark_ZFlat10(b *testing.B) { benchFile(b, 10, false) }
  1174. func Benchmark_ZFlat11(b *testing.B) { benchFile(b, 11, false) }