block.go 7.2 KB

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