hash_longest_match_inc.h 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277
  1. /* NOLINT(build/header_guard) */
  2. /* Copyright 2010 Google Inc. All Rights Reserved.
  3. Distributed under MIT license.
  4. See file LICENSE for detail or copy at https://opensource.org/licenses/MIT
  5. */
  6. /* template parameters: FN */
  7. /* A (forgetful) hash table to the data seen by the compressor, to
  8. help create backward references to previous data.
  9. This is a hash map of fixed size (bucket_size_) to a ring buffer of
  10. fixed size (block_size_). The ring buffer contains the last block_size_
  11. index positions of the given hash key in the compressed data. */
  12. #define HashLongestMatch HASHER()
  13. static BROTLI_INLINE size_t FN(HashTypeLength)(void) { return 4; }
  14. static BROTLI_INLINE size_t FN(StoreLookahead)(void) { return 4; }
  15. /* HashBytes is the function that chooses the bucket to place the address in. */
  16. static uint32_t FN(HashBytes)(
  17. const uint8_t* BROTLI_RESTRICT data, const int shift) {
  18. uint32_t h = BROTLI_UNALIGNED_LOAD32LE(data) * kHashMul32;
  19. /* The higher bits contain more mixture from the multiplication,
  20. so we take our results from there. */
  21. return (uint32_t)(h >> shift);
  22. }
  23. typedef struct HashLongestMatch {
  24. /* Number of hash buckets. */
  25. size_t bucket_size_;
  26. /* Only block_size_ newest backward references are kept,
  27. and the older are forgotten. */
  28. size_t block_size_;
  29. /* Left-shift for computing hash bucket index from hash value. */
  30. int hash_shift_;
  31. /* Mask for accessing entries in a block (in a ring-buffer manner). */
  32. uint32_t block_mask_;
  33. int block_bits_;
  34. int num_last_distances_to_check_;
  35. /* Shortcuts. */
  36. HasherCommon* common_;
  37. /* --- Dynamic size members --- */
  38. /* Number of entries in a particular bucket. */
  39. uint16_t* num_; /* uint16_t[bucket_size]; */
  40. /* Buckets containing block_size_ of backward references. */
  41. uint32_t* buckets_; /* uint32_t[bucket_size * block_size]; */
  42. } HashLongestMatch;
  43. static void FN(Initialize)(
  44. HasherCommon* common, HashLongestMatch* BROTLI_RESTRICT self,
  45. const BrotliEncoderParams* params) {
  46. self->common_ = common;
  47. BROTLI_UNUSED(params);
  48. self->hash_shift_ = 32 - common->params.bucket_bits;
  49. self->bucket_size_ = (size_t)1 << common->params.bucket_bits;
  50. self->block_size_ = (size_t)1 << common->params.block_bits;
  51. self->block_mask_ = (uint32_t)(self->block_size_ - 1);
  52. self->num_ = (uint16_t*)common->extra[0];
  53. self->buckets_ = (uint32_t*)common->extra[1];
  54. self->block_bits_ = common->params.block_bits;
  55. self->num_last_distances_to_check_ =
  56. common->params.num_last_distances_to_check;
  57. }
  58. static void FN(Prepare)(
  59. HashLongestMatch* BROTLI_RESTRICT self, BROTLI_BOOL one_shot,
  60. size_t input_size, const uint8_t* BROTLI_RESTRICT data) {
  61. uint16_t* BROTLI_RESTRICT num = self->num_;
  62. /* Partial preparation is 100 times slower (per socket). */
  63. size_t partial_prepare_threshold = self->bucket_size_ >> 6;
  64. if (one_shot && input_size <= partial_prepare_threshold) {
  65. size_t i;
  66. for (i = 0; i < input_size; ++i) {
  67. const uint32_t key = FN(HashBytes)(&data[i], self->hash_shift_);
  68. num[key] = 0;
  69. }
  70. } else {
  71. memset(num, 0, self->bucket_size_ * sizeof(num[0]));
  72. }
  73. }
  74. static BROTLI_INLINE void FN(HashMemAllocInBytes)(
  75. const BrotliEncoderParams* params, BROTLI_BOOL one_shot,
  76. size_t input_size, size_t* alloc_size) {
  77. size_t bucket_size = (size_t)1 << params->hasher.bucket_bits;
  78. size_t block_size = (size_t)1 << params->hasher.block_bits;
  79. BROTLI_UNUSED(one_shot);
  80. BROTLI_UNUSED(input_size);
  81. alloc_size[0] = sizeof(uint16_t) * bucket_size;
  82. alloc_size[1] = sizeof(uint32_t) * bucket_size * block_size;
  83. }
  84. /* Look at 4 bytes at &data[ix & mask].
  85. Compute a hash from these, and store the value of ix at that position. */
  86. static BROTLI_INLINE void FN(Store)(
  87. HashLongestMatch* BROTLI_RESTRICT self, const uint8_t* BROTLI_RESTRICT data,
  88. const size_t mask, const size_t ix) {
  89. uint16_t* BROTLI_RESTRICT num = self->num_;
  90. uint32_t* BROTLI_RESTRICT buckets = self->buckets_;
  91. const uint32_t key = FN(HashBytes)(&data[ix & mask], self->hash_shift_);
  92. const size_t minor_ix = num[key] & self->block_mask_;
  93. const size_t offset = minor_ix + (key << self->block_bits_);
  94. ++num[key];
  95. buckets[offset] = (uint32_t)ix;
  96. }
  97. static BROTLI_INLINE void FN(StoreRange)(HashLongestMatch* BROTLI_RESTRICT self,
  98. const uint8_t* BROTLI_RESTRICT data, const size_t mask,
  99. const size_t ix_start, const size_t ix_end) {
  100. size_t i;
  101. for (i = ix_start; i < ix_end; ++i) {
  102. FN(Store)(self, data, mask, i);
  103. }
  104. }
  105. static BROTLI_INLINE void FN(StitchToPreviousBlock)(
  106. HashLongestMatch* BROTLI_RESTRICT self,
  107. size_t num_bytes, size_t position, const uint8_t* ringbuffer,
  108. size_t ringbuffer_mask) {
  109. if (num_bytes >= FN(HashTypeLength)() - 1 && position >= 3) {
  110. /* Prepare the hashes for three last bytes of the last write.
  111. These could not be calculated before, since they require knowledge
  112. of both the previous and the current block. */
  113. FN(Store)(self, ringbuffer, ringbuffer_mask, position - 3);
  114. FN(Store)(self, ringbuffer, ringbuffer_mask, position - 2);
  115. FN(Store)(self, ringbuffer, ringbuffer_mask, position - 1);
  116. }
  117. }
  118. static BROTLI_INLINE void FN(PrepareDistanceCache)(
  119. HashLongestMatch* BROTLI_RESTRICT self,
  120. int* BROTLI_RESTRICT distance_cache) {
  121. PrepareDistanceCache(distance_cache, self->num_last_distances_to_check_);
  122. }
  123. /* Find a longest backward match of &data[cur_ix] up to the length of
  124. max_length and stores the position cur_ix in the hash table.
  125. REQUIRES: FN(PrepareDistanceCache) must be invoked for current distance cache
  126. values; if this method is invoked repeatedly with the same distance
  127. cache values, it is enough to invoke FN(PrepareDistanceCache) once.
  128. Does not look for matches longer than max_length.
  129. Does not look for matches further away than max_backward.
  130. Writes the best match into |out|.
  131. |out|->score is updated only if a better match is found. */
  132. static BROTLI_INLINE void FN(FindLongestMatch)(
  133. HashLongestMatch* BROTLI_RESTRICT self,
  134. const BrotliEncoderDictionary* dictionary,
  135. const uint8_t* BROTLI_RESTRICT data, const size_t ring_buffer_mask,
  136. const int* BROTLI_RESTRICT distance_cache, const size_t cur_ix,
  137. const size_t max_length, const size_t max_backward,
  138. const size_t dictionary_distance, const size_t max_distance,
  139. HasherSearchResult* BROTLI_RESTRICT out) {
  140. uint16_t* BROTLI_RESTRICT num = self->num_;
  141. uint32_t* BROTLI_RESTRICT buckets = self->buckets_;
  142. const size_t cur_ix_masked = cur_ix & ring_buffer_mask;
  143. /* Don't accept a short copy from far away. */
  144. score_t min_score = out->score;
  145. score_t best_score = out->score;
  146. size_t best_len = out->len;
  147. size_t i;
  148. /* Precalculate the hash key and prefetch the bucket. */
  149. const uint32_t key =
  150. FN(HashBytes)(&data[cur_ix_masked], self->hash_shift_);
  151. uint32_t* BROTLI_RESTRICT bucket = &buckets[key << self->block_bits_];
  152. PREFETCH_L1(bucket);
  153. if (self->block_bits_ > 4) PREFETCH_L1(bucket + 16);
  154. out->len = 0;
  155. out->len_code_delta = 0;
  156. BROTLI_DCHECK(cur_ix_masked + max_length <= ring_buffer_mask);
  157. /* Try last distance first. */
  158. for (i = 0; i < (size_t)self->num_last_distances_to_check_; ++i) {
  159. const size_t backward = (size_t)distance_cache[i];
  160. size_t prev_ix = (size_t)(cur_ix - backward);
  161. if (prev_ix >= cur_ix) {
  162. continue;
  163. }
  164. if (BROTLI_PREDICT_FALSE(backward > max_backward)) {
  165. continue;
  166. }
  167. prev_ix &= ring_buffer_mask;
  168. if (cur_ix_masked + best_len > ring_buffer_mask) {
  169. break;
  170. }
  171. if (prev_ix + best_len > ring_buffer_mask ||
  172. data[cur_ix_masked + best_len] != data[prev_ix + best_len]) {
  173. continue;
  174. }
  175. {
  176. const size_t len = FindMatchLengthWithLimit(&data[prev_ix],
  177. &data[cur_ix_masked],
  178. max_length);
  179. if (len >= 3 || (len == 2 && i < 2)) {
  180. /* Comparing for >= 2 does not change the semantics, but just saves for
  181. a few unnecessary binary logarithms in backward reference score,
  182. since we are not interested in such short matches. */
  183. score_t score = BackwardReferenceScoreUsingLastDistance(len);
  184. if (best_score < score) {
  185. if (i != 0) score -= BackwardReferencePenaltyUsingLastDistance(i);
  186. if (best_score < score) {
  187. best_score = score;
  188. best_len = len;
  189. out->len = best_len;
  190. out->distance = backward;
  191. out->score = best_score;
  192. }
  193. }
  194. }
  195. }
  196. }
  197. /* we require matches of len >4, so increase best_len to 3, so we can compare
  198. * 4 bytes all the time. */
  199. if (best_len < 3) {
  200. best_len = 3;
  201. }
  202. {
  203. const size_t down =
  204. (num[key] > self->block_size_) ? (num[key] - self->block_size_) : 0u;
  205. for (i = num[key]; i > down;) {
  206. size_t prev_ix = bucket[--i & self->block_mask_];
  207. const size_t backward = cur_ix - prev_ix;
  208. if (BROTLI_PREDICT_FALSE(backward > max_backward)) {
  209. break;
  210. }
  211. prev_ix &= ring_buffer_mask;
  212. if (cur_ix_masked + best_len > ring_buffer_mask) {
  213. break;
  214. }
  215. if (prev_ix + best_len > ring_buffer_mask ||
  216. /* compare 4 bytes ending at best_len + 1 */
  217. BrotliUnalignedRead32(&data[cur_ix_masked + best_len - 3]) !=
  218. BrotliUnalignedRead32(&data[prev_ix + best_len - 3])) {
  219. continue;
  220. }
  221. {
  222. const size_t len = FindMatchLengthWithLimit(&data[prev_ix],
  223. &data[cur_ix_masked],
  224. max_length);
  225. if (len >= 4) {
  226. /* Comparing for >= 3 does not change the semantics, but just saves
  227. for a few unnecessary binary logarithms in backward reference
  228. score, since we are not interested in such short matches. */
  229. score_t score = BackwardReferenceScore(len, backward);
  230. if (best_score < score) {
  231. best_score = score;
  232. best_len = len;
  233. out->len = best_len;
  234. out->distance = backward;
  235. out->score = best_score;
  236. }
  237. }
  238. }
  239. }
  240. bucket[num[key] & self->block_mask_] = (uint32_t)cur_ix;
  241. ++num[key];
  242. }
  243. if (min_score == out->score) {
  244. SearchInStaticDictionary(dictionary,
  245. self->common_, &data[cur_ix_masked], max_length, dictionary_distance,
  246. max_distance, out, BROTLI_FALSE);
  247. }
  248. }
  249. #undef HashLongestMatch