block.go 11 KB

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