enc_better.go 34 KB

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