Blame SOURCES/rhbz1881156.patch

d19186
From ce3b0936620b9abb2d6d21d3e608f37f3c7302d9 Mon Sep 17 00:00:00 2001
d19186
From: rpm-build <rpm-build>
d19186
Date: Thu, 1 Oct 2020 10:34:27 +0200
d19186
Subject: [PATCH] rhbz1881156.patch
d19186
d19186
---
d19186
 c/common/constants.c      |  15 +
d19186
 c/common/constants.h      | 136 ++++++++
d19186
 c/common/platform.h       |   8 +-
d19186
 c/dec/bit_reader.c        |  28 ++
d19186
 c/dec/bit_reader.h        |  74 +++-
d19186
 c/dec/decode.c            | 695 ++++++++++++++++++++++----------------
d19186
 c/dec/huffman.h           |  71 +++-
d19186
 c/dec/prefix.h            |  18 -
d19186
 c/dec/state.c             |  23 +-
d19186
 c/dec/state.h             | 181 ++++++++--
d19186
 c/enc/brotli_bit_stream.c |  21 +-
d19186
 research/brotli_decoder.c |   1 +
d19186
 scripts/sources.lst       |   1 +
d19186
 setup.py                  |   1 +
d19186
 14 files changed, 865 insertions(+), 408 deletions(-)
d19186
 create mode 100644 c/common/constants.c
d19186
d19186
diff --git a/c/common/constants.c b/c/common/constants.c
d19186
new file mode 100644
d19186
index 0000000..6bad9f6
d19186
--- /dev/null
d19186
+++ b/c/common/constants.c
d19186
@@ -0,0 +1,15 @@
d19186
+/* Copyright 2013 Google Inc. All Rights Reserved.
d19186
+
d19186
+   Distributed under MIT license.
d19186
+   See file LICENSE for detail or copy at https://opensource.org/licenses/MIT
d19186
+*/
d19186
+
d19186
+#include "./constants.h"
d19186
+
d19186
+const BrotliPrefixCodeRange
d19186
+    _kBrotliPrefixCodeRanges[BROTLI_NUM_BLOCK_LEN_SYMBOLS] = {
d19186
+        {1, 2},     {5, 2},     {9, 2},   {13, 2},    {17, 3},    {25, 3},
d19186
+        {33, 3},    {41, 3},    {49, 4},  {65, 4},    {81, 4},    {97, 4},
d19186
+        {113, 5},   {145, 5},   {177, 5}, {209, 5},   {241, 6},   {305, 6},
d19186
+        {369, 7},   {497, 8},   {753, 9}, {1265, 10}, {2289, 11}, {4337, 12},
d19186
+        {8433, 13}, {16625, 24}};
d19186
diff --git a/c/common/constants.h b/c/common/constants.h
d19186
index d1b88d1..e848195 100644
d19186
--- a/c/common/constants.h
d19186
+++ b/c/common/constants.h
d19186
@@ -4,9 +4,18 @@
d19186
    See file LICENSE for detail or copy at https://opensource.org/licenses/MIT
d19186
 */
d19186
 
d19186
+/**
d19186
+ * @file
d19186
+ * Common constants used in decoder and encoder API.
d19186
+ */
d19186
+
d19186
 #ifndef BROTLI_COMMON_CONSTANTS_H_
d19186
 #define BROTLI_COMMON_CONSTANTS_H_
d19186
 
d19186
+#include "./platform.h"
d19186
+#include <brotli/port.h>
d19186
+#include <brotli/types.h>
d19186
+
d19186
 /* Specification: 7.3. Encoding of the context map */
d19186
 #define BROTLI_CONTEXT_MAP_MAX_RLE 16
d19186
 
d19186
@@ -29,12 +38,31 @@
d19186
 #define BROTLI_INITIAL_REPEATED_CODE_LENGTH 8
d19186
 
d19186
 /* "Large Window Brotli" */
d19186
+
d19186
+/**
d19186
+ * The theoretical maximum number of distance bits specified for large window
d19186
+ * brotli, for 64-bit encoders and decoders. Even when in practice 32-bit
d19186
+ * encoders and decoders only support up to 30 max distance bits, the value is
d19186
+ * set to 62 because it affects the large window brotli file format.
d19186
+ * Specifically, it affects the encoding of simple huffman tree for distances,
d19186
+ * see Specification RFC 7932 chapter 3.4.
d19186
+ */
d19186
 #define BROTLI_LARGE_MAX_DISTANCE_BITS 62U
d19186
 #define BROTLI_LARGE_MIN_WBITS 10
d19186
+/**
d19186
+ * The maximum supported large brotli window bits by the encoder and decoder.
d19186
+ * Large window brotli allows up to 62 bits, however the current encoder and
d19186
+ * decoder, designed for 32-bit integers, only support up to 30 bits maximum.
d19186
+ */
d19186
 #define BROTLI_LARGE_MAX_WBITS 30
d19186
 
d19186
 /* Specification: 4. Encoding of distances */
d19186
 #define BROTLI_NUM_DISTANCE_SHORT_CODES 16
d19186
+/**
d19186
+ * Maximal number of "postfix" bits.
d19186
+ *
d19186
+ * Number of "postfix" bits is stored as 2 bits in meta-block header.
d19186
+ */
d19186
 #define BROTLI_MAX_NPOSTFIX 3
d19186
 #define BROTLI_MAX_NDIRECT 120
d19186
 #define BROTLI_MAX_DISTANCE_BITS 24U
d19186
@@ -45,9 +73,22 @@
d19186
 #define BROTLI_NUM_DISTANCE_SYMBOLS \
d19186
     BROTLI_DISTANCE_ALPHABET_SIZE(  \
d19186
         BROTLI_MAX_NDIRECT, BROTLI_MAX_NPOSTFIX, BROTLI_LARGE_MAX_DISTANCE_BITS)
d19186
+
d19186
+/* ((1 << 26) - 4) is the maximal distance that can be expressed in RFC 7932
d19186
+   brotli stream using NPOSTFIX = 0 and NDIRECT = 0. With other NPOSTFIX and
d19186
+   NDIRECT values distances up to ((1 << 29) + 88) could be expressed. */
d19186
 #define BROTLI_MAX_DISTANCE 0x3FFFFFC
d19186
+
d19186
+/* ((1 << 31) - 4) is the safe distance limit. Using this number as a limit
d19186
+   allows safe distance calculation without overflows, given the distance
d19186
+   alphabet size is limited to corresponding size
d19186
+   (see kLargeWindowDistanceCodeLimits). */
d19186
 #define BROTLI_MAX_ALLOWED_DISTANCE 0x7FFFFFFC
d19186
 
d19186
+
d19186
+/* Specification: 4. Encoding of Literal Insertion Lengths and Copy Lengths */
d19186
+#define BROTLI_NUM_INS_COPY_CODES 24
d19186
+
d19186
 /* 7.1. Context modes and context ID lookup for literals */
d19186
 /* "context IDs for literals are in the range of 0..63" */
d19186
 #define BROTLI_LITERAL_CONTEXT_BITS 6
d19186
@@ -61,4 +102,99 @@
d19186
 #define BROTLI_WINDOW_GAP 16
d19186
 #define BROTLI_MAX_BACKWARD_LIMIT(W) (((size_t)1 << (W)) - BROTLI_WINDOW_GAP)
d19186
 
d19186
+typedef struct BrotliDistanceCodeLimit {
d19186
+  uint32_t max_alphabet_size;
d19186
+  uint32_t max_distance;
d19186
+} BrotliDistanceCodeLimit;
d19186
+
d19186
+/* This function calculates maximal size of distance alphabet, such that the
d19186
+   distances greater than the given values can not be represented.
d19186
+
d19186
+   This limits are designed to support fast and safe 32-bit decoders.
d19186
+   "32-bit" means that signed integer values up to ((1 << 31) - 1) could be
d19186
+   safely expressed.
d19186
+
d19186
+   Brotli distance alphabet symbols do not represent consecutive distance
d19186
+   ranges. Each distance alphabet symbol (excluding direct distances and short
d19186
+   codes), represent interleaved (for NPOSTFIX > 0) range of distances.
d19186
+   A "group" of consecutive (1 << NPOSTFIX) symbols represent non-interleaved
d19186
+   range. Two consecutive groups require the same amount of "extra bits".
d19186
+
d19186
+   It is important that distance alphabet represents complete "groups".
d19186
+   To avoid complex logic on encoder side about interleaved ranges
d19186
+   it was decided to restrict both sides to complete distance code "groups".
d19186
+ */
d19186
+BROTLI_UNUSED_FUNCTION BrotliDistanceCodeLimit BrotliCalculateDistanceCodeLimit(
d19186
+    uint32_t max_distance, uint32_t npostfix, uint32_t ndirect) {
d19186
+  BrotliDistanceCodeLimit result;
d19186
+  /* Marking this function as unused, because not all files
d19186
+     including "constants.h" use it -> compiler warns about that. */
d19186
+  BROTLI_UNUSED(&BrotliCalculateDistanceCodeLimit);
d19186
+  if (max_distance <= ndirect) {
d19186
+    /* This case never happens / exists only for the sake of completeness. */
d19186
+    result.max_alphabet_size = max_distance + BROTLI_NUM_DISTANCE_SHORT_CODES;
d19186
+    result.max_distance = max_distance;
d19186
+    return result;
d19186
+  } else {
d19186
+    /* The first prohibited value. */
d19186
+    uint32_t forbidden_distance = max_distance + 1;
d19186
+    /* Subtract "directly" encoded region. */
d19186
+    uint32_t offset = forbidden_distance - ndirect - 1;
d19186
+    uint32_t ndistbits = 0;
d19186
+    uint32_t tmp;
d19186
+    uint32_t half;
d19186
+    uint32_t group;
d19186
+    /* Postfix for the last dcode in the group. */
d19186
+    uint32_t postfix = (1u << npostfix) - 1;
d19186
+    uint32_t extra;
d19186
+    uint32_t start;
d19186
+    /* Remove postfix and "head-start". */
d19186
+    offset = (offset >> npostfix) + 4;
d19186
+    /* Calculate the number of distance bits. */
d19186
+    tmp = offset / 2;
d19186
+    /* Poor-man's log2floor, to avoid extra dependencies. */
d19186
+    while (tmp != 0) {ndistbits++; tmp = tmp >> 1;}
d19186
+    /* One bit is covered with subrange addressing ("half"). */
d19186
+    ndistbits--;
d19186
+    /* Find subrange. */
d19186
+    half = (offset >> ndistbits) & 1;
d19186
+    /* Calculate the "group" part of dcode. */
d19186
+    group = ((ndistbits - 1) << 1) | half;
d19186
+    /* Calculated "group" covers the prohibited distance value. */
d19186
+    if (group == 0) {
d19186
+      /* This case is added for correctness; does not occur for limit > 128. */
d19186
+      result.max_alphabet_size = ndirect + BROTLI_NUM_DISTANCE_SHORT_CODES;
d19186
+      result.max_distance = ndirect;
d19186
+      return result;
d19186
+    }
d19186
+    /* Decrement "group", so it is the last permitted "group". */
d19186
+    group--;
d19186
+    /* After group was decremented, ndistbits and half must be recalculated. */
d19186
+    ndistbits = (group >> 1) + 1;
d19186
+    /* The last available distance in the subrange has all extra bits set. */
d19186
+    extra = (1u << ndistbits) - 1;
d19186
+    /* Calculate region start. NB: ndistbits >= 1. */
d19186
+    start = (1u << (ndistbits + 1)) - 4;
d19186
+    /* Move to subregion. */
d19186
+    start += (group & 1) << ndistbits;
d19186
+    /* Calculate the alphabet size. */
d19186
+    result.max_alphabet_size = ((group << npostfix) | postfix) + ndirect +
d19186
+        BROTLI_NUM_DISTANCE_SHORT_CODES + 1;
d19186
+    /* Calculate the maximal distance representable by alphabet. */
d19186
+    result.max_distance = ((start + extra) << npostfix) + postfix + ndirect + 1;
d19186
+    return result;
d19186
+  }
d19186
+}
d19186
+
d19186
+/* Represents the range of values belonging to a prefix code:
d19186
+   [offset, offset + 2^nbits) */
d19186
+typedef struct {
d19186
+  uint16_t offset;
d19186
+  uint8_t nbits;
d19186
+} BrotliPrefixCodeRange;
d19186
+
d19186
+/* "Soft-private", it is exported, but not "advertised" as API. */
d19186
+BROTLI_COMMON_API extern const BrotliPrefixCodeRange
d19186
+    _kBrotliPrefixCodeRanges[BROTLI_NUM_BLOCK_LEN_SYMBOLS];
d19186
+
d19186
 #endif  /* BROTLI_COMMON_CONSTANTS_H_ */
d19186
diff --git a/c/common/platform.h b/c/common/platform.h
d19186
index 0d84b19..94bf773 100755
d19186
--- a/c/common/platform.h
d19186
+++ b/c/common/platform.h
d19186
@@ -197,6 +197,10 @@ OR:
d19186
 
d19186
 #endif  /* ARMv8 */
d19186
 
d19186
+#if defined(__ARM_NEON__) || defined(__ARM_NEON)
d19186
+#define BROTLI_TARGET_NEON
d19186
+#endif
d19186
+
d19186
 #if defined(__i386) || defined(_M_IX86)
d19186
 #define BROTLI_TARGET_X86
d19186
 #endif
