enc_dfast.go 30 KB

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