enc_dfast.go 30 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105
  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. dFastLongTableBits = 17 // Bits used in the long match table
  8. dFastLongTableSize = 1 << dFastLongTableBits // Size of the table
  9. dFastLongTableMask = dFastLongTableSize - 1 // Mask for table indices. Redundant, but can eliminate bounds checks.
  10. dFastLongLen = 8 // Bytes used for table hash
  11. dLongTableShardCnt = 1 << (dFastLongTableBits - dictShardBits) // Number of shards in the table
  12. dLongTableShardSize = dFastLongTableSize / dLongTableShardCnt // Size of an individual shard
  13. dFastShortTableBits = tableBits // Bits used in the short match table
  14. dFastShortTableSize = 1 << dFastShortTableBits // Size of the table
  15. dFastShortTableMask = dFastShortTableSize - 1 // Mask for table indices. Redundant, but can eliminate bounds checks.
  16. dFastShortLen = 5 // Bytes used for table hash
  17. )
  18. type doubleFastEncoder struct {
  19. fastEncoder
  20. longTable [dFastLongTableSize]tableEntry
  21. }
  22. type doubleFastEncoderDict struct {
  23. fastEncoderDict
  24. longTable [dFastLongTableSize]tableEntry
  25. dictLongTable []tableEntry
  26. longTableShardDirty [dLongTableShardCnt]bool
  27. }
  28. // Encode mimmics functionality in zstd_dfast.c
  29. func (e *doubleFastEncoder) Encode(blk *blockEnc, src []byte) {
  30. const (
  31. // Input margin is the number of bytes we read (8)
  32. // and the maximum we will read ahead (2)
  33. inputMargin = 8 + 2
  34. minNonLiteralBlockSize = 16
  35. )
  36. // Protect against e.cur wraparound.
  37. for e.cur >= e.bufferReset-int32(len(e.hist)) {
  38. if len(e.hist) == 0 {
  39. e.table = [dFastShortTableSize]tableEntry{}
  40. e.longTable = [dFastLongTableSize]tableEntry{}
  41. e.cur = e.maxMatchOff
  42. break
  43. }
  44. // Shift down everything in the table that isn't already too far away.
  45. minOff := e.cur + int32(len(e.hist)) - e.maxMatchOff
  46. for i := range e.table[:] {
  47. v := e.table[i].offset
  48. if v < minOff {
  49. v = 0
  50. } else {
  51. v = v - e.cur + e.maxMatchOff
  52. }
  53. e.table[i].offset = v
  54. }
  55. for i := range e.longTable[:] {
  56. v := e.longTable[i].offset
  57. if v < minOff {
  58. v = 0
  59. } else {
  60. v = v - e.cur + e.maxMatchOff
  61. }
  62. e.longTable[i].offset = v
  63. }
  64. e.cur = e.maxMatchOff
  65. break
  66. }
  67. s := e.addBlock(src)
  68. blk.size = len(src)
  69. if len(src) < minNonLiteralBlockSize {
  70. blk.extraLits = len(src)
  71. blk.literals = blk.literals[:len(src)]
  72. copy(blk.literals, src)
  73. return
  74. }
  75. // Override src
  76. src = e.hist
  77. sLimit := int32(len(src)) - inputMargin
  78. // stepSize is the number of bytes to skip on every main loop iteration.
  79. // It should be >= 1.
  80. const stepSize = 1
  81. const kSearchStrength = 8
  82. // nextEmit is where in src the next emitLiteral should start from.
  83. nextEmit := s
  84. cv := load6432(src, s)
  85. // Relative offsets
  86. offset1 := int32(blk.recentOffsets[0])
  87. offset2 := int32(blk.recentOffsets[1])
  88. addLiterals := func(s *seq, until int32) {
  89. if until == nextEmit {
  90. return
  91. }
  92. blk.literals = append(blk.literals, src[nextEmit:until]...)
  93. s.litLen = uint32(until - nextEmit)
  94. }
  95. if debugEncoder {
  96. println("recent offsets:", blk.recentOffsets)
  97. }
  98. encodeLoop:
  99. for {
  100. var t int32
  101. // We allow the encoder to optionally turn off repeat offsets across blocks
  102. canRepeat := len(blk.sequences) > 2
  103. for {
  104. if debugAsserts && canRepeat && offset1 == 0 {
  105. panic("offset0 was 0")
  106. }
  107. nextHashL := hashLen(cv, dFastLongTableBits, dFastLongLen)
  108. nextHashS := hashLen(cv, dFastShortTableBits, dFastShortLen)
  109. candidateL := e.longTable[nextHashL]
  110. candidateS := e.table[nextHashS]
  111. const repOff = 1
  112. repIndex := s - offset1 + repOff
  113. entry := tableEntry{offset: s + e.cur, val: uint32(cv)}
  114. e.longTable[nextHashL] = entry
  115. e.table[nextHashS] = entry
  116. if canRepeat {
  117. if repIndex >= 0 && load3232(src, repIndex) == uint32(cv>>(repOff*8)) {
  118. // Consider history as well.
  119. var seq seq
  120. length := 4 + e.matchlen(s+4+repOff, repIndex+4, src)
  121. seq.matchLen = uint32(length - zstdMinMatch)
  122. // We might be able to match backwards.
  123. // Extend as long as we can.
  124. start := s + repOff
  125. // We end the search early, so we don't risk 0 literals
  126. // and have to do special offset treatment.
  127. startLimit := nextEmit + 1
  128. tMin := max(s-e.maxMatchOff, 0)
  129. for repIndex > tMin && start > startLimit && src[repIndex-1] == src[start-1] && seq.matchLen < maxMatchLength-zstdMinMatch-1 {
  130. repIndex--
  131. start--
  132. seq.matchLen++
  133. }
  134. addLiterals(&seq, start)
  135. // rep 0
  136. seq.offset = 1
  137. if debugSequences {
  138. println("repeat sequence", seq, "next s:", s)
  139. }
  140. blk.sequences = append(blk.sequences, seq)
  141. s += length + repOff
  142. nextEmit = s
  143. if s >= sLimit {
  144. if debugEncoder {
  145. println("repeat ended", s, length)
  146. }
  147. break encodeLoop
  148. }
  149. cv = load6432(src, s)
  150. continue
  151. }
  152. }
  153. // Find the offsets of our two matches.
  154. coffsetL := s - (candidateL.offset - e.cur)
  155. coffsetS := s - (candidateS.offset - e.cur)
  156. // Check if we have a long match.
  157. if coffsetL < e.maxMatchOff && uint32(cv) == candidateL.val {
  158. // Found a long match, likely at least 8 bytes.
  159. // Reference encoder checks all 8 bytes, we only check 4,
  160. // but the likelihood of both the first 4 bytes and the hash matching should be enough.
  161. t = candidateL.offset - e.cur
  162. if debugAsserts && s <= t {
  163. panic(fmt.Sprintf("s (%d) <= t (%d)", s, t))
  164. }
  165. if debugAsserts && s-t > e.maxMatchOff {
  166. panic("s - t >e.maxMatchOff")
  167. }
  168. if debugMatches {
  169. println("long match")
  170. }
  171. break
  172. }
  173. // Check if we have a short match.
  174. if coffsetS < e.maxMatchOff && uint32(cv) == candidateS.val {
  175. // found a regular match
  176. // See if we can find a long match at s+1
  177. const checkAt = 1
  178. cv := load6432(src, s+checkAt)
  179. nextHashL = hashLen(cv, dFastLongTableBits, dFastLongLen)
  180. candidateL = e.longTable[nextHashL]
  181. coffsetL = s - (candidateL.offset - e.cur) + checkAt
  182. // We can store it, since we have at least a 4 byte match.
  183. e.longTable[nextHashL] = tableEntry{offset: s + checkAt + e.cur, val: uint32(cv)}
  184. if coffsetL < e.maxMatchOff && uint32(cv) == candidateL.val {
  185. // Found a long match, likely at least 8 bytes.
  186. // Reference encoder checks all 8 bytes, we only check 4,
  187. // but the likelihood of both the first 4 bytes and the hash matching should be enough.
  188. t = candidateL.offset - e.cur
  189. s += checkAt
  190. if debugMatches {
  191. println("long match (after short)")
  192. }
  193. break
  194. }
  195. t = candidateS.offset - e.cur
  196. if debugAsserts && s <= t {
  197. panic(fmt.Sprintf("s (%d) <= t (%d)", s, t))
  198. }
  199. if debugAsserts && s-t > e.maxMatchOff {
  200. panic("s - t >e.maxMatchOff")
  201. }
  202. if debugAsserts && t < 0 {
  203. panic("t<0")
  204. }
  205. if debugMatches {
  206. println("short match")
  207. }
  208. break
  209. }
  210. // No match found, move forward in input.
  211. s += stepSize + ((s - nextEmit) >> (kSearchStrength - 1))
  212. if s >= sLimit {
  213. break encodeLoop
  214. }
  215. cv = load6432(src, s)
  216. }
  217. // A 4-byte match has been found. Update recent offsets.
  218. // We'll later see if more than 4 bytes.
  219. offset2 = offset1
  220. offset1 = s - t
  221. if debugAsserts && s <= t {
  222. panic(fmt.Sprintf("s (%d) <= t (%d)", s, t))
  223. }
  224. if debugAsserts && canRepeat && int(offset1) > len(src) {
  225. panic("invalid offset")
  226. }
  227. // Extend the 4-byte match as long as possible.
  228. l := e.matchlen(s+4, t+4, src) + 4
  229. // Extend backwards
  230. tMin := max(s-e.maxMatchOff, 0)
  231. for t > tMin && s > nextEmit && src[t-1] == src[s-1] && l < maxMatchLength {
  232. s--
  233. t--
  234. l++
  235. }
  236. // Write our sequence
  237. var seq seq
  238. seq.litLen = uint32(s - nextEmit)
  239. seq.matchLen = uint32(l - zstdMinMatch)
  240. if seq.litLen > 0 {
  241. blk.literals = append(blk.literals, src[nextEmit:s]...)
  242. }
  243. seq.offset = uint32(s-t) + 3
  244. s += l
  245. if debugSequences {
  246. println("sequence", seq, "next s:", s)
  247. }
  248. blk.sequences = append(blk.sequences, seq)
  249. nextEmit = s
  250. if s >= sLimit {
  251. break encodeLoop
  252. }
  253. // Index match start+1 (long) and start+2 (short)
  254. index0 := s - l + 1
  255. // Index match end-2 (long) and end-1 (short)
  256. index1 := s - 2
  257. cv0 := load6432(src, index0)
  258. cv1 := load6432(src, index1)
  259. te0 := tableEntry{offset: index0 + e.cur, val: uint32(cv0)}
  260. te1 := tableEntry{offset: index1 + e.cur, val: uint32(cv1)}
  261. e.longTable[hashLen(cv0, dFastLongTableBits, dFastLongLen)] = te0
  262. e.longTable[hashLen(cv1, dFastLongTableBits, dFastLongLen)] = te1
  263. cv0 >>= 8
  264. cv1 >>= 8
  265. te0.offset++
  266. te1.offset++
  267. te0.val = uint32(cv0)
  268. te1.val = uint32(cv1)
  269. e.table[hashLen(cv0, dFastShortTableBits, dFastShortLen)] = te0
  270. e.table[hashLen(cv1, dFastShortTableBits, dFastShortLen)] = te1
  271. cv = load6432(src, s)
  272. if !canRepeat {
  273. continue
  274. }
  275. // Check offset 2
  276. for {
  277. o2 := s - offset2
  278. if load3232(src, o2) != uint32(cv) {
  279. // Do regular search
  280. break
  281. }
  282. // Store this, since we have it.
  283. nextHashS := hashLen(cv, dFastShortTableBits, dFastShortLen)
  284. nextHashL := hashLen(cv, dFastLongTableBits, dFastLongLen)
  285. // We have at least 4 byte match.
  286. // No need to check backwards. We come straight from a match
  287. l := 4 + e.matchlen(s+4, o2+4, src)
  288. entry := tableEntry{offset: s + e.cur, val: uint32(cv)}
  289. e.longTable[nextHashL] = entry
  290. e.table[nextHashS] = entry
  291. seq.matchLen = uint32(l) - zstdMinMatch
  292. seq.litLen = 0
  293. // Since litlen is always 0, this is offset 1.
  294. seq.offset = 1
  295. s += l
  296. nextEmit = s
  297. if debugSequences {
  298. println("sequence", seq, "next s:", s)
  299. }
  300. blk.sequences = append(blk.sequences, seq)
  301. // Swap offset 1 and 2.
  302. offset1, offset2 = offset2, offset1
  303. if s >= sLimit {
  304. // Finished
  305. break encodeLoop
  306. }
  307. cv = load6432(src, s)
  308. }
  309. }
  310. if int(nextEmit) < len(src) {
  311. blk.literals = append(blk.literals, src[nextEmit:]...)
  312. blk.extraLits = len(src) - int(nextEmit)
  313. }
  314. blk.recentOffsets[0] = uint32(offset1)
  315. blk.recentOffsets[1] = uint32(offset2)
  316. if debugEncoder {
  317. println("returning, recent offsets:", blk.recentOffsets, "extra literals:", blk.extraLits)
  318. }
  319. }
  320. // EncodeNoHist will encode a block with no history and no following blocks.
  321. // Most notable difference is that src will not be copied for history and
  322. // we do not need to check for max match length.
  323. func (e *doubleFastEncoder) EncodeNoHist(blk *blockEnc, src []byte) {
  324. const (
  325. // Input margin is the number of bytes we read (8)
  326. // and the maximum we will read ahead (2)
  327. inputMargin = 8 + 2
  328. minNonLiteralBlockSize = 16
  329. )
  330. // Protect against e.cur wraparound.
  331. if e.cur >= e.bufferReset {
  332. for i := range e.table[:] {
  333. e.table[i] = tableEntry{}
  334. }
  335. for i := range e.longTable[:] {
  336. e.longTable[i] = tableEntry{}
  337. }
  338. e.cur = e.maxMatchOff
  339. }
  340. s := int32(0)
  341. blk.size = len(src)
  342. if len(src) < minNonLiteralBlockSize {
  343. blk.extraLits = len(src)
  344. blk.literals = blk.literals[:len(src)]
  345. copy(blk.literals, src)
  346. return
  347. }
  348. // Override src
  349. sLimit := int32(len(src)) - inputMargin
  350. // stepSize is the number of bytes to skip on every main loop iteration.
  351. // It should be >= 1.
  352. const stepSize = 1
  353. const kSearchStrength = 8
  354. // nextEmit is where in src the next emitLiteral should start from.
  355. nextEmit := s
  356. cv := load6432(src, s)
  357. // Relative offsets
  358. offset1 := int32(blk.recentOffsets[0])
  359. offset2 := int32(blk.recentOffsets[1])
  360. addLiterals := func(s *seq, until int32) {
  361. if until == nextEmit {
  362. return
  363. }
  364. blk.literals = append(blk.literals, src[nextEmit:until]...)
  365. s.litLen = uint32(until - nextEmit)
  366. }
  367. if debugEncoder {
  368. println("recent offsets:", blk.recentOffsets)
  369. }
  370. encodeLoop:
  371. for {
  372. var t int32
  373. for {
  374. nextHashL := hashLen(cv, dFastLongTableBits, dFastLongLen)
  375. nextHashS := hashLen(cv, dFastShortTableBits, dFastShortLen)
  376. candidateL := e.longTable[nextHashL]
  377. candidateS := e.table[nextHashS]
  378. const repOff = 1
  379. repIndex := s - offset1 + repOff
  380. entry := tableEntry{offset: s + e.cur, val: uint32(cv)}
  381. e.longTable[nextHashL] = entry
  382. e.table[nextHashS] = entry
  383. if len(blk.sequences) > 2 {
  384. if load3232(src, repIndex) == uint32(cv>>(repOff*8)) {
  385. // Consider history as well.
  386. var seq seq
  387. //length := 4 + e.matchlen(s+4+repOff, repIndex+4, src)
  388. length := 4 + int32(matchLen(src[s+4+repOff:], src[repIndex+4:]))
  389. seq.matchLen = uint32(length - zstdMinMatch)
  390. // We might be able to match backwards.
  391. // Extend as long as we can.
  392. start := s + repOff
  393. // We end the search early, so we don't risk 0 literals
  394. // and have to do special offset treatment.
  395. startLimit := nextEmit + 1
  396. tMin := max(s-e.maxMatchOff, 0)
  397. for repIndex > tMin && start > startLimit && src[repIndex-1] == src[start-1] {
  398. repIndex--
  399. start--
  400. seq.matchLen++
  401. }
  402. addLiterals(&seq, start)
  403. // rep 0
  404. seq.offset = 1
  405. if debugSequences {
  406. println("repeat sequence", seq, "next s:", s)
  407. }
  408. blk.sequences = append(blk.sequences, seq)
  409. s += length + repOff
  410. nextEmit = s
  411. if s >= sLimit {
  412. if debugEncoder {
  413. println("repeat ended", s, length)
  414. }
  415. break encodeLoop
  416. }
  417. cv = load6432(src, s)
  418. continue
  419. }
  420. }
  421. // Find the offsets of our two matches.
  422. coffsetL := s - (candidateL.offset - e.cur)
  423. coffsetS := s - (candidateS.offset - e.cur)
  424. // Check if we have a long match.
  425. if coffsetL < e.maxMatchOff && uint32(cv) == candidateL.val {
  426. // Found a long match, likely at least 8 bytes.
  427. // Reference encoder checks all 8 bytes, we only check 4,
  428. // but the likelihood of both the first 4 bytes and the hash matching should be enough.
  429. t = candidateL.offset - e.cur
  430. if debugAsserts && s <= t {
  431. panic(fmt.Sprintf("s (%d) <= t (%d). cur: %d", s, t, e.cur))
  432. }
  433. if debugAsserts && s-t > e.maxMatchOff {
  434. panic("s - t >e.maxMatchOff")
  435. }
  436. if debugMatches {
  437. println("long match")
  438. }
  439. break
  440. }
  441. // Check if we have a short match.
  442. if coffsetS < e.maxMatchOff && uint32(cv) == candidateS.val {
  443. // found a regular match
  444. // See if we can find a long match at s+1
  445. const checkAt = 1
  446. cv := load6432(src, s+checkAt)
  447. nextHashL = hashLen(cv, dFastLongTableBits, dFastLongLen)
  448. candidateL = e.longTable[nextHashL]
  449. coffsetL = s - (candidateL.offset - e.cur) + checkAt
  450. // We can store it, since we have at least a 4 byte match.
  451. e.longTable[nextHashL] = tableEntry{offset: s + checkAt + e.cur, val: uint32(cv)}
  452. if coffsetL < e.maxMatchOff && uint32(cv) == candidateL.val {
  453. // Found a long match, likely at least 8 bytes.
  454. // Reference encoder checks all 8 bytes, we only check 4,
  455. // but the likelihood of both the first 4 bytes and the hash matching should be enough.
  456. t = candidateL.offset - e.cur
  457. s += checkAt
  458. if debugMatches {
  459. println("long match (after short)")
  460. }
  461. break
  462. }
  463. t = candidateS.offset - e.cur
  464. if debugAsserts && s <= t {
  465. panic(fmt.Sprintf("s (%d) <= t (%d)", s, t))
  466. }
  467. if debugAsserts && s-t > e.maxMatchOff {
  468. panic("s - t >e.maxMatchOff")
  469. }
  470. if debugAsserts && t < 0 {
  471. panic("t<0")
  472. }
  473. if debugMatches {
  474. println("short match")
  475. }
  476. break
  477. }
  478. // No match found, move forward in input.
  479. s += stepSize + ((s - nextEmit) >> (kSearchStrength - 1))
  480. if s >= sLimit {
  481. break encodeLoop
  482. }
  483. cv = load6432(src, s)
  484. }
  485. // A 4-byte match has been found. Update recent offsets.
  486. // We'll later see if more than 4 bytes.
  487. offset2 = offset1
  488. offset1 = s - t
  489. if debugAsserts && s <= t {
  490. panic(fmt.Sprintf("s (%d) <= t (%d)", s, t))
  491. }
  492. // Extend the 4-byte match as long as possible.
  493. //l := e.matchlen(s+4, t+4, src) + 4
  494. l := int32(matchLen(src[s+4:], src[t+4:])) + 4
  495. // Extend backwards
  496. tMin := max(s-e.maxMatchOff, 0)
  497. for t > tMin && s > nextEmit && src[t-1] == src[s-1] {
  498. s--
  499. t--
  500. l++
  501. }
  502. // Write our sequence
  503. var seq seq
  504. seq.litLen = uint32(s - nextEmit)
  505. seq.matchLen = uint32(l - zstdMinMatch)
  506. if seq.litLen > 0 {
  507. blk.literals = append(blk.literals, src[nextEmit:s]...)
  508. }
  509. seq.offset = uint32(s-t) + 3
  510. s += l
  511. if debugSequences {
  512. println("sequence", seq, "next s:", s)
  513. }
  514. blk.sequences = append(blk.sequences, seq)
  515. nextEmit = s
  516. if s >= sLimit {
  517. break encodeLoop
  518. }
  519. // Index match start+1 (long) and start+2 (short)
  520. index0 := s - l + 1
  521. // Index match end-2 (long) and end-1 (short)
  522. index1 := s - 2
  523. cv0 := load6432(src, index0)
  524. cv1 := load6432(src, index1)
  525. te0 := tableEntry{offset: index0 + e.cur, val: uint32(cv0)}
  526. te1 := tableEntry{offset: index1 + e.cur, val: uint32(cv1)}
  527. e.longTable[hashLen(cv0, dFastLongTableBits, dFastLongLen)] = te0
  528. e.longTable[hashLen(cv1, dFastLongTableBits, dFastLongLen)] = te1
  529. cv0 >>= 8
  530. cv1 >>= 8
  531. te0.offset++
  532. te1.offset++
  533. te0.val = uint32(cv0)
  534. te1.val = uint32(cv1)
  535. e.table[hashLen(cv0, dFastShortTableBits, dFastShortLen)] = te0
  536. e.table[hashLen(cv1, dFastShortTableBits, dFastShortLen)] = te1
  537. cv = load6432(src, s)
  538. if len(blk.sequences) <= 2 {
  539. continue
  540. }
  541. // Check offset 2
  542. for {
  543. o2 := s - offset2
  544. if load3232(src, o2) != uint32(cv) {
  545. // Do regular search
  546. break
  547. }
  548. // Store this, since we have it.
  549. nextHashS := hashLen(cv1>>8, dFastShortTableBits, dFastShortLen)
  550. nextHashL := hashLen(cv, dFastLongTableBits, dFastLongLen)
  551. // We have at least 4 byte match.
  552. // No need to check backwards. We come straight from a match
  553. //l := 4 + e.matchlen(s+4, o2+4, src)
  554. l := 4 + int32(matchLen(src[s+4:], src[o2+4:]))
  555. entry := tableEntry{offset: s + e.cur, val: uint32(cv)}
  556. e.longTable[nextHashL] = entry
  557. e.table[nextHashS] = entry
  558. seq.matchLen = uint32(l) - zstdMinMatch
  559. seq.litLen = 0
  560. // Since litlen is always 0, this is offset 1.
  561. seq.offset = 1
  562. s += l
  563. nextEmit = s
  564. if debugSequences {
  565. println("sequence", seq, "next s:", s)
  566. }
  567. blk.sequences = append(blk.sequences, seq)
  568. // Swap offset 1 and 2.
  569. offset1, offset2 = offset2, offset1
  570. if s >= sLimit {
  571. // Finished
  572. break encodeLoop
  573. }
  574. cv = load6432(src, s)
  575. }
  576. }
  577. if int(nextEmit) < len(src) {
  578. blk.literals = append(blk.literals, src[nextEmit:]...)
  579. blk.extraLits = len(src) - int(nextEmit)
  580. }
  581. if debugEncoder {
  582. println("returning, recent offsets:", blk.recentOffsets, "extra literals:", blk.extraLits)
  583. }
  584. // We do not store history, so we must offset e.cur to avoid false matches for next user.
  585. if e.cur < e.bufferReset {
  586. e.cur += int32(len(src))
  587. }
  588. }
  589. // Encode will encode the content, with a dictionary if initialized for it.
  590. func (e *doubleFastEncoderDict) Encode(blk *blockEnc, src []byte) {
  591. const (
  592. // Input margin is the number of bytes we read (8)
  593. // and the maximum we will read ahead (2)
  594. inputMargin = 8 + 2
  595. minNonLiteralBlockSize = 16
  596. )
  597. // Protect against e.cur wraparound.
  598. for e.cur >= e.bufferReset-int32(len(e.hist)) {
  599. if len(e.hist) == 0 {
  600. for i := range e.table[:] {
  601. e.table[i] = tableEntry{}
  602. }
  603. for i := range e.longTable[:] {
  604. e.longTable[i] = tableEntry{}
  605. }
  606. e.markAllShardsDirty()
  607. e.cur = e.maxMatchOff
  608. break
  609. }
  610. // Shift down everything in the table that isn't already too far away.
  611. minOff := e.cur + int32(len(e.hist)) - e.maxMatchOff
  612. for i := range e.table[:] {
  613. v := e.table[i].offset
  614. if v < minOff {
  615. v = 0
  616. } else {
  617. v = v - e.cur + e.maxMatchOff
  618. }
  619. e.table[i].offset = v
  620. }
  621. for i := range e.longTable[:] {
  622. v := e.longTable[i].offset
  623. if v < minOff {
  624. v = 0
  625. } else {
  626. v = v - e.cur + e.maxMatchOff
  627. }
  628. e.longTable[i].offset = v
  629. }
  630. e.markAllShardsDirty()
  631. e.cur = e.maxMatchOff
  632. break
  633. }
  634. s := e.addBlock(src)
  635. blk.size = len(src)
  636. if len(src) < minNonLiteralBlockSize {
  637. blk.extraLits = len(src)
  638. blk.literals = blk.literals[:len(src)]
  639. copy(blk.literals, src)
  640. return
  641. }
  642. // Override src
  643. src = e.hist
  644. sLimit := int32(len(src)) - inputMargin
  645. // stepSize is the number of bytes to skip on every main loop iteration.
  646. // It should be >= 1.
  647. const stepSize = 1
  648. const kSearchStrength = 8
  649. // nextEmit is where in src the next emitLiteral should start from.
  650. nextEmit := s
  651. cv := load6432(src, s)
  652. // Relative offsets
  653. offset1 := int32(blk.recentOffsets[0])
  654. offset2 := int32(blk.recentOffsets[1])
  655. addLiterals := func(s *seq, until int32) {
  656. if until == nextEmit {
  657. return
  658. }
  659. blk.literals = append(blk.literals, src[nextEmit:until]...)
  660. s.litLen = uint32(until - nextEmit)
  661. }
  662. if debugEncoder {
  663. println("recent offsets:", blk.recentOffsets)
  664. }
  665. encodeLoop:
  666. for {
  667. var t int32
  668. // We allow the encoder to optionally turn off repeat offsets across blocks
  669. canRepeat := len(blk.sequences) > 2
  670. for {
  671. if debugAsserts && canRepeat && offset1 == 0 {
  672. panic("offset0 was 0")
  673. }
  674. nextHashL := hashLen(cv, dFastLongTableBits, dFastLongLen)
  675. nextHashS := hashLen(cv, dFastShortTableBits, dFastShortLen)
  676. candidateL := e.longTable[nextHashL]
  677. candidateS := e.table[nextHashS]
  678. const repOff = 1
  679. repIndex := s - offset1 + repOff
  680. entry := tableEntry{offset: s + e.cur, val: uint32(cv)}
  681. e.longTable[nextHashL] = entry
  682. e.markLongShardDirty(nextHashL)
  683. e.table[nextHashS] = entry
  684. e.markShardDirty(nextHashS)
  685. if canRepeat {
  686. if repIndex >= 0 && load3232(src, repIndex) == uint32(cv>>(repOff*8)) {
  687. // Consider history as well.
  688. var seq seq
  689. length := 4 + e.matchlen(s+4+repOff, repIndex+4, src)
  690. seq.matchLen = uint32(length - zstdMinMatch)
  691. // We might be able to match backwards.
  692. // Extend as long as we can.
  693. start := s + repOff
  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 := max(s-e.maxMatchOff, 0)
  698. for repIndex > tMin && start > startLimit && src[repIndex-1] == src[start-1] && seq.matchLen < maxMatchLength-zstdMinMatch-1 {
  699. repIndex--
  700. start--
  701. seq.matchLen++
  702. }
  703. addLiterals(&seq, start)
  704. // rep 0
  705. seq.offset = 1
  706. if debugSequences {
  707. println("repeat sequence", seq, "next s:", s)
  708. }
  709. blk.sequences = append(blk.sequences, seq)
  710. s += length + repOff
  711. nextEmit = s
  712. if s >= sLimit {
  713. if debugEncoder {
  714. println("repeat ended", s, length)
  715. }
  716. break encodeLoop
  717. }
  718. cv = load6432(src, s)
  719. continue
  720. }
  721. }
  722. // Find the offsets of our two matches.
  723. coffsetL := s - (candidateL.offset - e.cur)
  724. coffsetS := s - (candidateS.offset - e.cur)
  725. // Check if we have a long match.
  726. if coffsetL < e.maxMatchOff && uint32(cv) == candidateL.val {
  727. // Found a long match, likely at least 8 bytes.
  728. // Reference encoder checks all 8 bytes, we only check 4,
  729. // but the likelihood of both the first 4 bytes and the hash matching should be enough.
  730. t = candidateL.offset - e.cur
  731. if debugAsserts && s <= t {
  732. panic(fmt.Sprintf("s (%d) <= t (%d)", s, t))
  733. }
  734. if debugAsserts && s-t > e.maxMatchOff {
  735. panic("s - t >e.maxMatchOff")
  736. }
  737. if debugMatches {
  738. println("long match")
  739. }
  740. break
  741. }
  742. // Check if we have a short match.
  743. if coffsetS < e.maxMatchOff && uint32(cv) == candidateS.val {
  744. // found a regular match
  745. // See if we can find a long match at s+1
  746. const checkAt = 1
  747. cv := load6432(src, s+checkAt)
  748. nextHashL = hashLen(cv, dFastLongTableBits, dFastLongLen)
  749. candidateL = e.longTable[nextHashL]
  750. coffsetL = s - (candidateL.offset - e.cur) + checkAt
  751. // We can store it, since we have at least a 4 byte match.
  752. e.longTable[nextHashL] = tableEntry{offset: s + checkAt + e.cur, val: uint32(cv)}
  753. e.markLongShardDirty(nextHashL)
  754. if coffsetL < e.maxMatchOff && uint32(cv) == candidateL.val {
  755. // Found a long match, likely at least 8 bytes.
  756. // Reference encoder checks all 8 bytes, we only check 4,
  757. // but the likelihood of both the first 4 bytes and the hash matching should be enough.
  758. t = candidateL.offset - e.cur
  759. s += checkAt
  760. if debugMatches {
  761. println("long match (after short)")
  762. }
  763. break
  764. }
  765. t = candidateS.offset - e.cur
  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 debugAsserts && t < 0 {
  773. panic("t<0")
  774. }
  775. if debugMatches {
  776. println("short match")
  777. }
  778. break
  779. }
  780. // No match found, move forward in input.
  781. s += stepSize + ((s - nextEmit) >> (kSearchStrength - 1))
  782. if s >= sLimit {
  783. break encodeLoop
  784. }
  785. cv = load6432(src, s)
  786. }
  787. // A 4-byte match has been found. Update recent offsets.
  788. // We'll later see if more than 4 bytes.
  789. offset2 = offset1
  790. offset1 = s - t
  791. if debugAsserts && s <= t {
  792. panic(fmt.Sprintf("s (%d) <= t (%d)", s, t))
  793. }
  794. if debugAsserts && canRepeat && int(offset1) > len(src) {
  795. panic("invalid offset")
  796. }
  797. // Extend the 4-byte match as long as possible.
  798. l := e.matchlen(s+4, t+4, src) + 4
  799. // Extend backwards
  800. tMin := max(s-e.maxMatchOff, 0)
  801. for t > tMin && s > nextEmit && src[t-1] == src[s-1] && l < maxMatchLength {
  802. s--
  803. t--
  804. l++
  805. }
  806. // Write our sequence
  807. var seq seq
  808. seq.litLen = uint32(s - nextEmit)
  809. seq.matchLen = uint32(l - zstdMinMatch)
  810. if seq.litLen > 0 {
  811. blk.literals = append(blk.literals, src[nextEmit:s]...)
  812. }
  813. seq.offset = uint32(s-t) + 3
  814. s += l
  815. if debugSequences {
  816. println("sequence", seq, "next s:", s)
  817. }
  818. blk.sequences = append(blk.sequences, seq)
  819. nextEmit = s
  820. if s >= sLimit {
  821. break encodeLoop
  822. }
  823. // Index match start+1 (long) and start+2 (short)
  824. index0 := s - l + 1
  825. // Index match end-2 (long) and end-1 (short)
  826. index1 := s - 2
  827. cv0 := load6432(src, index0)
  828. cv1 := load6432(src, index1)
  829. te0 := tableEntry{offset: index0 + e.cur, val: uint32(cv0)}
  830. te1 := tableEntry{offset: index1 + e.cur, val: uint32(cv1)}
  831. longHash1 := hashLen(cv0, dFastLongTableBits, dFastLongLen)
  832. longHash2 := hashLen(cv1, dFastLongTableBits, dFastLongLen)
  833. e.longTable[longHash1] = te0
  834. e.longTable[longHash2] = te1
  835. e.markLongShardDirty(longHash1)
  836. e.markLongShardDirty(longHash2)
  837. cv0 >>= 8
  838. cv1 >>= 8
  839. te0.offset++
  840. te1.offset++
  841. te0.val = uint32(cv0)
  842. te1.val = uint32(cv1)
  843. hashVal1 := hashLen(cv0, dFastShortTableBits, dFastShortLen)
  844. hashVal2 := hashLen(cv1, dFastShortTableBits, dFastShortLen)
  845. e.table[hashVal1] = te0
  846. e.markShardDirty(hashVal1)
  847. e.table[hashVal2] = te1
  848. e.markShardDirty(hashVal2)
  849. cv = load6432(src, s)
  850. if !canRepeat {
  851. continue
  852. }
  853. // Check offset 2
  854. for {
  855. o2 := s - offset2
  856. if load3232(src, o2) != uint32(cv) {
  857. // Do regular search
  858. break
  859. }
  860. // Store this, since we have it.
  861. nextHashL := hashLen(cv, dFastLongTableBits, dFastLongLen)
  862. nextHashS := hashLen(cv, dFastShortTableBits, dFastShortLen)
  863. // We have at least 4 byte match.
  864. // No need to check backwards. We come straight from a match
  865. l := 4 + e.matchlen(s+4, o2+4, src)
  866. entry := tableEntry{offset: s + e.cur, val: uint32(cv)}
  867. e.longTable[nextHashL] = entry
  868. e.markLongShardDirty(nextHashL)
  869. e.table[nextHashS] = entry
  870. e.markShardDirty(nextHashS)
  871. seq.matchLen = uint32(l) - zstdMinMatch
  872. seq.litLen = 0
  873. // Since litlen is always 0, this is offset 1.
  874. seq.offset = 1
  875. s += l
  876. nextEmit = s
  877. if debugSequences {
  878. println("sequence", seq, "next s:", s)
  879. }
  880. blk.sequences = append(blk.sequences, seq)
  881. // Swap offset 1 and 2.
  882. offset1, offset2 = offset2, offset1
  883. if s >= sLimit {
  884. // Finished
  885. break encodeLoop
  886. }
  887. cv = load6432(src, s)
  888. }
  889. }
  890. if int(nextEmit) < len(src) {
  891. blk.literals = append(blk.literals, src[nextEmit:]...)
  892. blk.extraLits = len(src) - int(nextEmit)
  893. }
  894. blk.recentOffsets[0] = uint32(offset1)
  895. blk.recentOffsets[1] = uint32(offset2)
  896. if debugEncoder {
  897. println("returning, recent offsets:", blk.recentOffsets, "extra literals:", blk.extraLits)
  898. }
  899. // If we encoded more than 64K mark all dirty.
  900. if len(src) > 64<<10 {
  901. e.markAllShardsDirty()
  902. }
  903. }
  904. // ResetDict will reset and set a dictionary if not nil
  905. func (e *doubleFastEncoder) Reset(d *dict, singleBlock bool) {
  906. e.fastEncoder.Reset(d, singleBlock)
  907. if d != nil {
  908. panic("doubleFastEncoder: Reset with dict not supported")
  909. }
  910. }
  911. // ResetDict will reset and set a dictionary if not nil
  912. func (e *doubleFastEncoderDict) Reset(d *dict, singleBlock bool) {
  913. allDirty := e.allDirty
  914. e.fastEncoderDict.Reset(d, singleBlock)
  915. if d == nil {
  916. return
  917. }
  918. // Init or copy dict table
  919. if len(e.dictLongTable) != len(e.longTable) || d.id != e.lastDictID {
  920. if len(e.dictLongTable) != len(e.longTable) {
  921. e.dictLongTable = make([]tableEntry, len(e.longTable))
  922. }
  923. if len(d.content) >= 8 {
  924. cv := load6432(d.content, 0)
  925. e.dictLongTable[hashLen(cv, dFastLongTableBits, dFastLongLen)] = tableEntry{
  926. val: uint32(cv),
  927. offset: e.maxMatchOff,
  928. }
  929. end := int32(len(d.content)) - 8 + e.maxMatchOff
  930. for i := e.maxMatchOff + 1; i < end; i++ {
  931. cv = cv>>8 | (uint64(d.content[i-e.maxMatchOff+7]) << 56)
  932. e.dictLongTable[hashLen(cv, dFastLongTableBits, dFastLongLen)] = tableEntry{
  933. val: uint32(cv),
  934. offset: i,
  935. }
  936. }
  937. }
  938. e.lastDictID = d.id
  939. allDirty = true
  940. }
  941. // Reset table to initial state
  942. e.cur = e.maxMatchOff
  943. dirtyShardCnt := 0
  944. if !allDirty {
  945. for i := range e.longTableShardDirty {
  946. if e.longTableShardDirty[i] {
  947. dirtyShardCnt++
  948. }
  949. }
  950. }
  951. if allDirty || dirtyShardCnt > dLongTableShardCnt/2 {
  952. //copy(e.longTable[:], e.dictLongTable)
  953. e.longTable = *(*[dFastLongTableSize]tableEntry)(e.dictLongTable)
  954. for i := range e.longTableShardDirty {
  955. e.longTableShardDirty[i] = false
  956. }
  957. return
  958. }
  959. for i := range e.longTableShardDirty {
  960. if !e.longTableShardDirty[i] {
  961. continue
  962. }
  963. // copy(e.longTable[i*dLongTableShardSize:(i+1)*dLongTableShardSize], e.dictLongTable[i*dLongTableShardSize:(i+1)*dLongTableShardSize])
  964. *(*[dLongTableShardSize]tableEntry)(e.longTable[i*dLongTableShardSize:]) = *(*[dLongTableShardSize]tableEntry)(e.dictLongTable[i*dLongTableShardSize:])
  965. e.longTableShardDirty[i] = false
  966. }
  967. }
  968. func (e *doubleFastEncoderDict) markLongShardDirty(entryNum uint32) {
  969. e.longTableShardDirty[entryNum/dLongTableShardSize] = true
  970. }