enc_dfast.go 30 KB

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