snappy_test.go 41 KB

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