enc_better.go 34 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238
  1. // Copyright 2019+ Klaus Post. All rights reserved.
  2. // License information can be found in the LICENSE file.
  3. // Based on work by Yann Collet, released under BSD License.
  4. package zstd
  5. import "fmt"
  6. const (
  7. betterLongTableBits = 19 // Bits used in the long match table
  8. betterLongTableSize = 1 << betterLongTableBits // Size of the table
  9. betterLongLen = 8 // Bytes used for table hash
  10. // Note: Increasing the short table bits or making the hash shorter
  11. // can actually lead to compression degradation since it will 'steal' more from the
  12. // long match table and match offsets are quite big.
  13. // This greatly depends on the type of input.
  14. betterShortTableBits = 13 // Bits used in the short match table
  15. betterShortTableSize = 1 << betterShortTableBits // Size of the table
  16. betterShortLen = 5 // Bytes used for table hash
  17. betterLongTableShardCnt = 1 << (betterLongTableBits - dictShardBits) // Number of shards in the table
  18. betterLongTableShardSize = betterLongTableSize / betterLongTableShardCnt // Size of an individual shard
  19. betterShortTableShardCnt = 1 << (betterShortTableBits - dictShardBits) // Number of shards in the table
  20. betterShortTableShardSize = betterShortTableSize / betterShortTableShardCnt // Size of an individual shard
  21. )
  22. type prevEntry struct {
  23. offset int32
  24. prev int32
  25. }
  26. // betterFastEncoder uses 2 tables, one for short matches (5 bytes) and one for long matches.
  27. // The long match table contains the previous entry with the same hash,
  28. // effectively making it a "chain" of length 2.
  29. // When we find a long match we choose between the two values and select the longest.
  30. // When we find a short match, after checking the long, we check if we can find a long at n+1
  31. // and that it is longer (lazy matching).
  32. type betterFastEncoder struct {
  33. fastBase
  34. table [betterShortTableSize]tableEntry
  35. longTable [betterLongTableSize]prevEntry
  36. }
  37. type betterFastEncoderDict struct {
  38. betterFastEncoder
  39. dictTable []tableEntry
  40. dictLongTable []prevEntry
  41. shortTableShardDirty [betterShortTableShardCnt]bool
  42. longTableShardDirty [betterLongTableShardCnt]bool
  43. allDirty bool
  44. }
  45. // Encode improves compression...
  46. func (e *betterFastEncoder) Encode(blk *blockEnc, src []byte) {
  47. const (
  48. // Input margin is the number of bytes we read (8)
  49. // and the maximum we will read ahead (2)
  50. inputMargin = 8 + 2
  51. minNonLiteralBlockSize = 16
  52. )
  53. // Protect against e.cur wraparound.
  54. for e.cur >= e.bufferReset-int32(len(e.hist)) {
  55. if len(e.hist) == 0 {
  56. e.table = [betterShortTableSize]tableEntry{}
  57. e.longTable = [betterLongTableSize]prevEntry{}
  58. e.cur = e.maxMatchOff
  59. break
  60. }
  61. // Shift down everything in the table that isn't already too far away.
  62. minOff := e.cur + int32(len(e.hist)) - e.maxMatchOff
  63. for i := range e.table[:] {
  64. v := e.table[i].offset
  65. if v < minOff {
  66. v = 0
  67. } else {
  68. v = v - e.cur + e.maxMatchOff
  69. }
  70. e.table[i].offset = v
  71. }
  72. for i := range e.longTable[:] {
  73. v := e.longTable[i].offset
  74. v2 := e.longTable[i].prev
  75. if v < minOff {
  76. v = 0
  77. v2 = 0
  78. } else {
  79. v = v - e.cur + e.maxMatchOff
  80. if v2 < minOff {
  81. v2 = 0
  82. } else {
  83. v2 = v2 - e.cur + e.maxMatchOff
  84. }
  85. }
  86. e.longTable[i] = prevEntry{
  87. offset: v,
  88. prev: v2,
  89. }
  90. }
  91. e.cur = e.maxMatchOff
  92. break
  93. }
  94. // Add block to history
  95. s := e.addBlock(src)
  96. blk.size = len(src)
  97. // Check RLE first
  98. if len(src) > zstdMinMatch {
  99. ml := matchLen(src[1:], src)
  100. if ml == len(src)-1 {
  101. blk.literals = append(blk.literals, src[0])
  102. blk.sequences = append(blk.sequences, seq{litLen: 1, matchLen: uint32(len(src)-1) - zstdMinMatch, offset: 1 + 3})
  103. return
  104. }
  105. }
  106. if len(src) < minNonLiteralBlockSize {
  107. blk.extraLits = len(src)
  108. blk.literals = blk.literals[:len(src)]
  109. copy(blk.literals, src)
  110. return
  111. }
  112. // Override src
  113. src = e.hist
  114. sLimit := int32(len(src)) - inputMargin
  115. // stepSize is the number of bytes to skip on every main loop iteration.
  116. // It should be >= 1.
  117. const stepSize = 1
  118. const kSearchStrength = 9
  119. // nextEmit is where in src the next emitLiteral should start from.
  120. nextEmit := s
  121. cv := load6432(src, s)
  122. // Relative offsets
  123. offset1 := int32(blk.recentOffsets[0])
  124. offset2 := int32(blk.recentOffsets[1])
  125. addLiterals := func(s *seq, until int32) {
  126. if until == nextEmit {
  127. return
  128. }
  129. blk.literals = append(blk.literals, src[nextEmit:until]...)
  130. s.litLen = uint32(until - nextEmit)
  131. }
  132. if debugEncoder {
  133. println("recent offsets:", blk.recentOffsets)
  134. }
  135. encodeLoop:
  136. for {
  137. var t int32
  138. // We allow the encoder to optionally turn off repeat offsets across blocks
  139. canRepeat := len(blk.sequences) > 2
  140. var matched, index0 int32
  141. for {
  142. if debugAsserts && canRepeat && offset1 == 0 {
  143. panic("offset0 was 0")
  144. }
  145. nextHashL := hashLen(cv, betterLongTableBits, betterLongLen)
  146. nextHashS := hashLen(cv, betterShortTableBits, betterShortLen)
  147. candidateL := e.longTable[nextHashL]
  148. candidateS := e.table[nextHashS]
  149. const repOff = 1
  150. repIndex := s - offset1 + repOff
  151. off := s + e.cur
  152. e.longTable[nextHashL] = prevEntry{offset: off, prev: candidateL.offset}
  153. e.table[nextHashS] = tableEntry{offset: off, val: uint32(cv)}
  154. index0 = s + 1
  155. if canRepeat {
  156. if repIndex >= 0 && load3232(src, repIndex) == uint32(cv>>(repOff*8)) {
  157. // Consider history as well.
  158. var seq seq
  159. length := 4 + e.matchlen(s+4+repOff, repIndex+4, src)
  160. seq.matchLen = uint32(length - zstdMinMatch)
  161. // We might be able to match backwards.
  162. // Extend as long as we can.
  163. start := s + repOff
  164. // We end the search early, so we don't risk 0 literals
  165. // and have to do special offset treatment.
  166. startLimit := nextEmit + 1
  167. tMin := max(s-e.maxMatchOff, 0)
  168. for repIndex > tMin && start > startLimit && src[repIndex-1] == src[start-1] && seq.matchLen < maxMatchLength-zstdMinMatch-1 {
  169. repIndex--
  170. start--
  171. seq.matchLen++
  172. }
  173. addLiterals(&seq, start)
  174. // rep 0
  175. seq.offset = 1
  176. if debugSequences {
  177. println("repeat sequence", seq, "next s:", s)
  178. }
  179. blk.sequences = append(blk.sequences, seq)
  180. // Index match start+1 (long) -> s - 1
  181. index0 := s + repOff
  182. s += length + repOff
  183. nextEmit = s
  184. if s >= sLimit {
  185. if debugEncoder {
  186. println("repeat ended", s, length)
  187. }
  188. break encodeLoop
  189. }
  190. // Index skipped...
  191. for index0 < s-1 {
  192. cv0 := load6432(src, index0)
  193. cv1 := cv0 >> 8
  194. h0 := hashLen(cv0, betterLongTableBits, betterLongLen)
  195. off := index0 + e.cur
  196. e.longTable[h0] = prevEntry{offset: off, prev: e.longTable[h0].offset}
  197. e.table[hashLen(cv1, betterShortTableBits, betterShortLen)] = tableEntry{offset: off + 1, val: uint32(cv1)}
  198. index0 += 2
  199. }
  200. cv = load6432(src, s)
  201. continue
  202. }
  203. const repOff2 = 1
  204. // We deviate from the reference encoder and also check offset 2.
  205. // Still slower and not much better, so disabled.
  206. // repIndex = s - offset2 + repOff2
  207. if false && repIndex >= 0 && load6432(src, repIndex) == load6432(src, s+repOff) {
  208. // Consider history as well.
  209. var seq seq
  210. length := 8 + e.matchlen(s+8+repOff2, repIndex+8, src)
  211. seq.matchLen = uint32(length - zstdMinMatch)
  212. // We might be able to match backwards.
  213. // Extend as long as we can.
  214. start := s + repOff2
  215. // We end the search early, so we don't risk 0 literals
  216. // and have to do special offset treatment.
  217. startLimit := nextEmit + 1
  218. tMin := max(s-e.maxMatchOff, 0)
  219. for repIndex > tMin && start > startLimit && src[repIndex-1] == src[start-1] && seq.matchLen < maxMatchLength-zstdMinMatch-1 {
  220. repIndex--
  221. start--
  222. seq.matchLen++
  223. }
  224. addLiterals(&seq, start)
  225. // rep 2
  226. seq.offset = 2
  227. if debugSequences {
  228. println("repeat sequence 2", seq, "next s:", s)
  229. }
  230. blk.sequences = append(blk.sequences, seq)
  231. s += length + repOff2
  232. nextEmit = s
  233. if s >= sLimit {
  234. if debugEncoder {
  235. println("repeat ended", s, length)
  236. }
  237. break encodeLoop
  238. }
  239. // Index skipped...
  240. for index0 < s-1 {
  241. cv0 := load6432(src, index0)
  242. cv1 := cv0 >> 8
  243. h0 := hashLen(cv0, betterLongTableBits, betterLongLen)
  244. off := index0 + e.cur
  245. e.longTable[h0] = prevEntry{offset: off, prev: e.longTable[h0].offset}
  246. e.table[hashLen(cv1, betterShortTableBits, betterShortLen)] = tableEntry{offset: off + 1, val: uint32(cv1)}
  247. index0 += 2
  248. }
  249. cv = load6432(src, s)
  250. // Swap offsets
  251. offset1, offset2 = offset2, offset1
  252. continue
  253. }
  254. }
  255. // Find the offsets of our two matches.
  256. coffsetL := candidateL.offset - e.cur
  257. coffsetLP := candidateL.prev - e.cur
  258. // Check if we have a long match.
  259. if s-coffsetL < e.maxMatchOff && cv == load6432(src, coffsetL) {
  260. // Found a long match, at least 8 bytes.
  261. matched = e.matchlen(s+8, coffsetL+8, src) + 8
  262. t = coffsetL
  263. if debugAsserts && s <= t {
  264. panic(fmt.Sprintf("s (%d) <= t (%d)", s, t))
  265. }
  266. if debugAsserts && s-t > e.maxMatchOff {
  267. panic("s - t >e.maxMatchOff")
  268. }
  269. if debugMatches {
  270. println("long match")
  271. }
  272. if s-coffsetLP < e.maxMatchOff && cv == load6432(src, coffsetLP) {
  273. // Found a long match, at least 8 bytes.
  274. prevMatch := e.matchlen(s+8, coffsetLP+8, src) + 8
  275. if prevMatch > matched {
  276. matched = prevMatch
  277. t = coffsetLP
  278. }
  279. if debugAsserts && s <= t {
  280. panic(fmt.Sprintf("s (%d) <= t (%d)", s, t))
  281. }
  282. if debugAsserts && s-t > e.maxMatchOff {
  283. panic("s - t >e.maxMatchOff")
  284. }
  285. if debugMatches {
  286. println("long match")
  287. }
  288. }
  289. break
  290. }
  291. // Check if we have a long match on prev.
  292. if s-coffsetLP < e.maxMatchOff && cv == load6432(src, coffsetLP) {
  293. // Found a long match, at least 8 bytes.
  294. matched = e.matchlen(s+8, coffsetLP+8, src) + 8
  295. t = coffsetLP
  296. if debugAsserts && s <= t {
  297. panic(fmt.Sprintf("s (%d) <= t (%d)", s, t))
  298. }
  299. if debugAsserts && s-t > e.maxMatchOff {
  300. panic("s - t >e.maxMatchOff")
  301. }
  302. if debugMatches {
  303. println("long match")
  304. }
  305. break
  306. }
  307. coffsetS := candidateS.offset - e.cur
  308. // Check if we have a short match.
  309. if s-coffsetS < e.maxMatchOff && uint32(cv) == candidateS.val {
  310. // found a regular match
  311. matched = e.matchlen(s+4, coffsetS+4, src) + 4
  312. // See if we can find a long match at s+1
  313. const checkAt = 1
  314. cv := load6432(src, s+checkAt)
  315. nextHashL = hashLen(cv, betterLongTableBits, betterLongLen)
  316. candidateL = e.longTable[nextHashL]
  317. coffsetL = candidateL.offset - e.cur
  318. // We can store it, since we have at least a 4 byte match.
  319. e.longTable[nextHashL] = prevEntry{offset: s + checkAt + e.cur, prev: candidateL.offset}
  320. if s-coffsetL < e.maxMatchOff && cv == load6432(src, coffsetL) {
  321. // Found a long match, at least 8 bytes.
  322. matchedNext := e.matchlen(s+8+checkAt, coffsetL+8, src) + 8
  323. if matchedNext > matched {
  324. t = coffsetL
  325. s += checkAt
  326. matched = matchedNext
  327. if debugMatches {
  328. println("long match (after short)")
  329. }
  330. break
  331. }
  332. }
  333. // Check prev long...
  334. coffsetL = candidateL.prev - e.cur
  335. if s-coffsetL < e.maxMatchOff && cv == load6432(src, coffsetL) {
  336. // Found a long match, at least 8 bytes.
  337. matchedNext := e.matchlen(s+8+checkAt, coffsetL+8, src) + 8
  338. if matchedNext > matched {
  339. t = coffsetL
  340. s += checkAt
  341. matched = matchedNext
  342. if debugMatches {
  343. println("prev long match (after short)")
  344. }
  345. break
  346. }
  347. }
  348. t = coffsetS
  349. if debugAsserts && s <= t {
  350. panic(fmt.Sprintf("s (%d) <= t (%d)", s, t))
  351. }
  352. if debugAsserts && s-t > e.maxMatchOff {
  353. panic("s - t >e.maxMatchOff")
  354. }
  355. if debugAsserts && t < 0 {
  356. panic("t<0")
  357. }
  358. if debugMatches {
  359. println("short match")
  360. }
  361. break
  362. }
  363. // No match found, move forward in input.
  364. s += stepSize + ((s - nextEmit) >> (kSearchStrength - 1))
  365. if s >= sLimit {
  366. break encodeLoop
  367. }
  368. cv = load6432(src, s)
  369. }
  370. // Try to find a better match by searching for a long match at the end of the current best match
  371. if s+matched < sLimit {
  372. // Allow some bytes at the beginning to mismatch.
  373. // Sweet spot is around 3 bytes, but depends on input.
  374. // The skipped bytes are tested in Extend backwards,
  375. // and still picked up as part of the match if they do.
  376. const skipBeginning = 3
  377. nextHashL := hashLen(load6432(src, s+matched), betterLongTableBits, betterLongLen)
  378. s2 := s + skipBeginning
  379. cv := load3232(src, s2)
  380. candidateL := e.longTable[nextHashL]
  381. coffsetL := candidateL.offset - e.cur - matched + skipBeginning
  382. if coffsetL >= 0 && coffsetL < s2 && s2-coffsetL < e.maxMatchOff && cv == load3232(src, coffsetL) {
  383. // Found a long match, at least 4 bytes.
  384. matchedNext := e.matchlen(s2+4, coffsetL+4, src) + 4
  385. if matchedNext > matched {
  386. t = coffsetL
  387. s = s2
  388. matched = matchedNext
  389. if debugMatches {
  390. println("long match at end-of-match")
  391. }
  392. }
  393. }
  394. // Check prev long...
  395. if true {
  396. coffsetL = candidateL.prev - e.cur - matched + skipBeginning
  397. if coffsetL >= 0 && coffsetL < s2 && s2-coffsetL < e.maxMatchOff && cv == load3232(src, coffsetL) {
  398. // Found a long match, at least 4 bytes.
  399. matchedNext := e.matchlen(s2+4, coffsetL+4, src) + 4
  400. if matchedNext > matched {
  401. t = coffsetL
  402. s = s2
  403. matched = matchedNext
  404. if debugMatches {
  405. println("prev long match at end-of-match")
  406. }
  407. }
  408. }
  409. }
  410. }
  411. // A match has been found. Update recent offsets.
  412. offset2 = offset1
  413. offset1 = s - t
  414. if debugAsserts && s <= t {
  415. panic(fmt.Sprintf("s (%d) <= t (%d)", s, t))
  416. }
  417. if debugAsserts && canRepeat && int(offset1) > len(src) {
  418. panic("invalid offset")
  419. }
  420. // Extend the n-byte match as long as possible.
  421. l := matched
  422. // Extend backwards
  423. tMin := max(s-e.maxMatchOff, 0)
  424. for t > tMin && s > nextEmit && src[t-1] == src[s-1] && l < maxMatchLength {
  425. s--
  426. t--
  427. l++
  428. }
  429. // Write our sequence
  430. var seq seq
  431. seq.litLen = uint32(s - nextEmit)
  432. seq.matchLen = uint32(l - zstdMinMatch)
  433. if seq.litLen > 0 {
  434. blk.literals = append(blk.literals, src[nextEmit:s]...)
  435. }
  436. seq.offset = uint32(s-t) + 3
  437. s += l
  438. if debugSequences {
  439. println("sequence", seq, "next s:", s)
  440. }
  441. blk.sequences = append(blk.sequences, seq)
  442. nextEmit = s
  443. if s >= sLimit {
  444. break encodeLoop
  445. }
  446. // Index match start+1 (long) -> s - 1
  447. off := index0 + e.cur
  448. for index0 < s-1 {
  449. cv0 := load6432(src, index0)
  450. cv1 := cv0 >> 8
  451. h0 := hashLen(cv0, betterLongTableBits, betterLongLen)
  452. e.longTable[h0] = prevEntry{offset: off, prev: e.longTable[h0].offset}
  453. e.table[hashLen(cv1, betterShortTableBits, betterShortLen)] = tableEntry{offset: off + 1, val: uint32(cv1)}
  454. index0 += 2
  455. off += 2
  456. }
  457. cv = load6432(src, s)
  458. if !canRepeat {
  459. continue
  460. }
  461. // Check offset 2
  462. for {
  463. o2 := s - offset2
  464. if load3232(src, o2) != uint32(cv) {
  465. // Do regular search
  466. break
  467. }
  468. // Store this, since we have it.
  469. nextHashL := hashLen(cv, betterLongTableBits, betterLongLen)
  470. nextHashS := hashLen(cv, betterShortTableBits, betterShortLen)
  471. // We have at least 4 byte match.
  472. // No need to check backwards. We come straight from a match
  473. l := 4 + e.matchlen(s+4, o2+4, src)
  474. e.longTable[nextHashL] = prevEntry{offset: s + e.cur, prev: e.longTable[nextHashL].offset}
  475. e.table[nextHashS] = tableEntry{offset: s + e.cur, val: uint32(cv)}
  476. seq.matchLen = uint32(l) - zstdMinMatch
  477. seq.litLen = 0
  478. // Since litlen is always 0, this is offset 1.
  479. seq.offset = 1
  480. s += l
  481. nextEmit = s
  482. if debugSequences {
  483. println("sequence", seq, "next s:", s)
  484. }
  485. blk.sequences = append(blk.sequences, seq)
  486. // Swap offset 1 and 2.
  487. offset1, offset2 = offset2, offset1
  488. if s >= sLimit {
  489. // Finished
  490. break encodeLoop
  491. }
  492. cv = load6432(src, s)
  493. }
  494. }
  495. if int(nextEmit) < len(src) {
  496. blk.literals = append(blk.literals, src[nextEmit:]...)
  497. blk.extraLits = len(src) - int(nextEmit)
  498. }
  499. blk.recentOffsets[0] = uint32(offset1)
  500. blk.recentOffsets[1] = uint32(offset2)
  501. if debugEncoder {
  502. println("returning, recent offsets:", blk.recentOffsets, "extra literals:", blk.extraLits)
  503. }
  504. }
  505. // EncodeNoHist will encode a block with no history and no following blocks.
  506. // Most notable difference is that src will not be copied for history and
  507. // we do not need to check for max match length.
  508. func (e *betterFastEncoder) EncodeNoHist(blk *blockEnc, src []byte) {
  509. e.ensureHist(len(src))
  510. e.Encode(blk, src)
  511. }
  512. // Encode improves compression...
  513. func (e *betterFastEncoderDict) Encode(blk *blockEnc, src []byte) {
  514. const (
  515. // Input margin is the number of bytes we read (8)
  516. // and the maximum we will read ahead (2)
  517. inputMargin = 8 + 2
  518. minNonLiteralBlockSize = 16
  519. )
  520. // Protect against e.cur wraparound.
  521. for e.cur >= e.bufferReset-int32(len(e.hist)) {
  522. if len(e.hist) == 0 {
  523. for i := range e.table[:] {
  524. e.table[i] = tableEntry{}
  525. }
  526. for i := range e.longTable[:] {
  527. e.longTable[i] = prevEntry{}
  528. }
  529. e.cur = e.maxMatchOff
  530. e.allDirty = true
  531. break
  532. }
  533. // Shift down everything in the table that isn't already too far away.
  534. minOff := e.cur + int32(len(e.hist)) - e.maxMatchOff
  535. for i := range e.table[:] {
  536. v := e.table[i].offset
  537. if v < minOff {
  538. v = 0
  539. } else {
  540. v = v - e.cur + e.maxMatchOff
  541. }
  542. e.table[i].offset = v
  543. }
  544. for i := range e.longTable[:] {
  545. v := e.longTable[i].offset
  546. v2 := e.longTable[i].prev
  547. if v < minOff {
  548. v = 0
  549. v2 = 0
  550. } else {
  551. v = v - e.cur + e.maxMatchOff
  552. if v2 < minOff {
  553. v2 = 0
  554. } else {
  555. v2 = v2 - e.cur + e.maxMatchOff
  556. }
  557. }
  558. e.longTable[i] = prevEntry{
  559. offset: v,
  560. prev: v2,
  561. }
  562. }
  563. e.allDirty = true
  564. e.cur = e.maxMatchOff
  565. break
  566. }
  567. s := e.addBlock(src)
  568. blk.size = len(src)
  569. if len(src) < minNonLiteralBlockSize {
  570. blk.extraLits = len(src)
  571. blk.literals = blk.literals[:len(src)]
  572. copy(blk.literals, src)
  573. return
  574. }
  575. // Override src
  576. src = e.hist
  577. sLimit := int32(len(src)) - inputMargin
  578. // stepSize is the number of bytes to skip on every main loop iteration.
  579. // It should be >= 1.
  580. const stepSize = 1
  581. const kSearchStrength = 9
  582. // nextEmit is where in src the next emitLiteral should start from.
  583. nextEmit := s
  584. cv := load6432(src, s)
  585. // Relative offsets
  586. offset1 := int32(blk.recentOffsets[0])
  587. offset2 := int32(blk.recentOffsets[1])
  588. addLiterals := func(s *seq, until int32) {
  589. if until == nextEmit {
  590. return
  591. }
  592. blk.literals = append(blk.literals, src[nextEmit:until]...)
  593. s.litLen = uint32(until - nextEmit)
  594. }
  595. if debugEncoder {
  596. println("recent offsets:", blk.recentOffsets)
  597. }
  598. encodeLoop:
  599. for {
  600. var t int32
  601. // We allow the encoder to optionally turn off repeat offsets across blocks
  602. canRepeat := len(blk.sequences) > 2
  603. var matched, index0 int32
  604. for {
  605. if debugAsserts && canRepeat && offset1 == 0 {
  606. panic("offset0 was 0")
  607. }
  608. nextHashL := hashLen(cv, betterLongTableBits, betterLongLen)
  609. nextHashS := hashLen(cv, betterShortTableBits, betterShortLen)
  610. candidateL := e.longTable[nextHashL]
  611. candidateS := e.table[nextHashS]
  612. const repOff = 1
  613. repIndex := s - offset1 + repOff
  614. off := s + e.cur
  615. e.longTable[nextHashL] = prevEntry{offset: off, prev: candidateL.offset}
  616. e.markLongShardDirty(nextHashL)
  617. e.table[nextHashS] = tableEntry{offset: off, val: uint32(cv)}
  618. e.markShortShardDirty(nextHashS)
  619. index0 = s + 1
  620. if canRepeat {
  621. if repIndex >= 0 && load3232(src, repIndex) == uint32(cv>>(repOff*8)) {
  622. // Consider history as well.
  623. var seq seq
  624. length := 4 + e.matchlen(s+4+repOff, repIndex+4, src)
  625. seq.matchLen = uint32(length - zstdMinMatch)
  626. // We might be able to match backwards.
  627. // Extend as long as we can.
  628. start := s + repOff
  629. // We end the search early, so we don't risk 0 literals
  630. // and have to do special offset treatment.
  631. startLimit := nextEmit + 1
  632. tMin := max(s-e.maxMatchOff, 0)
  633. for repIndex > tMin && start > startLimit && src[repIndex-1] == src[start-1] && seq.matchLen < maxMatchLength-zstdMinMatch-1 {
  634. repIndex--
  635. start--
  636. seq.matchLen++
  637. }
  638. addLiterals(&seq, start)
  639. // rep 0
  640. seq.offset = 1
  641. if debugSequences {
  642. println("repeat sequence", seq, "next s:", s)
  643. }
  644. blk.sequences = append(blk.sequences, seq)
  645. // Index match start+1 (long) -> s - 1
  646. s += length + repOff
  647. nextEmit = s
  648. if s >= sLimit {
  649. if debugEncoder {
  650. println("repeat ended", s, length)
  651. }
  652. break encodeLoop
  653. }
  654. // Index skipped...
  655. for index0 < s-1 {
  656. cv0 := load6432(src, index0)
  657. cv1 := cv0 >> 8
  658. h0 := hashLen(cv0, betterLongTableBits, betterLongLen)
  659. off := index0 + e.cur
  660. e.longTable[h0] = prevEntry{offset: off, prev: e.longTable[h0].offset}
  661. e.markLongShardDirty(h0)
  662. h1 := hashLen(cv1, betterShortTableBits, betterShortLen)
  663. e.table[h1] = tableEntry{offset: off + 1, val: uint32(cv1)}
  664. e.markShortShardDirty(h1)
  665. index0 += 2
  666. }
  667. cv = load6432(src, s)
  668. continue
  669. }
  670. const repOff2 = 1
  671. // We deviate from the reference encoder and also check offset 2.
  672. // Still slower and not much better, so disabled.
  673. // repIndex = s - offset2 + repOff2
  674. if false && repIndex >= 0 && load6432(src, repIndex) == load6432(src, s+repOff) {
  675. // Consider history as well.
  676. var seq seq
  677. length := 8 + e.matchlen(s+8+repOff2, repIndex+8, src)
  678. seq.matchLen = uint32(length - zstdMinMatch)
  679. // We might be able to match backwards.
  680. // Extend as long as we can.
  681. start := s + repOff2
  682. // We end the search early, so we don't risk 0 literals
  683. // and have to do special offset treatment.
  684. startLimit := nextEmit + 1
  685. tMin := max(s-e.maxMatchOff, 0)
  686. for repIndex > tMin && start > startLimit && src[repIndex-1] == src[start-1] && seq.matchLen < maxMatchLength-zstdMinMatch-1 {
  687. repIndex--
  688. start--
  689. seq.matchLen++
  690. }
  691. addLiterals(&seq, start)
  692. // rep 2
  693. seq.offset = 2
  694. if debugSequences {
  695. println("repeat sequence 2", seq, "next s:", s)
  696. }
  697. blk.sequences = append(blk.sequences, seq)
  698. s += length + repOff2
  699. nextEmit = s
  700. if s >= sLimit {
  701. if debugEncoder {
  702. println("repeat ended", s, length)
  703. }
  704. break encodeLoop
  705. }
  706. // Index skipped...
  707. for index0 < s-1 {
  708. cv0 := load6432(src, index0)
  709. cv1 := cv0 >> 8
  710. h0 := hashLen(cv0, betterLongTableBits, betterLongLen)
  711. off := index0 + e.cur
  712. e.longTable[h0] = prevEntry{offset: off, prev: e.longTable[h0].offset}
  713. e.markLongShardDirty(h0)
  714. h1 := hashLen(cv1, betterShortTableBits, betterShortLen)
  715. e.table[h1] = tableEntry{offset: off + 1, val: uint32(cv1)}
  716. e.markShortShardDirty(h1)
  717. index0 += 2
  718. }
  719. cv = load6432(src, s)
  720. // Swap offsets
  721. offset1, offset2 = offset2, offset1
  722. continue
  723. }
  724. }
  725. // Find the offsets of our two matches.
  726. coffsetL := candidateL.offset - e.cur
  727. coffsetLP := candidateL.prev - e.cur
  728. // Check if we have a long match.
  729. if s-coffsetL < e.maxMatchOff && cv == load6432(src, coffsetL) {
  730. // Found a long match, at least 8 bytes.
  731. matched = e.matchlen(s+8, coffsetL+8, src) + 8
  732. t = coffsetL
  733. if debugAsserts && s <= t {
  734. panic(fmt.Sprintf("s (%d) <= t (%d)", s, t))
  735. }
  736. if debugAsserts && s-t > e.maxMatchOff {
  737. panic("s - t >e.maxMatchOff")
  738. }
  739. if debugMatches {
  740. println("long match")
  741. }
  742. if s-coffsetLP < e.maxMatchOff && cv == load6432(src, coffsetLP) {
  743. // Found a long match, at least 8 bytes.
  744. prevMatch := e.matchlen(s+8, coffsetLP+8, src) + 8
  745. if prevMatch > matched {
  746. matched = prevMatch
  747. t = coffsetLP
  748. }
  749. if debugAsserts && s <= t {
  750. panic(fmt.Sprintf("s (%d) <= t (%d)", s, t))
  751. }
  752. if debugAsserts && s-t > e.maxMatchOff {
  753. panic("s - t >e.maxMatchOff")
  754. }
  755. if debugMatches {
  756. println("long match")
  757. }
  758. }
  759. break
  760. }
  761. // Check if we have a long match on prev.
  762. if s-coffsetLP < e.maxMatchOff && cv == load6432(src, coffsetLP) {
  763. // Found a long match, at least 8 bytes.
  764. matched = e.matchlen(s+8, coffsetLP+8, src) + 8
  765. t = coffsetLP
  766. if debugAsserts && s <= t {
  767. panic(fmt.Sprintf("s (%d) <= t (%d)", s, t))
  768. }
  769. if debugAsserts && s-t > e.maxMatchOff {
  770. panic("s - t >e.maxMatchOff")
  771. }
  772. if debugMatches {
  773. println("long match")
  774. }
  775. break
  776. }
  777. coffsetS := candidateS.offset - e.cur
  778. // Check if we have a short match.
  779. if s-coffsetS < e.maxMatchOff && uint32(cv) == candidateS.val {
  780. // found a regular match
  781. matched = e.matchlen(s+4, coffsetS+4, src) + 4
  782. // See if we can find a long match at s+1
  783. const checkAt = 1
  784. cv := load6432(src, s+checkAt)
  785. nextHashL = hashLen(cv, betterLongTableBits, betterLongLen)
  786. candidateL = e.longTable[nextHashL]
  787. coffsetL = candidateL.offset - e.cur
  788. // We can store it, since we have at least a 4 byte match.
  789. e.longTable[nextHashL] = prevEntry{offset: s + checkAt + e.cur, prev: candidateL.offset}
  790. e.markLongShardDirty(nextHashL)
  791. if s-coffsetL < e.maxMatchOff && cv == load6432(src, coffsetL) {
  792. // Found a long match, at least 8 bytes.
  793. matchedNext := e.matchlen(s+8+checkAt, coffsetL+8, src) + 8
  794. if matchedNext > matched {
  795. t = coffsetL
  796. s += checkAt
  797. matched = matchedNext
  798. if debugMatches {
  799. println("long match (after short)")
  800. }
  801. break
  802. }
  803. }
  804. // Check prev long...
  805. coffsetL = candidateL.prev - e.cur
  806. if s-coffsetL < e.maxMatchOff && cv == load6432(src, coffsetL) {
  807. // Found a long match, at least 8 bytes.
  808. matchedNext := e.matchlen(s+8+checkAt, coffsetL+8, src) + 8
  809. if matchedNext > matched {
  810. t = coffsetL
  811. s += checkAt
  812. matched = matchedNext
  813. if debugMatches {
  814. println("prev long match (after short)")
  815. }
  816. break
  817. }
  818. }
  819. t = coffsetS
  820. if debugAsserts && s <= t {
  821. panic(fmt.Sprintf("s (%d) <= t (%d)", s, t))
  822. }
  823. if debugAsserts && s-t > e.maxMatchOff {
  824. panic("s - t >e.maxMatchOff")
  825. }
  826. if debugAsserts && t < 0 {
  827. panic("t<0")
  828. }
  829. if debugMatches {
  830. println("short match")
  831. }
  832. break
  833. }
  834. // No match found, move forward in input.
  835. s += stepSize + ((s - nextEmit) >> (kSearchStrength - 1))
  836. if s >= sLimit {
  837. break encodeLoop
  838. }
  839. cv = load6432(src, s)
  840. }
  841. // Try to find a better match by searching for a long match at the end of the current best match
  842. if s+matched < sLimit {
  843. nextHashL := hashLen(load6432(src, s+matched), betterLongTableBits, betterLongLen)
  844. cv := load3232(src, s)
  845. candidateL := e.longTable[nextHashL]
  846. coffsetL := candidateL.offset - e.cur - matched
  847. if coffsetL >= 0 && coffsetL < s && s-coffsetL < e.maxMatchOff && cv == load3232(src, coffsetL) {
  848. // Found a long match, at least 4 bytes.
  849. matchedNext := e.matchlen(s+4, coffsetL+4, src) + 4
  850. if matchedNext > matched {
  851. t = coffsetL
  852. matched = matchedNext
  853. if debugMatches {
  854. println("long match at end-of-match")
  855. }
  856. }
  857. }
  858. // Check prev long...
  859. if true {
  860. coffsetL = candidateL.prev - e.cur - matched
  861. if coffsetL >= 0 && coffsetL < s && s-coffsetL < e.maxMatchOff && cv == load3232(src, coffsetL) {
  862. // Found a long match, at least 4 bytes.
  863. matchedNext := e.matchlen(s+4, coffsetL+4, src) + 4
  864. if matchedNext > matched {
  865. t = coffsetL
  866. matched = matchedNext
  867. if debugMatches {
  868. println("prev long match at end-of-match")
  869. }
  870. }
  871. }
  872. }
  873. }
  874. // A match has been found. Update recent offsets.
  875. offset2 = offset1
  876. offset1 = s - t
  877. if debugAsserts && s <= t {
  878. panic(fmt.Sprintf("s (%d) <= t (%d)", s, t))
  879. }
  880. if debugAsserts && canRepeat && int(offset1) > len(src) {
  881. panic("invalid offset")
  882. }
  883. // Extend the n-byte match as long as possible.
  884. l := matched
  885. // Extend backwards
  886. tMin := max(s-e.maxMatchOff, 0)
  887. for t > tMin && s > nextEmit && src[t-1] == src[s-1] && l < maxMatchLength {
  888. s--
  889. t--
  890. l++
  891. }
  892. // Write our sequence
  893. var seq seq
  894. seq.litLen = uint32(s - nextEmit)
  895. seq.matchLen = uint32(l - zstdMinMatch)
  896. if seq.litLen > 0 {
  897. blk.literals = append(blk.literals, src[nextEmit:s]...)
  898. }
  899. seq.offset = uint32(s-t) + 3
  900. s += l
  901. if debugSequences {
  902. println("sequence", seq, "next s:", s)
  903. }
  904. blk.sequences = append(blk.sequences, seq)
  905. nextEmit = s
  906. if s >= sLimit {
  907. break encodeLoop
  908. }
  909. // Index match start+1 (long) -> s - 1
  910. off := index0 + e.cur
  911. for index0 < s-1 {
  912. cv0 := load6432(src, index0)
  913. cv1 := cv0 >> 8
  914. h0 := hashLen(cv0, betterLongTableBits, betterLongLen)
  915. e.longTable[h0] = prevEntry{offset: off, prev: e.longTable[h0].offset}
  916. e.markLongShardDirty(h0)
  917. h1 := hashLen(cv1, betterShortTableBits, betterShortLen)
  918. e.table[h1] = tableEntry{offset: off + 1, val: uint32(cv1)}
  919. e.markShortShardDirty(h1)
  920. index0 += 2
  921. off += 2
  922. }
  923. cv = load6432(src, s)
  924. if !canRepeat {
  925. continue
  926. }
  927. // Check offset 2
  928. for {
  929. o2 := s - offset2
  930. if load3232(src, o2) != uint32(cv) {
  931. // Do regular search
  932. break
  933. }
  934. // Store this, since we have it.
  935. nextHashL := hashLen(cv, betterLongTableBits, betterLongLen)
  936. nextHashS := hashLen(cv, betterShortTableBits, betterShortLen)
  937. // We have at least 4 byte match.
  938. // No need to check backwards. We come straight from a match
  939. l := 4 + e.matchlen(s+4, o2+4, src)
  940. e.longTable[nextHashL] = prevEntry{offset: s + e.cur, prev: e.longTable[nextHashL].offset}
  941. e.markLongShardDirty(nextHashL)
  942. e.table[nextHashS] = tableEntry{offset: s + e.cur, val: uint32(cv)}
  943. e.markShortShardDirty(nextHashS)
  944. seq.matchLen = uint32(l) - zstdMinMatch
  945. seq.litLen = 0
  946. // Since litlen is always 0, this is offset 1.
  947. seq.offset = 1
  948. s += l
  949. nextEmit = s
  950. if debugSequences {
  951. println("sequence", seq, "next s:", s)
  952. }
  953. blk.sequences = append(blk.sequences, seq)
  954. // Swap offset 1 and 2.
  955. offset1, offset2 = offset2, offset1
  956. if s >= sLimit {
  957. // Finished
  958. break encodeLoop
  959. }
  960. cv = load6432(src, s)
  961. }
  962. }
  963. if int(nextEmit) < len(src) {
  964. blk.literals = append(blk.literals, src[nextEmit:]...)
  965. blk.extraLits = len(src) - int(nextEmit)
  966. }
  967. blk.recentOffsets[0] = uint32(offset1)
  968. blk.recentOffsets[1] = uint32(offset2)
  969. if debugEncoder {
  970. println("returning, recent offsets:", blk.recentOffsets, "extra literals:", blk.extraLits)
  971. }
  972. }
  973. // ResetDict will reset and set a dictionary if not nil
  974. func (e *betterFastEncoder) Reset(d *dict, singleBlock bool) {
  975. e.resetBase(d, singleBlock)
  976. if d != nil {
  977. panic("betterFastEncoder: Reset with dict")
  978. }
  979. }
  980. // ResetDict will reset and set a dictionary if not nil
  981. func (e *betterFastEncoderDict) Reset(d *dict, singleBlock bool) {
  982. e.resetBase(d, singleBlock)
  983. if d == nil {
  984. return
  985. }
  986. dictChanged := d != e.lastDict
  987. // Init or copy dict table
  988. if len(e.dictTable) != len(e.table) || dictChanged {
  989. if len(e.dictTable) != len(e.table) {
  990. e.dictTable = make([]tableEntry, len(e.table))
  991. } else {
  992. clear(e.dictTable)
  993. }
  994. end := int32(len(d.content)) - 8 + e.maxMatchOff
  995. for i := e.maxMatchOff; i < end; i += 4 {
  996. const hashLog = betterShortTableBits
  997. cv := load6432(d.content, i-e.maxMatchOff)
  998. nextHash := hashLen(cv, hashLog, betterShortLen) // 0 -> 4
  999. nextHash1 := hashLen(cv>>8, hashLog, betterShortLen) // 1 -> 5
  1000. nextHash2 := hashLen(cv>>16, hashLog, betterShortLen) // 2 -> 6
  1001. nextHash3 := hashLen(cv>>24, hashLog, betterShortLen) // 3 -> 7
  1002. e.dictTable[nextHash] = tableEntry{
  1003. val: uint32(cv),
  1004. offset: i,
  1005. }
  1006. e.dictTable[nextHash1] = tableEntry{
  1007. val: uint32(cv >> 8),
  1008. offset: i + 1,
  1009. }
  1010. e.dictTable[nextHash2] = tableEntry{
  1011. val: uint32(cv >> 16),
  1012. offset: i + 2,
  1013. }
  1014. e.dictTable[nextHash3] = tableEntry{
  1015. val: uint32(cv >> 24),
  1016. offset: i + 3,
  1017. }
  1018. }
  1019. e.allDirty = true
  1020. }
  1021. // Init or copy dict long table
  1022. if len(e.dictLongTable) != len(e.longTable) || dictChanged {
  1023. if len(e.dictLongTable) != len(e.longTable) {
  1024. e.dictLongTable = make([]prevEntry, len(e.longTable))
  1025. } else {
  1026. clear(e.dictLongTable)
  1027. }
  1028. if len(d.content) >= 8 {
  1029. cv := load6432(d.content, 0)
  1030. h := hashLen(cv, betterLongTableBits, betterLongLen)
  1031. e.dictLongTable[h] = prevEntry{
  1032. offset: e.maxMatchOff,
  1033. prev: e.dictLongTable[h].offset,
  1034. }
  1035. end := int32(len(d.content)) - 8 + e.maxMatchOff
  1036. off := 8 // First to read
  1037. for i := e.maxMatchOff + 1; i < end; i++ {
  1038. cv = cv>>8 | (uint64(d.content[off]) << 56)
  1039. h := hashLen(cv, betterLongTableBits, betterLongLen)
  1040. e.dictLongTable[h] = prevEntry{
  1041. offset: i,
  1042. prev: e.dictLongTable[h].offset,
  1043. }
  1044. off++
  1045. }
  1046. }
  1047. e.allDirty = true
  1048. }
  1049. e.lastDict = d
  1050. // Reset table to initial state
  1051. {
  1052. dirtyShardCnt := 0
  1053. if !e.allDirty {
  1054. for i := range e.shortTableShardDirty {
  1055. if e.shortTableShardDirty[i] {
  1056. dirtyShardCnt++
  1057. }
  1058. }
  1059. }
  1060. const shardCnt = betterShortTableShardCnt
  1061. const shardSize = betterShortTableShardSize
  1062. if e.allDirty || dirtyShardCnt > shardCnt*4/6 {
  1063. copy(e.table[:], e.dictTable)
  1064. for i := range e.shortTableShardDirty {
  1065. e.shortTableShardDirty[i] = false
  1066. }
  1067. } else {
  1068. for i := range e.shortTableShardDirty {
  1069. if !e.shortTableShardDirty[i] {
  1070. continue
  1071. }
  1072. copy(e.table[i*shardSize:(i+1)*shardSize], e.dictTable[i*shardSize:(i+1)*shardSize])
  1073. e.shortTableShardDirty[i] = false
  1074. }
  1075. }
  1076. }
  1077. {
  1078. dirtyShardCnt := 0
  1079. if !e.allDirty {
  1080. for i := range e.shortTableShardDirty {
  1081. if e.shortTableShardDirty[i] {
  1082. dirtyShardCnt++
  1083. }
  1084. }
  1085. }
  1086. const shardCnt = betterLongTableShardCnt
  1087. const shardSize = betterLongTableShardSize
  1088. if e.allDirty || dirtyShardCnt > shardCnt*4/6 {
  1089. copy(e.longTable[:], e.dictLongTable)
  1090. for i := range e.longTableShardDirty {
  1091. e.longTableShardDirty[i] = false
  1092. }
  1093. } else {
  1094. for i := range e.longTableShardDirty {
  1095. if !e.longTableShardDirty[i] {
  1096. continue
  1097. }
  1098. copy(e.longTable[i*shardSize:(i+1)*shardSize], e.dictLongTable[i*shardSize:(i+1)*shardSize])
  1099. e.longTableShardDirty[i] = false
  1100. }
  1101. }
  1102. }
  1103. e.cur = e.maxMatchOff
  1104. e.allDirty = false
  1105. }
  1106. func (e *betterFastEncoderDict) markLongShardDirty(entryNum uint32) {
  1107. e.longTableShardDirty[entryNum/betterLongTableShardSize] = true
  1108. }
  1109. func (e *betterFastEncoderDict) markShortShardDirty(entryNum uint32) {
  1110. e.shortTableShardDirty[entryNum/betterShortTableShardSize] = true
  1111. }