block.go 9.6 KB

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