block.go 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423
  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. if cap(hashTable) < htSize {
  60. hashTable = htPool.Get().([]int)
  61. defer htPool.Put(hashTable)
  62. } else {
  63. hashTable = hashTable[:htSize]
  64. }
  65. _ = hashTable[htSize-1]
  66. // si: Current position of the search.
  67. // anchor: Position of the current literals.
  68. var si, di, anchor int
  69. sn := len(src) - mfLimit
  70. if sn <= 0 {
  71. goto lastLiterals
  72. }
  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. if isNotCompressible && anchor == 0 {
  181. // Incompressible.
  182. return 0, nil
  183. }
  184. // Last literals.
  185. lastLiterals:
  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 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. if cap(hashTable) < htSize {
  235. hashTable = htPool.Get().([]int)
  236. defer htPool.Put(hashTable)
  237. } else {
  238. hashTable = hashTable[:htSize]
  239. }
  240. _ = hashTable[htSize-1]
  241. chainTable := htPool.Get().([]int)
  242. defer htPool.Put(chainTable)
  243. _ = chainTable[htSize-1]
  244. if depth <= 0 {
  245. depth = winSize
  246. }
  247. sn := len(src) - mfLimit
  248. if sn <= 0 {
  249. goto lastLiterals
  250. }
  251. for si < sn {
  252. // Hash the next 4 bytes (sequence).
  253. match := binary.LittleEndian.Uint32(src[si:])
  254. h := blockHashHC(match)
  255. // Follow the chain until out of window and give the longest match.
  256. mLen := 0
  257. offset := 0
  258. for next, try := hashTable[h], depth; try > 0 && next > 0 && si-next < winSize; next = chainTable[next&winMask] {
  259. // The first (mLen==0) or next byte (mLen>=minMatch) at current match length
  260. // must match to improve on the match length.
  261. if src[next+mLen] != src[si+mLen] {
  262. continue
  263. }
  264. ml := 0
  265. // Compare the current position with a previous with the same hash.
  266. for ml < sn-si {
  267. x := binary.LittleEndian.Uint64(src[next+ml:]) ^ binary.LittleEndian.Uint64(src[si+ml:])
  268. if x == 0 {
  269. ml += 8
  270. } else {
  271. // Stop is first non-zero byte.
  272. ml += bits.TrailingZeros64(x) >> 3
  273. break
  274. }
  275. }
  276. if ml < minMatch || ml <= mLen {
  277. // Match too small (<minMath) or smaller than the current match.
  278. continue
  279. }
  280. // Found a longer match, keep its position and length.
  281. mLen = ml
  282. offset = si - next
  283. // Try another previous position with the same hash.
  284. try--
  285. }
  286. chainTable[si&winMask] = hashTable[h]
  287. hashTable[h] = si
  288. // No match found.
  289. if mLen == 0 {
  290. si += 1 + (si-anchor)>>adaptSkipLog
  291. continue
  292. }
  293. // Match found.
  294. // Update hash/chain tables with overlapping bytes:
  295. // si already hashed, add everything from si+1 up to the match length.
  296. winStart := si + 1
  297. if ws := si + mLen - winSize; ws > winStart {
  298. winStart = ws
  299. }
  300. for si, ml := winStart, si+mLen; si < ml; {
  301. match >>= 8
  302. match |= uint32(src[si+3]) << 24
  303. h := blockHashHC(match)
  304. chainTable[si&winMask] = hashTable[h]
  305. hashTable[h] = si
  306. si++
  307. }
  308. lLen := si - anchor
  309. si += mLen
  310. mLen -= minMatch // Match length does not include minMatch.
  311. if mLen < 0xF {
  312. dst[di] = byte(mLen)
  313. } else {
  314. dst[di] = 0xF
  315. }
  316. // Encode literals length.
  317. if lLen < 0xF {
  318. dst[di] |= byte(lLen << 4)
  319. } else {
  320. dst[di] |= 0xF0
  321. di++
  322. l := lLen - 0xF
  323. for ; l >= 0xFF; l -= 0xFF {
  324. dst[di] = 0xFF
  325. di++
  326. }
  327. dst[di] = byte(l)
  328. }
  329. di++
  330. // Literals.
  331. copy(dst[di:di+lLen], src[anchor:anchor+lLen])
  332. di += lLen
  333. anchor = si
  334. // Encode offset.
  335. di += 2
  336. dst[di-2], dst[di-1] = byte(offset), byte(offset>>8)
  337. // Encode match length part 2.
  338. if mLen >= 0xF {
  339. for mLen -= 0xF; mLen >= 0xFF; mLen -= 0xFF {
  340. dst[di] = 0xFF
  341. di++
  342. }
  343. dst[di] = byte(mLen)
  344. di++
  345. }
  346. }
  347. if isNotCompressible && anchor == 0 {
  348. // Incompressible.
  349. return 0, nil
  350. }
  351. // Last literals.
  352. lastLiterals:
  353. lLen := len(src) - anchor
  354. if lLen < 0xF {
  355. dst[di] = byte(lLen << 4)
  356. } else {
  357. dst[di] = 0xF0
  358. di++
  359. lLen -= 0xF
  360. for ; lLen >= 0xFF; lLen -= 0xFF {
  361. dst[di] = 0xFF
  362. di++
  363. }
  364. dst[di] = byte(lLen)
  365. }
  366. di++
  367. // Write the last literals.
  368. if isNotCompressible && di >= anchor {
  369. // Incompressible.
  370. return 0, nil
  371. }
  372. di += copy(dst[di:di+len(src)-anchor], src[anchor:])
  373. return di, nil
  374. }