enc_dfast.go 30 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107
  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. dictChanged := d != e.lastDict
  915. e.fastEncoderDict.Reset(d, singleBlock)
  916. if d == nil {
  917. return
  918. }
  919. // Init or copy dict table
  920. if len(e.dictLongTable) != len(e.longTable) || dictChanged {
  921. if len(e.dictLongTable) != len(e.longTable) {
  922. e.dictLongTable = make([]tableEntry, len(e.longTable))
  923. } else {
  924. clear(e.dictLongTable)
  925. }
  926. if len(d.content) >= 8 {
  927. cv := load6432(d.content, 0)
  928. e.dictLongTable[hashLen(cv, dFastLongTableBits, dFastLongLen)] = tableEntry{
  929. val: uint32(cv),
  930. offset: e.maxMatchOff,
  931. }
  932. end := int32(len(d.content)) - 8 + e.maxMatchOff
  933. for i := e.maxMatchOff + 1; i < end; i++ {
  934. cv = cv>>8 | (uint64(d.content[i-e.maxMatchOff+7]) << 56)
  935. e.dictLongTable[hashLen(cv, dFastLongTableBits, dFastLongLen)] = tableEntry{
  936. val: uint32(cv),
  937. offset: i,
  938. }
  939. }
  940. }
  941. allDirty = true
  942. }
  943. // Reset table to initial state
  944. e.cur = e.maxMatchOff
  945. dirtyShardCnt := 0
  946. if !allDirty {
  947. for i := range e.longTableShardDirty {
  948. if e.longTableShardDirty[i] {
  949. dirtyShardCnt++
  950. }
  951. }
  952. }
  953. if allDirty || dirtyShardCnt > dLongTableShardCnt/2 {
  954. //copy(e.longTable[:], e.dictLongTable)
  955. e.longTable = *(*[dFastLongTableSize]tableEntry)(e.dictLongTable)
  956. for i := range e.longTableShardDirty {
  957. e.longTableShardDirty[i] = false
  958. }
  959. return
  960. }
  961. for i := range e.longTableShardDirty {
  962. if !e.longTableShardDirty[i] {
  963. continue
  964. }
  965. // copy(e.longTable[i*dLongTableShardSize:(i+1)*dLongTableShardSize], e.dictLongTable[i*dLongTableShardSize:(i+1)*dLongTableShardSize])
  966. *(*[dLongTableShardSize]tableEntry)(e.longTable[i*dLongTableShardSize:]) = *(*[dLongTableShardSize]tableEntry)(e.dictLongTable[i*dLongTableShardSize:])
  967. e.longTableShardDirty[i] = false
  968. }
  969. }
  970. func (e *doubleFastEncoderDict) markLongShardDirty(entryNum uint32) {
  971. e.longTableShardDirty[entryNum/dLongTableShardSize] = true
  972. }