hash_longest_match_inc.h 9.8 KB

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