d19186
@@ -456,20 +460,20 @@ static BROTLI_INLINE void BROTLI_UNALIGNED_STORE64LE(void* p, uint64_t v) {
d19186
 #endif
d19186
 
d19186
 #if defined(BROTLI_ENABLE_LOG)
d19186
-#define BROTLI_DCHECK(x) assert(x)
d19186
 #define BROTLI_LOG(x) printf x
d19186
 #else
d19186
-#define BROTLI_DCHECK(x)
d19186
 #define BROTLI_LOG(x)
d19186
 #endif
d19186
 
d19186
 #if defined(BROTLI_DEBUG) || defined(BROTLI_ENABLE_LOG)
d19186
+#define BROTLI_DCHECK(x) assert(x)
d19186
 static BROTLI_INLINE void BrotliDump(const char* f, int l, const char* fn) {
d19186
   fprintf(stderr, "%s:%d (%s)\n", f, l, fn);
d19186
   fflush(stderr);
d19186
 }
d19186
 #define BROTLI_DUMP() BrotliDump(__FILE__, __LINE__, __FUNCTION__)
d19186
 #else
d19186
+#define BROTLI_DCHECK(x)
d19186
 #define BROTLI_DUMP() (void)(0)
d19186
 #endif
d19186
 
d19186
diff --git a/c/dec/bit_reader.c b/c/dec/bit_reader.c
d19186
index 722fd90..7f7b256 100644
d19186
--- a/c/dec/bit_reader.c
d19186
+++ b/c/dec/bit_reader.c
d19186
@@ -15,6 +15,17 @@
d19186
 extern "C" {
d19186
 #endif
d19186
 
d19186
+const uint32_t kBrotliBitMask[33] = {   0x00000000,
d19186
+    0x00000001, 0x00000003, 0x00000007, 0x0000000F,
d19186
+    0x0000001F, 0x0000003F, 0x0000007F, 0x000000FF,
d19186
+    0x000001FF, 0x000003FF, 0x000007FF, 0x00000FFF,
d19186
+    0x00001FFF, 0x00003FFF, 0x00007FFF, 0x0000FFFF,
d19186
+    0x0001FFFF, 0x0003FFFF, 0x0007FFFF, 0x000FFFFF,
d19186
+    0x001FFFFF, 0x003FFFFF, 0x007FFFFF, 0x00FFFFFF,
d19186
+    0x01FFFFFF, 0x03FFFFFF, 0x07FFFFFF, 0x0FFFFFFF,
d19186
+    0x1FFFFFFF, 0x3FFFFFFF, 0x7FFFFFFF, 0xFFFFFFFF
d19186
+};
d19186
+
d19186
 void BrotliInitBitReader(BrotliBitReader* const br) {
d19186
   br->val_ = 0;
d19186
   br->bit_pos_ = sizeof(br->val_) << 3;
d19186
@@ -43,6 +54,23 @@ BROTLI_BOOL BrotliWarmupBitReader(BrotliBitReader* const br) {
d19186
   return BROTLI_TRUE;
d19186
 }
d19186
 
d19186
+BROTLI_BOOL BrotliSafeReadBits32Slow(BrotliBitReader* const br,
d19186
+    uint32_t n_bits, uint32_t* val) {
d19186
+  uint32_t low_val;
d19186
+  uint32_t high_val;
d19186
+  BrotliBitReaderState memento;
d19186
+  BROTLI_DCHECK(n_bits <= 32);
d19186
+  BROTLI_DCHECK(n_bits > 24);
d19186
+  BrotliBitReaderSaveState(br, &memento);
d19186
+  if (!BrotliSafeReadBits(br, 16, &low_val) ||
d19186
+      !BrotliSafeReadBits(br, n_bits - 16, &high_val)) {
d19186
+    BrotliBitReaderRestoreState(br, &memento);
d19186
+    return BROTLI_FALSE;
d19186
+  }
d19186
+  *val = low_val | (high_val << 16);
d19186
+  return BROTLI_TRUE;
d19186
+}
d19186
+
d19186
 #if defined(__cplusplus) || defined(c_plusplus)
d19186
 }  /* extern "C" */
d19186
 #endif
d19186
diff --git a/c/dec/bit_reader.h b/c/dec/bit_reader.h
d19186
index c06e914..22bc060 100644
d19186
--- a/c/dec/bit_reader.h
d19186
+++ b/c/dec/bit_reader.h
d19186
@@ -11,6 +11,7 @@
d19186
 
d19186
 #include <string.h>  /* memcpy */
d19186
 
d19186
+#include "../common/constants.h"
d19186
 #include "../common/platform.h"
d19186
 #include <brotli/types.h>
d19186
 
d19186
@@ -20,16 +21,7 @@ extern "C" {
d19186
 
d19186
 #define BROTLI_SHORT_FILL_BIT_WINDOW_READ (sizeof(brotli_reg_t) >> 1)
d19186
 
d19186
-static const uint32_t kBitMask[33] = {  0x00000000,
d19186
-    0x00000001, 0x00000003, 0x00000007, 0x0000000F,
d19186
-    0x0000001F, 0x0000003F, 0x0000007F, 0x000000FF,
d19186
-    0x000001FF, 0x000003FF, 0x000007FF, 0x00000FFF,
d19186
-    0x00001FFF, 0x00003FFF, 0x00007FFF, 0x0000FFFF,
d19186
-    0x0001FFFF, 0x0003FFFF, 0x0007FFFF, 0x000FFFFF,
d19186
-    0x001FFFFF, 0x003FFFFF, 0x007FFFFF, 0x00FFFFFF,
d19186
-    0x01FFFFFF, 0x03FFFFFF, 0x07FFFFFF, 0x0FFFFFFF,
d19186
-    0x1FFFFFFF, 0x3FFFFFFF, 0x7FFFFFFF, 0xFFFFFFFF
d19186
-};
d19186
+BROTLI_INTERNAL extern const uint32_t kBrotliBitMask[33];
d19186
 
d19186
 static BROTLI_INLINE uint32_t BitMask(uint32_t n) {
d19186
   if (BROTLI_IS_CONSTANT(n) || BROTLI_HAS_UBFX) {
d19186
@@ -37,7 +29,7 @@ static BROTLI_INLINE uint32_t BitMask(uint32_t n) {
d19186
        "Unsigned Bit Field Extract" UBFX instruction on ARM. */
d19186
     return ~((0xFFFFFFFFu) << n);
d19186
   } else {
d19186
-    return kBitMask[n];
d19186
+    return kBrotliBitMask[n];
d19186
   }
d19186
 }
d19186
 
d19186
@@ -65,6 +57,12 @@ BROTLI_INTERNAL void BrotliInitBitReader(BrotliBitReader* const br);
d19186
    reading. */
d19186
 BROTLI_INTERNAL BROTLI_BOOL BrotliWarmupBitReader(BrotliBitReader* const br);
d19186
 
d19186
+/* Fallback for BrotliSafeReadBits32. Extracted as noninlined method to unburden
d19186
+   the main code-path. Never called for RFC brotli streams, required only for
d19186
+   "large-window" mode and other extensions. */
d19186
+BROTLI_INTERNAL BROTLI_NOINLINE BROTLI_BOOL BrotliSafeReadBits32Slow(
d19186
+    BrotliBitReader* const br, uint32_t n_bits, uint32_t* val);
d19186
+
d19186
 static BROTLI_INLINE void BrotliBitReaderSaveState(
d19186
     BrotliBitReader* const from, BrotliBitReaderState* to) {
d19186
   to->val_ = from->val_;
d19186
@@ -87,8 +85,11 @@ static BROTLI_INLINE uint32_t BrotliGetAvailableBits(
d19186
 }
d19186
 
d19186
 /* Returns amount of unread bytes the bit reader still has buffered from the
d19186
-   BrotliInput, including whole bytes in br->val_. */
d19186
+   BrotliInput, including whole bytes in br->val_. Result is capped with
d19186
+   maximal ring-buffer size (larger number won't be utilized anyway). */
d19186
 static BROTLI_INLINE size_t BrotliGetRemainingBytes(BrotliBitReader* br) {
d19186
+  static const size_t kCap = (size_t)1 << BROTLI_LARGE_MAX_WBITS;
d19186
+  if (br->avail_in > kCap) return kCap;
d19186
   return br->avail_in + (BrotliGetAvailableBits(br) >> 3);
d19186
 }
d19186
 
d19186
@@ -237,15 +238,17 @@ static BROTLI_INLINE void BrotliBitReaderUnload(BrotliBitReader* br) {
d19186
 static BROTLI_INLINE void BrotliTakeBits(
d19186
   BrotliBitReader* const br, uint32_t n_bits, uint32_t* val) {
d19186
   *val = (uint32_t)BrotliGetBitsUnmasked(br) & BitMask(n_bits);
d19186
-  BROTLI_LOG(("[BrotliReadBits]  %d %d %d val: %6x\n",
d19186
+  BROTLI_LOG(("[BrotliTakeBits]  %d %d %d val: %6x\n",
d19186
       (int)br->avail_in, (int)br->bit_pos_, (int)n_bits, (int)*val));
d19186
   BrotliDropBits(br, n_bits);
d19186
 }
d19186
 
d19186
 /* Reads the specified number of bits from |br| and advances the bit pos.
d19186
-   Assumes that there is enough input to perform BrotliFillBitWindow. */
d19186
-static BROTLI_INLINE uint32_t BrotliReadBits(
d19186
+   Assumes that there is enough input to perform BrotliFillBitWindow.
d19186
+   Up to 24 bits are allowed to be requested from this method. */
d19186
+static BROTLI_INLINE uint32_t BrotliReadBits24(
d19186
     BrotliBitReader* const br, uint32_t n_bits) {
d19186
+  BROTLI_DCHECK(n_bits <= 24);
d19186
   if (BROTLI_64_BITS || (n_bits <= 16)) {
d19186
     uint32_t val;
d19186
     BrotliFillBitWindow(br, n_bits);
d19186
@@ -262,10 +265,32 @@ static BROTLI_INLINE uint32_t BrotliReadBits(
d19186
   }
d19186
 }
d19186
 
d19186
+/* Same as BrotliReadBits24, but allows reading up to 32 bits. */
d19186
+static BROTLI_INLINE uint32_t BrotliReadBits32(
d19186
+    BrotliBitReader* const br, uint32_t n_bits) {
d19186
+  BROTLI_DCHECK(n_bits <= 32);
d19186
+  if (BROTLI_64_BITS || (n_bits <= 16)) {
d19186
+    uint32_t val;
d19186
+    BrotliFillBitWindow(br, n_bits);
d19186
+    BrotliTakeBits(br, n_bits, &val;;
d19186
+    return val;
d19186
+  } else {
d19186
+    uint32_t low_val;
d19186
+    uint32_t high_val;
d19186
+    BrotliFillBitWindow(br, 16);
d19186
+    BrotliTakeBits(br, 16, &low_val);
d19186
+    BrotliFillBitWindow(br, 16);
d19186
+    BrotliTakeBits(br, n_bits - 16, &high_val);
d19186
+    return low_val | (high_val << 16);
d19186
+  }
d19186
+}
d19186
+
d19186
 /* Tries to read the specified amount of bits. Returns BROTLI_FALSE, if there
d19186
-   is not enough input. |n_bits| MUST be positive. */
d19186
+   is not enough input. |n_bits| MUST be positive.
d19186
+   Up to 24 bits are allowed to be requested from this method. */
d19186
 static BROTLI_INLINE BROTLI_BOOL BrotliSafeReadBits(
d19186
     BrotliBitReader* const br, uint32_t n_bits, uint32_t* val) {
d19186
+  BROTLI_DCHECK(n_bits <= 24);
d19186
   while (BrotliGetAvailableBits(br) < n_bits) {
d19186
     if (!BrotliPullByte(br)) {
d19186
       return BROTLI_FALSE;
d19186
@@ -275,6 +300,23 @@ static BROTLI_INLINE BROTLI_BOOL BrotliSafeReadBits(
d19186
   return BROTLI_TRUE;
d19186
 }
d19186
 
d19186
+/* Same as BrotliSafeReadBits, but allows reading up to 32 bits. */
d19186
+static BROTLI_INLINE BROTLI_BOOL BrotliSafeReadBits32(
d19186
+    BrotliBitReader* const br, uint32_t n_bits, uint32_t* val) {
d19186
+  BROTLI_DCHECK(n_bits <= 32);
d19186
+  if (BROTLI_64_BITS || (n_bits <= 24)) {
d19186
+    while (BrotliGetAvailableBits(br) < n_bits) {
d19186
+      if (!BrotliPullByte(br)) {
d19186
+        return BROTLI_FALSE;
d19186
+      }
d19186
+    }
d19186
+    BrotliTakeBits(br, n_bits, val);
d19186
+    return BROTLI_TRUE;
d19186
+  } else {
d19186
+    return BrotliSafeReadBits32Slow(br, n_bits, val);
d19186
+  }
d19186
+}
d19186
+
d19186
 /* Advances the bit reader position to the next byte boundary and verifies
d19186
    that any skipped bits are set to zero. */
d19186
 static BROTLI_INLINE BROTLI_BOOL BrotliJumpToByteBoundary(BrotliBitReader* br) {
d19186
diff --git a/c/dec/decode.c b/c/dec/decode.c
d19186
index 674b829..ae5a3d3 100644
d19186
--- a/c/dec/decode.c
d19186
+++ b/c/dec/decode.c
d19186
@@ -6,10 +6,6 @@
d19186
 
d19186
 #include <brotli/decode.h>
d19186
 
d19186
-#if defined(__ARM_NEON__)
d19186
-#include <arm_neon.h>
d19186
-#endif
d19186
-
d19186
 #include <stdlib.h>  /* free, malloc */
d19186
 #include <string.h>  /* memcpy, memset */
d19186
 
d19186
@@ -24,6 +20,10 @@
d19186
 #include "./prefix.h"
d19186
 #include "./state.h"
d19186
 
d19186
+#if defined(BROTLI_TARGET_NEON)
d19186
+#include <arm_neon.h>
d19186
+#endif
d19186
+
d19186
 #if defined(__cplusplus) || defined(c_plusplus)
d19186
 extern "C" {
d19186
 #endif
d19186
@@ -41,7 +41,8 @@ extern "C" {
d19186
 
d19186
 /* We need the slack region for the following reasons:
d19186
     - doing up to two 16-byte copies for fast backward copying
d19186
-    - inserting transformed dictionary word (5 prefix + 24 base + 8 suffix) */
d19186
+    - inserting transformed dictionary word:
d19186
+        5 prefix + 24 base + 8 suffix */
d19186
 static const uint32_t kRingBufferWriteAheadSlack = 42;
d19186
 
d19186
 static const uint8_t kCodeLengthCodeOrder[BROTLI_CODE_LENGTH_CODES] = {
d19186
@@ -167,7 +168,7 @@ static BrotliDecoderErrorCode DecodeWindowBits(BrotliDecoderState* s,
d19186
 }
d19186
 
d19186
 static BROTLI_INLINE void memmove16(uint8_t* dst, uint8_t* src) {
d19186
-#if defined(__ARM_NEON__)
d19186
+#if defined(BROTLI_TARGET_NEON)
d19186
   vst1q_u8(dst, vld1q_u8(src));
d19186
 #else
d19186
   uint32_t buffer[4];
d19186
@@ -274,7 +275,8 @@ static BrotliDecoderErrorCode BROTLI_NOINLINE DecodeMetaBlockLength(
d19186
             s->loop_counter = i;
d19186
             return BROTLI_DECODER_NEEDS_MORE_INPUT;
d19186
           }
d19186
-          if (i + 1 == s->size_nibbles && s->size_nibbles > 4 && bits == 0) {
d19186
+          if (i + 1 == (int)s->size_nibbles && s->size_nibbles > 4 &&
d19186
+              bits == 0) {
d19186
             return BROTLI_FAILURE(BROTLI_DECODER_ERROR_FORMAT_EXUBERANT_NIBBLE);
d19186
           }
d19186
           s->meta_block_remaining_len |= (int)(bits << (i * 4));
d19186
@@ -323,7 +325,8 @@ static BrotliDecoderErrorCode BROTLI_NOINLINE DecodeMetaBlockLength(
d19186
             s->loop_counter = i;
d19186
             return BROTLI_DECODER_NEEDS_MORE_INPUT;
d19186
           }
d19186
-          if (i + 1 == s->size_nibbles && s->size_nibbles > 1 && bits == 0) {
d19186
+          if (i + 1 == (int)s->size_nibbles && s->size_nibbles > 1 &&
d19186
+              bits == 0) {
d19186
             return BROTLI_FAILURE(
d19186
                 BROTLI_DECODER_ERROR_FORMAT_EXUBERANT_META_NIBBLE);
d19186
           }
d19186
@@ -347,15 +350,17 @@ static BrotliDecoderErrorCode BROTLI_NOINLINE DecodeMetaBlockLength(
d19186
 static BROTLI_INLINE uint32_t DecodeSymbol(uint32_t bits,
d19186
                                            const HuffmanCode* table,
d19186
                                            BrotliBitReader* br) {
d19186
-  table += bits & HUFFMAN_TABLE_MASK;
d19186
-  if (table->bits > HUFFMAN_TABLE_BITS) {
d19186
-    uint32_t nbits = table->bits - HUFFMAN_TABLE_BITS;
d19186
+  BROTLI_HC_MARK_TABLE_FOR_FAST_LOAD(table);
d19186
+  BROTLI_HC_ADJUST_TABLE_INDEX(table, bits & HUFFMAN_TABLE_MASK);
d19186
+  if (BROTLI_HC_FAST_LOAD_BITS(table) > HUFFMAN_TABLE_BITS) {
d19186
+    uint32_t nbits = BROTLI_HC_FAST_LOAD_BITS(table) - HUFFMAN_TABLE_BITS;
d19186
     BrotliDropBits(br, HUFFMAN_TABLE_BITS);
d19186
-    table += table->value;
d19186
-    table += (bits >> HUFFMAN_TABLE_BITS) & BitMask(nbits);
d19186
+    BROTLI_HC_ADJUST_TABLE_INDEX(table,
d19186
+        BROTLI_HC_FAST_LOAD_VALUE(table) +
d19186
+        ((bits >> HUFFMAN_TABLE_BITS) & BitMask(nbits)));
d19186
   }
d19186
-  BrotliDropBits(br, table->bits);
d19186
-  return table->value;
d19186
+  BrotliDropBits(br, BROTLI_HC_FAST_LOAD_BITS(table));
d19186
+  return BROTLI_HC_FAST_LOAD_VALUE(table);
d19186
 }
d19186
 
d19186
 /* Reads and decodes the next Huffman code from bit-stream.
d19186
@@ -371,19 +376,20 @@ static BROTLI_NOINLINE BROTLI_BOOL SafeDecodeSymbol(
d19186
     const HuffmanCode* table, BrotliBitReader* br, uint32_t* result) {
d19186
   uint32_t val;
d19186
   uint32_t available_bits = BrotliGetAvailableBits(br);
d19186
+  BROTLI_HC_MARK_TABLE_FOR_FAST_LOAD(table);
d19186
   if (available_bits == 0) {
d19186
-    if (table->bits == 0) {
d19186
-      *result = table->value;
d19186
+    if (BROTLI_HC_FAST_LOAD_BITS(table) == 0) {
d19186
+      *result = BROTLI_HC_FAST_LOAD_VALUE(table);
d19186
       return BROTLI_TRUE;
d19186
     }
d19186
     return BROTLI_FALSE;  /* No valid bits at all. */
d19186
   }
d19186
   val = (uint32_t)BrotliGetBitsUnmasked(br);
d19186
-  table += val & HUFFMAN_TABLE_MASK;
d19186
-  if (table->bits <= HUFFMAN_TABLE_BITS) {
d19186
-    if (table->bits <= available_bits) {
d19186
-      BrotliDropBits(br, table->bits);
d19186
-      *result = table->value;
d19186
+  BROTLI_HC_ADJUST_TABLE_INDEX(table, val & HUFFMAN_TABLE_MASK);
d19186
+  if (BROTLI_HC_FAST_LOAD_BITS(table) <= HUFFMAN_TABLE_BITS) {
d19186
+    if (BROTLI_HC_FAST_LOAD_BITS(table) <= available_bits) {
d19186
+      BrotliDropBits(br, BROTLI_HC_FAST_LOAD_BITS(table));
d19186
+      *result = BROTLI_HC_FAST_LOAD_VALUE(table);
d19186
       return BROTLI_TRUE;
d19186
     } else {
d19186
       return BROTLI_FALSE;  /* Not enough bits for the first level. */
d19186
@@ -394,15 +400,15 @@ static BROTLI_NOINLINE BROTLI_BOOL SafeDecodeSymbol(
d19186
   }
d19186
 
d19186
   /* Speculatively drop HUFFMAN_TABLE_BITS. */
d19186
-  val = (val & BitMask(table->bits)) >> HUFFMAN_TABLE_BITS;
d19186
+  val = (val & BitMask(BROTLI_HC_FAST_LOAD_BITS(table))) >> HUFFMAN_TABLE_BITS;
d19186
   available_bits -= HUFFMAN_TABLE_BITS;
d19186
-  table += table->value + val;
d19186
-  if (available_bits < table->bits) {
d19186
+  BROTLI_HC_ADJUST_TABLE_INDEX(table, BROTLI_HC_FAST_LOAD_VALUE(table) + val);
d19186
+  if (available_bits < BROTLI_HC_FAST_LOAD_BITS(table)) {
d19186
     return BROTLI_FALSE;  /* Not enough bits for the second level. */
d19186
   }
d19186
 
d19186
-  BrotliDropBits(br, HUFFMAN_TABLE_BITS + table->bits);
d19186
-  *result = table->value;
d19186
+  BrotliDropBits(br, HUFFMAN_TABLE_BITS + BROTLI_HC_FAST_LOAD_BITS(table));
d19186
+  *result = BROTLI_HC_FAST_LOAD_VALUE(table);
d19186
   return BROTLI_TRUE;
d19186
 }
d19186
 
d19186
@@ -425,9 +431,10 @@ static BROTLI_INLINE void PreloadSymbol(int safe,
d19186
   if (safe) {
d19186
     return;
d19186
   }
d19186
-  table += BrotliGetBits(br, HUFFMAN_TABLE_BITS);
d19186
-  *bits = table->bits;
d19186
-  *value = table->value;
d19186
+  BROTLI_HC_MARK_TABLE_FOR_FAST_LOAD(table);
d19186
+  BROTLI_HC_ADJUST_TABLE_INDEX(table, BrotliGetBits(br, HUFFMAN_TABLE_BITS));
d19186
+  *bits = BROTLI_HC_FAST_LOAD_BITS(table);
d19186
+  *value = BROTLI_HC_FAST_LOAD_VALUE(table);
d19186
 }
d19186
 
d19186
 /* Decodes the next Huffman code using data prepared by PreloadSymbol.
d19186
@@ -441,10 +448,11 @@ static BROTLI_INLINE uint32_t ReadPreloadedSymbol(const HuffmanCode* table,
d19186
     uint32_t val = BrotliGet16BitsUnmasked(br);
d19186
     const HuffmanCode* ext = table + (val & HUFFMAN_TABLE_MASK) + *value;
d19186
     uint32_t mask = BitMask((*bits - HUFFMAN_TABLE_BITS));
d19186
+    BROTLI_HC_MARK_TABLE_FOR_FAST_LOAD(ext);
d19186
     BrotliDropBits(br, HUFFMAN_TABLE_BITS);
d19186
-    ext += (val >> HUFFMAN_TABLE_BITS) & mask;
d19186
-    BrotliDropBits(br, ext->bits);
d19186
-    result = ext->value;
d19186
+    BROTLI_HC_ADJUST_TABLE_INDEX(ext, (val >> HUFFMAN_TABLE_BITS) & mask);
d19186
+    BrotliDropBits(br, BROTLI_HC_FAST_LOAD_BITS(ext));
d19186
+    result = BROTLI_HC_FAST_LOAD_VALUE(ext);
d19186
   } else {
d19186
     BrotliDropBits(br, *bits);
d19186
   }
d19186
@@ -465,32 +473,34 @@ static BROTLI_INLINE uint32_t Log2Floor(uint32_t x) {
d19186
    Totally 1..4 symbols are read, 1..11 bits each.
d19186
    The list of symbols MUST NOT contain duplicates. */
d19186
 static BrotliDecoderErrorCode ReadSimpleHuffmanSymbols(
d19186
-    uint32_t alphabet_size, uint32_t max_symbol, BrotliDecoderState* s) {
d19186
+    uint32_t alphabet_size_max, uint32_t alphabet_size_limit,
d19186
+    BrotliDecoderState* s) {
d19186
   /* max_bits == 1..11; symbol == 0..3; 1..44 bits will be read. */
d19186
   BrotliBitReader* br = &s->br;
d19186
-  uint32_t max_bits = Log2Floor(alphabet_size - 1);
d19186
-  uint32_t i = s->sub_loop_counter;
d19186
-  uint32_t num_symbols = s->symbol;
d19186
+  BrotliMetablockHeaderArena* h = &s->arena.header;
d19186
+  uint32_t max_bits = Log2Floor(alphabet_size_max - 1);
d19186
+  uint32_t i = h->sub_loop_counter;
d19186
+  uint32_t num_symbols = h->symbol;
d19186
   while (i <= num_symbols) {
d19186
     uint32_t v;
d19186
     if (BROTLI_PREDICT_FALSE(!BrotliSafeReadBits(br, max_bits, &v))) {
d19186
-      s->sub_loop_counter = i;
d19186
-      s->substate_huffman = BROTLI_STATE_HUFFMAN_SIMPLE_READ;
d19186
+      h->sub_loop_counter = i;
d19186
+      h->substate_huffman = BROTLI_STATE_HUFFMAN_SIMPLE_READ;
d19186
       return BROTLI_DECODER_NEEDS_MORE_INPUT;
d19186
     }
d19186
-    if (v >= max_symbol) {
d19186
+    if (v >= alphabet_size_limit) {
d19186
       return
d19186
           BROTLI_FAILURE(BROTLI_DECODER_ERROR_FORMAT_SIMPLE_HUFFMAN_ALPHABET);
d19186
     }
d19186
-    s->symbols_lists_array[i] = (uint16_t)v;
d19186
-    BROTLI_LOG_UINT(s->symbols_lists_array[i]);
d19186
+    h->symbols_lists_array[i] = (uint16_t)v;
d19186
+    BROTLI_LOG_UINT(h->symbols_lists_array[i]);
d19186
     ++i;
d19186
   }
d19186
 
d19186
   for (i = 0; i < num_symbols; ++i) {
d19186
     uint32_t k = i + 1;
d19186
     for (; k <= num_symbols; ++k) {
d19186
-      if (s->symbols_lists_array[i] == s->symbols_lists_array[k]) {
d19186
+      if (h->symbols_lists_array[i] == h->symbols_lists_array[k]) {
d19186
         return BROTLI_FAILURE(BROTLI_DECODER_ERROR_FORMAT_SIMPLE_HUFFMAN_SAME);
d19186
       }
d19186
     }
d19186
@@ -583,33 +593,35 @@ static BROTLI_INLINE void ProcessRepeatedCodeLength(uint32_t code_len,
d19186
 static BrotliDecoderErrorCode ReadSymbolCodeLengths(
d19186
     uint32_t alphabet_size, BrotliDecoderState* s) {
d19186
   BrotliBitReader* br = &s->br;
d19186
-  uint32_t symbol = s->symbol;
d19186
-  uint32_t repeat = s->repeat;
d19186
-  uint32_t space = s->space;
d19186
-  uint32_t prev_code_len = s->prev_code_len;
d19186
-  uint32_t repeat_code_len = s->repeat_code_len;
d19186
-  uint16_t* symbol_lists = s->symbol_lists;
d19186
-  uint16_t* code_length_histo = s->code_length_histo;
d19186
-  int* next_symbol = s->next_symbol;
d19186
+  BrotliMetablockHeaderArena* h = &s->arena.header;
d19186
+  uint32_t symbol = h->symbol;
d19186
+  uint32_t repeat = h->repeat;
d19186
+  uint32_t space = h->space;
d19186
+  uint32_t prev_code_len = h->prev_code_len;
d19186
+  uint32_t repeat_code_len = h->repeat_code_len;
d19186
+  uint16_t* symbol_lists = h->symbol_lists;
d19186
+  uint16_t* code_length_histo = h->code_length_histo;
d19186
+  int* next_symbol = h->next_symbol;
d19186
   if (!BrotliWarmupBitReader(br)) {
d19186
     return BROTLI_DECODER_NEEDS_MORE_INPUT;
d19186
   }
d19186
   while (symbol < alphabet_size && space > 0) {
d19186
-    const HuffmanCode* p = s->table;
d19186
+    const HuffmanCode* p = h->table;
d19186
     uint32_t code_len;
d19186
+    BROTLI_HC_MARK_TABLE_FOR_FAST_LOAD(p);
d19186
     if (!BrotliCheckInputAmount(br, BROTLI_SHORT_FILL_BIT_WINDOW_READ)) {
d19186
-      s->symbol = symbol;
d19186
-      s->repeat = repeat;
d19186
-      s->prev_code_len = prev_code_len;
d19186
-      s->repeat_code_len = repeat_code_len;
d19186
-      s->space = space;
d19186
+      h->symbol = symbol;
d19186
+      h->repeat = repeat;
d19186
+      h->prev_code_len = prev_code_len;
d19186
+      h->repeat_code_len = repeat_code_len;
d19186
+      h->space = space;
d19186
       return BROTLI_DECODER_NEEDS_MORE_INPUT;
d19186
     }
d19186
     BrotliFillBitWindow16(br);
d19186
-    p += BrotliGetBitsUnmasked(br) &
d19186
-        BitMask(BROTLI_HUFFMAN_MAX_CODE_LENGTH_CODE_LENGTH);
d19186
-    BrotliDropBits(br, p->bits);  /* Use 1..5 bits. */
d19186
-    code_len = p->value;  /* code_len == 0..17 */
d19186
+    BROTLI_HC_ADJUST_TABLE_INDEX(p, BrotliGetBitsUnmasked(br) &
d19186
+        BitMask(BROTLI_HUFFMAN_MAX_CODE_LENGTH_CODE_LENGTH));
d19186
+    BrotliDropBits(br, BROTLI_HC_FAST_LOAD_BITS(p));  /* Use 1..5 bits. */
d19186
+    code_len = BROTLI_HC_FAST_LOAD_VALUE(p);  /* code_len == 0..17 */
d19186
     if (code_len < BROTLI_REPEAT_PREVIOUS_CODE_LENGTH) {
d19186
       ProcessSingleCodeLength(code_len, &symbol, &repeat, &space,
d19186
           &prev_code_len, symbol_lists, code_length_histo, next_symbol);
d19186
@@ -624,48 +636,52 @@ static BrotliDecoderErrorCode ReadSymbolCodeLengths(
d19186
           symbol_lists, code_length_histo, next_symbol);
d19186
     }
d19186
   }
d19186
-  s->space = space;
d19186
+  h->space = space;
d19186
   return BROTLI_DECODER_SUCCESS;
d19186
 }
d19186
 
d19186
 static BrotliDecoderErrorCode SafeReadSymbolCodeLengths(
d19186
     uint32_t alphabet_size, BrotliDecoderState* s) {
d19186
   BrotliBitReader* br = &s->br;
d19186
+  BrotliMetablockHeaderArena* h = &s->arena.header;
d19186
   BROTLI_BOOL get_byte = BROTLI_FALSE;
d19186
-  while (s->symbol < alphabet_size && s->space > 0) {
d19186
-    const HuffmanCode* p = s->table;
d19186
+  while (h->symbol < alphabet_size && h->space > 0) {
d19186
+    const HuffmanCode* p = h->table;
d19186
     uint32_t code_len;
d19186
     uint32_t available_bits;
d19186
     uint32_t bits = 0;
d19186
+    BROTLI_HC_MARK_TABLE_FOR_FAST_LOAD(p);
d19186
     if (get_byte && !BrotliPullByte(br)) return BROTLI_DECODER_NEEDS_MORE_INPUT;
d19186
     get_byte = BROTLI_FALSE;
d19186
     available_bits = BrotliGetAvailableBits(br);
d19186
     if (available_bits != 0) {
d19186
       bits = (uint32_t)BrotliGetBitsUnmasked(br);
d19186
     }
d19186
-    p += bits & BitMask(BROTLI_HUFFMAN_MAX_CODE_LENGTH_CODE_LENGTH);
d19186
-    if (p->bits > available_bits) {
d19186
+    BROTLI_HC_ADJUST_TABLE_INDEX(p,
d19186
+        bits & BitMask(BROTLI_HUFFMAN_MAX_CODE_LENGTH_CODE_LENGTH));
d19186
+    if (BROTLI_HC_FAST_LOAD_BITS(p) > available_bits) {
d19186
       get_byte = BROTLI_TRUE;
d19186
       continue;
d19186
     }
d19186
-    code_len = p->value;  /* code_len == 0..17 */
d19186
+    code_len = BROTLI_HC_FAST_LOAD_VALUE(p);  /* code_len == 0..17 */
d19186
     if (code_len < BROTLI_REPEAT_PREVIOUS_CODE_LENGTH) {
d19186
-      BrotliDropBits(br, p->bits);
d19186
-      ProcessSingleCodeLength(code_len, &s->symbol, &s->repeat, &s->space,
d19186
-          &s->prev_code_len, s->symbol_lists, s->code_length_histo,
d19186
-          s->next_symbol);
d19186
+      BrotliDropBits(br, BROTLI_HC_FAST_LOAD_BITS(p));
d19186
+      ProcessSingleCodeLength(code_len, &h->symbol, &h->repeat, &h->space,
d19186
+          &h->prev_code_len, h->symbol_lists, h->code_length_histo,
d19186
+          h->next_symbol);
d19186
     } else {  /* code_len == 16..17, extra_bits == 2..3 */
d19186
       uint32_t extra_bits = code_len - 14U;
d19186
-      uint32_t repeat_delta = (bits >> p->bits) & BitMask(extra_bits);
d19186
-      if (available_bits < p->bits + extra_bits) {
d19186
+      uint32_t repeat_delta = (bits >> BROTLI_HC_FAST_LOAD_BITS(p)) &
d19186
+          BitMask(extra_bits);
d19186
+      if (available_bits < BROTLI_HC_FAST_LOAD_BITS(p) + extra_bits) {
d19186
         get_byte = BROTLI_TRUE;
d19186
         continue;
d19186
       }
d19186
-      BrotliDropBits(br, p->bits + extra_bits);
d19186
+      BrotliDropBits(br, BROTLI_HC_FAST_LOAD_BITS(p) + extra_bits);
d19186
       ProcessRepeatedCodeLength(code_len, repeat_delta, alphabet_size,
d19186
-          &s->symbol, &s->repeat, &s->space, &s->prev_code_len,
d19186
-          &s->repeat_code_len, s->symbol_lists, s->code_length_histo,
d19186
-          s->next_symbol);
d19186
+          &h->symbol, &h->repeat, &h->space, &h->prev_code_len,
d19186
+          &h->repeat_code_len, h->symbol_lists, h->code_length_histo,
d19186
+          h->next_symbol);
d19186
     }
d19186
   }
d19186
   return BROTLI_DECODER_SUCCESS;
d19186
@@ -675,9 +691,10 @@ static BrotliDecoderErrorCode SafeReadSymbolCodeLengths(
d19186
    Each code is 2..4 bits long. In total 30..72 bits are used. */
d19186
 static BrotliDecoderErrorCode ReadCodeLengthCodeLengths(BrotliDecoderState* s) {
d19186
   BrotliBitReader* br = &s->br;
d19186
-  uint32_t num_codes = s->repeat;
d19186
-  unsigned space = s->space;
d19186
-  uint32_t i = s->sub_loop_counter;
d19186
+  BrotliMetablockHeaderArena* h = &s->arena.header;
d19186
+  uint32_t num_codes = h->repeat;
d19186
+  unsigned space = h->space;
d19186
+  uint32_t i = h->sub_loop_counter;
d19186
   for (; i < BROTLI_CODE_LENGTH_CODES; ++i) {
d19186
     const uint8_t code_len_idx = kCodeLengthCodeOrder[i];
d19186
     uint32_t ix;
d19186
@@ -690,21 +707,21 @@ static BrotliDecoderErrorCode ReadCodeLengthCodeLengths(BrotliDecoderState* s) {
d19186
         ix = 0;
d19186
       }
d19186
       if (kCodeLengthPrefixLength[ix] > available_bits) {
d19186
-        s->sub_loop_counter = i;
d19186
-        s->repeat = num_codes;
d19186
-        s->space = space;
d19186
-        s->substate_huffman = BROTLI_STATE_HUFFMAN_COMPLEX;
d19186
+        h->sub_loop_counter = i;
d19186
+        h->repeat = num_codes;
d19186
+        h->space = space;
d19186
+        h->substate_huffman = BROTLI_STATE_HUFFMAN_COMPLEX;
d19186
         return BROTLI_DECODER_NEEDS_MORE_INPUT;
d19186
       }
d19186
     }
d19186
     v = kCodeLengthPrefixValue[ix];
d19186
     BrotliDropBits(br, kCodeLengthPrefixLength[ix]);
d19186
-    s->code_length_code_lengths[code_len_idx] = (uint8_t)v;
d19186
-    BROTLI_LOG_ARRAY_INDEX(s->code_length_code_lengths, code_len_idx);
d19186
+    h->code_length_code_lengths[code_len_idx] = (uint8_t)v;
d19186
+    BROTLI_LOG_ARRAY_INDEX(h->code_length_code_lengths, code_len_idx);
d19186
     if (v != 0) {
d19186
       space = space - (32U >> v);
d19186
       ++num_codes;
d19186
-      ++s->code_length_histo[v];
d19186
+      ++h->code_length_histo[v];
d19186
       if (space - 1U >= 32U) {
d19186
         /* space is 0 or wrapped around. */
d19186
         break;
d19186
@@ -728,49 +745,48 @@ static BrotliDecoderErrorCode ReadCodeLengthCodeLengths(BrotliDecoderState* s) {
d19186
          encoded with predefined entropy code. 32 - 74 bits are used.
d19186
     B.2) Decoded table is used to decode code lengths of symbols in resulting
d19186
          Huffman table. In worst case 3520 bits are read. */
d19186
-static BrotliDecoderErrorCode ReadHuffmanCode(uint32_t alphabet_size,
d19186
-                                              uint32_t max_symbol,
d19186
+static BrotliDecoderErrorCode ReadHuffmanCode(uint32_t alphabet_size_max,
d19186
+                                              uint32_t alphabet_size_limit,
d19186
                                               HuffmanCode* table,
d19186
                                               uint32_t* opt_table_size,
d19186
                                               BrotliDecoderState* s) {
d19186
   BrotliBitReader* br = &s->br;
d19186
-  /* Unnecessary masking, but might be good for safety. */
d19186
-  alphabet_size &= 0x7FF;
d19186
+  BrotliMetablockHeaderArena* h = &s->arena.header;
d19186
   /* State machine. */
d19186
   for (;;) {
d19186
-    switch (s->substate_huffman) {
d19186
+    switch (h->substate_huffman) {
d19186
       case BROTLI_STATE_HUFFMAN_NONE:
d19186
-        if (!BrotliSafeReadBits(br, 2, &s->sub_loop_counter)) {
d19186
+        if (!BrotliSafeReadBits(br, 2, &h->sub_loop_counter)) {
d19186
           return BROTLI_DECODER_NEEDS_MORE_INPUT;
d19186
         }
d19186
-        BROTLI_LOG_UINT(s->sub_loop_counter);
d19186
+        BROTLI_LOG_UINT(h->sub_loop_counter);
d19186
         /* The value is used as follows:
d19186
            1 for simple code;
d19186
            0 for no skipping, 2 skips 2 code lengths, 3 skips 3 code lengths */
d19186
-        if (s->sub_loop_counter != 1) {
d19186
-          s->space = 32;
d19186
-          s->repeat = 0;  /* num_codes */
d19186
-          memset(&s->code_length_histo[0], 0, sizeof(s->code_length_histo[0]) *
d19186
+        if (h->sub_loop_counter != 1) {
d19186
+          h->space = 32;
d19186
+          h->repeat = 0;  /* num_codes */
d19186
+          memset(&h->code_length_histo[0], 0, sizeof(h->code_length_histo[0]) *
d19186
               (BROTLI_HUFFMAN_MAX_CODE_LENGTH_CODE_LENGTH + 1));
d19186
-          memset(&s->code_length_code_lengths[0], 0,
d19186
-              sizeof(s->code_length_code_lengths));
d19186
-          s->substate_huffman = BROTLI_STATE_HUFFMAN_COMPLEX;
d19186
+          memset(&h->code_length_code_lengths[0], 0,
d19186
+              sizeof(h->code_length_code_lengths));
d19186
+          h->substate_huffman = BROTLI_STATE_HUFFMAN_COMPLEX;
d19186
           continue;
d19186
         }
d19186
       /* Fall through. */
d19186
 
d19186
       case BROTLI_STATE_HUFFMAN_SIMPLE_SIZE:
d19186
         /* Read symbols, codes & code lengths directly. */
d19186
-        if (!BrotliSafeReadBits(br, 2, &s->symbol)) {  /* num_symbols */
d19186
-          s->substate_huffman = BROTLI_STATE_HUFFMAN_SIMPLE_SIZE;
d19186
+        if (!BrotliSafeReadBits(br, 2, &h->symbol)) {  /* num_symbols */
d19186
+          h->substate_huffman = BROTLI_STATE_HUFFMAN_SIMPLE_SIZE;
d19186
           return BROTLI_DECODER_NEEDS_MORE_INPUT;
d19186
         }
d19186
-        s->sub_loop_counter = 0;
d19186
+        h->sub_loop_counter = 0;
d19186
       /* Fall through. */
d19186
 
d19186
       case BROTLI_STATE_HUFFMAN_SIMPLE_READ: {
d19186
         BrotliDecoderErrorCode result =
d19186
-            ReadSimpleHuffmanSymbols(alphabet_size, max_symbol, s);
d19186
+            ReadSimpleHuffmanSymbols(alphabet_size_max, alphabet_size_limit, s);
d19186
         if (result != BROTLI_DECODER_SUCCESS) {
d19186
           return result;
d19186
         }
d19186
@@ -779,21 +795,21 @@ static BrotliDecoderErrorCode ReadHuffmanCode(uint32_t alphabet_size,
d19186
 
d19186
       case BROTLI_STATE_HUFFMAN_SIMPLE_BUILD: {
d19186
         uint32_t table_size;
d19186
-        if (s->symbol == 3) {
d19186
+        if (h->symbol == 3) {
d19186
           uint32_t bits;
d19186
           if (!BrotliSafeReadBits(br, 1, &bits)) {
d19186
-            s->substate_huffman = BROTLI_STATE_HUFFMAN_SIMPLE_BUILD;
d19186
+            h->substate_huffman = BROTLI_STATE_HUFFMAN_SIMPLE_BUILD;
d19186
             return BROTLI_DECODER_NEEDS_MORE_INPUT;
d19186
           }
d19186
-          s->symbol += bits;
d19186
+          h->symbol += bits;
d19186
         }
d19186
-        BROTLI_LOG_UINT(s->symbol);
d19186
+        BROTLI_LOG_UINT(h->symbol);
d19186
         table_size = BrotliBuildSimpleHuffmanTable(
d19186
-            table, HUFFMAN_TABLE_BITS, s->symbols_lists_array, s->symbol);
d19186
+            table, HUFFMAN_TABLE_BITS, h->symbols_lists_array, h->symbol);
d19186
         if (opt_table_size) {
d19186
           *opt_table_size = table_size;
d19186
         }
d19186
-        s->substate_huffman = BROTLI_STATE_HUFFMAN_NONE;
d19186
+        h->substate_huffman = BROTLI_STATE_HUFFMAN_NONE;
d19186
         return BROTLI_DECODER_SUCCESS;
d19186
       }
d19186
 
d19186
@@ -804,44 +820,45 @@ static BrotliDecoderErrorCode ReadHuffmanCode(uint32_t alphabet_size,
d19186
         if (result != BROTLI_DECODER_SUCCESS) {
d19186
           return result;
d19186
         }
d19186
-        BrotliBuildCodeLengthsHuffmanTable(s->table,
d19186
-                                           s->code_length_code_lengths,
d19186
-                                           s->code_length_histo);
d19186
-        memset(&s->code_length_histo[0], 0, sizeof(s->code_length_histo));
d19186
+        BrotliBuildCodeLengthsHuffmanTable(h->table,
d19186
+                                           h->code_length_code_lengths,
d19186
+                                           h->code_length_histo);
d19186
+        memset(&h->code_length_histo[0], 0, sizeof(h->code_length_histo));
d19186
         for (i = 0; i <= BROTLI_HUFFMAN_MAX_CODE_LENGTH; ++i) {
d19186
-          s->next_symbol[i] = (int)i - (BROTLI_HUFFMAN_MAX_CODE_LENGTH + 1);
d19186
-          s->symbol_lists[s->next_symbol[i]] = 0xFFFF;
d19186
+          h->next_symbol[i] = (int)i - (BROTLI_HUFFMAN_MAX_CODE_LENGTH + 1);
d19186
+          h->symbol_lists[h->next_symbol[i]] = 0xFFFF;
d19186
         }
d19186
 
d19186
-        s->symbol = 0;
d19186
-        s->prev_code_len = BROTLI_INITIAL_REPEATED_CODE_LENGTH;
d19186
-        s->repeat = 0;
d19186
-        s->repeat_code_len = 0;
d19186
-        s->space = 32768;
d19186
-        s->substate_huffman = BROTLI_STATE_HUFFMAN_LENGTH_SYMBOLS;
d19186
+        h->symbol = 0;
d19186
+        h->prev_code_len = BROTLI_INITIAL_REPEATED_CODE_LENGTH;
d19186
+        h->repeat = 0;
d19186
+        h->repeat_code_len = 0;
d19186
+        h->space = 32768;
d19186
+        h->substate_huffman = BROTLI_STATE_HUFFMAN_LENGTH_SYMBOLS;
d19186
       }
d19186
       /* Fall through. */
d19186
 
d19186
       case BROTLI_STATE_HUFFMAN_LENGTH_SYMBOLS: {
d19186
         uint32_t table_size;
d19186
-        BrotliDecoderErrorCode result = ReadSymbolCodeLengths(max_symbol, s);
d19186
+        BrotliDecoderErrorCode result = ReadSymbolCodeLengths(
d19186
+            alphabet_size_limit, s);
d19186
         if (result == BROTLI_DECODER_NEEDS_MORE_INPUT) {
d19186
-          result = SafeReadSymbolCodeLengths(max_symbol, s);
d19186
+          result = SafeReadSymbolCodeLengths(alphabet_size_limit, s);
d19186
         }
d19186
         if (result != BROTLI_DECODER_SUCCESS) {
d19186
           return result;
d19186
         }
d19186
 
d19186
-        if (s->space != 0) {
d19186
-          BROTLI_LOG(("[ReadHuffmanCode] space = %d\n", (int)s->space));
d19186
+        if (h->space != 0) {
d19186
+          BROTLI_LOG(("[ReadHuffmanCode] space = %d\n", (int)h->space));
d19186
           return BROTLI_FAILURE(BROTLI_DECODER_ERROR_FORMAT_HUFFMAN_SPACE);
d19186
         }
d19186
         table_size = BrotliBuildHuffmanTable(
d19186
-            table, HUFFMAN_TABLE_BITS, s->symbol_lists, s->code_length_histo);
d19186
+            table, HUFFMAN_TABLE_BITS, h->symbol_lists, h->code_length_histo);
d19186
         if (opt_table_size) {
d19186
           *opt_table_size = table_size;
d19186
         }
d19186
-        s->substate_huffman = BROTLI_STATE_HUFFMAN_NONE;
d19186
+        h->substate_huffman = BROTLI_STATE_HUFFMAN_NONE;
d19186
         return BROTLI_DECODER_SUCCESS;
d19186
       }
d19186
 
d19186
@@ -858,8 +875,8 @@ static BROTLI_INLINE uint32_t ReadBlockLength(const HuffmanCode* table,
d19186
   uint32_t code;
d19186
   uint32_t nbits;
d19186
   code = ReadSymbol(table, br);
d19186
-  nbits = kBlockLengthPrefixCode[code].nbits;  /* nbits == 2..24 */
d19186
-  return kBlockLengthPrefixCode[code].offset + BrotliReadBits(br, nbits);
d19186
+  nbits = _kBrotliPrefixCodeRanges[code].nbits;  /* nbits == 2..24 */
d19186
+  return _kBrotliPrefixCodeRanges[code].offset + BrotliReadBits24(br, nbits);
d19186
 }
d19186
 
d19186
 /* WARNING: if state is not BROTLI_STATE_READ_BLOCK_LENGTH_NONE, then
d19186
@@ -877,13 +894,14 @@ static BROTLI_INLINE BROTLI_BOOL SafeReadBlockLength(
d19186
   }
d19186
   {
d19186
     uint32_t bits;
d19186
-    uint32_t nbits = kBlockLengthPrefixCode[index].nbits;  /* nbits == 2..24 */
d19186
+    uint32_t nbits = _kBrotliPrefixCodeRanges[index].nbits;
d19186
+    uint32_t offset = _kBrotliPrefixCodeRanges[index].offset;
d19186
     if (!BrotliSafeReadBits(br, nbits, &bits)) {
d19186
       s->block_length_index = index;
d19186
       s->substate_read_block_length = BROTLI_STATE_READ_BLOCK_LENGTH_SUFFIX;
d19186
       return BROTLI_FALSE;
d19186
     }
d19186
-    *result = kBlockLengthPrefixCode[index].offset + bits;
d19186
+    *result = offset + bits;
d19186
     s->substate_read_block_length = BROTLI_STATE_READ_BLOCK_LENGTH_NONE;
d19186
     return BROTLI_TRUE;
d19186
   }
d19186
@@ -943,22 +961,22 @@ static BROTLI_NOINLINE void InverseMoveToFrontTransform(
d19186
 /* Decodes a series of Huffman table using ReadHuffmanCode function. */
d19186
 static BrotliDecoderErrorCode HuffmanTreeGroupDecode(
d19186
     HuffmanTreeGroup* group, BrotliDecoderState* s) {
d19186
-  if (s->substate_tree_group != BROTLI_STATE_TREE_GROUP_LOOP) {
d19186
-    s->next = group->codes;
d19186
-    s->htree_index = 0;
d19186
-    s->substate_tree_group = BROTLI_STATE_TREE_GROUP_LOOP;
d19186
+  BrotliMetablockHeaderArena* h = &s->arena.header;
d19186
+  if (h->substate_tree_group != BROTLI_STATE_TREE_GROUP_LOOP) {
d19186
+    h->next = group->codes;
d19186
+    h->htree_index = 0;
d19186
+    h->substate_tree_group = BROTLI_STATE_TREE_GROUP_LOOP;
d19186
   }
d19186
-  while (s->htree_index < group->num_htrees) {
d19186
+  while (h->htree_index < group->num_htrees) {
d19186
     uint32_t table_size;
d19186
-    BrotliDecoderErrorCode result =
d19186
-        ReadHuffmanCode(group->alphabet_size, group->max_symbol,
d19186
-                        s->next, &table_size, s);
d19186
+    BrotliDecoderErrorCode result = ReadHuffmanCode(group->alphabet_size_max,
d19186
+        group->alphabet_size_limit, h->next, &table_size, s);
d19186
     if (result != BROTLI_DECODER_SUCCESS) return result;
d19186
-    group->htrees[s->htree_index] = s->next;
d19186
-    s->next += table_size;
d19186
-    ++s->htree_index;
d19186
+    group->htrees[h->htree_index] = h->next;
d19186
+    h->next += table_size;
d19186
+    ++h->htree_index;
d19186
   }
d19186
-  s->substate_tree_group = BROTLI_STATE_TREE_GROUP_NONE;
d19186
+  h->substate_tree_group = BROTLI_STATE_TREE_GROUP_NONE;
d19186
   return BROTLI_DECODER_SUCCESS;
d19186
 }
d19186
 
d19186
@@ -976,15 +994,16 @@ static BrotliDecoderErrorCode DecodeContextMap(uint32_t context_map_size,
d19186
                                                BrotliDecoderState* s) {
d19186
   BrotliBitReader* br = &s->br;
d19186
   BrotliDecoderErrorCode result = BROTLI_DECODER_SUCCESS;
d19186
+  BrotliMetablockHeaderArena* h = &s->arena.header;
d19186
 
d19186
-  switch ((int)s->substate_context_map) {
d19186
+  switch ((int)h->substate_context_map) {
d19186
     case BROTLI_STATE_CONTEXT_MAP_NONE:
d19186
       result = DecodeVarLenUint8(s, br, num_htrees);
d19186
       if (result != BROTLI_DECODER_SUCCESS) {
d19186
         return result;
d19186
       }
d19186
       (*num_htrees)++;
d19186
-      s->context_index = 0;
d19186
+      h->context_index = 0;
d19186
       BROTLI_LOG_UINT(context_map_size);
d19186
       BROTLI_LOG_UINT(*num_htrees);
d19186
       *context_map_arg =
d19186
@@ -996,7 +1015,7 @@ static BrotliDecoderErrorCode DecodeContextMap(uint32_t context_map_size,
d19186
         memset(*context_map_arg, 0, (size_t)context_map_size);
d19186
         return BROTLI_DECODER_SUCCESS;
d19186
       }
d19186
-      s->substate_context_map = BROTLI_STATE_CONTEXT_MAP_READ_PREFIX;
d19186
+      h->substate_context_map = BROTLI_STATE_CONTEXT_MAP_READ_PREFIX;
d19186
     /* Fall through. */
d19186
 
d19186
     case BROTLI_STATE_CONTEXT_MAP_READ_PREFIX: {
d19186
@@ -1007,38 +1026,38 @@ static BrotliDecoderErrorCode DecodeContextMap(uint32_t context_map_size,
d19186
         return BROTLI_DECODER_NEEDS_MORE_INPUT;
d19186
       }
d19186
       if ((bits & 1) != 0) { /* Use RLE for zeros. */
d19186
-        s->max_run_length_prefix = (bits >> 1) + 1;
d19186
+        h->max_run_length_prefix = (bits >> 1) + 1;
d19186
         BrotliDropBits(br, 5);
d19186
       } else {
d19186
-        s->max_run_length_prefix = 0;
d19186
+        h->max_run_length_prefix = 0;
d19186
         BrotliDropBits(br, 1);
d19186
       }
d19186
-      BROTLI_LOG_UINT(s->max_run_length_prefix);
d19186
-      s->substate_context_map = BROTLI_STATE_CONTEXT_MAP_HUFFMAN;
d19186
+      BROTLI_LOG_UINT(h->max_run_length_prefix);
d19186
+      h->substate_context_map = BROTLI_STATE_CONTEXT_MAP_HUFFMAN;
d19186
     }
d19186
     /* Fall through. */
d19186
 
d19186
     case BROTLI_STATE_CONTEXT_MAP_HUFFMAN: {
d19186
-      uint32_t alphabet_size = *num_htrees + s->max_run_length_prefix;
d19186
+      uint32_t alphabet_size = *num_htrees + h->max_run_length_prefix;
d19186
       result = ReadHuffmanCode(alphabet_size, alphabet_size,
d19186
-                               s->context_map_table, NULL, s);
d19186
+                               h->context_map_table, NULL, s);
d19186
       if (result != BROTLI_DECODER_SUCCESS) return result;
d19186
-      s->code = 0xFFFF;
d19186
-      s->substate_context_map = BROTLI_STATE_CONTEXT_MAP_DECODE;
d19186
+      h->code = 0xFFFF;
d19186
+      h->substate_context_map = BROTLI_STATE_CONTEXT_MAP_DECODE;
d19186
     }
d19186
     /* Fall through. */
d19186
 
d19186
     case BROTLI_STATE_CONTEXT_MAP_DECODE: {
d19186
-      uint32_t context_index = s->context_index;
d19186
-      uint32_t max_run_length_prefix = s->max_run_length_prefix;
d19186
+      uint32_t context_index = h->context_index;
d19186
+      uint32_t max_run_length_prefix = h->max_run_length_prefix;
d19186
       uint8_t* context_map = *context_map_arg;
d19186
-      uint32_t code = s->code;
d19186
+      uint32_t code = h->code;
d19186
       BROTLI_BOOL skip_preamble = (code != 0xFFFF);
d19186
       while (context_index < context_map_size || skip_preamble) {
d19186
         if (!skip_preamble) {
d19186
-          if (!SafeReadSymbol(s->context_map_table, br, &code)) {
d19186
-            s->code = 0xFFFF;
d19186
-            s->context_index = context_index;
d19186
+          if (!SafeReadSymbol(h->context_map_table, br, &code)) {
d19186
+            h->code = 0xFFFF;
d19186
+            h->context_index = context_index;
d19186
             return BROTLI_DECODER_NEEDS_MORE_INPUT;
d19186
           }
d19186
           BROTLI_LOG_UINT(code);
d19186
@@ -1059,8 +1078,8 @@ static BrotliDecoderErrorCode DecodeContextMap(uint32_t context_map_size,
d19186
         {
d19186
           uint32_t reps;
d19186
           if (!BrotliSafeReadBits(br, code, &reps)) {
d19186
-            s->code = code;
d19186
-            s->context_index = context_index;
d19186
+            h->code = code;
d19186
+            h->context_index = context_index;
d19186
             return BROTLI_DECODER_NEEDS_MORE_INPUT;
d19186
           }
d19186
           reps += 1U << code;
d19186
@@ -1080,13 +1099,13 @@ static BrotliDecoderErrorCode DecodeContextMap(uint32_t context_map_size,
d19186
     case BROTLI_STATE_CONTEXT_MAP_TRANSFORM: {
d19186
       uint32_t bits;
d19186
       if (!BrotliSafeReadBits(br, 1, &bits)) {
d19186
-        s->substate_context_map = BROTLI_STATE_CONTEXT_MAP_TRANSFORM;
d19186
+        h->substate_context_map = BROTLI_STATE_CONTEXT_MAP_TRANSFORM;
d19186
         return BROTLI_DECODER_NEEDS_MORE_INPUT;
d19186
       }
d19186
       if (bits != 0) {
d19186
         InverseMoveToFrontTransform(*context_map_arg, context_map_size, s);
d19186
       }
d19186
-      s->substate_context_map = BROTLI_STATE_CONTEXT_MAP_NONE;
d19186
+      h->substate_context_map = BROTLI_STATE_CONTEXT_MAP_NONE;
d19186
       return BROTLI_DECODER_SUCCESS;
d19186
     }
d19186
 
d19186
@@ -1448,32 +1467,28 @@ static BrotliDecoderErrorCode ReadContextModes(BrotliDecoderState* s) {
d19186
 }
d19186
 
d19186
 static BROTLI_INLINE void TakeDistanceFromRingBuffer(BrotliDecoderState* s) {
d19186
-  if (s->distance_code == 0) {
d19186
-    --s->dist_rb_idx;
d19186
-    s->distance_code = s->dist_rb[s->dist_rb_idx & 3];
d19186
+  int offset = s->distance_code - 3;
d19186
+  if (s->distance_code <= 3) {
d19186
     /* Compensate double distance-ring-buffer roll for dictionary items. */
d19186
-    s->distance_context = 1;
d19186
+    s->distance_context = 1 >> s->distance_code;
d19186
+    s->distance_code = s->dist_rb[(s->dist_rb_idx - offset) & 3];
d19186
+    s->dist_rb_idx -= s->distance_context;
d19186
   } else {
d19186
-    int distance_code = s->distance_code << 1;
d19186
-    /* kDistanceShortCodeIndexOffset has 2-bit values from LSB:
d19186
-        3, 2, 1, 0, 3, 3, 3, 3, 3, 3, 2, 2, 2, 2, 2, 2 */
d19186
-    const uint32_t kDistanceShortCodeIndexOffset = 0xAAAFFF1B;
d19186
-    /* kDistanceShortCodeValueOffset has 2-bit values from LSB:
d19186
-       -0, 0,-0, 0,-1, 1,-2, 2,-3, 3,-1, 1,-2, 2,-3, 3 */
d19186
-    const uint32_t kDistanceShortCodeValueOffset = 0xFA5FA500;
d19186
-    int v = (s->dist_rb_idx +
d19186
-        (int)(kDistanceShortCodeIndexOffset >> distance_code)) & 0x3;
d19186
-    s->distance_code = s->dist_rb[v];
d19186
-    v = (int)(kDistanceShortCodeValueOffset >> distance_code) & 0x3;
d19186
-    if ((distance_code & 0x3) != 0) {
d19186
-      s->distance_code += v;
d19186
+    int index_delta = 3;
d19186
+    int delta;
d19186
+    int base = s->distance_code - 10;
d19186
+    if (s->distance_code < 10) {
d19186
+      base = s->distance_code - 4;
d19186
     } else {
d19186
-      s->distance_code -= v;
d19186
-      if (s->distance_code <= 0) {
d19186
-        /* A huge distance will cause a BROTLI_FAILURE() soon.
d19186
-           This is a little faster than failing here. */
d19186
-        s->distance_code = 0x7FFFFFFF;
d19186
-      }
d19186
+      index_delta = 2;
d19186
+    }
d19186
+    /* Unpack one of six 4-bit values. */
d19186
+    delta = ((0x605142 >> (4 * base)) & 0xF) - 3;
d19186
+    s->distance_code = s->dist_rb[(s->dist_rb_idx + index_delta) & 0x3] + delta;
d19186
+    if (s->distance_code <= 0) {
d19186
+      /* A huge distance will cause a BROTLI_FAILURE() soon.
d19186
+         This is a little faster than failing here. */
d19186
+      s->distance_code = 0x7FFFFFFF;
d19186
     }
d19186
   }
d19186
 }
d19186
@@ -1488,62 +1503,153 @@ static BROTLI_INLINE BROTLI_BOOL SafeReadBits(
d19186
   }
d19186
 }
d19186
 
d19186
+static BROTLI_INLINE BROTLI_BOOL SafeReadBits32(
d19186
+    BrotliBitReader* const br, uint32_t n_bits, uint32_t* val) {
d19186
+  if (n_bits != 0) {
d19186
+    return BrotliSafeReadBits32(br, n_bits, val);
d19186
+  } else {
d19186
+    *val = 0;
d19186
+    return BROTLI_TRUE;
d19186
+  }
d19186
+}
d19186
+
d19186
+/*
d19186
+   RFC 7932 Section 4 with "..." shortenings and "[]" emendations.
d19186
+
d19186
+   Each distance ... is represented with a pair <distance code, extra bits>...
d19186
+   The distance code is encoded using a prefix code... The number of extra bits
d19186
+   can be 0..24... Two additional parameters: NPOSTFIX (0..3), and ...
d19186
+   NDIRECT (0..120) ... are encoded in the meta-block header...
d19186
+
d19186
+   The first 16 distance symbols ... reference past distances... ring buffer ...
d19186
+   Next NDIRECT distance symbols ... represent distances from 1 to NDIRECT...
d19186
+   [For] distance symbols 16 + NDIRECT and greater ... the number of extra bits
d19186
+   ... is given by the following formula:
d19186
+
d19186
+   [ xcode = dcode - NDIRECT - 16 ]
d19186
+   ndistbits = 1 + [ xcode ] >> (NPOSTFIX + 1)
d19186
+
d19186
+   ...
d19186
+*/
d19186
+
d19186
+/*
d19186
+   RFC 7932 Section 9.2 with "..." shortenings and "[]" emendations.
d19186
+
d19186
+   ... to get the actual value of the parameter NDIRECT, left-shift this
d19186
+   four-bit number by NPOSTFIX bits ...
d19186
+*/
d19186
+
d19186
+/* Remaining formulas from RFC 7932 Section 4 could be rewritten as following:
d19186
+
d19186
+     alphabet_size = 16 + NDIRECT + (max_distbits << (NPOSTFIX + 1))
d19186
+
d19186
+     half = ((xcode >> NPOSTFIX) & 1) << ndistbits
d19186
+     postfix = xcode & ((1 << NPOSTFIX) - 1)
d19186
+     range_start = 2 * (1 << ndistbits - 1 - 1)
d19186
+
d19186
+     distance = (range_start + half + extra) << NPOSTFIX + postfix + NDIRECT + 1
d19186
+
d19186
+   NB: ndistbits >= 1 -> range_start >= 0
d19186
+   NB: range_start has factor 2, as the range is covered by 2 "halves"
d19186
+   NB: extra -1 offset in range_start formula covers the absence of
d19186
+       ndistbits = 0 case
d19186
+   NB: when NPOSTFIX = 0, NDIRECT is not greater than 15
d19186
+
d19186
+   In other words, xcode has the following binary structure - XXXHPPP:
d19186
+    - XXX represent the number of extra distance bits
d19186
+    - H selects upper / lower range of distances
d19186
+    - PPP represent "postfix"
d19186
+
d19186
+  "Regular" distance encoding has NPOSTFIX = 0; omitting the postfix part
d19186
+  simplifies distance calculation.
d19186
+
d19186
+  Using NPOSTFIX > 0 allows cheaper encoding of regular structures, e.g. where
d19186
+  most of distances have the same reminder of division by 2/4/8. For example,
d19186
+  the table of int32_t values that come from different sources; if it is likely
d19186
+  that 3 highest bytes of values from the same source are the same, then
d19186
+  copy distance often looks like 4x + y.
d19186
+
d19186
+  Distance calculation could be rewritten to:
d19186
+
d19186
+    ndistbits = NDISTBITS(NDIRECT, NPOSTFIX)[dcode]
d19186
+    distance = OFFSET(NDIRECT, NPOSTFIX)[dcode] + extra << NPOSTFIX
d19186
+
d19186
+  NDISTBITS and OFFSET could be pre-calculated, as NDIRECT and NPOSTFIX could
d19186
+  change only once per meta-block.
d19186
+*/
d19186
+
d19186
+/* Calculates distance lookup table.
d19186
+   NB: it is possible to have all 64 tables precalculated. */
d19186
+static void CalculateDistanceLut(BrotliDecoderState* s) {
d19186
+  BrotliMetablockBodyArena* b = &s->arena.body;
d19186
+  uint32_t npostfix = s->distance_postfix_bits;
d19186
+  uint32_t ndirect = s->num_direct_distance_codes;
d19186
+  uint32_t alphabet_size_limit = s->distance_hgroup.alphabet_size_limit;
d19186
+  uint32_t postfix = 1u << npostfix;
d19186
+  uint32_t j;
d19186
+  uint32_t bits = 1;
d19186
+  uint32_t half = 0;
d19186
+
d19186
+  /* Skip short codes. */
d19186
+  uint32_t i = BROTLI_NUM_DISTANCE_SHORT_CODES;
d19186
+
d19186
+  /* Fill direct codes. */
d19186
+  for (j = 0; j < ndirect; ++j) {
d19186
+    b->dist_extra_bits[i] = 0;
d19186
+    b->dist_offset[i] = j + 1;
d19186
+    ++i;
d19186
+  }
d19186
+
d19186
+  /* Fill regular distance codes. */
d19186
+  while (i < alphabet_size_limit) {
d19186
+    uint32_t base = ndirect + ((((2 + half) << bits) - 4) << npostfix) + 1;
d19186
+    /* Always fill the complete group. */
d19186
+    for (j = 0; j < postfix; ++j) {
d19186
+      b->dist_extra_bits[i] = (uint8_t)bits;
d19186
+      b->dist_offset[i] = base + j;
d19186
+      ++i;
d19186
+    }
d19186
+    bits = bits + half;
d19186
+    half = half ^ 1;
d19186
+  }
d19186
+}
d19186
+
d19186
 /* Precondition: s->distance_code < 0. */
d19186
 static BROTLI_INLINE BROTLI_BOOL ReadDistanceInternal(
d19186
     int safe, BrotliDecoderState* s, BrotliBitReader* br) {
d19186
-  int distval;
d19186
+  BrotliMetablockBodyArena* b = &s->arena.body;
d19186
+  uint32_t code;
d19186
+  uint32_t bits;
d19186
   BrotliBitReaderState memento;
d19186
   HuffmanCode* distance_tree = s->distance_hgroup.htrees[s->dist_htree_index];
d19186
   if (!safe) {
d19186
-    s->distance_code = (int)ReadSymbol(distance_tree, br);
d19186
+    code = ReadSymbol(distance_tree, br);
d19186
   } else {
d19186
-    uint32_t code;
d19186
     BrotliBitReaderSaveState(br, &memento);
d19186
     if (!SafeReadSymbol(distance_tree, br, &code)) {
d19186
       return BROTLI_FALSE;
d19186
     }
d19186
-    s->distance_code = (int)code;
d19186
   }
d19186
+  --s->block_length[2];
d19186
   /* Convert the distance code to the actual distance by possibly
d19186
-     looking up past distances from the s->ringbuffer. */
d19186
+     looking up past distances from the s->dist_rb. */
d19186
   s->distance_context = 0;
d19186
-  if ((s->distance_code & ~0xF) == 0) {
d19186
+  if ((code & ~0xFu) == 0) {
d19186
+    s->distance_code = (int)code;
d19186
     TakeDistanceFromRingBuffer(s);
d19186
-    --s->block_length[2];
d19186
     return BROTLI_TRUE;
d19186
   }
d19186
-  distval = s->distance_code - (int)s->num_direct_distance_codes;
d19186
-  if (distval >= 0) {
d19186
-    uint32_t nbits;
d19186
-    int postfix;
d19186
-    int offset;
d19186
-    if (!safe && (s->distance_postfix_bits == 0)) {
d19186
-      nbits = ((uint32_t)distval >> 1) + 1;
d19186
-      offset = ((2 + (distval & 1)) << nbits) - 4;
d19186
-      s->distance_code = (int)s->num_direct_distance_codes + offset +
d19186
-                         (int)BrotliReadBits(br, nbits);
d19186
-    } else {
d19186
-      /* This branch also works well when s->distance_postfix_bits == 0. */
d19186
-      uint32_t bits;
d19186
-      postfix = distval & s->distance_postfix_mask;
d19186
-      distval >>= s->distance_postfix_bits;
d19186
-      nbits = ((uint32_t)distval >> 1) + 1;
d19186
-      if (safe) {
d19186
-        if (!SafeReadBits(br, nbits, &bits)) {
d19186
-          s->distance_code = -1;  /* Restore precondition. */
d19186
-          BrotliBitReaderRestoreState(br, &memento);
d19186
-          return BROTLI_FALSE;
d19186
-        }
d19186
-      } else {
d19186
-        bits = BrotliReadBits(br, nbits);
d19186
-      }
d19186
-      offset = ((2 + (distval & 1)) << nbits) - 4;
d19186
-      s->distance_code = (int)s->num_direct_distance_codes +
d19186
-          ((offset + (int)bits) << s->distance_postfix_bits) + postfix;
d19186
+  if (!safe) {
d19186
+    bits = BrotliReadBits32(br, b->dist_extra_bits[code]);
d19186
+  } else {
d19186
+    if (!SafeReadBits32(br, b->dist_extra_bits[code], &bits)) {
d19186
+      ++s->block_length[2];
d19186
+      BrotliBitReaderRestoreState(br, &memento);
d19186
+      return BROTLI_FALSE;
d19186
     }
d19186
   }
d19186
-  s->distance_code = s->distance_code - BROTLI_NUM_DISTANCE_SHORT_CODES + 1;
d19186
-  --s->block_length[2];
d19186
+  s->distance_code =
d19186
+      (int)(b->dist_offset[code] + (bits << s->distance_postfix_bits));
d19186
   return BROTLI_TRUE;
d19186
 }
d19186
 
d19186
@@ -1579,9 +1685,9 @@ static BROTLI_INLINE BROTLI_BOOL ReadCommandInternal(
d19186
   *insert_length = v.insert_len_offset;
d19186
   if (!safe) {
d19186
     if (BROTLI_PREDICT_FALSE(v.insert_len_extra_bits != 0)) {
d19186
-      insert_len_extra = BrotliReadBits(br, v.insert_len_extra_bits);
d19186
+      insert_len_extra = BrotliReadBits24(br, v.insert_len_extra_bits);
d19186
     }
d19186
-    copy_length = BrotliReadBits(br, v.copy_len_extra_bits);
d19186
+    copy_length = BrotliReadBits24(br, v.copy_len_extra_bits);
d19186
   } else {
d19186
     if (!SafeReadBits(br, v.insert_len_extra_bits, &insert_len_extra) ||
d19186
         !SafeReadBits(br, v.copy_len_extra_bits, &copy_length)) {
d19186
@@ -1926,21 +2032,6 @@ static BROTLI_NOINLINE BrotliDecoderErrorCode SafeProcessCommands(
d19186
   return ProcessCommandsInternal(1, s);
d19186
 }
d19186
 
d19186
-/* Returns the maximum number of distance symbols which can only represent
d19186
-   distances not exceeding BROTLI_MAX_ALLOWED_DISTANCE. */
d19186
-static uint32_t BrotliMaxDistanceSymbol(uint32_t ndirect, uint32_t npostfix) {
d19186
-  static const uint32_t bound[BROTLI_MAX_NPOSTFIX + 1] = {0, 4, 12, 28};
d19186
-  static const uint32_t diff[BROTLI_MAX_NPOSTFIX + 1] = {73, 126, 228, 424};
d19186
-  uint32_t postfix = 1U << npostfix;
d19186
-  if (ndirect < bound[npostfix]) {
d19186
-    return ndirect + diff[npostfix] + postfix;
d19186
-  } else if (ndirect > bound[npostfix] + postfix) {
d19186
-    return ndirect + diff[npostfix];
d19186
-  } else {
d19186
-    return bound[npostfix] + diff[npostfix] + postfix;
d19186
-  }
d19186
-}
d19186
-
d19186
 BrotliDecoderResult BrotliDecoderDecompress(
d19186
     size_t encoded_size, const uint8_t* encoded_buffer, size_t* decoded_size,
d19186
     uint8_t* decoded_buffer) {
d19186
@@ -2158,33 +2249,23 @@ BrotliDecoderResult BrotliDecoderDecompressStream(
d19186
           s->state = BROTLI_STATE_UNCOMPRESSED;
d19186
           break;
d19186
         }
d19186
+        s->state = BROTLI_STATE_BEFORE_COMPRESSED_METABLOCK_HEADER;
d19186
+      /* Fall through. */
d19186
+
d19186
+      case BROTLI_STATE_BEFORE_COMPRESSED_METABLOCK_HEADER: {
d19186
+        BrotliMetablockHeaderArena* h = &s->arena.header;
d19186
         s->loop_counter = 0;
d19186
+        /* Initialize compressed metablock header arena. */
d19186
+        h->sub_loop_counter = 0;
d19186
+        /* Make small negative indexes addressable. */
d19186
+        h->symbol_lists =
d19186
+            &h->symbols_lists_array[BROTLI_HUFFMAN_MAX_CODE_LENGTH + 1];
d19186
+        h->substate_huffman = BROTLI_STATE_HUFFMAN_NONE;
d19186
+        h->substate_tree_group = BROTLI_STATE_TREE_GROUP_NONE;
d19186
+        h->substate_context_map = BROTLI_STATE_CONTEXT_MAP_NONE;
d19186
         s->state = BROTLI_STATE_HUFFMAN_CODE_0;
d19186
-        break;
d19186
-
d19186
-      case BROTLI_STATE_UNCOMPRESSED: {
d19186
-        result = CopyUncompressedBlockToOutput(
d19186
-            available_out, next_out, total_out, s);
d19186
-        if (result != BROTLI_DECODER_SUCCESS) {
d19186
-          break;
d19186
-        }
d19186
-        s->state = BROTLI_STATE_METABLOCK_DONE;
d19186
-        break;
d19186
       }
d19186
-
d19186
-      case BROTLI_STATE_METADATA:
d19186
-        for (; s->meta_block_remaining_len > 0; --s->meta_block_remaining_len) {
d19186
-          uint32_t bits;
d19186
-          /* Read one byte and ignore it. */
d19186
-          if (!BrotliSafeReadBits(br, 8, &bits)) {
d19186
-            result = BROTLI_DECODER_NEEDS_MORE_INPUT;
d19186
-            break;
d19186
-          }
d19186
-        }
d19186
-        if (result == BROTLI_DECODER_SUCCESS) {
d19186
-          s->state = BROTLI_STATE_METABLOCK_DONE;
d19186
-        }
d19186
-        break;
d19186
+      /* Fall through. */
d19186
 
d19186
       case BROTLI_STATE_HUFFMAN_CODE_0:
d19186
         if (s->loop_counter >= 3) {
d19186
@@ -2238,6 +2319,30 @@ BrotliDecoderResult BrotliDecoderDecompressStream(
d19186
         break;
d19186
       }
d19186
 
d19186
+      case BROTLI_STATE_UNCOMPRESSED: {
d19186
+        result = CopyUncompressedBlockToOutput(
d19186
+            available_out, next_out, total_out, s);
d19186
+        if (result != BROTLI_DECODER_SUCCESS) {
d19186
+          break;
d19186
+        }
d19186
+        s->state = BROTLI_STATE_METABLOCK_DONE;
d19186
+        break;
d19186
+      }
d19186
+
d19186
+      case BROTLI_STATE_METADATA:
d19186
+        for (; s->meta_block_remaining_len > 0; --s->meta_block_remaining_len) {
d19186
+          uint32_t bits;
d19186
+          /* Read one byte and ignore it. */
d19186
+          if (!BrotliSafeReadBits(br, 8, &bits)) {
d19186
+            result = BROTLI_DECODER_NEEDS_MORE_INPUT;
d19186
+            break;
d19186
+          }
d19186
+        }
d19186
+        if (result == BROTLI_DECODER_SUCCESS) {
d19186
+          s->state = BROTLI_STATE_METABLOCK_DONE;
d19186
+        }
d19186
+        break;
d19186
+
d19186
       case BROTLI_STATE_METABLOCK_HEADER_2: {
d19186
         uint32_t bits;
d19186
         if (!BrotliSafeReadBits(br, 6, &bits)) {
d19186
@@ -2246,11 +2351,9 @@ BrotliDecoderResult BrotliDecoderDecompressStream(
d19186
         }
d19186
         s->distance_postfix_bits = bits & BitMask(2);
d19186
         bits >>= 2;
d19186
-        s->num_direct_distance_codes = BROTLI_NUM_DISTANCE_SHORT_CODES +
d19186
-            (bits << s->distance_postfix_bits);
d19186
+        s->num_direct_distance_codes = bits << s->distance_postfix_bits;
d19186
         BROTLI_LOG_UINT(s->num_direct_distance_codes);
d19186
         BROTLI_LOG_UINT(s->distance_postfix_bits);
d19186
-        s->distance_postfix_mask = (int)BitMask(s->distance_postfix_bits);
d19186
         s->context_modes =
d19186
             (uint8_t*)BROTLI_DECODER_ALLOC(s, (size_t)s->num_block_types[0]);
d19186
         if (s->context_modes == 0) {
d19186
@@ -2282,17 +2385,19 @@ BrotliDecoderResult BrotliDecoderDecompressStream(
d19186
       /* Fall through. */
d19186
 
d19186
       case BROTLI_STATE_CONTEXT_MAP_2: {
d19186
-        uint32_t num_direct_codes =
d19186
-            s->num_direct_distance_codes - BROTLI_NUM_DISTANCE_SHORT_CODES;
d19186
-        uint32_t num_distance_codes = BROTLI_DISTANCE_ALPHABET_SIZE(
d19186
-            s->distance_postfix_bits, num_direct_codes,
d19186
-            (s->large_window ? BROTLI_LARGE_MAX_DISTANCE_BITS :
d19186
-                               BROTLI_MAX_DISTANCE_BITS));
d19186
-        uint32_t max_distance_symbol = (s->large_window ?
d19186
-            BrotliMaxDistanceSymbol(
d19186
-                num_direct_codes, s->distance_postfix_bits) :
d19186
-            num_distance_codes);
d19186
+        uint32_t npostfix = s->distance_postfix_bits;
d19186
+        uint32_t ndirect = s->num_direct_distance_codes;
d19186
+        uint32_t distance_alphabet_size_max = BROTLI_DISTANCE_ALPHABET_SIZE(
d19186
+            npostfix, ndirect, BROTLI_MAX_DISTANCE_BITS);
d19186
+        uint32_t distance_alphabet_size_limit = distance_alphabet_size_max;
d19186
         BROTLI_BOOL allocation_success = BROTLI_TRUE;
d19186
+        if (s->large_window) {
d19186
+          BrotliDistanceCodeLimit limit = BrotliCalculateDistanceCodeLimit(
d19186
+              BROTLI_MAX_ALLOWED_DISTANCE, npostfix, ndirect);
d19186
+          distance_alphabet_size_max = BROTLI_DISTANCE_ALPHABET_SIZE(
d19186
+              npostfix, ndirect, BROTLI_LARGE_MAX_DISTANCE_BITS);
d19186
+          distance_alphabet_size_limit = limit.max_alphabet_size;
d19186
+        }
d19186
         result = DecodeContextMap(
d19186
             s->num_block_types[2] << BROTLI_DISTANCE_CONTEXT_BITS,
d19186
             &s->num_dist_htrees, &s->dist_context_map, s);
d19186
@@ -2306,8 +2411,8 @@ BrotliDecoderResult BrotliDecoderDecompressStream(
d19186
             s, &s->insert_copy_hgroup, BROTLI_NUM_COMMAND_SYMBOLS,
d19186
             BROTLI_NUM_COMMAND_SYMBOLS, s->num_block_types[1]);
d19186
         allocation_success &= BrotliDecoderHuffmanTreeGroupInit(
d19186
-            s, &s->distance_hgroup, num_distance_codes,
d19186
-            max_distance_symbol, s->num_dist_htrees);
d19186
+            s, &s->distance_hgroup, distance_alphabet_size_max,
d19186
+            distance_alphabet_size_limit, s->num_dist_htrees);
d19186
         if (!allocation_success) {
d19186
           return SaveErrorCode(s,
d19186
               BROTLI_FAILURE(BROTLI_DECODER_ERROR_ALLOC_TREE_GROUPS));
d19186
@@ -2329,18 +2434,24 @@ BrotliDecoderResult BrotliDecoderDecompressStream(
d19186
         result = HuffmanTreeGroupDecode(hgroup, s);
d19186
         if (result != BROTLI_DECODER_SUCCESS) break;
d19186
         s->loop_counter++;
d19186
-        if (s->loop_counter >= 3) {
d19186
-          PrepareLiteralDecoding(s);
d19186
-          s->dist_context_map_slice = s->dist_context_map;
d19186
-          s->htree_command = s->insert_copy_hgroup.htrees[0];
d19186
-          if (!BrotliEnsureRingBuffer(s)) {
d19186
-            result = BROTLI_FAILURE(BROTLI_DECODER_ERROR_ALLOC_RING_BUFFER_2);
d19186
-            break;
d19186
-          }
d19186
-          s->state = BROTLI_STATE_COMMAND_BEGIN;
d19186
+        if (s->loop_counter < 3) {
d19186
+          break;
d19186
         }
d19186
-        break;
d19186
+        s->state = BROTLI_STATE_BEFORE_COMPRESSED_METABLOCK_BODY;
d19186
       }
d19186
+      /* Fall through. */
d19186
+
d19186
+      case BROTLI_STATE_BEFORE_COMPRESSED_METABLOCK_BODY:
d19186
+        PrepareLiteralDecoding(s);
d19186
+        s->dist_context_map_slice = s->dist_context_map;
d19186
+        s->htree_command = s->insert_copy_hgroup.htrees[0];
d19186
+        if (!BrotliEnsureRingBuffer(s)) {
d19186
+          result = BROTLI_FAILURE(BROTLI_DECODER_ERROR_ALLOC_RING_BUFFER_2);
d19186
+          break;
d19186
+        }
d19186
+        CalculateDistanceLut(s);
d19186
+        s->state = BROTLI_STATE_COMMAND_BEGIN;
d19186
+      /* Fall through. */
d19186
 
d19186
       case BROTLI_STATE_COMMAND_BEGIN:
d19186
       /* Fall through. */
d19186
diff --git a/c/dec/huffman.h b/c/dec/huffman.h
d19186
index 521ec6e..a8fbc45 100644
d19186
--- a/c/dec/huffman.h
d19186
+++ b/c/dec/huffman.h
d19186
@@ -18,12 +18,6 @@ extern "C" {
d19186
 
d19186
 #define BROTLI_HUFFMAN_MAX_CODE_LENGTH 15
d19186
 
d19186
-/* Maximum possible Huffman table size for an alphabet size of (index * 32),
d19186
-   max code length 15 and root table bits 8. */
d19186
-static const uint16_t kMaxHuffmanTableSize[] = {
d19186
-  256, 402, 436, 468, 500, 534, 566, 598, 630, 662, 694, 726, 758, 790, 822,
d19186
-  854, 886, 920, 952, 984, 1016, 1048, 1080, 1112, 1144, 1176, 1208, 1240, 1272,
d19186
-  1304, 1336, 1368, 1400, 1432, 1464, 1496, 1528};
d19186
 /* BROTLI_NUM_BLOCK_LEN_SYMBOLS == 26 */
d19186
 #define BROTLI_HUFFMAN_MAX_SIZE_26 396
d19186
 /* BROTLI_MAX_BLOCK_TYPE_SYMBOLS == 258 */
d19186
@@ -33,11 +27,66 @@ static const uint16_t kMaxHuffmanTableSize[] = {
d19186
 
d19186
 #define BROTLI_HUFFMAN_MAX_CODE_LENGTH_CODE_LENGTH 5
d19186
 
d19186
+#if ((defined(BROTLI_TARGET_ARMV7) || defined(BROTLI_TARGET_ARMV8_32)) && \
d19186
+  BROTLI_GNUC_HAS_ATTRIBUTE(aligned, 2, 7, 0))
d19186
+#define BROTLI_HUFFMAN_CODE_FAST_LOAD
d19186
+#endif
d19186
+
d19186
+#if !defined(BROTLI_HUFFMAN_CODE_FAST_LOAD)
d19186
+/* Do not create this struct directly - use the ConstructHuffmanCode
d19186
+ * constructor below! */
d19186
 typedef struct {
d19186
   uint8_t bits;    /* number of bits used for this symbol */
d19186
   uint16_t value;  /* symbol value or table offset */
d19186
 } HuffmanCode;
d19186
 
d19186
+static BROTLI_INLINE HuffmanCode ConstructHuffmanCode(const uint8_t bits,
d19186
+    const uint16_t value) {
d19186
+  HuffmanCode h;
d19186
+  h.bits = bits;
d19186
+  h.value = value;
d19186
+  return h;
d19186
+}
d19186
+
d19186
+/* Please use the following macros to optimize HuffmanCode accesses in hot
d19186
+ * paths.
d19186
+ *
d19186
+ * For example, assuming |table| contains a HuffmanCode pointer:
d19186
+ *
d19186
+ *   BROTLI_HC_MARK_TABLE_FOR_FAST_LOAD(table);
d19186
+ *   BROTLI_HC_ADJUST_TABLE_INDEX(table, index_into_table);
d19186
+ *   *bits = BROTLI_HC_GET_BITS(table);
d19186
+ *   *value = BROTLI_HC_GET_VALUE(table);
d19186
+ *   BROTLI_HC_ADJUST_TABLE_INDEX(table, offset);
d19186
+ *   *bits2 = BROTLI_HC_GET_BITS(table);
d19186
+ *   *value2 = BROTLI_HC_GET_VALUE(table);
d19186
+ *
d19186
+ */
d19186
+
d19186
+#define BROTLI_HC_MARK_TABLE_FOR_FAST_LOAD(H)
d19186
+#define BROTLI_HC_ADJUST_TABLE_INDEX(H, V) H += (V)
d19186
+
d19186
+/* These must be given a HuffmanCode pointer! */
d19186
+#define BROTLI_HC_FAST_LOAD_BITS(H) (H->bits)
d19186
+#define BROTLI_HC_FAST_LOAD_VALUE(H) (H->value)
d19186
+
d19186
+#else /* BROTLI_HUFFMAN_CODE_FAST_LOAD */
d19186
+
d19186
+typedef BROTLI_ALIGNED(4) uint32_t HuffmanCode;
d19186
+
d19186
+static BROTLI_INLINE HuffmanCode ConstructHuffmanCode(const uint8_t bits,
d19186
+    const uint16_t value) {
d19186
+  return (HuffmanCode) ((value & 0xFFFF) << 16) | (bits & 0xFF);
d19186
+}
d19186
+
d19186
+#define BROTLI_HC_MARK_TABLE_FOR_FAST_LOAD(H) uint32_t __fastload_##H = (*H)
d19186
+#define BROTLI_HC_ADJUST_TABLE_INDEX(H, V) H += (V); __fastload_##H = (*H)
d19186
+
d19186
+/* These must be given a HuffmanCode pointer! */
d19186
+#define BROTLI_HC_FAST_LOAD_BITS(H) ((__fastload_##H) & 0xFF)
d19186
+#define BROTLI_HC_FAST_LOAD_VALUE(H) ((__fastload_##H) >> 16)
d19186
+#endif /* BROTLI_HUFFMAN_CODE_FAST_LOAD */
d19186
+
d19186
 /* Builds Huffman lookup table assuming code lengths are in symbol order. */
d19186
 BROTLI_INTERNAL void BrotliBuildCodeLengthsHuffmanTable(HuffmanCode* root_table,
d19186
     const uint8_t* const code_lengths, uint16_t* count);
d19186
@@ -45,7 +94,7 @@ BROTLI_INTERNAL void BrotliBuildCodeLengthsHuffmanTable(HuffmanCode* root_table,
d19186
 /* Builds Huffman lookup table assuming code lengths are in symbol order.
d19186
    Returns size of resulting table. */
d19186
 BROTLI_INTERNAL uint32_t BrotliBuildHuffmanTable(HuffmanCode* root_table,
d19186
-    int root_bits, const uint16_t* const symbol_lists, uint16_t* count_arg);
d19186
+    int root_bits, const uint16_t* const symbol_lists, uint16_t* count);
d19186
 
d19186
 /* Builds a simple Huffman table. The |num_symbols| parameter is to be
d19186
    interpreted as follows: 0 means 1 symbol, 1 means 2 symbols,
d19186
@@ -55,13 +104,13 @@ BROTLI_INTERNAL uint32_t BrotliBuildSimpleHuffmanTable(HuffmanCode* table,
d19186
     int root_bits, uint16_t* symbols, uint32_t num_symbols);
d19186
 
d19186
 /* Contains a collection of Huffman trees with the same alphabet size. */
d19186
-/* max_symbol is needed due to simple codes since log2(alphabet_size) could be
d19186
-   greater than log2(max_symbol). */
d19186
+/* alphabet_size_limit is needed due to simple codes, since
d19186
+   log2(alphabet_size_max) could be greater than log2(alphabet_size_limit). */
d19186
 typedef struct {
d19186
   HuffmanCode** htrees;
d19186
   HuffmanCode* codes;
d19186
-  uint16_t alphabet_size;
d19186
-  uint16_t max_symbol;
d19186
+  uint16_t alphabet_size_max;
d19186
+  uint16_t alphabet_size_limit;
d19186
   uint16_t num_htrees;
d19186
 } HuffmanTreeGroup;
d19186
 
d19186
diff --git a/c/dec/prefix.h b/c/dec/prefix.h
d19186
index 3ea062d..481a2c7 100644
d19186
--- a/c/dec/prefix.h
d19186
+++ b/c/dec/prefix.h
d19186
@@ -13,24 +13,6 @@
d19186
 #include "../common/constants.h"
d19186
 #include <brotli/types.h>
d19186
 
d19186
-/* Represents the range of values belonging to a prefix code:
d19186
-   [offset, offset + 2^nbits) */
d19186
-struct PrefixCodeRange {
d19186
-  uint16_t offset;
d19186
-  uint8_t nbits;
d19186
-};
d19186
-
d19186
-static const struct PrefixCodeRange
d19186
-    kBlockLengthPrefixCode[BROTLI_NUM_BLOCK_LEN_SYMBOLS] = {
d19186
-  {   1,  2}, {    5,  2}, {  9,   2}, {  13,  2},
d19186
-  {  17,  3}, {   25,  3}, {  33,  3}, {  41,  3},
d19186
-  {  49,  4}, {   65,  4}, {  81,  4}, {  97,  4},
d19186
-  { 113,  5}, {  145,  5}, { 177,  5}, { 209,  5},
d19186
-  { 241,  6}, {  305,  6}, { 369,  7}, { 497,  8},
d19186
-  { 753,  9}, { 1265, 10}, {2289, 11}, {4337, 12},
d19186
-  {8433, 13}, {16625, 24}
d19186
-};
d19186
-
d19186
 typedef struct CmdLutElement {
d19186
   uint8_t insert_len_extra_bits;
d19186
   uint8_t copy_len_extra_bits;
d19186
diff --git a/c/dec/state.c b/c/dec/state.c
d19186
index e0b37c2..f847836 100644
d19186
--- a/c/dec/state.c
d19186
+++ b/c/dec/state.c
d19186
@@ -33,10 +33,7 @@ BROTLI_BOOL BrotliDecoderStateInit(BrotliDecoderState* s,
d19186
   s->state = BROTLI_STATE_UNINITED;
d19186
   s->large_window = 0;
d19186
   s->substate_metablock_header = BROTLI_STATE_METABLOCK_HEADER_NONE;
d19186
-  s->substate_tree_group = BROTLI_STATE_TREE_GROUP_NONE;
d19186
-  s->substate_context_map = BROTLI_STATE_CONTEXT_MAP_NONE;
d19186
   s->substate_uncompressed = BROTLI_STATE_UNCOMPRESSED_NONE;
d19186
-  s->substate_huffman = BROTLI_STATE_HUFFMAN_NONE;
d19186
   s->substate_decode_uint8 = BROTLI_STATE_DECODE_UINT8_NONE;
d19186
   s->substate_read_block_length = BROTLI_STATE_READ_BLOCK_LENGTH_NONE;
d19186
 
d19186
@@ -59,8 +56,6 @@ BROTLI_BOOL BrotliDecoderStateInit(BrotliDecoderState* s,
d19186
   s->context_map_slice = NULL;
d19186
   s->dist_context_map_slice = NULL;
d19186
 
d19186
-  s->sub_loop_counter = 0;
d19186
-
d19186
   s->literal_hgroup.codes = NULL;
d19186
   s->literal_hgroup.htrees = NULL;
d19186
   s->insert_copy_hgroup.codes = NULL;
d19186
@@ -84,9 +79,6 @@ BROTLI_BOOL BrotliDecoderStateInit(BrotliDecoderState* s,
d19186
   s->block_type_trees = NULL;
d19186
   s->block_len_trees = NULL;
d19186
 
d19186
-  /* Make small negative indexes addressable. */
d19186
-  s->symbol_lists = &s->symbols_lists_array[BROTLI_HUFFMAN_MAX_CODE_LENGTH + 1];
d19186
-
d19186
   s->mtf_upper_bound = 63;
d19186
 
d19186
   s->dictionary = BrotliGetDictionary();
d19186
@@ -142,17 +134,20 @@ void BrotliDecoderStateCleanup(BrotliDecoderState* s) {
d19186
 }
d19186
 
d19186
 BROTLI_BOOL BrotliDecoderHuffmanTreeGroupInit(BrotliDecoderState* s,
d19186
-    HuffmanTreeGroup* group, uint32_t alphabet_size, uint32_t max_symbol,
d19186
-    uint32_t ntrees) {
d19186
-  /* Pack two allocations into one */
d19186
-  const size_t max_table_size = kMaxHuffmanTableSize[(alphabet_size + 31) >> 5];
d19186
+    HuffmanTreeGroup* group, uint32_t alphabet_size_max,
d19186
+    uint32_t alphabet_size_limit, uint32_t ntrees) {
d19186
+  /* 376 = 256 (1-st level table) + 4 + 7 + 15 + 31 + 63 (2-nd level mix-tables)
d19186
+     This number is discovered "unlimited" "enough" calculator; it is actually
d19186
+     a wee bigger than required in several cases (especially for alphabets with
d19186
+     less than 16 symbols). */
d19186
+  const size_t max_table_size = alphabet_size_limit + 376;
d19186
   const size_t code_size = sizeof(HuffmanCode) * ntrees * max_table_size;
d19186
   const size_t htree_size = sizeof(HuffmanCode*) * ntrees;
d19186
   /* Pointer alignment is, hopefully, wider than sizeof(HuffmanCode). */
d19186
   HuffmanCode** p = (HuffmanCode**)BROTLI_DECODER_ALLOC(s,
d19186
       code_size + htree_size);
d19186
-  group->alphabet_size = (uint16_t)alphabet_size;
d19186
-  group->max_symbol = (uint16_t)max_symbol;
d19186
+  group->alphabet_size_max = (uint16_t)alphabet_size_max;
d19186
+  group->alphabet_size_limit = (uint16_t)alphabet_size_limit;
d19186
   group->num_htrees = (uint16_t)ntrees;
d19186
   group->htrees = p;
d19186
   group->codes = (HuffmanCode*)(&p[ntrees]);
d19186
diff --git a/c/dec/state.h b/c/dec/state.h
d19186
index d28b639..54dab69 100644
d19186
--- a/c/dec/state.h
d19186
+++ b/c/dec/state.h
d19186
@@ -21,6 +21,95 @@
d19186
 extern "C" {
d19186
 #endif
d19186
 
d19186
+/* Graphviz diagram that describes state transitions:
d19186
+
d19186
+digraph States {
d19186
+  graph [compound=true]
d19186
+  concentrate=true
d19186
+  node [shape="box"]
d19186
+
d19186
+  UNINITED -> {LARGE_WINDOW_BITS -> INITIALIZE}
d19186
+  subgraph cluster_metablock_workflow {
d19186
+    style="rounded"
d19186
+    label=< METABLOCK CYCLE >
d19186
+    METABLOCK_BEGIN -> METABLOCK_HEADER
d19186
+    METABLOCK_HEADER:sw -> METADATA
d19186
+    METABLOCK_HEADER:s -> UNCOMPRESSED
d19186
+    METABLOCK_HEADER:se -> METABLOCK_DONE:ne
d19186
+    METADATA:s -> METABLOCK_DONE:w
d19186
+    UNCOMPRESSED:s -> METABLOCK_DONE:n
d19186
+    METABLOCK_DONE:e -> METABLOCK_BEGIN:e [constraint="false"]
d19186
+  }
d19186
+  INITIALIZE -> METABLOCK_BEGIN
d19186
+  METABLOCK_DONE -> DONE
d19186
+
d19186
+  subgraph cluster_compressed_metablock {
d19186
+    style="rounded"
d19186
+    label=< COMPRESSED METABLOCK >
d19186
+
d19186
+    subgraph cluster_command {
d19186
+      style="rounded"
d19186
+      label=< HOT LOOP >
d19186
+
d19186
+      _METABLOCK_DONE_PORT_ [shape=point style=invis]
d19186
+
d19186
+      {
d19186
+        // Set different shape for nodes returning from "compressed metablock".
d19186
+        node [shape=invhouse]; CMD_INNER CMD_POST_DECODE_LITERALS;
d19186
+        CMD_POST_WRAP_COPY; CMD_INNER_WRITE; CMD_POST_WRITE_1;
d19186
+      }
d19186
+
d19186
+      CMD_BEGIN -> CMD_INNER -> CMD_POST_DECODE_LITERALS -> CMD_POST_WRAP_COPY
d19186
+
d19186
+      // IO ("write") nodes are not in the hot loop!
d19186
+      CMD_INNER_WRITE [style=dashed]
d19186
+      CMD_INNER -> CMD_INNER_WRITE
d19186
+      CMD_POST_WRITE_1 [style=dashed]
d19186
+      CMD_POST_DECODE_LITERALS -> CMD_POST_WRITE_1
d19186
+      CMD_POST_WRITE_2 [style=dashed]
d19186
+      CMD_POST_WRAP_COPY -> CMD_POST_WRITE_2
d19186
+
d19186
+      CMD_POST_WRITE_1 -> CMD_BEGIN:s [constraint="false"]
d19186
+      CMD_INNER_WRITE -> {CMD_INNER CMD_POST_DECODE_LITERALS}
d19186
+          [constraint="false"]
d19186
+      CMD_BEGIN:ne -> CMD_POST_DECODE_LITERALS [constraint="false"]
d19186
+      CMD_POST_WRAP_COPY -> CMD_BEGIN [constraint="false"]
d19186
+      CMD_POST_DECODE_LITERALS -> CMD_BEGIN:ne [constraint="false"]
d19186
+      CMD_POST_WRITE_2 -> CMD_POST_WRAP_COPY [constraint="false"]
d19186
+      {rank=same; CMD_BEGIN; CMD_INNER; CMD_POST_DECODE_LITERALS;
d19186
+          CMD_POST_WRAP_COPY}
d19186
+      {rank=same; CMD_INNER_WRITE; CMD_POST_WRITE_1; CMD_POST_WRITE_2}
d19186
+
d19186
+      {CMD_INNER CMD_POST_DECODE_LITERALS CMD_POST_WRAP_COPY} ->
d19186
+          _METABLOCK_DONE_PORT_ [style=invis]
d19186
+      {CMD_INNER_WRITE CMD_POST_WRITE_1} -> _METABLOCK_DONE_PORT_
d19186
+          [constraint="false" style=invis]
d19186
+    }
d19186
+
d19186
+    BEFORE_COMPRESSED_METABLOCK_HEADER:s -> HUFFMAN_CODE_0:n
d19186
+    HUFFMAN_CODE_0 -> HUFFMAN_CODE_1 -> HUFFMAN_CODE_2 -> HUFFMAN_CODE_3
d19186
+    HUFFMAN_CODE_0 -> METABLOCK_HEADER_2 -> CONTEXT_MODES -> CONTEXT_MAP_1
d19186
+    CONTEXT_MAP_1 -> CONTEXT_MAP_2 -> TREE_GROUP
d19186
+    TREE_GROUP -> BEFORE_COMPRESSED_METABLOCK_BODY:e
d19186
+    BEFORE_COMPRESSED_METABLOCK_BODY:s -> CMD_BEGIN:n
d19186
+
d19186
+    HUFFMAN_CODE_3:e -> HUFFMAN_CODE_0:ne [constraint="false"]
d19186
+    {rank=same; HUFFMAN_CODE_0; HUFFMAN_CODE_1; HUFFMAN_CODE_2; HUFFMAN_CODE_3}
d19186
+    {rank=same; METABLOCK_HEADER_2; CONTEXT_MODES; CONTEXT_MAP_1; CONTEXT_MAP_2;
d19186
+        TREE_GROUP}
d19186
+  }
d19186
+  METABLOCK_HEADER:e -> BEFORE_COMPRESSED_METABLOCK_HEADER:n
d19186
+
d19186
+  _METABLOCK_DONE_PORT_ -> METABLOCK_DONE:se
d19186
+      [constraint="false" ltail=cluster_command]
d19186
+
d19186
+  UNINITED [shape=Mdiamond];
d19186
+  DONE [shape=Msquare];
d19186
+}
d19186
+
d19186
+
d19186
+ */
d19186
+
d19186
 typedef enum {
d19186
   BROTLI_STATE_UNINITED,
d19186
   BROTLI_STATE_LARGE_WINDOW_BITS,
d19186
@@ -39,6 +128,7 @@ typedef enum {
d19186
   BROTLI_STATE_METABLOCK_DONE,
d19186
   BROTLI_STATE_COMMAND_POST_WRITE_1,
d19186
   BROTLI_STATE_COMMAND_POST_WRITE_2,
d19186
+  BROTLI_STATE_BEFORE_COMPRESSED_METABLOCK_HEADER,
d19186
   BROTLI_STATE_HUFFMAN_CODE_0,
d19186
   BROTLI_STATE_HUFFMAN_CODE_1,
d19186
   BROTLI_STATE_HUFFMAN_CODE_2,
d19186
@@ -46,6 +136,7 @@ typedef enum {
d19186
   BROTLI_STATE_CONTEXT_MAP_1,
d19186
   BROTLI_STATE_CONTEXT_MAP_2,
d19186
   BROTLI_STATE_TREE_GROUP,
d19186
+  BROTLI_STATE_BEFORE_COMPRESSED_METABLOCK_BODY,
d19186
   BROTLI_STATE_DONE
d19186
 } BrotliRunningState;
d19186
 
d19186
@@ -98,6 +189,50 @@ typedef enum {
d19186
   BROTLI_STATE_READ_BLOCK_LENGTH_SUFFIX
d19186
 } BrotliRunningReadBlockLengthState;
d19186
 
d19186
+typedef struct BrotliMetablockHeaderArena {
d19186
+  BrotliRunningTreeGroupState substate_tree_group;
d19186
+  BrotliRunningContextMapState substate_context_map;
d19186
+  BrotliRunningHuffmanState substate_huffman;
d19186
+
d19186
+  uint32_t sub_loop_counter;
d19186
+
d19186
+  uint32_t repeat_code_len;
d19186
+  uint32_t prev_code_len;
d19186
+
d19186
+  /* For ReadHuffmanCode. */
d19186
+  uint32_t symbol;
d19186
+  uint32_t repeat;
d19186
+  uint32_t space;
d19186
+
d19186
+  /* Huffman table for "histograms". */
d19186
+  HuffmanCode table[32];
d19186
+  /* List of heads of symbol chains. */
d19186
+  uint16_t* symbol_lists;
d19186
+  /* Storage from symbol_lists. */
d19186
+  uint16_t symbols_lists_array[BROTLI_HUFFMAN_MAX_CODE_LENGTH + 1 +
d19186
+                               BROTLI_NUM_COMMAND_SYMBOLS];
d19186
+  /* Tails of symbol chains. */
d19186
+  int next_symbol[32];
d19186
+  uint8_t code_length_code_lengths[BROTLI_CODE_LENGTH_CODES];
d19186
+  /* Population counts for the code lengths. */
d19186
+  uint16_t code_length_histo[16];
d19186
+
d19186
+  /* For HuffmanTreeGroupDecode. */
d19186
+  int htree_index;
d19186
+  HuffmanCode* next;
d19186
+
d19186
+  /* For DecodeContextMap. */
d19186
+  uint32_t context_index;
d19186
+  uint32_t max_run_length_prefix;
d19186
+  uint32_t code;
d19186
+  HuffmanCode context_map_table[BROTLI_HUFFMAN_MAX_SIZE_272];
d19186
+} BrotliMetablockHeaderArena;
d19186
+
d19186
+typedef struct BrotliMetablockBodyArena {
d19186
+  uint8_t dist_extra_bits[544];
d19186
+  uint32_t dist_offset[544];
d19186
+} BrotliMetablockBodyArena;
d19186
+
d19186
 struct BrotliDecoderStateStruct {
d19186
   BrotliRunningState state;
d19186
 
d19186
@@ -110,7 +245,8 @@ struct BrotliDecoderStateStruct {
d19186
   brotli_free_func free_func;
d19186
   void* memory_manager_opaque;
d19186
 
d19186
-  /* Temporary storage for remaining input. */
d19186
+  /* Temporary storage for remaining input. Brotli stream format is designed in
d19186
+     a way, that 64 bits are enough to make progress in decoding. */
d19186
   union {
d19186
     uint64_t u64;
d19186
     uint8_t u8[8];
d19186
@@ -125,7 +261,6 @@ struct BrotliDecoderStateStruct {
d19186
   int dist_rb_idx;
d19186
   int dist_rb[4];
d19186
   int error_code;
d19186
-  uint32_t sub_loop_counter;
d19186
   uint8_t* ringbuffer;
d19186
   uint8_t* ringbuffer_end;
d19186
   HuffmanCode* htree_command;
d19186
@@ -153,13 +288,10 @@ struct BrotliDecoderStateStruct {
d19186
   uint32_t block_type_rb[6];
d19186
   uint32_t distance_postfix_bits;
d19186
   uint32_t num_direct_distance_codes;
d19186
-  int distance_postfix_mask;
d19186
   uint32_t num_dist_htrees;
d19186
   uint8_t* dist_context_map;
d19186
   HuffmanCode* literal_htree;
d19186
   uint8_t dist_htree_index;
d19186
-  uint32_t repeat_code_len;
d19186
-  uint32_t prev_code_len;