Changeset 222903 in webkit


Ignore:
Timestamp:
Oct 5, 2017 12:54:02 AM (7 years ago)
Author:
fred.wang@free.fr
Message:

Upgrade Brotli to version 1.0.1 and WOFF2 to latest upstream
https://bugs.webkit.org/show_bug.cgi?id=177768

Patch by Frederic Wang <fwang@igalia.com> on 2017-10-05
Reviewed by Michael Catanzaro.

  • brotli/CMakeLists.txt:
  • brotli/README.webkit:
  • brotli/common/constants.h: Added.
  • brotli/common/dictionary.bin: Added.
  • brotli/common/dictionary.c: Added.
  • brotli/common/dictionary.h: Added.
  • brotli/common/version.h: Added.
  • brotli/dec/Makefile: Removed.
  • brotli/dec/bit_reader.c:
  • brotli/dec/bit_reader.h:
  • brotli/dec/context.h:
  • brotli/dec/decode.c:
  • brotli/dec/decode.h: Removed.
  • brotli/dec/dictionary.c: Removed.
  • brotli/dec/dictionary.h: Removed.
  • brotli/dec/huffman.c:
  • brotli/dec/huffman.h:
  • brotli/dec/port.h:

(BrotliDump):
(BrotliRBit):

  • brotli/dec/prefix.h:
  • brotli/dec/state.c:
  • brotli/dec/state.h:
  • brotli/dec/transform.h:
  • brotli/dec/types.h: Removed.
  • brotli/include/brotli/decode.h: Added.
  • brotli/include/brotli/encode.h: Added.
  • brotli/include/brotli/port.h: Added.
  • brotli/include/brotli/types.h: Added.
  • brotli/update.sh:
  • woff2/CMakeLists.txt:
  • woff2/README.webkit:
  • woff2/src/buffer.h:

(woff2::Buffer::Buffer):
(woff2::Buffer::Read):

  • woff2/src/convert_woff2ttf_*.cc: Added.
  • woff2/src/font.cc:
  • woff2/src/glyph.cc:
  • woff2/src/normalize.cc:
  • woff2/src/port.h:
  • woff2/src/store_bytes.h:

(woff2::Store16):

  • woff2/src/variable_length.cc:
  • woff2/src/woff2_common.cc:
  • woff2/src/woff2_dec.cc:
  • woff2/src/woff2_decompress.cc:
  • woff2/src/woff2_enc.cc:
  • woff2/src/woff2_info.cc: Added.
Location:
trunk/Source/ThirdParty
Files:
15 added
5 deleted
28 edited

Legend:

