block.go 7.8 KB

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