block.go 9.9 KB

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