block.go 9.8 KB

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