hash.go 9.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342
  1. package brotli
  2. import (
  3. "encoding/binary"
  4. "fmt"
  5. )
  6. type hasherCommon struct {
  7. params hasherParams
  8. is_prepared_ bool
  9. dict_num_lookups uint
  10. dict_num_matches uint
  11. }
  12. func (h *hasherCommon) Common() *hasherCommon {
  13. return h
  14. }
  15. type hasherHandle interface {
  16. Common() *hasherCommon
  17. Initialize(params *encoderParams)
  18. Prepare(one_shot bool, input_size uint, data []byte)
  19. StitchToPreviousBlock(num_bytes uint, position uint, ringbuffer []byte, ringbuffer_mask uint)
  20. HashTypeLength() uint
  21. StoreLookahead() uint
  22. PrepareDistanceCache(distance_cache []int)
  23. FindLongestMatch(dictionary *encoderDictionary, data []byte, ring_buffer_mask uint, distance_cache []int, cur_ix uint, max_length uint, max_backward uint, gap uint, max_distance uint, out *hasherSearchResult)
  24. StoreRange(data []byte, mask uint, ix_start uint, ix_end uint)
  25. Store(data []byte, mask uint, ix uint)
  26. }
  27. const kCutoffTransformsCount uint32 = 10
  28. /* 0, 12, 27, 23, 42, 63, 56, 48, 59, 64 */
  29. /* 0+0, 4+8, 8+19, 12+11, 16+26, 20+43, 24+32, 28+20, 32+27, 36+28 */
  30. const kCutoffTransforms uint64 = 0x071B520ADA2D3200
  31. type hasherSearchResult struct {
  32. len uint
  33. distance uint
  34. score uint
  35. len_code_delta int
  36. }
  37. /* kHashMul32 multiplier has these properties:
  38. * The multiplier must be odd. Otherwise we may lose the highest bit.
  39. * No long streaks of ones or zeros.
  40. * There is no effort to ensure that it is a prime, the oddity is enough
  41. for this use.
  42. * The number has been tuned heuristically against compression benchmarks. */
  43. const kHashMul32 uint32 = 0x1E35A7BD
  44. const kHashMul64 uint64 = 0x1E35A7BD1E35A7BD
  45. const kHashMul64Long uint64 = 0x1FE35A7BD3579BD3
  46. func hash14(data []byte) uint32 {
  47. var h uint32 = binary.LittleEndian.Uint32(data) * kHashMul32
  48. /* The higher bits contain more mixture from the multiplication,
  49. so we take our results from there. */
  50. return h >> (32 - 14)
  51. }
  52. func prepareDistanceCache(distance_cache []int, num_distances int) {
  53. if num_distances > 4 {
  54. var last_distance int = distance_cache[0]
  55. distance_cache[4] = last_distance - 1
  56. distance_cache[5] = last_distance + 1
  57. distance_cache[6] = last_distance - 2
  58. distance_cache[7] = last_distance + 2
  59. distance_cache[8] = last_distance - 3
  60. distance_cache[9] = last_distance + 3
  61. if num_distances > 10 {
  62. var next_last_distance int = distance_cache[1]
  63. distance_cache[10] = next_last_distance - 1
  64. distance_cache[11] = next_last_distance + 1
  65. distance_cache[12] = next_last_distance - 2
  66. distance_cache[13] = next_last_distance + 2
  67. distance_cache[14] = next_last_distance - 3
  68. distance_cache[15] = next_last_distance + 3
  69. }
  70. }
  71. }
  72. const literalByteScore = 135
  73. const distanceBitPenalty = 30
  74. /* Score must be positive after applying maximal penalty. */
  75. const scoreBase = (distanceBitPenalty * 8 * 8)
  76. /* Usually, we always choose the longest backward reference. This function
  77. allows for the exception of that rule.
  78. If we choose a backward reference that is further away, it will
  79. usually be coded with more bits. We approximate this by assuming
  80. log2(distance). If the distance can be expressed in terms of the
  81. last four distances, we use some heuristic constants to estimate
  82. the bits cost. For the first up to four literals we use the bit
  83. cost of the literals from the literal cost model, after that we
  84. use the average bit cost of the cost model.
  85. This function is used to sometimes discard a longer backward reference
  86. when it is not much longer and the bit cost for encoding it is more
  87. than the saved literals.
  88. backward_reference_offset MUST be positive. */
  89. func backwardReferenceScore(copy_length uint, backward_reference_offset uint) uint {
  90. return scoreBase + literalByteScore*uint(copy_length) - distanceBitPenalty*uint(log2FloorNonZero(backward_reference_offset))
  91. }
  92. func backwardReferenceScoreUsingLastDistance(copy_length uint) uint {
  93. return literalByteScore*uint(copy_length) + scoreBase + 15
  94. }
  95. func backwardReferencePenaltyUsingLastDistance(distance_short_code uint) uint {
  96. return uint(39) + ((0x1CA10 >> (distance_short_code & 0xE)) & 0xE)
  97. }
  98. func testStaticDictionaryItem(dictionary *encoderDictionary, item uint, data []byte, max_length uint, max_backward uint, max_distance uint, out *hasherSearchResult) bool {
  99. var len uint
  100. var word_idx uint
  101. var offset uint
  102. var matchlen uint
  103. var backward uint
  104. var score uint
  105. len = item & 0x1F
  106. word_idx = item >> 5
  107. offset = uint(dictionary.words.offsets_by_length[len]) + len*word_idx
  108. if len > max_length {
  109. return false
  110. }
  111. matchlen = findMatchLengthWithLimit(data, dictionary.words.data[offset:], uint(len))
  112. if matchlen+uint(dictionary.cutoffTransformsCount) <= len || matchlen == 0 {
  113. return false
  114. }
  115. {
  116. var cut uint = len - matchlen
  117. var transform_id uint = (cut << 2) + uint((dictionary.cutoffTransforms>>(cut*6))&0x3F)
  118. backward = max_backward + 1 + word_idx + (transform_id << dictionary.words.size_bits_by_length[len])
  119. }
  120. if backward > max_distance {
  121. return false
  122. }
  123. score = backwardReferenceScore(matchlen, backward)
  124. if score < out.score {
  125. return false
  126. }
  127. out.len = matchlen
  128. out.len_code_delta = int(len) - int(matchlen)
  129. out.distance = backward
  130. out.score = score
  131. return true
  132. }
  133. func searchInStaticDictionary(dictionary *encoderDictionary, handle hasherHandle, data []byte, max_length uint, max_backward uint, max_distance uint, out *hasherSearchResult, shallow bool) {
  134. var key uint
  135. var i uint
  136. var self *hasherCommon = handle.Common()
  137. if self.dict_num_matches < self.dict_num_lookups>>7 {
  138. return
  139. }
  140. key = uint(hash14(data) << 1)
  141. for i = 0; ; (func() { i++; key++ })() {
  142. var tmp uint
  143. if shallow {
  144. tmp = 1
  145. } else {
  146. tmp = 2
  147. }
  148. if i >= tmp {
  149. break
  150. }
  151. var item uint = uint(dictionary.hash_table[key])
  152. self.dict_num_lookups++
  153. if item != 0 {
  154. var item_matches bool = testStaticDictionaryItem(dictionary, item, data, max_length, max_backward, max_distance, out)
  155. if item_matches {
  156. self.dict_num_matches++
  157. }
  158. }
  159. }
  160. }
  161. type backwardMatch struct {
  162. distance uint32
  163. length_and_code uint32
  164. }
  165. func initBackwardMatch(self *backwardMatch, dist uint, len uint) {
  166. self.distance = uint32(dist)
  167. self.length_and_code = uint32(len << 5)
  168. }
  169. func initDictionaryBackwardMatch(self *backwardMatch, dist uint, len uint, len_code uint) {
  170. self.distance = uint32(dist)
  171. var tmp uint
  172. if len == len_code {
  173. tmp = 0
  174. } else {
  175. tmp = len_code
  176. }
  177. self.length_and_code = uint32(len<<5 | tmp)
  178. }
  179. func backwardMatchLength(self *backwardMatch) uint {
  180. return uint(self.length_and_code >> 5)
  181. }
  182. func backwardMatchLengthCode(self *backwardMatch) uint {
  183. var code uint = uint(self.length_and_code) & 31
  184. if code != 0 {
  185. return code
  186. } else {
  187. return backwardMatchLength(self)
  188. }
  189. }
  190. func hasherReset(handle hasherHandle) {
  191. if handle == nil {
  192. return
  193. }
  194. handle.Common().is_prepared_ = false
  195. }
  196. func newHasher(typ int) hasherHandle {
  197. switch typ {
  198. case 2:
  199. return &hashLongestMatchQuickly{
  200. bucketBits: 16,
  201. bucketSweep: 1,
  202. hashLen: 5,
  203. useDictionary: true,
  204. }
  205. case 3:
  206. return &hashLongestMatchQuickly{
  207. bucketBits: 16,
  208. bucketSweep: 2,
  209. hashLen: 5,
  210. useDictionary: false,
  211. }
  212. case 4:
  213. return &hashLongestMatchQuickly{
  214. bucketBits: 17,
  215. bucketSweep: 4,
  216. hashLen: 5,
  217. useDictionary: true,
  218. }
  219. case 5:
  220. return new(h5)
  221. case 6:
  222. return new(h6)
  223. case 10:
  224. return new(h10)
  225. case 35:
  226. return &hashComposite{
  227. ha: newHasher(3),
  228. hb: &hashRolling{jump: 4},
  229. }
  230. case 40:
  231. return &hashForgetfulChain{
  232. bucketBits: 15,
  233. numBanks: 1,
  234. bankBits: 16,
  235. numLastDistancesToCheck: 4,
  236. }
  237. case 41:
  238. return &hashForgetfulChain{
  239. bucketBits: 15,
  240. numBanks: 1,
  241. bankBits: 16,
  242. numLastDistancesToCheck: 10,
  243. }
  244. case 42:
  245. return &hashForgetfulChain{
  246. bucketBits: 15,
  247. numBanks: 512,
  248. bankBits: 9,
  249. numLastDistancesToCheck: 16,
  250. }
  251. case 54:
  252. return &hashLongestMatchQuickly{
  253. bucketBits: 20,
  254. bucketSweep: 4,
  255. hashLen: 7,
  256. useDictionary: false,
  257. }
  258. case 55:
  259. return &hashComposite{
  260. ha: newHasher(54),
  261. hb: &hashRolling{jump: 4},
  262. }
  263. case 65:
  264. return &hashComposite{
  265. ha: newHasher(6),
  266. hb: &hashRolling{jump: 1},
  267. }
  268. }
  269. panic(fmt.Sprintf("unknown hasher type: %d", typ))
  270. }
  271. func hasherSetup(handle *hasherHandle, params *encoderParams, data []byte, position uint, input_size uint, is_last bool) {
  272. var self hasherHandle = nil
  273. var common *hasherCommon = nil
  274. var one_shot bool = (position == 0 && is_last)
  275. if *handle == nil {
  276. chooseHasher(params, &params.hasher)
  277. self = newHasher(params.hasher.type_)
  278. *handle = self
  279. common = self.Common()
  280. common.params = params.hasher
  281. self.Initialize(params)
  282. }
  283. self = *handle
  284. common = self.Common()
  285. if !common.is_prepared_ {
  286. self.Prepare(one_shot, input_size, data)
  287. if position == 0 {
  288. common.dict_num_lookups = 0
  289. common.dict_num_matches = 0
  290. }
  291. common.is_prepared_ = true
  292. }
  293. }
  294. func initOrStitchToPreviousBlock(handle *hasherHandle, data []byte, mask uint, params *encoderParams, position uint, input_size uint, is_last bool) {
  295. var self hasherHandle
  296. hasherSetup(handle, params, data, position, input_size, is_last)
  297. self = *handle
  298. self.StitchToPreviousBlock(input_size, position, data, mask)
  299. }