block.go 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413
  1. package lz4
  2. import (
  3. "encoding/binary"
  4. "math/bits"
  5. "sync"
  6. )
  7. // blockHash hashes the lower 6 bytes into a value < htSize.
  8. func blockHash(x uint64) uint32 {
  9. const prime6bytes = 227718039650203
  10. return uint32(((x << (64 - 48)) * prime6bytes) >> (64 - hashLog))
  11. }
  12. // CompressBlockBound returns the maximum size of a given buffer of size n, when not compressible.
  13. func CompressBlockBound(n int) int {
  14. return n + n/255 + 16
  15. }
  16. // UncompressBlock uncompresses the source buffer into the destination one,
  17. // and returns the uncompressed size.
  18. //
  19. // The destination buffer must be sized appropriately.
  20. //
  21. // An error is returned if the source data is invalid or the destination buffer is too small.
  22. func UncompressBlock(src, dst []byte) (int, error) {
  23. if len(src) == 0 {
  24. return 0, nil
  25. }
  26. if di := decodeBlock(dst, src); di >= 0 {
  27. return di, nil
  28. }
  29. return 0, ErrInvalidSourceShortBuffer
  30. }
  31. // CompressBlock compresses the source buffer into the destination one.
  32. // This is the fast version of LZ4 compression and also the default one.
  33. //
  34. // The argument hashTable is scratch space for a hash table used by the
  35. // compressor. If provided, it should have length at least 1<<16. If it is
  36. // shorter (or nil), CompressBlock allocates its own hash table.
  37. //
  38. // The size of the compressed data is returned.
  39. //
  40. // If the destination buffer size is lower than CompressBlockBound and
  41. // the compressed size is 0 and no error, then the data is incompressible.
  42. //
  43. // An error is returned if the destination buffer is too small.
  44. func CompressBlock(src, dst []byte, hashTable []int) (_ int, err error) {
  45. defer recoverBlock(&err)
  46. // Return 0, nil only if the destination buffer size is < CompressBlockBound.
  47. isNotCompressible := len(dst) < CompressBlockBound(len(src))
  48. // adaptSkipLog sets how quickly the compressor begins skipping blocks when data is incompressible.
  49. // This significantly speeds up incompressible data and usually has very small impact on compression.
  50. // bytes to skip = 1 + (bytes since last match >> adaptSkipLog)
  51. const adaptSkipLog = 7
  52. if len(hashTable) < htSize {
  53. htIface := htPool.Get()
  54. defer htPool.Put(htIface)
  55. hashTable = (*(htIface).(*[htSize]int))[:]
  56. }
  57. // Prove to the compiler the table has at least htSize elements.
  58. // The compiler can see that "uint32() >> hashShift" cannot be out of bounds.
  59. hashTable = hashTable[:htSize]
  60. // si: Current position of the search.
  61. // anchor: Position of the current literals.
  62. var si, di, anchor int
  63. sn := len(src) - mfLimit
  64. if sn <= 0 {
  65. goto lastLiterals
  66. }
  67. // Fast scan strategy: the hash table only stores the last 4 bytes sequences.
  68. for si < sn {
  69. // Hash the next 6 bytes (sequence)...
  70. match := binary.LittleEndian.Uint64(src[si:])
  71. h := blockHash(match)
  72. h2 := blockHash(match >> 8)
  73. // We check a match at s, s+1 and s+2 and pick the first one we get.
  74. // Checking 3 only requires us to load the source one.
  75. ref := hashTable[h]
  76. ref2 := hashTable[h2]
  77. hashTable[h] = si
  78. hashTable[h2] = si + 1
  79. offset := si - ref
  80. // If offset <= 0 we got an old entry in the hash table.
  81. if offset <= 0 || offset >= winSize || // Out of window.
  82. uint32(match) != binary.LittleEndian.Uint32(src[ref:]) { // Hash collision on different matches.
  83. // No match. Start calculating another hash.
  84. // The processor can usually do this out-of-order.
  85. h = blockHash(match >> 16)
  86. ref = hashTable[h]
  87. // Check the second match at si+1
  88. si += 1
  89. offset = si - ref2
  90. if offset <= 0 || offset >= winSize ||
  91. uint32(match>>8) != binary.LittleEndian.Uint32(src[ref2:]) {
  92. // No match. Check the third match at si+2
  93. si += 1
  94. offset = si - ref
  95. hashTable[h] = si
  96. if offset <= 0 || offset >= winSize ||
  97. uint32(match>>16) != binary.LittleEndian.Uint32(src[ref:]) {
  98. // Skip one extra byte (at si+3) before we check 3 matches again.
  99. si += 2 + (si-anchor)>>adaptSkipLog
  100. continue
  101. }
  102. }
  103. }
  104. // Match found.
  105. lLen := si - anchor // Literal length.
  106. // We already matched 4 bytes.
  107. mLen := 4
  108. // Extend backwards if we can, reducing literals.
  109. tOff := si - offset - 1
  110. for lLen > 0 && tOff >= 0 && src[si-1] == src[tOff] {
  111. si--
  112. tOff--
  113. lLen--
  114. mLen++
  115. }
  116. // Add the match length, so we continue search at the end.
  117. // Use mLen to store the offset base.
  118. si, mLen = si+mLen, si+minMatch
  119. // Find the longest match by looking by batches of 8 bytes.
  120. for si+8 < sn {
  121. x := binary.LittleEndian.Uint64(src[si:]) ^ binary.LittleEndian.Uint64(src[si-offset:])
  122. if x == 0 {
  123. si += 8
  124. } else {
  125. // Stop is first non-zero byte.
  126. si += bits.TrailingZeros64(x) >> 3
  127. break
  128. }
  129. }
  130. mLen = si - mLen
  131. if mLen < 0xF {
  132. dst[di] = byte(mLen)
  133. } else {
  134. dst[di] = 0xF
  135. }
  136. // Encode literals length.
  137. if lLen < 0xF {
  138. dst[di] |= byte(lLen << 4)
  139. } else {
  140. dst[di] |= 0xF0
  141. di++
  142. l := lLen - 0xF
  143. for ; l >= 0xFF; l -= 0xFF {
  144. dst[di] = 0xFF
  145. di++
  146. }
  147. dst[di] = byte(l)
  148. }
  149. di++
  150. // Literals.
  151. copy(dst[di:di+lLen], src[anchor:anchor+lLen])
  152. di += lLen + 2
  153. anchor = si
  154. // Encode offset.
  155. _ = dst[di] // Bound check elimination.
  156. dst[di-2], dst[di-1] = byte(offset), byte(offset>>8)
  157. // Encode match length part 2.
  158. if mLen >= 0xF {
  159. for mLen -= 0xF; mLen >= 0xFF; mLen -= 0xFF {
  160. dst[di] = 0xFF
  161. di++
  162. }
  163. dst[di] = byte(mLen)
  164. di++
  165. }
  166. // Check if we can load next values.
  167. if si >= sn {
  168. break
  169. }
  170. // Hash match end-2
  171. h = blockHash(binary.LittleEndian.Uint64(src[si-2:]))
  172. hashTable[h] = si - 2
  173. }
  174. lastLiterals:
  175. if isNotCompressible && anchor == 0 {
  176. // Incompressible.
  177. return 0, nil
  178. }
  179. // Last literals.
  180. lLen := len(src) - anchor
  181. if lLen < 0xF {
  182. dst[di] = byte(lLen << 4)
  183. } else {
  184. dst[di] = 0xF0
  185. di++
  186. for lLen -= 0xF; lLen >= 0xFF; lLen -= 0xFF {
  187. dst[di] = 0xFF
  188. di++
  189. }
  190. dst[di] = byte(lLen)
  191. }
  192. di++
  193. // Write the last literals.
  194. if isNotCompressible && di >= anchor {
  195. // Incompressible.
  196. return 0, nil
  197. }
  198. di += copy(dst[di:di+len(src)-anchor], src[anchor:])
  199. return di, nil
  200. }
  201. // Pool of hash tables for CompressBlock.
  202. var htPool = sync.Pool{
  203. New: func() interface{} {
  204. return new([htSize]int)
  205. },
  206. }
  207. // blockHash hashes 4 bytes into a value < winSize.
  208. func blockHashHC(x uint32) uint32 {
  209. const hasher uint32 = 2654435761 // Knuth multiplicative hash.
  210. return x * hasher >> (32 - winSizeLog)
  211. }
  212. // CompressBlockHC compresses the source buffer src into the destination dst
  213. // with max search depth (use 0 or negative value for no max).
  214. //
  215. // CompressBlockHC compression ratio is better than CompressBlock but it is also slower.
  216. //
  217. // The size of the compressed data is returned.
  218. //
  219. // If the destination buffer size is lower than CompressBlockBound and
  220. // the compressed size is 0 and no error, then the data is incompressible.
  221. //
  222. // An error is returned if the destination buffer is too small.
  223. func CompressBlockHC(src, dst []byte, depth int) (_ int, err error) {
  224. defer recoverBlock(&err)
  225. // Return 0, nil only if the destination buffer size is < CompressBlockBound.
  226. isNotCompressible := len(dst) < CompressBlockBound(len(src))
  227. // adaptSkipLog sets how quickly the compressor begins skipping blocks when data is incompressible.
  228. // This significantly speeds up incompressible data and usually has very small impact on compression.
  229. // bytes to skip = 1 + (bytes since last match >> adaptSkipLog)
  230. const adaptSkipLog = 7
  231. var si, di, anchor int
  232. // hashTable: stores the last position found for a given hash
  233. // chainTable: stores previous positions for a given hash
  234. var hashTable, chainTable [winSize]int
  235. if depth <= 0 {
  236. depth = winSize
  237. }
  238. sn := len(src) - mfLimit
  239. if sn <= 0 {
  240. goto lastLiterals
  241. }
  242. for si < sn {
  243. // Hash the next 4 bytes (sequence).
  244. match := binary.LittleEndian.Uint32(src[si:])
  245. h := blockHashHC(match)
  246. // Follow the chain until out of window and give the longest match.
  247. mLen := 0
  248. offset := 0
  249. for next, try := hashTable[h], depth; try > 0 && next > 0 && si-next < winSize; next = chainTable[next&winMask] {
  250. // The first (mLen==0) or next byte (mLen>=minMatch) at current match length
  251. // must match to improve on the match length.
  252. if src[next+mLen] != src[si+mLen] {
  253. continue
  254. }
  255. ml := 0
  256. // Compare the current position with a previous with the same hash.
  257. for ml < sn-si {
  258. x := binary.LittleEndian.Uint64(src[next+ml:]) ^ binary.LittleEndian.Uint64(src[si+ml:])
  259. if x == 0 {
  260. ml += 8
  261. } else {
  262. // Stop is first non-zero byte.
  263. ml += bits.TrailingZeros64(x) >> 3
  264. break
  265. }
  266. }
  267. if ml < minMatch || ml <= mLen {
  268. // Match too small (<minMath) or smaller than the current match.
  269. continue
  270. }
  271. // Found a longer match, keep its position and length.
  272. mLen = ml
  273. offset = si - next
  274. // Try another previous position with the same hash.
  275. try--
  276. }
  277. chainTable[si&winMask] = hashTable[h]
  278. hashTable[h] = si
  279. // No match found.
  280. if mLen == 0 {
  281. si += 1 + (si-anchor)>>adaptSkipLog
  282. continue
  283. }
  284. // Match found.
  285. // Update hash/chain tables with overlapping bytes:
  286. // si already hashed, add everything from si+1 up to the match length.
  287. winStart := si + 1
  288. if ws := si + mLen - winSize; ws > winStart {
  289. winStart = ws
  290. }
  291. for si, ml := winStart, si+mLen; si < ml; {
  292. match >>= 8
  293. match |= uint32(src[si+3]) << 24
  294. h := blockHashHC(match)
  295. chainTable[si&winMask] = hashTable[h]
  296. hashTable[h] = si
  297. si++
  298. }
  299. lLen := si - anchor
  300. si += mLen
  301. mLen -= minMatch // Match length does not include minMatch.
  302. if mLen < 0xF {
  303. dst[di] = byte(mLen)
  304. } else {
  305. dst[di] = 0xF
  306. }
  307. // Encode literals length.
  308. if lLen < 0xF {
  309. dst[di] |= byte(lLen << 4)
  310. } else {
  311. dst[di] |= 0xF0
  312. di++
  313. l := lLen - 0xF
  314. for ; l >= 0xFF; l -= 0xFF {
  315. dst[di] = 0xFF
  316. di++
  317. }
  318. dst[di] = byte(l)
  319. }
  320. di++
  321. // Literals.
  322. copy(dst[di:di+lLen], src[anchor:anchor+lLen])
  323. di += lLen
  324. anchor = si
  325. // Encode offset.
  326. di += 2
  327. dst[di-2], dst[di-1] = byte(offset), byte(offset>>8)
  328. // Encode match length part 2.
  329. if mLen >= 0xF {
  330. for mLen -= 0xF; mLen >= 0xFF; mLen -= 0xFF {
  331. dst[di] = 0xFF
  332. di++
  333. }
  334. dst[di] = byte(mLen)
  335. di++
  336. }
  337. }
  338. if isNotCompressible && anchor == 0 {
  339. // Incompressible.
  340. return 0, nil
  341. }
  342. // Last literals.
  343. lastLiterals:
  344. lLen := len(src) - anchor
  345. if lLen < 0xF {
  346. dst[di] = byte(lLen << 4)
  347. } else {
  348. dst[di] = 0xF0
  349. di++
  350. lLen -= 0xF
  351. for ; lLen >= 0xFF; lLen -= 0xFF {
  352. dst[di] = 0xFF
  353. di++
  354. }
  355. dst[di] = byte(lLen)
  356. }
  357. di++
  358. // Write the last literals.
  359. if isNotCompressible && di >= anchor {
  360. // Incompressible.
  361. return 0, nil
  362. }
  363. di += copy(dst[di:di+len(src)-anchor], src[anchor:])
  364. return di, nil
  365. }