hash.h 24 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755
  1. /* Copyright 2010 Google Inc. All Rights Reserved.
  2. Distributed under MIT license.
  3. See file LICENSE for detail or copy at https://opensource.org/licenses/MIT
  4. */
  5. /* A (forgetful) hash table to the data seen by the compressor, to
  6. help create backward references to previous data. */
  7. #ifndef BROTLI_ENC_HASH_H_
  8. #define BROTLI_ENC_HASH_H_
  9. #include <stdlib.h> /* exit */
  10. #include <string.h> /* memcmp, memset */
  11. #include <brotli/types.h>
  12. #include "../common/constants.h"
  13. #include "../common/dictionary.h"
  14. #include "../common/platform.h"
  15. #include "compound_dictionary.h"
  16. #include "encoder_dict.h"
  17. #include "fast_log.h"
  18. #include "find_match_length.h"
  19. #include "matching_tag_mask.h"
  20. #include "memory.h"
  21. #include "quality.h"
  22. #include "static_dict.h"
  23. #if defined(__cplusplus) || defined(c_plusplus)
  24. extern "C" {
  25. #endif
  26. typedef struct {
  27. /**
  28. * Dynamically allocated areas; regular hasher uses one or two allocations;
  29. * "composite" hasher uses up to 4 allocations.
  30. */
  31. void* extra[4];
  32. /**
  33. * False before the fisrt invocation of HasherSetup (where "extra" memory)
  34. * is allocated.
  35. */
  36. BROTLI_BOOL is_setup_;
  37. size_t dict_num_lookups;
  38. size_t dict_num_matches;
  39. BrotliHasherParams params;
  40. /**
  41. * False if hasher needs to be "prepared" before use (before the first
  42. * invocation of HasherSetup or after HasherReset). "preparation" is hasher
  43. * data initialization (using input ringbuffer).
  44. */
  45. BROTLI_BOOL is_prepared_;
  46. } HasherCommon;
  47. #define score_t size_t
  48. static const uint32_t kCutoffTransformsCount = 10;
  49. /* 0, 12, 27, 23, 42, 63, 56, 48, 59, 64 */
  50. /* 0+0, 4+8, 8+19, 12+11, 16+26, 20+43, 24+32, 28+20, 32+27, 36+28 */
  51. static const uint64_t kCutoffTransforms =
  52. BROTLI_MAKE_UINT64_T(0x071B520A, 0xDA2D3200);
  53. typedef struct HasherSearchResult {
  54. size_t len;
  55. size_t distance;
  56. score_t score;
  57. int len_code_delta; /* == len_code - len */
  58. } HasherSearchResult;
  59. /* kHashMul32 multiplier has these properties:
  60. * The multiplier must be odd. Otherwise we may lose the highest bit.
  61. * No long streaks of ones or zeros.
  62. * There is no effort to ensure that it is a prime, the oddity is enough
  63. for this use.
  64. * The number has been tuned heuristically against compression benchmarks. */
  65. static const uint32_t kHashMul32 = 0x1E35A7BD;
  66. static const uint64_t kHashMul64 =
  67. BROTLI_MAKE_UINT64_T(0x1FE35A7Bu, 0xD3579BD3u);
  68. static BROTLI_INLINE uint32_t Hash14(const uint8_t* data) {
  69. uint32_t h = BROTLI_UNALIGNED_LOAD32LE(data) * kHashMul32;
  70. /* The higher bits contain more mixture from the multiplication,
  71. so we take our results from there. */
  72. return h >> (32 - 14);
  73. }
  74. static BROTLI_INLINE void PrepareDistanceCache(
  75. int* BROTLI_RESTRICT distance_cache, const int num_distances) {
  76. if (num_distances > 4) {
  77. int last_distance = distance_cache[0];
  78. distance_cache[4] = last_distance - 1;
  79. distance_cache[5] = last_distance + 1;
  80. distance_cache[6] = last_distance - 2;
  81. distance_cache[7] = last_distance + 2;
  82. distance_cache[8] = last_distance - 3;
  83. distance_cache[9] = last_distance + 3;
  84. if (num_distances > 10) {
  85. int next_last_distance = distance_cache[1];
  86. distance_cache[10] = next_last_distance - 1;
  87. distance_cache[11] = next_last_distance + 1;
  88. distance_cache[12] = next_last_distance - 2;
  89. distance_cache[13] = next_last_distance + 2;
  90. distance_cache[14] = next_last_distance - 3;
  91. distance_cache[15] = next_last_distance + 3;
  92. }
  93. }
  94. }
  95. #define BROTLI_LITERAL_BYTE_SCORE 135
  96. #define BROTLI_DISTANCE_BIT_PENALTY 30
  97. /* Score must be positive after applying maximal penalty. */
  98. #define BROTLI_SCORE_BASE (BROTLI_DISTANCE_BIT_PENALTY * 8 * sizeof(size_t))
  99. /* Usually, we always choose the longest backward reference. This function
  100. allows for the exception of that rule.
  101. If we choose a backward reference that is further away, it will
  102. usually be coded with more bits. We approximate this by assuming
  103. log2(distance). If the distance can be expressed in terms of the
  104. last four distances, we use some heuristic constants to estimate
  105. the bits cost. For the first up to four literals we use the bit
  106. cost of the literals from the literal cost model, after that we
  107. use the average bit cost of the cost model.
  108. This function is used to sometimes discard a longer backward reference
  109. when it is not much longer and the bit cost for encoding it is more
  110. than the saved literals.
  111. backward_reference_offset MUST be positive. */
  112. static BROTLI_INLINE score_t BackwardReferenceScore(
  113. size_t copy_length, size_t backward_reference_offset) {
  114. return BROTLI_SCORE_BASE + BROTLI_LITERAL_BYTE_SCORE * (score_t)copy_length -
  115. BROTLI_DISTANCE_BIT_PENALTY * Log2FloorNonZero(backward_reference_offset);
  116. }
  117. static BROTLI_INLINE score_t BackwardReferenceScoreUsingLastDistance(
  118. size_t copy_length) {
  119. return BROTLI_LITERAL_BYTE_SCORE * (score_t)copy_length +
  120. BROTLI_SCORE_BASE + 15;
  121. }
  122. static BROTLI_INLINE score_t BackwardReferencePenaltyUsingLastDistance(
  123. size_t distance_short_code) {
  124. return (score_t)39 + ((0x1CA10 >> (distance_short_code & 0xE)) & 0xE);
  125. }
  126. static BROTLI_INLINE BROTLI_BOOL TestStaticDictionaryItem(
  127. const BrotliEncoderDictionary* dictionary, size_t len, size_t word_idx,
  128. const uint8_t* data, size_t max_length, size_t max_backward,
  129. size_t max_distance, HasherSearchResult* out) {
  130. size_t offset;
  131. size_t matchlen;
  132. size_t backward;
  133. score_t score;
  134. offset = dictionary->words->offsets_by_length[len] + len * word_idx;
  135. if (len > max_length) {
  136. return BROTLI_FALSE;
  137. }
  138. matchlen =
  139. FindMatchLengthWithLimit(data, &dictionary->words->data[offset], len);
  140. if (matchlen + dictionary->cutoffTransformsCount <= len || matchlen == 0) {
  141. return BROTLI_FALSE;
  142. }
  143. {
  144. size_t cut = len - matchlen;
  145. size_t transform_id = (cut << 2) +
  146. (size_t)((dictionary->cutoffTransforms >> (cut * 6)) & 0x3F);
  147. backward = max_backward + 1 + word_idx +
  148. (transform_id << dictionary->words->size_bits_by_length[len]);
  149. }
  150. if (backward > max_distance) {
  151. return BROTLI_FALSE;
  152. }
  153. score = BackwardReferenceScore(matchlen, backward);
  154. if (score < out->score) {
  155. return BROTLI_FALSE;
  156. }
  157. out->len = matchlen;
  158. out->len_code_delta = (int)len - (int)matchlen;
  159. out->distance = backward;
  160. out->score = score;
  161. return BROTLI_TRUE;
  162. }
  163. static BROTLI_INLINE void SearchInStaticDictionary(
  164. const BrotliEncoderDictionary* dictionary,
  165. HasherCommon* common, const uint8_t* data, size_t max_length,
  166. size_t max_backward, size_t max_distance,
  167. HasherSearchResult* out, BROTLI_BOOL shallow) {
  168. size_t key;
  169. size_t i;
  170. if (common->dict_num_matches < (common->dict_num_lookups >> 7)) {
  171. return;
  172. }
  173. key = Hash14(data) << 1;
  174. for (i = 0; i < (shallow ? 1u : 2u); ++i, ++key) {
  175. common->dict_num_lookups++;
  176. if (dictionary->hash_table_lengths[key] != 0) {
  177. BROTLI_BOOL item_matches = TestStaticDictionaryItem(
  178. dictionary, dictionary->hash_table_lengths[key],
  179. dictionary->hash_table_words[key], data,
  180. max_length, max_backward, max_distance, out);
  181. if (item_matches) {
  182. common->dict_num_matches++;
  183. }
  184. }
  185. }
  186. }
  187. typedef struct BackwardMatch {
  188. uint32_t distance;
  189. uint32_t length_and_code;
  190. } BackwardMatch;
  191. static BROTLI_INLINE void InitBackwardMatch(BackwardMatch* self,
  192. size_t dist, size_t len) {
  193. self->distance = (uint32_t)dist;
  194. self->length_and_code = (uint32_t)(len << 5);
  195. }
  196. static BROTLI_INLINE void InitDictionaryBackwardMatch(BackwardMatch* self,
  197. size_t dist, size_t len, size_t len_code) {
  198. self->distance = (uint32_t)dist;
  199. self->length_and_code =
  200. (uint32_t)((len << 5) | (len == len_code ? 0 : len_code));
  201. }
  202. static BROTLI_INLINE size_t BackwardMatchLength(const BackwardMatch* self) {
  203. return self->length_and_code >> 5;
  204. }
  205. static BROTLI_INLINE size_t BackwardMatchLengthCode(const BackwardMatch* self) {
  206. size_t code = self->length_and_code & 31;
  207. return code ? code : BackwardMatchLength(self);
  208. }
  209. #define EXPAND_CAT(a, b) CAT(a, b)
  210. #define CAT(a, b) a ## b
  211. #define FN(X) EXPAND_CAT(X, HASHER())
  212. #define HASHER() H10
  213. #define BUCKET_BITS 17
  214. #define MAX_TREE_SEARCH_DEPTH 64
  215. #define MAX_TREE_COMP_LENGTH 128
  216. #include "hash_to_binary_tree_inc.h" /* NOLINT(build/include) */
  217. #undef MAX_TREE_SEARCH_DEPTH
  218. #undef MAX_TREE_COMP_LENGTH
  219. #undef BUCKET_BITS
  220. #undef HASHER
  221. /* MAX_NUM_MATCHES == 64 + MAX_TREE_SEARCH_DEPTH */
  222. #define MAX_NUM_MATCHES_H10 128
  223. /* For BUCKET_SWEEP_BITS == 0, enabling the dictionary lookup makes compression
  224. a little faster (0.5% - 1%) and it compresses 0.15% better on small text
  225. and HTML inputs. */
  226. #define HASHER() H2
  227. #define BUCKET_BITS 16
  228. #define BUCKET_SWEEP_BITS 0
  229. #define HASH_LEN 5
  230. #define USE_DICTIONARY 1
  231. #include "hash_longest_match_quickly_inc.h" /* NOLINT(build/include) */
  232. #undef BUCKET_SWEEP_BITS
  233. #undef USE_DICTIONARY
  234. #undef HASHER
  235. #define HASHER() H3
  236. #define BUCKET_SWEEP_BITS 1
  237. #define USE_DICTIONARY 0
  238. #include "hash_longest_match_quickly_inc.h" /* NOLINT(build/include) */
  239. #undef USE_DICTIONARY
  240. #undef BUCKET_SWEEP_BITS
  241. #undef BUCKET_BITS
  242. #undef HASHER
  243. #define HASHER() H4
  244. #define BUCKET_BITS 17
  245. #define BUCKET_SWEEP_BITS 2
  246. #define USE_DICTIONARY 1
  247. #include "hash_longest_match_quickly_inc.h" /* NOLINT(build/include) */
  248. #undef USE_DICTIONARY
  249. #undef HASH_LEN
  250. #undef BUCKET_SWEEP_BITS
  251. #undef BUCKET_BITS
  252. #undef HASHER
  253. #define HASHER() H5
  254. #include "hash_longest_match_inc.h" /* NOLINT(build/include) */
  255. #undef HASHER
  256. #define HASHER() H6
  257. #include "hash_longest_match64_inc.h" /* NOLINT(build/include) */
  258. #undef HASHER
  259. #if defined(BROTLI_MAX_SIMD_QUALITY)
  260. #define HASHER() H58
  261. #include "hash_longest_match_simd_inc.h" /* NOLINT(build/include) */
  262. #undef HASHER
  263. #define HASHER() H68
  264. #include "hash_longest_match64_simd_inc.h" /* NOLINT(build/include) */
  265. #undef HASHER
  266. #endif
  267. #define BUCKET_BITS 15
  268. #define NUM_LAST_DISTANCES_TO_CHECK 4
  269. #define NUM_BANKS 1
  270. #define BANK_BITS 16
  271. #define HASHER() H40
  272. #include "hash_forgetful_chain_inc.h" /* NOLINT(build/include) */
  273. #undef HASHER
  274. #undef NUM_LAST_DISTANCES_TO_CHECK
  275. #define NUM_LAST_DISTANCES_TO_CHECK 10
  276. #define HASHER() H41
  277. #include "hash_forgetful_chain_inc.h" /* NOLINT(build/include) */
  278. #undef HASHER
  279. #undef NUM_LAST_DISTANCES_TO_CHECK
  280. #undef NUM_BANKS
  281. #undef BANK_BITS
  282. #define NUM_LAST_DISTANCES_TO_CHECK 16
  283. #define NUM_BANKS 512
  284. #define BANK_BITS 9
  285. #define HASHER() H42
  286. #include "hash_forgetful_chain_inc.h" /* NOLINT(build/include) */
  287. #undef HASHER
  288. #undef NUM_LAST_DISTANCES_TO_CHECK
  289. #undef NUM_BANKS
  290. #undef BANK_BITS
  291. #undef BUCKET_BITS
  292. #define HASHER() H54
  293. #define BUCKET_BITS 20
  294. #define BUCKET_SWEEP_BITS 2
  295. #define HASH_LEN 7
  296. #define USE_DICTIONARY 0
  297. #include "hash_longest_match_quickly_inc.h" /* NOLINT(build/include) */
  298. #undef USE_DICTIONARY
  299. #undef HASH_LEN
  300. #undef BUCKET_SWEEP_BITS
  301. #undef BUCKET_BITS
  302. #undef HASHER
  303. /* fast large window hashers */
  304. #define HASHER() HROLLING_FAST
  305. #define CHUNKLEN 32
  306. #define JUMP 4
  307. #define NUMBUCKETS 16777216
  308. #define MASK ((NUMBUCKETS * 64) - 1)
  309. #include "hash_rolling_inc.h" /* NOLINT(build/include) */
  310. #undef JUMP
  311. #undef HASHER
  312. #define HASHER() HROLLING
  313. #define JUMP 1
  314. #include "hash_rolling_inc.h" /* NOLINT(build/include) */
  315. #undef MASK
  316. #undef NUMBUCKETS
  317. #undef JUMP
  318. #undef CHUNKLEN
  319. #undef HASHER
  320. #define HASHER() H35
  321. #define HASHER_A H3
  322. #define HASHER_B HROLLING_FAST
  323. #include "hash_composite_inc.h" /* NOLINT(build/include) */
  324. #undef HASHER_A
  325. #undef HASHER_B
  326. #undef HASHER
  327. #define HASHER() H55
  328. #define HASHER_A H54
  329. #define HASHER_B HROLLING_FAST
  330. #include "hash_composite_inc.h" /* NOLINT(build/include) */
  331. #undef HASHER_A
  332. #undef HASHER_B
  333. #undef HASHER
  334. #define HASHER() H65
  335. #define HASHER_A H6
  336. #define HASHER_B HROLLING
  337. #include "hash_composite_inc.h" /* NOLINT(build/include) */
  338. #undef HASHER_A
  339. #undef HASHER_B
  340. #undef HASHER
  341. #undef FN
  342. #undef CAT
  343. #undef EXPAND_CAT
  344. #if defined(BROTLI_MAX_SIMD_QUALITY)
  345. #define FOR_SIMPLE_HASHERS(H) \
  346. H(2) H(3) H(4) H(5) H(6) H(40) H(41) H(42) H(54) H(58) H(68)
  347. #else
  348. #define FOR_SIMPLE_HASHERS(H) \
  349. H(2) H(3) H(4) H(5) H(6) H(40) H(41) H(42) H(54)
  350. #endif
  351. #define FOR_COMPOSITE_HASHERS(H) H(35) H(55) H(65)
  352. #define FOR_GENERIC_HASHERS(H) FOR_SIMPLE_HASHERS(H) FOR_COMPOSITE_HASHERS(H)
  353. #define FOR_ALL_HASHERS(H) FOR_GENERIC_HASHERS(H) H(10)
  354. typedef struct {
  355. HasherCommon common;
  356. union {
  357. #define MEMBER_(N) \
  358. H ## N _H ## N;
  359. FOR_ALL_HASHERS(MEMBER_)
  360. #undef MEMBER_
  361. } privat;
  362. } Hasher;
  363. /* MUST be invoked before any other method. */
  364. static BROTLI_INLINE void HasherInit(Hasher* hasher) {
  365. hasher->common.is_setup_ = BROTLI_FALSE;
  366. hasher->common.extra[0] = NULL;
  367. hasher->common.extra[1] = NULL;
  368. hasher->common.extra[2] = NULL;
  369. hasher->common.extra[3] = NULL;
  370. }
  371. static BROTLI_INLINE void DestroyHasher(MemoryManager* m, Hasher* hasher) {
  372. if (hasher->common.extra[0] != NULL) BROTLI_FREE(m, hasher->common.extra[0]);
  373. if (hasher->common.extra[1] != NULL) BROTLI_FREE(m, hasher->common.extra[1]);
  374. if (hasher->common.extra[2] != NULL) BROTLI_FREE(m, hasher->common.extra[2]);
  375. if (hasher->common.extra[3] != NULL) BROTLI_FREE(m, hasher->common.extra[3]);
  376. }
  377. static BROTLI_INLINE void HasherReset(Hasher* hasher) {
  378. hasher->common.is_prepared_ = BROTLI_FALSE;
  379. }
  380. static BROTLI_INLINE void HasherSize(const BrotliEncoderParams* params,
  381. BROTLI_BOOL one_shot, const size_t input_size, size_t* alloc_size) {
  382. switch (params->hasher.type) {
  383. #define SIZE_(N) \
  384. case N: \
  385. HashMemAllocInBytesH ## N(params, one_shot, input_size, alloc_size); \
  386. break;
  387. FOR_ALL_HASHERS(SIZE_)
  388. #undef SIZE_
  389. default:
  390. break;
  391. }
  392. }
  393. static BROTLI_INLINE void HasherSetup(MemoryManager* m, Hasher* hasher,
  394. BrotliEncoderParams* params, const uint8_t* data, size_t position,
  395. size_t input_size, BROTLI_BOOL is_last) {
  396. BROTLI_BOOL one_shot = (position == 0 && is_last);
  397. if (!hasher->common.is_setup_) {
  398. size_t alloc_size[4] = {0};
  399. size_t i;
  400. ChooseHasher(params, &params->hasher);
  401. hasher->common.params = params->hasher;
  402. hasher->common.dict_num_lookups = 0;
  403. hasher->common.dict_num_matches = 0;
  404. HasherSize(params, one_shot, input_size, alloc_size);
  405. for (i = 0; i < 4; ++i) {
  406. if (alloc_size[i] == 0) continue;
  407. hasher->common.extra[i] = BROTLI_ALLOC(m, uint8_t, alloc_size[i]);
  408. if (BROTLI_IS_OOM(m) || BROTLI_IS_NULL(hasher->common.extra[i])) return;
  409. }
  410. switch (hasher->common.params.type) {
  411. #define INITIALIZE_(N) \
  412. case N: \
  413. InitializeH ## N(&hasher->common, \
  414. &hasher->privat._H ## N, params); \
  415. break;
  416. FOR_ALL_HASHERS(INITIALIZE_);
  417. #undef INITIALIZE_
  418. default:
  419. break;
  420. }
  421. HasherReset(hasher);
  422. hasher->common.is_setup_ = BROTLI_TRUE;
  423. }
  424. if (!hasher->common.is_prepared_) {
  425. switch (hasher->common.params.type) {
  426. #define PREPARE_(N) \
  427. case N: \
  428. PrepareH ## N( \
  429. &hasher->privat._H ## N, \
  430. one_shot, input_size, data); \
  431. break;
  432. FOR_ALL_HASHERS(PREPARE_)
  433. #undef PREPARE_
  434. default: break;
  435. }
  436. hasher->common.is_prepared_ = BROTLI_TRUE;
  437. }
  438. }
  439. static BROTLI_INLINE void InitOrStitchToPreviousBlock(
  440. MemoryManager* m, Hasher* hasher, const uint8_t* data, size_t mask,
  441. BrotliEncoderParams* params, size_t position, size_t input_size,
  442. BROTLI_BOOL is_last) {
  443. HasherSetup(m, hasher, params, data, position, input_size, is_last);
  444. if (BROTLI_IS_OOM(m)) return;
  445. switch (hasher->common.params.type) {
  446. #define INIT_(N) \
  447. case N: \
  448. StitchToPreviousBlockH ## N( \
  449. &hasher->privat._H ## N, \
  450. input_size, position, data, mask); \
  451. break;
  452. FOR_ALL_HASHERS(INIT_)
  453. #undef INIT_
  454. default: break;
  455. }
  456. }
  457. /* NB: when seamless dictionary-ring-buffer copies are implemented, don't forget
  458. to add proper guards for non-zero-BROTLI_PARAM_STREAM_OFFSET. */
  459. static BROTLI_INLINE void FindCompoundDictionaryMatch(
  460. const PreparedDictionary* self, const uint8_t* BROTLI_RESTRICT data,
  461. const size_t ring_buffer_mask, const int* BROTLI_RESTRICT distance_cache,
  462. const size_t cur_ix, const size_t max_length, const size_t distance_offset,
  463. const size_t max_distance, HasherSearchResult* BROTLI_RESTRICT out) {
  464. const uint32_t source_size = self->source_size;
  465. const size_t boundary = distance_offset - source_size;
  466. const uint32_t hash_bits = self->hash_bits;
  467. const uint32_t bucket_bits = self->bucket_bits;
  468. const uint32_t slot_bits = self->slot_bits;
  469. const uint32_t hash_shift = 64u - bucket_bits;
  470. const uint32_t slot_mask = (~((uint32_t)0U)) >> (32 - slot_bits);
  471. const uint64_t hash_mask = (~((uint64_t)0U)) >> (64 - hash_bits);
  472. const uint32_t* slot_offsets = (uint32_t*)(&self[1]);
  473. const uint16_t* heads = (uint16_t*)(&slot_offsets[(size_t)1u << slot_bits]);
  474. const uint32_t* items = (uint32_t*)(&heads[(size_t)1u << bucket_bits]);
  475. const uint8_t* source = NULL;
  476. const size_t cur_ix_masked = cur_ix & ring_buffer_mask;
  477. score_t best_score = out->score;
  478. size_t best_len = out->len;
  479. size_t i;
  480. const uint64_t h =
  481. (BROTLI_UNALIGNED_LOAD64LE(&data[cur_ix_masked]) & hash_mask) *
  482. kPreparedDictionaryHashMul64Long;
  483. const uint32_t key = (uint32_t)(h >> hash_shift);
  484. const uint32_t slot = key & slot_mask;
  485. const uint32_t head = heads[key];
  486. const uint32_t* BROTLI_RESTRICT chain = &items[slot_offsets[slot] + head];
  487. uint32_t item = (head == 0xFFFF) ? 1 : 0;
  488. const void* tail = (void*)&items[self->num_items];
  489. if (self->magic == kPreparedDictionaryMagic) {
  490. source = (const uint8_t*)tail;
  491. } else {
  492. /* kLeanPreparedDictionaryMagic */
  493. source = (const uint8_t*)BROTLI_UNALIGNED_LOAD_PTR((const uint8_t**)tail);
  494. }
  495. BROTLI_DCHECK(cur_ix_masked + max_length <= ring_buffer_mask);
  496. for (i = 0; i < 4; ++i) {
  497. const size_t distance = (size_t)distance_cache[i];
  498. size_t offset;
  499. size_t limit;
  500. size_t len;
  501. if (distance <= boundary || distance > distance_offset) continue;
  502. offset = distance_offset - distance;
  503. limit = source_size - offset;
  504. limit = limit > max_length ? max_length : limit;
  505. len = FindMatchLengthWithLimit(&source[offset], &data[cur_ix_masked],
  506. limit);
  507. if (len >= 2) {
  508. score_t score = BackwardReferenceScoreUsingLastDistance(len);
  509. if (best_score < score) {
  510. if (i != 0) score -= BackwardReferencePenaltyUsingLastDistance(i);
  511. if (best_score < score) {
  512. best_score = score;
  513. if (len > best_len) best_len = len;
  514. out->len = len;
  515. out->len_code_delta = 0;
  516. out->distance = distance;
  517. out->score = best_score;
  518. }
  519. }
  520. }
  521. }
  522. /* we require matches of len >4, so increase best_len to 3, so we can compare
  523. * 4 bytes all the time. */
  524. if (best_len < 3) {
  525. best_len = 3;
  526. }
  527. while (item == 0) {
  528. size_t offset;
  529. size_t distance;
  530. size_t limit;
  531. item = *chain;
  532. chain++;
  533. offset = item & 0x7FFFFFFF;
  534. item &= 0x80000000;
  535. distance = distance_offset - offset;
  536. limit = source_size - offset;
  537. limit = (limit > max_length) ? max_length : limit;
  538. if (distance > max_distance) continue;
  539. if (cur_ix_masked + best_len > ring_buffer_mask || best_len >= limit ||
  540. /* compare 4 bytes ending at best_len + 1 */
  541. BrotliUnalignedRead32(&data[cur_ix_masked + best_len - 3]) !=
  542. BrotliUnalignedRead32(&source[offset + best_len - 3])) {
  543. continue;
  544. }
  545. {
  546. const size_t len = FindMatchLengthWithLimit(&source[offset],
  547. &data[cur_ix_masked],
  548. limit);
  549. if (len >= 4) {
  550. score_t score = BackwardReferenceScore(len, distance);
  551. if (best_score < score) {
  552. best_score = score;
  553. best_len = len;
  554. out->len = best_len;
  555. out->len_code_delta = 0;
  556. out->distance = distance;
  557. out->score = best_score;
  558. }
  559. }
  560. }
  561. }
  562. }
  563. /* NB: when seamless dictionary-ring-buffer copies are implemented, don't forget
  564. to add proper guards for non-zero-BROTLI_PARAM_STREAM_OFFSET. */
  565. static BROTLI_INLINE size_t FindAllCompoundDictionaryMatches(
  566. const PreparedDictionary* self, const uint8_t* BROTLI_RESTRICT data,
  567. const size_t ring_buffer_mask, const size_t cur_ix, const size_t min_length,
  568. const size_t max_length, const size_t distance_offset,
  569. const size_t max_distance, BackwardMatch* matches, size_t match_limit) {
  570. const uint32_t source_size = self->source_size;
  571. const uint32_t hash_bits = self->hash_bits;
  572. const uint32_t bucket_bits = self->bucket_bits;
  573. const uint32_t slot_bits = self->slot_bits;
  574. const uint32_t hash_shift = 64u - bucket_bits;
  575. const uint32_t slot_mask = (~((uint32_t)0U)) >> (32 - slot_bits);
  576. const uint64_t hash_mask = (~((uint64_t)0U)) >> (64 - hash_bits);
  577. const uint32_t* slot_offsets = (uint32_t*)(&self[1]);
  578. const uint16_t* heads = (uint16_t*)(&slot_offsets[(size_t)1u << slot_bits]);
  579. const uint32_t* items = (uint32_t*)(&heads[(size_t)1u << bucket_bits]);
  580. const uint8_t* source = NULL;
  581. const size_t cur_ix_masked = cur_ix & ring_buffer_mask;
  582. size_t best_len = min_length;
  583. const uint64_t h =
  584. (BROTLI_UNALIGNED_LOAD64LE(&data[cur_ix_masked]) & hash_mask) *
  585. kPreparedDictionaryHashMul64Long;
  586. const uint32_t key = (uint32_t)(h >> hash_shift);
  587. const uint32_t slot = key & slot_mask;
  588. const uint32_t head = heads[key];
  589. const uint32_t* BROTLI_RESTRICT chain = &items[slot_offsets[slot] + head];
  590. uint32_t item = (head == 0xFFFF) ? 1 : 0;
  591. size_t found = 0;
  592. const void* tail = (void*)&items[self->num_items];
  593. if (self->magic == kPreparedDictionaryMagic) {
  594. source = (const uint8_t*)tail;
  595. } else {
  596. /* kLeanPreparedDictionaryMagic */
  597. source = (const uint8_t*)BROTLI_UNALIGNED_LOAD_PTR((const uint8_t**)tail);
  598. }
  599. BROTLI_DCHECK(cur_ix_masked + max_length <= ring_buffer_mask);
  600. while (item == 0) {
  601. size_t offset;
  602. size_t distance;
  603. size_t limit;
  604. size_t len;
  605. item = *chain;
  606. chain++;
  607. offset = item & 0x7FFFFFFF;
  608. item &= 0x80000000;
  609. distance = distance_offset - offset;
  610. limit = source_size - offset;
  611. limit = (limit > max_length) ? max_length : limit;
  612. if (distance > max_distance) continue;
  613. if (cur_ix_masked + best_len > ring_buffer_mask ||
  614. best_len >= limit ||
  615. data[cur_ix_masked + best_len] != source[offset + best_len]) {
  616. continue;
  617. }
  618. len = FindMatchLengthWithLimit(
  619. &source[offset], &data[cur_ix_masked], limit);
  620. if (len > best_len) {
  621. best_len = len;
  622. InitBackwardMatch(matches++, distance, len);
  623. found++;
  624. if (found == match_limit) break;
  625. }
  626. }
  627. return found;
  628. }
  629. static BROTLI_INLINE void LookupCompoundDictionaryMatch(
  630. const CompoundDictionary* addon, const uint8_t* BROTLI_RESTRICT data,
  631. const size_t ring_buffer_mask, const int* BROTLI_RESTRICT distance_cache,
  632. const size_t cur_ix, const size_t max_length,
  633. const size_t max_ring_buffer_distance, const size_t max_distance,
  634. HasherSearchResult* sr) {
  635. size_t base_offset = max_ring_buffer_distance + 1 + addon->total_size - 1;
  636. size_t d;
  637. for (d = 0; d < addon->num_chunks; ++d) {
  638. /* Only one prepared dictionary type is currently supported. */
  639. FindCompoundDictionaryMatch(
  640. (const PreparedDictionary*)addon->chunks[d], data, ring_buffer_mask,
  641. distance_cache, cur_ix, max_length,
  642. base_offset - addon->chunk_offsets[d], max_distance, sr);
  643. }
  644. }
  645. static BROTLI_INLINE size_t LookupAllCompoundDictionaryMatches(
  646. const CompoundDictionary* addon, const uint8_t* BROTLI_RESTRICT data,
  647. const size_t ring_buffer_mask, const size_t cur_ix, size_t min_length,
  648. const size_t max_length, const size_t max_ring_buffer_distance,
  649. const size_t max_distance, BackwardMatch* matches,
  650. size_t match_limit) {
  651. size_t base_offset = max_ring_buffer_distance + 1 + addon->total_size - 1;
  652. size_t d;
  653. size_t total_found = 0;
  654. for (d = 0; d < addon->num_chunks; ++d) {
  655. /* Only one prepared dictionary type is currently supported. */
  656. total_found += FindAllCompoundDictionaryMatches(
  657. (const PreparedDictionary*)addon->chunks[d], data, ring_buffer_mask,
  658. cur_ix, min_length, max_length, base_offset - addon->chunk_offsets[d],
  659. max_distance, matches + total_found, match_limit - total_found);
  660. if (total_found == match_limit) break;
  661. if (total_found > 0) {
  662. min_length = BackwardMatchLength(&matches[total_found - 1]);
  663. }
  664. }
  665. return total_found;
  666. }
  667. #if defined(__cplusplus) || defined(c_plusplus)
  668. } /* extern "C" */
  669. #endif
  670. #endif /* BROTLI_ENC_HASH_H_ */