hash_longest_match_inc.h 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286
  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, BUCKET_BITS, BLOCK_BITS,
  7. NUM_LAST_DISTANCES_TO_CHECK */
  8. /* A (forgetful) hash table to the data seen by the compressor, to
  9. help create backward references to previous data.
  10. This is a hash map of fixed size (BUCKET_SIZE) to a ring buffer of
  11. fixed size (BLOCK_SIZE). The ring buffer contains the last BLOCK_SIZE
  12. index positions of the given hash key in the compressed data. */
  13. #define HashLongestMatch HASHER()
  14. /* Number of hash buckets. */
  15. #define BUCKET_SIZE (1 << BUCKET_BITS)
  16. /* Only BLOCK_SIZE newest backward references are kept,
  17. and the older are forgotten. */
  18. #define BLOCK_SIZE (1u << BLOCK_BITS)
  19. /* Mask for accessing entries in a block (in a ringbuffer manner). */
  20. #define BLOCK_MASK ((1 << BLOCK_BITS) - 1)
  21. #define HASH_MAP_SIZE (2 << BUCKET_BITS)
  22. static BROTLI_INLINE size_t FN(HashTypeLength)(void) { return 4; }
  23. static BROTLI_INLINE size_t FN(StoreLookahead)(void) { return 4; }
  24. /* HashBytes is the function that chooses the bucket to place
  25. the address in. The HashLongestMatch and HashLongestMatchQuickly
  26. classes have separate, different implementations of hashing. */
  27. static uint32_t FN(HashBytes)(const uint8_t *data) {
  28. uint32_t h = BROTLI_UNALIGNED_LOAD32(data) * kHashMul32;
  29. /* The higher bits contain more mixture from the multiplication,
  30. so we take our results from there. */
  31. return h >> (32 - BUCKET_BITS);
  32. }
  33. typedef struct HashLongestMatch {
  34. /* Number of entries in a particular bucket. */
  35. uint16_t num_[BUCKET_SIZE];
  36. /* Buckets containing BLOCK_SIZE of backward references. */
  37. uint32_t buckets_[BLOCK_SIZE << BUCKET_BITS];
  38. /* True if num_ array needs to be initialized. */
  39. int is_dirty_;
  40. size_t num_dict_lookups_;
  41. size_t num_dict_matches_;
  42. } HashLongestMatch;
  43. static void FN(Reset)(HashLongestMatch* self) {
  44. self->is_dirty_ = 1;
  45. self->num_dict_lookups_ = 0;
  46. self->num_dict_matches_ = 0;
  47. }
  48. static void FN(InitEmpty)(HashLongestMatch* self) {
  49. if (self->is_dirty_) {
  50. memset(self->num_, 0, sizeof(self->num_));
  51. self->is_dirty_ = 0;
  52. }
  53. }
  54. static void FN(InitForData)(HashLongestMatch* self, const uint8_t* data,
  55. size_t num) {
  56. size_t i;
  57. for (i = 0; i < num; ++i) {
  58. const uint32_t key = FN(HashBytes)(&data[i]);
  59. self->num_[key] = 0;
  60. }
  61. if (num != 0) {
  62. self->is_dirty_ = 0;
  63. }
  64. }
  65. static void FN(Init)(
  66. MemoryManager* m, HashLongestMatch* self, const uint8_t* data, int lgwin,
  67. size_t position, size_t bytes, int is_last) {
  68. /* Choose which init method is faster.
  69. Init() is about 100 times faster than InitForData(). */
  70. const size_t kMaxBytesForPartialHashInit = HASH_MAP_SIZE >> 7;
  71. BROTLI_UNUSED(m);
  72. BROTLI_UNUSED(lgwin);
  73. if (position == 0 && is_last && bytes <= kMaxBytesForPartialHashInit) {
  74. FN(InitForData)(self, data, bytes);
  75. } else {
  76. FN(InitEmpty)(self);
  77. }
  78. }
  79. /* Look at 4 bytes at &data[ix & mask].
  80. Compute a hash from these, and store the value of ix at that position. */
  81. static BROTLI_INLINE void FN(Store)(HashLongestMatch* self, const uint8_t *data,
  82. const size_t mask, const size_t ix) {
  83. const uint32_t key = FN(HashBytes)(&data[ix & mask]);
  84. const size_t minor_ix = self->num_[key] & BLOCK_MASK;
  85. self->buckets_[minor_ix + (key << BLOCK_BITS)] = (uint32_t)ix;
  86. ++self->num_[key];
  87. }
  88. static BROTLI_INLINE void FN(StoreRange)(HashLongestMatch* self,
  89. const uint8_t *data, const size_t mask, const size_t ix_start,
  90. const size_t ix_end) {
  91. size_t i;
  92. for (i = ix_start; i < ix_end; ++i) {
  93. FN(Store)(self, data, mask, i);
  94. }
  95. }
  96. static BROTLI_INLINE void FN(StitchToPreviousBlock)(HashLongestMatch* self,
  97. size_t num_bytes, size_t position, const uint8_t* ringbuffer,
  98. size_t ringbuffer_mask) {
  99. if (num_bytes >= FN(HashTypeLength)() - 1 && position >= 3) {
  100. /* Prepare the hashes for three last bytes of the last write.
  101. These could not be calculated before, since they require knowledge
  102. of both the previous and the current block. */
  103. FN(Store)(self, ringbuffer, ringbuffer_mask, position - 3);
  104. FN(Store)(self, ringbuffer, ringbuffer_mask, position - 2);
  105. FN(Store)(self, ringbuffer, ringbuffer_mask, position - 1);
  106. }
  107. }
  108. /* Find a longest backward match of &data[cur_ix] up to the length of
  109. max_length and stores the position cur_ix in the hash table.
  110. Does not look for matches longer than max_length.
  111. Does not look for matches further away than max_backward.
  112. Writes the best found match length into best_len_out.
  113. Writes the index (&data[index]) offset from the start of the best match
  114. into best_distance_out.
  115. Write the score of the best match into best_score_out.
  116. Returns 1 when match is found, otherwise 0. */
  117. static BROTLI_INLINE int FN(FindLongestMatch)(HashLongestMatch* self,
  118. const uint8_t* BROTLI_RESTRICT data, const size_t ring_buffer_mask,
  119. const int* BROTLI_RESTRICT distance_cache, const size_t cur_ix,
  120. const size_t max_length, const size_t max_backward,
  121. size_t* BROTLI_RESTRICT best_len_out,
  122. size_t* BROTLI_RESTRICT best_len_code_out,
  123. size_t* BROTLI_RESTRICT best_distance_out,
  124. double* BROTLI_RESTRICT best_score_out) {
  125. const size_t cur_ix_masked = cur_ix & ring_buffer_mask;
  126. int is_match_found = 0;
  127. /* Don't accept a short copy from far away. */
  128. double best_score = *best_score_out;
  129. size_t best_len = *best_len_out;
  130. size_t i;
  131. *best_len_code_out = 0;
  132. *best_len_out = 0;
  133. /* Try last distance first. */
  134. for (i = 0; i < NUM_LAST_DISTANCES_TO_CHECK; ++i) {
  135. const size_t idx = kDistanceCacheIndex[i];
  136. const size_t backward =
  137. (size_t)(distance_cache[idx] + kDistanceCacheOffset[i]);
  138. size_t prev_ix = (size_t)(cur_ix - backward);
  139. if (prev_ix >= cur_ix) {
  140. continue;
  141. }
  142. if (PREDICT_FALSE(backward > max_backward)) {
  143. continue;
  144. }
  145. prev_ix &= ring_buffer_mask;
  146. if (cur_ix_masked + best_len > ring_buffer_mask ||
  147. prev_ix + best_len > ring_buffer_mask ||
  148. data[cur_ix_masked + best_len] != data[prev_ix + best_len]) {
  149. continue;
  150. }
  151. {
  152. const size_t len = FindMatchLengthWithLimit(&data[prev_ix],
  153. &data[cur_ix_masked],
  154. max_length);
  155. if (len >= 3 || (len == 2 && i < 2)) {
  156. /* Comparing for >= 2 does not change the semantics, but just saves for
  157. a few unnecessary binary logarithms in backward reference score,
  158. since we are not interested in such short matches. */
  159. double score = BackwardReferenceScoreUsingLastDistance(len, i);
  160. if (best_score < score) {
  161. best_score = score;
  162. best_len = len;
  163. *best_len_out = best_len;
  164. *best_len_code_out = best_len;
  165. *best_distance_out = backward;
  166. *best_score_out = best_score;
  167. is_match_found = 1;
  168. }
  169. }
  170. }
  171. }
  172. {
  173. const uint32_t key = FN(HashBytes)(&data[cur_ix_masked]);
  174. const uint32_t * BROTLI_RESTRICT const bucket =
  175. &self->buckets_[key << BLOCK_BITS];
  176. const size_t down =
  177. (self->num_[key] > BLOCK_SIZE) ? (self->num_[key] - BLOCK_SIZE) : 0u;
  178. for (i = self->num_[key]; i > down;) {
  179. size_t prev_ix = bucket[--i & BLOCK_MASK];
  180. const size_t backward = cur_ix - prev_ix;
  181. if (PREDICT_FALSE(backward == 0 || backward > max_backward)) {
  182. break;
  183. }
  184. prev_ix &= ring_buffer_mask;
  185. if (cur_ix_masked + best_len > ring_buffer_mask ||
  186. prev_ix + best_len > ring_buffer_mask ||
  187. data[cur_ix_masked + best_len] != data[prev_ix + best_len]) {
  188. continue;
  189. }
  190. {
  191. const size_t len = FindMatchLengthWithLimit(&data[prev_ix],
  192. &data[cur_ix_masked],
  193. max_length);
  194. if (len >= 4) {
  195. /* Comparing for >= 3 does not change the semantics, but just saves
  196. for a few unnecessary binary logarithms in backward reference
  197. score, since we are not interested in such short matches. */
  198. double score = BackwardReferenceScore(len, backward);
  199. if (best_score < score) {
  200. best_score = score;
  201. best_len = len;
  202. *best_len_out = best_len;
  203. *best_len_code_out = best_len;
  204. *best_distance_out = backward;
  205. *best_score_out = best_score;
  206. is_match_found = 1;
  207. }
  208. }
  209. }
  210. }
  211. self->buckets_[(key << BLOCK_BITS) + (self->num_[key] & BLOCK_MASK)] =
  212. (uint32_t)cur_ix;
  213. ++self->num_[key];
  214. }
  215. if (!is_match_found &&
  216. self->num_dict_matches_ >= (self->num_dict_lookups_ >> 7)) {
  217. size_t dict_key = Hash14(&data[cur_ix_masked]) << 1;
  218. int k;
  219. for (k = 0; k < 2; ++k, ++dict_key) {
  220. const uint16_t v = kStaticDictionaryHash[dict_key];
  221. ++self->num_dict_lookups_;
  222. if (v > 0) {
  223. const size_t len = v & 31;
  224. const size_t dist = v >> 5;
  225. const size_t offset =
  226. kBrotliDictionaryOffsetsByLength[len] + len * dist;
  227. if (len <= max_length) {
  228. const size_t matchlen =
  229. FindMatchLengthWithLimit(&data[cur_ix_masked],
  230. &kBrotliDictionary[offset], len);
  231. if (matchlen + kCutoffTransformsCount > len && matchlen > 0) {
  232. const size_t transform_id = kCutoffTransforms[len - matchlen];
  233. const size_t transform_step =
  234. (size_t)1 << kBrotliDictionarySizeBitsByLength[len];
  235. const size_t word_id = dist + transform_id * transform_step;
  236. const size_t backward = max_backward + word_id + 1;
  237. double score = BackwardReferenceScore(matchlen, backward);
  238. if (best_score < score) {
  239. ++self->num_dict_matches_;
  240. best_score = score;
  241. best_len = matchlen;
  242. *best_len_out = best_len;
  243. *best_len_code_out = len;
  244. *best_distance_out = backward;
  245. *best_score_out = best_score;
  246. is_match_found = 1;
  247. }
  248. }
  249. }
  250. }
  251. }
  252. }
  253. return is_match_found;
  254. }
  255. #undef HASH_MAP_SIZE
  256. #undef BLOCK_MASK
  257. #undef BLOCK_SIZE
  258. #undef BUCKET_SIZE
  259. #undef HashLongestMatch