]> git.proxmox.com Git - mirror_edk2.git/blobdiff - BaseTools/Source/C/BrotliCompress/enc/hash_forgetful_chain_inc.h
BaseTools: Copy Brotli algorithm 3rd party source code for tool
[mirror_edk2.git] / BaseTools / Source / C / BrotliCompress / enc / hash_forgetful_chain_inc.h
diff --git a/BaseTools/Source/C/BrotliCompress/enc/hash_forgetful_chain_inc.h b/BaseTools/Source/C/BrotliCompress/enc/hash_forgetful_chain_inc.h
new file mode 100644 (file)
index 0000000..069441c
--- /dev/null
@@ -0,0 +1,249 @@
+/* NOLINT(build/header_guard) */\r
+/* Copyright 2016 Google Inc. All Rights Reserved.\r
+\r
+   Distributed under MIT license.\r
+   See file LICENSE for detail or copy at https://opensource.org/licenses/MIT\r
+*/\r
+\r
+/* template parameters: FN, BUCKET_BITS, NUM_BANKS, BANK_BITS,\r
+                        NUM_LAST_DISTANCES_TO_CHECK */\r
+\r
+/* A (forgetful) hash table to the data seen by the compressor, to\r
+   help create backward references to previous data.\r
+\r
+   Hashes are stored in chains which are bucketed to groups. Group of chains\r
+   share a storage "bank". When more than "bank size" chain nodes are added,\r
+   oldest nodes are replaced; this way several chains may share a tail. */\r
+\r
+#define HashForgetfulChain HASHER()\r
+\r
+#define BANK_SIZE (1 << BANK_BITS)\r
+\r
+/* Number of hash buckets. */\r
+#define BUCKET_SIZE (1 << BUCKET_BITS)\r
+\r
+#define CAPPED_CHAINS 0\r
+\r
+static BROTLI_INLINE size_t FN(HashTypeLength)(void) { return 4; }\r
+static BROTLI_INLINE size_t FN(StoreLookahead)(void) { return 4; }\r
+\r
+/* HashBytes is the function that chooses the bucket to place the address in.*/\r
+static BROTLI_INLINE size_t FN(HashBytes)(const uint8_t *data) {\r
+  const uint32_t h = BROTLI_UNALIGNED_LOAD32(data) * kHashMul32;\r
+  /* The higher bits contain more mixture from the multiplication,\r
+     so we take our results from there. */\r
+  return h >> (32 - BUCKET_BITS);\r
+}\r
+\r
+typedef struct FN(Slot) {\r
+  uint16_t delta;\r
+  uint16_t next;\r
+} FN(Slot);\r
+\r
+typedef struct FN(Bank) {\r
+  FN(Slot) slots[BANK_SIZE];\r
+} FN(Bank);\r
+\r
+typedef struct HashForgetfulChain {\r
+  uint32_t addr[BUCKET_SIZE];\r
+  uint16_t head[BUCKET_SIZE];\r
+  /* Truncated hash used for quick rejection of "distance cache" candidates. */\r
+  uint8_t tiny_hash[65536];\r
+  FN(Bank) banks[NUM_BANKS];\r
+  uint16_t free_slot_idx[NUM_BANKS];\r
+  BROTLI_BOOL is_dirty_;\r
+  DictionarySearchStatictics dict_search_stats_;\r
+  size_t max_hops;\r
+} HashForgetfulChain;\r
+\r
+static void FN(Reset)(HashForgetfulChain* self) {\r
+  self->is_dirty_ = BROTLI_TRUE;\r
+  DictionarySearchStaticticsReset(&self->dict_search_stats_);\r
+}\r
+\r
+static void FN(InitEmpty)(HashForgetfulChain* self) {\r
+  if (self->is_dirty_) {\r
+    /* Fill |addr| array with 0xCCCCCCCC value. Because of wrapping, position\r
+       processed by hasher never reaches 3GB + 64M; this makes all new chains\r
+       to be terminated after the first node. */\r
+    memset(self->addr, 0xCC, sizeof(self->addr));\r
+    memset(self->head, 0, sizeof(self->head));\r
+    memset(self->tiny_hash, 0, sizeof(self->tiny_hash));\r
+    memset(self->free_slot_idx, 0, sizeof(self->free_slot_idx));\r
+    self->is_dirty_ = BROTLI_FALSE;\r
+  }\r
+}\r
+\r
+static void FN(InitForData)(HashForgetfulChain* self, const uint8_t* data,\r
+    size_t num) {\r
+  size_t i;\r
+  for (i = 0; i < num; ++i) {\r
+    size_t bucket = FN(HashBytes)(&data[i]);\r
+    /* See InitEmpty comment. */\r
+    self->addr[bucket] = 0xCCCCCCCC;\r
+    self->head[bucket] = 0xCCCC;\r
+  }\r
+  memset(self->tiny_hash, 0, sizeof(self->tiny_hash));\r
+  memset(self->free_slot_idx, 0, sizeof(self->free_slot_idx));\r
+  if (num != 0) {\r
+    self->is_dirty_ = BROTLI_FALSE;\r
+  }\r
+}\r
+\r
+static void FN(Init)(\r
+    MemoryManager* m, HashForgetfulChain* self, const uint8_t* data,\r
+    const BrotliEncoderParams* params, size_t position, size_t bytes,\r
+    BROTLI_BOOL is_last) {\r
+  /* Choose which init method is faster.\r
+     Init() is about 100 times faster than InitForData(). */\r
+  const size_t kMaxBytesForPartialHashInit = BUCKET_SIZE >> 6;\r
+  BROTLI_UNUSED(m);\r
+  self->max_hops = (params->quality > 6 ? 7u : 8u) << (params->quality - 4);\r
+  if (position == 0 && is_last && bytes <= kMaxBytesForPartialHashInit) {\r
+    FN(InitForData)(self, data, bytes);\r
+  } else {\r
+    FN(InitEmpty)(self);\r
+  }\r
+}\r
+\r
+/* Look at 4 bytes at &data[ix & mask]. Compute a hash from these, and prepend\r
+   node to corresponding chain; also update tiny_hash for current position. */\r
+static BROTLI_INLINE void FN(Store)(HashForgetfulChain* BROTLI_RESTRICT self,\r
+    const uint8_t* BROTLI_RESTRICT data, const size_t mask, const size_t ix) {\r
+  const size_t key = FN(HashBytes)(&data[ix & mask]);\r
+  const size_t bank = key & (NUM_BANKS - 1);\r
+  const size_t idx = self->free_slot_idx[bank]++ & (BANK_SIZE - 1);\r
+  size_t delta = ix - self->addr[key];\r
+  self->tiny_hash[(uint16_t)ix] = (uint8_t)key;\r
+  if (delta > 0xFFFF) delta = CAPPED_CHAINS ? 0 : 0xFFFF;\r
+  self->banks[bank].slots[idx].delta = (uint16_t)delta;\r
+  self->banks[bank].slots[idx].next = self->head[key];\r
+  self->addr[key] = (uint32_t)ix;\r
+  self->head[key] = (uint16_t)idx;\r
+}\r
+\r
+static BROTLI_INLINE void FN(StoreRange)(HashForgetfulChain* self,\r
+    const uint8_t *data, const size_t mask, const size_t ix_start,\r
+    const size_t ix_end) {\r
+  size_t i;\r
+  for (i = ix_start; i < ix_end; ++i) {\r
+    FN(Store)(self, data, mask, i);\r
+  }\r
+}\r
+\r
+static BROTLI_INLINE void FN(StitchToPreviousBlock)(HashForgetfulChain* self,\r
+    size_t num_bytes, size_t position, const uint8_t* ringbuffer,\r
+    size_t ring_buffer_mask) {\r
+  if (num_bytes >= FN(HashTypeLength)() - 1 && position >= 3) {\r
+    /* Prepare the hashes for three last bytes of the last write.\r
+       These could not be calculated before, since they require knowledge\r
+       of both the previous and the current block. */\r
+    FN(Store)(self, ringbuffer, ring_buffer_mask, position - 3);\r
+    FN(Store)(self, ringbuffer, ring_buffer_mask, position - 2);\r
+    FN(Store)(self, ringbuffer, ring_buffer_mask, position - 1);\r
+  }\r
+}\r
+\r
+/* Find a longest backward match of &data[cur_ix] up to the length of\r
+   max_length and stores the position cur_ix in the hash table.\r
+\r
+   Does not look for matches longer than max_length.\r
+   Does not look for matches further away than max_backward.\r
+   Writes the best match into |out|.\r
+   Returns 1 when match is found, otherwise 0. */\r
+static BROTLI_INLINE BROTLI_BOOL FN(FindLongestMatch)(\r
+    HashForgetfulChain* self, const uint8_t* BROTLI_RESTRICT data,\r
+    const size_t ring_buffer_mask, const int* BROTLI_RESTRICT distance_cache,\r
+    const size_t cur_ix, const size_t max_length, const size_t max_backward,\r
+    HasherSearchResult* BROTLI_RESTRICT out) {\r
+  const size_t cur_ix_masked = cur_ix & ring_buffer_mask;\r
+  BROTLI_BOOL is_match_found = BROTLI_FALSE;\r
+  /* Don't accept a short copy from far away. */\r
+  score_t best_score = out->score;\r
+  size_t best_len = out->len;\r
+  size_t i;\r
+  const size_t key = FN(HashBytes)(&data[cur_ix_masked]);\r
+  const uint8_t tiny_hash = (uint8_t)(key);\r
+  out->len = 0;\r
+  out->len_x_code = 0;\r
+  /* Try last distance first. */\r
+  for (i = 0; i < NUM_LAST_DISTANCES_TO_CHECK; ++i) {\r
+    const size_t idx = kDistanceCacheIndex[i];\r
+    const size_t backward =\r
+        (size_t)(distance_cache[idx] + kDistanceCacheOffset[i]);\r
+    size_t prev_ix = (cur_ix - backward);\r
+    if (i > 0 && self->tiny_hash[(uint16_t)prev_ix] != tiny_hash) continue;\r
+    if (prev_ix >= cur_ix || backward > max_backward) {\r
+      continue;\r
+    }\r
+    prev_ix &= ring_buffer_mask;\r
+    {\r
+      const size_t len = FindMatchLengthWithLimit(&data[prev_ix],\r
+                                                  &data[cur_ix_masked],\r
+                                                  max_length);\r
+      if (len >= 2) {\r
+        score_t score = BackwardReferenceScoreUsingLastDistance(len, i);\r
+        if (best_score < score) {\r
+          best_score = score;\r
+          best_len = len;\r
+          out->len = best_len;\r
+          out->distance = backward;\r
+          out->score = best_score;\r
+          is_match_found = BROTLI_TRUE;\r
+        }\r
+      }\r
+    }\r
+  }\r
+  {\r
+    const size_t bank = key & (NUM_BANKS - 1);\r
+    size_t backward = 0;\r
+    size_t hops = self->max_hops;\r
+    size_t delta = cur_ix - self->addr[key];\r
+    size_t slot = self->head[key];\r
+    while (hops--) {\r
+      size_t prev_ix;\r
+      size_t last = slot;\r
+      backward += delta;\r
+      if (backward > max_backward || (CAPPED_CHAINS && !delta)) break;\r
+      prev_ix = (cur_ix - backward) & ring_buffer_mask;\r
+      slot = self->banks[bank].slots[last].next;\r
+      delta = self->banks[bank].slots[last].delta;\r
+      if (cur_ix_masked + best_len > ring_buffer_mask ||\r
+          prev_ix + best_len > ring_buffer_mask ||\r
+          data[cur_ix_masked + best_len] != data[prev_ix + best_len]) {\r
+        continue;\r
+      }\r
+      {\r
+        const size_t len = FindMatchLengthWithLimit(&data[prev_ix],\r
+                                                    &data[cur_ix_masked],\r
+                                                    max_length);\r
+        if (len >= 4) {\r
+          /* Comparing for >= 3 does not change the semantics, but just saves\r
+             for a few unnecessary binary logarithms in backward reference\r
+             score, since we are not interested in such short matches. */\r
+          score_t score = BackwardReferenceScore(len, backward);\r
+          if (best_score < score) {\r
+            best_score = score;\r
+            best_len = len;\r
+            out->len = best_len;\r
+            out->distance = backward;\r
+            out->score = best_score;\r
+            is_match_found = BROTLI_TRUE;\r
+          }\r
+        }\r
+      }\r
+    }\r
+    FN(Store)(self, data, ring_buffer_mask, cur_ix);\r
+  }\r
+  if (!is_match_found) {\r
+    is_match_found = SearchInStaticDictionary(&self->dict_search_stats_,\r
+        &data[cur_ix_masked], max_length, max_backward, out, BROTLI_FALSE);\r
+  }\r
+  return is_match_found;\r
+}\r
+\r
+#undef BANK_SIZE\r
+#undef BUCKET_SIZE\r
+#undef CAPPED_CHAINS\r
+\r
+#undef HashForgetfulChain\r