s2_test.go 47 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847
  1. // Copyright 2011 The Snappy-Go Authors. All rights reserved.
  2. // Copyright (c) 2019 Klaus Post. All rights reserved.
  3. // Use of this source code is governed by a BSD-style
  4. // license that can be found in the LICENSE file.
  5. package s2
  6. import (
  7. "bytes"
  8. "encoding/binary"
  9. "flag"
  10. "fmt"
  11. "io"
  12. "io/ioutil"
  13. "math"
  14. "math/rand"
  15. "net/http"
  16. "os"
  17. "path/filepath"
  18. "runtime"
  19. "strings"
  20. "sync"
  21. "testing"
  22. "github.com/klauspost/compress/snappy"
  23. "github.com/klauspost/compress/zstd"
  24. )
  25. const maxUint = ^uint(0)
  26. const maxInt = int(maxUint >> 1)
  27. var (
  28. download = flag.Bool("download", false, "If true, download any missing files before running benchmarks")
  29. testdataDir = flag.String("testdataDir", "testdata", "Directory containing the test data")
  30. benchdataDir = flag.String("benchdataDir", "testdata/bench", "Directory containing the benchmark data")
  31. )
  32. func TestMaxEncodedLen(t *testing.T) {
  33. testSet := []struct {
  34. in, out int64
  35. }{
  36. {in: 0, out: 1},
  37. {in: 1 << 24, out: 1<<24 + int64(binary.PutVarint([]byte{binary.MaxVarintLen32: 0}, int64(1<<24))) + literalExtraSize(1<<24)},
  38. {in: MaxBlockSize, out: math.MaxUint32},
  39. {in: math.MaxUint32 - binary.MaxVarintLen32 - literalExtraSize(math.MaxUint32), out: math.MaxUint32},
  40. {in: math.MaxUint32 - 9, out: -1},
  41. {in: math.MaxUint32 - 8, out: -1},
  42. {in: math.MaxUint32 - 7, out: -1},
  43. {in: math.MaxUint32 - 6, out: -1},
  44. {in: math.MaxUint32 - 5, out: -1},
  45. {in: math.MaxUint32 - 4, out: -1},
  46. {in: math.MaxUint32 - 3, out: -1},
  47. {in: math.MaxUint32 - 2, out: -1},
  48. {in: math.MaxUint32 - 1, out: -1},
  49. {in: math.MaxUint32, out: -1},
  50. {in: -1, out: -1},
  51. {in: -2, out: -1},
  52. }
  53. // 32 bit platforms have a different threshold.
  54. if maxInt == math.MaxInt32 {
  55. testSet[2].out = -1
  56. testSet[3].out = -1
  57. }
  58. // Test all sizes up to maxBlockSize.
  59. for i := int64(0); i < maxBlockSize; i++ {
  60. testSet = append(testSet, struct{ in, out int64 }{in: i, out: i + int64(binary.PutVarint([]byte{binary.MaxVarintLen32: 0}, i)) + literalExtraSize(i)})
  61. }
  62. for i := range testSet {
  63. tt := testSet[i]
  64. want := tt.out
  65. got := int64(MaxEncodedLen(int(tt.in)))
  66. if got != want {
  67. t.Fatalf("input: %d, want: %d, got: %d", tt.in, want, got)
  68. }
  69. }
  70. }
  71. func cmp(got, want []byte) error {
  72. if bytes.Equal(got, want) {
  73. return nil
  74. }
  75. if len(got) != len(want) {
  76. return fmt.Errorf("got %d bytes, want %d", len(got), len(want))
  77. }
  78. for i := range got {
  79. if got[i] != want[i] {
  80. return fmt.Errorf("byte #%d: got 0x%02x, want 0x%02x", i, got[i], want[i])
  81. }
  82. }
  83. return nil
  84. }
  85. func roundtrip(b, ebuf, dbuf []byte) error {
  86. bOrg := make([]byte, len(b))
  87. copy(bOrg, b)
  88. asmEnc := Encode(nil, b)
  89. if err := cmp(bOrg, b); err != nil {
  90. return fmt.Errorf("src was changed: %v", err)
  91. }
  92. goEnc := encodeGo(nil, b)
  93. if err := cmp(bOrg, b); err != nil {
  94. return fmt.Errorf("src was changed: %v", err)
  95. }
  96. //fmt.Println("asm:", len(asmEnc), "go:", len(goEnc))
  97. dGo, err := Decode(nil, goEnc)
  98. if err != nil {
  99. return fmt.Errorf("decoding error: %v", err)
  100. }
  101. if err := cmp(dGo, b); err != nil {
  102. return fmt.Errorf("roundtrip mismatch: %v", err)
  103. }
  104. // fmt.Println("decode asm...")
  105. d, err := Decode(nil, asmEnc)
  106. if err != nil {
  107. return fmt.Errorf("decoding error: %v", err)
  108. }
  109. if err := cmp(d, b); err != nil {
  110. return fmt.Errorf("roundtrip mismatch: %v", err)
  111. }
  112. d, err = Decode(dbuf, EncodeBetter(ebuf, b))
  113. if err != nil {
  114. return fmt.Errorf("decoding better error: %v", err)
  115. }
  116. if err := cmp(d, b); err != nil {
  117. return fmt.Errorf("roundtrip better mismatch: %v", err)
  118. }
  119. // Test concat with some existing data.
  120. dst := []byte("existing")
  121. // Add 3 different encodes and a 0 length block.
  122. concat, err := ConcatBlocks(dst, Encode(nil, b), EncodeBetter(nil, b), []byte{0}, snappy.Encode(nil, b))
  123. if err != nil {
  124. return fmt.Errorf("concat error: %v", err)
  125. }
  126. if err := cmp(concat[:len(dst)], dst); err != nil {
  127. return fmt.Errorf("concat existing mismatch: %v", err)
  128. }
  129. concat = concat[len(dst):]
  130. d, _ = Decode(nil, concat)
  131. want := append(make([]byte, 0, len(b)*3), b...)
  132. want = append(want, b...)
  133. want = append(want, b...)
  134. if err := cmp(d, want); err != nil {
  135. return fmt.Errorf("roundtrip concat mismatch: %v", err)
  136. }
  137. return nil
  138. }
  139. func TestEmpty(t *testing.T) {
  140. if err := roundtrip(nil, nil, nil); err != nil {
  141. t.Fatal(err)
  142. }
  143. }
  144. func TestSmallCopy(t *testing.T) {
  145. for _, ebuf := range [][]byte{nil, make([]byte, 20), make([]byte, 64)} {
  146. for _, dbuf := range [][]byte{nil, make([]byte, 20), make([]byte, 64)} {
  147. for i := 0; i < 32; i++ {
  148. s := "aaaa" + strings.Repeat("b", i) + "aaaabbbb"
  149. if err := roundtrip([]byte(s), ebuf, dbuf); err != nil {
  150. t.Errorf("len(ebuf)=%d, len(dbuf)=%d, i=%d: %v", len(ebuf), len(dbuf), i, err)
  151. }
  152. }
  153. }
  154. }
  155. }
  156. func TestSmallRand(t *testing.T) {
  157. rng := rand.New(rand.NewSource(1))
  158. for n := 1; n < 20000; n += 23 {
  159. b := make([]byte, n)
  160. for i := range b {
  161. b[i] = uint8(rng.Intn(256))
  162. }
  163. if err := roundtrip(b, nil, nil); err != nil {
  164. t.Fatal(err)
  165. }
  166. }
  167. }
  168. func TestSmallRegular(t *testing.T) {
  169. for n := 1; n < 20000; n += 23 {
  170. b := make([]byte, n)
  171. for i := range b {
  172. b[i] = uint8(i%10 + 'a')
  173. }
  174. if err := roundtrip(b, nil, nil); err != nil {
  175. t.Fatal(err)
  176. }
  177. }
  178. }
  179. func TestSmallRepeat(t *testing.T) {
  180. for n := 1; n < 20000; n += 23 {
  181. b := make([]byte, n)
  182. for i := range b[:n/2] {
  183. b[i] = uint8(i * 255 / n)
  184. }
  185. for i := range b[n/2:] {
  186. b[i+n/2] = uint8(i%10 + 'a')
  187. }
  188. if err := roundtrip(b, nil, nil); err != nil {
  189. t.Fatal(err)
  190. }
  191. }
  192. }
  193. func TestInvalidVarint(t *testing.T) {
  194. testCases := []struct {
  195. desc string
  196. input string
  197. }{{
  198. "invalid varint, final byte has continuation bit set",
  199. "\xff",
  200. }, {
  201. "invalid varint, value overflows uint64",
  202. "\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\x00",
  203. }, {
  204. // https://github.com/google/snappy/blob/master/format_description.txt
  205. // says that "the stream starts with the uncompressed length [as a
  206. // varint] (up to a maximum of 2^32 - 1)".
  207. "valid varint (as uint64), but value overflows uint32",
  208. "\x80\x80\x80\x80\x10",
  209. }}
  210. for _, tc := range testCases {
  211. input := []byte(tc.input)
  212. if _, err := DecodedLen(input); err != ErrCorrupt {
  213. t.Errorf("%s: DecodedLen: got %v, want ErrCorrupt", tc.desc, err)
  214. }
  215. if _, err := Decode(nil, input); err != ErrCorrupt {
  216. t.Errorf("%s: Decode: got %v, want ErrCorrupt", tc.desc, err)
  217. }
  218. }
  219. }
  220. func TestDecode(t *testing.T) {
  221. lit40Bytes := make([]byte, 40)
  222. for i := range lit40Bytes {
  223. lit40Bytes[i] = byte(i)
  224. }
  225. lit40 := string(lit40Bytes)
  226. testCases := []struct {
  227. desc string
  228. input string
  229. want string
  230. wantErr error
  231. }{{
  232. `decodedLen=0; valid input`,
  233. "\x00",
  234. "",
  235. nil,
  236. }, {
  237. `decodedLen=3; tagLiteral, 0-byte length; length=3; valid input`,
  238. "\x03" + "\x08\xff\xff\xff",
  239. "\xff\xff\xff",
  240. nil,
  241. }, {
  242. `decodedLen=2; tagLiteral, 0-byte length; length=3; not enough dst bytes`,
  243. "\x02" + "\x08\xff\xff\xff",
  244. "",
  245. ErrCorrupt,
  246. }, {
  247. `decodedLen=3; tagLiteral, 0-byte length; length=3; not enough src bytes`,
  248. "\x03" + "\x08\xff\xff",
  249. "",
  250. ErrCorrupt,
  251. }, {
  252. `decodedLen=40; tagLiteral, 0-byte length; length=40; valid input`,
  253. "\x28" + "\x9c" + lit40,
  254. lit40,
  255. nil,
  256. }, {
  257. `decodedLen=1; tagLiteral, 1-byte length; not enough length bytes`,
  258. "\x01" + "\xf0",
  259. "",
  260. ErrCorrupt,
  261. }, {
  262. `decodedLen=3; tagLiteral, 1-byte length; length=3; valid input`,
  263. "\x03" + "\xf0\x02\xff\xff\xff",
  264. "\xff\xff\xff",
  265. nil,
  266. }, {
  267. `decodedLen=1; tagLiteral, 2-byte length; not enough length bytes`,
  268. "\x01" + "\xf4\x00",
  269. "",
  270. ErrCorrupt,
  271. }, {
  272. `decodedLen=3; tagLiteral, 2-byte length; length=3; valid input`,
  273. "\x03" + "\xf4\x02\x00\xff\xff\xff",
  274. "\xff\xff\xff",
  275. nil,
  276. }, {
  277. `decodedLen=1; tagLiteral, 3-byte length; not enough length bytes`,
  278. "\x01" + "\xf8\x00\x00",
  279. "",
  280. ErrCorrupt,
  281. }, {
  282. `decodedLen=3; tagLiteral, 3-byte length; length=3; valid input`,
  283. "\x03" + "\xf8\x02\x00\x00\xff\xff\xff",
  284. "\xff\xff\xff",
  285. nil,
  286. }, {
  287. `decodedLen=1; tagLiteral, 4-byte length; not enough length bytes`,
  288. "\x01" + "\xfc\x00\x00\x00",
  289. "",
  290. ErrCorrupt,
  291. }, {
  292. `decodedLen=1; tagLiteral, 4-byte length; length=3; not enough dst bytes`,
  293. "\x01" + "\xfc\x02\x00\x00\x00\xff\xff\xff",
  294. "",
  295. ErrCorrupt,
  296. }, {
  297. `decodedLen=4; tagLiteral, 4-byte length; length=3; not enough src bytes`,
  298. "\x04" + "\xfc\x02\x00\x00\x00\xff",
  299. "",
  300. ErrCorrupt,
  301. }, {
  302. `decodedLen=3; tagLiteral, 4-byte length; length=3; valid input`,
  303. "\x03" + "\xfc\x02\x00\x00\x00\xff\xff\xff",
  304. "\xff\xff\xff",
  305. nil,
  306. }, {
  307. `decodedLen=4; tagCopy1, 1 extra length|offset byte; not enough extra bytes`,
  308. "\x04" + "\x01",
  309. "",
  310. ErrCorrupt,
  311. }, {
  312. `decodedLen=4; tagCopy2, 2 extra length|offset bytes; not enough extra bytes`,
  313. "\x04" + "\x02\x00",
  314. "",
  315. ErrCorrupt,
  316. }, {
  317. `decodedLen=4; tagCopy4, 4 extra length|offset bytes; not enough extra bytes`,
  318. "\x04" + "\x03\x00\x00\x00",
  319. "",
  320. ErrCorrupt,
  321. }, {
  322. `decodedLen=4; tagLiteral (4 bytes "abcd"); valid input`,
  323. "\x04" + "\x0cabcd",
  324. "abcd",
  325. nil,
  326. }, {
  327. `decodedLen=13; tagLiteral (4 bytes "abcd"); tagCopy1; length=9 offset=4; valid input`,
  328. "\x0d" + "\x0cabcd" + "\x15\x04",
  329. "abcdabcdabcda",
  330. nil,
  331. }, {
  332. `decodedLen=8; tagLiteral (4 bytes "abcd"); tagCopy1; length=4 offset=4; valid input`,
  333. "\x08" + "\x0cabcd" + "\x01\x04",
  334. "abcdabcd",
  335. nil,
  336. }, {
  337. `decodedLen=8; tagLiteral (4 bytes "abcd"); tagCopy1; length=4 offset=2; valid input`,
  338. "\x08" + "\x0cabcd" + "\x01\x02",
  339. "abcdcdcd",
  340. nil,
  341. }, {
  342. `decodedLen=8; tagLiteral (4 bytes "abcd"); tagCopy1; length=4 offset=1; valid input`,
  343. "\x08" + "\x0cabcd" + "\x01\x01",
  344. "abcddddd",
  345. nil,
  346. }, {
  347. `decodedLen=8; tagLiteral (4 bytes "abcd"); tagCopy1; length=4 offset=0; repeat offset as first match`,
  348. "\x08" + "\x0cabcd" + "\x01\x00",
  349. "",
  350. ErrCorrupt,
  351. }, {
  352. `decodedLen=13; tagLiteral (4 bytes "abcd"); tagCopy1; length=4 offset=1; literal: 'z'; tagCopy1; length=4 offset=0; repeat offset as second match`,
  353. "\x0d" + "\x0cabcd" + "\x01\x01" + "\x00z" + "\x01\x00",
  354. "abcdddddzzzzz",
  355. nil,
  356. }, {
  357. `decodedLen=9; tagLiteral (4 bytes "abcd"); tagCopy1; length=4 offset=4; inconsistent dLen`,
  358. "\x09" + "\x0cabcd" + "\x01\x04",
  359. "",
  360. ErrCorrupt,
  361. }, {
  362. `decodedLen=8; tagLiteral (4 bytes "abcd"); tagCopy1; length=4 offset=5; offset too large`,
  363. "\x08" + "\x0cabcd" + "\x01\x05",
  364. "",
  365. ErrCorrupt,
  366. }, {
  367. `decodedLen=7; tagLiteral (4 bytes "abcd"); tagCopy1; length=4 offset=4; length too large`,
  368. "\x07" + "\x0cabcd" + "\x01\x04",
  369. "",
  370. ErrCorrupt,
  371. }, {
  372. `decodedLen=6; tagLiteral (4 bytes "abcd"); tagCopy2; length=2 offset=3; valid input`,
  373. "\x06" + "\x0cabcd" + "\x06\x03\x00",
  374. "abcdbc",
  375. nil,
  376. }, {
  377. `decodedLen=6; tagLiteral (4 bytes "abcd"); tagCopy4; length=2 offset=3; valid input`,
  378. "\x06" + "\x0cabcd" + "\x07\x03\x00\x00\x00",
  379. "abcdbc",
  380. nil,
  381. }}
  382. const (
  383. // notPresentXxx defines a range of byte values [0xa0, 0xc5) that are
  384. // not present in either the input or the output. It is written to dBuf
  385. // to check that Decode does not write bytes past the end of
  386. // dBuf[:dLen].
  387. //
  388. // The magic number 37 was chosen because it is prime. A more 'natural'
  389. // number like 32 might lead to a false negative if, for example, a
  390. // byte was incorrectly copied 4*8 bytes later.
  391. notPresentBase = 0xa0
  392. notPresentLen = 37
  393. )
  394. var dBuf [100]byte
  395. loop:
  396. for i, tc := range testCases {
  397. input := []byte(tc.input)
  398. for _, x := range input {
  399. if notPresentBase <= x && x < notPresentBase+notPresentLen {
  400. t.Errorf("#%d (%s): input shouldn't contain %#02x\ninput: % x", i, tc.desc, x, input)
  401. continue loop
  402. }
  403. }
  404. dLen, n := binary.Uvarint(input)
  405. if n <= 0 {
  406. t.Errorf("#%d (%s): invalid varint-encoded dLen", i, tc.desc)
  407. continue
  408. }
  409. if dLen > uint64(len(dBuf)) {
  410. t.Errorf("#%d (%s): dLen %d is too large", i, tc.desc, dLen)
  411. continue
  412. }
  413. for j := range dBuf {
  414. dBuf[j] = byte(notPresentBase + j%notPresentLen)
  415. }
  416. g, gotErr := Decode(dBuf[:], input)
  417. if got := string(g); got != tc.want || gotErr != tc.wantErr {
  418. t.Errorf("#%d (%s):\ngot %q, %v\nwant %q, %v",
  419. i, tc.desc, got, gotErr, tc.want, tc.wantErr)
  420. continue
  421. }
  422. for j, x := range dBuf {
  423. if uint64(j) < dLen {
  424. continue
  425. }
  426. if w := byte(notPresentBase + j%notPresentLen); x != w {
  427. t.Errorf("#%d (%s): Decode overrun: dBuf[%d] was modified: got %#02x, want %#02x\ndBuf: % x",
  428. i, tc.desc, j, x, w, dBuf)
  429. continue loop
  430. }
  431. }
  432. }
  433. }
  434. func TestDecodeCopy4(t *testing.T) {
  435. dots := strings.Repeat(".", 65536)
  436. input := strings.Join([]string{
  437. "\x89\x80\x04", // decodedLen = 65545.
  438. "\x0cpqrs", // 4-byte literal "pqrs".
  439. "\xf4\xff\xff" + dots, // 65536-byte literal dots.
  440. "\x13\x04\x00\x01\x00", // tagCopy4; length=5 offset=65540.
  441. }, "")
  442. gotBytes, err := Decode(nil, []byte(input))
  443. if err != nil {
  444. t.Fatal(err)
  445. }
  446. got := string(gotBytes)
  447. want := "pqrs" + dots + "pqrs."
  448. if len(got) != len(want) {
  449. t.Fatalf("got %d bytes, want %d", len(got), len(want))
  450. }
  451. if got != want {
  452. for i := 0; i < len(got); i++ {
  453. if g, w := got[i], want[i]; g != w {
  454. t.Fatalf("byte #%d: got %#02x, want %#02x", i, g, w)
  455. }
  456. }
  457. }
  458. }
  459. // TestDecodeLengthOffset tests decoding an encoding of the form literal +
  460. // copy-length-offset + literal. For example: "abcdefghijkl" + "efghij" + "AB".
  461. func TestDecodeLengthOffset(t *testing.T) {
  462. const (
  463. prefix = "abcdefghijklmnopqr"
  464. suffix = "ABCDEFGHIJKLMNOPQR"
  465. // notPresentXxx defines a range of byte values [0xa0, 0xc5) that are
  466. // not present in either the input or the output. It is written to
  467. // gotBuf to check that Decode does not write bytes past the end of
  468. // gotBuf[:totalLen].
  469. //
  470. // The magic number 37 was chosen because it is prime. A more 'natural'
  471. // number like 32 might lead to a false negative if, for example, a
  472. // byte was incorrectly copied 4*8 bytes later.
  473. notPresentBase = 0xa0
  474. notPresentLen = 37
  475. )
  476. var gotBuf, wantBuf, inputBuf [128]byte
  477. for length := 1; length <= 18; length++ {
  478. for offset := 1; offset <= 18; offset++ {
  479. loop:
  480. for suffixLen := 0; suffixLen <= 18; suffixLen++ {
  481. totalLen := len(prefix) + length + suffixLen
  482. inputLen := binary.PutUvarint(inputBuf[:], uint64(totalLen))
  483. inputBuf[inputLen] = tagLiteral + 4*byte(len(prefix)-1)
  484. inputLen++
  485. inputLen += copy(inputBuf[inputLen:], prefix)
  486. inputBuf[inputLen+0] = tagCopy2 + 4*byte(length-1)
  487. inputBuf[inputLen+1] = byte(offset)
  488. inputBuf[inputLen+2] = 0x00
  489. inputLen += 3
  490. if suffixLen > 0 {
  491. inputBuf[inputLen] = tagLiteral + 4*byte(suffixLen-1)
  492. inputLen++
  493. inputLen += copy(inputBuf[inputLen:], suffix[:suffixLen])
  494. }
  495. input := inputBuf[:inputLen]
  496. for i := range gotBuf {
  497. gotBuf[i] = byte(notPresentBase + i%notPresentLen)
  498. }
  499. got, err := Decode(gotBuf[:], input)
  500. if err != nil {
  501. t.Errorf("length=%d, offset=%d; suffixLen=%d: %v", length, offset, suffixLen, err)
  502. continue
  503. }
  504. wantLen := 0
  505. wantLen += copy(wantBuf[wantLen:], prefix)
  506. for i := 0; i < length; i++ {
  507. wantBuf[wantLen] = wantBuf[wantLen-offset]
  508. wantLen++
  509. }
  510. wantLen += copy(wantBuf[wantLen:], suffix[:suffixLen])
  511. want := wantBuf[:wantLen]
  512. for _, x := range input {
  513. if notPresentBase <= x && x < notPresentBase+notPresentLen {
  514. t.Errorf("length=%d, offset=%d; suffixLen=%d: input shouldn't contain %#02x\ninput: % x",
  515. length, offset, suffixLen, x, input)
  516. continue loop
  517. }
  518. }
  519. for i, x := range gotBuf {
  520. if i < totalLen {
  521. continue
  522. }
  523. if w := byte(notPresentBase + i%notPresentLen); x != w {
  524. t.Errorf("length=%d, offset=%d; suffixLen=%d; totalLen=%d: "+
  525. "Decode overrun: gotBuf[%d] was modified: got %#02x, want %#02x\ngotBuf: % x",
  526. length, offset, suffixLen, totalLen, i, x, w, gotBuf)
  527. continue loop
  528. }
  529. }
  530. for _, x := range want {
  531. if notPresentBase <= x && x < notPresentBase+notPresentLen {
  532. t.Errorf("length=%d, offset=%d; suffixLen=%d: want shouldn't contain %#02x\nwant: % x",
  533. length, offset, suffixLen, x, want)
  534. continue loop
  535. }
  536. }
  537. if !bytes.Equal(got, want) {
  538. t.Errorf("length=%d, offset=%d; suffixLen=%d:\ninput % x\ngot % x\nwant % x",
  539. length, offset, suffixLen, input, got, want)
  540. continue
  541. }
  542. }
  543. }
  544. }
  545. }
  546. const (
  547. goldenText = "Mark.Twain-Tom.Sawyer.txt"
  548. goldenCompressed = goldenText + ".rawsnappy"
  549. )
  550. func TestDecodeGoldenInput(t *testing.T) {
  551. tDir := filepath.FromSlash(*testdataDir)
  552. src, err := ioutil.ReadFile(filepath.Join(tDir, goldenCompressed))
  553. if err != nil {
  554. t.Fatalf("ReadFile: %v", err)
  555. }
  556. got, err := Decode(nil, src)
  557. if err != nil {
  558. t.Fatalf("Decode: %v", err)
  559. }
  560. want, err := ioutil.ReadFile(filepath.Join(tDir, goldenText))
  561. if err != nil {
  562. t.Fatalf("ReadFile: %v", err)
  563. }
  564. if err := cmp(got, want); err != nil {
  565. t.Fatal(err)
  566. }
  567. }
  568. // TestSlowForwardCopyOverrun tests the "expand the pattern" algorithm
  569. // described in decode_amd64.s and its claim of a 10 byte overrun worst case.
  570. func TestSlowForwardCopyOverrun(t *testing.T) {
  571. const base = 100
  572. for length := 1; length < 18; length++ {
  573. for offset := 1; offset < 18; offset++ {
  574. highWaterMark := base
  575. d := base
  576. l := length
  577. o := offset
  578. // makeOffsetAtLeast8
  579. for o < 8 {
  580. if end := d + 8; highWaterMark < end {
  581. highWaterMark = end
  582. }
  583. l -= o
  584. d += o
  585. o += o
  586. }
  587. // fixUpSlowForwardCopy
  588. a := d
  589. d += l
  590. // finishSlowForwardCopy
  591. for l > 0 {
  592. if end := a + 8; highWaterMark < end {
  593. highWaterMark = end
  594. }
  595. a += 8
  596. l -= 8
  597. }
  598. dWant := base + length
  599. overrun := highWaterMark - dWant
  600. if d != dWant || overrun < 0 || 10 < overrun {
  601. t.Errorf("length=%d, offset=%d: d and overrun: got (%d, %d), want (%d, something in [0, 10])",
  602. length, offset, d, overrun, dWant)
  603. }
  604. }
  605. }
  606. }
  607. // TestEncoderSkip will test skipping various sizes and block types.
  608. func TestEncoderSkip(t *testing.T) {
  609. for ti, origLen := range []int{10 << 10, 256 << 10, 2 << 20, 8 << 20} {
  610. if testing.Short() && ti > 1 {
  611. break
  612. }
  613. t.Run(fmt.Sprint(origLen), func(t *testing.T) {
  614. src := make([]byte, origLen)
  615. rng := rand.New(rand.NewSource(1))
  616. firstHalf, secondHalf := src[:origLen/2], src[origLen/2:]
  617. bonus := secondHalf[len(secondHalf)-origLen/10:]
  618. for i := range firstHalf {
  619. // Incompressible.
  620. firstHalf[i] = uint8(rng.Intn(256))
  621. }
  622. for i := range secondHalf {
  623. // Easy to compress.
  624. secondHalf[i] = uint8(i & 32)
  625. }
  626. for i := range bonus {
  627. // Incompressible.
  628. bonus[i] = uint8(rng.Intn(256))
  629. }
  630. var dst bytes.Buffer
  631. enc := NewWriter(&dst, WriterBlockSize(64<<10))
  632. _, err := io.Copy(enc, bytes.NewBuffer(src))
  633. if err != nil {
  634. t.Fatal(err)
  635. }
  636. err = enc.Close()
  637. if err != nil {
  638. t.Fatal(err)
  639. }
  640. compressed := dst.Bytes()
  641. dec := NewReader(nil)
  642. for i := 0; i < len(src); i += len(src)/20 - 17 {
  643. t.Run(fmt.Sprint("skip-", i), func(t *testing.T) {
  644. want := src[i:]
  645. dec.Reset(bytes.NewBuffer(compressed))
  646. // Read some of it first
  647. read, err := io.CopyN(ioutil.Discard, dec, int64(len(want)/10))
  648. if err != nil {
  649. t.Fatal(err)
  650. }
  651. // skip what we just read.
  652. want = want[read:]
  653. err = dec.Skip(int64(i))
  654. if err != nil {
  655. t.Fatal(err)
  656. }
  657. got, err := ioutil.ReadAll(dec)
  658. if err != nil {
  659. t.Errorf("Skipping %d returned error: %v", i, err)
  660. return
  661. }
  662. if !bytes.Equal(want, got) {
  663. t.Log("got len:", len(got))
  664. t.Log("want len:", len(want))
  665. t.Errorf("Skipping %d did not return correct data (content mismatch)", i)
  666. return
  667. }
  668. })
  669. if testing.Short() && i > 0 {
  670. return
  671. }
  672. }
  673. })
  674. }
  675. }
  676. // TestEncodeNoiseThenRepeats encodes input for which the first half is very
  677. // incompressible and the second half is very compressible. The encoded form's
  678. // length should be closer to 50% of the original length than 100%.
  679. func TestEncodeNoiseThenRepeats(t *testing.T) {
  680. for _, origLen := range []int{256 * 1024, 2048 * 1024} {
  681. src := make([]byte, origLen)
  682. rng := rand.New(rand.NewSource(1))
  683. firstHalf, secondHalf := src[:origLen/2], src[origLen/2:]
  684. for i := range firstHalf {
  685. firstHalf[i] = uint8(rng.Intn(256))
  686. }
  687. for i := range secondHalf {
  688. secondHalf[i] = uint8(i >> 8)
  689. }
  690. dst := Encode(nil, src)
  691. if got, want := len(dst), origLen*3/4; got >= want {
  692. t.Fatalf("origLen=%d: got %d encoded bytes, want less than %d", origLen, got, want)
  693. }
  694. t.Log(len(dst))
  695. }
  696. }
  697. func TestFramingFormat(t *testing.T) {
  698. // src is comprised of alternating 1e5-sized sequences of random
  699. // (incompressible) bytes and repeated (compressible) bytes. 1e5 was chosen
  700. // because it is larger than maxBlockSize (64k).
  701. src := make([]byte, 1e6)
  702. rng := rand.New(rand.NewSource(1))
  703. for i := 0; i < 10; i++ {
  704. if i%2 == 0 {
  705. for j := 0; j < 1e5; j++ {
  706. src[1e5*i+j] = uint8(rng.Intn(256))
  707. }
  708. } else {
  709. for j := 0; j < 1e5; j++ {
  710. src[1e5*i+j] = uint8(i)
  711. }
  712. }
  713. }
  714. buf := new(bytes.Buffer)
  715. bw := NewWriter(buf)
  716. if _, err := bw.Write(src); err != nil {
  717. t.Fatalf("Write: encoding: %v", err)
  718. }
  719. err := bw.Close()
  720. if err != nil {
  721. t.Fatal(err)
  722. }
  723. dst, err := ioutil.ReadAll(NewReader(buf))
  724. if err != nil {
  725. t.Fatalf("ReadAll: decoding: %v", err)
  726. }
  727. if err := cmp(dst, src); err != nil {
  728. t.Fatal(err)
  729. }
  730. }
  731. func TestFramingFormatBetter(t *testing.T) {
  732. // src is comprised of alternating 1e5-sized sequences of random
  733. // (incompressible) bytes and repeated (compressible) bytes. 1e5 was chosen
  734. // because it is larger than maxBlockSize (64k).
  735. src := make([]byte, 1e6)
  736. rng := rand.New(rand.NewSource(1))
  737. for i := 0; i < 10; i++ {
  738. if i%2 == 0 {
  739. for j := 0; j < 1e5; j++ {
  740. src[1e5*i+j] = uint8(rng.Intn(256))
  741. }
  742. } else {
  743. for j := 0; j < 1e5; j++ {
  744. src[1e5*i+j] = uint8(i)
  745. }
  746. }
  747. }
  748. buf := new(bytes.Buffer)
  749. bw := NewWriter(buf, WriterBetterCompression())
  750. if _, err := bw.Write(src); err != nil {
  751. t.Fatalf("Write: encoding: %v", err)
  752. }
  753. err := bw.Close()
  754. if err != nil {
  755. t.Fatal(err)
  756. }
  757. dst, err := ioutil.ReadAll(NewReader(buf))
  758. if err != nil {
  759. t.Fatalf("ReadAll: decoding: %v", err)
  760. }
  761. if err := cmp(dst, src); err != nil {
  762. t.Fatal(err)
  763. }
  764. }
  765. func TestEmitLiteral(t *testing.T) {
  766. testCases := []struct {
  767. length int
  768. want string
  769. }{
  770. {1, "\x00"},
  771. {2, "\x04"},
  772. {59, "\xe8"},
  773. {60, "\xec"},
  774. {61, "\xf0\x3c"},
  775. {62, "\xf0\x3d"},
  776. {254, "\xf0\xfd"},
  777. {255, "\xf0\xfe"},
  778. {256, "\xf0\xff"},
  779. {257, "\xf4\x00\x01"},
  780. {65534, "\xf4\xfd\xff"},
  781. {65535, "\xf4\xfe\xff"},
  782. {65536, "\xf4\xff\xff"},
  783. }
  784. dst := make([]byte, 70000)
  785. nines := bytes.Repeat([]byte{0x99}, 65536)
  786. for _, tc := range testCases {
  787. lit := nines[:tc.length]
  788. n := emitLiteral(dst, lit)
  789. if !bytes.HasSuffix(dst[:n], lit) {
  790. t.Errorf("length=%d: did not end with that many literal bytes", tc.length)
  791. continue
  792. }
  793. got := string(dst[:n-tc.length])
  794. if got != tc.want {
  795. t.Errorf("length=%d:\ngot % x\nwant % x", tc.length, got, tc.want)
  796. continue
  797. }
  798. }
  799. }
  800. func TestEmitCopy(t *testing.T) {
  801. testCases := []struct {
  802. offset int
  803. length int
  804. want string
  805. }{
  806. {8, 04, "\x01\x08"},
  807. {8, 11, "\x1d\x08"},
  808. {8, 12, "\x2e\x08\x00"},
  809. {8, 13, "\x32\x08\x00"},
  810. {8, 59, "\xea\x08\x00"},
  811. {8, 60, "\xee\x08\x00"},
  812. {8, 61, "\xf2\x08\x00"},
  813. {8, 62, "\xf6\x08\x00"},
  814. {8, 63, "\xfa\x08\x00"},
  815. {8, 64, "\xfe\x08\x00"},
  816. {8, 65, "\xee\x08\x00\x05\x00"},
  817. {8, 66, "\xee\x08\x00\x09\x00"},
  818. {8, 67, "\xee\x08\x00\x0d\x00"},
  819. {8, 68, "\xee\x08\x00\x11\x00"},
  820. {8, 69, "\xee\x08\x00\x15\x08"},
  821. {8, 80, "\xee\x08\x00\x15\x00\x0c"},
  822. {8, 800, "\xee\x08\x00\x19\x00\xe0\x01"},
  823. {8, 800000, "\xee\x08\x00\x1d\x00\xc0\x34\x0b"},
  824. {256, 04, "\x21\x00"},
  825. {256, 11, "\x3d\x00"},
  826. {256, 12, "\x2e\x00\x01"},
  827. {256, 13, "\x32\x00\x01"},
  828. {256, 59, "\xea\x00\x01"},
  829. {256, 60, "\xee\x00\x01"},
  830. {256, 61, "\xf2\x00\x01"},
  831. {256, 62, "\xf6\x00\x01"},
  832. {256, 63, "\xfa\x00\x01"},
  833. {256, 64, "\xfe\x00\x01"},
  834. {256, 65, "\xee\x00\x01\x05\x00"},
  835. {256, 66, "\xee\x00\x01\x09\x00"},
  836. {256, 67, "\xee\x00\x01\x0d\x00"},
  837. {256, 68, "\xee\x00\x01\x11\x00"},
  838. {256, 69, "\xee\x00\x01\x35\x00"},
  839. {256, 80, "\xee\x00\x01\x15\x00\x0c"},
  840. {256, 800, "\xee\x00\x01\x19\x00\xe0\x01"},
  841. {256, 80000, "\xee\x00\x01\x1d\x00\x40\x38\x00"},
  842. {2048, 04, "\x0e\x00\x08"},
  843. {2048, 11, "\x2a\x00\x08"},
  844. {2048, 12, "\x2e\x00\x08"},
  845. {2048, 13, "\x32\x00\x08"},
  846. {2048, 59, "\xea\x00\x08"},
  847. {2048, 60, "\xee\x00\x08"},
  848. {2048, 61, "\xf2\x00\x08"},
  849. {2048, 62, "\xf6\x00\x08"},
  850. {2048, 63, "\xfa\x00\x08"},
  851. {2048, 64, "\xfe\x00\x08"},
  852. {2048, 65, "\xee\x00\x08\x05\x00"},
  853. {2048, 66, "\xee\x00\x08\x09\x00"},
  854. {2048, 67, "\xee\x00\x08\x0d\x00"},
  855. {2048, 68, "\xee\x00\x08\x11\x00"},
  856. {2048, 69, "\xee\x00\x08\x15\x00\x01"},
  857. {2048, 80, "\xee\x00\x08\x15\x00\x0c"},
  858. {2048, 800, "\xee\x00\x08\x19\x00\xe0\x01"},
  859. {2048, 80000, "\xee\x00\x08\x1d\x00\x40\x38\x00"},
  860. {204800, 04, "\x0f\x00\x20\x03\x00"},
  861. {204800, 65, "\xff\x00\x20\x03\x00\x03\x00\x20\x03\x00"},
  862. {204800, 69, "\xff\x00\x20\x03\x00\x05\x00"},
  863. {204800, 800, "\xff\x00\x20\x03\x00\x19\x00\xdc\x01"},
  864. {204800, 80000, "\xff\x00\x20\x03\x00\x1d\x00\x3c\x38\x00"},
  865. }
  866. dst := make([]byte, 1024)
  867. for _, tc := range testCases {
  868. n := emitCopy(dst, tc.offset, tc.length)
  869. got := string(dst[:n])
  870. if got != tc.want {
  871. t.Errorf("offset=%d, length=%d:\ngot % x\nwant % x", tc.offset, tc.length, got, tc.want)
  872. }
  873. }
  874. }
  875. func TestNewWriter(t *testing.T) {
  876. // Test all 32 possible sub-sequences of these 5 input slices.
  877. //
  878. // Their lengths sum to 400,000, which is over 6 times the Writer ibuf
  879. // capacity: 6 * maxBlockSize is 393,216.
  880. inputs := [][]byte{
  881. bytes.Repeat([]byte{'a'}, 40000),
  882. bytes.Repeat([]byte{'b'}, 150000),
  883. bytes.Repeat([]byte{'c'}, 60000),
  884. bytes.Repeat([]byte{'d'}, 120000),
  885. bytes.Repeat([]byte{'e'}, 30000),
  886. }
  887. loop:
  888. for i := 0; i < 1<<uint(len(inputs)); i++ {
  889. var want []byte
  890. buf := new(bytes.Buffer)
  891. w := NewWriter(buf)
  892. for j, input := range inputs {
  893. if i&(1<<uint(j)) == 0 {
  894. continue
  895. }
  896. if _, err := w.Write(input); err != nil {
  897. t.Errorf("i=%#02x: j=%d: Write: %v", i, j, err)
  898. continue loop
  899. }
  900. want = append(want, input...)
  901. }
  902. if err := w.Close(); err != nil {
  903. t.Errorf("i=%#02x: Close: %v", i, err)
  904. continue
  905. }
  906. got, err := ioutil.ReadAll(NewReader(buf))
  907. if err != nil {
  908. t.Errorf("i=%#02x: ReadAll: %v", i, err)
  909. continue
  910. }
  911. if err := cmp(got, want); err != nil {
  912. t.Errorf("i=%#02x: %v", i, err)
  913. continue
  914. }
  915. }
  916. }
  917. func TestFlush(t *testing.T) {
  918. buf := new(bytes.Buffer)
  919. w := NewWriter(buf)
  920. defer w.Close()
  921. if _, err := w.Write(bytes.Repeat([]byte{'x'}, 20)); err != nil {
  922. t.Fatalf("Write: %v", err)
  923. }
  924. if n := buf.Len(); n != 0 {
  925. t.Fatalf("before Flush: %d bytes were written to the underlying io.Writer, want 0", n)
  926. }
  927. if err := w.Flush(); err != nil {
  928. t.Fatalf("Flush: %v", err)
  929. }
  930. if n := buf.Len(); n == 0 {
  931. t.Fatalf("after Flush: %d bytes were written to the underlying io.Writer, want non-0", n)
  932. }
  933. }
  934. func TestReaderUncompressedDataOK(t *testing.T) {
  935. r := NewReader(strings.NewReader(magicChunk +
  936. "\x01\x08\x00\x00" + // Uncompressed chunk, 8 bytes long (including 4 byte checksum).
  937. "\x68\x10\xe6\xb6" + // Checksum.
  938. "\x61\x62\x63\x64", // Uncompressed payload: "abcd".
  939. ))
  940. g, err := ioutil.ReadAll(r)
  941. if err != nil {
  942. t.Fatal(err)
  943. }
  944. if got, want := string(g), "abcd"; got != want {
  945. t.Fatalf("got %q, want %q", got, want)
  946. }
  947. }
  948. func TestReaderUncompressedDataNoPayload(t *testing.T) {
  949. r := NewReader(strings.NewReader(magicChunk +
  950. "\x01\x04\x00\x00" + // Uncompressed chunk, 4 bytes long.
  951. "", // No payload; corrupt input.
  952. ))
  953. if _, err := ioutil.ReadAll(r); err != ErrCorrupt {
  954. t.Fatalf("got %v, want %v", err, ErrCorrupt)
  955. }
  956. }
  957. func TestReaderUncompressedDataTooLong(t *testing.T) {
  958. // The maximum legal chunk length... is 4MB + 4 bytes checksum.
  959. n := maxBlockSize + checksumSize
  960. n32 := uint32(n)
  961. r := NewReader(strings.NewReader(magicChunk +
  962. // Uncompressed chunk, n bytes long.
  963. string([]byte{chunkTypeUncompressedData, uint8(n32), uint8(n32 >> 8), uint8(n32 >> 16)}) +
  964. strings.Repeat("\x00", n),
  965. ))
  966. // CRC is not set, so we should expect that error.
  967. if _, err := ioutil.ReadAll(r); err != ErrCRC {
  968. t.Fatalf("got %v, want %v", err, ErrCRC)
  969. }
  970. // test first invalid.
  971. n++
  972. n32 = uint32(n)
  973. r = NewReader(strings.NewReader(magicChunk +
  974. // Uncompressed chunk, n bytes long.
  975. string([]byte{chunkTypeUncompressedData, uint8(n32), uint8(n32 >> 8), uint8(n32 >> 16)}) +
  976. strings.Repeat("\x00", n),
  977. ))
  978. if _, err := ioutil.ReadAll(r); err != ErrCorrupt {
  979. t.Fatalf("got %v, want %v", err, ErrCorrupt)
  980. }
  981. }
  982. func TestReaderReset(t *testing.T) {
  983. gold := bytes.Repeat([]byte("All that is gold does not glitter,\n"), 10000)
  984. buf := new(bytes.Buffer)
  985. w := NewWriter(buf)
  986. _, err := w.Write(gold)
  987. if err != nil {
  988. t.Fatalf("Write: %v", err)
  989. }
  990. err = w.Close()
  991. if err != nil {
  992. t.Fatalf("Close: %v", err)
  993. }
  994. encoded, invalid, partial := buf.String(), "invalid", "partial"
  995. r := NewReader(nil)
  996. for i, s := range []string{encoded, invalid, partial, encoded, partial, invalid, encoded, encoded} {
  997. if s == partial {
  998. r.Reset(strings.NewReader(encoded))
  999. if _, err := r.Read(make([]byte, 101)); err != nil {
  1000. t.Errorf("#%d: %v", i, err)
  1001. continue
  1002. }
  1003. continue
  1004. }
  1005. r.Reset(strings.NewReader(s))
  1006. got, err := ioutil.ReadAll(r)
  1007. switch s {
  1008. case encoded:
  1009. if err != nil {
  1010. t.Errorf("#%d: %v", i, err)
  1011. continue
  1012. }
  1013. if err := cmp(got, gold); err != nil {
  1014. t.Errorf("#%d: %v", i, err)
  1015. continue
  1016. }
  1017. case invalid:
  1018. if err == nil {
  1019. t.Errorf("#%d: got nil error, want non-nil", i)
  1020. continue
  1021. }
  1022. }
  1023. }
  1024. }
  1025. func TestWriterReset(t *testing.T) {
  1026. gold := bytes.Repeat([]byte("Not all those who wander are lost;\n"), 10000)
  1027. const n = 20
  1028. var w *Writer
  1029. w = NewWriter(nil)
  1030. defer w.Close()
  1031. var gots, wants [][]byte
  1032. failed := false
  1033. for i := 0; i <= n; i++ {
  1034. buf := new(bytes.Buffer)
  1035. w.Reset(buf)
  1036. want := gold[:len(gold)*i/n]
  1037. if _, err := w.Write(want); err != nil {
  1038. t.Errorf("#%d: Write: %v", i, err)
  1039. failed = true
  1040. continue
  1041. }
  1042. if err := w.Flush(); err != nil {
  1043. t.Errorf("#%d: Flush: %v", i, err)
  1044. failed = true
  1045. got, err := ioutil.ReadAll(NewReader(buf))
  1046. if err != nil {
  1047. t.Errorf("#%d: ReadAll: %v", i, err)
  1048. failed = true
  1049. continue
  1050. }
  1051. gots = append(gots, got)
  1052. wants = append(wants, want)
  1053. }
  1054. if failed {
  1055. continue
  1056. }
  1057. for i := range gots {
  1058. if err := cmp(gots[i], wants[i]); err != nil {
  1059. t.Errorf("#%d: %v", i, err)
  1060. }
  1061. }
  1062. }
  1063. }
  1064. func TestWriterResetWithoutFlush(t *testing.T) {
  1065. buf0 := new(bytes.Buffer)
  1066. buf1 := new(bytes.Buffer)
  1067. w := NewWriter(buf0)
  1068. if _, err := w.Write([]byte("xxx")); err != nil {
  1069. t.Fatalf("Write #0: %v", err)
  1070. }
  1071. // Note that we don't Flush the Writer before calling Reset.
  1072. w.Reset(buf1)
  1073. if _, err := w.Write([]byte("yyy")); err != nil {
  1074. t.Fatalf("Write #1: %v", err)
  1075. }
  1076. if err := w.Flush(); err != nil {
  1077. t.Fatalf("Flush: %v", err)
  1078. }
  1079. got, err := ioutil.ReadAll(NewReader(buf1))
  1080. if err != nil {
  1081. t.Fatalf("ReadAll: %v", err)
  1082. }
  1083. if err := cmp(got, []byte("yyy")); err != nil {
  1084. t.Fatal(err)
  1085. }
  1086. }
  1087. type writeCounter int
  1088. func (c *writeCounter) Write(p []byte) (int, error) {
  1089. *c++
  1090. return len(p), nil
  1091. }
  1092. // TestNumUnderlyingWrites tests that each Writer flush only makes one or two
  1093. // Write calls on its underlying io.Writer, depending on whether or not the
  1094. // flushed buffer was compressible.
  1095. func TestNumUnderlyingWrites(t *testing.T) {
  1096. testCases := []struct {
  1097. input []byte
  1098. want int
  1099. }{
  1100. // Magic header + block
  1101. {bytes.Repeat([]byte{'x'}, 100), 2},
  1102. // One block each:
  1103. {bytes.Repeat([]byte{'y'}, 100), 1},
  1104. {[]byte("ABCDEFGHIJKLMNOPQRST"), 1},
  1105. }
  1106. // If we are doing sync writes, we write uncompressed as two writes.
  1107. if runtime.GOMAXPROCS(0) == 1 {
  1108. testCases[2].want++
  1109. }
  1110. var c writeCounter
  1111. w := NewWriter(&c)
  1112. defer w.Close()
  1113. for i, tc := range testCases {
  1114. c = 0
  1115. if _, err := w.Write(tc.input); err != nil {
  1116. t.Errorf("#%d: Write: %v", i, err)
  1117. continue
  1118. }
  1119. if err := w.Flush(); err != nil {
  1120. t.Errorf("#%d: Flush: %v", i, err)
  1121. continue
  1122. }
  1123. if int(c) != tc.want {
  1124. t.Errorf("#%d: got %d underlying writes, want %d", i, c, tc.want)
  1125. continue
  1126. }
  1127. }
  1128. }
  1129. func testWriterRoundtrip(t *testing.T, src []byte, opts ...WriterOption) {
  1130. var buf bytes.Buffer
  1131. enc := NewWriter(&buf, opts...)
  1132. n, err := enc.Write(src)
  1133. if err != nil {
  1134. t.Error(err)
  1135. return
  1136. }
  1137. if n != len(src) {
  1138. t.Error(io.ErrShortWrite)
  1139. return
  1140. }
  1141. err = enc.Flush()
  1142. if err != nil {
  1143. t.Error(err)
  1144. return
  1145. }
  1146. t.Logf("encoded to %d -> %d bytes", len(src), buf.Len())
  1147. dec := NewReader(&buf)
  1148. decoded, err := ioutil.ReadAll(dec)
  1149. if err != nil {
  1150. t.Error(err)
  1151. return
  1152. }
  1153. if len(decoded) != len(src) {
  1154. t.Error("decoded len:", len(decoded), "!=", len(src))
  1155. return
  1156. }
  1157. err = cmp(src, decoded)
  1158. if err != nil {
  1159. t.Error(err)
  1160. }
  1161. }
  1162. func testBlockRoundtrip(t *testing.T, src []byte) {
  1163. dst := Encode(nil, src)
  1164. t.Logf("encoded to %d -> %d bytes", len(src), len(dst))
  1165. decoded, err := Decode(nil, dst)
  1166. if err != nil {
  1167. t.Error(err)
  1168. return
  1169. }
  1170. if len(decoded) != len(src) {
  1171. t.Error("decoded len:", len(decoded), "!=", len(src))
  1172. return
  1173. }
  1174. err = cmp(decoded, src)
  1175. if err != nil {
  1176. t.Error(err)
  1177. }
  1178. }
  1179. func testBetterBlockRoundtrip(t *testing.T, src []byte) {
  1180. dst := EncodeBetter(nil, src)
  1181. t.Logf("encoded to %d -> %d bytes", len(src), len(dst))
  1182. decoded, err := Decode(nil, dst)
  1183. if err != nil {
  1184. t.Error(err)
  1185. return
  1186. }
  1187. if len(decoded) != len(src) {
  1188. t.Error("decoded len:", len(decoded), "!=", len(src))
  1189. return
  1190. }
  1191. err = cmp(src, decoded)
  1192. if err != nil {
  1193. t.Error(err)
  1194. }
  1195. }
  1196. func testSnappyDecode(t *testing.T, src []byte) {
  1197. var buf bytes.Buffer
  1198. enc := snappy.NewBufferedWriter(&buf)
  1199. n, err := enc.Write(src)
  1200. if err != nil {
  1201. t.Error(err)
  1202. return
  1203. }
  1204. if n != len(src) {
  1205. t.Error(io.ErrShortWrite)
  1206. return
  1207. }
  1208. t.Logf("encoded to %d -> %d bytes", len(src), buf.Len())
  1209. dec := NewReader(&buf)
  1210. decoded, err := ioutil.ReadAll(dec)
  1211. if err != nil {
  1212. t.Error(err)
  1213. return
  1214. }
  1215. if len(decoded) != len(src) {
  1216. t.Error("decoded len:", len(decoded), "!=", len(src))
  1217. return
  1218. }
  1219. err = cmp(src, decoded)
  1220. if err != nil {
  1221. t.Error(err)
  1222. }
  1223. }
  1224. func benchDecode(b *testing.B, src []byte) {
  1225. encoded := Encode(nil, src)
  1226. // Bandwidth is in amount of uncompressed data.
  1227. b.SetBytes(int64(len(src)))
  1228. b.ResetTimer()
  1229. for i := 0; i < b.N; i++ {
  1230. Decode(src, encoded)
  1231. }
  1232. }
  1233. func benchDecodeBetter(b *testing.B, src []byte) {
  1234. encoded := EncodeBetter(nil, src)
  1235. // Bandwidth is in amount of uncompressed data.
  1236. b.SetBytes(int64(len(src)))
  1237. b.ResetTimer()
  1238. for i := 0; i < b.N; i++ {
  1239. Decode(src, encoded)
  1240. }
  1241. }
  1242. func benchEncode(b *testing.B, src []byte) {
  1243. // Bandwidth is in amount of uncompressed data.
  1244. b.SetBytes(int64(len(src)))
  1245. dst := make([]byte, MaxEncodedLen(len(src)))
  1246. b.ResetTimer()
  1247. for i := 0; i < b.N; i++ {
  1248. Encode(dst, src)
  1249. }
  1250. }
  1251. func benchEncodeBetter(b *testing.B, src []byte) {
  1252. // Bandwidth is in amount of uncompressed data.
  1253. b.SetBytes(int64(len(src)))
  1254. dst := make([]byte, MaxEncodedLen(len(src)))
  1255. b.ResetTimer()
  1256. for i := 0; i < b.N; i++ {
  1257. EncodeBetter(dst, src)
  1258. }
  1259. }
  1260. func testOrBenchmark(b testing.TB) string {
  1261. if _, ok := b.(*testing.B); ok {
  1262. return "benchmark"
  1263. }
  1264. return "test"
  1265. }
  1266. func readFile(b testing.TB, filename string) []byte {
  1267. src, err := ioutil.ReadFile(filename)
  1268. if err != nil {
  1269. b.Skipf("skipping %s: %v", testOrBenchmark(b), err)
  1270. }
  1271. if len(src) == 0 {
  1272. b.Fatalf("%s has zero length", filename)
  1273. }
  1274. return src
  1275. }
  1276. // expand returns a slice of length n containing repeated copies of src.
  1277. func expand(src []byte, n int) []byte {
  1278. dst := make([]byte, n)
  1279. for x := dst; len(x) > 0; {
  1280. i := copy(x, src)
  1281. x = x[i:]
  1282. }
  1283. return dst
  1284. }
  1285. func benchWords(b *testing.B, n int, decode bool) {
  1286. // Note: the file is OS-language dependent so the resulting values are not
  1287. // directly comparable for non-US-English OS installations.
  1288. data := expand(readFile(b, "/usr/share/dict/words"), n)
  1289. if decode {
  1290. benchDecode(b, data)
  1291. } else {
  1292. benchEncode(b, data)
  1293. }
  1294. }
  1295. func BenchmarkWordsDecode1e1(b *testing.B) { benchWords(b, 1e1, true) }
  1296. func BenchmarkWordsDecode1e2(b *testing.B) { benchWords(b, 1e2, true) }
  1297. func BenchmarkWordsDecode1e3(b *testing.B) { benchWords(b, 1e3, true) }
  1298. func BenchmarkWordsDecode1e4(b *testing.B) { benchWords(b, 1e4, true) }
  1299. func BenchmarkWordsDecode1e5(b *testing.B) { benchWords(b, 1e5, true) }
  1300. func BenchmarkWordsDecode1e6(b *testing.B) { benchWords(b, 1e6, true) }
  1301. func BenchmarkWordsEncode1e1(b *testing.B) { benchWords(b, 1e1, false) }
  1302. func BenchmarkWordsEncode1e2(b *testing.B) { benchWords(b, 1e2, false) }
  1303. func BenchmarkWordsEncode1e3(b *testing.B) { benchWords(b, 1e3, false) }
  1304. func BenchmarkWordsEncode1e4(b *testing.B) { benchWords(b, 1e4, false) }
  1305. func BenchmarkWordsEncode1e5(b *testing.B) { benchWords(b, 1e5, false) }
  1306. func BenchmarkWordsEncode1e6(b *testing.B) { benchWords(b, 1e6, false) }
  1307. func BenchmarkRandomEncode(b *testing.B) {
  1308. rng := rand.New(rand.NewSource(1))
  1309. data := make([]byte, 1<<20)
  1310. for i := range data {
  1311. data[i] = uint8(rng.Intn(256))
  1312. }
  1313. benchEncode(b, data)
  1314. }
  1315. func BenchmarkRandomEncodeBetter(b *testing.B) {
  1316. rng := rand.New(rand.NewSource(1))
  1317. data := make([]byte, 1<<20)
  1318. for i := range data {
  1319. data[i] = uint8(rng.Intn(256))
  1320. }
  1321. benchEncodeBetter(b, data)
  1322. }
  1323. // testFiles' values are copied directly from
  1324. // https://raw.githubusercontent.com/google/snappy/master/snappy_unittest.cc
  1325. // The label field is unused in snappy-go.
  1326. var testFiles = []struct {
  1327. label string
  1328. filename string
  1329. sizeLimit int
  1330. }{
  1331. {"html", "html", 0},
  1332. {"urls", "urls.10K", 0},
  1333. {"jpg", "fireworks.jpeg", 0},
  1334. {"jpg_200b", "fireworks.jpeg", 200},
  1335. {"pdf", "paper-100k.pdf", 0},
  1336. {"html4", "html_x_4", 0},
  1337. {"txt1", "alice29.txt", 0},
  1338. {"txt2", "asyoulik.txt", 0},
  1339. {"txt3", "lcet10.txt", 0},
  1340. {"txt4", "plrabn12.txt", 0},
  1341. {"pb", "geo.protodata", 0},
  1342. {"gaviota", "kppkn.gtb", 0},
  1343. {"txt1_128b", "alice29.txt", 128},
  1344. {"txt1_1000b", "alice29.txt", 1000},
  1345. {"txt1_10000b", "alice29.txt", 10000},
  1346. {"txt1_20000b", "alice29.txt", 20000},
  1347. }
  1348. const (
  1349. // The benchmark data files are at this canonical URL.
  1350. benchURL = "https://raw.githubusercontent.com/google/snappy/master/testdata/"
  1351. )
  1352. func downloadBenchmarkFiles(b testing.TB, basename string) (errRet error) {
  1353. bDir := filepath.FromSlash(*benchdataDir)
  1354. filename := filepath.Join(bDir, basename)
  1355. if stat, err := os.Stat(filename); err == nil && stat.Size() != 0 {
  1356. return nil
  1357. }
  1358. if !*download {
  1359. b.Skipf("test data not found; skipping %s without the -download flag", testOrBenchmark(b))
  1360. }
  1361. // Download the official snappy C++ implementation reference test data
  1362. // files for benchmarking.
  1363. if err := os.MkdirAll(bDir, 0777); err != nil && !os.IsExist(err) {
  1364. return fmt.Errorf("failed to create %s: %s", bDir, err)
  1365. }
  1366. f, err := os.Create(filename)
  1367. if err != nil {
  1368. return fmt.Errorf("failed to create %s: %s", filename, err)
  1369. }
  1370. defer f.Close()
  1371. defer func() {
  1372. if errRet != nil {
  1373. os.Remove(filename)
  1374. }
  1375. }()
  1376. url := benchURL + basename
  1377. resp, err := http.Get(url)
  1378. if err != nil {
  1379. return fmt.Errorf("failed to download %s: %s", url, err)
  1380. }
  1381. defer resp.Body.Close()
  1382. if s := resp.StatusCode; s != http.StatusOK {
  1383. return fmt.Errorf("downloading %s: HTTP status code %d (%s)", url, s, http.StatusText(s))
  1384. }
  1385. _, err = io.Copy(f, resp.Body)
  1386. if err != nil {
  1387. return fmt.Errorf("failed to download %s to %s: %s", url, filename, err)
  1388. }
  1389. return nil
  1390. }
  1391. func benchFile(b *testing.B, i int, decode bool) {
  1392. if err := downloadBenchmarkFiles(b, testFiles[i].filename); err != nil {
  1393. b.Fatalf("failed to download testdata: %s", err)
  1394. }
  1395. bDir := filepath.FromSlash(*benchdataDir)
  1396. data := readFile(b, filepath.Join(bDir, testFiles[i].filename))
  1397. var once sync.Once
  1398. b.Run("block", func(b *testing.B) {
  1399. if n := testFiles[i].sizeLimit; 0 < n && n < len(data) {
  1400. data = data[:n]
  1401. }
  1402. if decode {
  1403. b.SetBytes(int64(len(data)))
  1404. b.ResetTimer()
  1405. b.RunParallel(func(pb *testing.PB) {
  1406. encoded := Encode(nil, data)
  1407. once.Do(func() {
  1408. if testing.Verbose() {
  1409. b.Log(len(encoded), " -> ", len(data))
  1410. }
  1411. })
  1412. tmp := make([]byte, len(data))
  1413. for pb.Next() {
  1414. var err error
  1415. tmp, err = Decode(tmp, encoded)
  1416. if err != nil {
  1417. b.Fatal(err)
  1418. }
  1419. }
  1420. })
  1421. } else {
  1422. b.SetBytes(int64(len(data)))
  1423. b.ResetTimer()
  1424. once.Do(func() {
  1425. if testing.Verbose() {
  1426. b.Log(len(data), " -> ", len(Encode(nil, data)))
  1427. }
  1428. })
  1429. b.RunParallel(func(pb *testing.PB) {
  1430. dst := make([]byte, MaxEncodedLen(len(data)))
  1431. tmp := make([]byte, len(data))
  1432. for pb.Next() {
  1433. res := Encode(dst, data)
  1434. if len(res) == 0 {
  1435. panic(0)
  1436. }
  1437. if false {
  1438. tmp, _ = Decode(tmp, res)
  1439. if !bytes.Equal(tmp, data) {
  1440. panic("wrong")
  1441. }
  1442. }
  1443. }
  1444. })
  1445. }
  1446. })
  1447. once = sync.Once{}
  1448. b.Run("block-better", func(b *testing.B) {
  1449. if decode {
  1450. b.SetBytes(int64(len(data)))
  1451. b.ResetTimer()
  1452. b.RunParallel(func(pb *testing.PB) {
  1453. encoded := EncodeBetter(nil, data)
  1454. tmp := make([]byte, len(data))
  1455. once.Do(func() {
  1456. if testing.Verbose() {
  1457. b.Log(len(encoded), " -> ", len(data))
  1458. }
  1459. })
  1460. for pb.Next() {
  1461. var err error
  1462. tmp, err = Decode(tmp, encoded)
  1463. if err != nil {
  1464. b.Fatal(err)
  1465. }
  1466. }
  1467. })
  1468. } else {
  1469. b.SetBytes(int64(len(data)))
  1470. b.ResetTimer()
  1471. b.RunParallel(func(pb *testing.PB) {
  1472. once.Do(func() {
  1473. if testing.Verbose() {
  1474. b.Log(len(data), " -> ", len(EncodeBetter(nil, data)))
  1475. }
  1476. })
  1477. dst := make([]byte, MaxEncodedLen(len(data)))
  1478. tmp := make([]byte, len(data))
  1479. for pb.Next() {
  1480. res := EncodeBetter(dst, data)
  1481. if len(res) == 0 {
  1482. panic(0)
  1483. }
  1484. if false {
  1485. tmp, _ = Decode(tmp, res)
  1486. if !bytes.Equal(tmp, data) {
  1487. panic("wrong")
  1488. }
  1489. }
  1490. }
  1491. })
  1492. }
  1493. })
  1494. }
  1495. func benchFileSnappy(b *testing.B, i int, decode bool) {
  1496. if err := downloadBenchmarkFiles(b, testFiles[i].filename); err != nil {
  1497. b.Fatalf("failed to download testdata: %s", err)
  1498. }
  1499. bDir := filepath.FromSlash(*benchdataDir)
  1500. data := readFile(b, filepath.Join(bDir, testFiles[i].filename))
  1501. var once sync.Once
  1502. if n := testFiles[i].sizeLimit; 0 < n && n < len(data) {
  1503. data = data[:n]
  1504. }
  1505. b.Run("snappy", func(b *testing.B) {
  1506. if decode {
  1507. b.SetBytes(int64(len(data)))
  1508. b.ResetTimer()
  1509. b.RunParallel(func(pb *testing.PB) {
  1510. encoded := snappy.Encode(nil, data)
  1511. once.Do(func() {
  1512. if testing.Verbose() {
  1513. b.Log(len(encoded), " -> ", len(data))
  1514. }
  1515. })
  1516. tmp := make([]byte, len(data))
  1517. for pb.Next() {
  1518. var err error
  1519. tmp, err = snappy.Decode(tmp, encoded)
  1520. if err != nil {
  1521. b.Fatal(err)
  1522. }
  1523. }
  1524. })
  1525. } else {
  1526. b.SetBytes(int64(len(data)))
  1527. b.ResetTimer()
  1528. once.Do(func() {
  1529. if testing.Verbose() {
  1530. b.Log(len(data), " -> ", len(snappy.Encode(nil, data)))
  1531. }
  1532. })
  1533. b.RunParallel(func(pb *testing.PB) {
  1534. dst := make([]byte, snappy.MaxEncodedLen(len(data)))
  1535. tmp := make([]byte, len(data))
  1536. for pb.Next() {
  1537. res := snappy.Encode(dst, data)
  1538. if len(res) == 0 {
  1539. panic(0)
  1540. }
  1541. if false {
  1542. tmp, _ = snappy.Decode(tmp, res)
  1543. if !bytes.Equal(tmp, data) {
  1544. panic("wrong")
  1545. }
  1546. }
  1547. }
  1548. })
  1549. }
  1550. })
  1551. once = sync.Once{}
  1552. b.Run("s2-snappy", func(b *testing.B) {
  1553. if decode {
  1554. b.SetBytes(int64(len(data)))
  1555. b.ResetTimer()
  1556. b.RunParallel(func(pb *testing.PB) {
  1557. encoded := EncodeSnappy(nil, data)
  1558. once.Do(func() {
  1559. if testing.Verbose() {
  1560. b.Log(len(encoded), " -> ", len(data))
  1561. }
  1562. })
  1563. tmp := make([]byte, len(data))
  1564. for pb.Next() {
  1565. var err error
  1566. tmp, err = snappy.Decode(tmp, encoded)
  1567. if err != nil {
  1568. b.Fatal(err)
  1569. }
  1570. }
  1571. })
  1572. } else {
  1573. b.SetBytes(int64(len(data)))
  1574. b.ResetTimer()
  1575. once.Do(func() {
  1576. if testing.Verbose() {
  1577. b.Log(len(data), " -> ", len(EncodeSnappy(nil, data)))
  1578. }
  1579. })
  1580. b.RunParallel(func(pb *testing.PB) {
  1581. dst := make([]byte, snappy.MaxEncodedLen(len(data)))
  1582. tmp := make([]byte, len(data))
  1583. for pb.Next() {
  1584. res := EncodeSnappy(dst, data)
  1585. if len(res) == 0 {
  1586. panic(0)
  1587. }
  1588. if false {
  1589. tmp, _ = snappy.Decode(tmp, res)
  1590. if !bytes.Equal(tmp, data) {
  1591. panic("wrong")
  1592. }
  1593. }
  1594. }
  1595. })
  1596. }
  1597. })
  1598. fmt.Println("")
  1599. }
  1600. func TestRoundtrips(t *testing.T) {
  1601. testFile(t, 0, 10)
  1602. testFile(t, 1, 10)
  1603. testFile(t, 2, 10)
  1604. testFile(t, 3, 10)
  1605. testFile(t, 4, 10)
  1606. testFile(t, 5, 10)
  1607. testFile(t, 6, 10)
  1608. testFile(t, 7, 10)
  1609. testFile(t, 8, 10)
  1610. testFile(t, 9, 10)
  1611. testFile(t, 10, 10)
  1612. testFile(t, 11, 10)
  1613. testFile(t, 12, 0)
  1614. testFile(t, 13, 0)
  1615. testFile(t, 14, 0)
  1616. testFile(t, 15, 0)
  1617. }
  1618. func testFile(t *testing.T, i, repeat int) {
  1619. if err := downloadBenchmarkFiles(t, testFiles[i].filename); err != nil {
  1620. t.Skipf("failed to download testdata: %s", err)
  1621. }
  1622. if testing.Short() {
  1623. repeat = 0
  1624. }
  1625. t.Run(fmt.Sprint(i, "-", testFiles[i].label), func(t *testing.T) {
  1626. bDir := filepath.FromSlash(*benchdataDir)
  1627. data := readFile(t, filepath.Join(bDir, testFiles[i].filename))
  1628. oSize := len(data)
  1629. for i := 0; i < repeat; i++ {
  1630. data = append(data, data[:oSize]...)
  1631. }
  1632. t.Run("s2", func(t *testing.T) {
  1633. testWriterRoundtrip(t, data)
  1634. })
  1635. t.Run("s2-better", func(t *testing.T) {
  1636. testWriterRoundtrip(t, data, WriterBetterCompression())
  1637. })
  1638. t.Run("block", func(t *testing.T) {
  1639. d := data
  1640. testBlockRoundtrip(t, d)
  1641. })
  1642. t.Run("block-better", func(t *testing.T) {
  1643. d := data
  1644. testBetterBlockRoundtrip(t, d)
  1645. })
  1646. t.Run("snappy", func(t *testing.T) {
  1647. testSnappyDecode(t, data)
  1648. })
  1649. })
  1650. }
  1651. func TestDataRoundtrips(t *testing.T) {
  1652. test := func(t *testing.T, data []byte) {
  1653. t.Run("s2", func(t *testing.T) {
  1654. testWriterRoundtrip(t, data)
  1655. })
  1656. t.Run("s2-better", func(t *testing.T) {
  1657. testWriterRoundtrip(t, data, WriterBetterCompression())
  1658. })
  1659. t.Run("block", func(t *testing.T) {
  1660. d := data
  1661. testBlockRoundtrip(t, d)
  1662. })
  1663. t.Run("block-better", func(t *testing.T) {
  1664. d := data
  1665. testBetterBlockRoundtrip(t, d)
  1666. })
  1667. t.Run("snappy", func(t *testing.T) {
  1668. testSnappyDecode(t, data)
  1669. })
  1670. }
  1671. t.Run("longblock", func(t *testing.T) {
  1672. data := make([]byte, 1<<25)
  1673. test(t, data)
  1674. })
  1675. t.Run("4f9e1a0", func(t *testing.T) {
  1676. comp, _ := ioutil.ReadFile("testdata/4f9e1a0da7915a3d69632f5613ed78bc998a8a23.zst")
  1677. dec, _ := zstd.NewReader(bytes.NewBuffer(comp))
  1678. data, _ := ioutil.ReadAll(dec)
  1679. test(t, data)
  1680. })
  1681. }
  1682. func BenchmarkDecodeS2Block(b *testing.B) {
  1683. for i, _ := range testFiles {
  1684. b.Run(fmt.Sprint(i, "-", testFiles[i].label), func(b *testing.B) {
  1685. benchFile(b, i, true)
  1686. })
  1687. }
  1688. }
  1689. func BenchmarkEncodeS2Block(b *testing.B) {
  1690. for i, _ := range testFiles {
  1691. b.Run(fmt.Sprint(i, "-", testFiles[i].label), func(b *testing.B) {
  1692. benchFile(b, i, false)
  1693. })
  1694. }
  1695. }
  1696. func BenchmarkDecodeSnappyBlock(b *testing.B) {
  1697. for i, _ := range testFiles {
  1698. b.Run(fmt.Sprint(i, "-", testFiles[i].label), func(b *testing.B) {
  1699. benchFileSnappy(b, i, true)
  1700. })
  1701. }
  1702. }
  1703. func BenchmarkEncodeSnappyBlock(b *testing.B) {
  1704. for i, _ := range testFiles {
  1705. b.Run(fmt.Sprint(i, "-", testFiles[i].label), func(b *testing.B) {
  1706. benchFileSnappy(b, i, false)
  1707. })
  1708. }
  1709. }
  1710. func TestMatchLen(t *testing.T) {
  1711. // ref is a simple, reference implementation of matchLen.
  1712. ref := func(a, b []byte) int {
  1713. n := 0
  1714. for i := range a {
  1715. if a[i] != b[i] {
  1716. break
  1717. }
  1718. n++
  1719. }
  1720. return n
  1721. }
  1722. nums := []int{0, 1, 2, 7, 8, 9, 29, 30, 31, 32, 33, 34, 38, 39, 40}
  1723. for yIndex := 40; yIndex > 30; yIndex-- {
  1724. xxx := bytes.Repeat([]byte("x"), 40)
  1725. if yIndex < len(xxx) {
  1726. xxx[yIndex] = 'y'
  1727. }
  1728. for _, i := range nums {
  1729. for _, j := range nums {
  1730. if i >= j {
  1731. continue
  1732. }
  1733. got := matchLen(xxx[j:], xxx[i:])
  1734. want := ref(xxx[j:], xxx[i:])
  1735. if got != want {
  1736. t.Errorf("yIndex=%d, i=%d, j=%d: got %d, want %d", yIndex, i, j, got, want)
  1737. }
  1738. }
  1739. }
  1740. }
  1741. }