encode_best.go 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797
  1. // Copyright 2016 The Snappy-Go Authors. All rights reserved.
  2. // Copyright (c) 2019 Klaus Post. All rights reserved.
  3. // Use of this source code is governed by a BSD-style
  4. // license that can be found in the LICENSE file.
  5. package s2
  6. import (
  7. "fmt"
  8. "math"
  9. "math/bits"
  10. )
  11. // encodeBlockBest encodes a non-empty src to a guaranteed-large-enough dst. It
  12. // assumes that the varint-encoded length of the decompressed bytes has already
  13. // been written.
  14. //
  15. // It also assumes that:
  16. //
  17. // len(dst) >= MaxEncodedLen(len(src)) &&
  18. // minNonLiteralBlockSize <= len(src) && len(src) <= maxBlockSize
  19. func encodeBlockBest(dst, src []byte, dict *Dict) (d int) {
  20. // Initialize the hash tables.
  21. const (
  22. // Long hash matches.
  23. lTableBits = bestLongTableBits
  24. maxLTableSize = bestLongTableSize
  25. // Short hash matches.
  26. sTableBits = bestShortTableBits
  27. maxSTableSize = bestShortTableSize
  28. inputMargin = 8 + 2
  29. debug = false
  30. )
  31. // sLimit is when to stop looking for offset/length copies. The inputMargin
  32. // lets us use a fast path for emitLiteral in the main loop, while we are
  33. // looking for copies.
  34. sLimit := len(src) - inputMargin
  35. if len(src) < minNonLiteralBlockSize {
  36. return 0
  37. }
  38. sLimitDict := min(len(src)-inputMargin, MaxDictSrcOffset-inputMargin)
  39. tbl := getBestTables()
  40. lTable := &tbl.lTable
  41. sTable := &tbl.sTable
  42. defer bestTablePool.Put(tbl)
  43. // Bail if we can't compress to at least this.
  44. dstLimit := len(src) - 5
  45. // nextEmit is where in src the next emitLiteral should start from.
  46. nextEmit := 0
  47. // The encoded form must start with a literal, as there are no previous
  48. // bytes to copy, so we start looking for hash matches at s == 1.
  49. s := 1
  50. repeat := 1
  51. if dict != nil {
  52. dict.initBest()
  53. s = 0
  54. repeat = len(dict.dict) - dict.repeat
  55. }
  56. cv := load64(src, s)
  57. // We search for a repeat at -1, but don't output repeats when nextEmit == 0
  58. const lowbitMask = 0xffffffff
  59. getCur := func(x uint64) int {
  60. return int(x & lowbitMask)
  61. }
  62. getPrev := func(x uint64) int {
  63. return int(x >> 32)
  64. }
  65. const maxSkip = 64
  66. for {
  67. type match struct {
  68. offset int
  69. s int
  70. length int
  71. score int
  72. rep, dict bool
  73. }
  74. var best match
  75. for {
  76. // Next src position to check
  77. nextS := (s-nextEmit)>>8 + 1
  78. if nextS > maxSkip {
  79. nextS = s + maxSkip
  80. } else {
  81. nextS += s
  82. }
  83. if nextS > sLimit {
  84. goto emitRemainder
  85. }
  86. if dict != nil && s >= MaxDictSrcOffset {
  87. dict = nil
  88. if repeat > s {
  89. repeat = math.MinInt32
  90. }
  91. }
  92. hashL := hash8(cv, lTableBits)
  93. hashS := hash4(cv, sTableBits)
  94. candidateL := lTable[hashL]
  95. candidateS := sTable[hashS]
  96. score := func(m match) int {
  97. // Matches that are longer forward are penalized since we must emit it as a literal.
  98. score := m.length - m.s
  99. if nextEmit == m.s {
  100. // If we do not have to emit literals, we save 1 byte
  101. score++
  102. }
  103. offset := m.s - m.offset
  104. if m.rep {
  105. return score - emitRepeatSize(offset, m.length)
  106. }
  107. return score - emitCopySize(offset, m.length)
  108. }
  109. matchAt := func(offset, s int, first uint32, rep bool) match {
  110. if best.length != 0 && best.s-best.offset == s-offset {
  111. // Don't retest if we have the same offset.
  112. return match{offset: offset, s: s}
  113. }
  114. if load32(src, offset) != first {
  115. return match{offset: offset, s: s}
  116. }
  117. m := match{offset: offset, s: s, length: 4 + offset, rep: rep}
  118. s += 4
  119. for s < len(src) {
  120. if len(src)-s < 8 {
  121. if src[s] == src[m.length] {
  122. m.length++
  123. s++
  124. continue
  125. }
  126. break
  127. }
  128. if diff := load64(src, s) ^ load64(src, m.length); diff != 0 {
  129. m.length += bits.TrailingZeros64(diff) >> 3
  130. break
  131. }
  132. s += 8
  133. m.length += 8
  134. }
  135. m.length -= offset
  136. m.score = score(m)
  137. if m.score <= -m.s {
  138. // Eliminate if no savings, we might find a better one.
  139. m.length = 0
  140. }
  141. return m
  142. }
  143. matchDict := func(candidate, s int, first uint32, rep bool) match {
  144. if s >= MaxDictSrcOffset {
  145. return match{offset: candidate, s: s}
  146. }
  147. // Calculate offset as if in continuous array with s
  148. offset := -len(dict.dict) + candidate
  149. if best.length != 0 && best.s-best.offset == s-offset && !rep {
  150. // Don't retest if we have the same offset.
  151. return match{offset: offset, s: s}
  152. }
  153. if load32(dict.dict, candidate) != first {
  154. return match{offset: offset, s: s}
  155. }
  156. m := match{offset: offset, s: s, length: 4 + candidate, rep: rep, dict: true}
  157. s += 4
  158. if !rep {
  159. for s < sLimitDict && m.length < len(dict.dict) {
  160. if len(src)-s < 8 || len(dict.dict)-m.length < 8 {
  161. if src[s] == dict.dict[m.length] {
  162. m.length++
  163. s++
  164. continue
  165. }
  166. break
  167. }
  168. if diff := load64(src, s) ^ load64(dict.dict, m.length); diff != 0 {
  169. m.length += bits.TrailingZeros64(diff) >> 3
  170. break
  171. }
  172. s += 8
  173. m.length += 8
  174. }
  175. } else {
  176. for s < len(src) && m.length < len(dict.dict) {
  177. if len(src)-s < 8 || len(dict.dict)-m.length < 8 {
  178. if src[s] == dict.dict[m.length] {
  179. m.length++
  180. s++
  181. continue
  182. }
  183. break
  184. }
  185. if diff := load64(src, s) ^ load64(dict.dict, m.length); diff != 0 {
  186. m.length += bits.TrailingZeros64(diff) >> 3
  187. break
  188. }
  189. s += 8
  190. m.length += 8
  191. }
  192. }
  193. m.length -= candidate
  194. m.score = score(m)
  195. if m.score <= -m.s {
  196. // Eliminate if no savings, we might find a better one.
  197. m.length = 0
  198. }
  199. return m
  200. }
  201. bestOf := func(a, b match) match {
  202. if b.length == 0 {
  203. return a
  204. }
  205. if a.length == 0 {
  206. return b
  207. }
  208. as := a.score + b.s
  209. bs := b.score + a.s
  210. if as >= bs {
  211. return a
  212. }
  213. return b
  214. }
  215. if s > 0 {
  216. best = bestOf(matchAt(getCur(candidateL), s, uint32(cv), false), matchAt(getPrev(candidateL), s, uint32(cv), false))
  217. best = bestOf(best, matchAt(getCur(candidateS), s, uint32(cv), false))
  218. best = bestOf(best, matchAt(getPrev(candidateS), s, uint32(cv), false))
  219. }
  220. if dict != nil {
  221. candidateL := dict.bestTableLong[hashL]
  222. candidateS := dict.bestTableShort[hashS]
  223. best = bestOf(best, matchDict(int(candidateL&0xffff), s, uint32(cv), false))
  224. best = bestOf(best, matchDict(int(candidateL>>16), s, uint32(cv), false))
  225. best = bestOf(best, matchDict(int(candidateS&0xffff), s, uint32(cv), false))
  226. best = bestOf(best, matchDict(int(candidateS>>16), s, uint32(cv), false))
  227. }
  228. {
  229. if (dict == nil || repeat <= s) && repeat > 0 {
  230. best = bestOf(best, matchAt(s-repeat+1, s+1, uint32(cv>>8), true))
  231. } else if s-repeat < -4 && dict != nil {
  232. candidate := len(dict.dict) - (repeat - s)
  233. best = bestOf(best, matchDict(candidate, s, uint32(cv), true))
  234. candidate++
  235. best = bestOf(best, matchDict(candidate, s+1, uint32(cv>>8), true))
  236. }
  237. if best.length > 0 {
  238. hashS := hash4(cv>>8, sTableBits)
  239. // s+1
  240. nextShort := sTable[hashS]
  241. s := s + 1
  242. cv := load64(src, s)
  243. hashL := hash8(cv, lTableBits)
  244. nextLong := lTable[hashL]
  245. best = bestOf(best, matchAt(getCur(nextShort), s, uint32(cv), false))
  246. best = bestOf(best, matchAt(getPrev(nextShort), s, uint32(cv), false))
  247. best = bestOf(best, matchAt(getCur(nextLong), s, uint32(cv), false))
  248. best = bestOf(best, matchAt(getPrev(nextLong), s, uint32(cv), false))
  249. // Dict at + 1
  250. if dict != nil {
  251. candidateL := dict.bestTableLong[hashL]
  252. candidateS := dict.bestTableShort[hashS]
  253. best = bestOf(best, matchDict(int(candidateL&0xffff), s, uint32(cv), false))
  254. best = bestOf(best, matchDict(int(candidateS&0xffff), s, uint32(cv), false))
  255. }
  256. // s+2
  257. if true {
  258. hashS := hash4(cv>>8, sTableBits)
  259. nextShort = sTable[hashS]
  260. s++
  261. cv = load64(src, s)
  262. hashL := hash8(cv, lTableBits)
  263. nextLong = lTable[hashL]
  264. if (dict == nil || repeat <= s) && repeat > 0 {
  265. // Repeat at + 2
  266. best = bestOf(best, matchAt(s-repeat, s, uint32(cv), true))
  267. } else if repeat-s > 4 && dict != nil {
  268. candidate := len(dict.dict) - (repeat - s)
  269. best = bestOf(best, matchDict(candidate, s, uint32(cv), true))
  270. }
  271. best = bestOf(best, matchAt(getCur(nextShort), s, uint32(cv), false))
  272. best = bestOf(best, matchAt(getPrev(nextShort), s, uint32(cv), false))
  273. best = bestOf(best, matchAt(getCur(nextLong), s, uint32(cv), false))
  274. best = bestOf(best, matchAt(getPrev(nextLong), s, uint32(cv), false))
  275. // Dict at +2
  276. // Very small gain
  277. if dict != nil {
  278. candidateL := dict.bestTableLong[hashL]
  279. candidateS := dict.bestTableShort[hashS]
  280. best = bestOf(best, matchDict(int(candidateL&0xffff), s, uint32(cv), false))
  281. best = bestOf(best, matchDict(int(candidateS&0xffff), s, uint32(cv), false))
  282. }
  283. }
  284. // Search for a match at best match end, see if that is better.
  285. // Allow some bytes at the beginning to mismatch.
  286. // Sweet spot is around 1-2 bytes, but depends on input.
  287. // The skipped bytes are tested in Extend backwards,
  288. // and still picked up as part of the match if they do.
  289. const skipBeginning = 2
  290. const skipEnd = 1
  291. if sAt := best.s + best.length - skipEnd; sAt < sLimit {
  292. sBack := best.s + skipBeginning - skipEnd
  293. backL := best.length - skipBeginning
  294. // Load initial values
  295. cv = load64(src, sBack)
  296. // Grab candidates...
  297. next := lTable[hash8(load64(src, sAt), lTableBits)]
  298. if checkAt := getCur(next) - backL; checkAt > 0 {
  299. best = bestOf(best, matchAt(checkAt, sBack, uint32(cv), false))
  300. }
  301. if checkAt := getPrev(next) - backL; checkAt > 0 {
  302. best = bestOf(best, matchAt(checkAt, sBack, uint32(cv), false))
  303. }
  304. // Disabled: Extremely small gain
  305. if false {
  306. next = sTable[hash4(load64(src, sAt), sTableBits)]
  307. if checkAt := getCur(next) - backL; checkAt > 0 {
  308. best = bestOf(best, matchAt(checkAt, sBack, uint32(cv), false))
  309. }
  310. if checkAt := getPrev(next) - backL; checkAt > 0 {
  311. best = bestOf(best, matchAt(checkAt, sBack, uint32(cv), false))
  312. }
  313. }
  314. }
  315. }
  316. }
  317. // Update table
  318. lTable[hashL] = uint64(s) | candidateL<<32
  319. sTable[hashS] = uint64(s) | candidateS<<32
  320. if best.length > 0 {
  321. break
  322. }
  323. cv = load64(src, nextS)
  324. s = nextS
  325. }
  326. // Extend backwards, not needed for repeats...
  327. s = best.s
  328. if !best.rep && !best.dict {
  329. for best.offset > 0 && s > nextEmit && src[best.offset-1] == src[s-1] {
  330. best.offset--
  331. best.length++
  332. s--
  333. }
  334. }
  335. if false && best.offset >= s {
  336. panic(fmt.Errorf("t %d >= s %d", best.offset, s))
  337. }
  338. // Bail if we exceed the maximum size.
  339. if d+(s-nextEmit) > dstLimit {
  340. return 0
  341. }
  342. base := s
  343. offset := s - best.offset
  344. s += best.length
  345. if offset > 65535 && s-base <= 5 && !best.rep {
  346. // Bail if the match is equal or worse to the encoding.
  347. s = best.s + 1
  348. if s >= sLimit {
  349. goto emitRemainder
  350. }
  351. cv = load64(src, s)
  352. continue
  353. }
  354. if debug && nextEmit != base {
  355. fmt.Println("EMIT", base-nextEmit, "literals. base-after:", base)
  356. }
  357. d += emitLiteral(dst[d:], src[nextEmit:base])
  358. if best.rep {
  359. if nextEmit > 0 || best.dict {
  360. if debug {
  361. fmt.Println("REPEAT, length", best.length, "offset:", offset, "s-after:", s, "dict:", best.dict, "best:", best)
  362. }
  363. // same as `add := emitCopy(dst[d:], repeat, s-base)` but skips storing offset.
  364. d += emitRepeat(dst[d:], offset, best.length)
  365. } else {
  366. // First match without dict cannot be a repeat.
  367. if debug {
  368. fmt.Println("COPY, length", best.length, "offset:", offset, "s-after:", s, "dict:", best.dict, "best:", best)
  369. }
  370. d += emitCopy(dst[d:], offset, best.length)
  371. }
  372. } else {
  373. if debug {
  374. fmt.Println("COPY, length", best.length, "offset:", offset, "s-after:", s, "dict:", best.dict, "best:", best)
  375. }
  376. d += emitCopy(dst[d:], offset, best.length)
  377. }
  378. repeat = offset
  379. nextEmit = s
  380. if s >= sLimit {
  381. goto emitRemainder
  382. }
  383. if d > dstLimit {
  384. // Do we have space for more, if not bail.
  385. return 0
  386. }
  387. // Fill tables...
  388. for i := best.s + 1; i < s; i++ {
  389. cv0 := load64(src, i)
  390. long0 := hash8(cv0, lTableBits)
  391. short0 := hash4(cv0, sTableBits)
  392. lTable[long0] = uint64(i) | lTable[long0]<<32
  393. sTable[short0] = uint64(i) | sTable[short0]<<32
  394. }
  395. cv = load64(src, s)
  396. }
  397. emitRemainder:
  398. if nextEmit < len(src) {
  399. // Bail if we exceed the maximum size.
  400. if d+len(src)-nextEmit > dstLimit {
  401. return 0
  402. }
  403. if debug && nextEmit != s {
  404. fmt.Println("emitted ", len(src)-nextEmit, "literals")
  405. }
  406. d += emitLiteral(dst[d:], src[nextEmit:])
  407. }
  408. return d
  409. }
  410. // encodeBlockBestSnappy encodes a non-empty src to a guaranteed-large-enough dst. It
  411. // assumes that the varint-encoded length of the decompressed bytes has already
  412. // been written.
  413. //
  414. // It also assumes that:
  415. //
  416. // len(dst) >= MaxEncodedLen(len(src)) &&
  417. // minNonLiteralBlockSize <= len(src) && len(src) <= maxBlockSize
  418. func encodeBlockBestSnappy(dst, src []byte) (d int) {
  419. // Initialize the hash tables.
  420. const (
  421. // Long hash matches.
  422. lTableBits = bestLongTableBits
  423. maxLTableSize = bestLongTableSize
  424. // Short hash matches.
  425. sTableBits = bestShortTableBits
  426. maxSTableSize = bestShortTableSize
  427. inputMargin = 8 + 2
  428. )
  429. // sLimit is when to stop looking for offset/length copies. The inputMargin
  430. // lets us use a fast path for emitLiteral in the main loop, while we are
  431. // looking for copies.
  432. sLimit := len(src) - inputMargin
  433. if len(src) < minNonLiteralBlockSize {
  434. return 0
  435. }
  436. tbl := getBestTables()
  437. lTable := &tbl.lTable
  438. sTable := &tbl.sTable
  439. defer bestTablePool.Put(tbl)
  440. // Bail if we can't compress to at least this.
  441. dstLimit := len(src) - 5
  442. // nextEmit is where in src the next emitLiteral should start from.
  443. nextEmit := 0
  444. // The encoded form must start with a literal, as there are no previous
  445. // bytes to copy, so we start looking for hash matches at s == 1.
  446. s := 1
  447. cv := load64(src, s)
  448. // We search for a repeat at -1, but don't output repeats when nextEmit == 0
  449. repeat := 1
  450. const lowbitMask = 0xffffffff
  451. getCur := func(x uint64) int {
  452. return int(x & lowbitMask)
  453. }
  454. getPrev := func(x uint64) int {
  455. return int(x >> 32)
  456. }
  457. const maxSkip = 64
  458. for {
  459. type match struct {
  460. offset int
  461. s int
  462. length int
  463. score int
  464. }
  465. var best match
  466. for {
  467. // Next src position to check
  468. nextS := (s-nextEmit)>>8 + 1
  469. if nextS > maxSkip {
  470. nextS = s + maxSkip
  471. } else {
  472. nextS += s
  473. }
  474. if nextS > sLimit {
  475. goto emitRemainder
  476. }
  477. hashL := hash8(cv, lTableBits)
  478. hashS := hash4(cv, sTableBits)
  479. candidateL := lTable[hashL]
  480. candidateS := sTable[hashS]
  481. score := func(m match) int {
  482. // Matches that are longer forward are penalized since we must emit it as a literal.
  483. score := m.length - m.s
  484. if nextEmit == m.s {
  485. // If we do not have to emit literals, we save 1 byte
  486. score++
  487. }
  488. offset := m.s - m.offset
  489. return score - emitCopyNoRepeatSize(offset, m.length)
  490. }
  491. matchAt := func(offset, s int, first uint32) match {
  492. if best.length != 0 && best.s-best.offset == s-offset {
  493. // Don't retest if we have the same offset.
  494. return match{offset: offset, s: s}
  495. }
  496. if load32(src, offset) != first {
  497. return match{offset: offset, s: s}
  498. }
  499. m := match{offset: offset, s: s, length: 4 + offset}
  500. s += 4
  501. for s <= sLimit {
  502. if diff := load64(src, s) ^ load64(src, m.length); diff != 0 {
  503. m.length += bits.TrailingZeros64(diff) >> 3
  504. break
  505. }
  506. s += 8
  507. m.length += 8
  508. }
  509. m.length -= offset
  510. m.score = score(m)
  511. if m.score <= -m.s {
  512. // Eliminate if no savings, we might find a better one.
  513. m.length = 0
  514. }
  515. return m
  516. }
  517. bestOf := func(a, b match) match {
  518. if b.length == 0 {
  519. return a
  520. }
  521. if a.length == 0 {
  522. return b
  523. }
  524. as := a.score + b.s
  525. bs := b.score + a.s
  526. if as >= bs {
  527. return a
  528. }
  529. return b
  530. }
  531. best = bestOf(matchAt(getCur(candidateL), s, uint32(cv)), matchAt(getPrev(candidateL), s, uint32(cv)))
  532. best = bestOf(best, matchAt(getCur(candidateS), s, uint32(cv)))
  533. best = bestOf(best, matchAt(getPrev(candidateS), s, uint32(cv)))
  534. {
  535. best = bestOf(best, matchAt(s-repeat+1, s+1, uint32(cv>>8)))
  536. if best.length > 0 {
  537. // s+1
  538. nextShort := sTable[hash4(cv>>8, sTableBits)]
  539. s := s + 1
  540. cv := load64(src, s)
  541. nextLong := lTable[hash8(cv, lTableBits)]
  542. best = bestOf(best, matchAt(getCur(nextShort), s, uint32(cv)))
  543. best = bestOf(best, matchAt(getPrev(nextShort), s, uint32(cv)))
  544. best = bestOf(best, matchAt(getCur(nextLong), s, uint32(cv)))
  545. best = bestOf(best, matchAt(getPrev(nextLong), s, uint32(cv)))
  546. // Repeat at + 2
  547. best = bestOf(best, matchAt(s-repeat+1, s+1, uint32(cv>>8)))
  548. // s+2
  549. if true {
  550. nextShort = sTable[hash4(cv>>8, sTableBits)]
  551. s++
  552. cv = load64(src, s)
  553. nextLong = lTable[hash8(cv, lTableBits)]
  554. best = bestOf(best, matchAt(getCur(nextShort), s, uint32(cv)))
  555. best = bestOf(best, matchAt(getPrev(nextShort), s, uint32(cv)))
  556. best = bestOf(best, matchAt(getCur(nextLong), s, uint32(cv)))
  557. best = bestOf(best, matchAt(getPrev(nextLong), s, uint32(cv)))
  558. }
  559. // Search for a match at best match end, see if that is better.
  560. if sAt := best.s + best.length; sAt < sLimit {
  561. sBack := best.s
  562. backL := best.length
  563. // Load initial values
  564. cv = load64(src, sBack)
  565. // Search for mismatch
  566. next := lTable[hash8(load64(src, sAt), lTableBits)]
  567. //next := sTable[hash4(load64(src, sAt), sTableBits)]
  568. if checkAt := getCur(next) - backL; checkAt > 0 {
  569. best = bestOf(best, matchAt(checkAt, sBack, uint32(cv)))
  570. }
  571. if checkAt := getPrev(next) - backL; checkAt > 0 {
  572. best = bestOf(best, matchAt(checkAt, sBack, uint32(cv)))
  573. }
  574. }
  575. }
  576. }
  577. // Update table
  578. lTable[hashL] = uint64(s) | candidateL<<32
  579. sTable[hashS] = uint64(s) | candidateS<<32
  580. if best.length > 0 {
  581. break
  582. }
  583. cv = load64(src, nextS)
  584. s = nextS
  585. }
  586. // Extend backwards, not needed for repeats...
  587. s = best.s
  588. if true {
  589. for best.offset > 0 && s > nextEmit && src[best.offset-1] == src[s-1] {
  590. best.offset--
  591. best.length++
  592. s--
  593. }
  594. }
  595. if false && best.offset >= s {
  596. panic(fmt.Errorf("t %d >= s %d", best.offset, s))
  597. }
  598. // Bail if we exceed the maximum size.
  599. if d+(s-nextEmit) > dstLimit {
  600. return 0
  601. }
  602. base := s
  603. offset := s - best.offset
  604. s += best.length
  605. if offset > 65535 && s-base <= 5 {
  606. // Bail if the match is equal or worse to the encoding.
  607. s = best.s + 1
  608. if s >= sLimit {
  609. goto emitRemainder
  610. }
  611. cv = load64(src, s)
  612. continue
  613. }
  614. d += emitLiteral(dst[d:], src[nextEmit:base])
  615. d += emitCopyNoRepeat(dst[d:], offset, best.length)
  616. repeat = offset
  617. nextEmit = s
  618. if s >= sLimit {
  619. goto emitRemainder
  620. }
  621. if d > dstLimit {
  622. // Do we have space for more, if not bail.
  623. return 0
  624. }
  625. // Fill tables...
  626. for i := best.s + 1; i < s; i++ {
  627. cv0 := load64(src, i)
  628. long0 := hash8(cv0, lTableBits)
  629. short0 := hash4(cv0, sTableBits)
  630. lTable[long0] = uint64(i) | lTable[long0]<<32
  631. sTable[short0] = uint64(i) | sTable[short0]<<32
  632. }
  633. cv = load64(src, s)
  634. }
  635. emitRemainder:
  636. if nextEmit < len(src) {
  637. // Bail if we exceed the maximum size.
  638. if d+len(src)-nextEmit > dstLimit {
  639. return 0
  640. }
  641. d += emitLiteral(dst[d:], src[nextEmit:])
  642. }
  643. return d
  644. }
  645. // emitCopySize returns the size to encode the offset+length
  646. //
  647. // It assumes that:
  648. //
  649. // 1 <= offset && offset <= math.MaxUint32
  650. // 4 <= length && length <= 1 << 24
  651. func emitCopySize(offset, length int) int {
  652. if offset >= 65536 {
  653. i := 0
  654. if length > 64 {
  655. length -= 64
  656. if length >= 4 {
  657. // Emit remaining as repeats
  658. return 5 + emitRepeatSize(offset, length)
  659. }
  660. i = 5
  661. }
  662. if length == 0 {
  663. return i
  664. }
  665. return i + 5
  666. }
  667. // Offset no more than 2 bytes.
  668. if length > 64 {
  669. if offset < 2048 {
  670. // Emit 8 bytes, then rest as repeats...
  671. return 2 + emitRepeatSize(offset, length-8)
  672. }
  673. // Emit remaining as repeats, at least 4 bytes remain.
  674. return 3 + emitRepeatSize(offset, length-60)
  675. }
  676. if length >= 12 || offset >= 2048 {
  677. return 3
  678. }
  679. // Emit the remaining copy, encoded as 2 bytes.
  680. return 2
  681. }
  682. // emitCopyNoRepeatSize returns the size to encode the offset+length
  683. //
  684. // It assumes that:
  685. //
  686. // 1 <= offset && offset <= math.MaxUint32
  687. // 4 <= length && length <= 1 << 24
  688. func emitCopyNoRepeatSize(offset, length int) int {
  689. if offset >= 65536 {
  690. return 5 + 5*(length/64)
  691. }
  692. // Offset no more than 2 bytes.
  693. if length > 64 {
  694. // Emit remaining as repeats, at least 4 bytes remain.
  695. return 3 + 3*(length/60)
  696. }
  697. if length >= 12 || offset >= 2048 {
  698. return 3
  699. }
  700. // Emit the remaining copy, encoded as 2 bytes.
  701. return 2
  702. }
  703. // emitRepeatSize returns the number of bytes required to encode a repeat.
  704. // Length must be at least 4 and < 1<<24
  705. func emitRepeatSize(offset, length int) int {
  706. // Repeat offset, make length cheaper
  707. if length <= 4+4 || (length < 8+4 && offset < 2048) {
  708. return 2
  709. }
  710. if length < (1<<8)+4+4 {
  711. return 3
  712. }
  713. if length < (1<<16)+(1<<8)+4 {
  714. return 4
  715. }
  716. const maxRepeat = (1 << 24) - 1
  717. length -= (1 << 16) - 4
  718. left := 0
  719. if length > maxRepeat {
  720. left = length - maxRepeat + 4
  721. }
  722. if left > 0 {
  723. return 5 + emitRepeatSize(offset, left)
  724. }
  725. return 5
  726. }