s2_test.go 56 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195
  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. "math"
  13. "math/rand"
  14. "net/http"
  15. "os"
  16. "path/filepath"
  17. "runtime"
  18. "strings"
  19. "testing"
  20. "github.com/klauspost/compress/internal/snapref"
  21. "github.com/klauspost/compress/zip"
  22. "github.com/klauspost/compress/zstd"
  23. )
  24. const maxUint = ^uint(0)
  25. const maxInt = int(maxUint >> 1)
  26. var (
  27. download = flag.Bool("download", false, "If true, download any missing files before running benchmarks")
  28. testdataDir = flag.String("testdataDir", "testdata", "Directory containing the test data")
  29. benchdataDir = flag.String("benchdataDir", "testdata/bench", "Directory containing the benchmark data")
  30. )
  31. func TestMaxEncodedLen(t *testing.T) {
  32. testSet := []struct {
  33. in, out int64
  34. }{
  35. 0: {in: 0, out: 1},
  36. 1: {in: 1 << 24, out: 1<<24 + int64(binary.PutVarint([]byte{binary.MaxVarintLen32: 0}, int64(1<<24))) + literalExtraSize(1<<24)},
  37. 2: {in: MaxBlockSize, out: math.MaxUint32},
  38. 3: {in: math.MaxUint32 - binary.MaxVarintLen32 - literalExtraSize(math.MaxUint32), out: math.MaxUint32},
  39. 4: {in: math.MaxUint32 - 9, out: -1},
  40. 5: {in: math.MaxUint32 - 8, out: -1},
  41. 6: {in: math.MaxUint32 - 7, out: -1},
  42. 7: {in: math.MaxUint32 - 6, out: -1},
  43. 8: {in: math.MaxUint32 - 5, out: -1},
  44. 9: {in: math.MaxUint32 - 4, out: -1},
  45. 10: {in: math.MaxUint32 - 3, out: -1},
  46. 11: {in: math.MaxUint32 - 2, out: -1},
  47. 12: {in: math.MaxUint32 - 1, out: -1},
  48. 13: {in: math.MaxUint32, out: -1},
  49. 14: {in: -1, out: -1},
  50. 15: {in: -2, out: -1},
  51. }
  52. // 32 bit platforms have a different threshold.
  53. if maxInt == math.MaxInt32 {
  54. testSet[2].out = math.MaxInt32
  55. testSet[3].out = -1
  56. }
  57. t.Log("Maxblock:", MaxBlockSize, "reduction:", intReduction)
  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.Errorf("test %d: input: %d, want: %d, got: %d", i, 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}, EncodeSnappy(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 := os.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 := os.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(io.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 := io.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 := io.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 := io.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, "\x11\b\x15\x001"},
  817. {8, 66, "\x11\b\x15\x002"},
  818. {8, 67, "\x11\b\x15\x003"},
  819. {8, 68, "\x11\b\x15\x004"},
  820. {8, 69, "\x11\b\x15\x005"},
  821. {8, 80, "\x11\b\x15\x00@"},
  822. {8, 800, "\x11\b\x19\x00\x14\x02"},
  823. {8, 800000, "\x11\b\x1d\x00\xf44\v"},
  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, "1\x00\x15\x001"},
  835. {256, 66, "1\x00\x15\x002"},
  836. {256, 67, "1\x00\x15\x003"},
  837. {256, 68, "1\x00\x15\x004"},
  838. {256, 69, "1\x00\x15\x005"},
  839. {256, 80, "1\x00\x15\x00@"},
  840. {256, 800, "1\x00\x19\x00\x14\x02"},
  841. {256, 80000, "1\x00\x1d\x00t8\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 %q\nwant %q", 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 := io.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 := io.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 := io.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 := io.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 := io.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 := io.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. w := NewWriter(nil)
  1029. defer w.Close()
  1030. var gots, wants [][]byte
  1031. failed := false
  1032. for i := 0; i <= n; i++ {
  1033. buf := new(bytes.Buffer)
  1034. w.Reset(buf)
  1035. want := gold[:len(gold)*i/n]
  1036. if _, err := w.Write(want); err != nil {
  1037. t.Errorf("#%d: Write: %v", i, err)
  1038. failed = true
  1039. continue
  1040. }
  1041. if err := w.Flush(); err != nil {
  1042. t.Errorf("#%d: Flush: %v", i, err)
  1043. failed = true
  1044. got, err := io.ReadAll(NewReader(buf))
  1045. if err != nil {
  1046. t.Errorf("#%d: ReadAll: %v", i, err)
  1047. failed = true
  1048. continue
  1049. }
  1050. gots = append(gots, got)
  1051. wants = append(wants, want)
  1052. }
  1053. if failed {
  1054. continue
  1055. }
  1056. for i := range gots {
  1057. if err := cmp(gots[i], wants[i]); err != nil {
  1058. t.Errorf("#%d: %v", i, err)
  1059. }
  1060. }
  1061. }
  1062. }
  1063. func TestWriterResetWithoutFlush(t *testing.T) {
  1064. buf0 := new(bytes.Buffer)
  1065. buf1 := new(bytes.Buffer)
  1066. w := NewWriter(buf0)
  1067. if _, err := w.Write([]byte("xxx")); err != nil {
  1068. t.Fatalf("Write #0: %v", err)
  1069. }
  1070. // Note that we don't Flush the Writer before calling Reset.
  1071. w.Reset(buf1)
  1072. if _, err := w.Write([]byte("yyy")); err != nil {
  1073. t.Fatalf("Write #1: %v", err)
  1074. }
  1075. if err := w.Flush(); err != nil {
  1076. t.Fatalf("Flush: %v", err)
  1077. }
  1078. got, err := io.ReadAll(NewReader(buf1))
  1079. if err != nil {
  1080. t.Fatalf("ReadAll: %v", err)
  1081. }
  1082. if err := cmp(got, []byte("yyy")); err != nil {
  1083. t.Fatal(err)
  1084. }
  1085. }
  1086. type writeCounter int
  1087. func (c *writeCounter) Write(p []byte) (int, error) {
  1088. *c++
  1089. return len(p), nil
  1090. }
  1091. // TestNumUnderlyingWrites tests that each Writer flush only makes one or two
  1092. // Write calls on its underlying io.Writer, depending on whether or not the
  1093. // flushed buffer was compressible.
  1094. func TestNumUnderlyingWrites(t *testing.T) {
  1095. testCases := []struct {
  1096. input []byte
  1097. want int
  1098. }{
  1099. // Magic header + block
  1100. {bytes.Repeat([]byte{'x'}, 100), 2},
  1101. // One block each:
  1102. {bytes.Repeat([]byte{'y'}, 100), 1},
  1103. {[]byte("ABCDEFGHIJKLMNOPQRST"), 1},
  1104. }
  1105. // If we are doing sync writes, we write uncompressed as two writes.
  1106. if runtime.GOMAXPROCS(0) == 1 {
  1107. testCases[2].want++
  1108. }
  1109. var c writeCounter
  1110. w := NewWriter(&c)
  1111. defer w.Close()
  1112. for i, tc := range testCases {
  1113. c = 0
  1114. if _, err := w.Write(tc.input); err != nil {
  1115. t.Errorf("#%d: Write: %v", i, err)
  1116. continue
  1117. }
  1118. if err := w.Flush(); err != nil {
  1119. t.Errorf("#%d: Flush: %v", i, err)
  1120. continue
  1121. }
  1122. if int(c) != tc.want {
  1123. t.Errorf("#%d: got %d underlying writes, want %d", i, c, tc.want)
  1124. continue
  1125. }
  1126. }
  1127. }
  1128. func testWriterRoundtrip(t *testing.T, src []byte, opts ...WriterOption) {
  1129. var buf bytes.Buffer
  1130. enc := NewWriter(&buf, opts...)
  1131. n, err := enc.Write(src)
  1132. if err != nil {
  1133. t.Error(err)
  1134. return
  1135. }
  1136. if n != len(src) {
  1137. t.Error(io.ErrShortWrite)
  1138. return
  1139. }
  1140. err = enc.Flush()
  1141. if err != nil {
  1142. t.Error(err)
  1143. return
  1144. }
  1145. // Extra flush and close should be noops.
  1146. err = enc.Flush()
  1147. if err != nil {
  1148. t.Error(err)
  1149. return
  1150. }
  1151. err = enc.Close()
  1152. if err != nil {
  1153. t.Error(err)
  1154. return
  1155. }
  1156. t.Logf("encoded to %d -> %d bytes", len(src), buf.Len())
  1157. dec := NewReader(&buf)
  1158. decoded, err := io.ReadAll(dec)
  1159. if err != nil {
  1160. t.Error(err)
  1161. return
  1162. }
  1163. if len(decoded) != len(src) {
  1164. t.Error("decoded len:", len(decoded), "!=", len(src))
  1165. return
  1166. }
  1167. err = cmp(src, decoded)
  1168. if err != nil {
  1169. t.Error(err)
  1170. }
  1171. }
  1172. func testBlockRoundtrip(t *testing.T, src []byte) {
  1173. dst := Encode(nil, src)
  1174. t.Logf("encoded to %d -> %d bytes", len(src), len(dst))
  1175. decoded, err := Decode(nil, dst)
  1176. if err != nil {
  1177. t.Error(err)
  1178. return
  1179. }
  1180. if len(decoded) != len(src) {
  1181. t.Error("decoded len:", len(decoded), "!=", len(src))
  1182. return
  1183. }
  1184. err = cmp(decoded, src)
  1185. if err != nil {
  1186. t.Error(err)
  1187. }
  1188. }
  1189. func testBetterBlockRoundtrip(t *testing.T, src []byte) {
  1190. dst := EncodeBetter(nil, src)
  1191. t.Logf("encoded to %d -> %d bytes", len(src), len(dst))
  1192. decoded, err := Decode(nil, dst)
  1193. if err != nil {
  1194. t.Error(err)
  1195. return
  1196. }
  1197. if len(decoded) != len(src) {
  1198. t.Error("decoded len:", len(decoded), "!=", len(src))
  1199. return
  1200. }
  1201. err = cmp(src, decoded)
  1202. if err != nil {
  1203. t.Error(err)
  1204. }
  1205. }
  1206. func testBestBlockRoundtrip(t *testing.T, src []byte) {
  1207. dst := EncodeBest(nil, src)
  1208. t.Logf("encoded to %d -> %d bytes", len(src), len(dst))
  1209. decoded, err := Decode(nil, dst)
  1210. if err != nil {
  1211. t.Error(err)
  1212. return
  1213. }
  1214. if len(decoded) != len(src) {
  1215. t.Error("decoded len:", len(decoded), "!=", len(src))
  1216. return
  1217. }
  1218. err = cmp(src, decoded)
  1219. if err != nil {
  1220. t.Error(err)
  1221. }
  1222. }
  1223. func testSnappyBlockRoundtrip(t *testing.T, src []byte) {
  1224. // Write with s2, decode with snapref.
  1225. t.Run("regular", func(t *testing.T) {
  1226. dst := EncodeSnappy(nil, src)
  1227. t.Logf("encoded to %d -> %d bytes", len(src), len(dst))
  1228. decoded, err := snapref.Decode(nil, dst)
  1229. if err != nil {
  1230. t.Error(err)
  1231. return
  1232. }
  1233. if len(decoded) != len(src) {
  1234. t.Error("decoded len:", len(decoded), "!=", len(src))
  1235. return
  1236. }
  1237. err = cmp(src, decoded)
  1238. if err != nil {
  1239. t.Error(err)
  1240. }
  1241. })
  1242. t.Run("better", func(t *testing.T) {
  1243. dst := EncodeSnappyBetter(nil, src)
  1244. t.Logf("encoded to %d -> %d bytes", len(src), len(dst))
  1245. decoded, err := snapref.Decode(nil, dst)
  1246. if err != nil {
  1247. t.Error(err)
  1248. return
  1249. }
  1250. if len(decoded) != len(src) {
  1251. t.Error("decoded len:", len(decoded), "!=", len(src))
  1252. return
  1253. }
  1254. err = cmp(src, decoded)
  1255. if err != nil {
  1256. t.Error(err)
  1257. }
  1258. })
  1259. t.Run("best", func(t *testing.T) {
  1260. dst := EncodeSnappyBest(nil, src)
  1261. t.Logf("encoded to %d -> %d bytes", len(src), len(dst))
  1262. decoded, err := snapref.Decode(nil, dst)
  1263. if err != nil {
  1264. t.Error(err)
  1265. return
  1266. }
  1267. if len(decoded) != len(src) {
  1268. t.Error("decoded len:", len(decoded), "!=", len(src))
  1269. return
  1270. }
  1271. err = cmp(src, decoded)
  1272. if err != nil {
  1273. t.Error(err)
  1274. }
  1275. })
  1276. }
  1277. func testSnappyDecode(t *testing.T, src []byte) {
  1278. var buf bytes.Buffer
  1279. enc := snapref.NewBufferedWriter(&buf)
  1280. n, err := enc.Write(src)
  1281. if err != nil {
  1282. t.Error(err)
  1283. return
  1284. }
  1285. if n != len(src) {
  1286. t.Error(io.ErrShortWrite)
  1287. return
  1288. }
  1289. enc.Close()
  1290. t.Logf("encoded to %d -> %d bytes", len(src), buf.Len())
  1291. dec := NewReader(&buf)
  1292. decoded, err := io.ReadAll(dec)
  1293. if err != nil {
  1294. t.Error(err)
  1295. return
  1296. }
  1297. if len(decoded) != len(src) {
  1298. t.Error("decoded len:", len(decoded), "!=", len(src))
  1299. return
  1300. }
  1301. err = cmp(src, decoded)
  1302. if err != nil {
  1303. t.Error(err)
  1304. }
  1305. }
  1306. func benchDecode(b *testing.B, src []byte) {
  1307. b.Run("default", func(b *testing.B) {
  1308. encoded := Encode(nil, src)
  1309. b.SetBytes(int64(len(src)))
  1310. b.ReportAllocs()
  1311. b.ResetTimer()
  1312. for i := 0; i < b.N; i++ {
  1313. _, err := Decode(src[:0], encoded)
  1314. if err != nil {
  1315. b.Fatal(err)
  1316. }
  1317. }
  1318. b.ReportMetric(100*float64(len(encoded))/float64(len(src)), "pct")
  1319. })
  1320. b.Run("better", func(b *testing.B) {
  1321. encoded := EncodeBetter(nil, src)
  1322. b.SetBytes(int64(len(src)))
  1323. b.ReportAllocs()
  1324. b.ResetTimer()
  1325. for i := 0; i < b.N; i++ {
  1326. _, err := Decode(src[:0], encoded)
  1327. if err != nil {
  1328. b.Fatal(err)
  1329. }
  1330. }
  1331. b.ReportMetric(100*float64(len(encoded))/float64(len(src)), "pct")
  1332. })
  1333. b.Run("best", func(b *testing.B) {
  1334. encoded := EncodeBest(nil, src)
  1335. b.SetBytes(int64(len(src)))
  1336. b.ReportAllocs()
  1337. b.ResetTimer()
  1338. for i := 0; i < b.N; i++ {
  1339. _, err := Decode(src[:0], encoded)
  1340. if err != nil {
  1341. b.Fatal(err)
  1342. }
  1343. }
  1344. b.ReportMetric(100*float64(len(encoded))/float64(len(src)), "pct")
  1345. })
  1346. b.Run("snappy-input", func(b *testing.B) {
  1347. encoded := snapref.Encode(nil, src)
  1348. b.SetBytes(int64(len(src)))
  1349. b.ReportAllocs()
  1350. b.ResetTimer()
  1351. for i := 0; i < b.N; i++ {
  1352. _, err := Decode(src[:0], encoded)
  1353. if err != nil {
  1354. b.Fatal(err)
  1355. }
  1356. }
  1357. b.ReportMetric(100*float64(len(encoded))/float64(len(src)), "pct")
  1358. })
  1359. }
  1360. func benchEncode(b *testing.B, src []byte) {
  1361. // Bandwidth is in amount of uncompressed data.
  1362. dst := make([]byte, snapref.MaxEncodedLen(len(src)))
  1363. b.ResetTimer()
  1364. b.Run("default", func(b *testing.B) {
  1365. b.SetBytes(int64(len(src)))
  1366. b.ReportAllocs()
  1367. for i := 0; i < b.N; i++ {
  1368. Encode(dst, src)
  1369. }
  1370. b.ReportMetric(100*float64(len(Encode(dst, src)))/float64(len(src)), "pct")
  1371. })
  1372. b.Run("better", func(b *testing.B) {
  1373. b.SetBytes(int64(len(src)))
  1374. b.ReportAllocs()
  1375. for i := 0; i < b.N; i++ {
  1376. EncodeBetter(dst, src)
  1377. }
  1378. b.ReportMetric(100*float64(len(EncodeBetter(dst, src)))/float64(len(src)), "pct")
  1379. })
  1380. b.Run("best", func(b *testing.B) {
  1381. b.SetBytes(int64(len(src)))
  1382. b.ReportAllocs()
  1383. for i := 0; i < b.N; i++ {
  1384. EncodeBest(dst, src)
  1385. }
  1386. b.ReportMetric(100*float64(len(EncodeBest(dst, src)))/float64(len(src)), "pct")
  1387. })
  1388. b.Run("snappy-default", func(b *testing.B) {
  1389. b.SetBytes(int64(len(src)))
  1390. b.ReportAllocs()
  1391. for i := 0; i < b.N; i++ {
  1392. EncodeSnappy(dst, src)
  1393. }
  1394. b.ReportMetric(100*float64(len(EncodeSnappy(dst, src)))/float64(len(src)), "pct")
  1395. })
  1396. b.Run("snappy-better", func(b *testing.B) {
  1397. b.SetBytes(int64(len(src)))
  1398. b.ReportAllocs()
  1399. for i := 0; i < b.N; i++ {
  1400. EncodeSnappyBetter(dst, src)
  1401. }
  1402. b.ReportMetric(100*float64(len(EncodeSnappyBetter(dst, src)))/float64(len(src)), "pct")
  1403. })
  1404. b.Run("snappy-best", func(b *testing.B) {
  1405. b.SetBytes(int64(len(src)))
  1406. b.ReportAllocs()
  1407. for i := 0; i < b.N; i++ {
  1408. EncodeSnappyBest(dst, src)
  1409. }
  1410. b.ReportMetric(100*float64(len(EncodeSnappyBest(dst, src)))/float64(len(src)), "pct")
  1411. })
  1412. b.Run("snappy-ref-noasm", func(b *testing.B) {
  1413. b.SetBytes(int64(len(src)))
  1414. b.ReportAllocs()
  1415. for i := 0; i < b.N; i++ {
  1416. snapref.Encode(dst, src)
  1417. }
  1418. b.ReportMetric(100*float64(len(snapref.Encode(dst, src)))/float64(len(src)), "pct")
  1419. })
  1420. }
  1421. func testOrBenchmark(b testing.TB) string {
  1422. if _, ok := b.(*testing.B); ok {
  1423. return "benchmark"
  1424. }
  1425. return "test"
  1426. }
  1427. func readFile(b testing.TB, filename string) []byte {
  1428. src, err := os.ReadFile(filename)
  1429. if err != nil {
  1430. b.Skipf("skipping %s: %v", testOrBenchmark(b), err)
  1431. }
  1432. if len(src) == 0 {
  1433. b.Fatalf("%s has zero length", filename)
  1434. }
  1435. return src
  1436. }
  1437. // expand returns a slice of length n containing mutated copies of src.
  1438. func expand(src []byte, n int) []byte {
  1439. dst := make([]byte, n)
  1440. cnt := uint8(0)
  1441. for x := dst; len(x) > 0; cnt++ {
  1442. idx := copy(x, src)
  1443. for i := range x {
  1444. if i >= len(src) {
  1445. break
  1446. }
  1447. x[i] = src[i] ^ cnt
  1448. }
  1449. x = x[idx:]
  1450. }
  1451. return dst
  1452. }
  1453. func benchTwain(b *testing.B, n int, decode bool) {
  1454. data := expand(readFile(b, "../testdata/Mark.Twain-Tom.Sawyer.txt"), n)
  1455. if decode {
  1456. benchDecode(b, data)
  1457. } else {
  1458. benchEncode(b, data)
  1459. }
  1460. }
  1461. func BenchmarkTwainDecode1e1(b *testing.B) { benchTwain(b, 1e1, true) }
  1462. func BenchmarkTwainDecode1e2(b *testing.B) { benchTwain(b, 1e2, true) }
  1463. func BenchmarkTwainDecode1e3(b *testing.B) { benchTwain(b, 1e3, true) }
  1464. func BenchmarkTwainDecode1e4(b *testing.B) { benchTwain(b, 1e4, true) }
  1465. func BenchmarkTwainDecode1e5(b *testing.B) { benchTwain(b, 1e5, true) }
  1466. func BenchmarkTwainDecode1e6(b *testing.B) { benchTwain(b, 1e6, true) }
  1467. func BenchmarkTwainDecode1e7(b *testing.B) { benchTwain(b, 1e7, true) }
  1468. func BenchmarkTwainEncode1e1(b *testing.B) { benchTwain(b, 1e1, false) }
  1469. func BenchmarkTwainEncode1e2(b *testing.B) { benchTwain(b, 1e2, false) }
  1470. func BenchmarkTwainEncode1e3(b *testing.B) { benchTwain(b, 1e3, false) }
  1471. func BenchmarkTwainEncode1e4(b *testing.B) { benchTwain(b, 1e4, false) }
  1472. func BenchmarkTwainEncode1e5(b *testing.B) { benchTwain(b, 1e5, false) }
  1473. func BenchmarkTwainEncode1e6(b *testing.B) { benchTwain(b, 1e6, false) }
  1474. func BenchmarkTwainEncode1e7(b *testing.B) { benchTwain(b, 1e7, false) }
  1475. func BenchmarkRandomEncodeBlock1MB(b *testing.B) {
  1476. rng := rand.New(rand.NewSource(1))
  1477. data := make([]byte, 1<<20)
  1478. for i := range data {
  1479. data[i] = uint8(rng.Intn(256))
  1480. }
  1481. benchEncode(b, data)
  1482. }
  1483. func BenchmarkRandomEncodeBetterBlock16MB(b *testing.B) {
  1484. rng := rand.New(rand.NewSource(1))
  1485. data := make([]byte, 16<<20)
  1486. for i := range data {
  1487. data[i] = uint8(rng.Intn(256))
  1488. }
  1489. benchEncode(b, data)
  1490. }
  1491. // testFiles' values are copied directly from
  1492. // https://raw.githubusercontent.com/google/snappy/master/snappy_unittest.cc
  1493. // The label field is unused in snappy-go.
  1494. var testFiles = []struct {
  1495. label string
  1496. filename string
  1497. sizeLimit int
  1498. }{
  1499. {"html", "html", 0},
  1500. {"urls", "urls.10K", 0},
  1501. {"jpg", "fireworks.jpeg", 0},
  1502. {"jpg_200b", "fireworks.jpeg", 200},
  1503. {"pdf", "paper-100k.pdf", 0},
  1504. {"html4", "html_x_4", 0},
  1505. {"txt1", "alice29.txt", 0},
  1506. {"txt2", "asyoulik.txt", 0},
  1507. {"txt3", "lcet10.txt", 0},
  1508. {"txt4", "plrabn12.txt", 0},
  1509. {"pb", "geo.protodata", 0},
  1510. {"gaviota", "kppkn.gtb", 0},
  1511. {"txt1_128b", "alice29.txt", 128},
  1512. {"txt1_1000b", "alice29.txt", 1000},
  1513. {"txt1_10000b", "alice29.txt", 10000},
  1514. {"txt1_20000b", "alice29.txt", 20000},
  1515. }
  1516. const (
  1517. // The benchmark data files are at this canonical URL.
  1518. benchURL = "https://raw.githubusercontent.com/google/snappy/master/testdata/"
  1519. )
  1520. func downloadBenchmarkFiles(b testing.TB, basename string) (errRet error) {
  1521. bDir := filepath.FromSlash(*benchdataDir)
  1522. filename := filepath.Join(bDir, basename)
  1523. if stat, err := os.Stat(filename); err == nil && stat.Size() != 0 {
  1524. return nil
  1525. }
  1526. if !*download {
  1527. b.Skipf("test data not found; skipping %s without the -download flag", testOrBenchmark(b))
  1528. }
  1529. // Download the official snappy C++ implementation reference test data
  1530. // files for benchmarking.
  1531. if err := os.MkdirAll(bDir, 0777); err != nil && !os.IsExist(err) {
  1532. return fmt.Errorf("failed to create %s: %s", bDir, err)
  1533. }
  1534. f, err := os.Create(filename)
  1535. if err != nil {
  1536. return fmt.Errorf("failed to create %s: %s", filename, err)
  1537. }
  1538. defer f.Close()
  1539. defer func() {
  1540. if errRet != nil {
  1541. os.Remove(filename)
  1542. }
  1543. }()
  1544. url := benchURL + basename
  1545. resp, err := http.Get(url)
  1546. if err != nil {
  1547. return fmt.Errorf("failed to download %s: %s", url, err)
  1548. }
  1549. defer resp.Body.Close()
  1550. if s := resp.StatusCode; s != http.StatusOK {
  1551. return fmt.Errorf("downloading %s: HTTP status code %d (%s)", url, s, http.StatusText(s))
  1552. }
  1553. _, err = io.Copy(f, resp.Body)
  1554. if err != nil {
  1555. return fmt.Errorf("failed to download %s to %s: %s", url, filename, err)
  1556. }
  1557. return nil
  1558. }
  1559. func benchFile(b *testing.B, i int, decode bool) {
  1560. if err := downloadBenchmarkFiles(b, testFiles[i].filename); err != nil {
  1561. b.Fatalf("failed to download testdata: %s", err)
  1562. }
  1563. bDir := filepath.FromSlash(*benchdataDir)
  1564. data := readFile(b, filepath.Join(bDir, testFiles[i].filename))
  1565. if !decode {
  1566. b.Run("est-size", func(b *testing.B) {
  1567. if n := testFiles[i].sizeLimit; 0 < n && n < len(data) {
  1568. data = data[:n]
  1569. }
  1570. b.SetBytes(int64(len(data)))
  1571. b.ReportAllocs()
  1572. b.ResetTimer()
  1573. b.RunParallel(func(pb *testing.PB) {
  1574. for pb.Next() {
  1575. _ = EstimateBlockSize(data)
  1576. }
  1577. })
  1578. sz := float64(EstimateBlockSize(data))
  1579. if sz > 0 {
  1580. b.ReportMetric(100*sz/float64(len(data)), "pct")
  1581. b.ReportMetric(sz, "B")
  1582. }
  1583. })
  1584. }
  1585. b.Run("block", func(b *testing.B) {
  1586. if n := testFiles[i].sizeLimit; 0 < n && n < len(data) {
  1587. data = data[:n]
  1588. }
  1589. if decode {
  1590. b.SetBytes(int64(len(data)))
  1591. b.ReportAllocs()
  1592. b.ResetTimer()
  1593. b.RunParallel(func(pb *testing.PB) {
  1594. encoded := Encode(nil, data)
  1595. tmp := make([]byte, len(data))
  1596. for pb.Next() {
  1597. var err error
  1598. tmp, err = Decode(tmp, encoded)
  1599. if err != nil {
  1600. b.Fatal(err)
  1601. }
  1602. }
  1603. })
  1604. } else {
  1605. b.SetBytes(int64(len(data)))
  1606. b.ReportAllocs()
  1607. b.ResetTimer()
  1608. b.RunParallel(func(pb *testing.PB) {
  1609. dst := make([]byte, MaxEncodedLen(len(data)))
  1610. tmp := make([]byte, len(data))
  1611. for pb.Next() {
  1612. res := Encode(dst, data)
  1613. if len(res) == 0 {
  1614. panic(0)
  1615. }
  1616. if false {
  1617. tmp, _ = Decode(tmp, res)
  1618. if !bytes.Equal(tmp, data) {
  1619. panic("wrong")
  1620. }
  1621. }
  1622. }
  1623. })
  1624. }
  1625. b.ReportMetric(100*float64(len(Encode(nil, data)))/float64(len(data)), "pct")
  1626. b.ReportMetric(float64(len(Encode(nil, data))), "B")
  1627. })
  1628. b.Run("block-better", func(b *testing.B) {
  1629. if decode {
  1630. b.SetBytes(int64(len(data)))
  1631. b.ReportAllocs()
  1632. b.ResetTimer()
  1633. b.RunParallel(func(pb *testing.PB) {
  1634. encoded := EncodeBetter(nil, data)
  1635. tmp := make([]byte, len(data))
  1636. for pb.Next() {
  1637. var err error
  1638. tmp, err = Decode(tmp, encoded)
  1639. if err != nil {
  1640. b.Fatal(err)
  1641. }
  1642. }
  1643. })
  1644. } else {
  1645. b.SetBytes(int64(len(data)))
  1646. b.ReportAllocs()
  1647. b.ResetTimer()
  1648. b.RunParallel(func(pb *testing.PB) {
  1649. dst := make([]byte, MaxEncodedLen(len(data)))
  1650. tmp := make([]byte, len(data))
  1651. for pb.Next() {
  1652. res := EncodeBetter(dst, data)
  1653. if len(res) == 0 {
  1654. panic(0)
  1655. }
  1656. if false {
  1657. tmp, _ = Decode(tmp, res)
  1658. if !bytes.Equal(tmp, data) {
  1659. panic("wrong")
  1660. }
  1661. }
  1662. }
  1663. })
  1664. }
  1665. b.ReportMetric(100*float64(len(EncodeBetter(nil, data)))/float64(len(data)), "pct")
  1666. b.ReportMetric(float64(len(EncodeBetter(nil, data))), "B")
  1667. })
  1668. b.Run("block-best", func(b *testing.B) {
  1669. if decode {
  1670. b.SetBytes(int64(len(data)))
  1671. b.ReportAllocs()
  1672. b.ResetTimer()
  1673. b.RunParallel(func(pb *testing.PB) {
  1674. encoded := EncodeBest(nil, data)
  1675. tmp := make([]byte, len(data))
  1676. for pb.Next() {
  1677. var err error
  1678. tmp, err = Decode(tmp, encoded)
  1679. if err != nil {
  1680. b.Fatal(err)
  1681. }
  1682. }
  1683. })
  1684. b.ReportMetric(100*float64(len(EncodeBest(nil, data)))/float64(len(data)), "pct")
  1685. } else {
  1686. b.SetBytes(int64(len(data)))
  1687. b.ReportAllocs()
  1688. b.ResetTimer()
  1689. b.RunParallel(func(pb *testing.PB) {
  1690. dst := make([]byte, MaxEncodedLen(len(data)))
  1691. tmp := make([]byte, len(data))
  1692. for pb.Next() {
  1693. res := EncodeBest(dst, data)
  1694. if len(res) == 0 {
  1695. panic(0)
  1696. }
  1697. if false {
  1698. tmp, _ = Decode(tmp, res)
  1699. if !bytes.Equal(tmp, data) {
  1700. panic("wrong")
  1701. }
  1702. }
  1703. }
  1704. })
  1705. b.ReportMetric(100*float64(len(EncodeBest(nil, data)))/float64(len(data)), "pct")
  1706. }
  1707. b.ReportMetric(float64(len(EncodeBest(nil, data))), "B")
  1708. })
  1709. }
  1710. func benchFileSnappy(b *testing.B, i int, decode bool) {
  1711. if err := downloadBenchmarkFiles(b, testFiles[i].filename); err != nil {
  1712. b.Fatalf("failed to download testdata: %s", err)
  1713. }
  1714. bDir := filepath.FromSlash(*benchdataDir)
  1715. data := readFile(b, filepath.Join(bDir, testFiles[i].filename))
  1716. if n := testFiles[i].sizeLimit; 0 < n && n < len(data) {
  1717. data = data[:n]
  1718. }
  1719. b.Run("s2-snappy", func(b *testing.B) {
  1720. if decode {
  1721. b.SetBytes(int64(len(data)))
  1722. b.ResetTimer()
  1723. b.ReportAllocs()
  1724. b.RunParallel(func(pb *testing.PB) {
  1725. encoded := EncodeSnappy(nil, data)
  1726. tmp := make([]byte, len(data))
  1727. for pb.Next() {
  1728. var err error
  1729. tmp, err = Decode(tmp, encoded)
  1730. if err != nil {
  1731. b.Fatal(err)
  1732. }
  1733. }
  1734. })
  1735. b.ReportMetric(100*float64(len(EncodeSnappy(nil, data)))/float64(len(data)), "pct")
  1736. } else {
  1737. b.SetBytes(int64(len(data)))
  1738. b.ReportAllocs()
  1739. b.ResetTimer()
  1740. b.RunParallel(func(pb *testing.PB) {
  1741. dst := make([]byte, MaxEncodedLen(len(data)))
  1742. for pb.Next() {
  1743. res := EncodeSnappy(dst, data)
  1744. if len(res) == 0 {
  1745. panic(0)
  1746. }
  1747. }
  1748. })
  1749. b.ReportMetric(100*float64(len(EncodeSnappy(nil, data)))/float64(len(data)), "pct")
  1750. }
  1751. b.ReportMetric(float64(len(EncodeSnappy(nil, data))), "B")
  1752. })
  1753. b.Run("s2-snappy-better", func(b *testing.B) {
  1754. if decode {
  1755. b.SetBytes(int64(len(data)))
  1756. b.ResetTimer()
  1757. b.RunParallel(func(pb *testing.PB) {
  1758. encoded := EncodeSnappyBetter(nil, data)
  1759. tmp := make([]byte, len(data))
  1760. b.ReportAllocs()
  1761. b.ResetTimer()
  1762. for pb.Next() {
  1763. var err error
  1764. tmp, err = Decode(tmp, encoded)
  1765. if err != nil {
  1766. b.Fatal(err)
  1767. }
  1768. }
  1769. })
  1770. b.ReportMetric(100*float64(len(EncodeSnappyBetter(nil, data)))/float64(len(data)), "pct")
  1771. } else {
  1772. b.SetBytes(int64(len(data)))
  1773. b.ReportAllocs()
  1774. b.ResetTimer()
  1775. b.RunParallel(func(pb *testing.PB) {
  1776. dst := make([]byte, MaxEncodedLen(len(data)))
  1777. tmp := make([]byte, len(data))
  1778. for pb.Next() {
  1779. res := EncodeSnappyBetter(dst, data)
  1780. if len(res) == 0 {
  1781. panic(0)
  1782. }
  1783. if false {
  1784. tmp, _ = Decode(tmp, res)
  1785. if !bytes.Equal(tmp, data) {
  1786. panic("wrong")
  1787. }
  1788. }
  1789. }
  1790. })
  1791. b.ReportMetric(100*float64(len(EncodeSnappyBetter(nil, data)))/float64(len(data)), "pct")
  1792. }
  1793. b.ReportMetric(float64(len(EncodeSnappyBetter(nil, data))), "B")
  1794. })
  1795. b.Run("s2-snappy-best", func(b *testing.B) {
  1796. if decode {
  1797. b.SetBytes(int64(len(data)))
  1798. b.ReportAllocs()
  1799. b.ResetTimer()
  1800. b.RunParallel(func(pb *testing.PB) {
  1801. encoded := EncodeSnappyBest(nil, data)
  1802. tmp := make([]byte, len(data))
  1803. for pb.Next() {
  1804. var err error
  1805. tmp, err = Decode(tmp, encoded)
  1806. if err != nil {
  1807. b.Fatal(err)
  1808. }
  1809. }
  1810. })
  1811. b.ReportMetric(100*float64(len(EncodeSnappyBest(nil, data)))/float64(len(data)), "pct")
  1812. } else {
  1813. b.SetBytes(int64(len(data)))
  1814. b.ReportAllocs()
  1815. b.ResetTimer()
  1816. b.RunParallel(func(pb *testing.PB) {
  1817. dst := make([]byte, MaxEncodedLen(len(data)))
  1818. tmp := make([]byte, len(data))
  1819. for pb.Next() {
  1820. res := EncodeSnappyBest(dst, data)
  1821. if len(res) == 0 {
  1822. panic(0)
  1823. }
  1824. if false {
  1825. tmp, _ = snapref.Decode(tmp, res)
  1826. if !bytes.Equal(tmp, data) {
  1827. panic("wrong")
  1828. }
  1829. }
  1830. }
  1831. })
  1832. b.ReportMetric(100*float64(len(EncodeSnappyBest(nil, data)))/float64(len(data)), "pct")
  1833. }
  1834. b.ReportMetric(float64(len(EncodeSnappyBest(nil, data))), "B")
  1835. })
  1836. b.Run("snappy-noasm", func(b *testing.B) {
  1837. if decode {
  1838. b.SetBytes(int64(len(data)))
  1839. b.ReportAllocs()
  1840. b.ResetTimer()
  1841. b.RunParallel(func(pb *testing.PB) {
  1842. encoded := snapref.Encode(nil, data)
  1843. tmp := make([]byte, len(data))
  1844. for pb.Next() {
  1845. var err error
  1846. tmp, err = snapref.Decode(tmp, encoded)
  1847. if err != nil {
  1848. b.Fatal(err)
  1849. }
  1850. }
  1851. })
  1852. b.ReportMetric(100*float64(len(snapref.Encode(nil, data)))/float64(len(data)), "pct")
  1853. } else {
  1854. b.SetBytes(int64(len(data)))
  1855. b.ReportAllocs()
  1856. b.ResetTimer()
  1857. b.RunParallel(func(pb *testing.PB) {
  1858. dst := make([]byte, snapref.MaxEncodedLen(len(data)))
  1859. tmp := make([]byte, len(data))
  1860. for pb.Next() {
  1861. res := snapref.Encode(dst, data)
  1862. if len(res) == 0 {
  1863. panic(0)
  1864. }
  1865. if false {
  1866. tmp, _ = snapref.Decode(tmp, res)
  1867. if !bytes.Equal(tmp, data) {
  1868. panic("wrong")
  1869. }
  1870. }
  1871. }
  1872. })
  1873. b.ReportMetric(100*float64(len(snapref.Encode(nil, data)))/float64(len(data)), "pct")
  1874. }
  1875. })
  1876. }
  1877. func TestRoundtrips(t *testing.T) {
  1878. testFile(t, 0, 10)
  1879. testFile(t, 1, 10)
  1880. testFile(t, 2, 10)
  1881. testFile(t, 3, 10)
  1882. testFile(t, 4, 10)
  1883. testFile(t, 5, 10)
  1884. testFile(t, 6, 10)
  1885. testFile(t, 7, 10)
  1886. testFile(t, 8, 10)
  1887. testFile(t, 9, 10)
  1888. testFile(t, 10, 10)
  1889. testFile(t, 11, 10)
  1890. testFile(t, 12, 0)
  1891. testFile(t, 13, 0)
  1892. testFile(t, 14, 0)
  1893. testFile(t, 15, 0)
  1894. }
  1895. func testFile(t *testing.T, i, repeat int) {
  1896. if err := downloadBenchmarkFiles(t, testFiles[i].filename); err != nil {
  1897. t.Skipf("failed to download testdata: %s", err)
  1898. }
  1899. if testing.Short() {
  1900. repeat = 0
  1901. }
  1902. t.Run(fmt.Sprint(i, "-", testFiles[i].label), func(t *testing.T) {
  1903. bDir := filepath.FromSlash(*benchdataDir)
  1904. data := readFile(t, filepath.Join(bDir, testFiles[i].filename))
  1905. if testing.Short() && len(data) > 10000 {
  1906. t.SkipNow()
  1907. }
  1908. oSize := len(data)
  1909. for i := 0; i < repeat; i++ {
  1910. data = append(data, data[:oSize]...)
  1911. }
  1912. t.Run("s2", func(t *testing.T) {
  1913. testWriterRoundtrip(t, data)
  1914. })
  1915. t.Run("s2-better", func(t *testing.T) {
  1916. testWriterRoundtrip(t, data, WriterBetterCompression())
  1917. })
  1918. t.Run("s2-best", func(t *testing.T) {
  1919. testWriterRoundtrip(t, data, WriterBestCompression())
  1920. })
  1921. t.Run("s2-uncompressed", func(t *testing.T) {
  1922. testWriterRoundtrip(t, data, WriterUncompressed())
  1923. })
  1924. t.Run("block", func(t *testing.T) {
  1925. d := data
  1926. testBlockRoundtrip(t, d)
  1927. })
  1928. t.Run("block-better", func(t *testing.T) {
  1929. d := data
  1930. testBetterBlockRoundtrip(t, d)
  1931. })
  1932. t.Run("block-best", func(t *testing.T) {
  1933. d := data
  1934. testBestBlockRoundtrip(t, d)
  1935. })
  1936. t.Run("s2-snappy", func(t *testing.T) {
  1937. d := data
  1938. testSnappyBlockRoundtrip(t, d)
  1939. })
  1940. t.Run("snappy", func(t *testing.T) {
  1941. testSnappyDecode(t, data)
  1942. })
  1943. })
  1944. }
  1945. func TestDataRoundtrips(t *testing.T) {
  1946. test := func(t *testing.T, data []byte) {
  1947. t.Run("s2", func(t *testing.T) {
  1948. testWriterRoundtrip(t, data)
  1949. })
  1950. t.Run("s2-better", func(t *testing.T) {
  1951. testWriterRoundtrip(t, data, WriterBetterCompression())
  1952. })
  1953. t.Run("s2-best", func(t *testing.T) {
  1954. testWriterRoundtrip(t, data, WriterBestCompression())
  1955. })
  1956. t.Run("block", func(t *testing.T) {
  1957. d := data
  1958. testBlockRoundtrip(t, d)
  1959. })
  1960. t.Run("block-better", func(t *testing.T) {
  1961. d := data
  1962. testBetterBlockRoundtrip(t, d)
  1963. })
  1964. t.Run("block-best", func(t *testing.T) {
  1965. d := data
  1966. testBestBlockRoundtrip(t, d)
  1967. })
  1968. t.Run("s2-snappy", func(t *testing.T) {
  1969. d := data
  1970. testSnappyBlockRoundtrip(t, d)
  1971. })
  1972. t.Run("snappy", func(t *testing.T) {
  1973. testSnappyDecode(t, data)
  1974. })
  1975. }
  1976. t.Run("longblock", func(t *testing.T) {
  1977. data := make([]byte, 1<<25)
  1978. if testing.Short() {
  1979. data = data[:1<<20]
  1980. }
  1981. test(t, data)
  1982. })
  1983. t.Run("4f9e1a0", func(t *testing.T) {
  1984. comp, _ := os.ReadFile("testdata/4f9e1a0da7915a3d69632f5613ed78bc998a8a23.zst")
  1985. dec, _ := zstd.NewReader(bytes.NewBuffer(comp))
  1986. data, _ := io.ReadAll(dec)
  1987. test(t, data)
  1988. })
  1989. data, err := os.ReadFile("testdata/enc_regressions.zip")
  1990. if err != nil {
  1991. t.Fatal(err)
  1992. }
  1993. zr, err := zip.NewReader(bytes.NewReader(data), int64(len(data)))
  1994. if err != nil {
  1995. t.Fatal(err)
  1996. }
  1997. for _, tt := range zr.File {
  1998. if !strings.HasSuffix(t.Name(), "") {
  1999. continue
  2000. }
  2001. t.Run(tt.Name, func(t *testing.T) {
  2002. r, err := tt.Open()
  2003. if err != nil {
  2004. t.Error(err)
  2005. return
  2006. }
  2007. b, err := io.ReadAll(r)
  2008. if err != nil {
  2009. t.Error(err)
  2010. return
  2011. }
  2012. test(t, b[:len(b):len(b)])
  2013. })
  2014. }
  2015. }
  2016. func BenchmarkDecodeS2BlockParallel(b *testing.B) {
  2017. for i := range testFiles {
  2018. b.Run(fmt.Sprint(i, "-", testFiles[i].label), func(b *testing.B) {
  2019. benchFile(b, i, true)
  2020. })
  2021. }
  2022. }
  2023. func BenchmarkEncodeS2BlockParallel(b *testing.B) {
  2024. for i := range testFiles {
  2025. b.Run(fmt.Sprint(i, "-", testFiles[i].label), func(b *testing.B) {
  2026. benchFile(b, i, false)
  2027. })
  2028. }
  2029. }
  2030. func BenchmarkDecodeSnappyBlockParallel(b *testing.B) {
  2031. for i := range testFiles {
  2032. b.Run(fmt.Sprint(i, "-", testFiles[i].label), func(b *testing.B) {
  2033. benchFileSnappy(b, i, true)
  2034. })
  2035. }
  2036. }
  2037. func BenchmarkEncodeSnappyBlockParallel(b *testing.B) {
  2038. for i := range testFiles {
  2039. b.Run(fmt.Sprint(i, "-", testFiles[i].label), func(b *testing.B) {
  2040. benchFileSnappy(b, i, false)
  2041. })
  2042. }
  2043. }
  2044. func TestMatchLen(t *testing.T) {
  2045. // ref is a simple, reference implementation of matchLen.
  2046. ref := func(a, b []byte) int {
  2047. n := 0
  2048. for i := range a {
  2049. if a[i] != b[i] {
  2050. break
  2051. }
  2052. n++
  2053. }
  2054. return n
  2055. }
  2056. // We allow slightly shorter matches at the end of slices
  2057. const maxBelow = 0
  2058. nums := []int{0, 1, 2, 7, 8, 9, 16, 20, 29, 30, 31, 32, 33, 34, 38, 39, 40}
  2059. for yIndex := 40; yIndex > 30; yIndex-- {
  2060. xxx := bytes.Repeat([]byte("x"), 40)
  2061. if yIndex < len(xxx) {
  2062. xxx[yIndex] = 'y'
  2063. }
  2064. for _, i := range nums {
  2065. for _, j := range nums {
  2066. if i >= j {
  2067. continue
  2068. }
  2069. got := matchLen(xxx[j:], xxx[i:])
  2070. want := ref(xxx[j:], xxx[i:])
  2071. if got > want {
  2072. t.Errorf("yIndex=%d, i=%d, j=%d: got %d, want %d", yIndex, i, j, got, want)
  2073. continue
  2074. }
  2075. if got < want-maxBelow {
  2076. t.Errorf("yIndex=%d, i=%d, j=%d: got %d, want %d", yIndex, i, j, got, want)
  2077. }
  2078. }
  2079. }
  2080. }
  2081. }