block.go 7.7 KB

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