enc_better.go 34 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234
  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. // Init or copy dict table
  987. if len(e.dictTable) != len(e.table) || d.id != e.lastDictID {
  988. if len(e.dictTable) != len(e.table) {
  989. e.dictTable = make([]tableEntry, len(e.table))
  990. }
  991. end := int32(len(d.content)) - 8 + e.maxMatchOff
  992. for i := e.maxMatchOff; i < end; i += 4 {
  993. const hashLog = betterShortTableBits
  994. cv := load6432(d.content, i-e.maxMatchOff)
  995. nextHash := hashLen(cv, hashLog, betterShortLen) // 0 -> 4
  996. nextHash1 := hashLen(cv>>8, hashLog, betterShortLen) // 1 -> 5
  997. nextHash2 := hashLen(cv>>16, hashLog, betterShortLen) // 2 -> 6
  998. nextHash3 := hashLen(cv>>24, hashLog, betterShortLen) // 3 -> 7
  999. e.dictTable[nextHash] = tableEntry{
  1000. val: uint32(cv),
  1001. offset: i,
  1002. }
  1003. e.dictTable[nextHash1] = tableEntry{
  1004. val: uint32(cv >> 8),
  1005. offset: i + 1,
  1006. }
  1007. e.dictTable[nextHash2] = tableEntry{
  1008. val: uint32(cv >> 16),
  1009. offset: i + 2,
  1010. }
  1011. e.dictTable[nextHash3] = tableEntry{
  1012. val: uint32(cv >> 24),
  1013. offset: i + 3,
  1014. }
  1015. }
  1016. e.lastDictID = d.id
  1017. e.allDirty = true
  1018. }
  1019. // Init or copy dict table
  1020. if len(e.dictLongTable) != len(e.longTable) || d.id != e.lastDictID {
  1021. if len(e.dictLongTable) != len(e.longTable) {
  1022. e.dictLongTable = make([]prevEntry, len(e.longTable))
  1023. }
  1024. if len(d.content) >= 8 {
  1025. cv := load6432(d.content, 0)
  1026. h := hashLen(cv, betterLongTableBits, betterLongLen)
  1027. e.dictLongTable[h] = prevEntry{
  1028. offset: e.maxMatchOff,
  1029. prev: e.dictLongTable[h].offset,
  1030. }
  1031. end := int32(len(d.content)) - 8 + e.maxMatchOff
  1032. off := 8 // First to read
  1033. for i := e.maxMatchOff + 1; i < end; i++ {
  1034. cv = cv>>8 | (uint64(d.content[off]) << 56)
  1035. h := hashLen(cv, betterLongTableBits, betterLongLen)
  1036. e.dictLongTable[h] = prevEntry{
  1037. offset: i,
  1038. prev: e.dictLongTable[h].offset,
  1039. }
  1040. off++
  1041. }
  1042. }
  1043. e.lastDictID = d.id
  1044. e.allDirty = true
  1045. }
  1046. // Reset table to initial state
  1047. {
  1048. dirtyShardCnt := 0
  1049. if !e.allDirty {
  1050. for i := range e.shortTableShardDirty {
  1051. if e.shortTableShardDirty[i] {
  1052. dirtyShardCnt++
  1053. }
  1054. }
  1055. }
  1056. const shardCnt = betterShortTableShardCnt
  1057. const shardSize = betterShortTableShardSize
  1058. if e.allDirty || dirtyShardCnt > shardCnt*4/6 {
  1059. copy(e.table[:], e.dictTable)
  1060. for i := range e.shortTableShardDirty {
  1061. e.shortTableShardDirty[i] = false
  1062. }
  1063. } else {
  1064. for i := range e.shortTableShardDirty {
  1065. if !e.shortTableShardDirty[i] {
  1066. continue
  1067. }
  1068. copy(e.table[i*shardSize:(i+1)*shardSize], e.dictTable[i*shardSize:(i+1)*shardSize])
  1069. e.shortTableShardDirty[i] = false
  1070. }
  1071. }
  1072. }
  1073. {
  1074. dirtyShardCnt := 0
  1075. if !e.allDirty {
  1076. for i := range e.shortTableShardDirty {
  1077. if e.shortTableShardDirty[i] {
  1078. dirtyShardCnt++
  1079. }
  1080. }
  1081. }
  1082. const shardCnt = betterLongTableShardCnt
  1083. const shardSize = betterLongTableShardSize
  1084. if e.allDirty || dirtyShardCnt > shardCnt*4/6 {
  1085. copy(e.longTable[:], e.dictLongTable)
  1086. for i := range e.longTableShardDirty {
  1087. e.longTableShardDirty[i] = false
  1088. }
  1089. } else {
  1090. for i := range e.longTableShardDirty {
  1091. if !e.longTableShardDirty[i] {
  1092. continue
  1093. }
  1094. copy(e.longTable[i*shardSize:(i+1)*shardSize], e.dictLongTable[i*shardSize:(i+1)*shardSize])
  1095. e.longTableShardDirty[i] = false
  1096. }
  1097. }
  1098. }
  1099. e.cur = e.maxMatchOff
  1100. e.allDirty = false
  1101. }
  1102. func (e *betterFastEncoderDict) markLongShardDirty(entryNum uint32) {
  1103. e.longTableShardDirty[entryNum/betterLongTableShardSize] = true
  1104. }
  1105. func (e *betterFastEncoderDict) markShortShardDirty(entryNum uint32) {
  1106. e.shortTableShardDirty[entryNum/betterShortTableShardSize] = true
  1107. }