enc_better.go 34 KB

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