block.go 7.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333
  1. package lz4
  2. import (
  3. "encoding/binary"
  4. "math/bits"
  5. )
  6. // blockHash hashes 4 bytes into a value < winSize.
  7. func blockHash(x uint32) uint32 {
  8. const hasher uint32 = 2654435761 // Knuth multiplicative hash.
  9. return x * hasher >> hashShift
  10. }
  11. // CompressBlockBound returns the maximum size of a given buffer of size n, when not compressible.
  12. func CompressBlockBound(n int) int {
  13. return n + n/255 + 16
  14. }
  15. // UncompressBlock uncompresses the source buffer into the destination one,
  16. // and returns the uncompressed size.
  17. //
  18. // The destination buffer must be sized appropriately.
  19. //
  20. // An error is returned if the source data is invalid or the destination buffer is too small.
  21. func UncompressBlock(src, dst []byte) (int, error) {
  22. if len(src) == 0 {
  23. return 0, nil
  24. }
  25. if di := decodeBlock(dst, src); di >= 0 {
  26. return di, nil
  27. }
  28. return 0, ErrInvalidSourceShortBuffer
  29. }
  30. // CompressBlock compresses the source buffer into the destination one.
  31. // This is the fast version of LZ4 compression and also the default one.
  32. // The size of hashTable must be at least 64Kb.
  33. //
  34. // The size of the compressed data is returned. If it is 0 and no error, then the data is incompressible.
  35. //
  36. // An error is returned if the destination buffer is too small.
  37. func CompressBlock(src, dst []byte, hashTable []int) (di int, err error) {
  38. defer recoverBlock(&err)
  39. // adaptSkipLog sets how quickly the compressor begins skipping blocks when data is incompressible.
  40. // This significantly speeds up incompressible data and usually has very small impact on compresssion.
  41. // bytes to skip = 1 + (bytes since last match >> adaptSkipLog)
  42. const adaptSkipLog = 7
  43. sn, dn := len(src)-mfLimit, len(dst)
  44. if sn <= 0 || dn == 0 {
  45. return 0, nil
  46. }
  47. var si int
  48. // Fast scan strategy: the hash table only stores the last 4 bytes sequences.
  49. anchor := si // Position of the current literals.
  50. for si < sn {
  51. // Hash the next 4 bytes (sequence)...
  52. match := binary.LittleEndian.Uint32(src[si:])
  53. h := blockHash(match)
  54. ref := hashTable[h]
  55. hashTable[h] = si
  56. if ref >= sn { // Invalid reference (dirty hashtable).
  57. si += 1 + (si-anchor)>>adaptSkipLog
  58. continue
  59. }
  60. offset := si - ref
  61. if offset <= 0 || offset >= winSize || // Out of window.
  62. match != binary.LittleEndian.Uint32(src[ref:]) { // Hash collision on different matches.
  63. si += 1 + (si-anchor)>>adaptSkipLog
  64. continue
  65. }
  66. // Match found.
  67. // acc = accInit
  68. lLen := si - anchor // Literal length.
  69. // Encode match length part 1.
  70. si += minMatch
  71. mLen := si // Match length has minMatch already.
  72. // Find the longest match, first looking by batches of 8 bytes.
  73. for si < sn {
  74. x := binary.LittleEndian.Uint64(src[si:]) ^ binary.LittleEndian.Uint64(src[si-offset:])
  75. if x == 0 {
  76. si += 8
  77. } else {
  78. // Stop is first non-zero byte.
  79. si += bits.TrailingZeros64(x) >> 3
  80. break
  81. }
  82. }
  83. mLen = si - mLen
  84. if mLen < 0xF {
  85. dst[di] = byte(mLen)
  86. } else {
  87. dst[di] = 0xF
  88. }
  89. // Encode literals length.
  90. if lLen < 0xF {
  91. dst[di] |= byte(lLen << 4)
  92. } else {
  93. dst[di] |= 0xF0
  94. di++
  95. l := lLen - 0xF
  96. for ; l >= 0xFF; l -= 0xFF {
  97. dst[di] = 0xFF
  98. di++
  99. }
  100. dst[di] = byte(l)
  101. }
  102. di++
  103. // Literals.
  104. copy(dst[di:di+lLen], src[anchor:anchor+lLen])
  105. di += lLen + 2
  106. anchor = si
  107. // Encode offset.
  108. _ = dst[di] // Bound check elimination.
  109. dst[di-2], dst[di-1] = byte(offset), byte(offset>>8)
  110. // Encode match length part 2.
  111. if mLen >= 0xF {
  112. for mLen -= 0xF; mLen >= 0xFF; mLen -= 0xFF {
  113. dst[di] = 0xFF
  114. di++
  115. }
  116. dst[di] = byte(mLen)
  117. di++
  118. }
  119. }
  120. if anchor == 0 {
  121. // Incompressible.
  122. return 0, nil
  123. }
  124. // Last literals.
  125. lLen := len(src) - anchor
  126. if lLen < 0xF {
  127. dst[di] = byte(lLen << 4)
  128. } else {
  129. dst[di] = 0xF0
  130. di++
  131. for lLen -= 0xF; lLen >= 0xFF; lLen -= 0xFF {
  132. dst[di] = 0xFF
  133. di++
  134. }
  135. dst[di] = byte(lLen)
  136. }
  137. di++
  138. // Write the last literals.
  139. if di >= anchor {
  140. // Incompressible.
  141. return 0, nil
  142. }
  143. di += copy(dst[di:di+len(src)-anchor], src[anchor:])
  144. return di, nil
  145. }
  146. // CompressBlockHC compresses the source buffer src into the destination dst
  147. // with max search depth (use 0 or negative value for no max).
  148. //
  149. // CompressBlockHC compression ratio is better than CompressBlock but it is also slower.
  150. //
  151. // The size of the compressed data is returned. If it is 0 and no error, then the data is not compressible.
  152. //
  153. // An error is returned if the destination buffer is too small.
  154. func CompressBlockHC(src, dst []byte, depth int) (di int, err error) {
  155. defer recoverBlock(&err)
  156. // adaptSkipLog sets how quickly the compressor begins skipping blocks when data is incompressible.
  157. // This significantly speeds up incompressible data and usually has very small impact on compresssion.
  158. // bytes to skip = 1 + (bytes since last match >> adaptSkipLog)
  159. const adaptSkipLog = 7
  160. sn, dn := len(src)-mfLimit, len(dst)
  161. if sn <= 0 || dn == 0 {
  162. return 0, nil
  163. }
  164. var si int
  165. // hashTable: stores the last position found for a given hash
  166. // chainTable: stores previous positions for a given hash
  167. var hashTable, chainTable [winSize]int
  168. if depth <= 0 {
  169. depth = winSize
  170. }
  171. anchor := si
  172. for si < sn {
  173. // Hash the next 4 bytes (sequence).
  174. match := binary.LittleEndian.Uint32(src[si:])
  175. h := blockHash(match)
  176. // Follow the chain until out of window and give the longest match.
  177. mLen := 0
  178. offset := 0
  179. for next, try := hashTable[h], depth; try > 0 && next > 0 && si-next < winSize; next = chainTable[next&winMask] {
  180. // The first (mLen==0) or next byte (mLen>=minMatch) at current match length
  181. // must match to improve on the match length.
  182. if src[next+mLen] != src[si+mLen] {
  183. continue
  184. }
  185. ml := 0
  186. // Compare the current position with a previous with the same hash.
  187. for ml < sn-si {
  188. x := binary.LittleEndian.Uint64(src[next+ml:]) ^ binary.LittleEndian.Uint64(src[si+ml:])
  189. if x == 0 {
  190. ml += 8
  191. } else {
  192. // Stop is first non-zero byte.
  193. ml += bits.TrailingZeros64(x) >> 3
  194. break
  195. }
  196. }
  197. if ml < minMatch || ml <= mLen {
  198. // Match too small (<minMath) or smaller than the current match.
  199. continue
  200. }
  201. // Found a longer match, keep its position and length.
  202. mLen = ml
  203. offset = si - next
  204. // Try another previous position with the same hash.
  205. try--
  206. }
  207. chainTable[si&winMask] = hashTable[h]
  208. hashTable[h] = si
  209. // No match found.
  210. if mLen == 0 {
  211. si += 1 + (si-anchor)>>adaptSkipLog
  212. continue
  213. }
  214. // Match found.
  215. // Update hash/chain tables with overlapping bytes:
  216. // si already hashed, add everything from si+1 up to the match length.
  217. winStart := si + 1
  218. if ws := si + mLen - winSize; ws > winStart {
  219. winStart = ws
  220. }
  221. for si, ml := winStart, si+mLen; si < ml; {
  222. match >>= 8
  223. match |= uint32(src[si+3]) << 24
  224. h := blockHash(match)
  225. chainTable[si&winMask] = hashTable[h]
  226. hashTable[h] = si
  227. si++
  228. }
  229. lLen := si - anchor
  230. si += mLen
  231. mLen -= minMatch // Match length does not include minMatch.
  232. if mLen < 0xF {
  233. dst[di] = byte(mLen)
  234. } else {
  235. dst[di] = 0xF
  236. }
  237. // Encode literals length.
  238. if lLen < 0xF {
  239. dst[di] |= byte(lLen << 4)
  240. } else {
  241. dst[di] |= 0xF0
  242. di++
  243. l := lLen - 0xF
  244. for ; l >= 0xFF; l -= 0xFF {
  245. dst[di] = 0xFF
  246. di++
  247. }
  248. dst[di] = byte(l)
  249. }
  250. di++
  251. // Literals.
  252. copy(dst[di:di+lLen], src[anchor:anchor+lLen])
  253. di += lLen
  254. anchor = si
  255. // Encode offset.
  256. di += 2
  257. dst[di-2], dst[di-1] = byte(offset), byte(offset>>8)
  258. // Encode match length part 2.
  259. if mLen >= 0xF {
  260. for mLen -= 0xF; mLen >= 0xFF; mLen -= 0xFF {
  261. dst[di] = 0xFF
  262. di++
  263. }
  264. dst[di] = byte(mLen)
  265. di++
  266. }
  267. }
  268. if anchor == 0 {
  269. // Incompressible.
  270. return 0, nil
  271. }
  272. // Last literals.
  273. lLen := len(src) - anchor
  274. if lLen < 0xF {
  275. dst[di] = byte(lLen << 4)
  276. } else {
  277. dst[di] = 0xF0
  278. di++
  279. lLen -= 0xF
  280. for ; lLen >= 0xFF; lLen -= 0xFF {
  281. dst[di] = 0xFF
  282. di++
  283. }
  284. dst[di] = byte(lLen)
  285. }
  286. di++
  287. // Write the last literals.
  288. if di >= anchor {
  289. // Incompressible.
  290. return 0, nil
  291. }
  292. di += copy(dst[di:di+len(src)-anchor], src[anchor:])
  293. return di, nil
  294. }