Unmodified
Added
Removed
  • trunk/Source/ThirdParty/ChangeLog

    r220403 r222903  
     12017-10-05  Frederic Wang  <fwang@igalia.com>
     2
     3        Upgrade Brotli to version 1.0.1 and WOFF2 to latest upstream
     4        https://bugs.webkit.org/show_bug.cgi?id=177768
     5
     6        Reviewed by Michael Catanzaro.
     7
     8        * brotli/CMakeLists.txt:
     9        * brotli/README.webkit:
     10        * brotli/common/constants.h: Added.
     11        * brotli/common/dictionary.bin: Added.
     12        * brotli/common/dictionary.c: Added.
     13        * brotli/common/dictionary.h: Added.
     14        * brotli/common/version.h: Added.
     15        * brotli/dec/Makefile: Removed.
     16        * brotli/dec/bit_reader.c:
     17        * brotli/dec/bit_reader.h:
     18        * brotli/dec/context.h:
     19        * brotli/dec/decode.c:
     20        * brotli/dec/decode.h: Removed.
     21        * brotli/dec/dictionary.c: Removed.
     22        * brotli/dec/dictionary.h: Removed.
     23        * brotli/dec/huffman.c:
     24        * brotli/dec/huffman.h:
     25        * brotli/dec/port.h:
     26        (BrotliDump):
     27        (BrotliRBit):
     28        * brotli/dec/prefix.h:
     29        * brotli/dec/state.c:
     30        * brotli/dec/state.h:
     31        * brotli/dec/transform.h:
     32        * brotli/dec/types.h: Removed.
     33        * brotli/include/brotli/decode.h: Added.
     34        * brotli/include/brotli/encode.h: Added.
     35        * brotli/include/brotli/port.h: Added.
     36        * brotli/include/brotli/types.h: Added.
     37        * brotli/update.sh:
     38        * woff2/CMakeLists.txt:
     39        * woff2/README.webkit:
     40        * woff2/src/buffer.h:
     41        (woff2::Buffer::Buffer):
     42        (woff2::Buffer::Read):
     43        * woff2/src/convert_woff2ttf_*.cc: Added.
     44        * woff2/src/font.cc:
     45        * woff2/src/glyph.cc:
     46        * woff2/src/normalize.cc:
     47        * woff2/src/port.h:
     48        * woff2/src/store_bytes.h:
     49        (woff2::Store16):
     50        * woff2/src/variable_length.cc:
     51        * woff2/src/woff2_common.cc:
     52        * woff2/src/woff2_dec.cc:
     53        * woff2/src/woff2_decompress.cc:
     54        * woff2/src/woff2_enc.cc:
     55        * woff2/src/woff2_info.cc: Added.
     56
    1572017-08-08  Michael Catanzaro  <mcatanzaro@igalia.com>
    258
  • trunk/Source/ThirdParty/brotli/CMakeLists.txt

    r220403 r222903  
    22
    33set(BROTLI_INCLUDE_DIRECTORIES
     4  "${BROTLI_DIR}/common"
    45  "${BROTLI_DIR}/dec"
     6  "${BROTLI_DIR}/include"
    57)
    68
    79set(BROTLI_SOURCES
     10    ${BROTLI_DIR}/common/dictionary.c
    811    ${BROTLI_DIR}/dec/bit_reader.c
    912    ${BROTLI_DIR}/dec/decode.c
    10     ${BROTLI_DIR}/dec/dictionary.c
    1113    ${BROTLI_DIR}/dec/huffman.c
    1214    ${BROTLI_DIR}/dec/state.c
  • trunk/Source/ThirdParty/brotli/README.webkit

    r202225 r222903  
    1515from within the modules/brotli directory.
    1616
    17 Current version: [commit 29d31d5921b0a2b323ac24e7f7d0cdc9a3c0dd08].
     17Current version: [commit 4f8cd4c0f4443d51a9603790a445b06c073b7a4d].
  • trunk/Source/ThirdParty/brotli/dec/bit_reader.c

    r197933 r222903  
    99#include "./bit_reader.h"
    1010
     11#include <brotli/types.h>
    1112#include "./port.h"
    12 #include "./types.h"
    1313
    1414#if defined(__cplusplus) || defined(c_plusplus)
     
    2121}
    2222
    23 int BrotliWarmupBitReader(BrotliBitReader* const br) {
     23BROTLI_BOOL BrotliWarmupBitReader(BrotliBitReader* const br) {
    2424  size_t aligned_read_mask = (sizeof(br->val_) >> 1) - 1;
    2525  /* Fixing alignment after unaligned BrotliFillWindow would result accumulator
    2626     overflow. If unalignment is caused by BrotliSafeReadBits, then there is
    27      enough space in accumulator to fix aligment. */
     27     enough space in accumulator to fix alignment. */
    2828  if (!BROTLI_ALIGNED_READ) {
    2929    aligned_read_mask = 0;
     
    3131  if (BrotliGetAvailableBits(br) == 0) {
    3232    if (!BrotliPullByte(br)) {
    33       return 0;
     33      return BROTLI_FALSE;
    3434    }
    3535  }
     
    3838    if (!BrotliPullByte(br)) {
    3939      /* If we consumed all the input, we don't care about the alignment. */
    40       return 1;
     40      return BROTLI_TRUE;
    4141    }
    4242  }
    43   return 1;
     43  return BROTLI_TRUE;
    4444}
    4545
  • trunk/Source/ThirdParty/brotli/dec/bit_reader.h

    r202225 r222903  
    1212#include <string.h>  /* memcpy */
    1313
     14#include <brotli/types.h>
    1415#include "./port.h"
    15 #include "./types.h"
    1616
    1717#if defined(__cplusplus) || defined(c_plusplus)
     
    1919#endif
    2020
    21 #if (BROTLI_64_BITS)
    22 #define BROTLI_SHORT_FILL_BIT_WINDOW_READ 4
    23 typedef uint64_t reg_t;
    24 #else
    25 #define BROTLI_SHORT_FILL_BIT_WINDOW_READ 2
    26 typedef uint32_t reg_t;
    27 #endif
     21#define BROTLI_SHORT_FILL_BIT_WINDOW_READ (sizeof(reg_t) >> 1)
    2822
    2923static const uint32_t kBitMask[33] = { 0x0000,
     
    6256} BrotliBitReaderState;
    6357
    64 /* Initializes the bitreader fields. */
     58/* Initializes the BrotliBitReader fields. */
    6559BROTLI_INTERNAL void BrotliInitBitReader(BrotliBitReader* const br);
    6660
     
    6963   For BROTLI_ALIGNED_READ this function also prepares bit reader for aligned
    7064   reading. */
    71 BROTLI_INTERNAL int BrotliWarmupBitReader(BrotliBitReader* const br);
     65BROTLI_INTERNAL BROTLI_BOOL BrotliWarmupBitReader(BrotliBitReader* const br);
    7266
    7367static BROTLI_INLINE void BrotliBitReaderSaveState(
     
    9892}
    9993
    100 /* Checks if there is at least num bytes left in the input ringbuffer (excluding
    101    the bits remaining in br->val_). */
    102 static BROTLI_INLINE int BrotliCheckInputAmount(
     94/* Checks if there is at least |num| bytes left in the input ring-buffer
     95   (excluding the bits remaining in br->val_). */
     96static BROTLI_INLINE BROTLI_BOOL BrotliCheckInputAmount(
    10397    BrotliBitReader* const br, size_t num) {
    104   return br->avail_in >= num;
     98  return TO_BROTLI_BOOL(br->avail_in >= num);
    10599}
    106100
     
    164158   Precondition: accumulator contains at least 1 bit.
    165159   n_bits should be in the range [1..24] for regular build. For portable
    166    non-64-bit little endian build only 16 bits are safe to request. */
     160   non-64-bit little-endian build only 16 bits are safe to request. */
    167161static BROTLI_INLINE void BrotliFillBitWindow(
    168162    BrotliBitReader* const br, uint32_t n_bits) {
     
    214208}
    215209
    216 /* Mosltly like BrotliFillBitWindow, but guarantees only 16 bits and reads no
     210/* Mostly like BrotliFillBitWindow, but guarantees only 16 bits and reads no
    217211   more than BROTLI_SHORT_FILL_BIT_WINDOW_READ bytes of input. */
    218212static BROTLI_INLINE void BrotliFillBitWindow16(BrotliBitReader* const br) {
     
    221215
    222216/* Pulls one byte of input to accumulator. */
    223 static BROTLI_INLINE int BrotliPullByte(BrotliBitReader* const br) {
     217static BROTLI_INLINE BROTLI_BOOL BrotliPullByte(BrotliBitReader* const br) {
    224218  if (br->avail_in == 0) {
    225     return 0;
     219    return BROTLI_FALSE;
    226220  }
    227221  br->val_ >>= 8;
     
    234228  --br->avail_in;
    235229  ++br->next_in;
    236   return 1;
     230  return BROTLI_TRUE;
    237231}
    238232
    239233/* Returns currently available bits.
    240    The number of valid bits could be calclulated by BrotliGetAvailableBits. */
     234   The number of valid bits could be calculated by BrotliGetAvailableBits. */
    241235static BROTLI_INLINE reg_t BrotliGetBitsUnmasked(BrotliBitReader* const br) {
    242236  return br->val_ >> br->bit_pos_;
     
    251245}
    252246
    253 /* Returns the specified number of bits from br without advancing bit pos. */
     247/* Returns the specified number of bits from |br| without advancing bit pos. */
    254248static BROTLI_INLINE uint32_t BrotliGetBits(
    255249    BrotliBitReader* const br, uint32_t n_bits) {
     
    260254/* Tries to peek the specified amount of bits. Returns 0, if there is not
    261255   enough input. */
    262 static BROTLI_INLINE int BrotliSafeGetBits(
     256static BROTLI_INLINE BROTLI_BOOL BrotliSafeGetBits(
    263257    BrotliBitReader* const br, uint32_t n_bits, uint32_t* val) {
    264258  while (BrotliGetAvailableBits(br) < n_bits) {
    265259    if (!BrotliPullByte(br)) {
    266       return 0;
     260      return BROTLI_FALSE;
    267261    }
    268262  }
    269263  *val = (uint32_t)BrotliGetBitsUnmasked(br) & BitMask(n_bits);
    270   return 1;
     264  return BROTLI_TRUE;
    271265}
    272266
     
    290284}
    291285
    292 /* Reads the specified number of bits from br and advances the bit pos.
     286/* Reads the specified number of bits from |br| and advances the bit pos.
    293287   Precondition: accumulator MUST contain at least n_bits. */
    294288static BROTLI_INLINE void BrotliTakeBits(
     
    300294}
    301295
    302 /* Reads the specified number of bits from br and advances the bit pos.
     296/* Reads the specified number of bits from |br| and advances the bit pos.
    303297   Assumes that there is enough input to perform BrotliFillBitWindow. */
    304298static BROTLI_INLINE uint32_t BrotliReadBits(
     
    322316/* Tries to read the specified amount of bits. Returns 0, if there is not
    323317   enough input. n_bits MUST be positive. */
    324 static BROTLI_INLINE int BrotliSafeReadBits(
     318static BROTLI_INLINE BROTLI_BOOL BrotliSafeReadBits(
    325319    BrotliBitReader* const br, uint32_t n_bits, uint32_t* val) {
    326320  while (BrotliGetAvailableBits(br) < n_bits) {
    327321    if (!BrotliPullByte(br)) {
    328       return 0;
     322      return BROTLI_FALSE;
    329323    }
    330324  }
    331325  BrotliTakeBits(br, n_bits, val);
    332   return 1;
     326  return BROTLI_TRUE;
    333327}
    334328
    335329/* Advances the bit reader position to the next byte boundary and verifies
    336330   that any skipped bits are set to zero. */
    337 static BROTLI_INLINE int BrotliJumpToByteBoundary(BrotliBitReader* br) {
     331static BROTLI_INLINE BROTLI_BOOL BrotliJumpToByteBoundary(BrotliBitReader* br) {
    338332  uint32_t pad_bits_count = BrotliGetAvailableBits(br) & 0x7;
    339333  uint32_t pad_bits = 0;
     
    341335    BrotliTakeBits(br, pad_bits_count, &pad_bits);
    342336  }
    343   return pad_bits == 0;
    344 }
    345 
    346 /* Peeks a byte at specified offset.
    347    Precondition: bit reader is parked to a byte boundary.
    348    Returns -1 if operation is not feasible. */
    349 static BROTLI_INLINE int BrotliPeekByte(BrotliBitReader* br, size_t offset) {
    350   uint32_t available_bits = BrotliGetAvailableBits(br);
    351   size_t bytes_left = available_bits >> 3;
    352   BROTLI_DCHECK((available_bits & 7) == 0);
    353   if (offset < bytes_left) {
    354     return (BrotliGetBitsUnmasked(br) >> (unsigned)(offset << 3)) & 0xFF;
    355   }
    356   offset -= bytes_left;
    357   if (offset < br->avail_in) {
    358     return br->next_in[offset];
    359   }
    360   return -1;
     337  return TO_BROTLI_BOOL(pad_bits == 0);
    361338}
    362339
  • trunk/Source/ThirdParty/brotli/dec/context.h

    r197933 r222903  
    100100#define BROTLI_DEC_CONTEXT_H_
    101101
    102 #include "./types.h"
     102#include <brotli/types.h>
    103103
    104104enum ContextType {
  • trunk/Source/ThirdParty/brotli/dec/decode.c

    r202225 r222903  
    55*/
    66
    7 #include "./decode.h"
     7#include <brotli/decode.h>
    88
    99#ifdef __ARM_NEON__
     
    1414#include <string.h>  /* memcpy, memset */
    1515
     16#include "../common/constants.h"
     17#include "../common/dictionary.h"
     18#include "../common/version.h"
    1619#include "./bit_reader.h"
    1720#include "./context.h"
    18 #include "./dictionary.h"
    1921#include "./huffman.h"
    2022#include "./port.h"
     
    3537         (unsigned long)(idx), (unsigned long)array_name[idx]))
    3638
    37 static const uint32_t kDefaultCodeLength = 8;
    38 static const uint32_t kCodeLengthRepeatCode = 16;
    39 static const uint32_t kNumLiteralCodes = 256;
    40 static const uint32_t kNumInsertAndCopyCodes = 704;
    41 static const uint32_t kNumBlockLengthCodes = 26;
    42 static const int kLiteralContextBits = 6;
    43 static const int kDistanceContextBits = 2;
    44 
    4539#define HUFFMAN_TABLE_BITS 8U
    4640#define HUFFMAN_TABLE_MASK 0xff
    4741
    48 #define CODE_LENGTH_CODES 18
    49 static const uint8_t kCodeLengthCodeOrder[CODE_LENGTH_CODES] = {
     42/* We need the slack region for the following reasons:
     43    - doing up to two 16-byte copies for fast backward copying
     44    - inserting transformed dictionary word (5 prefix + 24 base + 8 suffix) */
     45static const uint32_t kRingBufferWriteAheadSlack = 42;
     46
     47static const uint8_t kCodeLengthCodeOrder[BROTLI_CODE_LENGTH_CODES] = {
    5048  1, 2, 3, 4, 0, 5, 17, 6, 16, 7, 8, 9, 10, 11, 12, 13, 14, 15,
    5149};
     
    6058};
    6159
    62 #define NUM_DISTANCE_SHORT_CODES 16
    63 
    64 BrotliState* BrotliCreateState(
     60BROTLI_BOOL BrotliDecoderSetParameter(
     61    BrotliDecoderState* state, BrotliDecoderParameter p, uint32_t value) {
     62  switch (p) {
     63    case BROTLI_DECODER_PARAM_DISABLE_RING_BUFFER_REALLOCATION:
     64      state->canny_ringbuffer_allocation = !!value ? 0 : 1;
     65      return BROTLI_TRUE;
     66
     67    default: return BROTLI_FALSE;
     68  }
     69}
     70
     71BrotliDecoderState* BrotliDecoderCreateInstance(
    6572    brotli_alloc_func alloc_func, brotli_free_func free_func, void* opaque) {
    66   BrotliState* state = 0;
     73  BrotliDecoderState* state = 0;
    6774  if (!alloc_func && !free_func) {
    68     state = (BrotliState*)malloc(sizeof(BrotliState));
     75    state = (BrotliDecoderState*)malloc(sizeof(BrotliDecoderState));
    6976  } else if (alloc_func && free_func) {
    70     state = (BrotliState*)alloc_func(opaque, sizeof(BrotliState));
     77    state = (BrotliDecoderState*)alloc_func(opaque, sizeof(BrotliDecoderState));
    7178  }
    7279  if (state == 0) {
     
    7481    return 0;
    7582  }
    76   BrotliStateInitWithCustomAllocators(state, alloc_func, free_func, opaque);
    77   state->error_code = BROTLI_NO_ERROR;
     83  BrotliDecoderStateInitWithCustomAllocators(
     84      state, alloc_func, free_func, opaque);
    7885  return state;
    7986}
    8087
    81 /* Deinitializes and frees BrotliState instance. */
    82 void BrotliDestroyState(BrotliState* state) {
     88/* Deinitializes and frees BrotliDecoderState instance. */
     89void BrotliDecoderDestroyInstance(BrotliDecoderState* state) {
    8390  if (!state) {
    8491    return;
     
    8693    brotli_free_func free_func = state->free_func;
    8794    void* opaque = state->memory_manager_opaque;
    88     BrotliStateCleanup(state);
     95    BrotliDecoderStateCleanup(state);
    8996    free_func(opaque, state);
    9097  }
    9198}
    9299
    93 /* Saves error code and converts it to BrotliResult */
    94 static BROTLI_NOINLINE BrotliResult SaveErrorCode(
    95     BrotliState* s, BrotliErrorCode e) {
     100/* Saves error code and converts it to BrotliDecoderResult */
     101static BROTLI_NOINLINE BrotliDecoderResult SaveErrorCode(
     102    BrotliDecoderState* s, BrotliDecoderErrorCode e) {
    96103  s->error_code = (int)e;
    97104  switch (e) {
    98     case BROTLI_SUCCESS: return BROTLI_RESULT_SUCCESS;
    99     case BROTLI_NEEDS_MORE_INPUT: return BROTLI_RESULT_NEEDS_MORE_INPUT;
    100     case BROTLI_NEEDS_MORE_OUTPUT: return BROTLI_RESULT_NEEDS_MORE_OUTPUT;
    101     default: return BROTLI_RESULT_ERROR;
     105    case BROTLI_DECODER_SUCCESS:
     106      return BROTLI_DECODER_RESULT_SUCCESS;
     107    case BROTLI_DECODER_NEEDS_MORE_INPUT:
     108      return BROTLI_DECODER_RESULT_NEEDS_MORE_INPUT;
     109    case BROTLI_DECODER_NEEDS_MORE_OUTPUT:
     110      return BROTLI_DECODER_RESULT_NEEDS_MORE_OUTPUT;
     111    default:
     112      return BROTLI_DECODER_RESULT_ERROR;
    102113  }
    103114}
     
    133144
    134145/* Decodes a number in the range [0..255], by reading 1 - 11 bits. */
    135 static BROTLI_NOINLINE BrotliErrorCode DecodeVarLenUint8(BrotliState* s,
    136     BrotliBitReader* br, uint32_t* value) {
     146static BROTLI_NOINLINE BrotliDecoderErrorCode DecodeVarLenUint8(
     147    BrotliDecoderState* s, BrotliBitReader* br, uint32_t* value) {
    137148  uint32_t bits;
    138149  switch (s->substate_decode_uint8) {
    139150    case BROTLI_STATE_DECODE_UINT8_NONE:
    140       if (PREDICT_FALSE(!BrotliSafeReadBits(br, 1, &bits))) {
    141         return BROTLI_NEEDS_MORE_INPUT;
     151      if (BROTLI_PREDICT_FALSE(!BrotliSafeReadBits(br, 1, &bits))) {
     152        return BROTLI_DECODER_NEEDS_MORE_INPUT;
    142153      }
    143154      if (bits == 0) {
    144155        *value = 0;
    145         return BROTLI_SUCCESS;
     156        return BROTLI_DECODER_SUCCESS;
    146157      }
    147158      /* No break, transit to the next state. */
    148159
    149160    case BROTLI_STATE_DECODE_UINT8_SHORT:
    150       if (PREDICT_FALSE(!BrotliSafeReadBits(br, 3, &bits))) {
     161      if (BROTLI_PREDICT_FALSE(!BrotliSafeReadBits(br, 3, &bits))) {
    151162        s->substate_decode_uint8 = BROTLI_STATE_DECODE_UINT8_SHORT;
    152         return BROTLI_NEEDS_MORE_INPUT;
     163        return BROTLI_DECODER_NEEDS_MORE_INPUT;
    153164      }
    154165      if (bits == 0) {
    155166        *value = 1;
    156167        s->substate_decode_uint8 = BROTLI_STATE_DECODE_UINT8_NONE;
    157         return BROTLI_SUCCESS;
     168        return BROTLI_DECODER_SUCCESS;
    158169      }
    159170      /* Use output value as a temporary storage. It MUST be persisted. */
     
    162173
    163174    case BROTLI_STATE_DECODE_UINT8_LONG:
    164       if (PREDICT_FALSE(!BrotliSafeReadBits(br, *value, &bits))) {
     175      if (BROTLI_PREDICT_FALSE(!BrotliSafeReadBits(br, *value, &bits))) {
    165176        s->substate_decode_uint8 = BROTLI_STATE_DECODE_UINT8_LONG;
    166         return BROTLI_NEEDS_MORE_INPUT;
     177        return BROTLI_DECODER_NEEDS_MORE_INPUT;
    167178      }
    168179      *value = (1U << *value) + bits;
    169180      s->substate_decode_uint8 = BROTLI_STATE_DECODE_UINT8_NONE;
    170       return BROTLI_SUCCESS;
     181      return BROTLI_DECODER_SUCCESS;
    171182
    172183    default:
    173       return BROTLI_FAILURE(BROTLI_ERROR_UNREACHABLE);
     184      return
     185          BROTLI_FAILURE(BROTLI_DECODER_ERROR_UNREACHABLE);
    174186  }
    175187}
    176188
    177189/* Decodes a metablock length and flags by reading 2 - 31 bits. */
    178 static BrotliErrorCode BROTLI_NOINLINE DecodeMetaBlockLength(
    179     BrotliState* s, BrotliBitReader* br) {
     190static BrotliDecoderErrorCode BROTLI_NOINLINE DecodeMetaBlockLength(
     191    BrotliDecoderState* s, BrotliBitReader* br) {
    180192  uint32_t bits;
    181193  int i;
     
    184196      case BROTLI_STATE_METABLOCK_HEADER_NONE:
    185197        if (!BrotliSafeReadBits(br, 1, &bits)) {
    186           return BROTLI_NEEDS_MORE_INPUT;
    187         }
    188         s->is_last_metablock = (uint8_t)bits;
     198          return BROTLI_DECODER_NEEDS_MORE_INPUT;
     199        }
     200        s->is_last_metablock = bits ? 1 : 0;
    189201        s->meta_block_remaining_len = 0;
    190202        s->is_uncompressed = 0;
     
    199211      case BROTLI_STATE_METABLOCK_HEADER_EMPTY:
    200212        if (!BrotliSafeReadBits(br, 1, &bits)) {
    201           return BROTLI_NEEDS_MORE_INPUT;
     213          return BROTLI_DECODER_NEEDS_MORE_INPUT;
    202214        }
    203215        if (bits) {
    204216          s->substate_metablock_header = BROTLI_STATE_METABLOCK_HEADER_NONE;
    205           return BROTLI_SUCCESS;
     217          return BROTLI_DECODER_SUCCESS;
    206218        }
    207219        s->substate_metablock_header = BROTLI_STATE_METABLOCK_HEADER_NIBBLES;
     
    210222      case BROTLI_STATE_METABLOCK_HEADER_NIBBLES:
    211223        if (!BrotliSafeReadBits(br, 2, &bits)) {
    212           return BROTLI_NEEDS_MORE_INPUT;
     224          return BROTLI_DECODER_NEEDS_MORE_INPUT;
    213225        }
    214226        s->size_nibbles = (uint8_t)(bits + 4);
     
    224236      case BROTLI_STATE_METABLOCK_HEADER_SIZE:
    225237        i = s->loop_counter;
    226         for (; i < s->size_nibbles; ++i) {
     238        for (; i < (int)s->size_nibbles; ++i) {
    227239          if (!BrotliSafeReadBits(br, 4, &bits)) {
    228240            s->loop_counter = i;
    229             return BROTLI_NEEDS_MORE_INPUT;
     241            return BROTLI_DECODER_NEEDS_MORE_INPUT;
    230242          }
    231243          if (i + 1 == s->size_nibbles && s->size_nibbles > 4 && bits == 0) {
    232             return BROTLI_FAILURE(BROTLI_ERROR_FORMAT_EXUBERANT_NIBBLE);
     244            return BROTLI_FAILURE(BROTLI_DECODER_ERROR_FORMAT_EXUBERANT_NIBBLE);
    233245          }
    234246          s->meta_block_remaining_len |= (int)(bits << (i * 4));
     
    241253        if (!s->is_last_metablock) {
    242254          if (!BrotliSafeReadBits(br, 1, &bits)) {
    243             return BROTLI_NEEDS_MORE_INPUT;
     255            return BROTLI_DECODER_NEEDS_MORE_INPUT;
    244256          }
    245           s->is_uncompressed = (uint8_t)bits;
     257          s->is_uncompressed = bits ? 1 : 0;
    246258        }
    247259        ++s->meta_block_remaining_len;
    248260        s->substate_metablock_header = BROTLI_STATE_METABLOCK_HEADER_NONE;
    249         return BROTLI_SUCCESS;
     261        return BROTLI_DECODER_SUCCESS;
    250262
    251263      case BROTLI_STATE_METABLOCK_HEADER_RESERVED:
    252264        if (!BrotliSafeReadBits(br, 1, &bits)) {
    253           return BROTLI_NEEDS_MORE_INPUT;
     265          return BROTLI_DECODER_NEEDS_MORE_INPUT;
    254266        }
    255267        if (bits != 0) {
    256           return BROTLI_FAILURE(BROTLI_ERROR_FORMAT_RESERVED);
     268          return BROTLI_FAILURE(BROTLI_DECODER_ERROR_FORMAT_RESERVED);
    257269        }
    258270        s->substate_metablock_header = BROTLI_STATE_METABLOCK_HEADER_BYTES;
     
    261273      case BROTLI_STATE_METABLOCK_HEADER_BYTES:
    262274        if (!BrotliSafeReadBits(br, 2, &bits)) {
    263           return BROTLI_NEEDS_MORE_INPUT;
     275          return BROTLI_DECODER_NEEDS_MORE_INPUT;
    264276        }
    265277        if (bits == 0) {
    266278          s->substate_metablock_header = BROTLI_STATE_METABLOCK_HEADER_NONE;
    267           return BROTLI_SUCCESS;
     279          return BROTLI_DECODER_SUCCESS;
    268280        }
    269281        s->size_nibbles = (uint8_t)bits;
     
    273285      case BROTLI_STATE_METABLOCK_HEADER_METADATA:
    274286        i = s->loop_counter;
    275         for (; i < s->size_nibbles; ++i) {
     287        for (; i < (int)s->size_nibbles; ++i) {
    276288          if (!BrotliSafeReadBits(br, 8, &bits)) {
    277289            s->loop_counter = i;
    278             return BROTLI_NEEDS_MORE_INPUT;
     290            return BROTLI_DECODER_NEEDS_MORE_INPUT;
    279291          }
    280292          if (i + 1 == s->size_nibbles && s->size_nibbles > 1 && bits == 0) {
    281             return BROTLI_FAILURE(BROTLI_ERROR_FORMAT_EXUBERANT_META_NIBBLE);
     293            return BROTLI_FAILURE(
     294                BROTLI_DECODER_ERROR_FORMAT_EXUBERANT_META_NIBBLE);
    282295          }
    283296          s->meta_block_remaining_len |= (int)(bits << (i * 8));
     
    285298        ++s->meta_block_remaining_len;
    286299        s->substate_metablock_header = BROTLI_STATE_METABLOCK_HEADER_NONE;
    287         return BROTLI_SUCCESS;
     300        return BROTLI_DECODER_SUCCESS;
    288301
    289302      default:
    290         return BROTLI_FAILURE(BROTLI_ERROR_UNREACHABLE);
     303        return
     304            BROTLI_FAILURE(BROTLI_DECODER_ERROR_UNREACHABLE);
    291305    }
    292306  }
     
    320334/* Same as DecodeSymbol, but it is known that there is less than 15 bits of
    321335   input are currently available. */
    322 static BROTLI_NOINLINE int SafeDecodeSymbol(const HuffmanCode* table,
    323                                             BrotliBitReader* br,
    324                                             uint32_t* result) {
     336static BROTLI_NOINLINE BROTLI_BOOL SafeDecodeSymbol(
     337    const HuffmanCode* table, BrotliBitReader* br, uint32_t* result) {
    325338  uint32_t val;
    326339  uint32_t available_bits = BrotliGetAvailableBits(br);
     
    328341    if (table->bits == 0) {
    329342      *result = table->value;
    330       return 1;
    331     }
    332     return 0; /* No valid bits at all. */
     343      return BROTLI_TRUE;
     344    }
     345    return BROTLI_FALSE; /* No valid bits at all. */
    333346  }
    334347  val = (uint32_t)BrotliGetBitsUnmasked(br);
     
    338351      BrotliDropBits(br, table->bits);
    339352      *result = table->value;
    340       return 1;
     353      return BROTLI_TRUE;
    341354    } else {
    342       return 0; /* Not enough bits for the first level. */
     355      return BROTLI_FALSE; /* Not enough bits for the first level. */
    343356    }
    344357  }
    345358  if (available_bits <= HUFFMAN_TABLE_BITS) {
    346     return 0; /* Not enough bits to move to the second level. */
     359    return BROTLI_FALSE; /* Not enough bits to move to the second level. */
    347360  }
    348361
     
    352365  table += table->value + val;
    353366  if (available_bits < table->bits) {
    354     return 0; /* Not enough bits for the second level. */
     367    return BROTLI_FALSE; /* Not enough bits for the second level. */
    355368  }
    356369
    357370  BrotliDropBits(br, HUFFMAN_TABLE_BITS + table->bits);
    358371  *result = table->value;
    359   return 1;
    360 }
    361 
    362 static BROTLI_INLINE int SafeReadSymbol(const HuffmanCode* table,
    363                                         BrotliBitReader* br,
    364                                         uint32_t* result) {
     372  return BROTLI_TRUE;
     373}
     374
     375static BROTLI_INLINE BROTLI_BOOL SafeReadSymbol(
     376    const HuffmanCode* table, BrotliBitReader* br, uint32_t* result) {
    365377  uint32_t val;
    366   if (PREDICT_TRUE(BrotliSafeGetBits(br, 15, &val))) {
     378  if (BROTLI_PREDICT_TRUE(BrotliSafeGetBits(br, 15, &val))) {
    367379    *result = DecodeSymbol(val, table, br);
    368     return 1;
     380    return BROTLI_TRUE;
    369381  }
    370382  return SafeDecodeSymbol(table, br, result);
     
    392404                                                  uint32_t* value) {
    393405  uint32_t result = *value;
    394   if (PREDICT_FALSE(*bits > HUFFMAN_TABLE_BITS)) {
     406  if (BROTLI_PREDICT_FALSE(*bits > HUFFMAN_TABLE_BITS)) {
    395407    uint32_t val = BrotliGet16BitsUnmasked(br);
    396408    const HuffmanCode* ext = table + (val & HUFFMAN_TABLE_MASK) + *value;
     
    420432   The list of symbols MUST NOT contain duplicates.
    421433 */
    422 static BrotliErrorCode ReadSimpleHuffmanSymbols(uint32_t alphabet_size,
    423                                                 BrotliState* s) {
     434static BrotliDecoderErrorCode ReadSimpleHuffmanSymbols(
     435    uint32_t alphabet_size, BrotliDecoderState* s) {
    424436  /* max_bits == 1..10; symbol == 0..3; 1..40 bits will be read. */
    425437  BrotliBitReader* br = &s->br;
     
    429441  while (i <= num_symbols) {
    430442    uint32_t v;
    431     if (PREDICT_FALSE(!BrotliSafeReadBits(br, max_bits, &v))) {
     443    if (BROTLI_PREDICT_FALSE(!BrotliSafeReadBits(br, max_bits, &v))) {
    432444      s->sub_loop_counter = i;
    433445      s->substate_huffman = BROTLI_STATE_HUFFMAN_SIMPLE_READ;
    434       return BROTLI_NEEDS_MORE_INPUT;
     446      return BROTLI_DECODER_NEEDS_MORE_INPUT;
    435447    }
    436448    if (v >= alphabet_size) {
    437       return BROTLI_FAILURE(BROTLI_ERROR_FORMAT_SIMPLE_HUFFMAN_ALPHABET);
     449      return
     450          BROTLI_FAILURE(BROTLI_DECODER_ERROR_FORMAT_SIMPLE_HUFFMAN_ALPHABET);
    438451    }
    439452    s->symbols_lists_array[i] = (uint16_t)v;
     
    446459    for (; k <= num_symbols; ++k) {
    447460      if (s->symbols_lists_array[i] == s->symbols_lists_array[k]) {
    448         return BROTLI_FAILURE(BROTLI_ERROR_FORMAT_SIMPLE_HUFFMAN_SAME);
    449       }
    450     }
    451   }
    452 
    453   return BROTLI_SUCCESS;
     461        return BROTLI_FAILURE(BROTLI_DECODER_ERROR_FORMAT_SIMPLE_HUFFMAN_SAME);
     462      }
     463    }
     464  }
     465
     466  return BROTLI_DECODER_SUCCESS;
    454467}
    455468
     
    457470    A) reset the repeat variable
    458471    B) remember code length (if it is not 0)
    459     C) extend corredponding index-chain
    460     D) reduce the huffman space
     472    C) extend corresponding index-chain
     473    D) reduce the Huffman space
    461474    E) update the histogram
    462475 */
     
    479492/* Process repeated symbol code length.
    480493    A) Check if it is the extension of previous repeat sequence; if the decoded
    481        value is not kCodeLengthRepeatCode, then it is a new symbol-skip
     494       value is not BROTLI_REPEAT_PREVIOUS_CODE_LENGTH, then it is a new
     495       symbol-skip
    482496    B) Update repeat variable
    483     C) Check if operation is feasible (fits alphapet)
     497    C) Check if operation is feasible (fits alphabet)
    484498    D) For each symbol do the same operations as in ProcessSingleCodeLength
    485499
    486    PRECONDITION: code_len == kCodeLengthRepeatCode or kCodeLengthRepeatCode + 1
     500   PRECONDITION: code_len == BROTLI_REPEAT_PREVIOUS_CODE_LENGTH or
     501                 code_len == BROTLI_REPEAT_ZERO_CODE_LENGTH
    487502 */
    488503static BROTLI_INLINE void ProcessRepeatedCodeLength(uint32_t code_len,
     
    492507    uint16_t* code_length_histo, int* next_symbol) {
    493508  uint32_t old_repeat;
    494   uint32_t new_len = 0;
    495   if (code_len == kCodeLengthRepeatCode) {
     509  uint32_t extra_bits = 3;  /* for BROTLI_REPEAT_ZERO_CODE_LENGTH */
     510  uint32_t new_len = 0;  /* for BROTLI_REPEAT_ZERO_CODE_LENGTH */
     511  if (code_len == BROTLI_REPEAT_PREVIOUS_CODE_LENGTH) {
    496512    new_len = *prev_code_len;
     513    extra_bits = 2;
    497514  }
    498515  if (*repeat_code_len != new_len) {
     
    503520  if (*repeat > 0) {
    504521    *repeat -= 2;
    505     *repeat <<= code_len - 14U;
     522    *repeat <<= extra_bits;
    506523  }
    507524  *repeat += repeat_delta + 3U;
     
    532549
    533550/* Reads and decodes symbol codelengths. */
    534 static BrotliErrorCode ReadSymbolCodeLengths(
    535     uint32_t alphabet_size, BrotliState* s) {
     551static BrotliDecoderErrorCode ReadSymbolCodeLengths(
     552    uint32_t alphabet_size, BrotliDecoderState* s) {
    536553  BrotliBitReader* br = &s->br;
    537554  uint32_t symbol = s->symbol;
     
    544561  int* next_symbol = s->next_symbol;
    545562  if (!BrotliWarmupBitReader(br)) {
    546     return BROTLI_NEEDS_MORE_INPUT;
     563    return BROTLI_DECODER_NEEDS_MORE_INPUT;
    547564  }
    548565  while (symbol < alphabet_size && space > 0) {
     
    555572      s->repeat_code_len = repeat_code_len;
    556573      s->space = space;
    557       return BROTLI_NEEDS_MORE_INPUT;
     574      return BROTLI_DECODER_NEEDS_MORE_INPUT;
    558575    }
    559576    BrotliFillBitWindow16(br);
     
    562579    BrotliDropBits(br, p->bits);  /* Use 1..5 bits */
    563580    code_len = p->value;  /* code_len == 0..17 */
    564     if (code_len < kCodeLengthRepeatCode) {
     581    if (code_len < BROTLI_REPEAT_PREVIOUS_CODE_LENGTH) {
    565582      ProcessSingleCodeLength(code_len, &symbol, &repeat, &space,
    566583          &prev_code_len, symbol_lists, code_length_histo, next_symbol);
    567584    } else { /* code_len == 16..17, extra_bits == 2..3 */
     585      uint32_t extra_bits =
     586          (code_len == BROTLI_REPEAT_PREVIOUS_CODE_LENGTH) ? 2 : 3;
    568587      uint32_t repeat_delta =
    569           (uint32_t)BrotliGetBitsUnmasked(br) & BitMask(code_len - 14U);
    570       BrotliDropBits(br, code_len - 14U);
     588          (uint32_t)BrotliGetBitsUnmasked(br) & BitMask(extra_bits);
     589      BrotliDropBits(br, extra_bits);
    571590      ProcessRepeatedCodeLength(code_len, repeat_delta, alphabet_size,
    572591          &symbol, &repeat, &space, &prev_code_len, &repeat_code_len,
     
    575594  }
    576595  s->space = space;
    577   return BROTLI_SUCCESS;
    578 }
    579 
    580 static BrotliErrorCode SafeReadSymbolCodeLengths(
    581     uint32_t alphabet_size, BrotliState* s) {
     596  return BROTLI_DECODER_SUCCESS;
     597}
     598
     599static BrotliDecoderErrorCode SafeReadSymbolCodeLengths(
     600    uint32_t alphabet_size, BrotliDecoderState* s) {
    582601  BrotliBitReader* br = &s->br;
     602  BROTLI_BOOL get_byte = BROTLI_FALSE;
    583603  while (s->symbol < alphabet_size && s->space > 0) {
    584604    const HuffmanCode* p = s->table;
    585605    uint32_t code_len;
     606    uint32_t available_bits;
    586607    uint32_t bits = 0;
    587     uint32_t available_bits = BrotliGetAvailableBits(br);
     608    if (get_byte && !BrotliPullByte(br)) return BROTLI_DECODER_NEEDS_MORE_INPUT;
     609    get_byte = BROTLI_FALSE;
     610    available_bits = BrotliGetAvailableBits(br);
    588611    if (available_bits != 0) {
    589612      bits = (uint32_t)BrotliGetBitsUnmasked(br);
    590613    }
    591614    p += bits & BitMask(BROTLI_HUFFMAN_MAX_CODE_LENGTH_CODE_LENGTH);
    592     if (p->bits > available_bits) goto pullMoreInput;
     615    if (p->bits > available_bits) {
     616      get_byte = BROTLI_TRUE;
     617      continue;
     618    }
    593619    code_len = p->value; /* code_len == 0..17 */
    594     if (code_len < kCodeLengthRepeatCode) {
     620    if (code_len < BROTLI_REPEAT_PREVIOUS_CODE_LENGTH) {
    595621      BrotliDropBits(br, p->bits);
    596622      ProcessSingleCodeLength(code_len, &s->symbol, &s->repeat, &s->space,
     
    600626      uint32_t extra_bits = code_len - 14U;
    601627      uint32_t repeat_delta = (bits >> p->bits) & BitMask(extra_bits);
    602       if (available_bits < p->bits + extra_bits) goto pullMoreInput;
     628      if (available_bits < p->bits + extra_bits) {
     629        get_byte = BROTLI_TRUE;
     630        continue;
     631      }
    603632      BrotliDropBits(br, p->bits + extra_bits);
    604633      ProcessRepeatedCodeLength(code_len, repeat_delta, alphabet_size,
     
    607636          s->next_symbol);
    608637    }
    609     continue;
    610 
    611 pullMoreInput:
    612     if (!BrotliPullByte(br)) {
    613       return BROTLI_NEEDS_MORE_INPUT;
    614     }
    615   }
    616   return BROTLI_SUCCESS;
     638  }
     639  return BROTLI_DECODER_SUCCESS;
    617640}
    618641
    619642/* Reads and decodes 15..18 codes using static prefix code.
    620643   Each code is 2..4 bits long. In total 30..72 bits are used. */
    621 static BrotliErrorCode ReadCodeLengthCodeLengths(BrotliState* s) {
     644static BrotliDecoderErrorCode ReadCodeLengthCodeLengths(BrotliDecoderState* s) {
    622645  BrotliBitReader* br = &s->br;
    623646  uint32_t num_codes = s->repeat;
    624647  unsigned space = s->space;
    625648  uint32_t i = s->sub_loop_counter;
    626   for (; i < CODE_LENGTH_CODES; ++i) {
     649  for (; i < BROTLI_CODE_LENGTH_CODES; ++i) {
    627650    const uint8_t code_len_idx = kCodeLengthCodeOrder[i];
    628651    uint32_t ix;
    629652    uint32_t v;
    630     if (PREDICT_FALSE(!BrotliSafeGetBits(br, 4, &ix))) {
     653    if (BROTLI_PREDICT_FALSE(!BrotliSafeGetBits(br, 4, &ix))) {
    631654      uint32_t available_bits = BrotliGetAvailableBits(br);
    632655      if (available_bits != 0) {
     
    640663        s->space = space;
    641664        s->substate_huffman = BROTLI_STATE_HUFFMAN_COMPLEX;
    642         return BROTLI_NEEDS_MORE_INPUT;
     665        return BROTLI_DECODER_NEEDS_MORE_INPUT;
    643666      }
    644667    }
     
    658681  }
    659682  if (!(num_codes == 1 || space == 0)) {
    660     return BROTLI_FAILURE(BROTLI_ERROR_FORMAT_CL_SPACE);
    661   }
    662   return BROTLI_SUCCESS;
     683    return BROTLI_FAILURE(BROTLI_DECODER_ERROR_FORMAT_CL_SPACE);
     684  }
     685  return BROTLI_DECODER_SUCCESS;
    663686}
    664687
     
    675698         Huffman table. In worst case 3520 bits are read.
    676699*/
    677 static BrotliErrorCode ReadHuffmanCode(uint32_t alphabet_size,
    678                                        HuffmanCode* table,
    679                                        uint32_t* opt_table_size,
    680                                        BrotliState* s) {
     700static BrotliDecoderErrorCode ReadHuffmanCode(uint32_t alphabet_size,
     701                                              HuffmanCode* table,
     702                                              uint32_t* opt_table_size,
     703                                              BrotliDecoderState* s) {
    681704  BrotliBitReader* br = &s->br;
    682705  /* Unnecessary masking, but might be good for safety. */
    683706  alphabet_size &= 0x3ff;
    684707  /* State machine */
    685   switch (s->substate_huffman) {
    686     case BROTLI_STATE_HUFFMAN_NONE:
    687       if (!BrotliSafeReadBits(br, 2, &s->sub_loop_counter)) {
    688         return BROTLI_NEEDS_MORE_INPUT;
    689       }
    690       BROTLI_LOG_UINT(s->sub_loop_counter);
    691       /* The value is used as follows:
    692          1 for simple code;
    693          0 for no skipping, 2 skips 2 code lengths, 3 skips 3 code lengths */
    694       if (s->sub_loop_counter != 1) {
    695         s->space = 32;
    696         s->repeat = 0; /* num_codes */
    697         memset(&s->code_length_histo[0], 0, sizeof(s->code_length_histo[0]) *
    698             (BROTLI_HUFFMAN_MAX_CODE_LENGTH_CODE_LENGTH + 1));
    699         memset(&s->code_length_code_lengths[0], 0,
    700             sizeof(s->code_length_code_lengths));
    701         s->substate_huffman = BROTLI_STATE_HUFFMAN_COMPLEX;
    702         goto Complex;
    703       }
    704       /* No break, transit to the next state. */
    705 
    706     case BROTLI_STATE_HUFFMAN_SIMPLE_SIZE:
    707       /* Read symbols, codes & code lengths directly. */
    708       if (!BrotliSafeReadBits(br, 2, &s->symbol)) { /* num_symbols */
    709         s->substate_huffman = BROTLI_STATE_HUFFMAN_SIMPLE_SIZE;
    710         return BROTLI_NEEDS_MORE_INPUT;
    711       }
    712       s->sub_loop_counter = 0;
    713       /* No break, transit to the next state. */
    714     case BROTLI_STATE_HUFFMAN_SIMPLE_READ: {
    715       BrotliErrorCode result = ReadSimpleHuffmanSymbols(alphabet_size, s);
    716       if (result != BROTLI_SUCCESS) {
    717         return result;
    718       }
    719       /* No break, transit to the next state. */
    720     }
    721     case BROTLI_STATE_HUFFMAN_SIMPLE_BUILD: {
    722       uint32_t table_size;
    723       if (s->symbol == 3) {
    724         uint32_t bits;
    725         if (!BrotliSafeReadBits(br, 1, &bits)) {
    726           s->substate_huffman = BROTLI_STATE_HUFFMAN_SIMPLE_BUILD;
    727           return BROTLI_NEEDS_MORE_INPUT;
    728         }
    729         s->symbol += bits;
    730       }
    731       BROTLI_LOG_UINT(s->symbol);
    732       table_size = BrotliBuildSimpleHuffmanTable(
    733           table, HUFFMAN_TABLE_BITS, s->symbols_lists_array, s->symbol);
    734       if (opt_table_size) {
    735         *opt_table_size = table_size;
    736       }
    737       s->substate_huffman = BROTLI_STATE_HUFFMAN_NONE;
    738       return BROTLI_SUCCESS;
    739     }
    740 
    741 Complex: /* Decode Huffman-coded code lengths. */
    742     case BROTLI_STATE_HUFFMAN_COMPLEX: {
    743       uint32_t i;
    744       BrotliErrorCode result = ReadCodeLengthCodeLengths(s);
    745       if (result != BROTLI_SUCCESS) {
    746         return result;
    747       }
    748       BrotliBuildCodeLengthsHuffmanTable(s->table,
    749                                          s->code_length_code_lengths,
    750                                          s->code_length_histo);
    751       memset(&s->code_length_histo[0], 0, sizeof(s->code_length_histo));
    752       for (i = 0; i <= BROTLI_HUFFMAN_MAX_CODE_LENGTH; ++i) {
    753         s->next_symbol[i] = (int)i - (BROTLI_HUFFMAN_MAX_CODE_LENGTH + 1);
    754         s->symbol_lists[(int)i - (BROTLI_HUFFMAN_MAX_CODE_LENGTH + 1)] = 0xFFFF;
    755       }
    756 
    757       s->symbol = 0;
    758       s->prev_code_len = kDefaultCodeLength;
    759       s->repeat = 0;
    760       s->repeat_code_len = 0;
    761       s->space = 32768;
    762       s->substate_huffman = BROTLI_STATE_HUFFMAN_LENGTH_SYMBOLS;
    763       /* No break, transit to the next state. */
    764     }
    765     case BROTLI_STATE_HUFFMAN_LENGTH_SYMBOLS: {
    766       uint32_t table_size;
    767       BrotliErrorCode result = ReadSymbolCodeLengths(alphabet_size, s);
    768       if (result == BROTLI_NEEDS_MORE_INPUT) {
    769         result = SafeReadSymbolCodeLengths(alphabet_size, s);
    770       }
    771       if (result != BROTLI_SUCCESS) {
    772         return result;
    773       }
    774 
    775       if (s->space != 0) {
    776         BROTLI_LOG(("[ReadHuffmanCode] space = %d\n", s->space));
    777         return BROTLI_FAILURE(BROTLI_ERROR_FORMAT_HUFFMAN_SPACE);
    778       }
    779       table_size = BrotliBuildHuffmanTable(
    780           table, HUFFMAN_TABLE_BITS, s->symbol_lists, s->code_length_histo);
    781       if (opt_table_size) {
    782         *opt_table_size = table_size;
    783       }
    784       s->substate_huffman = BROTLI_STATE_HUFFMAN_NONE;
    785       return BROTLI_SUCCESS;
    786     }
    787 
    788     default:
    789       return BROTLI_FAILURE(BROTLI_ERROR_UNREACHABLE);
     708  for (;;) {
     709    switch (s->substate_huffman) {
     710      case BROTLI_STATE_HUFFMAN_NONE:
     711        if (!BrotliSafeReadBits(br, 2, &s->sub_loop_counter)) {
     712          return BROTLI_DECODER_NEEDS_MORE_INPUT;
     713        }
     714        BROTLI_LOG_UINT(s->sub_loop_counter);
     715        /* The value is used as follows:
     716           1 for simple code;
     717           0 for no skipping, 2 skips 2 code lengths, 3 skips 3 code lengths */
     718        if (s->sub_loop_counter != 1) {
     719          s->space = 32;
     720          s->repeat = 0; /* num_codes */
     721          memset(&s->code_length_histo[0], 0, sizeof(s->code_length_histo[0]) *
     722              (BROTLI_HUFFMAN_MAX_CODE_LENGTH_CODE_LENGTH + 1));
     723          memset(&s->code_length_code_lengths[0], 0,
     724              sizeof(s->code_length_code_lengths));
     725          s->substate_huffman = BROTLI_STATE_HUFFMAN_COMPLEX;
     726          continue;
     727        }
     728        /* No break, transit to the next state. */
     729
     730      case BROTLI_STATE_HUFFMAN_SIMPLE_SIZE:
     731        /* Read symbols, codes & code lengths directly. */
     732        if (!BrotliSafeReadBits(br, 2, &s->symbol)) { /* num_symbols */
     733          s->substate_huffman = BROTLI_STATE_HUFFMAN_SIMPLE_SIZE;
     734          return BROTLI_DECODER_NEEDS_MORE_INPUT;
     735        }
     736        s->sub_loop_counter = 0;
     737        /* No break, transit to the next state. */
     738      case BROTLI_STATE_HUFFMAN_SIMPLE_READ: {
     739        BrotliDecoderErrorCode result =
     740            ReadSimpleHuffmanSymbols(alphabet_size, s);
     741        if (result != BROTLI_DECODER_SUCCESS) {
     742          return result;
     743        }
     744        /* No break, transit to the next state. */
     745      }
     746      case BROTLI_STATE_HUFFMAN_SIMPLE_BUILD: {
     747        uint32_t table_size;
     748        if (s->symbol == 3) {
     749          uint32_t bits;
     750          if (!BrotliSafeReadBits(br, 1, &bits)) {
     751            s->substate_huffman = BROTLI_STATE_HUFFMAN_SIMPLE_BUILD;
     752            return BROTLI_DECODER_NEEDS_MORE_INPUT;
     753          }
     754          s->symbol += bits;
     755        }
     756        BROTLI_LOG_UINT(s->symbol);
     757        table_size = BrotliBuildSimpleHuffmanTable(
     758            table, HUFFMAN_TABLE_BITS, s->symbols_lists_array, s->symbol);
     759        if (opt_table_size) {
     760          *opt_table_size = table_size;
     761        }
     762        s->substate_huffman = BROTLI_STATE_HUFFMAN_NONE;
     763        return BROTLI_DECODER_SUCCESS;
     764      }
     765
     766      /* Decode Huffman-coded code lengths. */
     767      case BROTLI_STATE_HUFFMAN_COMPLEX: {
     768        uint32_t i;
     769        BrotliDecoderErrorCode result = ReadCodeLengthCodeLengths(s);
     770        if (result != BROTLI_DECODER_SUCCESS) {
     771          return result;
     772        }
     773        BrotliBuildCodeLengthsHuffmanTable(s->table,
     774                                           s->code_length_code_lengths,
     775                                           s->code_length_histo);
     776        memset(&s->code_length_histo[0], 0, sizeof(s->code_length_histo));
     777        for (i = 0; i <= BROTLI_HUFFMAN_MAX_CODE_LENGTH; ++i) {
     778          s->next_symbol[i] = (int)i - (BROTLI_HUFFMAN_MAX_CODE_LENGTH + 1);
     779          s->symbol_lists[s->next_symbol[i]] = 0xFFFF;
     780        }
     781
     782        s->symbol = 0;
     783        s->prev_code_len = BROTLI_INITIAL_REPEATED_CODE_LENGTH;
     784        s->repeat = 0;
     785        s->repeat_code_len = 0;
     786        s->space = 32768;
     787        s->substate_huffman = BROTLI_STATE_HUFFMAN_LENGTH_SYMBOLS;
     788        /* No break, transit to the next state. */
     789      }
     790      case BROTLI_STATE_HUFFMAN_LENGTH_SYMBOLS: {
     791        uint32_t table_size;
     792        BrotliDecoderErrorCode result = ReadSymbolCodeLengths(alphabet_size, s);
     793        if (result == BROTLI_DECODER_NEEDS_MORE_INPUT) {
     794          result = SafeReadSymbolCodeLengths(alphabet_size, s);
     795        }
     796        if (result != BROTLI_DECODER_SUCCESS) {
     797          return result;
     798        }
     799
     800        if (s->space != 0) {
     801          BROTLI_LOG(("[ReadHuffmanCode] space = %d\n", s->space));
     802          return BROTLI_FAILURE(BROTLI_DECODER_ERROR_FORMAT_HUFFMAN_SPACE);
     803        }
     804        table_size = BrotliBuildHuffmanTable(
     805            table, HUFFMAN_TABLE_BITS, s->symbol_lists, s->code_length_histo);
     806        if (opt_table_size) {
     807          *opt_table_size = table_size;
     808        }
     809        s->substate_huffman = BROTLI_STATE_HUFFMAN_NONE;
     810        return BROTLI_DECODER_SUCCESS;
     811      }
     812
     813      default:
     814        return
     815            BROTLI_FAILURE(BROTLI_DECODER_ERROR_UNREACHABLE);
     816    }
    790817  }
    791818}
     
    803830/* WARNING: if state is not BROTLI_STATE_READ_BLOCK_LENGTH_NONE, then
    804831   reading can't be continued with ReadBlockLength. */
    805 static BROTLI_INLINE int SafeReadBlockLength(BrotliState* s,
    806                                              uint32_t* result,
    807                                              const HuffmanCode* table,
    808                                              BrotliBitReader* br) {
     832static BROTLI_INLINE BROTLI_BOOL SafeReadBlockLength(
     833    BrotliDecoderState* s, uint32_t* result, const HuffmanCode* table,
     834    BrotliBitReader* br) {
    809835  uint32_t index;
    810836  if (s->substate_read_block_length == BROTLI_STATE_READ_BLOCK_LENGTH_NONE) {
    811837    if (!SafeReadSymbol(table, br, &index)) {
    812       return 0;
     838      return BROTLI_FALSE;
    813839    }
    814840  } else {
     
    821847      s->block_length_index = index;
    822848      s->substate_read_block_length = BROTLI_STATE_READ_BLOCK_LENGTH_SUFFIX;
    823       return 0;
     849      return BROTLI_FALSE;
    824850    }
    825851    *result = kBlockLengthPrefixCode[index].offset + bits;
    826852    s->substate_read_block_length = BROTLI_STATE_READ_BLOCK_LENGTH_NONE;
    827     return 1;
     853    return BROTLI_TRUE;
    828854  }
    829855}
     
    844870   inner for loop with do-while.
    845871 */
    846 static BROTLI_NOINLINE void InverseMoveToFrontTransform(uint8_t* v,
    847     uint32_t v_len, BrotliState* state) {
     872static BROTLI_NOINLINE void InverseMoveToFrontTransform(
     873    uint8_t* v, uint32_t v_len, BrotliDecoderState* state) {
    848874  /* Reinitialize elements that could have been changed. */
    849   uint32_t i = 4;
     875  uint32_t i = 1;
    850876  uint32_t upper_bound = state->mtf_upper_bound;
    851   uint8_t* mtf = &state->mtf[4];  /* Make mtf[-1] addressable. */
     877  uint32_t* mtf = &state->mtf[1];  /* Make mtf[-1] addressable. */
     878  uint8_t* mtf_u8 = (uint8_t*)mtf;
    852879  /* Load endian-aware constant. */
    853880  const uint8_t b0123[4] = {0, 1, 2, 3};
     
    856883
    857884  /* Initialize list using 4 consequent values pattern. */
    858   *(uint32_t*)mtf = pattern;
     885  mtf[0] = pattern;
    859886  do {
    860887    pattern += 0x04040404; /* Advance all 4 values by 4. */
    861     *(uint32_t*)(mtf + i) = pattern;
    862     i += 4;
     888    mtf[i] = pattern;
     889    i++;
    863890  } while (i <= upper_bound);
    864891
     
    867894  for (i = 0; i < v_len; ++i) {
    868895    int index = v[i];
    869     uint8_t value = mtf[index];
     896    uint8_t value = mtf_u8[index];
    870897    upper_bound |= v[i];
    871898    v[i] = value;
    872     mtf[-1] = value;
     899    mtf_u8[-1] = value;
    873900    do {
    874901      index--;
    875       mtf[index + 1] = mtf[index];
     902      mtf_u8[index + 1] = mtf_u8[index];
    876903    } while (index >= 0);
    877904  }
    878905  /* Remember amount of elements to be reinitialized. */
    879   state->mtf_upper_bound = upper_bound;
     906  state->mtf_upper_bound = upper_bound >> 2;
    880907}
    881908
    882909/* Decodes a series of Huffman table using ReadHuffmanCode function. */
    883 static BrotliErrorCode HuffmanTreeGroupDecode(HuffmanTreeGroup* group,
    884                                               BrotliState* s) {
     910static BrotliDecoderErrorCode HuffmanTreeGroupDecode(
     911    HuffmanTreeGroup* group, BrotliDecoderState* s) {
    885912  if (s->substate_tree_group != BROTLI_STATE_TREE_GROUP_LOOP) {
    886913    s->next = group->codes;
     
    890917  while (s->htree_index < group->num_htrees) {
    891918    uint32_t table_size;
    892     BrotliErrorCode result =
     919    BrotliDecoderErrorCode result =
    893920        ReadHuffmanCode(group->alphabet_size, s->next, &table_size, s);
    894     if (result != BROTLI_SUCCESS) return result;
     921    if (result != BROTLI_DECODER_SUCCESS) return result;
    895922    group->htrees[s->htree_index] = s->next;
    896923    s->next += table_size;
     
    898925  }
    899926  s->substate_tree_group = BROTLI_STATE_TREE_GROUP_NONE;
    900   return BROTLI_SUCCESS;
     927  return BROTLI_DECODER_SUCCESS;
    901928}
    902929
     
    910937    4) Optionally, apply InverseMoveToFront transform to the resulting map.
    911938 */
    912 static BrotliErrorCode DecodeContextMap(uint32_t context_map_size,
    913                                         uint32_t* num_htrees,
    914                                         uint8_t** context_map_arg,
    915                                         BrotliState* s) {
     939static BrotliDecoderErrorCode DecodeContextMap(uint32_t context_map_size,
     940                                               uint32_t* num_htrees,
     941                                               uint8_t** context_map_arg,
     942                                               BrotliDecoderState* s) {
    916943  BrotliBitReader* br = &s->br;
    917   BrotliErrorCode result = BROTLI_SUCCESS;
     944  BrotliDecoderErrorCode result = BROTLI_DECODER_SUCCESS;
    918945
    919946  switch ((int)s->substate_context_map) {
    920947    case BROTLI_STATE_CONTEXT_MAP_NONE:
    921948      result = DecodeVarLenUint8(s, br, num_htrees);
    922       if (result != BROTLI_SUCCESS) {
     949      if (result != BROTLI_DECODER_SUCCESS) {
    923950        return result;
    924951      }
     
    929956      *context_map_arg = (uint8_t*)BROTLI_ALLOC(s, (size_t)context_map_size);
    930957      if (*context_map_arg == 0) {
    931         return BROTLI_FAILURE(BROTLI_ERROR_ALLOC_CONTEXT_MAP);
     958        return BROTLI_FAILURE(BROTLI_DECODER_ERROR_ALLOC_CONTEXT_MAP);
    932959      }
    933960      if (*num_htrees <= 1) {
    934961        memset(*context_map_arg, 0, (size_t)context_map_size);
    935         return BROTLI_SUCCESS;
     962        return BROTLI_DECODER_SUCCESS;
    936963      }
    937964      s->substate_context_map = BROTLI_STATE_CONTEXT_MAP_READ_PREFIX;
     
    942969         to peek 4 bits ahead. */
    943970      if (!BrotliSafeGetBits(br, 5, &bits)) {
    944         return BROTLI_NEEDS_MORE_INPUT;
    945       }
    946       if ((bits & 1) != 0) { /* Use RLE for zeroes. */
     971        return BROTLI_DECODER_NEEDS_MORE_INPUT;
     972      }
     973      if ((bits & 1) != 0) { /* Use RLE for zeros. */
    947974        s->max_run_length_prefix = (bits >> 1) + 1;
    948975        BrotliDropBits(br, 5);
     
    958985      result = ReadHuffmanCode(*num_htrees + s->max_run_length_prefix,
    959986                               s->context_map_table, NULL, s);
    960       if (result != BROTLI_SUCCESS) return result;
     987      if (result != BROTLI_DECODER_SUCCESS) return result;
    961988      s->code = 0xFFFF;
    962989      s->substate_context_map = BROTLI_STATE_CONTEXT_MAP_DECODE;
     
    967994      uint8_t* context_map = *context_map_arg;
    968995      uint32_t code = s->code;
    969       if (code != 0xFFFF) {
    970         goto rleCode;
    971       }
    972       while (context_index < context_map_size) {
    973         if (!SafeReadSymbol(s->context_map_table, br, &code)) {
    974           s->code = 0xFFFF;
    975           s->context_index = context_index;
    976           return BROTLI_NEEDS_MORE_INPUT;
    977         }
    978         BROTLI_LOG_UINT(code);
    979 
    980         if (code == 0) {
    981           context_map[context_index++] = 0;
    982           continue;
    983         }
    984         if (code > max_run_length_prefix) {
    985           context_map[context_index++] =
    986               (uint8_t)(code - max_run_length_prefix);
    987           continue;
    988         }
    989 rleCode:
     996      BROTLI_BOOL skip_preamble = (code != 0xFFFF);
     997      while (context_index < context_map_size || skip_preamble) {
     998        if (!skip_preamble) {
     999          if (!SafeReadSymbol(s->context_map_table, br, &code)) {
     1000            s->code = 0xFFFF;
     1001            s->context_index = context_index;
     1002            return BROTLI_DECODER_NEEDS_MORE_INPUT;
     1003          }
     1004          BROTLI_LOG_UINT(code);
     1005
     1006          if (code == 0) {
     1007            context_map[context_index++] = 0;
     1008            continue;
     1009          }
     1010          if (code > max_run_length_prefix) {
     1011            context_map[context_index++] =
     1012                (uint8_t)(code - max_run_length_prefix);
     1013            continue;
     1014          }
     1015        } else {
     1016          skip_preamble = BROTLI_FALSE;
     1017        }
     1018        /* RLE sub-stage. */
    9901019        {
    9911020          uint32_t reps;
     
    9931022            s->code = code;
    9941023            s->context_index = context_index;
    995             return BROTLI_NEEDS_MORE_INPUT;
     1024            return BROTLI_DECODER_NEEDS_MORE_INPUT;
    9961025          }
    9971026          reps += 1U << code;
    9981027          BROTLI_LOG_UINT(reps);
    9991028          if (context_index + reps > context_map_size) {
    1000             return BROTLI_FAILURE(BROTLI_ERROR_FORMAT_CONTEXT_MAP_REPEAT);
     1029            return
     1030                BROTLI_FAILURE(BROTLI_DECODER_ERROR_FORMAT_CONTEXT_MAP_REPEAT);
    10011031          }
    10021032          do {
     
    10111041      if (!BrotliSafeReadBits(br, 1, &bits)) {
    10121042        s->substate_context_map = BROTLI_STATE_CONTEXT_MAP_TRANSFORM;
    1013         return BROTLI_NEEDS_MORE_INPUT;
     1043        return BROTLI_DECODER_NEEDS_MORE_INPUT;
    10141044      }
    10151045      if (bits != 0) {
     
    10171047      }
    10181048      s->substate_context_map = BROTLI_STATE_CONTEXT_MAP_NONE;
    1019       return BROTLI_SUCCESS;
     1049      return BROTLI_DECODER_SUCCESS;
    10201050    }
    10211051    default:
    1022       return BROTLI_FAILURE(BROTLI_ERROR_UNREACHABLE);
    1023   }
    1024 }
    1025 
    1026 /* Decodes a command or literal and updates block type ringbuffer.
     1052      return
     1053          BROTLI_FAILURE(BROTLI_DECODER_ERROR_UNREACHABLE);
     1054  }
     1055}
     1056
     1057/* Decodes a command or literal and updates block type ring-buffer.
    10271058   Reads 3..54 bits. */
    1028 static BROTLI_INLINE int DecodeBlockTypeAndLength(int safe,
    1029     BrotliState* s, int tree_type) {
     1059static BROTLI_INLINE BROTLI_BOOL DecodeBlockTypeAndLength(
     1060    int safe, BrotliDecoderState* s, int tree_type) {
    10301061  uint32_t max_block_type = s->num_block_types[tree_type];
    10311062  const HuffmanCode* type_tree = &s->block_type_trees[
     
    10441075    BrotliBitReaderState memento;
    10451076    BrotliBitReaderSaveState(br, &memento);
    1046     if (!SafeReadSymbol(type_tree, br, &block_type)) return 0;
     1077    if (!SafeReadSymbol(type_tree, br, &block_type)) return BROTLI_FALSE;
    10471078    if (!SafeReadBlockLength(s, &s->block_length[tree_type], len_tree, br)) {
    10481079      s->substate_read_block_length = BROTLI_STATE_READ_BLOCK_LENGTH_NONE;
    10491080      BrotliBitReaderRestoreState(br, &memento);
    1050       return 0;
     1081      return BROTLI_FALSE;
    10511082    }
    10521083  }
     
    10641095  ringbuffer[0] = ringbuffer[1];
    10651096  ringbuffer[1] = block_type;
    1066   return 1;
    1067 }
    1068 
    1069 static BROTLI_INLINE void DetectTrivialLiteralBlockTypes(BrotliState* s) {
     1097  return BROTLI_TRUE;
     1098}
     1099
     1100static BROTLI_INLINE void DetectTrivialLiteralBlockTypes(
     1101    BrotliDecoderState* s) {
    10701102  size_t i;
    10711103  for (i = 0; i < 8; ++i) s->trivial_literal_contexts[i] = 0;
    10721104  for (i = 0; i < s->num_block_types[0]; i++) {
    1073     size_t offset = i << kLiteralContextBits;
     1105    size_t offset = i << BROTLI_LITERAL_CONTEXT_BITS;
    10741106    size_t error = 0;
    10751107    size_t sample = s->context_map[offset];
    10761108    size_t j;
    1077     for (j = 0; j < (1u << kLiteralContextBits);) {
     1109    for (j = 0; j < (1u << BROTLI_LITERAL_CONTEXT_BITS);) {
    10781110      BROTLI_REPEAT(4, error |= s->context_map[offset + j++] ^ sample;)
    10791111    }
     
    10841116}
    10851117
    1086 static BROTLI_INLINE void PrepareLiteralDecoding(BrotliState* s) {
     1118static BROTLI_INLINE void PrepareLiteralDecoding(BrotliDecoderState* s) {
    10871119  uint8_t context_mode;
    10881120  size_t trivial;
    10891121  uint32_t block_type = s->block_type_rb[1];
    1090   uint32_t context_offset = block_type << kLiteralContextBits;
     1122  uint32_t context_offset = block_type << BROTLI_LITERAL_CONTEXT_BITS;
    10911123  s->context_map_slice = s->context_map + context_offset;
    10921124  trivial = s->trivial_literal_contexts[block_type >> 5];
     
    11001132/* Decodes the block type and updates the state for literal context.
    11011133   Reads 3..54 bits. */
    1102 static BROTLI_INLINE int DecodeLiteralBlockSwitchInternal(int safe,
    1103     BrotliState* s) {
     1134static BROTLI_INLINE BROTLI_BOOL DecodeLiteralBlockSwitchInternal(
     1135    int safe, BrotliDecoderState* s) {
    11041136  if (!DecodeBlockTypeAndLength(safe, s, 0)) {
    1105     return 0;
     1137    return BROTLI_FALSE;
    11061138  }
    11071139  PrepareLiteralDecoding(s);
    1108   return 1;
    1109 }
    1110 
    1111 static void BROTLI_NOINLINE DecodeLiteralBlockSwitch(BrotliState* s) {
     1140  return BROTLI_TRUE;
     1141}
     1142
     1143static void BROTLI_NOINLINE DecodeLiteralBlockSwitch(BrotliDecoderState* s) {
    11121144  DecodeLiteralBlockSwitchInternal(0, s);
    11131145}
    11141146
    1115 static int BROTLI_NOINLINE SafeDecodeLiteralBlockSwitch(BrotliState* s) {
     1147static BROTLI_BOOL BROTLI_NOINLINE SafeDecodeLiteralBlockSwitch(
     1148    BrotliDecoderState* s) {
    11161149  return DecodeLiteralBlockSwitchInternal(1, s);
    11171150}
     
    11191152/* Block switch for insert/copy length.
    11201153   Reads 3..54 bits. */
    1121 static BROTLI_INLINE int DecodeCommandBlockSwitchInternal(int safe,
    1122     BrotliState* s) {
     1154static BROTLI_INLINE BROTLI_BOOL DecodeCommandBlockSwitchInternal(
     1155    int safe, BrotliDecoderState* s) {
    11231156  if (!DecodeBlockTypeAndLength(safe, s, 1)) {
    1124     return 0;
     1157    return BROTLI_FALSE;
    11251158  }
    11261159  s->htree_command = s->insert_copy_hgroup.htrees[s->block_type_rb[3]];
    1127   return 1;
    1128 }
    1129 
    1130 static void BROTLI_NOINLINE DecodeCommandBlockSwitch(BrotliState* s) {
     1160  return BROTLI_TRUE;
     1161}
     1162
     1163static void BROTLI_NOINLINE DecodeCommandBlockSwitch(BrotliDecoderState* s) {
    11311164  DecodeCommandBlockSwitchInternal(0, s);
    11321165}
    1133 static int BROTLI_NOINLINE SafeDecodeCommandBlockSwitch(BrotliState* s) {
     1166static BROTLI_BOOL BROTLI_NOINLINE SafeDecodeCommandBlockSwitch(
     1167    BrotliDecoderState* s) {
    11341168  return DecodeCommandBlockSwitchInternal(1, s);
    11351169}
     
    11371171/* Block switch for distance codes.
    11381172   Reads 3..54 bits. */
    1139 static BROTLI_INLINE int DecodeDistanceBlockSwitchInternal(int safe,
    1140     BrotliState* s) {
     1173static BROTLI_INLINE BROTLI_BOOL DecodeDistanceBlockSwitchInternal(
     1174    int safe, BrotliDecoderState* s) {
    11411175  if (!DecodeBlockTypeAndLength(safe, s, 2)) {
    1142     return 0;
    1143   }
    1144   s->dist_context_map_slice =
    1145       s->dist_context_map + (s->block_type_rb[5] << kDistanceContextBits);
     1176    return BROTLI_FALSE;
     1177  }
     1178  s->dist_context_map_slice = s->dist_context_map +
     1179      (s->block_type_rb[5] << BROTLI_DISTANCE_CONTEXT_BITS);
    11461180  s->dist_htree_index = s->dist_context_map_slice[s->distance_context];
    1147   return 1;
    1148 }
    1149 
    1150 static void BROTLI_NOINLINE DecodeDistanceBlockSwitch(BrotliState* s) {
     1181  return BROTLI_TRUE;
     1182}
     1183
     1184static void BROTLI_NOINLINE DecodeDistanceBlockSwitch(BrotliDecoderState* s) {
    11511185  DecodeDistanceBlockSwitchInternal(0, s);
    11521186}
    11531187
    1154 static int BROTLI_NOINLINE SafeDecodeDistanceBlockSwitch(BrotliState* s) {
     1188static BROTLI_BOOL BROTLI_NOINLINE SafeDecodeDistanceBlockSwitch(
     1189    BrotliDecoderState* s) {
    11551190  return DecodeDistanceBlockSwitchInternal(1, s);
    11561191}
    11571192
    1158 static BrotliErrorCode BROTLI_NOINLINE WriteRingBuffer(size_t* available_out,
    1159     uint8_t** next_out, size_t* total_out, BrotliState* s) {
    1160   size_t pos = (s->pos > s->ringbuffer_size) ? (size_t)s->ringbuffer_size
    1161                                              : (size_t)(s->pos);
     1193static size_t UnwrittenBytes(const BrotliDecoderState* s, BROTLI_BOOL wrap) {
     1194  size_t pos = wrap && s->pos > s->ringbuffer_size ?
     1195      (size_t)s->ringbuffer_size : (size_t)(s->pos);
     1196  size_t partial_pos_rb = (s->rb_roundtrips * (size_t)s->ringbuffer_size) + pos;
     1197  return partial_pos_rb - s->partial_pos_out;
     1198}
     1199
     1200/* Dumps output.
     1201   Returns BROTLI_DECODER_NEEDS_MORE_OUTPUT only if there is more output to push
     1202   and either ring-buffer is as big as window size, or |force| is true.
     1203 */
     1204static BrotliDecoderErrorCode BROTLI_NOINLINE WriteRingBuffer(
     1205    BrotliDecoderState* s, size_t* available_out, uint8_t** next_out,
     1206    size_t* total_out, BROTLI_BOOL force) {
    11621207  uint8_t* start =
    11631208      s->ringbuffer + (s->partial_pos_out & (size_t)s->ringbuffer_mask);
    1164   size_t partial_pos_rb = (s->rb_roundtrips * (size_t)s->ringbuffer_size) + pos;
    1165   size_t to_write = (partial_pos_rb - s->partial_pos_out);
     1209  size_t to_write = UnwrittenBytes(s, BROTLI_TRUE);
    11661210  size_t num_written = *available_out;
    11671211  if (num_written > to_write) {
     
    11691213  }
    11701214  if (s->meta_block_remaining_len < 0) {
    1171     return BROTLI_FAILURE(BROTLI_ERROR_FORMAT_BLOCK_LENGTH_1);
    1172   }
    1173   memcpy(*next_out, start, num_written);
    1174   *next_out += num_written;
     1215    return BROTLI_FAILURE(BROTLI_DECODER_ERROR_FORMAT_BLOCK_LENGTH_1);
     1216  }
     1217  if (next_out && !*next_out) {
     1218    *next_out = start;
     1219  } else {
     1220    if (next_out) {
     1221      memcpy(*next_out, start, num_written);
     1222      *next_out += num_written;
     1223    }
     1224  }
    11751225  *available_out -= num_written;
    11761226  BROTLI_LOG_UINT(to_write);
    11771227  BROTLI_LOG_UINT(num_written);
    11781228  s->partial_pos_out += num_written;
    1179   if (total_out) *total_out = s->partial_pos_out;
     1229  if (total_out) {
     1230    *total_out = s->partial_pos_out;
     1231  }
    11801232  if (num_written < to_write) {
    1181     return BROTLI_NEEDS_MORE_OUTPUT;
    1182   }
    1183 
    1184   if (s->pos >= s->ringbuffer_size) {
     1233    if (s->ringbuffer_size == (1 << s->window_bits) || force) {
     1234      return BROTLI_DECODER_NEEDS_MORE_OUTPUT;
     1235    } else {
     1236      return BROTLI_DECODER_SUCCESS;
     1237    }
     1238  }
     1239  /* Wrap ring buffer only if it has reached its maximal size. */
     1240  if (s->ringbuffer_size == (1 << s->window_bits) &&
     1241      s->pos >= s->ringbuffer_size) {
    11851242    s->pos -= s->ringbuffer_size;
    11861243    s->rb_roundtrips++;
    1187   }
    1188   return BROTLI_SUCCESS;
    1189 }
    1190 
    1191 /* Allocates ringbuffer.
    1192 
    1193   s->ringbuffer_size MUST be updated by BrotliCalculateRingBufferSize before
    1194   this function is called.
    1195 
    1196    Last two bytes of ringbuffer are initialized to 0, so context calculation
     1244    s->should_wrap_ringbuffer = (size_t)s->pos != 0 ? 1 : 0;
     1245  }
     1246  return BROTLI_DECODER_SUCCESS;
     1247}
     1248
     1249static void BROTLI_NOINLINE WrapRingBuffer(BrotliDecoderState* s) {
     1250  if (s->should_wrap_ringbuffer) {
     1251    memcpy(s->ringbuffer, s->ringbuffer_end, (size_t)s->pos);
     1252    s->should_wrap_ringbuffer = 0;
     1253  }
     1254}
     1255
     1256/* Allocates ring-buffer.
     1257
     1258   s->ringbuffer_size MUST be updated by BrotliCalculateRingBufferSize before
     1259   this function is called.
     1260
     1261   Last two bytes of ring-buffer are initialized to 0, so context calculation
    11971262   could be done uniformly for the first two and all other positions.
    1198 
    1199    Custom dictionary, if any, is copied to the end of ringbuffer.
    12001263*/
    1201 static int BROTLI_NOINLINE BrotliAllocateRingBuffer(BrotliState* s) {
    1202   /* We need the slack region for the following reasons:
    1203       - doing up to two 16-byte copies for fast backward copying
    1204       - inserting transformed dictionary word (5 prefix + 24 base + 8 suffix) */
    1205   static const int kRingBufferWriteAheadSlack = 42;
    1206   s->ringbuffer = (uint8_t*)BROTLI_ALLOC(s, (size_t)(s->ringbuffer_size +
    1207       kRingBufferWriteAheadSlack));
     1264static BROTLI_BOOL BROTLI_NOINLINE BrotliEnsureRingBuffer(
     1265    BrotliDecoderState* s) {
     1266  uint8_t* old_ringbuffer = s->ringbuffer;
     1267  if (s->ringbuffer_size == s->new_ringbuffer_size) {
     1268    return BROTLI_TRUE;
     1269  }
     1270
     1271  s->ringbuffer = (uint8_t*)BROTLI_ALLOC(s, (size_t)(s->new_ringbuffer_size) +
     1272      kRingBufferWriteAheadSlack);
    12081273  if (s->ringbuffer == 0) {
    1209     return 0;
    1210   }
    1211 
     1274    /* Restore previous value. */
     1275    s->ringbuffer = old_ringbuffer;
     1276    return BROTLI_FALSE;
     1277  }
     1278  s->ringbuffer[s->new_ringbuffer_size - 2] = 0;
     1279  s->ringbuffer[s->new_ringbuffer_size - 1] = 0;
     1280
     1281  if (!!old_ringbuffer) {
     1282    memcpy(s->ringbuffer, old_ringbuffer, (size_t)s->pos);
     1283    BROTLI_FREE(s, old_ringbuffer);
     1284  }
     1285
     1286  s->ringbuffer_size = s->new_ringbuffer_size;
     1287  s->ringbuffer_mask = s->new_ringbuffer_size - 1;
    12121288  s->ringbuffer_end = s->ringbuffer + s->ringbuffer_size;
    12131289
    1214   s->ringbuffer[s->ringbuffer_size - 2] = 0;
    1215   s->ringbuffer[s->ringbuffer_size - 1] = 0;
    1216 
    1217   if (s->custom_dict) {
    1218     memcpy(&s->ringbuffer[(-s->custom_dict_size) & s->ringbuffer_mask],
    1219            s->custom_dict, (size_t)s->custom_dict_size);
    1220   }
    1221 
    1222   return 1;
    1223 }
    1224 
    1225 static BrotliErrorCode BROTLI_NOINLINE CopyUncompressedBlockToOutput(
     1290  return BROTLI_TRUE;
     1291}
     1292
     1293static BrotliDecoderErrorCode BROTLI_NOINLINE CopyUncompressedBlockToOutput(
    12261294    size_t* available_out, uint8_t** next_out, size_t* total_out,
    1227     BrotliState* s) {
     1295    BrotliDecoderState* s) {
    12281296  /* TODO: avoid allocation for single uncompressed block. */
    1229   if (!s->ringbuffer && !BrotliAllocateRingBuffer(s)) {
    1230     return BROTLI_FAILURE(BROTLI_ERROR_ALLOC_RING_BUFFER_1);
     1297  if (!BrotliEnsureRingBuffer(s)) {
     1298    return BROTLI_FAILURE(BROTLI_DECODER_ERROR_ALLOC_RING_BUFFER_1);
    12311299  }
    12321300
     
    12421310          nbytes = s->ringbuffer_size - s->pos;
    12431311        }
    1244         /* Copy remaining bytes from s->br.buf_ to ringbuffer. */
     1312        /* Copy remaining bytes from s->br.buf_ to ring-buffer. */
    12451313        BrotliCopyBytes(&s->ringbuffer[s->pos], &s->br, (size_t)nbytes);
    12461314        s->pos += nbytes;
    12471315        s->meta_block_remaining_len -= nbytes;
    1248         if (s->pos < s->ringbuffer_size) {
     1316        if (s->pos < 1 << s->window_bits) {
    12491317          if (s->meta_block_remaining_len == 0) {
    1250             return BROTLI_SUCCESS;
     1318            return BROTLI_DECODER_SUCCESS;
    12511319          }
    1252           return BROTLI_NEEDS_MORE_INPUT;
     1320          return BROTLI_DECODER_NEEDS_MORE_INPUT;
    12531321        }
    12541322        s->substate_uncompressed = BROTLI_STATE_UNCOMPRESSED_WRITE;
     
    12561324      }
    12571325      case BROTLI_STATE_UNCOMPRESSED_WRITE: {
    1258         BrotliErrorCode result =
    1259             WriteRingBuffer(available_out, next_out, total_out, s);
    1260         if (result != BROTLI_SUCCESS) {
     1326        BrotliDecoderErrorCode result;
     1327        result = WriteRingBuffer(
     1328            s, available_out, next_out, total_out, BROTLI_FALSE);
     1329        if (result != BROTLI_DECODER_SUCCESS) {
    12611330          return result;
    12621331        }
    1263         s->max_distance = s->max_backward_distance;
     1332        if (s->ringbuffer_size == 1 << s->window_bits) {
     1333          s->max_distance = s->max_backward_distance;
     1334        }
    12641335        s->substate_uncompressed = BROTLI_STATE_UNCOMPRESSED_NONE;
    12651336        break;
     
    12701341}
    12711342
    1272 int BrotliDecompressedSize(size_t encoded_size,
    1273                            const uint8_t* encoded_buffer,
    1274                            size_t* decoded_size) {
    1275   BrotliState s;
    1276   int next_block_header;
    1277   BrotliStateInit(&s);
    1278   s.br.next_in = encoded_buffer;
    1279   s.br.avail_in = encoded_size;
    1280   if (!BrotliWarmupBitReader(&s.br)) {
    1281     return 0;
    1282   }
    1283   DecodeWindowBits(&s.br);
    1284   if (DecodeMetaBlockLength(&s, &s.br) != BROTLI_SUCCESS) {
    1285     return 0;
    1286   }
    1287   *decoded_size = (size_t)s.meta_block_remaining_len;
    1288   if (s.is_last_metablock) {
    1289     return 1;
    1290   }
    1291   if (!s.is_uncompressed || !BrotliJumpToByteBoundary(&s.br)) {
    1292     return 0;
    1293   }
    1294   next_block_header = BrotliPeekByte(&s.br, (size_t)s.meta_block_remaining_len);
    1295   return (next_block_header != -1) && ((next_block_header & 3) == 3);
    1296 }
    1297 
    12981343/* Calculates the smallest feasible ring buffer.
    12991344
    1300    If we know the data size is small, do not allocate more ringbuffer
     1345   If we know the data size is small, do not allocate more ring buffer
    13011346   size than needed to reduce memory usage.
    13021347
    13031348   When this method is called, metablock size and flags MUST be decoded.
    13041349*/
    1305 static void BROTLI_NOINLINE BrotliCalculateRingBufferSize(BrotliState* s,
    1306     BrotliBitReader* br) {
    1307   int is_last = s->is_last_metablock;
     1350static void BROTLI_NOINLINE BrotliCalculateRingBufferSize(
     1351    BrotliDecoderState* s) {
    13081352  int window_size = 1 << s->window_bits;
    1309   s->ringbuffer_size = window_size;
    1310 
    1311   if (s->is_uncompressed) {
    1312     int next_block_header =
    1313         BrotliPeekByte(br, (size_t)s->meta_block_remaining_len);
    1314     if (next_block_header != -1) {  /* Peek succeeded */
    1315       if ((next_block_header & 3) == 3) {  /* ISLAST and ISEMPTY */
    1316         is_last = 1;
    1317       }
    1318     }
    1319   }
    1320 
     1353  int new_ringbuffer_size = window_size;
    13211354  /* We need at least 2 bytes of ring buffer size to get the last two
    13221355     bytes for context from there */
    1323   if (is_last) {
    1324     int min_size_x2 = (s->meta_block_remaining_len + s->custom_dict_size) * 2;
    1325     while (s->ringbuffer_size >= min_size_x2 && s->ringbuffer_size > 32) {
    1326       s->ringbuffer_size >>= 1;
    1327     }
    1328   }
    1329 
    1330   s->ringbuffer_mask = s->ringbuffer_size - 1;
     1356  int min_size = s->ringbuffer_size ? s->ringbuffer_size : 1024;
     1357  int output_size;
     1358
     1359  /* If maximum is already reached, no further extension is retired. */
     1360  if (s->ringbuffer_size == window_size) {
     1361    return;
     1362  }
     1363
     1364  /* Metadata blocks does not touch ring buffer. */
     1365  if (s->is_metadata) {
     1366    return;
     1367  }
     1368
     1369  if (!s->ringbuffer) {
     1370    output_size = 0;
     1371  } else {
     1372    output_size = s->pos;
     1373  }
     1374  output_size += s->meta_block_remaining_len;
     1375  min_size = min_size < output_size ? output_size : min_size;
     1376
     1377  if (!!s->canny_ringbuffer_allocation) {
     1378    /* Reduce ring buffer size to save memory when server is unscrupulous.
     1379       In worst case memory usage might be 1.5x bigger for a short period of
     1380       ring buffer reallocation.*/
     1381    while ((new_ringbuffer_size >> 1) >= min_size) {
     1382      new_ringbuffer_size >>= 1;
     1383    }
     1384  }
     1385
     1386  s->new_ringbuffer_size = new_ringbuffer_size;
    13311387}
    13321388
    13331389/* Reads 1..256 2-bit context modes. */
    1334 static BrotliErrorCode ReadContextModes(BrotliState* s) {
     1390static BrotliDecoderErrorCode ReadContextModes(BrotliDecoderState* s) {
    13351391  BrotliBitReader* br = &s->br;
    13361392  int i = s->loop_counter;
     
    13401396    if (!BrotliSafeReadBits(br, 2, &bits)) {
    13411397      s->loop_counter = i;
    1342       return BROTLI_NEEDS_MORE_INPUT;
     1398      return BROTLI_DECODER_NEEDS_MORE_INPUT;
    13431399    }
    13441400    s->context_modes[i] = (uint8_t)(bits << 1);
     
    13461402    i++;
    13471403  }
    1348   return BROTLI_SUCCESS;
    1349 }
    1350 
    1351 static BROTLI_INLINE void TakeDistanceFromRingBuffer(BrotliState* s) {
     1404  return BROTLI_DECODER_SUCCESS;
     1405}
     1406
     1407static BROTLI_INLINE void TakeDistanceFromRingBuffer(BrotliDecoderState* s) {
    13521408  if (s->distance_code == 0) {
    13531409    --s->dist_rb_idx;
    13541410    s->distance_code = s->dist_rb[s->dist_rb_idx & 3];
     1411    /* Compensate double distance-ring-buffer roll for dictionary items. */
     1412    s->distance_context = 1;
    13551413  } else {
    13561414    int distance_code = s->distance_code << 1;
     
    13781436}
    13791437
    1380 static BROTLI_INLINE int SafeReadBits(
     1438static BROTLI_INLINE BROTLI_BOOL SafeReadBits(
    13811439    BrotliBitReader* const br, uint32_t n_bits, uint32_t* val) {
    13821440  if (n_bits != 0) {
     
    13841442  } else {
    13851443    *val = 0;
    1386     return 1;
     1444    return BROTLI_TRUE;
    13871445  }
    13881446}
    13891447
    13901448/* Precondition: s->distance_code < 0 */
    1391 static BROTLI_INLINE int ReadDistanceInternal(int safe,
    1392     BrotliState* s, BrotliBitReader* br) {
     1449static BROTLI_INLINE BROTLI_BOOL ReadDistanceInternal(
     1450    int safe, BrotliDecoderState* s, BrotliBitReader* br) {
    13931451  int distval;
    13941452  BrotliBitReaderState memento;
     
    14001458    BrotliBitReaderSaveState(br, &memento);
    14011459    if (!SafeReadSymbol(distance_tree, br, &code)) {
    1402       return 0;
     1460      return BROTLI_FALSE;
    14031461    }
    14041462    s->distance_code = (int)code;
     
    14061464  /* Convert the distance code to the actual distance by possibly */
    14071465  /* looking up past distances from the s->ringbuffer. */
     1466  s->distance_context = 0;
    14081467  if ((s->distance_code & ~0xf) == 0) {
    14091468    TakeDistanceFromRingBuffer(s);
    14101469    --s->block_length[2];
    1411     return 1;
     1470    return BROTLI_TRUE;
    14121471  }
    14131472  distval = s->distance_code - (int)s->num_direct_distance_codes;
     
    14311490          s->distance_code = -1; /* Restore precondition. */
    14321491          BrotliBitReaderRestoreState(br, &memento);
    1433           return 0;
     1492          return BROTLI_FALSE;
    14341493        }
    14351494      } else {
     
    14411500    }
    14421501  }
    1443   s->distance_code = s->distance_code - NUM_DISTANCE_SHORT_CODES + 1;
     1502  s->distance_code = s->distance_code - BROTLI_NUM_DISTANCE_SHORT_CODES + 1;
    14441503  --s->block_length[2];
    1445   return 1;
    1446 }
    1447 
    1448 static BROTLI_INLINE void ReadDistance(BrotliState* s, BrotliBitReader* br) {
     1504  return BROTLI_TRUE;
     1505}
     1506
     1507static BROTLI_INLINE void ReadDistance(
     1508    BrotliDecoderState* s, BrotliBitReader* br) {
    14491509  ReadDistanceInternal(0, s, br);
    14501510}
    14511511
    1452 static BROTLI_INLINE int SafeReadDistance(BrotliState* s, BrotliBitReader* br) {
     1512static BROTLI_INLINE BROTLI_BOOL SafeReadDistance(
     1513    BrotliDecoderState* s, BrotliBitReader* br) {
    14531514  return ReadDistanceInternal(1, s, br);
    14541515}
    14551516
    1456 static BROTLI_INLINE int ReadCommandInternal(int safe,
    1457     BrotliState* s, BrotliBitReader* br, int* insert_length) {
     1517static BROTLI_INLINE BROTLI_BOOL ReadCommandInternal(
     1518    int safe, BrotliDecoderState* s, BrotliBitReader* br, int* insert_length) {
    14581519  uint32_t cmd_code;
    14591520  uint32_t insert_len_extra = 0;
     
    14661527    BrotliBitReaderSaveState(br, &memento);
    14671528    if (!SafeReadSymbol(s->htree_command, br, &cmd_code)) {
    1468       return 0;
     1529      return BROTLI_FALSE;
    14691530    }
    14701531  }
     
    14751536  *insert_length = v.insert_len_offset;
    14761537  if (!safe) {
    1477     if (PREDICT_FALSE(v.insert_len_extra_bits != 0)) {
     1538    if (BROTLI_PREDICT_FALSE(v.insert_len_extra_bits != 0)) {
    14781539      insert_len_extra = BrotliReadBits(br, v.insert_len_extra_bits);
    14791540    }
     
    14831544        !SafeReadBits(br, v.copy_len_extra_bits, &copy_length)) {
    14841545      BrotliBitReaderRestoreState(br, &memento);
    1485       return 0;
     1546      return BROTLI_FALSE;
    14861547    }
    14871548  }
     
    14891550  --s->block_length[1];
    14901551  *insert_length += (int)insert_len_extra;
    1491   return 1;
    1492 }
    1493 
    1494 static BROTLI_INLINE void ReadCommand(BrotliState* s, BrotliBitReader* br,
    1495     int* insert_length) {
     1552  return BROTLI_TRUE;
     1553}
     1554
     1555static BROTLI_INLINE void ReadCommand(
     1556    BrotliDecoderState* s, BrotliBitReader* br, int* insert_length) {
    14961557  ReadCommandInternal(0, s, br, insert_length);
    14971558}
    14981559
    1499 static BROTLI_INLINE int SafeReadCommand(BrotliState* s, BrotliBitReader* br,
    1500     int* insert_length) {
     1560static BROTLI_INLINE BROTLI_BOOL SafeReadCommand(
     1561    BrotliDecoderState* s, BrotliBitReader* br, int* insert_length) {
    15011562  return ReadCommandInternal(1, s, br, insert_length);
    15021563}
    15031564
    1504 static BROTLI_INLINE int CheckInputAmount(int safe,
    1505     BrotliBitReader* const br, size_t num) {
     1565static BROTLI_INLINE BROTLI_BOOL CheckInputAmount(
     1566    int safe, BrotliBitReader* const br, size_t num) {
    15061567  if (safe) {
    1507     return 1;
     1568    return BROTLI_TRUE;
    15081569  }
    15091570  return BrotliCheckInputAmount(br, num);
    15101571}
    15111572
    1512 #define BROTLI_SAFE(METHOD)               \
    1513   {                                       \
    1514     if (safe) {                           \
    1515       if (!Safe##METHOD) {                \
    1516         result = BROTLI_NEEDS_MORE_INPUT; \
    1517         goto saveStateAndReturn;          \
    1518       }                                   \
    1519     } else {                              \
    1520       METHOD;                             \
    1521     }                                     \
    1522   }
    1523 
    1524 static BROTLI_INLINE BrotliErrorCode ProcessCommandsInternal(int safe,
    1525     BrotliState* s) {
     1573#define BROTLI_SAFE(METHOD)                       \
     1574  {                                               \
     1575    if (safe) {                                   \
     1576      if (!Safe##METHOD) {                        \
     1577        result = BROTLI_DECODER_NEEDS_MORE_INPUT; \
     1578        goto saveStateAndReturn;                  \
     1579      }                                           \
     1580    } else {                                      \
     1581      METHOD;                                     \
     1582    }                                             \
     1583  }
     1584
     1585static BROTLI_INLINE BrotliDecoderErrorCode ProcessCommandsInternal(
     1586    int safe, BrotliDecoderState* s) {
    15261587  int pos = s->pos;
    15271588  int i = s->loop_counter;
    1528   BrotliErrorCode result = BROTLI_SUCCESS;
     1589  BrotliDecoderErrorCode result = BROTLI_DECODER_SUCCESS;
    15291590  BrotliBitReader* br = &s->br;
    15301591
    15311592  if (!CheckInputAmount(safe, br, 28)) {
    1532     result = BROTLI_NEEDS_MORE_INPUT;
     1593    result = BROTLI_DECODER_NEEDS_MORE_INPUT;
    15331594    goto saveStateAndReturn;
    15341595  }
     
    15471608    goto CommandPostWrapCopy;
    15481609  } else {
    1549     return BROTLI_FAILURE(BROTLI_ERROR_UNREACHABLE);
     1610    return BROTLI_FAILURE(BROTLI_DECODER_ERROR_UNREACHABLE);
    15501611  }
    15511612
     
    15561617  if (!CheckInputAmount(safe, br, 28)) { /* 156 bits + 7 bytes */
    15571618    s->state = BROTLI_STATE_COMMAND_BEGIN;
    1558     result = BROTLI_NEEDS_MORE_INPUT;
     1619    result = BROTLI_DECODER_NEEDS_MORE_INPUT;
    15591620    goto saveStateAndReturn;
    15601621  }
    1561   if (PREDICT_FALSE(s->block_length[1] == 0)) {
     1622  if (BROTLI_PREDICT_FALSE(s->block_length[1] == 0)) {
    15621623    BROTLI_SAFE(DecodeCommandBlockSwitch(s));
    15631624    goto CommandBegin;
     
    15841645      if (!CheckInputAmount(safe, br, 28)) { /* 162 bits + 7 bytes */
    15851646        s->state = BROTLI_STATE_COMMAND_INNER;
    1586         result = BROTLI_NEEDS_MORE_INPUT;
     1647        result = BROTLI_DECODER_NEEDS_MORE_INPUT;
    15871648        goto saveStateAndReturn;
    15881649      }
    1589       if (PREDICT_FALSE(s->block_length[0] == 0)) {
     1650      if (BROTLI_PREDICT_FALSE(s->block_length[0] == 0)) {
    15901651        BROTLI_SAFE(DecodeLiteralBlockSwitch(s));
    15911652        PreloadSymbol(safe, s->literal_htree, br, &bits, &value);
     
    15981659        uint32_t literal;
    15991660        if (!SafeReadSymbol(s->literal_htree, br, &literal)) {
    1600           result = BROTLI_NEEDS_MORE_INPUT;
     1661          result = BROTLI_DECODER_NEEDS_MORE_INPUT;
    16011662          goto saveStateAndReturn;
    16021663        }
     
    16061667      BROTLI_LOG_ARRAY_INDEX(s->ringbuffer, pos);
    16071668      ++pos;
    1608       if (PREDICT_FALSE(pos == s->ringbuffer_size)) {
     1669      if (BROTLI_PREDICT_FALSE(pos == s->ringbuffer_size)) {
    16091670        s->state = BROTLI_STATE_COMMAND_INNER_WRITE;
    16101671        --i;
     
    16201681      if (!CheckInputAmount(safe, br, 28)) { /* 162 bits + 7 bytes */
    16211682        s->state = BROTLI_STATE_COMMAND_INNER;
    1622         result = BROTLI_NEEDS_MORE_INPUT;
     1683        result = BROTLI_DECODER_NEEDS_MORE_INPUT;
    16231684        goto saveStateAndReturn;
    16241685      }
    1625       if (PREDICT_FALSE(s->block_length[0] == 0)) {
     1686      if (BROTLI_PREDICT_FALSE(s->block_length[0] == 0)) {
    16261687        BROTLI_SAFE(DecodeLiteralBlockSwitch(s));
    16271688        if (s->trivial_literal_context) goto CommandInner;
     
    16361697        uint32_t literal;
    16371698        if (!SafeReadSymbol(hc, br, &literal)) {
    1638           result = BROTLI_NEEDS_MORE_INPUT;
     1699          result = BROTLI_DECODER_NEEDS_MORE_INPUT;
    16391700          goto saveStateAndReturn;
    16401701        }
     
    16461707      BROTLI_LOG_ARRAY_INDEX(s->ringbuffer, pos & s->ringbuffer_mask);
    16471708      ++pos;
    1648       if (PREDICT_FALSE(pos == s->ringbuffer_size)) {
     1709      if (BROTLI_PREDICT_FALSE(pos == s->ringbuffer_size)) {
    16491710        s->state = BROTLI_STATE_COMMAND_INNER_WRITE;
    16501711        --i;
     
    16541715  }
    16551716  BROTLI_LOG_UINT(s->meta_block_remaining_len);
    1656   if (PREDICT_FALSE(s->meta_block_remaining_len <= 0)) {
     1717  if (BROTLI_PREDICT_FALSE(s->meta_block_remaining_len <= 0)) {
    16571718    s->state = BROTLI_STATE_METABLOCK_DONE;
    16581719    goto saveStateAndReturn;
     
    16641725  }
    16651726  if (s->distance_code >= 0) {
     1727    /* Implicit distance case. */
     1728    s->distance_context = s->distance_code ? 0 : 1;
    16661729    --s->dist_rb_idx;
    16671730    s->distance_code = s->dist_rb[s->dist_rb_idx & 3];
    1668     goto postReadDistance;  /* We already have the implicit distance */
    1669   }
    1670   /* Read distance code in the command, unless it was implicitly zero. */
    1671   if (PREDICT_FALSE(s->block_length[2] == 0)) {
    1672     BROTLI_SAFE(DecodeDistanceBlockSwitch(s));
    1673   }
    1674   BROTLI_SAFE(ReadDistance(s, br));
    1675 postReadDistance:
     1731  } else {
     1732    /* Read distance code in the command, unless it was implicitly zero. */
     1733    if (BROTLI_PREDICT_FALSE(s->block_length[2] == 0)) {
     1734      BROTLI_SAFE(DecodeDistanceBlockSwitch(s));
     1735    }
     1736    BROTLI_SAFE(ReadDistance(s, br));
     1737  }
    16761738  BROTLI_LOG(("[ProcessCommandsInternal] pos = %d distance = %d\n",
    16771739              pos, s->distance_code));
    16781740  if (s->max_distance != s->max_backward_distance) {
    1679     if (pos < s->max_backward_distance_minus_custom_dict_size) {
    1680       s->max_distance = pos + s->custom_dict_size;
    1681     } else {
    1682       s->max_distance = s->max_backward_distance;
    1683     }
     1741    s->max_distance =
     1742        (pos < s->max_backward_distance) ? pos : s->max_backward_distance;
    16841743  }
    16851744  i = s->copy_length;
     
    16871746  the distance is larger than the max LZ77 distance */
    16881747  if (s->distance_code > s->max_distance) {
    1689     if (i >= kBrotliMinDictionaryWordLength &&
    1690         i <= kBrotliMaxDictionaryWordLength) {
    1691       int offset = (int)kBrotliDictionaryOffsetsByLength[i];
    1692       int word_id = s->distance_code - s->max_distance - 1;
    1693       uint32_t shift = kBrotliDictionarySizeBitsByLength[i];
     1748    int address = s->distance_code - s->max_distance - 1;
     1749    if (i >= BROTLI_MIN_DICTIONARY_WORD_LENGTH &&
     1750        i <= BROTLI_MAX_DICTIONARY_WORD_LENGTH) {
     1751      int offset = (int)s->dictionary->offsets_by_length[i];
     1752      uint32_t shift = s->dictionary->size_bits_by_length[i];
    16941753      int mask = (int)BitMask(shift);
    1695       int word_idx = word_id & mask;
    1696       int transform_idx = word_id >> shift;
     1754      int word_idx = address & mask;
     1755      int transform_idx = address >> shift;
     1756      /* Compensate double distance-ring-buffer roll. */
     1757      s->dist_rb_idx += s->distance_context;
    16971758      offset += word_idx * i;
     1759      if (BROTLI_PREDICT_FALSE(!s->dictionary->data)) {
     1760        return BROTLI_FAILURE(BROTLI_DECODER_ERROR_DICTIONARY_NOT_SET);
     1761      }
    16981762      if (transform_idx < kNumTransforms) {
    1699         const uint8_t* word = &kBrotliDictionary[offset];
     1763        const uint8_t* word = &s->dictionary->data[offset];
    17001764        int len = i;
    17011765        if (transform_idx == 0) {
    17021766          memcpy(&s->ringbuffer[pos], word, (size_t)len);
     1767          BROTLI_LOG(("[ProcessCommandsInternal] dictionary word: [%.*s]\n",
     1768                      len, word));
    17031769        } else {
    17041770          len = TransformDictionaryWord(
    17051771              &s->ringbuffer[pos], word, len, transform_idx);
     1772          BROTLI_LOG(("[ProcessCommandsInternal] dictionary word: [%.*s],"
     1773                      " transform_idx = %d, transformed: [%.*s]\n",
     1774                      i, word, transform_idx, len, &s->ringbuffer[pos]));
    17061775        }
    17071776        pos += len;
     
    17161785            "len: %d bytes left: %d\n",
    17171786            pos, s->distance_code, i, s->meta_block_remaining_len));
    1718         return BROTLI_FAILURE(BROTLI_ERROR_FORMAT_TRANSFORM);
     1787        return BROTLI_FAILURE(BROTLI_DECODER_ERROR_FORMAT_TRANSFORM);
    17191788      }
    17201789    } else {
     
    17221791          "len: %d bytes left: %d\n",
    17231792          pos, s->distance_code, i, s->meta_block_remaining_len));
    1724       return BROTLI_FAILURE(BROTLI_ERROR_FORMAT_DICTIONARY);
     1793      return BROTLI_FAILURE(BROTLI_DECODER_ERROR_FORMAT_DICTIONARY);
    17251794    }
    17261795  } else {
     
    17341803    ++s->dist_rb_idx;
    17351804    s->meta_block_remaining_len -= i;
    1736     /* There are 32+ bytes of slack in the ringbuffer allocation.
     1805    /* There are 32+ bytes of slack in the ring-buffer allocation.
    17371806       Also, we have 16 short codes, that make these 16 bytes irrelevant
    1738        in the ringbuffer. Let's copy over them as a first guess.
     1807       in the ring-buffer. Let's copy over them as a first guess.
    17391808     */
    17401809    memmove16(copy_dst, copy_src);
     
    17731842          s->ringbuffer[(pos - s->distance_code) & s->ringbuffer_mask];
    17741843      ++pos;
    1775       if (PREDICT_FALSE(--wrap_guard == 0)) {
     1844      if (BROTLI_PREDICT_FALSE(--wrap_guard == 0)) {
    17761845        s->state = BROTLI_STATE_COMMAND_POST_WRITE_2;
    17771846        goto saveStateAndReturn;
     
    17951864#undef BROTLI_SAFE
    17961865
    1797 static BROTLI_NOINLINE BrotliErrorCode ProcessCommands(BrotliState* s) {
     1866static BROTLI_NOINLINE BrotliDecoderErrorCode ProcessCommands(
     1867    BrotliDecoderState* s) {
    17981868  return ProcessCommandsInternal(0, s);
    17991869}
    18001870
    1801 static BROTLI_NOINLINE BrotliErrorCode SafeProcessCommands(BrotliState* s) {
     1871static BROTLI_NOINLINE BrotliDecoderErrorCode SafeProcessCommands(
     1872    BrotliDecoderState* s) {
    18021873  return ProcessCommandsInternal(1, s);
    18031874}
    18041875
    1805 BrotliResult BrotliDecompressBuffer(size_t encoded_size,
    1806                                     const uint8_t* encoded_buffer,
    1807                                     size_t* decoded_size,
    1808                                     uint8_t* decoded_buffer) {
    1809   BrotliState s;
    1810   BrotliResult result;
     1876BrotliDecoderResult BrotliDecoderDecompress(
     1877    size_t encoded_size, const uint8_t* encoded_buffer, size_t* decoded_size,
     1878    uint8_t* decoded_buffer) {
     1879  BrotliDecoderState s;
     1880  BrotliDecoderResult result;
    18111881  size_t total_out = 0;
    18121882  size_t available_in = encoded_size;
     
    18141884  size_t available_out = *decoded_size;
    18151885  uint8_t* next_out = decoded_buffer;
    1816   BrotliStateInit(&s);
    1817   result = BrotliDecompressStream(&available_in, &next_in, &available_out,
    1818       &next_out, &total_out, &s);
     1886  BrotliDecoderStateInit(&s);
     1887  result = BrotliDecoderDecompressStream(
     1888      &s, &available_in, &next_in, &available_out, &next_out, &total_out);
    18191889  *decoded_size = total_out;
    1820   BrotliStateCleanup(&s);
    1821   if (result != BROTLI_RESULT_SUCCESS) {
    1822     result = BROTLI_RESULT_ERROR;
     1890  BrotliDecoderStateCleanup(&s);
     1891  if (result != BROTLI_DECODER_RESULT_SUCCESS) {
     1892    result = BROTLI_DECODER_RESULT_ERROR;
    18231893  }
    18241894  return result;
     
    18281898    * invalid input implies that the whole stream is invalid -> any amount of
    18291899      input could be read and discarded
    1830     * when result is "needs more input", then at leat one more byte is REQUIRED
     1900    * when result is "needs more input", then at least one more byte is REQUIRED
    18311901      to complete decoding; all input data MUST be consumed by decoder, so
    18321902      client could swap the input buffer
     
    18371907      buffer; this is possible because the invariant is hold on enter
    18381908*/
    1839 BrotliResult BrotliDecompressStream(size_t* available_in,
    1840     const uint8_t** next_in, size_t* available_out, uint8_t** next_out,
    1841     size_t* total_out, BrotliState* s) {
    1842   BrotliErrorCode result = BROTLI_SUCCESS;
     1909BrotliDecoderResult BrotliDecoderDecompressStream(
     1910    BrotliDecoderState* s, size_t* available_in, const uint8_t** next_in,
     1911    size_t* available_out, uint8_t** next_out, size_t* total_out) {
     1912  BrotliDecoderErrorCode result = BROTLI_DECODER_SUCCESS;
    18431913  BrotliBitReader* br = &s->br;
     1914  /* Do not try to process further in a case of unrecoverable error. */
     1915  if ((int)s->error_code < 0) {
     1916    return BROTLI_DECODER_RESULT_ERROR;
     1917  }
     1918  if (*available_out && (!next_out || !*next_out)) {
     1919    return SaveErrorCode(
     1920        s, BROTLI_FAILURE(BROTLI_DECODER_ERROR_INVALID_ARGUMENTS));
     1921  }
     1922  if (!*available_out) next_out = 0;
    18441923  if (s->buffer_length == 0) { /* Just connect bit reader to input stream. */
    18451924    br->avail_in = *available_in;
     
    18491928       be required to complete the transaction -> reading more data must be
    18501929       done in a loop -> do it in a main loop. */
    1851     result = BROTLI_NEEDS_MORE_INPUT;
     1930    result = BROTLI_DECODER_NEEDS_MORE_INPUT;
    18521931    br->next_in = &s->buffer.u8[0];
    18531932  }
    18541933  /* State machine */
    18551934  for (;;) {
    1856     if (result != BROTLI_SUCCESS) { /* Error | needs more input/output */
    1857       if (result == BROTLI_NEEDS_MORE_INPUT) {
    1858         if (s->ringbuffer != 0) { /* Proactively push output. */
    1859           WriteRingBuffer(available_out, next_out, total_out, s);
     1935    if (result != BROTLI_DECODER_SUCCESS) { /* Error, needs more input/output */
     1936      if (result == BROTLI_DECODER_NEEDS_MORE_INPUT) {
     1937        if (s->ringbuffer != 0) { /* Pro-actively push output. */
     1938          BrotliDecoderErrorCode intermediate_result = WriteRingBuffer(s,
     1939              available_out, next_out, total_out, BROTLI_TRUE);
     1940          /* WriteRingBuffer checks s->meta_block_remaining_len validity. */
     1941          if ((int)intermediate_result < 0) {
     1942            result = intermediate_result;
     1943            break;
     1944          }
    18601945        }
    18611946        if (s->buffer_length != 0) { /* Used with internal buffer. */
    18621947          if (br->avail_in == 0) { /* Successfully finished read transaction. */
    1863             /* Accamulator contains less than 8 bits, because internal buffer
     1948            /* Accumulator contains less than 8 bits, because internal buffer
    18641949               is expanded byte-by-byte until it is enough to complete read. */
    18651950            s->buffer_length = 0;
    18661951            /* Switch to input stream and restart. */
    1867             result = BROTLI_SUCCESS;
     1952            result = BROTLI_DECODER_SUCCESS;
    18681953            br->avail_in = *available_in;
    18691954            br->next_in = *next_in;
     
    18721957            /* Not enough data in buffer, but can take one more byte from
    18731958               input stream. */
    1874             result = BROTLI_SUCCESS;
     1959            result = BROTLI_DECODER_SUCCESS;
    18751960            s->buffer.u8[s->buffer_length] = **next_in;
    18761961            s->buffer_length++;
     
    19061991      } else {
    19071992        /* Using input stream in last iteration. When decoder switches to input
    1908            stream it has less than 8 bits in accamulator, so it is safe to
    1909            return unused accamulator bits there. */
     1993           stream it has less than 8 bits in accumulator, so it is safe to
     1994           return unused accumulator bits there. */
    19101995        BrotliBitReaderUnload(br);
    19111996        *available_in = br->avail_in;
     
    19182003        /* Prepare to the first read. */
    19192004        if (!BrotliWarmupBitReader(br)) {
    1920           result = BROTLI_NEEDS_MORE_INPUT;
     2005          result = BROTLI_DECODER_NEEDS_MORE_INPUT;
    19212006          break;
    19222007        }
     
    19262011        if (s->window_bits == 9) {
    19272012          /* Value 9 is reserved for future use. */
    1928           result = BROTLI_FAILURE(BROTLI_ERROR_FORMAT_WINDOW_BITS);
     2013          result = BROTLI_FAILURE(BROTLI_DECODER_ERROR_FORMAT_WINDOW_BITS);
    19292014          break;
    19302015        }
    19312016        /* Maximum distance, see section 9.1. of the spec. */
    1932         s->max_backward_distance = (1 << s->window_bits) - 16;
    1933         /* Limit custom dictionary size. */
    1934         if (s->custom_dict_size >= s->max_backward_distance) {
    1935           s->custom_dict += s->custom_dict_size - s->max_backward_distance;
    1936           s->custom_dict_size = s->max_backward_distance;
    1937         }
    1938         s->max_backward_distance_minus_custom_dict_size =
    1939             s->max_backward_distance - s->custom_dict_size;
     2017        s->max_backward_distance = (1 << s->window_bits) - BROTLI_WINDOW_GAP;
    19402018
    19412019        /* Allocate memory for both block_type_trees and block_len_trees. */
     
    19442022                (BROTLI_HUFFMAN_MAX_SIZE_258 + BROTLI_HUFFMAN_MAX_SIZE_26));
    19452023        if (s->block_type_trees == 0) {
    1946           result = BROTLI_FAILURE(BROTLI_ERROR_ALLOC_BLOCK_TYPE_TREES);
     2024          result = BROTLI_FAILURE(BROTLI_DECODER_ERROR_ALLOC_BLOCK_TYPE_TREES);
    19472025          break;
    19482026        }
     
    19532031        /* No break, continue to next state */
    19542032      case BROTLI_STATE_METABLOCK_BEGIN:
    1955         BrotliStateMetablockBegin(s);
     2033        BrotliDecoderStateMetablockBegin(s);
    19562034        BROTLI_LOG_UINT(s->pos);
    19572035        s->state = BROTLI_STATE_METABLOCK_HEADER;
     
    19592037      case BROTLI_STATE_METABLOCK_HEADER:
    19602038        result = DecodeMetaBlockLength(s, br); /* Reads 2 - 31 bits. */
    1961         if (result != BROTLI_SUCCESS) {
     2039        if (result != BROTLI_DECODER_SUCCESS) {
    19622040          break;
    19632041        }
     
    19682046        if (s->is_metadata || s->is_uncompressed) {
    19692047          if (!BrotliJumpToByteBoundary(br)) {
    1970             result = BROTLI_FAILURE(BROTLI_ERROR_FORMAT_PADDING_1);
     2048            result = BROTLI_FAILURE(BROTLI_DECODER_ERROR_FORMAT_PADDING_1);
    19712049            break;
    19722050          }
     
    19802058          break;
    19812059        }
    1982         if (!s->ringbuffer) {
    1983           BrotliCalculateRingBufferSize(s, br);
    1984         }
     2060        BrotliCalculateRingBufferSize(s);
    19852061        if (s->is_uncompressed) {
    19862062          s->state = BROTLI_STATE_UNCOMPRESSED;
     
    19912067        break;
    19922068      case BROTLI_STATE_UNCOMPRESSED: {
    1993         int bytes_copied = s->meta_block_remaining_len;
    19942069        result = CopyUncompressedBlockToOutput(
    19952070            available_out, next_out, total_out, s);
    1996         bytes_copied -= s->meta_block_remaining_len;
    1997         if (result != BROTLI_SUCCESS) {
     2071        if (result != BROTLI_DECODER_SUCCESS) {
    19982072          break;
    19992073        }
     
    20062080          /* Read one byte and ignore it. */
    20072081          if (!BrotliSafeReadBits(br, 8, &bits)) {
    2008             result = BROTLI_NEEDS_MORE_INPUT;
     2082            result = BROTLI_DECODER_NEEDS_MORE_INPUT;
    20092083            break;
    20102084          }
    20112085        }
    2012         if (result == BROTLI_SUCCESS) {
     2086        if (result == BROTLI_DECODER_SUCCESS) {
    20132087          s->state = BROTLI_STATE_METABLOCK_DONE;
    20142088        }
     
    20212095        /* Reads 1..11 bits. */
    20222096        result = DecodeVarLenUint8(s, br, &s->num_block_types[s->loop_counter]);
    2023         if (result != BROTLI_SUCCESS) {
     2097        if (result != BROTLI_DECODER_SUCCESS) {
    20242098          break;
    20252099        }
     
    20362110        result = ReadHuffmanCode(s->num_block_types[s->loop_counter] + 2,
    20372111            &s->block_type_trees[tree_offset], NULL, s);
    2038         if (result != BROTLI_SUCCESS) break;
     2112        if (result != BROTLI_DECODER_SUCCESS) break;
    20392113        s->state = BROTLI_STATE_HUFFMAN_CODE_2;
    20402114        /* No break, continue to next state */
     
    20422116      case BROTLI_STATE_HUFFMAN_CODE_2: {
    20432117        int tree_offset = s->loop_counter * BROTLI_HUFFMAN_MAX_SIZE_26;
    2044         result = ReadHuffmanCode(kNumBlockLengthCodes,
     2118        result = ReadHuffmanCode(BROTLI_NUM_BLOCK_LEN_SYMBOLS,
    20452119            &s->block_len_trees[tree_offset], NULL, s);
    2046         if (result != BROTLI_SUCCESS) break;
     2120        if (result != BROTLI_DECODER_SUCCESS) break;
    20472121        s->state = BROTLI_STATE_HUFFMAN_CODE_3;
    20482122        /* No break, continue to next state */
     
    20522126        if (!SafeReadBlockLength(s, &s->block_length[s->loop_counter],
    20532127            &s->block_len_trees[tree_offset], br)) {
    2054           result = BROTLI_NEEDS_MORE_INPUT;
     2128          result = BROTLI_DECODER_NEEDS_MORE_INPUT;
    20552129          break;
    20562130        }
     
    20632137        uint32_t bits;
    20642138        if (!BrotliSafeReadBits(br, 6, &bits)) {
    2065           result = BROTLI_NEEDS_MORE_INPUT;
     2139          result = BROTLI_DECODER_NEEDS_MORE_INPUT;
    20662140          break;
    20672141        }
    20682142        s->distance_postfix_bits = bits & BitMask(2);
    20692143        bits >>= 2;
    2070         s->num_direct_distance_codes =
    2071             NUM_DISTANCE_SHORT_CODES + (bits << s->distance_postfix_bits);
     2144        s->num_direct_distance_codes = BROTLI_NUM_DISTANCE_SHORT_CODES +
     2145            (bits << s->distance_postfix_bits);
    20722146        BROTLI_LOG_UINT(s->num_direct_distance_codes);
    20732147        BROTLI_LOG_UINT(s->distance_postfix_bits);
     
    20762150            (uint8_t*)BROTLI_ALLOC(s, (size_t)s->num_block_types[0]);
    20772151        if (s->context_modes == 0) {
    2078           result = BROTLI_FAILURE(BROTLI_ERROR_ALLOC_CONTEXT_MODES);
     2152          result = BROTLI_FAILURE(BROTLI_DECODER_ERROR_ALLOC_CONTEXT_MODES);
    20792153          break;
    20802154        }
     
    20852159      case BROTLI_STATE_CONTEXT_MODES:
    20862160        result = ReadContextModes(s);
    2087         if (result != BROTLI_SUCCESS) {
     2161        if (result != BROTLI_DECODER_SUCCESS) {
    20882162          break;
    20892163        }
     
    20922166      case BROTLI_STATE_CONTEXT_MAP_1:
    20932167        result = DecodeContextMap(
    2094             s->num_block_types[0] << kLiteralContextBits,
     2168            s->num_block_types[0] << BROTLI_LITERAL_CONTEXT_BITS,
    20952169            &s->num_literal_htrees, &s->context_map, s);
    2096         if (result != BROTLI_SUCCESS) {
     2170        if (result != BROTLI_DECODER_SUCCESS) {
    20972171          break;
    20982172        }
     
    21022176      case BROTLI_STATE_CONTEXT_MAP_2:
    21032177        {
    2104           uint32_t num_distance_codes =
    2105               s->num_direct_distance_codes + (48U << s->distance_postfix_bits);
     2178          uint32_t num_distance_codes = s->num_direct_distance_codes +
     2179              ((2 * BROTLI_MAX_DISTANCE_BITS) << s->distance_postfix_bits);
     2180          BROTLI_BOOL allocation_success = BROTLI_TRUE;
    21062181          result = DecodeContextMap(
    2107               s->num_block_types[2] << kDistanceContextBits,
     2182              s->num_block_types[2] << BROTLI_DISTANCE_CONTEXT_BITS,
    21082183              &s->num_dist_htrees, &s->dist_context_map, s);
    2109           if (result != BROTLI_SUCCESS) {
     2184          if (result != BROTLI_DECODER_SUCCESS) {
    21102185            break;
    21112186          }
    2112           BrotliHuffmanTreeGroupInit(s, &s->literal_hgroup, kNumLiteralCodes,
    2113                                      s->num_literal_htrees);
    2114           BrotliHuffmanTreeGroupInit(s, &s->insert_copy_hgroup,
    2115                                      kNumInsertAndCopyCodes,
    2116                                      s->num_block_types[1]);
    2117           BrotliHuffmanTreeGroupInit(s, &s->distance_hgroup, num_distance_codes,
    2118                                      s->num_dist_htrees);
    2119           if (s->literal_hgroup.codes == 0 ||
    2120               s->insert_copy_hgroup.codes == 0 ||
    2121               s->distance_hgroup.codes == 0) {
     2187          allocation_success &= BrotliDecoderHuffmanTreeGroupInit(
     2188              s, &s->literal_hgroup, BROTLI_NUM_LITERAL_SYMBOLS,
     2189              s->num_literal_htrees);
     2190          allocation_success &= BrotliDecoderHuffmanTreeGroupInit(
     2191              s, &s->insert_copy_hgroup, BROTLI_NUM_COMMAND_SYMBOLS,
     2192              s->num_block_types[1]);
     2193          allocation_success &= BrotliDecoderHuffmanTreeGroupInit(
     2194              s, &s->distance_hgroup, num_distance_codes,
     2195              s->num_dist_htrees);
     2196          if (!allocation_success) {
    21222197            return SaveErrorCode(s,
    2123                 BROTLI_FAILURE(BROTLI_ERROR_ALLOC_TREE_GROUPS));
     2198                BROTLI_FAILURE(BROTLI_DECODER_ERROR_ALLOC_TREE_GROUPS));
    21242199          }
    21252200        }
     
    21412216              break;
    21422217            default:
    2143               return SaveErrorCode(s,
    2144                   BROTLI_FAILURE(BROTLI_ERROR_UNREACHABLE));
     2218              return SaveErrorCode(s, BROTLI_FAILURE(
     2219                  BROTLI_DECODER_ERROR_UNREACHABLE));
    21452220          }
    21462221          result = HuffmanTreeGroupDecode(hgroup, s);
    21472222        }
    2148         if (result != BROTLI_SUCCESS) break;
     2223        if (result != BROTLI_DECODER_SUCCESS) break;
    21492224        s->loop_counter++;
    21502225        if (s->loop_counter >= 3) {
     
    21522227          s->dist_context_map_slice = s->dist_context_map;
    21532228          s->htree_command = s->insert_copy_hgroup.htrees[0];
    2154           if (!s->ringbuffer && !BrotliAllocateRingBuffer(s)) {
    2155             result = BROTLI_FAILURE(BROTLI_ERROR_ALLOC_RING_BUFFER_2);
     2229          if (!BrotliEnsureRingBuffer(s)) {
     2230            result = BROTLI_FAILURE(BROTLI_DECODER_ERROR_ALLOC_RING_BUFFER_2);
    21562231            break;
    21572232          }
     
    21642239      case BROTLI_STATE_COMMAND_POST_WRAP_COPY:
    21652240        result = ProcessCommands(s);
    2166         if (result == BROTLI_NEEDS_MORE_INPUT) {
     2241        if (result == BROTLI_DECODER_NEEDS_MORE_INPUT) {
    21672242          result = SafeProcessCommands(s);
    21682243        }
     
    21712246      case BROTLI_STATE_COMMAND_POST_WRITE_1:
    21722247      case BROTLI_STATE_COMMAND_POST_WRITE_2:
    2173         result = WriteRingBuffer(available_out, next_out, total_out, s);
    2174         if (result != BROTLI_SUCCESS) {
    2175           break;
    2176         }
    2177         s->max_distance = s->max_backward_distance;
     2248        result = WriteRingBuffer(
     2249            s, available_out, next_out, total_out, BROTLI_FALSE);
     2250        if (result != BROTLI_DECODER_SUCCESS) {
     2251          break;
     2252        }
     2253        WrapRingBuffer(s);
     2254        if (s->ringbuffer_size == 1 << s->window_bits) {
     2255          s->max_distance = s->max_backward_distance;
     2256        }
    21782257        if (s->state == BROTLI_STATE_COMMAND_POST_WRITE_1) {
    2179           memcpy(s->ringbuffer, s->ringbuffer_end, (size_t)s->pos);
    21802258          if (s->meta_block_remaining_len == 0) {
    21812259            /* Next metablock, if any */
     
    22012279      case BROTLI_STATE_METABLOCK_DONE:
    22022280        if (s->meta_block_remaining_len < 0) {
    2203           result = BROTLI_FAILURE(BROTLI_ERROR_FORMAT_BLOCK_LENGTH_2);
    2204           break;
    2205         }
    2206         BrotliStateCleanupAfterMetablock(s);
     2281          result = BROTLI_FAILURE(BROTLI_DECODER_ERROR_FORMAT_BLOCK_LENGTH_2);
     2282          break;
     2283        }
     2284        BrotliDecoderStateCleanupAfterMetablock(s);
    22072285        if (!s->is_last_metablock) {
    22082286          s->state = BROTLI_STATE_METABLOCK_BEGIN;
     
    22102288        }
    22112289        if (!BrotliJumpToByteBoundary(br)) {
    2212           result = BROTLI_FAILURE(BROTLI_ERROR_FORMAT_PADDING_2);
     2290          result = BROTLI_FAILURE(BROTLI_DECODER_ERROR_FORMAT_PADDING_2);
    22132291          break;
    22142292        }
     
    22222300      case BROTLI_STATE_DONE:
    22232301        if (s->ringbuffer != 0) {
    2224           result = WriteRingBuffer(available_out, next_out, total_out, s);
    2225           if (result != BROTLI_SUCCESS) {
     2302          result = WriteRingBuffer(
     2303              s, available_out, next_out, total_out, BROTLI_TRUE);
     2304          if (result != BROTLI_DECODER_SUCCESS) {
    22262305            break;
    22272306          }
     
    22332312}
    22342313
    2235 void BrotliSetCustomDictionary(
    2236     size_t size, const uint8_t* dict, BrotliState* s) {
    2237   if (size > (1u << 24)) {
    2238     return;
    2239   }
    2240   s->custom_dict = dict;
    2241   s->custom_dict_size = (int)size;
    2242 }
    2243 
    2244 BrotliErrorCode BrotliGetErrorCode(const BrotliState* s) {
    2245   return (BrotliErrorCode)s->error_code;
    2246 }
    2247 
    2248 const char* BrotliErrorString(BrotliErrorCode c) {
     2314BROTLI_BOOL BrotliDecoderHasMoreOutput(const BrotliDecoderState* s) {
     2315  /* After unrecoverable error remaining output is considered nonsensical. */
     2316  if ((int)s->error_code < 0) {
     2317    return BROTLI_FALSE;
     2318  }
     2319  return TO_BROTLI_BOOL(
     2320      s->ringbuffer != 0 && UnwrittenBytes(s, BROTLI_FALSE) != 0);
     2321}
     2322
     2323const uint8_t* BrotliDecoderTakeOutput(BrotliDecoderState* s, size_t* size) {
     2324  uint8_t* result = 0;
     2325  size_t available_out = *size ? *size : 1u << 24;
     2326  size_t requested_out = available_out;
     2327  BrotliDecoderErrorCode status;
     2328  if ((s->ringbuffer == 0) || ((int)s->error_code < 0)) {
     2329    *size = 0;
     2330    return 0;
     2331  }
     2332  WrapRingBuffer(s);
     2333  status = WriteRingBuffer(s, &available_out, &result, 0, BROTLI_TRUE);
     2334  /* Either WriteRingBuffer returns those "success" codes... */
     2335  if (status == BROTLI_DECODER_SUCCESS ||
     2336      status == BROTLI_DECODER_NEEDS_MORE_OUTPUT) {
     2337    *size = requested_out - available_out;
     2338  } else {
     2339    /* ... or stream is broken. Normally this should be caught by
     2340       BrotliDecoderDecompressStream, this is just a safeguard. */
     2341    if ((int)status < 0) SaveErrorCode(s, status);
     2342    *size = 0;
     2343    result = 0;
     2344  }
     2345  return result;
     2346}
     2347
     2348BROTLI_BOOL BrotliDecoderIsUsed(const BrotliDecoderState* s) {
     2349  return TO_BROTLI_BOOL(s->state != BROTLI_STATE_UNINITED ||
     2350      BrotliGetAvailableBits(&s->br) != 0);
     2351}
     2352
     2353BROTLI_BOOL BrotliDecoderIsFinished(const BrotliDecoderState* s) {
     2354  return TO_BROTLI_BOOL(s->state == BROTLI_STATE_DONE) &&
     2355      !BrotliDecoderHasMoreOutput(s);
     2356}
     2357
     2358BrotliDecoderErrorCode BrotliDecoderGetErrorCode(const BrotliDecoderState* s) {
     2359  return (BrotliDecoderErrorCode)s->error_code;
     2360}
     2361
     2362const char* BrotliDecoderErrorString(BrotliDecoderErrorCode c) {
    22492363  switch (c) {
    2250 #define _BROTLI_ERROR_CODE_CASE(PREFIX, NAME, CODE) \
    2251     case BROTLI ## PREFIX ## NAME: return #NAME;
    2252 #define _BROTLI_NOTHING
    2253     BROTLI_ERROR_CODES_LIST(_BROTLI_ERROR_CODE_CASE, _BROTLI_NOTHING)
    2254 #undef _BROTLI_ERROR_CODE_CASE
    2255 #undef _BROTLI_NOTHING
     2364#define BROTLI_ERROR_CODE_CASE_(PREFIX, NAME, CODE) \
     2365    case BROTLI_DECODER ## PREFIX ## NAME: return #NAME;
     2366#define BROTLI_NOTHING_
     2367    BROTLI_DECODER_ERROR_CODES_LIST(BROTLI_ERROR_CODE_CASE_, BROTLI_NOTHING_)
     2368#undef BROTLI_ERROR_CODE_CASE_
     2369#undef BROTLI_NOTHING_
    22562370    default: return "INVALID";
    22572371  }
     2372}
     2373
     2374uint32_t BrotliDecoderVersion() {
     2375  return BROTLI_VERSION;
    22582376}
    22592377
  • trunk/Source/ThirdParty/brotli/dec/huffman.c

    r202225 r222903  
    1111#include <string.h>  /* memcpy, memset */
    1212
     13#include "../common/constants.h"
     14#include <brotli/types.h>
    1315#include "./port.h"
    14 #include "./types.h"
    1516
    1617#if defined(__cplusplus) || defined(c_plusplus)
     
    2122
    2223#ifdef BROTLI_RBIT
    23 #define BROTLI_REVERSE_BITS_BASE (32 - BROTLI_REVERSE_BITS_MAX)
     24#define BROTLI_REVERSE_BITS_BASE \
     25  ((sizeof(reg_t) << 3) - BROTLI_REVERSE_BITS_MAX)
    2426#else
    2527#define BROTLI_REVERSE_BITS_BASE 0
     
    6163
    6264#define BROTLI_REVERSE_BITS_LOWEST \
    63   (1U << (BROTLI_REVERSE_BITS_MAX - 1 + BROTLI_REVERSE_BITS_BASE))
     65  ((reg_t)1 << (BROTLI_REVERSE_BITS_MAX - 1 + BROTLI_REVERSE_BITS_BASE))
    6466
    6567/* Returns reverse(num >> BROTLI_REVERSE_BITS_BASE, BROTLI_REVERSE_BITS_MAX),
    6668   where reverse(value, len) is the bit-wise reversal of the len least
    6769   significant bits of value. */
    68 static BROTLI_INLINE uint32_t BrotliReverseBits(uint32_t num) {
     70static BROTLI_INLINE reg_t BrotliReverseBits(reg_t num) {
    6971#ifdef BROTLI_RBIT
    7072  return BROTLI_RBIT(num);
     
    103105                                        const uint8_t* const code_lengths,
    104106                                        uint16_t* count) {
    105   HuffmanCode code;   /* current table entry */
    106   int symbol;         /* symbol index in original or sorted table */
    107   uint32_t key;       /* prefix code */
    108   uint32_t key_step;  /* prefix code addend */
    109   int step;           /* step size to replicate values in current table */
    110   int table_size;     /* size of current table */
    111   int sorted[18];     /* symbols sorted by code length */
     107  HuffmanCode code; /* current table entry */
     108  int symbol;       /* symbol index in original or sorted table */
     109  reg_t key;        /* prefix code */
     110  reg_t key_step;   /* prefix code addend */
     111  int step;         /* step size to replicate values in current table */
     112  int table_size;   /* size of current table */
     113  int sorted[BROTLI_CODE_LENGTH_CODES];  /* symbols sorted by code length */
    112114  /* offsets in sorted table for each length */
    113115  int offset[BROTLI_HUFFMAN_MAX_CODE_LENGTH_CODE_LENGTH + 1];
     
    126128  });
    127129  /* Symbols with code length 0 are placed after all other symbols. */
    128   offset[0] = 17;
     130  offset[0] = BROTLI_CODE_LENGTH_CODES - 1;
    129131
    130132  /* sort symbols by length, by symbol order within each length */
    131   symbol = 18;
     133  symbol = BROTLI_CODE_LENGTH_CODES;
    132134  do {
    133135    BROTLI_REPEAT(6, {
     
    143145    code.bits = 0;
    144146    code.value = (uint16_t)sorted[0];
    145     for (key = 0; key < (uint32_t)table_size; ++key) {
     147    for (key = 0; key < (reg_t)table_size; ++key) {
    146148      table[key] = code;
    147149    }
     
    171173                                 const uint16_t* const symbol_lists,
    172174                                 uint16_t* count) {
    173   HuffmanCode code;       /* current table entry */
    174   HuffmanCode* table;     /* next available space in table */
    175   int len;                /* current code length */
    176   int symbol;             /* symbol index in original or sorted table */
    177   uint32_t key;           /* prefix code */
    178   uint32_t key_step;      /* prefix code addend */
    179   uint32_t sub_key;       /* 2nd level table prefix code */
    180   uint32_t sub_key_step;  /* 2nd level table prefix code addend */
    181   int step;               /* step size to replicate values in current table */
    182   int table_bits;         /* key length of current table */
    183   int table_size;         /* size of current table */
    184   int total_size;         /* sum of root table size and 2nd level table sizes */
     175  HuffmanCode code;    /* current table entry */
     176  HuffmanCode* table;  /* next available space in table */
     177  int len;             /* current code length */
     178  int symbol;          /* symbol index in original or sorted table */
     179  reg_t key;           /* prefix code */
     180  reg_t key_step;      /* prefix code addend */
     181  reg_t sub_key;       /* 2nd level table prefix code */
     182  reg_t sub_key_step;  /* 2nd level table prefix code addend */
     183  int step;            /* step size to replicate values in current table */
     184  int table_bits;      /* key length of current table */
     185  int table_size;      /* size of current table */
     186  int total_size;      /* sum of root table size and 2nd level table sizes */
    185187  int max_length = -1;
    186188  int bits;
  • trunk/Source/ThirdParty/brotli/dec/huffman.h

    r202225 r222903  
    1010#define BROTLI_DEC_HUFFMAN_H_
    1111
    12 #include "./types.h"
     12#include <brotli/types.h>
    1313#include "./port.h"
    1414
     
    1919#define BROTLI_HUFFMAN_MAX_CODE_LENGTH 15
    2020
    21 /* For current format this constant equals to kNumInsertAndCopyCodes */
    22 #define BROTLI_HUFFMAN_MAX_CODE_LENGTHS_SIZE 704
    23 
    2421/* Maximum possible Huffman table size for an alphabet size of (index * 32),
    2522 * max code length 15 and root table bits 8. */
     
    2724  256, 402, 436, 468, 500, 534, 566, 598, 630, 662, 694, 726, 758, 790, 822,
    2825  854, 886, 920, 952, 984, 1016, 1048, 1080};
     26/* BROTLI_NUM_BLOCK_LEN_SYMBOLS == 26 */
    2927#define BROTLI_HUFFMAN_MAX_SIZE_26 396
     28/* BROTLI_MAX_BLOCK_TYPE_SYMBOLS == 258 */
    3029#define BROTLI_HUFFMAN_MAX_SIZE_258 632
     30/* BROTLI_MAX_CONTEXT_MAP_SYMBOLS == 272 */
    3131#define BROTLI_HUFFMAN_MAX_SIZE_272 646
    3232
  • trunk/Source/ThirdParty/brotli/dec/port.h

    r202225 r222903  
    1717    * BROTLI_BUILD_PORTABLE disables dangerous optimizations, like unaligned
    1818      read and overlapping memcpy; this reduces decompression speed by 5%
     19    * BROTLI_BUILD_NO_RBIT disables "rbit" optimization for ARM CPUs
    1920    * BROTLI_DEBUG dumps file name and line number when decoder detects stream
    2021      or memory error
     
    3031#endif
    3132
    32 /* Compatibility with non-clang compilers. */
    33 #ifndef __has_builtin
    34 #define __has_builtin(x) 0
    35 #endif
    36 
    37 #ifndef __has_attribute
    38 #define __has_attribute(x) 0
    39 #endif
    40 
    41 #ifndef __has_feature
    42 #define __has_feature(x) 0
    43 #endif
     33#include <brotli/port.h>
    4434
    4535#if defined(__arm__) || defined(__thumb__) || \
    46     defined(_M_ARM) || defined(_M_ARMT)
     36    defined(_M_ARM) || defined(_M_ARMT) || defined(__ARM64_ARCH_8__)
    4737#define BROTLI_TARGET_ARM
    48 #if (defined(__ARM_ARCH) && (__ARM_ARCH >= 7)) || \
    49     (defined(M_ARM) && (M_ARM >= 7))
     38#if (defined(__ARM_ARCH) && (__ARM_ARCH == 7)) || \
     39    (defined(M_ARM) && (M_ARM == 7))
    5040#define BROTLI_TARGET_ARMV7
    5141#endif  /* ARMv7 */
    52 #if defined(__aarch64__)
     42#if defined(__aarch64__) || defined(__ARM64_ARCH_8__)
    5343#define BROTLI_TARGET_ARMV8
    5444#endif  /* ARMv8 */
     
    6757#endif
    6858
    69 #if defined(__GNUC__) && defined(__GNUC_MINOR__)
    70 #define BROTLI_GCC_VERSION (__GNUC__ * 100 + __GNUC_MINOR__)
    71 #else
    72 #define BROTLI_GCC_VERSION 0
    73 #endif
    74 
    75 #if defined(__ICC)
    76 #define BROTLI_ICC_VERSION __ICC
    77 #else
    78 #define BROTLI_ICC_VERSION 0
    79 #endif
    80 
    81 #if defined(BROTLI_BUILD_MODERN_COMPILER)
    82 #define BROTLI_MODERN_COMPILER 1
    83 #elif (BROTLI_GCC_VERSION > 300) || (BROTLI_ICC_VERSION >= 1600)
    84 #define BROTLI_MODERN_COMPILER 1
    85 #else
    86 #define BROTLI_MODERN_COMPILER 0
    87 #endif
    88 
    8959#ifdef BROTLI_BUILD_PORTABLE
    9060#define BROTLI_ALIGNED_READ (!!1)
    9161#elif defined(BROTLI_TARGET_X86) || defined(BROTLI_TARGET_X64) || \
    9262     defined(BROTLI_TARGET_ARMV7) || defined(BROTLI_TARGET_ARMV8)
    93 /* Allow unaligned read only for whitelisted CPUs. */
     63/* Allow unaligned read only for white-listed CPUs. */
    9464#define BROTLI_ALIGNED_READ (!!0)
    9565#else
    9666#define BROTLI_ALIGNED_READ (!!1)
    97 #endif
    98 
    99 /* Define "PREDICT_TRUE" and "PREDICT_FALSE" macros for capable compilers.
    100 
    101 To apply compiler hint, enclose the branching condition into macros, like this:
    102 
    103   if (PREDICT_TRUE(zero == 0)) {
    104     // main execution path
    105   } else {
    106     // compiler should place this code outside of main execution path
    107   }
    108 
    109 OR:
    110 
    111   if (PREDICT_FALSE(something_rare_or_unexpected_happens)) {
    112     // compiler should place this code outside of main execution path
    113   }
    114 
    115 */
    116 #if BROTLI_MODERN_COMPILER || __has_builtin(__builtin_expect)
    117 #define PREDICT_TRUE(x) (__builtin_expect(!!(x), 1))
    118 #define PREDICT_FALSE(x) (__builtin_expect(x, 0))
    119 #else
    120 #define PREDICT_FALSE(x) (x)
    121 #define PREDICT_TRUE(x) (x)
    12267#endif
    12368
     
    12873#define IS_CONSTANT(x) (!!0)
    12974#endif
    130 
    131 #if BROTLI_MODERN_COMPILER || __has_attribute(always_inline)
    132 #define ATTRIBUTE_ALWAYS_INLINE __attribute__ ((always_inline))
    133 #else
    134 #define ATTRIBUTE_ALWAYS_INLINE
    135 #endif
    136 
    137 #if defined(_WIN32) || defined(__CYGWIN__)
    138 #define ATTRIBUTE_VISIBILITY_HIDDEN
    139 #elif BROTLI_MODERN_COMPILER || __has_attribute(visibility)
    140 #define ATTRIBUTE_VISIBILITY_HIDDEN __attribute__ ((visibility ("hidden")))
    141 #else
    142 #define ATTRIBUTE_VISIBILITY_HIDDEN
    143 #endif
    144 
    145 #ifndef BROTLI_INTERNAL
    146 #define BROTLI_INTERNAL ATTRIBUTE_VISIBILITY_HIDDEN
    147 #endif
    148 
    149 #ifndef _MSC_VER
    150 #if defined(__cplusplus) || !defined(__STRICT_ANSI__) || \
    151     __STDC_VERSION__ >= 199901L
    152 #define BROTLI_INLINE inline ATTRIBUTE_ALWAYS_INLINE
    153 #else
    154 #define BROTLI_INLINE
    155 #endif
    156 #else  /* _MSC_VER */
    157 #define BROTLI_INLINE __forceinline
    158 #endif  /* _MSC_VER */
    15975
    16076#ifdef BROTLI_ENABLE_LOG
     
    16783
    16884#if defined(BROTLI_DEBUG) || defined(BROTLI_ENABLE_LOG)
    169 static inline void BrotliDump(const char* f, int l, const char* fn) {
     85static BROTLI_INLINE void BrotliDump(const char* f, int l, const char* fn) {
    17086  fprintf(stderr, "%s:%d (%s)\n", f, l, fn);
    17187  fflush(stderr);
     
    185101#else
    186102#define BROTLI_64_BITS 0
     103#endif
     104
     105#if (BROTLI_64_BITS)
     106#define reg_t uint64_t
     107#else
     108#define reg_t uint32_t
    187109#endif
    188110
     
    212134#endif
    213135
    214 #if BROTLI_MODERN_COMPILER || __has_attribute(noinline)
    215 #define BROTLI_NOINLINE __attribute__((noinline))
    216 #else
    217 #define BROTLI_NOINLINE
    218 #endif
    219 
    220136#define BROTLI_REPEAT(N, X) {     \
    221137  if ((N & 1) != 0) {X;}          \
     
    224140}
    225141
    226 #if BROTLI_MODERN_COMPILER || defined(__llvm__)
    227 #if defined(BROTLI_TARGET_ARMV7)
    228 static BROTLI_INLINE unsigned BrotliRBit(unsigned input) {
    229   unsigned output;
     142#if (BROTLI_MODERN_COMPILER || defined(__llvm__)) && \
     143    !defined(BROTLI_BUILD_NO_RBIT)
     144#if defined(BROTLI_TARGET_ARMV7) || defined(BROTLI_TARGET_ARMV8)
     145/* TODO: detect ARMv6T2 and enable this code for it. */
     146static BROTLI_INLINE reg_t BrotliRBit(reg_t input) {
     147  reg_t output;
    230148  __asm__("rbit %0, %1\n" : "=r"(output) : "r"(input));
    231149  return output;
     
    248166}
    249167
    250 #define BROTLI_UNUSED(X) (void)(X)
    251 
    252168#endif  /* BROTLI_DEC_PORT_H_ */
  • trunk/Source/ThirdParty/brotli/dec/prefix.h

    r197933 r222903  
    1212#define BROTLI_DEC_PREFIX_H_
    1313
    14 #include "./types.h"
     14#include "../common/constants.h"
     15#include <brotli/types.h>
    1516
    1617/* Represents the range of values belonging to a prefix code: */
     
    2122};
    2223
    23 static const struct PrefixCodeRange kBlockLengthPrefixCode[] = {
     24static const struct PrefixCodeRange
     25    kBlockLengthPrefixCode[BROTLI_NUM_BLOCK_LEN_SYMBOLS] = {
    2426  {   1,  2}, {    5,  2}, {  9,   2}, {  13,  2},
    2527  {  17,  3}, {   25,  3}, {  33,  3}, {  41,  3},
     
    4042} CmdLutElement;
    4143
    42 static const CmdLutElement kCmdLut[704] = {
     44static const CmdLutElement kCmdLut[BROTLI_NUM_COMMAND_SYMBOLS] = {
    4345  { 0x00, 0x00, 0, 0x00, 0x0000, 0x0002 },
    4446  { 0x00, 0x00, 0, 0x01, 0x0000, 0x0003 },
  • trunk/Source/ThirdParty/brotli/dec/state.c

    r202225 r222903  
    99#include <stdlib.h>  /* free, malloc */
    1010
     11#include <brotli/types.h>
    1112#include "./huffman.h"
    12 #include "./types.h"
    1313
    1414#if defined(__cplusplus) || defined(c_plusplus)
    1515extern "C" {
    1616#endif
    17 
    18 /* Declared in decode.h */
    19 int BrotliStateIsStreamStart(const BrotliState* s);
    20 int BrotliStateIsStreamEnd(const BrotliState* s);
    2117
    2218static void* DefaultAllocFunc(void* opaque, size_t size) {
     
    3026}
    3127
    32 void BrotliStateInit(BrotliState* s) {
    33   BrotliStateInitWithCustomAllocators(s, 0, 0, 0);
     28void BrotliDecoderStateInit(BrotliDecoderState* s) {
     29  BrotliDecoderStateInitWithCustomAllocators(s, 0, 0, 0);
    3430}
    3531
    36 void BrotliStateInitWithCustomAllocators(BrotliState* s,
     32void BrotliDecoderStateInitWithCustomAllocators(BrotliDecoderState* s,
    3733    brotli_alloc_func alloc_func, brotli_free_func free_func, void* opaque) {
    3834  if (!alloc_func) {
     
    4642  }
    4743
     44  s->error_code = 0; /* BROTLI_DECODER_NO_ERROR */
     45
    4846  BrotliInitBitReader(&s->br);
    4947  s->state = BROTLI_STATE_UNINITED;
     
    5654  s->substate_read_block_length = BROTLI_STATE_READ_BLOCK_LENGTH_NONE;
    5755
     56  s->dictionary = BrotliGetDictionary();
     57
    5858  s->buffer_length = 0;
    5959  s->loop_counter = 0;
     
    6565  s->block_len_trees = NULL;
    6666  s->ringbuffer = NULL;
     67  s->ringbuffer_size = 0;
     68  s->new_ringbuffer_size = 0;
     69  s->ringbuffer_mask = 0;
    6770
    6871  s->context_map = NULL;
     
    8184  s->distance_hgroup.htrees = NULL;
    8285
    83   s->custom_dict = NULL;
    84   s->custom_dict_size = 0;
     86  s->is_last_metablock = 0;
     87  s->is_uncompressed = 0;
     88  s->is_metadata = 0;
     89  s->should_wrap_ringbuffer = 0;
     90  s->canny_ringbuffer_allocation = 1;
    8591
    86   s->is_last_metablock = 0;
    8792  s->window_bits = 0;
    8893  s->max_distance = 0;
     
    98103  s->symbol_lists = &s->symbols_lists_array[BROTLI_HUFFMAN_MAX_CODE_LENGTH + 1];
    99104
    100   s->mtf_upper_bound = 255;
     105  s->mtf_upper_bound = 63;
    101106}
    102107
    103 void BrotliStateMetablockBegin(BrotliState* s) {
     108void BrotliDecoderStateMetablockBegin(BrotliDecoderState* s) {
    104109  s->meta_block_remaining_len = 0;
    105110  s->block_length[0] = 1U << 28;
     
    132137}
    133138
    134 void BrotliStateCleanupAfterMetablock(BrotliState* s) {
     139void BrotliDecoderStateCleanupAfterMetablock(BrotliDecoderState* s) {
    135140  BROTLI_FREE(s, s->context_modes);
    136141  BROTLI_FREE(s, s->context_map);
    137142  BROTLI_FREE(s, s->dist_context_map);
    138 
    139   BrotliHuffmanTreeGroupRelease(s, &s->literal_hgroup);
    140   BrotliHuffmanTreeGroupRelease(s, &s->insert_copy_hgroup);
    141   BrotliHuffmanTreeGroupRelease(s, &s->distance_hgroup);
     143  BROTLI_FREE(s, s->literal_hgroup.htrees);
     144  BROTLI_FREE(s, s->insert_copy_hgroup.htrees);
     145  BROTLI_FREE(s, s->distance_hgroup.htrees);
    142146}
    143147
    144 void BrotliStateCleanup(BrotliState* s) {
    145   BrotliStateCleanupAfterMetablock(s);
     148void BrotliDecoderStateCleanup(BrotliDecoderState* s) {
     149  BrotliDecoderStateCleanupAfterMetablock(s);
    146150
    147151  BROTLI_FREE(s, s->ringbuffer);
     
    149153}
    150154
    151 int BrotliStateIsStreamStart(const BrotliState* s) {
    152   return (s->state == BROTLI_STATE_UNINITED &&
    153       BrotliGetAvailableBits(&s->br) == 0);
    154 }
    155 
    156 int BrotliStateIsStreamEnd(const BrotliState* s) {
    157   return s->state == BROTLI_STATE_DONE;
    158 }
    159 
    160 void BrotliHuffmanTreeGroupInit(BrotliState* s, HuffmanTreeGroup* group,
    161     uint32_t alphabet_size, uint32_t ntrees) {
     155BROTLI_BOOL BrotliDecoderHuffmanTreeGroupInit(BrotliDecoderState* s,
     156    HuffmanTreeGroup* group, uint32_t alphabet_size, uint32_t ntrees) {
    162157  /* Pack two allocations into one */
    163158  const size_t max_table_size = kMaxHuffmanTableSize[(alphabet_size + 31) >> 5];
    164159  const size_t code_size = sizeof(HuffmanCode) * ntrees * max_table_size;
    165160  const size_t htree_size = sizeof(HuffmanCode*) * ntrees;
    166   char* p = (char*)BROTLI_ALLOC(s, code_size + htree_size);
     161  /* Pointer alignment is, hopefully, wider than sizeof(HuffmanCode). */
     162  HuffmanCode** p = (HuffmanCode**)BROTLI_ALLOC(s, code_size + htree_size);
    167163  group->alphabet_size = (uint16_t)alphabet_size;
    168164  group->num_htrees = (uint16_t)ntrees;
    169   group->codes = (HuffmanCode*)p;
    170   group->htrees = (HuffmanCode**)(p + code_size);
    171 }
    172 
    173 void BrotliHuffmanTreeGroupRelease(BrotliState* s, HuffmanTreeGroup* group) {
    174   BROTLI_FREE(s, group->codes);
    175   group->htrees = NULL;
     165  group->htrees = p;
     166  group->codes = (HuffmanCode*)(&p[ntrees]);
     167  return !!p;
    176168}
    177169
  • trunk/Source/ThirdParty/brotli/dec/state.h

    r202225 r222903  
    1010#define BROTLI_DEC_STATE_H_
    1111
     12#include "../common/constants.h"
     13#include "../common/dictionary.h"
     14#include <brotli/types.h>
    1215#include "./bit_reader.h"
    1316#include "./huffman.h"
    14 #include "./types.h"
    1517#include "./port.h"
    1618
     
    9496} BrotliRunningReadBlockLengthState;
    9597
    96 struct BrotliStateStruct {
     98struct BrotliDecoderStateStruct {
    9799  BrotliRunningState state;
    98100
     
    115117  int pos;
    116118  int max_backward_distance;
    117   int max_backward_distance_minus_custom_dict_size;
    118119  int max_distance;
    119120  int ringbuffer_size;
     
    141142  block type. It is then not needed to keep the context (faster decoding). */
    142143  int trivial_literal_context;
     144  /* Distance context is actual after command is decoded and before distance
     145  is computed. After distance computation it is used as a temporary variable. */
    143146  int distance_context;
    144147  int meta_block_remaining_len;
     
    161164
    162165  /* For partial write operations */
    163   size_t rb_roundtrips;  /* How many times we went around the ringbuffer */
    164   size_t partial_pos_out;  /* How much output to the user in total (<= rb) */
     166  size_t rb_roundtrips;  /* How many times we went around the ring-buffer */
     167  size_t partial_pos_out;  /* How much output to the user in total */
    165168
    166169  /* For ReadHuffmanCode */
     
    170173
    171174  HuffmanCode table[32];
    172   /* List of of symbol chains. */
     175  /* List of heads of symbol chains. */
    173176  uint16_t* symbol_lists;
    174177  /* Storage from symbol_lists. */
    175178  uint16_t symbols_lists_array[BROTLI_HUFFMAN_MAX_CODE_LENGTH + 1 +
    176                                BROTLI_HUFFMAN_MAX_CODE_LENGTHS_SIZE];
     179                               BROTLI_NUM_COMMAND_SYMBOLS];
    177180  /* Tails of symbol chains. */
    178181  int next_symbol[32];
    179   uint8_t code_length_code_lengths[18];
     182  uint8_t code_length_code_lengths[BROTLI_CODE_LENGTH_CODES];
    180183  /* Population counts for the code lengths */
    181184  uint16_t code_length_histo[16];
     
    193196  /* For InverseMoveToFrontTransform */
    194197  uint32_t mtf_upper_bound;
    195   uint8_t mtf[256 + 4];
    196 
    197   /* For custom dictionaries */
    198   const uint8_t* custom_dict;
    199   int custom_dict_size;
     198  uint32_t mtf[64 + 1];
    200199
    201200  /* less used attributes are in the end of this struct */
     
    209208  BrotliRunningReadBlockLengthState substate_read_block_length;
    210209
    211   uint8_t is_last_metablock;
    212   uint8_t is_uncompressed;
    213   uint8_t is_metadata;
    214   uint8_t size_nibbles;
     210  unsigned int is_last_metablock : 1;
     211  unsigned int is_uncompressed : 1;
     212  unsigned int is_metadata : 1;
     213  unsigned int should_wrap_ringbuffer : 1;
     214  unsigned int canny_ringbuffer_allocation : 1;
     215  unsigned int size_nibbles : 8;
    215216  uint32_t window_bits;
     217
     218  int new_ringbuffer_size;
    216219
    217220  uint32_t num_literal_htrees;
    218221  uint8_t* context_map;
    219222  uint8_t* context_modes;
     223  const BrotliDictionary* dictionary;
    220224
    221225  uint32_t trivial_literal_contexts[8];  /* 256 bits */
    222226};
    223227
    224 typedef struct BrotliStateStruct BrotliStateInternal;
    225 #define BrotliState BrotliStateInternal
    226 
    227 BROTLI_INTERNAL void BrotliStateInit(BrotliState* s);
    228 BROTLI_INTERNAL void BrotliStateInitWithCustomAllocators(BrotliState* s,
    229     brotli_alloc_func alloc_func, brotli_free_func free_func, void* opaque);
    230 BROTLI_INTERNAL void BrotliStateCleanup(BrotliState* s);
    231 BROTLI_INTERNAL void BrotliStateMetablockBegin(BrotliState* s);
    232 BROTLI_INTERNAL void BrotliStateCleanupAfterMetablock(BrotliState* s);
    233 BROTLI_INTERNAL void BrotliHuffmanTreeGroupInit(BrotliState* s,
    234     HuffmanTreeGroup* group, uint32_t alphabet_size, uint32_t ntrees);
    235 BROTLI_INTERNAL void BrotliHuffmanTreeGroupRelease(BrotliState* s,
    236     HuffmanTreeGroup* group);
     228typedef struct BrotliDecoderStateStruct BrotliDecoderStateInternal;
     229#define BrotliDecoderState BrotliDecoderStateInternal
     230
     231BROTLI_INTERNAL void BrotliDecoderStateInit(BrotliDecoderState* s);
     232BROTLI_INTERNAL void BrotliDecoderStateInitWithCustomAllocators(
     233    BrotliDecoderState* s, brotli_alloc_func alloc_func,
     234    brotli_free_func free_func, void* opaque);
     235BROTLI_INTERNAL void BrotliDecoderStateCleanup(BrotliDecoderState* s);
     236BROTLI_INTERNAL void BrotliDecoderStateMetablockBegin(BrotliDecoderState* s);
     237BROTLI_INTERNAL void BrotliDecoderStateCleanupAfterMetablock(
     238    BrotliDecoderState* s);
     239BROTLI_INTERNAL BROTLI_BOOL BrotliDecoderHuffmanTreeGroupInit(
     240    BrotliDecoderState* s, HuffmanTreeGroup* group, uint32_t alphabet_size,
     241    uint32_t ntrees);
    237242
    238243#if defined(__cplusplus) || defined(c_plusplus)
  • trunk/Source/ThirdParty/brotli/dec/transform.h

    r197933 r222903  
    1010#define BROTLI_DEC_TRANSFORM_H_
    1111
     12#include <brotli/types.h>
    1213#include "./port.h"
    13 #include "./types.h"
    1414
    1515#if defined(__cplusplus) || defined(c_plusplus)
     
    248248    return 1;
    249249  }
    250   /* An overly simplified uppercasing model for utf-8. */
     250  /* An overly simplified uppercasing model for UTF-8. */
    251251  if (p[0] < 0xe0) {
    252252    p[1] ^= 32;
  • trunk/Source/ThirdParty/brotli/update.sh

    r197933 r222903  
    1111perl -p -i -e "s/\[commit [0-9a-f]{40}\]/[${COMMIT}]/" README.webkit;
    1212
    13 rm -rf dec
    14 mv ${MY_TEMP_DIR}/brotli/dec dec
     13rm -rf dec common include/brotli
     14mv ${MY_TEMP_DIR}/brotli/c/dec dec
     15mv ${MY_TEMP_DIR}/brotli/c/common common
     16mv ${MY_TEMP_DIR}/brotli/c/include/brotli include/brotli
    1517rm -rf ${MY_TEMP_DIR}
    1618
  • trunk/Source/ThirdParty/woff2/CMakeLists.txt

    r220403 r222903  
    1313)
    1414
    15 include_directories("${THIRDPARTY_DIR}/brotli/dec")
     15include_directories("${THIRDPARTY_DIR}/brotli/include")
    1616include_directories("${WOFF2_INCLUDE_DIRECTORIES}")
    1717add_library(woff2 STATIC ${WOFF2_SOURCES})
  • trunk/Source/ThirdParty/woff2/README.webkit

    r206511 r222903  
    1212from within the modules/woff2 directory.
    1313
    14 Current version: [commit 63b8fb6d0d797f04e77ee825fd8fcf7ea6205aac].
     14Current version: [commit aa283a500aeb655834d77f3cf9cf1b093b0b4389].
  • trunk/Source/ThirdParty/woff2/src/buffer.h

    r197933 r222903  
    6666class Buffer {
    6767 public:
    68   Buffer(const uint8_t *buffer, size_t len)
    69       : buffer_(buffer),
     68  Buffer(const uint8_t *data, size_t len)
     69      : buffer_(data),
    7070        length_(len),
    7171        offset_(0) { }
     
    7575  }
    7676
    77   bool Read(uint8_t *buffer, size_t n_bytes) {
     77  bool Read(uint8_t *data, size_t n_bytes) {
    7878    if (n_bytes > 1024 * 1024 * 1024) {
    7979      return FONT_COMPRESSION_FAILURE();
     
    8383      return FONT_COMPRESSION_FAILURE();
    8484    }
    85     if (buffer) {
    86       std::memcpy(buffer, buffer_ + offset_, n_bytes);
     85    if (data) {
     86      std::memcpy(data, buffer_ + offset_, n_bytes);
    8787    }
    8888    offset_ += n_bytes;
  • trunk/Source/ThirdParty/woff2/src/font.cc

    r206511 r222903  
    106106  }
    107107
     108  // Sanity check key tables
     109  const Font::Table* head_table = font->FindTable(kHeadTableTag);
     110  if (head_table != NULL && head_table->length < 52) {
     111    return FONT_COMPRESSION_FAILURE();
     112  }
     113
    108114  return true;
    109115}
     
    326332  }
    327333  int index_fmt = IndexFormat(font);
    328   int num_glyphs = (loca_table->length / (index_fmt == 0 ? 2 : 4)) - 1;
    329   return num_glyphs;
     334  int loca_record_size = (index_fmt == 0 ? 2 : 4);
     335  if (loca_table->length < loca_record_size) {
     336    return 0;
     337  }
     338  return (loca_table->length / loca_record_size) - 1;
    330339}
    331340
  • trunk/Source/ThirdParty/woff2/src/glyph.cc

    r206511 r222903  
    119119    // Read the run-length coded flags.
    120120    std::vector<std::vector<uint8_t> > flags(num_contours);
    121     uint8_t flag = 0;
    122     uint8_t flag_repeat = 0;
    123     for (int i = 0; i < num_contours; ++i) {
    124       flags[i].resize(glyph->contours[i].size());
    125       for (size_t j = 0; j < glyph->contours[i].size(); ++j) {
    126         if (flag_repeat == 0) {
    127           if (!buffer.ReadU8(&flag)) {
    128             return FONT_COMPRESSION_FAILURE();
    129           }
    130           if (flag & kFLAG_REPEAT) {
    131             if (!buffer.ReadU8(&flag_repeat)) {
     121    {
     122      uint8_t flag = 0;
     123      uint8_t flag_repeat = 0;
     124      for (int i = 0; i < num_contours; ++i) {
     125        flags[i].resize(glyph->contours[i].size());
     126        for (size_t j = 0; j < glyph->contours[i].size(); ++j) {
     127          if (flag_repeat == 0) {
     128            if (!buffer.ReadU8(&flag)) {
    132129              return FONT_COMPRESSION_FAILURE();
    133130            }
    134           }
    135         } else {
    136           flag_repeat--;
    137         }
    138         flags[i][j] = flag;
    139         glyph->contours[i][j].on_curve = flag & kFLAG_ONCURVE;
     131            if (flag & kFLAG_REPEAT) {
     132              if (!buffer.ReadU8(&flag_repeat)) {
     133                return FONT_COMPRESSION_FAILURE();
     134              }
     135            }
     136          } else {
     137            flag_repeat--;
     138          }
     139          flags[i][j] = flag;
     140          glyph->contours[i][j].on_curve = flag & kFLAG_ONCURVE;
     141        }
    140142      }
    141143    }
  • trunk/Source/ThirdParty/woff2/src/normalize.cc

    r197933 r222903  
    5353  loca_table->length = (num_glyphs + 1) * glyph_sz;
    5454
    55   uint8_t* glyf_dst = &glyf_table->buffer[0];
     55  uint8_t* glyf_dst = num_glyphs ? &glyf_table->buffer[0] : NULL;
    5656  uint8_t* loca_dst = &loca_table->buffer[0];
    5757  uint32_t glyf_offset = 0;
     
    7979    glyf_offset += glyf_dst_size;
    8080  }
    81   if (glyf_offset == 0) {
    82     return false;
    83   }
    8481
    8582  StoreLoca(index_fmt, glyf_offset, &loca_offset, loca_dst);
    8683
    8784  glyf_table->buffer.resize(glyf_offset);
    88   glyf_table->data = &glyf_table->buffer[0];
     85  glyf_table->data = glyf_offset ? &glyf_table->buffer[0] : NULL;
    8986  glyf_table->length = glyf_offset;
    90   loca_table->data = &loca_table->buffer[0];
     87  loca_table->data = loca_offset ? &loca_table->buffer[0] : NULL;
    9188
    9289  return true;
  • trunk/Source/ThirdParty/woff2/src/port.h

    r206418 r222903  
    6161#endif
    6262
     63#if (defined(__ARM_ARCH) && (__ARM_ARCH == 7)) || \
     64    (defined(M_ARM) && (M_ARM == 7)) || \
     65    defined(__aarch64__) || defined(__ARM64_ARCH_8__) || defined(__i386) || \
     66    defined(_M_IX86) || defined(__x86_64__) || defined(_M_X64)
     67#if defined(__BYTE_ORDER__) && (__BYTE_ORDER__ == __ORDER_LITTLE_ENDIAN__)
     68#define WOFF_LITTLE_ENDIAN
     69#elif defined(__BYTE_ORDER__) && (__BYTE_ORDER__ == __ORDER_BIG_ENDIAN__)
     70#define WOFF_BIG_ENDIAN
     71#endif  /* endianness */
     72#endif  /* CPU whitelist */
     73
    6374#endif  // WOFF2_PORT_H_
  • trunk/Source/ThirdParty/woff2/src/store_bytes.h

    r206511 r222903  
    2323#include <string.h>
    2424
     25#include "./port.h"
     26
    2527namespace woff2 {
    2628
     
    3436
    3537inline size_t Store16(uint8_t* dst, size_t offset, int x) {
    36 #if (defined(__BYTE_ORDER__) && (__BYTE_ORDER__ == __ORDER_LITTLE_ENDIAN__))
     38#if defined(WOFF_LITTLE_ENDIAN)
    3739  *reinterpret_cast<uint16_t*>(dst + offset) =
    3840      ((x & 0xFF) << 8) | ((x & 0xFF00) >> 8);
    39 #elif (defined(__BYTE_ORDER__) && (__BYTE_ORDER__ == __ORDER_BIG_ENDIAN__))
     41#elif defined(WOFF_BIG_ENDIAN)
    4042  *reinterpret_cast<uint16_t*>(dst + offset) = static_cast<uint16_t>(x);
    4143#else
     
    5456
    5557inline void Store16(int val, size_t* offset, uint8_t* dst) {
    56 #if (defined(__BYTE_ORDER__) && (__BYTE_ORDER__ == __ORDER_LITTLE_ENDIAN__))
     58#if defined(WOFF_LITTLE_ENDIAN)
    5759  *reinterpret_cast<uint16_t*>(dst + *offset) =
    5860      ((val & 0xFF) << 8) | ((val & 0xFF00) >> 8);
    5961  *offset += 2;
    60 #elif (defined(__BYTE_ORDER__) && (__BYTE_ORDER__ == __ORDER_BIG_ENDIAN__))
     62#elif defined(WOFF_BIG_ENDIAN)
    6163  *reinterpret_cast<uint16_t*>(dst + *offset) = static_cast<uint16_t>(val);
    6264  *offset += 2;
  • trunk/Source/ThirdParty/woff2/src/variable_length.cc

    r197933 r222903  
    5050  std::vector<uint8_t> packed;
    5151  Write255UShort(&packed, val);
    52   for (uint8_t val : packed) {
    53     dst[(*offset)++] = val;
     52  for (uint8_t packed_byte : packed) {
     53    dst[(*offset)++] = packed_byte;
    5454  }
    5555}
  • trunk/Source/ThirdParty/woff2/src/woff2_common.cc

    r206511 r222903  
    1919#include "./woff2_common.h"
    2020
     21#include "./port.h"
     22
    2123namespace woff2 {
    2224
     
    2628  size_t aligned_size = size & ~3;
    2729  for (size_t i = 0; i < aligned_size; i += 4) {
    28 #if (defined(__BYTE_ORDER__) && (__BYTE_ORDER__ == __ORDER_LITTLE_ENDIAN__))
     30#if defined(WOFF_LITTLE_ENDIAN)
    2931    uint32_t v = *reinterpret_cast<const uint32_t*>(buf + i);
    3032    checksum += (((v & 0xFF) << 24) | ((v & 0xFF00) << 8) |
    3133      ((v & 0xFF0000) >> 8) | ((v & 0xFF000000) >> 24));
    32 #elif (defined(__BYTE_ORDER__) && (__BYTE_ORDER__ == __ORDER_BIG_ENDIAN__))
     34#elif defined(WOFF_BIG_ENDIAN)
    3335    checksum += *reinterpret_cast<const uint32_t*>(buf + i);
    3436#else
  • trunk/Source/ThirdParty/woff2/src/woff2_dec.cc

    r206511 r222903  
    2828#include <utility>
    2929
    30 #include "./decode.h"
     30#include "./brotli/decode.h"
    3131#include "./buffer.h"
    3232#include "./port.h"
     
    412412  }
    413413
     414  // https://dev.w3.org/webfonts/WOFF2/spec/#conform-mustRejectLoca
     415  // dst_length here is origLength in the spec
     416  uint32_t expected_loca_dst_length = (info->index_format ? 4 : 2)
     417    * (static_cast<uint32_t>(info->num_glyphs) + 1);
     418  if (PREDICT_FALSE(loca_table->dst_length != expected_loca_dst_length)) {
     419    return FONT_COMPRESSION_FAILURE();
     420  }
     421
    414422  unsigned int offset = (2 + kNumSubStreams) * 4;
    415423  if (PREDICT_FALSE(offset > glyf_table->transform_length)) {
     
    593601        return FONT_COMPRESSION_FAILURE();
    594602      }
     603    } else {
     604      // n_contours == 0; empty glyph. Must NOT have a bbox.
     605      if (PREDICT_FALSE(have_bbox)) {
     606#ifdef FONT_COMPRESSION_BIN
     607        fprintf(stderr, "Empty glyph has a bbox\n");
     608#endif
     609        return FONT_COMPRESSION_FAILURE();
     610      }
    595611    }
    596612
     
    670686  bool has_monospace_lsbs = (hmtx_flags & 2) == 0;
    671687
     688  // Bits 2-7 are reserved and MUST be zero.
     689  if ((hmtx_flags & 0xFC) != 0) {
     690#ifdef FONT_COMPRESSION_BIN
     691    fprintf(stderr, "Illegal hmtx flags; bits 2-7 must be 0\n");
     692#endif
     693    return FONT_COMPRESSION_FAILURE();
     694  }
     695
    672696  // you say you transformed but there is little evidence of it
    673697  if (has_proportional_lsbs && has_monospace_lsbs) {
     
    743767  const uint8_t* src_buf, size_t src_size) {
    744768  size_t uncompressed_size = dst_size;
    745   int ok = BrotliDecompressBuffer(src_size, src_buf,
    746                                   &uncompressed_size, dst_buf);
    747   if (PREDICT_FALSE(!ok || uncompressed_size != dst_size)) {
     769  BrotliDecoderResult result = BrotliDecoderDecompress(
     770      src_size, src_buf, &uncompressed_size, dst_buf);
     771  if (PREDICT_FALSE(result != BROTLI_DECODER_RESULT_SUCCESS ||
     772                    uncompressed_size != dst_size)) {
    748773    return FONT_COMPRESSION_FAILURE();
    749774  }
     
    876901
    877902  // 'glyf' without 'loca' doesn't make sense
    878   if (PREDICT_FALSE(static_cast<bool>(FindTable(&tables, kGlyfTableTag)) !=
    879                     static_cast<bool>(FindTable(&tables, kLocaTableTag)))) {
    880     return FONT_COMPRESSION_FAILURE();
     903  const Table* glyf_table = FindTable(&tables, kGlyfTableTag);
     904  const Table* loca_table = FindTable(&tables, kLocaTableTag);
     905  if (PREDICT_FALSE(static_cast<bool>(glyf_table) !=
     906                    static_cast<bool>(loca_table))) {
     907#ifdef FONT_COMPRESSION_BIN
     908      fprintf(stderr, "Cannot have just one of glyf/loca\n");
     909#endif
     910    return FONT_COMPRESSION_FAILURE();
     911  }
     912
     913  if (glyf_table != NULL) {
     914    if (PREDICT_FALSE((glyf_table->flags & kWoff2FlagsTransform)
     915                      != (loca_table->flags & kWoff2FlagsTransform))) {
     916#ifdef FONT_COMPRESSION_BIN
     917      fprintf(stderr, "Cannot transform just one of glyf/loca\n");
     918#endif
     919      return FONT_COMPRESSION_FAILURE();
     920    }
    881921  }
    882922
     
    899939    // TODO(user) a collection with optimized hmtx that reused glyf/loca
    900940    // would fail. We don't optimize hmtx for collections yet.
    901     if (PREDICT_FALSE(static_cast<uint64_t>(table.src_offset + table.src_length)
     941    if (PREDICT_FALSE(static_cast<uint64_t>(table.src_offset) + table.src_length
    902942        > transformed_buf_size)) {
    903943      return FONT_COMPRESSION_FAILURE();
     
    11001140      ttc_font.table_indices.resize(num_tables);
    11011141
    1102       const Table* glyf_table = NULL;
    1103       const Table* loca_table = NULL;
     1142
     1143      unsigned int glyf_idx = 0;
     1144      unsigned int loca_idx = 0;
    11041145
    11051146      for (uint32_t j = 0; j < num_tables; j++) {
     
    11131154        const Table& table = hdr->tables[table_idx];
    11141155        if (table.tag == kLocaTableTag) {
    1115           loca_table = &table;
     1156          loca_idx = table_idx;
    11161157        }
    11171158        if (table.tag == kGlyfTableTag) {
    1118           glyf_table = &table;
     1159          glyf_idx = table_idx;
    11191160        }
    11201161
    11211162      }
    11221163
    1123       if (PREDICT_FALSE((glyf_table == NULL) != (loca_table == NULL))) {
     1164      // if we have both glyf and loca make sure they are consecutive
     1165      // if we have just one we'll reject the font elsewhere
     1166      if (glyf_idx > 0 || loca_idx > 0) {
     1167        if (PREDICT_FALSE(glyf_idx > loca_idx || loca_idx - glyf_idx != 1)) {
    11241168#ifdef FONT_COMPRESSION_BIN
    1125         fprintf(stderr, "Cannot have just one of glyf/loca\n");
     1169        fprintf(stderr, "TTC font %d has non-consecutive glyf/loca\n", i);
    11261170#endif
    1127         return FONT_COMPRESSION_FAILURE();
     1171          return FONT_COMPRESSION_FAILURE();
     1172        }
    11281173      }
    11291174    }
     
    12991344  const uint8_t* src_buf = data + hdr.compressed_offset;
    13001345  std::vector<uint8_t> uncompressed_buf(hdr.uncompressed_size);
     1346  if (PREDICT_FALSE(hdr.uncompressed_size < 1)) {
     1347    return FONT_COMPRESSION_FAILURE();
     1348  }
    13011349  if (PREDICT_FALSE(!Woff2Uncompress(&uncompressed_buf[0],
    13021350                                     hdr.uncompressed_size, src_buf,
  • trunk/Source/ThirdParty/woff2/src/woff2_decompress.cc

    r206511 r222903  
    3333  string outfilename = filename.substr(0, filename.find_last_of(".")) + ".ttf";
    3434
     35  // Note: update woff2_dec_fuzzer_new_entry.cc if this pattern changes.
    3536  string input = woff2::GetFileContent(filename);
    3637  const uint8_t* raw_input = reinterpret_cast<const uint8_t*>(input.data());
  • trunk/Source/ThirdParty/woff2/src/woff2_enc.cc

    r206511 r222903  
    2424#include <vector>
    2525
    26 #include "./compressor.h"
     26#include "./brotli/encode.h"
    2727#include "./buffer.h"
    2828#include "./font.h"
     
    3535#include "./woff2_common.h"
    3636
    37 
    3837namespace woff2 {
    3938
     
    4847const size_t kWoff2EntrySize = 20;
    4948
    50 
    51 bool Compress(const uint8_t* data, const size_t len,
    52               uint8_t* result, uint32_t* result_len,
    53               brotli::BrotliParams::Mode mode, int quality) {
     49bool Compress(const uint8_t* data, const size_t len, uint8_t* result,
     50              uint32_t* result_len, BrotliEncoderMode mode, int quality) {
    5451  size_t compressed_len = *result_len;
    55   brotli::BrotliParams params;
    56   params.mode = mode;
    57   params.quality = quality;
    58   if (brotli::BrotliCompressBuffer(params, len, data, &compressed_len, result)
    59       == 0) {
     52  if (BrotliEncoderCompress(quality, BROTLI_DEFAULT_WINDOW, mode, len, data,
     53                            &compressed_len, result) == 0) {
    6054    return false;
    6155  }
     
    6862                   int quality) {
    6963  return Compress(data, len, result, result_len,
    70                   brotli::BrotliParams::MODE_FONT, quality);
     64                  BROTLI_MODE_FONT, quality);
    7165}
    7266
     
    7569                  int quality) {
    7670  return Compress(data, len, result, result_len,
    77                   brotli::BrotliParams::MODE_TEXT, quality);
     71                  BROTLI_MODE_TEXT, quality);
    7872}
    7973
     
    112106size_t ComputeWoff2Length(const FontCollection& font_collection,
    113107                          const std::vector<Table>& tables,
    114                           std::map<uint32_t, uint16_t> index_by_offset,
     108                          std::map<std::pair<uint32_t, uint32_t>, uint16_t>
     109                            index_by_tag_offset,
    115110                          size_t compressed_data_length,
    116111                          size_t extended_metadata_length) {
     
    135130        if (table.tag & 0x80808080) continue;
    136131
    137         uint16_t table_index = index_by_offset[table.offset];
     132        std::pair<uint32_t, uint32_t> tag_offset(table.tag, table.offset);
     133        uint16_t table_index = index_by_tag_offset[tag_offset];
    138134        size += Size255UShort(table_index);  // 255UInt16 index entry
    139135      }
     
    327323
    328324  std::vector<Table> tables;
    329   std::map<uint32_t, uint16_t> index_by_offset;
     325  std::map<std::pair<uint32_t, uint32_t>, uint16_t> index_by_tag_offset;
    330326
    331327  for (const auto& font : font_collection.fonts) {
     
    337333      }
    338334
    339       if (index_by_offset.find(src_table.offset) == index_by_offset.end()) {
    340         index_by_offset[src_table.offset] = tables.size();
     335      std::pair<uint32_t, uint32_t> tag_offset(src_table.tag, src_table.offset);
     336      if (index_by_tag_offset.find(tag_offset) == index_by_tag_offset.end()) {
     337        index_by_tag_offset[tag_offset] = tables.size();
    341338      } else {
    342339        return false;
     
    363360
    364361  size_t woff2_length = ComputeWoff2Length(font_collection, tables,
    365       index_by_offset, total_compressed_length, compressed_metadata_buf_length);
     362      index_by_tag_offset, total_compressed_length,
     363      compressed_metadata_buf_length);
    366364  if (woff2_length > *result_length) {
    367365#ifdef FONT_COMPRESSION_BIN
     
    436434        uint32_t table_length =
    437435          table.IsReused() ? table.reuse_of->length : table.length;
    438         if (index_by_offset.find(table_offset) == index_by_offset.end()) {
     436        std::pair<uint32_t, uint32_t> tag_offset(table.tag, table_offset);
     437        if (index_by_tag_offset.find(tag_offset) == index_by_tag_offset.end()) {
    439438#ifdef FONT_COMPRESSION_BIN
    440439          fprintf(stderr, "Missing table index for offset 0x%08x\n",
     
    443442          return FONT_COMPRESSION_FAILURE();
    444443        }
    445         uint16_t index = index_by_offset[table_offset];
     444        uint16_t index = index_by_tag_offset[tag_offset];
    446445        Store255UShort(index, &offset, result);
    447446
Note: See TracChangeset for help on using the changeset viewer.