[
  {
    "path": ".gitignore",
    "content": "out/*\r\nNUL"
  },
  {
    "path": ".gitmodules",
    "content": "[submodule \"libnt\"]\n\tpath = libnt\n\turl = https://github.com/svoboda18/libnt\n"
  },
  {
    "path": "Makefile",
    "content": "# env controlled\r\nDEBUG ?= 0\r\nCROSS_COMPILE ?=\r\nSH ?= sh\r\n\r\n# Build configuration (static only, shared are broken)\r\noverride TOPDIR ?= $(shell cygpath -m $(shell pwd))\r\noverride STATIC ?= 1\r\noverride SVB_MINGW ?= 1\r\noverride SVB_FLAGS ?= -DSVB_WIN32 -DANDROID\r\noverride BUILD_FLAGS ?= -fno-exceptions -fdiagnostics-absolute-paths -Wno-deprecated-non-prototype -DHOST\r\noverride BUILD_EXTRAS ?= 0\r\noverride BIN_EXT ?= .exe\r\noverride LIB_EXT ?= .a\r\n\r\nifeq ($(STATIC),0)\r\n$(warning WARNING: Host libraries are statically linked)\r\noverride LIB_EXT ?= .dll\r\nendif\r\n\r\nifeq ($(DEBUG),1)\r\noverride BUILD_FLAGS += -ggdb -ffunction-sections -Wall -Wextra -Wpedantic -Wconversion-null -Wno-gnu-include-next\r\noverride SVB_FLAGS += -DSVB_DEBUG\r\nelse\r\noverride BUILD_FLAGS += -Oz\r\nendif\r\noverride LDFLAGS ?= -Wl,-gc-sections\r\n\r\nifeq ($(SVB_MINGW),1)\r\noverride SVB_FLAGS += -DSVB_MINGW -DHAVE_LIB_NT_H -I$(TOPDIR)/libnt/include\r\nall:: svbnt magiskboot\r\nelse\r\nall:: print_info init_out res magiskboot\r\nendif\r\n\r\noverride CC := $(CROSS_COMPILE)clang\r\noverride CFLAGS ?= $(BUILD_FLAGS) $(SVB_FLAGS)\r\noverride CXX := $(CROSS_COMPILE)clang++\r\noverride CXXSTD ?= c++17\r\noverride CXXLIB ?= libc++\r\noverride CXXFLAGS ?= -std=$(CXXSTD) -stdlib=$(CXXLIB) $(BUILD_FLAGS) $(SVB_FLAGS)\r\n# LD is set for shared libs\r\nifeq ($(STATIC),0)\r\noverride LD := $(CROSS_COMPILE)clang $(BUILD_FLAGS)\r\noverride LDXX := $(CROSS_COMPILE)clang++ -std=$(CXXSTD) -stdlib=$(CXXLIB) $(BUILD_FLAGS) -static-libstdc++\r\n#override LDFLAGS += -Wl,--large-address-aware\r\nendif\r\noverride STRIP_CMD ?= $(CROSS_COMPILE)strip\r\noverride STRIPFLAGS ?= --strip-all -R .comment -R .gnu.version --strip-unneeded\r\noverride AR := $(CROSS_COMPILE)ar\r\noverride ARFLAGS := rcsD\r\n\r\noverride DEPLOY ?= $(TOPDIR)/build\r\noverride OUT ?= $(TOPDIR)/out\r\noverride SRP ?= $(OUT)\r\noverride OBJ ?= $(OUT)/obj\r\noverride LIB ?= $(OBJ)/lib\r\noverride SLIB ?= $(LIB)/shared\r\noverride LIB_OUT ?= $(LIB)\r\nifeq ($(STATIC),0)\r\noverride LIB_OUT ?= $(SLIB)\r\nendif\r\n\r\noverride STRIP ?= $(SH) $(TOPDIR)/scripts/strip.sh\r\noverride MKDIR ?= $(SH) $(TOPDIR)/scripts/mkdir.sh\r\n\r\noverride BIN_RES ?= $(OBJ)/bin.res\r\noverride DLL_RES ?= $(OBJ)/dll.res\r\n\r\nifeq ($(SVB_MINGW),1)\r\noverride LIBS ?= -lWs2_32 $(LIB)/libnt.a -limagehlp -lpthread\r\nendif\r\n\r\noverride NTLIB ?= libnt\r\n\r\noverride GNUMAKEFLAGS += --output-sync=line --no-print-directory\r\noverride MAKEFLAGS ?= -$(MAKEFLAGS) $(GNUMAKEFLAGS) --warn-undefined-variables\r\n\r\nMAGISKBOOT_SRC = \\\r\n    bootimg.cpp \\\r\n    hexpatch.cpp \\\r\n    compress.cpp \\\r\n    format.cpp \\\r\n    dtb.cpp \\\r\n    ramdisk.cpp \\\r\n    pattern.cpp \\\r\n    cpio.cpp \\\r\n    main.cpp\r\nMAGISKBOOT_OBJ ?= $(patsubst %.cpp,$(OBJ)/magiskboot/%.o,$(MAGISKBOOT_SRC))\r\n\r\nLIBBASE_SRC = \\\r\n    magiskbase/files.cpp \\\r\n    magiskbase/misc.cpp \\\r\n    magiskbase/xwrap.cpp \\\r\n    magiskbase/stream.cpp\r\n\r\nLIBBASE_OBJ ?= $(patsubst %.cpp,$(OBJ)/%.o,$(LIBBASE_SRC))\r\n\r\nLIBMINCRYPT_SRC = \\\r\n    external/mincrypt/dsa_sig.c \\\r\n    external/mincrypt/p256.c \\\r\n    external/mincrypt/p256_ec.c \\\r\n    external/mincrypt/p256_ecdsa.c \\\r\n    external/mincrypt/rsa.c \\\r\n    external/mincrypt/sha.c \\\r\n    external/mincrypt/sha256.c\r\nLIBMINCRYPT_OBJ = $(patsubst %.c,$(OBJ)/%.o,$(LIBMINCRYPT_SRC))\r\n\r\nLIBLZMA_SRC = \\\r\n    external/lzma/common/tuklib_cpucores.c \\\r\n    external/lzma/common/tuklib_exit.c \\\r\n    external/lzma/common/tuklib_mbstr_fw.c \\\r\n    external/lzma/common/tuklib_mbstr_width.c \\\r\n    external/lzma/common/tuklib_open_stdxxx.c \\\r\n    external/lzma/common/tuklib_physmem.c \\\r\n    external/lzma/common/tuklib_progname.c \\\r\n    external/lzma/liblzma/check/check.c \\\r\n    external/lzma/liblzma/check/crc32_fast.c \\\r\n    external/lzma/liblzma/check/crc32_table.c \\\r\n    external/lzma/liblzma/check/crc64_fast.c \\\r\n    external/lzma/liblzma/check/crc64_table.c \\\r\n    external/lzma/liblzma/check/sha256.c \\\r\n    external/lzma/liblzma/common/alone_decoder.c \\\r\n    external/lzma/liblzma/common/alone_encoder.c \\\r\n    external/lzma/liblzma/common/auto_decoder.c \\\r\n    external/lzma/liblzma/common/block_buffer_decoder.c \\\r\n    external/lzma/liblzma/common/block_buffer_encoder.c \\\r\n    external/lzma/liblzma/common/block_decoder.c \\\r\n    external/lzma/liblzma/common/block_encoder.c \\\r\n    external/lzma/liblzma/common/block_header_decoder.c \\\r\n    external/lzma/liblzma/common/block_header_encoder.c \\\r\n    external/lzma/liblzma/common/block_util.c \\\r\n    external/lzma/liblzma/common/common.c \\\r\n    external/lzma/liblzma/common/easy_buffer_encoder.c \\\r\n    external/lzma/liblzma/common/easy_decoder_memusage.c \\\r\n    external/lzma/liblzma/common/easy_encoder.c \\\r\n    external/lzma/liblzma/common/easy_encoder_memusage.c \\\r\n    external/lzma/liblzma/common/easy_preset.c \\\r\n    external/lzma/liblzma/common/filter_buffer_decoder.c \\\r\n    external/lzma/liblzma/common/filter_buffer_encoder.c \\\r\n    external/lzma/liblzma/common/filter_common.c \\\r\n    external/lzma/liblzma/common/filter_decoder.c \\\r\n    external/lzma/liblzma/common/filter_encoder.c \\\r\n    external/lzma/liblzma/common/filter_flags_decoder.c \\\r\n    external/lzma/liblzma/common/filter_flags_encoder.c \\\r\n    external/lzma/liblzma/common/hardware_cputhreads.c \\\r\n    external/lzma/liblzma/common/hardware_physmem.c \\\r\n    external/lzma/liblzma/common/index.c \\\r\n    external/lzma/liblzma/common/index_decoder.c \\\r\n    external/lzma/liblzma/common/index_encoder.c \\\r\n    external/lzma/liblzma/common/index_hash.c \\\r\n    external/lzma/liblzma/common/outqueue.c \\\r\n    external/lzma/liblzma/common/stream_buffer_decoder.c \\\r\n    external/lzma/liblzma/common/stream_buffer_encoder.c \\\r\n    external/lzma/liblzma/common/stream_decoder.c \\\r\n    external/lzma/liblzma/common/stream_encoder.c \\\r\n    external/lzma/liblzma/common/stream_encoder_mt.c \\\r\n    external/lzma/liblzma/common/stream_flags_common.c \\\r\n    external/lzma/liblzma/common/stream_flags_decoder.c \\\r\n    external/lzma/liblzma/common/stream_flags_encoder.c \\\r\n    external/lzma/liblzma/common/vli_decoder.c \\\r\n    external/lzma/liblzma/common/vli_encoder.c \\\r\n    external/lzma/liblzma/common/vli_size.c \\\r\n    external/lzma/liblzma/delta/delta_common.c \\\r\n    external/lzma/liblzma/delta/delta_decoder.c \\\r\n    external/lzma/liblzma/delta/delta_encoder.c \\\r\n    external/lzma/liblzma/lz/lz_decoder.c \\\r\n    external/lzma/liblzma/lz/lz_encoder.c \\\r\n    external/lzma/liblzma/lz/lz_encoder_mf.c \\\r\n    external/lzma/liblzma/lzma/fastpos_table.c \\\r\n    external/lzma/liblzma/lzma/lzma2_decoder.c \\\r\n    external/lzma/liblzma/lzma/lzma2_encoder.c \\\r\n    external/lzma/liblzma/lzma/lzma_decoder.c \\\r\n    external/lzma/liblzma/lzma/lzma_encoder.c \\\r\n    external/lzma/liblzma/lzma/lzma_encoder_optimum_fast.c \\\r\n    external/lzma/liblzma/lzma/lzma_encoder_optimum_normal.c \\\r\n    external/lzma/liblzma/lzma/lzma_encoder_presets.c \\\r\n    external/lzma/liblzma/rangecoder/price_table.c \\\r\n    external/lzma/liblzma/simple/arm.c \\\r\n    external/lzma/liblzma/simple/armthumb.c \\\r\n    external/lzma/liblzma/simple/ia64.c \\\r\n    external/lzma/liblzma/simple/powerpc.c \\\r\n    external/lzma/liblzma/simple/simple_coder.c \\\r\n    external/lzma/liblzma/simple/simple_decoder.c \\\r\n    external/lzma/liblzma/simple/simple_encoder.c \\\r\n    external/lzma/liblzma/simple/sparc.c \\\r\n    external/lzma/liblzma/simple/x86.c\r\nLIBLZMA_INCLUDES = \\\r\n    -I$(TOPDIR)/external/xz_config \\\r\n    -I$(TOPDIR)/external/xz/common \\\r\n    -I$(TOPDIR)/external/xz/liblzma/api \\\r\n    -I$(TOPDIR)/external/xz/liblzma/check \\\r\n    -I$(TOPDIR)/external/xz/liblzma/common \\\r\n    -I$(TOPDIR)/external/xz/liblzma/delta \\\r\n    -I$(TOPDIR)/external/xz/liblzma/lz \\\r\n    -I$(TOPDIR)/external/xz/liblzma/lzma \\\r\n    -I$(TOPDIR)/external/xz/liblzma/rangecoder \\\r\n    -I$(TOPDIR)/external/xz/liblzma/simple \\\r\n    -I$(TOPDIR)/external/xz/liblzma\r\nLIBLZMA_OBJ = $(patsubst %.c,$(OBJ)/%.o,$(LIBLZMA_SRC))\r\n\r\nLIBBZ2_SRC = \\\r\n    external/bzip2/blocksort.c  \\\r\n    external/bzip2/huffman.c    \\\r\n    external/bzip2/crctable.c   \\\r\n    external/bzip2/randtable.c  \\\r\n    external/bzip2/compress.c   \\\r\n    external/bzip2/decompress.c \\\r\n    external/bzip2/bzlib.c\r\nLIBBZ2_OBJ = $(patsubst %.c,$(OBJ)/%.o,$(LIBBZ2_SRC))\r\n\r\nLIBLZ4_SRC = \\\r\n    external/lz4/lz4.c \\\r\n    external/lz4/lz4frame.c \\\r\n    external/lz4/lz4hc.c \\\r\n    external/lz4/xxhash.c\r\nLIBLZ4_OBJ = $(patsubst %.c,$(OBJ)/%.o,$(LIBLZ4_SRC))\r\n\r\nLIBZOPFLI_SRC = \\\r\n    external/zopfli/blocksplitter.c \\\r\n    external/zopfli/cache.c \\\r\n    external/zopfli/deflate.c \\\r\n    external/zopfli/gzip_container.c \\\r\n    external/zopfli/hash.c \\\r\n    external/zopfli/katajainen.c \\\r\n    external/zopfli/lz77.c \\\r\n    external/zopfli/squeeze.c \\\r\n    external/zopfli/tree.c \\\r\n    external/zopfli/util.c \\\r\n    external/zopfli/zlib_container.c \\\r\n    external/zopfli/zopfli_lib.c\r\nLIBZOPFLI_OBJ = $(patsubst %.c,$(OBJ)/%.o,$(LIBZOPFLI_SRC))\r\n\r\nLIBZ_SRC = \\\r\n    external/zlib/adler32.c \\\r\n    external/zlib/compress.c \\\r\n    external/zlib/crc32.c \\\r\n    external/zlib/deflate.c \\\r\n    external/zlib/gzclose.c \\\r\n    external/zlib/gzlib.c \\\r\n    external/zlib/gzread.c \\\r\n    external/zlib/gzwrite.c \\\r\n    external/zlib/infback.c \\\r\n    external/zlib/inflate.c \\\r\n    external/zlib/inftrees.c \\\r\n    external/zlib/inffast.c \\\r\n    external/zlib/trees.c \\\r\n    external/zlib/uncompr.c \\\r\n    external/zlib/zutil.c\r\nLIBZ_OBJ = $(patsubst %.c,$(OBJ)/%.o,$(LIBZ_SRC))\r\n\r\nLIBFDT_SRC = \\\r\n    external/libfdt/fdt.c \\\r\n    external/libfdt/fdt_addresses.c \\\r\n    external/libfdt/fdt_empty_tree.c \\\r\n    external/libfdt/fdt_overlay.c \\\r\n    external/libfdt/fdt_ro.c \\\r\n    external/libfdt/fdt_rw.c \\\r\n    external/libfdt/fdt_strerror.c \\\r\n    external/libfdt/fdt_sw.c \\\r\n    external/libfdt/fdt_wip.c\r\nLIBFDT_OBJ = $(patsubst %.c,$(OBJ)/%.o,$(LIBFDT_SRC))\r\n\r\nBUILD_SHARED ?= \\\r\n\t$(SLIB)/svbmincrypt.dll \\\r\n\t$(SLIB)/svbzopfli.dll \\\r\n\t$(SLIB)/svbbase.dll \\\r\n\t$(SLIB)/svblzma.dll \\\r\n\t$(SLIB)/svblz4.dll \\\r\n\t$(SLIB)/svbfdt.dll \\\r\n\t$(SLIB)/svbbz2.dll \\\r\n\t$(SLIB)/svbz.dll\r\nBUILD_FILES ?= $(SRP)/magiskboot$(BIN_EXT)\r\n\r\nBUILD_EXTRA ?=\r\n\r\nifeq (1,$(STATIC))\r\noverride BUILD_SHARED ?=\r\nendif\r\n\r\nifeq (1,$(BUILD_EXTRAS))\r\noverride BUILD_FILES ?= $(BUILD_FILES) $(BUILD_EXTRAS)\r\nendif\r\n\r\noverride MAKEFLAGS += -rsR\r\n\r\nexport TOPDIR DEBUG STATIC SVB_MINGW BUILD_FILES CROSS_COMPILE AR LIBS SVB_FLAGS CC CFLAGS CXX CXXSTD CXXLIB CXXFLAGS \\\r\n\tLD LDXX LDFLAGS STRIP STRIP_CMD STRIPFLAGS AR ARFLAGS LIBS DEPLOY OUT OBJ LIB SRP SLIB BIN_RES DLL_RES BIN_EXT LIB_EXT LIB_OUT MKDIR \\\r\n\tGNUMAKEFLAGS\r\n\r\n.PHONY: all\r\n\r\nprint_info:\r\n\t$(info INFO: CXX STD VERSION '$(CXXSTD)')\r\n\t$(info INFO: CXX STD LIB '$(CXXLIB)')\r\n\t$(info INFO: CC '$(CC) $(CFLAGS)')\r\n\t$(info INFO: CXX '$(CXX) $(CXXFLAGS)')\r\n\t$(info INFO: LD '$(CXX) $(CXXFLAGS) $(LDFLAGS) $(BIN_RES) $(LIBS)')\r\n\t$(info INFO: AR '$(AR) $(ARFLAGS)')\r\n\t$(info INFO: STRIP '$(STRIP) $(STRIPFLAGS)')\r\n\r\ninit_out:\r\n\t@$(MKDIR) -p $(OUT)\r\n\t@$(MKDIR) -p $(OBJ)\r\n\t@$(MKDIR) -p $(LIB)\r\n\t@if [[ $(STATIC) -eq 0 ]]; then \\\r\n\t\t$(MKDIR) -p $(SLIB); \\\r\n\tfi\r\n\r\nres: $(BIN_RES) $(DLL_RES)\r\n\r\nsvbnt: init_out print_info res\r\n\t@$(MAKE) $(MAKEFLAGS) -C $(NTLIB)\r\n\r\n$(OBJ)/%.res: %.rc\r\n\t@echo -e \"  WINDRES   `basename $@`\"\r\n\t@windres --input=$< --output-format=coff --output=$@\r\n\r\nclean:\r\n\t@echo -e \"  RM\\t    obj\"\r\n\t@rm -rf $(OBJ)\r\n\t@echo -e \"  RM\\t    bin\"\r\n\t@rm -rf $(OUT)\r\n\r\noverride INCLUDES ?= \\\r\n    -Iinclude \\\r\n    -I$(TOPDIR)/external \\\r\n    -I$(TOPDIR)/external/libfdt \\\r\n    -I$(TOPDIR)/external/mincrypt/include \\\r\n    -Imagiskbase/include \\\r\n    -I$(TOPDIR)/external/bzip2 \\\r\n    -I$(TOPDIR)/external/xz/liblzma/api \\\r\n    -I$(TOPDIR)/external/zlib \\\r\n    -I$(TOPDIR)/external/lz4\r\n\r\n# libmagiskbase always static\r\nextlib: $(LIB_OUT)/libmincrypt$(LIB_EXT) $(LIB_OUT)/libz$(LIB_EXT) $(LIB_OUT)/liblzma$(LIB_EXT) \\\r\n\t\t$(LIB_OUT)/libbz2$(LIB_EXT) $(LIB_OUT)/liblz4$(LIB_EXT) $(LIB_OUT)/libzopfli$(LIB_EXT) $(LIB_OUT)/libfdt$(LIB_EXT)\r\n\r\nmagiskboot: extlib $(LIB)/libmagiskbase.a $(OUT)/magiskboot$(BIN_EXT)\r\n\r\n$(OBJ)/external/zopfli/%.o: $(TOPDIR)/%.c\r\n\t@$(MKDIR) -p `dirname $@`\r\n\t@echo -e \"  CC\\t    `basename $@`\"\r\n\t@$(CC) $(CFLAGS) -Wall -Werror -Wno-unused -Wno-unused-parameter $(INCLUDES) -c $< -o $@\r\n\r\n$(OBJ)/external/lzma/%.o: $(TOPDIR)/external/xz/%.c\r\n\t@$(MKDIR) -p `dirname $@`\r\n\t@echo -e \"  CC\\t    `basename $@`\"\r\n\t@$(CC) $(CFLAGS) -DHAVE_CONFIG_H -Wno-implicit-function-declaration $(INCLUDES) $(LIBLZMA_INCLUDES) -c $< -o $@\r\n\r\n$(OBJ)/%.o: $(TOPDIR)/%.c\r\n\t@$(MKDIR) -p `dirname $@`\r\n\t@echo -e \"  CC\\t    `basename $@`\"\r\n\t@$(CC) $(CFLAGS) $(INCLUDES) -c $< -o $@\r\n\r\n$(OBJ)/%.o: %.cpp\r\n\t@$(MKDIR) -p `dirname $@`\r\n\t@echo -e \"  CXX\\t    `basename $@`\"\r\n\t@$(CXX) -static $(CXXFLAGS) $(INCLUDES) -c $< -o $@\r\n\r\n$(OBJ)/magiskboot/%.o: %.cpp\r\n\t@$(MKDIR) -p `dirname $@`\r\n\t@echo -e \"  CXX\\t    `basename $@`\"\r\n\t@$(CXX) -static $(CXXFLAGS) $(INCLUDES) -c $< -o $@\r\n\r\nMAGISKBOOT_LD ?= $(LIB)/libmincrypt.a $(LIB)/liblzma.a $(LIB)/libbz2.a \\\r\n\t\t $(LIB)/liblz4.a $(LIB)/libzopfli.a $(LIB)/libfdt.a $(LIB)/libz.a\r\nifeq ($(STATIC),0)\r\noverride MAGISKBOOT_LD ?= $(shell echo $(MAGISKBOOT_LD) | sed \"s@\\(obj/lib/\\)lib\\(\\w\\+\\)\\.a@\\1shared/svb\\2\\.dll@g\")\r\nendif\r\n$(OUT)/magiskboot$(BIN_EXT): $(MAGISKBOOT_OBJ) $(LIB)/libmagiskbase.a $(MAGISKBOOT_LD)\r\n\t@$(MKDIR) -p `dirname $@`\r\n\t@echo -e \"  LD\\t    `basename $@`\"\r\n\t@$(CXX) $(CXXFLAGS) $^ -o $@ -static $(LDFLAGS) $(BIN_RES) $(LIBS)\r\n\t@$(STRIP) $(STRIPFLAGS) $@\r\n\r\n$(LIB)/libmagiskbase.a: $(LIBBASE_OBJ)\r\n\t@$(MKDIR) -p `dirname $@`\r\n\t@echo -e \"  AR\\t    `basename $@`\"\r\n\t@$(AR) $(ARFLAGS) $@ $^\r\n\r\n$(SLIB)/lib%.dll: $(LIB)/lib%.a\r\n\t@echo -e \"  LD\\t    `basename $@`\"\r\n\t@$(LD) -shared -o $(SLIB)/svb$*.dll \\\r\n\t    -Wl,--export-all-symbols \\\r\n\t    -Wl,--enable-auto-import \\\r\n\t    -Wl,--whole-archive $^ \\\r\n\t    -Wl,--no-whole-archive -lpthread $(DLL_RES)\r\n\r\n$(LIB)/libmincrypt.a: $(LIBMINCRYPT_OBJ)\r\n\t@$(MKDIR) -p `dirname $@`\r\n\t@echo -e \"  AR\\t    `basename $@`\"\r\n\t@$(AR) $(ARFLAGS) $@ $^\r\n\r\n$(LIB)/liblzma.a: $(LIBLZMA_OBJ)\r\n\t@$(MKDIR) -p `dirname $@`\r\n\t@echo -e \"  AR\\t    `basename $@`\"\r\n\t@$(AR) $(ARFLAGS) $@ $^\r\n\r\n$(LIB)/libbz2.a: $(LIBBZ2_OBJ)\r\n\t@$(MKDIR) -p `dirname $@`\r\n\t@echo -e \"  AR\\t    `basename $@`\"\r\n\t@$(AR) $(ARFLAGS) $@ $^\r\n\r\n$(LIB)/liblz4.a: $(LIBLZ4_OBJ)\r\n\t@$(MKDIR) -p `dirname $@`\r\n\t@echo -e \"  AR\\t    `basename $@`\"\r\n\t@$(AR) $(ARFLAGS) $@ $^\r\n\r\n$(LIB)/libzopfli.a: $(LIBZOPFLI_OBJ)\r\n\t@$(MKDIR) -p `dirname $@`\r\n\t@echo -e \"  AR\\t    `basename $@`\"\r\n\t@$(AR) $(ARFLAGS) $@ $^\r\n\r\n$(LIB)/libz.a: $(LIBZ_OBJ)\r\n\t@$(MKDIR) -p `dirname $@`\r\n\t@echo -e \"  AR\\t    `basename $@`\"\r\n\t@$(AR) $(ARFLAGS) $@ $^\r\n\r\n$(LIB)/libfdt.a: $(LIBFDT_OBJ)\r\n\t@$(MKDIR) -p `dirname $@`\r\n\t@echo -e \"  AR\\t    `basename $@`\"\r\n\t@$(AR) $(ARFLAGS) $@ $^"
  },
  {
    "path": "README.md",
    "content": "# MagiskBoot - Boot Image Modification Tool\r\nThe most complete tool for unpacking and repacking Android boot images.\r\n\r\n**Note**: This is a minimal (dirty) copy of topjohnwu's [MagiskBoot](https://github.com/topjohnwu/Magisk/tree/master/native/src/boot).\r\n\r\n## Documentation\r\n- [MagiskBoot Documentation](https://topjohnwu.github.io/Magisk/tools.html#magiskboot)\r\n\r\n## Build\r\n- Using MSYS2 `clang64` environment with `mingw-w64-clang-x86_64-toolchain` packages group, LLVM version 14 and up, run `mingw32-make` command. (`magiskboot.exe` will appear in the `out` folder).\r\n- if built a non-static variant, all DLLs in `out/obj/lib/shared` must be present in your PATH for successful execution. \r\n\r\n## What's changed:\r\n- `cpio` action `extract` with no paramaters to `ramdisk` folder in current directory.\r\n   * it creates `cpio` file to allow mode/uid/gid changes in Windows (with `sync` or `pack`)\r\n- new `cpio` action `sync` that synchronize incpio entries with `ramdisk` directory (as new cpio). Any changes will be captured and dumped to `incpio`.\r\n- new `cpio` action `pack` as follows: `cpio pack [-c <config>] <infolder> <outcpio>`\r\n   * if `<config>` is undefined `cpio` is looked-up instead.\r\n\r\n## For Windows\r\n- There's some UBs/SFs that needs to be addressed (test and report).\r\n- Tested and working operations are limited."
  },
  {
    "path": "bin.rc",
    "content": "#include <windows.h>\r\n\r\nVS_VERSION_INFO VERSIONINFO\r\nFILEVERSION     1,0,0,0\r\nPRODUCTVERSION  1,0,0,0\r\nFILEFLAGSMASK      VS_FFI_FILEFLAGSMASK\r\n#ifdef SVB_DEBUG\r\n  FILEFLAGS        VS_FF_DEBUG | VS_FF_PRERELEASE\r\n#else\r\n  FILEFLAGS        0\r\n#endif\r\nFILEOS             VOS_NT_WINDOWS32\r\nFILETYPE           VFT_APP\r\nFILESUBTYPE        VFT2_UNKNOWN\r\nBEGIN\r\n  BLOCK \"StringFileInfo\"\r\n  BEGIN\r\n    BLOCK \"040904E4\"\r\n    BEGIN\r\n      VALUE \"FileDescription\", \"magiskboot binary\"\r\n      VALUE \"FileVersion\", \"1.0.0.0\"\r\n      VALUE \"ProductVersion\", \"1.0.0.0\"\r\n    END\r\n  END\r\n  BLOCK \"VarFileInfo\"\r\n  BEGIN\r\n    VALUE \"Translation\", 0x409, 1252\r\n  END\r\nEND"
  },
  {
    "path": "bootimg.cpp",
    "content": "#include <functional>\n#include <memory>\n\n#include <libfdt.h>\n#include <mincrypt/sha.h>\n#include <mincrypt/sha256.h>\n#include <base.hpp>\n\n#include \"bootimg.hpp\"\n#include \"magiskboot.hpp\"\n#include \"compress.hpp\"\n\n#ifdef SVB_WIN32\n#define off64_t off_t\n#define lseek64 lseek\n#define ftruncate64 ftruncate\n#endif\n\nusing namespace std;\n\nuint32_t dyn_img_hdr::j32 = 0;\nuint64_t dyn_img_hdr::j64 = 0;\n\n#define PADDING 15\n\nstatic void decompress(format_t type, int fd, const void *in, size_t size) {\n    auto ptr = get_decoder(type, make_unique<fd_stream>(fd));\n    ptr->write(in, size, true);\n}\n\nstatic off_t compress(format_t type, int fd, const void *in, size_t size) {\n    auto prev = lseek(fd, 0, SEEK_CUR);\n    {\n        auto strm = get_encoder(type, make_unique<fd_stream>(fd));\n        strm->write(in, size, true);\n    }\n    auto now = lseek(fd, 0, SEEK_CUR);\n    return now - prev;\n}\n\nstatic void dump(const void *buf, size_t size, const char *filename) {\n    if (size == 0)\n        return;\n    int fd = creat(filename, 0644);\n    xwrite(fd, buf, size);\n    close(fd);\n}\n\nstatic size_t restore(int fd, const char *filename) {\n    int ifd = xopen(filename, O_RDONLY);\n    size_t size = lseek(ifd, 0, SEEK_END);\n    lseek(ifd, 0, SEEK_SET);\n    xsendfile(fd, ifd, nullptr, size);\n    close(ifd);\n    return size;\n}\n\nvoid dyn_img_hdr::print() {\n    uint32_t ver = header_version();\n    fprintf(stderr, \"%-*s [%u]\\n\", PADDING, \"HEADER_VER\", ver);\n    if (!is_vendor)\n        fprintf(stderr, \"%-*s [%u]\\n\", PADDING, \"KERNEL_SZ\", kernel_size());\n    fprintf(stderr, \"%-*s [%u]\\n\", PADDING, \"RAMDISK_SZ\", ramdisk_size());\n    if (ver < 3)\n        fprintf(stderr, \"%-*s [%u]\\n\", PADDING, \"SECOND_SZ\", second_size());\n    if (ver == 0)\n        fprintf(stderr, \"%-*s [%u]\\n\", PADDING, \"EXTRA_SZ\", extra_size());\n    if (ver == 1 || ver == 2)\n        fprintf(stderr, \"%-*s [%u]\\n\", PADDING, \"RECOV_DTBO_SZ\", recovery_dtbo_size());\n    if (ver == 2 || is_vendor)\n        fprintf(stderr, \"%-*s [%u]\\n\", PADDING, \"DTB_SZ\", dtb_size());\n\n    if (uint32_t os_ver = os_version()) {\n        int a,b,c,y,m = 0;\n        int version = os_ver >> 11;\n        int patch_level = os_ver & 0x7ff;\n\n        a = (version >> 14) & 0x7f;\n        b = (version >> 7) & 0x7f;\n        c = version & 0x7f;\n        fprintf(stderr, \"%-*s [%d.%d.%d]\\n\", PADDING, \"OS_VERSION\", a, b, c);\n\n        y = (patch_level >> 4) + 2000;\n        m = patch_level & 0xf;\n        fprintf(stderr, \"%-*s [%d-%02d]\\n\", PADDING, \"OS_PATCH_LEVEL\", y, m);\n    }\n\n    fprintf(stderr, \"%-*s [%u]\\n\", PADDING, \"PAGESIZE\", page_size());\n    if (char *n = name()) {\n        fprintf(stderr, \"%-*s [%s]\\n\", PADDING, \"NAME\", n);\n    }\n    fprintf(stderr, \"%-*s [%.*s%.*s]\\n\", PADDING, \"CMDLINE\",\n            BOOT_ARGS_SIZE, cmdline(), BOOT_EXTRA_ARGS_SIZE, extra_cmdline());\n    if (char *checksum = id()) {\n        fprintf(stderr, \"%-*s [\", PADDING, \"CHECKSUM\");\n        for (int i = 0; i < SHA256_DIGEST_SIZE; ++i)\n            fprintf(stderr, \"%02hhx\", checksum[i]);\n        fprintf(stderr, \"]\\n\");\n    }\n}\n\nvoid dyn_img_hdr::dump_hdr_file() {\n    FILE *fp = xfopen(HEADER_FILE, \"w\");\n    if (name())\n        fprintf(fp, \"name=%s\\n\", name());\n    fprintf(fp, \"cmdline=%.*s%.*s\\n\", BOOT_ARGS_SIZE, cmdline(), BOOT_EXTRA_ARGS_SIZE, extra_cmdline());\n    uint32_t ver = os_version();\n    if (ver) {\n        int a, b, c, y, m;\n        int version, patch_level;\n        version = ver >> 11;\n        patch_level = ver & 0x7ff;\n\n        a = (version >> 14) & 0x7f;\n        b = (version >> 7) & 0x7f;\n        c = version & 0x7f;\n        fprintf(fp, \"os_version=%d.%d.%d\\n\", a, b, c);\n\n        y = (patch_level >> 4) + 2000;\n        m = patch_level & 0xf;\n        fprintf(fp, \"os_patch_level=%d-%02d\\n\", y, m);\n    }\n    fclose(fp);\n}\n\nvoid dyn_img_hdr::load_hdr_file() {\n    parse_prop_file(HEADER_FILE, [=](string_view key, string_view value) -> bool {\n        if (key == \"name\" && name()) {\n            memset(name(), 0, 16);\n            memcpy(name(), value.data(), value.length() > 15 ? 15 : value.length());\n        } else if (key == \"cmdline\") {\n            memset(cmdline(), 0, BOOT_ARGS_SIZE);\n            memset(extra_cmdline(), 0, BOOT_EXTRA_ARGS_SIZE);\n            if (value.length() > BOOT_ARGS_SIZE) {\n                memcpy(cmdline(), value.data(), BOOT_ARGS_SIZE);\n                auto len = std::min(value.length() - BOOT_ARGS_SIZE, (size_t) BOOT_EXTRA_ARGS_SIZE);\n                memcpy(extra_cmdline(), &value[BOOT_ARGS_SIZE], len);\n            } else {\n                memcpy(cmdline(), value.data(), value.length());\n            }\n        } else if (key == \"os_version\") {\n            int patch_level = os_version() & 0x7ff;\n            int a, b, c;\n            sscanf(value.data(), \"%d.%d.%d\", &a, &b, &c);\n            os_version() = (((a << 14) | (b << 7) | c) << 11) | patch_level;\n        } else if (key == \"os_patch_level\") {\n            int os_ver = os_version() >> 11;\n            int y, m;\n            sscanf(value.data(), \"%d-%d\", &y, &m);\n            y -= 2000;\n            os_version() = (os_ver << 11) | (y << 4) | m;\n        }\n        return true;\n    });\n}\n\nboot_img::boot_img(const char *image) : map(image) {\n    fprintf(stderr, \"Parsing image: [%s]\\n\", image);\n    for (const uint8_t *addr = map.buf; addr < map.buf + map.sz; ++addr) {\n        format_t fmt = check_fmt(addr, map.sz);\n        switch (fmt) {\n        case CHROMEOS:\n            // chromeos require external signing\n            flags[CHROMEOS_FLAG] = true;\n            addr += 65535;\n            break;\n        case DHTB:\n            flags[DHTB_FLAG] = true;\n            flags[SEANDROID_FLAG] = true;\n            fprintf(stderr, \"DHTB_HDR\\n\");\n            addr += sizeof(dhtb_hdr) - 1;\n            break;\n        case BLOB_FMT:\n            flags[BLOB_FLAG] = true;\n            fprintf(stderr, \"TEGRA_BLOB\\n\");\n            addr += sizeof(blob_hdr) - 1;\n            break;\n        case AOSP:\n        case AOSP_VENDOR:\n            parse_image(addr, fmt);\n            return;\n        default:\n            break;\n        }\n    }\n    exit(1);\n}\n\nboot_img::~boot_img() {\n    delete hdr;\n}\n\nstatic int find_dtb_offset(const uint8_t *buf, unsigned sz) {\n    const uint8_t * const end = buf + sz;\n\n    for (auto curr = buf; curr < end; curr += sizeof(fdt_header)) {\n        curr = static_cast<uint8_t*>(memmem(curr, end - curr, DTB_MAGIC, sizeof(fdt32_t)));\n        if (curr == nullptr)\n            return -1;\n\n        auto fdt_hdr = reinterpret_cast<const fdt_header *>(curr);\n\n        // Check that fdt_header.totalsize does not overflow kernel image size\n        uint32_t totalsize = fdt32_to_cpu(fdt_hdr->totalsize);\n        if (totalsize > end - curr)\n            continue;\n\n        // Check that fdt_header.off_dt_struct does not overflow kernel image size\n        uint32_t off_dt_struct = fdt32_to_cpu(fdt_hdr->off_dt_struct);\n        if (off_dt_struct > end - curr)\n            continue;\n\n        // Check that fdt_node_header.tag of first node is FDT_BEGIN_NODE\n        auto fdt_node_hdr = reinterpret_cast<const fdt_node_header *>(curr + off_dt_struct);\n        if (fdt32_to_cpu(fdt_node_hdr->tag) != FDT_BEGIN_NODE)\n            continue;\n\n        return curr - buf;\n    }\n    return -1;\n}\n\nstatic format_t check_fmt_lg(const uint8_t *buf, unsigned sz) {\n    format_t fmt = check_fmt(buf, sz);\n    if (fmt == LZ4_LEGACY) {\n        // We need to check if it is LZ4_LG\n        uint32_t off = 4;\n        uint32_t block_sz;\n        while (off + sizeof(block_sz) <= sz) {\n            memcpy(&block_sz, buf + off, sizeof(block_sz));\n            off += sizeof(block_sz);\n            if (off + block_sz > sz)\n                return LZ4_LG;\n            off += block_sz;\n        }\n    }\n    return fmt;\n}\n\n#define CMD_MATCH(s) BUFFER_MATCH(h->cmdline, s)\n\ndyn_img_hdr *boot_img::create_hdr(const uint8_t *addr, format_t type) {\n    if (type == AOSP_VENDOR) {\n        fprintf(stderr, \"VENDOR_BOOT_HDR\\n\");\n        auto h = reinterpret_cast<const boot_img_hdr_vnd_v3*>(addr);\n        hdr_addr = addr;\n        switch (h->header_version) {\n        case 4:\n            return new dyn_img_vnd_v4(addr);\n        default:\n            return new dyn_img_vnd_v3(addr);\n        }\n    }\n\n    auto h = reinterpret_cast<const boot_img_hdr_v0*>(addr);\n\n    if (h->page_size >= 0x02000000) {\n        fprintf(stderr, \"PXA_BOOT_HDR\\n\");\n        hdr_addr = addr;\n        return new dyn_img_pxa(addr);\n    }\n\n    auto make_hdr = [](const uint8_t *ptr) -> dyn_img_hdr * {\n        auto h = reinterpret_cast<const boot_img_hdr_v0*>(ptr);\n        switch (h->header_version) {\n        case 1:\n            return new dyn_img_v1(ptr);\n        case 2:\n            return new dyn_img_v2(ptr);\n        case 3:\n            return new dyn_img_v3(ptr);\n        case 4:\n            return new dyn_img_v4(ptr);\n        default:\n            return new dyn_img_v0(ptr);\n        }\n    };\n\n    // For NOOKHD and ACCLAIM, the entire boot image is shifted by a fixed offset.\n    // For AMONET, only the header is internally shifted by a fixed offset.\n\n    if (BUFFER_CONTAIN(addr, AMONET_MICROLOADER_SZ, AMONET_MICROLOADER_MAGIC) &&\n        BUFFER_MATCH(addr + AMONET_MICROLOADER_SZ, BOOT_MAGIC)) {\n        flags[AMONET_FLAG] = true;\n        fprintf(stderr, \"AMONET_MICROLOADER\\n\");\n\n        // The real header is shifted, copy to temporary buffer\n        h = reinterpret_cast<const boot_img_hdr_v0*>(addr + AMONET_MICROLOADER_SZ);\n        auto real_hdr_sz = h->page_size - AMONET_MICROLOADER_SZ;\n        auto buf = make_unique<uint8_t[]>(h->page_size);\n        memcpy(buf.get(), h, real_hdr_sz);\n\n        hdr_addr = addr;\n        return make_hdr(buf.get());\n    }\n\n    if (CMD_MATCH(NOOKHD_RL_MAGIC) ||\n        CMD_MATCH(NOOKHD_GL_MAGIC) ||\n        CMD_MATCH(NOOKHD_GR_MAGIC) ||\n        CMD_MATCH(NOOKHD_EB_MAGIC) ||\n        CMD_MATCH(NOOKHD_ER_MAGIC)) {\n        flags[NOOKHD_FLAG] = true;\n        fprintf(stderr, \"NOOKHD_LOADER\\n\");\n        addr += NOOKHD_PRE_HEADER_SZ;\n    } else if (BUFFER_MATCH(h->name, ACCLAIM_MAGIC)) {\n        flags[ACCLAIM_FLAG] = true;\n        fprintf(stderr, \"ACCLAIM_LOADER\\n\");\n        addr += ACCLAIM_PRE_HEADER_SZ;\n    }\n\n    // addr could be adjusted\n    hdr_addr = addr;\n    return make_hdr(addr);\n}\n\n#define get_block(name)                 \\\nname = hdr_addr + off;                  \\\noff += hdr->name##_size();              \\\noff = align_to(off, hdr->page_size());\n\n#define get_ignore(name)                                            \\\nif (hdr->name##_size()) {                                           \\\n    auto blk_sz = align_to(hdr->name##_size(), hdr->page_size());   \\\n    ignore_size += blk_sz;                                          \\\n    off += blk_sz;                                                  \\\n}\n\nvoid boot_img::parse_image(const uint8_t *addr, format_t type) {\n    hdr = create_hdr(addr, type);\n\n    if (char *id = hdr->id()) {\n        for (int i = SHA_DIGEST_SIZE + 4; i < SHA256_DIGEST_SIZE; ++i) {\n            if (id[i]) {\n                flags[SHA256_FLAG] = true;\n                break;\n            }\n        }\n    }\n\n    hdr->print();\n\n    size_t off = hdr->hdr_space();\n    get_block(kernel);\n    get_block(ramdisk);\n    get_block(second);\n    get_block(extra);\n    get_block(recovery_dtbo);\n    get_block(dtb);\n\n    ignore = hdr_addr + off;\n    get_ignore(signature)\n    get_ignore(vendor_ramdisk_table)\n    get_ignore(bootconfig)\n\n    if (auto size = hdr->kernel_size()) {\n        if (int dtb_off = find_dtb_offset(kernel, size); dtb_off > 0) {\n            kernel_dtb = kernel + dtb_off;\n            hdr->kernel_dt_size = size - dtb_off;\n            hdr->kernel_size() = dtb_off;\n            fprintf(stderr, \"%-*s [%u]\\n\", PADDING, \"KERNEL_DTB_SZ\", hdr->kernel_dt_size);\n        }\n\n        k_fmt = check_fmt_lg(kernel, hdr->kernel_size());\n        if (k_fmt == MTK) {\n            fprintf(stderr, \"MTK_KERNEL_HDR\\n\");\n            flags[MTK_KERNEL] = true;\n            k_hdr = reinterpret_cast<const mtk_hdr *>(kernel);\n            fprintf(stderr, \"%-*s [%u]\\n\", PADDING, \"SIZE\", k_hdr->size);\n            fprintf(stderr, \"%-*s [%s]\\n\", PADDING, \"NAME\", k_hdr->name);\n            kernel += sizeof(mtk_hdr);\n            hdr->kernel_size() -= sizeof(mtk_hdr);\n            k_fmt = check_fmt_lg(kernel, hdr->kernel_size());\n        }\n        if (k_fmt == ZIMAGE) {\n            z_hdr = reinterpret_cast<const zimage_hdr *>(kernel);\n            if (void *gzip_offset = memmem(kernel, hdr->kernel_size(), GZIP1_MAGIC \"\\x08\\x00\", 4)) {\n                fprintf(stderr, \"ZIMAGE_KERNEL\\n\");\n                z_info.hdr_sz = (uint8_t *) gzip_offset - kernel;\n\n                // Find end of piggy\n                uint32_t zImage_size = z_hdr->end - z_hdr->start;\n                uint32_t piggy_end = zImage_size;\n                uint32_t offsets[16];\n                memcpy(offsets, kernel + zImage_size - sizeof(offsets), sizeof(offsets));\n                for (int i = 15; i >= 0; --i) {\n                    if (offsets[i] > (zImage_size - 0xFF) && offsets[i] < zImage_size) {\n                        piggy_end = offsets[i];\n                        break;\n                    }\n                }\n\n                if (piggy_end == zImage_size) {\n                    fprintf(stderr, \"! Could not find end of zImage piggy, keeping raw kernel\\n\");\n                } else {\n                    flags[ZIMAGE_KERNEL] = true;\n                    z_info.tail = kernel + piggy_end;\n                    z_info.tail_sz = hdr->kernel_size() - piggy_end;\n                    kernel += z_info.hdr_sz;\n                    hdr->kernel_size() = piggy_end - z_info.hdr_sz;\n                    k_fmt = check_fmt_lg(kernel, hdr->kernel_size());\n                }\n            } else {\n                fprintf(stderr, \"! Could not find zImage gzip piggy, keeping raw kernel\\n\");\n            }\n        }\n        fprintf(stderr, \"%-*s [%s]\\n\", PADDING, \"KERNEL_FMT\", fmt2name[k_fmt]);\n    }\n    if (auto size = hdr->ramdisk_size()) {\n        if (hdr->is_vendor && hdr->header_version() >= 4) {\n            // v4 vendor boot contains multiple ramdisks\n            // Do not try to mess with it for now\n            r_fmt = UNKNOWN;\n        } else {\n            r_fmt = check_fmt_lg(ramdisk, size);\n        }\n        if (r_fmt == MTK) {\n            fprintf(stderr, \"MTK_RAMDISK_HDR\\n\");\n            flags[MTK_RAMDISK] = true;\n            r_hdr = reinterpret_cast<const mtk_hdr *>(ramdisk);\n            fprintf(stderr, \"%-*s [%u]\\n\", PADDING, \"SIZE\", r_hdr->size);\n            fprintf(stderr, \"%-*s [%s]\\n\", PADDING, \"NAME\", r_hdr->name);\n            ramdisk += sizeof(mtk_hdr);\n            hdr->ramdisk_size() -= sizeof(mtk_hdr);\n            r_fmt = check_fmt_lg(ramdisk, hdr->ramdisk_size());\n        }\n        fprintf(stderr, \"%-*s [%s]\\n\", PADDING, \"RAMDISK_FMT\", fmt2name[r_fmt]);\n    }\n    if (auto size = hdr->extra_size()) {\n        e_fmt = check_fmt_lg(extra, size);\n        fprintf(stderr, \"%-*s [%s]\\n\", PADDING, \"EXTRA_FMT\", fmt2name[e_fmt]);\n    }\n\n    if (addr + off < map.buf + map.sz) {\n        tail = addr + off;\n        tail_size = map.buf + map.sz - tail;\n\n        // Check special flags\n        if (tail_size >= 16 && BUFFER_MATCH(tail, SEANDROID_MAGIC)) {\n            fprintf(stderr, \"SAMSUNG_SEANDROID\\n\");\n            flags[SEANDROID_FLAG] = true;\n        } else if (tail_size >= 16 && BUFFER_MATCH(tail, LG_BUMP_MAGIC)) {\n            fprintf(stderr, \"LG_BUMP_IMAGE\\n\");\n            flags[LG_BUMP_FLAG] = true;\n        }\n\n        // Find AVB footer\n        const void *footer = tail + tail_size - sizeof(AvbFooter);\n        if (BUFFER_MATCH(footer, AVB_FOOTER_MAGIC)) {\n            avb_footer = reinterpret_cast<const AvbFooter*>(footer);\n            // Double check if meta header exists\n            const void *meta = hdr_addr + __builtin_bswap64(avb_footer->vbmeta_offset);\n            if (BUFFER_MATCH(meta, AVB_MAGIC)) {\n                fprintf(stderr, \"VBMETA\\n\");\n                flags[AVB_FLAG] = true;\n                vbmeta = reinterpret_cast<const AvbVBMetaImageHeader*>(meta);\n            }\n        }\n    }\n}\n\nint split_image_dtb(const char *filename) {\n    auto img = mmap_data(filename);\n\n    if (int off = find_dtb_offset(img.buf, img.sz); off > 0) {\n        format_t fmt = check_fmt_lg(img.buf, img.sz);\n        if (COMPRESSED(fmt)) {\n            int fd = creat(KERNEL_FILE, 0644);\n            decompress(fmt, fd, img.buf, off);\n            close(fd);\n        } else {\n            dump(img.buf, off, KERNEL_FILE);\n        }\n        dump(img.buf + off, img.sz - off, KER_DTB_FILE);\n        return 0;\n    } else {\n        fprintf(stderr, \"Cannot find DTB in %s\\n\", filename);\n        return 1;\n    }\n}\n\nint unpack(const char *image, bool skip_decomp, bool hdr) {\n    boot_img boot(image);\n\n    if (hdr)\n        boot.hdr->dump_hdr_file();\n\n    // Dump kernel\n    if (!skip_decomp && COMPRESSED(boot.k_fmt)) {\n        if (boot.hdr->kernel_size() != 0) {\n            int fd = creat(KERNEL_FILE, 0644);\n            decompress(boot.k_fmt, fd, boot.kernel, boot.hdr->kernel_size());\n            close(fd);\n        }\n    } else {\n        dump(boot.kernel, boot.hdr->kernel_size(), KERNEL_FILE);\n    }\n\n    // Dump kernel_dtb\n    dump(boot.kernel_dtb, boot.hdr->kernel_dt_size, KER_DTB_FILE);\n\n    // Dump ramdisk\n    if (!skip_decomp && COMPRESSED(boot.r_fmt)) {\n        if (boot.hdr->ramdisk_size() != 0) {\n            int fd = creat(RAMDISK_FILE, 0644);\n            decompress(boot.r_fmt, fd, boot.ramdisk, boot.hdr->ramdisk_size());\n            close(fd);\n        }\n    } else {\n        dump(boot.ramdisk, boot.hdr->ramdisk_size(), RAMDISK_FILE);\n    }\n\n    // Dump second\n    dump(boot.second, boot.hdr->second_size(), SECOND_FILE);\n\n    // Dump extra\n    if (!skip_decomp && COMPRESSED(boot.e_fmt)) {\n        if (boot.hdr->extra_size() != 0) {\n            int fd = creat(EXTRA_FILE, 0644);\n            decompress(boot.e_fmt, fd, boot.extra, boot.hdr->extra_size());\n            close(fd);\n        }\n    } else {\n        dump(boot.extra, boot.hdr->extra_size(), EXTRA_FILE);\n    }\n\n    // Dump recovery_dtbo\n    dump(boot.recovery_dtbo, boot.hdr->recovery_dtbo_size(), RECV_DTBO_FILE);\n\n    // Dump dtb\n    dump(boot.dtb, boot.hdr->dtb_size(), DTB_FILE);\n\n    return boot.flags[CHROMEOS_FLAG] ? 2 : 0;\n}\n\n#define file_align_with(page_size) \\\nwrite_zero(fd, align_padding(lseek(fd, 0, SEEK_CUR) - off.header, page_size))\n\n#define file_align() file_align_with(boot.hdr->page_size())\n\nvoid repack(const char *src_img, const char *out_img, bool skip_comp) {\n    const boot_img boot(src_img);\n    fprintf(stderr, \"Repack to image: [%s]\\n\", out_img);\n\n    struct {\n        uint32_t header;\n        uint32_t kernel;\n        uint32_t ramdisk;\n        uint32_t second;\n        uint32_t extra;\n        uint32_t dtb;\n        uint32_t total;\n        uint32_t vbmeta;\n    } off{};\n\n    // Create a new boot header and reset sizes\n    auto hdr = boot.hdr->clone();\n    hdr->kernel_size() = 0;\n    hdr->ramdisk_size() = 0;\n    hdr->second_size() = 0;\n    hdr->dtb_size() = 0;\n    hdr->kernel_dt_size = 0;\n\n    if (access(HEADER_FILE, R_OK) == 0)\n        hdr->load_hdr_file();\n\n    /***************\n     * Write blocks\n     ***************/\n\n    // Create new image\n    int fd = creat(out_img, 0644);\n\n    if (boot.flags[DHTB_FLAG]) {\n        // Skip DHTB header\n        write_zero(fd, sizeof(dhtb_hdr));\n    } else if (boot.flags[BLOB_FLAG]) {\n        xwrite(fd, boot.map.buf, sizeof(blob_hdr));\n    } else if (boot.flags[NOOKHD_FLAG]) {\n        xwrite(fd, boot.map.buf, NOOKHD_PRE_HEADER_SZ);\n    } else if (boot.flags[ACCLAIM_FLAG]) {\n        xwrite(fd, boot.map.buf, ACCLAIM_PRE_HEADER_SZ);\n    }\n\n    // Copy raw header\n    off.header = lseek(fd, 0, SEEK_CUR);\n    xwrite(fd, boot.hdr_addr, hdr->hdr_space());\n\n    // kernel\n    off.kernel = lseek(fd, 0, SEEK_CUR);\n    if (boot.flags[MTK_KERNEL]) {\n        // Copy MTK headers\n        xwrite(fd, boot.k_hdr, sizeof(mtk_hdr));\n    }\n    if (boot.flags[ZIMAGE_KERNEL]) {\n        // Copy zImage headers\n        xwrite(fd, boot.z_hdr, boot.z_info.hdr_sz);\n    }\n    if (access(KERNEL_FILE, R_OK) == 0) {\n        auto m = mmap_data(KERNEL_FILE);\n        if (!skip_comp && !COMPRESSED_ANY(check_fmt(m.buf, m.sz)) && COMPRESSED(boot.k_fmt)) {\n            // Always use zopfli for zImage compression\n            auto fmt = (boot.flags[ZIMAGE_KERNEL] && boot.k_fmt == GZIP) ? ZOPFLI : boot.k_fmt;\n            hdr->kernel_size() = compress(fmt, fd, m.buf, m.sz);\n        } else {\n            hdr->kernel_size() = xwrite(fd, m.buf, m.sz);\n        }\n\n        if (boot.flags[ZIMAGE_KERNEL]) {\n            if (hdr->kernel_size() > boot.hdr->kernel_size()) {\n                fprintf(stderr, \"! Recompressed kernel is too large, using original kernel\\n\");\n                ftruncate64(fd, lseek64(fd, - (off64_t) hdr->kernel_size(), SEEK_CUR));\n                xwrite(fd, boot.kernel, boot.hdr->kernel_size());\n            } else if (!skip_comp) {\n                // Pad zeros to make sure the zImage file size does not change\n                // Also ensure the last 4 bytes are the uncompressed vmlinux size\n                uint32_t sz = m.sz;\n                write_zero(fd, boot.hdr->kernel_size() - hdr->kernel_size() - sizeof(sz));\n                xwrite(fd, &sz, sizeof(sz));\n            }\n\n            // zImage size shall remain the same\n            hdr->kernel_size() = boot.hdr->kernel_size();\n        }\n    } else if (boot.hdr->kernel_size() != 0) {\n        xwrite(fd, boot.kernel, boot.hdr->kernel_size());\n        hdr->kernel_size() = boot.hdr->kernel_size();\n    }\n    if (boot.flags[ZIMAGE_KERNEL]) {\n        // Copy zImage tail and adjust size accordingly\n        hdr->kernel_size() += boot.z_info.hdr_sz;\n        hdr->kernel_size() += xwrite(fd, boot.z_info.tail, boot.z_info.tail_sz);\n    }\n\n    // kernel dtb\n    if (access(KER_DTB_FILE, R_OK) == 0)\n        hdr->kernel_size() += restore(fd, KER_DTB_FILE);\n    file_align();\n\n    // ramdisk\n    off.ramdisk = lseek(fd, 0, SEEK_CUR);\n    if (boot.flags[MTK_RAMDISK]) {\n        // Copy MTK headers\n        xwrite(fd, boot.r_hdr, sizeof(mtk_hdr));\n    }\n    if (access(RAMDISK_FILE, R_OK) == 0) {\n        auto m = mmap_data(RAMDISK_FILE);\n        auto r_fmt = boot.r_fmt;\n        if (!skip_comp && !hdr->is_vendor && hdr->header_version() == 4 && r_fmt != LZ4_LEGACY) {\n            // A v4 boot image ramdisk will have to be merged with other vendor ramdisks,\n            // and they have to use the exact same compression method. v4 GKIs are required to\n            // use lz4 (legacy), so hardcode the format here.\n            fprintf(stderr, \"RAMDISK_FMT: [%s] -> [%s]\\n\", fmt2name[r_fmt], fmt2name[LZ4_LEGACY]);\n            r_fmt = LZ4_LEGACY;\n        }\n        if (!skip_comp && !COMPRESSED_ANY(check_fmt(m.buf, m.sz)) && COMPRESSED(r_fmt)) {\n            hdr->ramdisk_size() = compress(r_fmt, fd, m.buf, m.sz);\n        } else {\n            hdr->ramdisk_size() = xwrite(fd, m.buf, m.sz);\n        }\n        file_align();\n    }\n\n    // second\n    off.second = lseek(fd, 0, SEEK_CUR);\n    if (access(SECOND_FILE, R_OK) == 0) {\n        hdr->second_size() = restore(fd, SECOND_FILE);\n        file_align();\n    }\n\n    // extra\n    off.extra = lseek(fd, 0, SEEK_CUR);\n    if (access(EXTRA_FILE, R_OK) == 0) {\n        auto m = mmap_data(EXTRA_FILE);\n        if (!skip_comp && !COMPRESSED_ANY(check_fmt(m.buf, m.sz)) && COMPRESSED(boot.e_fmt)) {\n            hdr->extra_size() = compress(boot.e_fmt, fd, m.buf, m.sz);\n        } else {\n            hdr->extra_size() = xwrite(fd, m.buf, m.sz);\n        }\n        file_align();\n    }\n\n    // recovery_dtbo\n    if (access(RECV_DTBO_FILE, R_OK) == 0) {\n        hdr->recovery_dtbo_offset() = lseek(fd, 0, SEEK_CUR);\n        hdr->recovery_dtbo_size() = restore(fd, RECV_DTBO_FILE);\n        file_align();\n    }\n\n    // dtb\n    off.dtb = lseek(fd, 0, SEEK_CUR);\n    if (access(DTB_FILE, R_OK) == 0) {\n        hdr->dtb_size() = restore(fd, DTB_FILE);\n        file_align();\n    }\n\n    // Directly copy ignored blobs\n    if (boot.ignore_size) {\n        // ignore_size should already be aligned\n        xwrite(fd, boot.ignore, boot.ignore_size);\n    }\n\n    // Proprietary stuffs\n    if (boot.flags[SEANDROID_FLAG]) {\n        xwrite(fd, SEANDROID_MAGIC, 16);\n        if (boot.flags[DHTB_FLAG]) {\n            xwrite(fd, \"\\xFF\\xFF\\xFF\\xFF\", 4);\n        }\n    } else if (boot.flags[LG_BUMP_FLAG]) {\n        xwrite(fd, LG_BUMP_MAGIC, 16);\n    }\n\n    off.total = lseek(fd, 0, SEEK_CUR);\n    file_align();\n\n    // vbmeta\n    if (boot.flags[AVB_FLAG]) {\n        // According to avbtool.py, if the input is not an Android sparse image\n        // (which boot images are not), the default block size is 4096\n        file_align_with(4096);\n        off.vbmeta = lseek(fd, 0, SEEK_CUR);\n        uint64_t vbmeta_size = __builtin_bswap64(boot.avb_footer->vbmeta_size);\n        xwrite(fd, boot.vbmeta, vbmeta_size);\n    }\n\n    // Pad image to original size if not chromeos (as it requires post processing)\n    if (!boot.flags[CHROMEOS_FLAG]) {\n        off_t current = lseek(fd, 0, SEEK_CUR);\n        if (current < boot.map.sz) {\n            write_zero(fd, boot.map.sz - current);\n        }\n    }\n\n    close(fd);\n\n    /******************\n     * Patch the image\n     ******************/\n\n    // Map output image as rw\n    auto out = mmap_data(out_img, true);\n\n    // MTK headers\n    if (boot.flags[MTK_KERNEL]) {\n        auto m_hdr = reinterpret_cast<mtk_hdr *>(out.buf + off.kernel);\n        m_hdr->size = hdr->kernel_size();\n        hdr->kernel_size() += sizeof(mtk_hdr);\n    }\n    if (boot.flags[MTK_RAMDISK]) {\n        auto m_hdr = reinterpret_cast<mtk_hdr *>(out.buf + off.ramdisk);\n        m_hdr->size = hdr->ramdisk_size();\n        hdr->ramdisk_size() += sizeof(mtk_hdr);\n    }\n\n    // Make sure header size matches\n    hdr->header_size() = hdr->hdr_size();\n\n    // Update checksum\n    if (char *id = hdr->id()) {\n        HASH_CTX ctx;\n        boot.flags[SHA256_FLAG] ? SHA256_init(&ctx) : SHA_init(&ctx);\n        uint32_t size = hdr->kernel_size();\n        HASH_update(&ctx, out.buf + off.kernel, size);\n        HASH_update(&ctx, &size, sizeof(size));\n        size = hdr->ramdisk_size();\n        HASH_update(&ctx, out.buf + off.ramdisk, size);\n        HASH_update(&ctx, &size, sizeof(size));\n        size = hdr->second_size();\n        HASH_update(&ctx, out.buf + off.second, size);\n        HASH_update(&ctx, &size, sizeof(size));\n        size = hdr->extra_size();\n        if (size) {\n            HASH_update(&ctx, out.buf + off.extra, size);\n            HASH_update(&ctx, &size, sizeof(size));\n        }\n        uint32_t ver = hdr->header_version();\n        if (ver == 1 || ver == 2) {\n            size = hdr->recovery_dtbo_size();\n            HASH_update(&ctx, out.buf + hdr->recovery_dtbo_offset(), size);\n            HASH_update(&ctx, &size, sizeof(size));\n        }\n        if (ver == 2) {\n            size = hdr->dtb_size();\n            HASH_update(&ctx, out.buf + off.dtb, size);\n            HASH_update(&ctx, &size, sizeof(size));\n        }\n        memset(id, 0, BOOT_ID_SIZE);\n        memcpy(id, HASH_final(&ctx), boot.flags[SHA256_FLAG] ? SHA256_DIGEST_SIZE : SHA_DIGEST_SIZE);\n    }\n\n    // Print new header info\n    hdr->print();\n\n    // Copy main header\n    if (boot.flags[AMONET_FLAG]) {\n        auto real_hdr_sz = std::min(hdr->hdr_space() - AMONET_MICROLOADER_SZ, hdr->hdr_size());\n        memcpy(out.buf + off.header + AMONET_MICROLOADER_SZ, hdr->raw_hdr(), real_hdr_sz);\n    } else {\n        memcpy(out.buf + off.header, hdr->raw_hdr(), hdr->hdr_size());\n    }\n\n    if (boot.flags[AVB_FLAG]) {\n        // Copy and patch AVB structures\n        auto footer = reinterpret_cast<AvbFooter*>(out.buf + out.sz - sizeof(AvbFooter));\n        auto vbmeta = reinterpret_cast<AvbVBMetaImageHeader*>(out.buf + off.vbmeta);\n        memcpy(footer, boot.avb_footer, sizeof(AvbFooter));\n        footer->original_image_size = __builtin_bswap64(off.total);\n        footer->vbmeta_offset = __builtin_bswap64(off.vbmeta);\n        if (check_env(\"PATCHVBMETAFLAG\")) {\n            vbmeta->flags = __builtin_bswap32(3);\n        }\n    }\n\n    if (boot.flags[DHTB_FLAG]) {\n        // DHTB header\n        auto d_hdr = reinterpret_cast<dhtb_hdr *>(out.buf);\n        memcpy(d_hdr, DHTB_MAGIC, 8);\n        d_hdr->size = off.total - sizeof(dhtb_hdr);\n        SHA256_hash(out.buf + sizeof(dhtb_hdr), d_hdr->size, d_hdr->checksum);\n    } else if (boot.flags[BLOB_FLAG]) {\n        // Blob header\n        auto b_hdr = reinterpret_cast<blob_hdr *>(out.buf);\n        b_hdr->size = off.total - sizeof(blob_hdr);\n    }\n}\n"
  },
  {
    "path": "bootimg.hpp",
    "content": "#pragma once\r\n\r\n#include <stdint.h>\r\n#include <utility>\r\n#include <bitset>\r\n#include \"format.hpp\"\r\n\r\n/******************\r\n * Special Headers\r\n *****************/\r\n\r\nstruct mtk_hdr {\r\n    uint32_t magic;         /* MTK magic */\r\n    uint32_t size;          /* Size of the content */\r\n    char name[32];          /* The type of the header */\r\n\r\n    char padding[472];      /* Padding to 512 bytes */\r\n} __attribute__((packed));\r\n\r\nstruct dhtb_hdr {\r\n    char magic[8];          /* DHTB magic */\r\n    uint8_t checksum[40];   /* Payload SHA256, whole image + SEANDROIDENFORCE + 0xFFFFFFFF */\r\n    uint32_t size;          /* Payload size, whole image + SEANDROIDENFORCE + 0xFFFFFFFF */\r\n\r\n    char padding[460];      /* Padding to 512 bytes */\r\n} __attribute__((packed));\r\n\r\nstruct blob_hdr {\r\n    char secure_magic[20];  /* \"-SIGNED-BY-SIGNBLOB-\" */\r\n    uint32_t datalen;       /* 0x00000000 */\r\n    uint32_t signature;     /* 0x00000000 */\r\n    char magic[16];         /* \"MSM-RADIO-UPDATE\" */\r\n    uint32_t hdr_version;   /* 0x00010000 */\r\n    uint32_t hdr_size;      /* Size of header */\r\n    uint32_t part_offset;   /* Same as size */\r\n    uint32_t num_parts;     /* Number of partitions */\r\n    uint32_t unknown[7];    /* All 0x00000000 */\r\n    char name[4];           /* Name of partition */\r\n    uint32_t offset;        /* offset in blob where this partition starts */\r\n    uint32_t size;          /* Size of data */\r\n    uint32_t version;       /* 0x00000001 */\r\n} __attribute__((packed));\r\n\r\nstruct zimage_hdr {\r\n    uint32_t code[9];\r\n    uint32_t magic;      /* zImage magic */\r\n    uint32_t start;      /* absolute load/run zImage address */\r\n    uint32_t end;        /* zImage end address */\r\n    uint32_t endian;     /* endianness flag */\r\n    // There could be more fields, but we don't care\r\n} __attribute__((packed));\r\n\r\n/**************\r\n * AVB Headers\r\n **************/\r\n\r\n#define AVB_FOOTER_MAGIC_LEN 4\r\n#define AVB_MAGIC_LEN 4\r\n#define AVB_RELEASE_STRING_SIZE 48\r\n\r\n// https://android.googlesource.com/platform/external/avb/+/refs/heads/android11-release/libavb/avb_footer.h\r\nstruct AvbFooter {\r\n    uint8_t magic[AVB_FOOTER_MAGIC_LEN];\r\n    uint32_t version_major;\r\n    uint32_t version_minor;\r\n    uint64_t original_image_size;\r\n    uint64_t vbmeta_offset;\r\n    uint64_t vbmeta_size;\r\n    uint8_t reserved[28];\r\n} __attribute__((packed));\r\n\r\n// https://android.googlesource.com/platform/external/avb/+/refs/heads/android11-release/libavb/avb_vbmeta_image.h\r\nstruct AvbVBMetaImageHeader {\r\n    uint8_t magic[AVB_MAGIC_LEN];\r\n    uint32_t required_libavb_version_major;\r\n    uint32_t required_libavb_version_minor;\r\n    uint64_t authentication_data_block_size;\r\n    uint64_t auxiliary_data_block_size;\r\n    uint32_t algorithm_type;\r\n    uint64_t hash_offset;\r\n    uint64_t hash_size;\r\n    uint64_t signature_offset;\r\n    uint64_t signature_size;\r\n    uint64_t public_key_offset;\r\n    uint64_t public_key_size;\r\n    uint64_t public_key_metadata_offset;\r\n    uint64_t public_key_metadata_size;\r\n    uint64_t descriptors_offset;\r\n    uint64_t descriptors_size;\r\n    uint64_t rollback_index;\r\n    uint32_t flags;\r\n    uint32_t rollback_index_location;\r\n    uint8_t release_string[AVB_RELEASE_STRING_SIZE];\r\n    uint8_t reserved[80];\r\n} __attribute__((packed));\r\n\r\n/*********************\r\n * Boot Image Headers\r\n *********************/\r\n\r\n// https://android.googlesource.com/platform/system/tools/mkbootimg/+/refs/heads/android12-release/include/bootimg/bootimg.h\r\n\r\n#define BOOT_MAGIC_SIZE 8\r\n#define BOOT_NAME_SIZE 16\r\n#define BOOT_ID_SIZE 32\r\n#define BOOT_ARGS_SIZE 512\r\n#define BOOT_EXTRA_ARGS_SIZE 1024\r\n#define VENDOR_BOOT_ARGS_SIZE 2048\r\n#define VENDOR_RAMDISK_NAME_SIZE 32\r\n#define VENDOR_RAMDISK_TABLE_ENTRY_BOARD_ID_SIZE 16\r\n\r\n/* When the boot image header has a version of 0 - 2, the structure of the boot\r\n * image is as follows:\r\n *\r\n * +-----------------+\r\n * | boot header     | 1 page\r\n * +-----------------+\r\n * | kernel          | n pages\r\n * +-----------------+\r\n * | ramdisk         | m pages\r\n * +-----------------+\r\n * | second stage    | o pages\r\n * +-----------------+\r\n * | extra blob      | x pages (non standard)\r\n * +-----------------+\r\n * | recovery dtbo   | p pages\r\n * +-----------------+\r\n * | dtb             | q pages\r\n * +-----------------+\r\n *\r\n * n = (kernel_size + page_size - 1) / page_size\r\n * m = (ramdisk_size + page_size - 1) / page_size\r\n * o = (second_size + page_size - 1) / page_size\r\n * p = (recovery_dtbo_size + page_size - 1) / page_size\r\n * q = (dtb_size + page_size - 1) / page_size\r\n * x = (extra_size + page_size - 1) / page_size\r\n */\r\n\r\nstruct boot_img_hdr_v0_common {\r\n    char magic[BOOT_MAGIC_SIZE];\r\n\r\n    uint32_t kernel_size;  /* size in bytes */\r\n    uint32_t kernel_addr;  /* physical load addr */\r\n\r\n    uint32_t ramdisk_size; /* size in bytes */\r\n    uint32_t ramdisk_addr; /* physical load addr */\r\n\r\n    uint32_t second_size;  /* size in bytes */\r\n    uint32_t second_addr;  /* physical load addr */\r\n} __attribute__((packed));\r\n\r\nstruct boot_img_hdr_v0 : public boot_img_hdr_v0_common {\r\n    uint32_t tags_addr;    /* physical addr for kernel tags */\r\n\r\n    // In AOSP headers, this field is used for page size.\r\n    // For Samsung PXA headers, the use of this field is unknown;\r\n    // however, its value is something unrealistic to be treated as page size.\r\n    // We use this fact to determine whether this is an AOSP or PXA header.\r\n    union {\r\n        uint32_t unknown;\r\n        uint32_t page_size;    /* flash page size we assume */\r\n    };\r\n\r\n    // In header v1, this field is used for header version\r\n    // However, on some devices like Samsung, this field is used to store DTB\r\n    // We treat this field differently based on its value\r\n    union {\r\n        uint32_t header_version;  /* the version of the header */\r\n        uint32_t extra_size;      /* extra blob size in bytes */\r\n    };\r\n\r\n    // Operating system version and security patch level.\r\n    // For version \"A.B.C\" and patch level \"Y-M-D\":\r\n    //   (7 bits for each of A, B, C; 7 bits for (Y-2000), 4 bits for M)\r\n    //   os_version = A[31:25] B[24:18] C[17:11] (Y-2000)[10:4] M[3:0]\r\n    uint32_t os_version;\r\n\r\n    char name[BOOT_NAME_SIZE];  /* asciiz product name */\r\n    char cmdline[BOOT_ARGS_SIZE];\r\n    char id[BOOT_ID_SIZE];      /* timestamp / checksum / sha1 / etc */\r\n\r\n    // Supplemental command line data; kept here to maintain\r\n    // binary compatibility with older versions of mkbootimg.\r\n    char extra_cmdline[BOOT_EXTRA_ARGS_SIZE];\r\n} __attribute__((packed));\r\n\r\nstruct boot_img_hdr_v1 : public boot_img_hdr_v0 {\r\n    uint32_t recovery_dtbo_size;    /* size in bytes for recovery DTBO/ACPIO image */\r\n    uint64_t recovery_dtbo_offset;  /* offset to recovery dtbo/acpio in boot image */\r\n    uint32_t header_size;\r\n} __attribute__((packed));\r\n\r\nstruct boot_img_hdr_v2 : public boot_img_hdr_v1 {\r\n    uint32_t dtb_size;  /* size in bytes for DTB image */\r\n    uint64_t dtb_addr;  /* physical load address for DTB image */\r\n} __attribute__((packed));\r\n\r\n// Special Samsung header\r\nstruct boot_img_hdr_pxa : public boot_img_hdr_v0_common {\r\n    uint32_t extra_size;   /* extra blob size in bytes */\r\n    uint32_t unknown;\r\n    uint32_t tags_addr;    /* physical addr for kernel tags */\r\n    uint32_t page_size;    /* flash page size we assume */\r\n\r\n    char name[24];         /* asciiz product name */\r\n    char cmdline[BOOT_ARGS_SIZE];\r\n    char id[BOOT_ID_SIZE]; /* timestamp / checksum / sha1 / etc */\r\n\r\n    char extra_cmdline[BOOT_EXTRA_ARGS_SIZE];\r\n} __attribute__((packed));\r\n\r\n/* When the boot image header has a version of 3 - 4, the structure of the boot\r\n * image is as follows:\r\n *\r\n * +---------------------+\r\n * | boot header         | 4096 bytes\r\n * +---------------------+\r\n * | kernel              | m pages\r\n * +---------------------+\r\n * | ramdisk             | n pages\r\n * +---------------------+\r\n * | boot signature      | g pages\r\n * +---------------------+\r\n *\r\n * m = (kernel_size + 4096 - 1) / 4096\r\n * n = (ramdisk_size + 4096 - 1) / 4096\r\n * g = (signature_size + 4096 - 1) / 4096\r\n *\r\n * Page size is fixed at 4096 bytes.\r\n *\r\n * The structure of the vendor boot image is as follows:\r\n *\r\n * +------------------------+\r\n * | vendor boot header     | o pages\r\n * +------------------------+\r\n * | vendor ramdisk section | p pages\r\n * +------------------------+\r\n * | dtb                    | q pages\r\n * +------------------------+\r\n * | vendor ramdisk table   | r pages\r\n * +------------------------+\r\n * | bootconfig             | s pages\r\n * +------------------------+\r\n *\r\n * o = (2128 + page_size - 1) / page_size\r\n * p = (vendor_ramdisk_size + page_size - 1) / page_size\r\n * q = (dtb_size + page_size - 1) / page_size\r\n * r = (vendor_ramdisk_table_size + page_size - 1) / page_size\r\n * s = (vendor_bootconfig_size + page_size - 1) / page_size\r\n *\r\n * Note that in version 4 of the vendor boot image, multiple vendor ramdisks can\r\n * be included in the vendor boot image. The bootloader can select a subset of\r\n * ramdisks to load at runtime. To help the bootloader select the ramdisks, each\r\n * ramdisk is tagged with a type tag and a set of hardware identifiers\r\n * describing the board, soc or platform that this ramdisk is intended for.\r\n *\r\n * The vendor ramdisk section is consist of multiple ramdisk images concatenated\r\n * one after another, and vendor_ramdisk_size is the size of the section, which\r\n * is the total size of all the ramdisks included in the vendor boot image.\r\n *\r\n * The vendor ramdisk table holds the size, offset, type, name and hardware\r\n * identifiers of each ramdisk. The type field denotes the type of its content.\r\n * The vendor ramdisk names are unique. The hardware identifiers are specified\r\n * in the board_id field in each table entry. The board_id field is consist of a\r\n * vector of unsigned integer words, and the encoding scheme is defined by the\r\n * hardware vendor.\r\n *\r\n * For the different type of ramdisks, there are:\r\n *    - VENDOR_RAMDISK_TYPE_NONE indicates the value is unspecified.\r\n *    - VENDOR_RAMDISK_TYPE_PLATFORM ramdisks contain platform specific bits, so\r\n *      the bootloader should always load these into memory.\r\n *    - VENDOR_RAMDISK_TYPE_RECOVERY ramdisks contain recovery resources, so\r\n *      the bootloader should load these when booting into recovery.\r\n *    - VENDOR_RAMDISK_TYPE_DLKM ramdisks contain dynamic loadable kernel\r\n *      modules.\r\n *\r\n * Version 4 of the vendor boot image also adds a bootconfig section to the end\r\n * of the image. This section contains Boot Configuration parameters known at\r\n * build time. The bootloader is responsible for placing this section directly\r\n * after the generic ramdisk, followed by the bootconfig trailer, before\r\n * entering the kernel.\r\n */\r\n\r\nstruct boot_img_hdr_v3 {\r\n    uint8_t magic[BOOT_MAGIC_SIZE];\r\n\r\n    uint32_t kernel_size;  /* size in bytes */\r\n    uint32_t ramdisk_size; /* size in bytes */\r\n    uint32_t os_version;\r\n    uint32_t header_size;\r\n    uint32_t reserved[4];\r\n\r\n    uint32_t header_version;\r\n\r\n    char cmdline[BOOT_ARGS_SIZE + BOOT_EXTRA_ARGS_SIZE];\r\n} __attribute__((packed));\r\n\r\nstruct boot_img_hdr_vnd_v3 {\r\n    // Must be VENDOR_BOOT_MAGIC.\r\n    uint8_t magic[BOOT_MAGIC_SIZE];\r\n    // Version of the vendor boot image header.\r\n    uint32_t header_version;\r\n    uint32_t page_size;     /* flash page size we assume */\r\n    uint32_t kernel_addr;   /* physical load addr */\r\n    uint32_t ramdisk_addr;  /* physical load addr */\r\n    uint32_t ramdisk_size;  /* size in bytes */\r\n    char cmdline[VENDOR_BOOT_ARGS_SIZE];\r\n    uint32_t tags_addr;     /* physical addr for kernel tags (if required) */\r\n    char name[BOOT_NAME_SIZE]; /* asciiz product name */\r\n    uint32_t header_size;\r\n    uint32_t dtb_size;      /* size in bytes for DTB image */\r\n    uint64_t dtb_addr;      /* physical load address for DTB image */\r\n} __attribute__((packed));\r\n\r\nstruct boot_img_hdr_v4 : public boot_img_hdr_v3 {\r\n    uint32_t signature_size; /* size in bytes */\r\n} __attribute__((packed));\r\n\r\nstruct boot_img_hdr_vnd_v4 : public boot_img_hdr_vnd_v3 {\r\n    uint32_t vendor_ramdisk_table_size;       /* size in bytes for the vendor ramdisk table */\r\n    uint32_t vendor_ramdisk_table_entry_num;  /* number of entries in the vendor ramdisk table */\r\n    uint32_t vendor_ramdisk_table_entry_size; /* size in bytes for a vendor ramdisk table entry */\r\n    uint32_t bootconfig_size; /* size in bytes for the bootconfig section */\r\n} __attribute__((packed));\r\n\r\nstruct vendor_ramdisk_table_entry_v4 {\r\n    uint32_t ramdisk_size;   /* size in bytes for the ramdisk image */\r\n    uint32_t ramdisk_offset; /* offset to the ramdisk image in vendor ramdisk section */\r\n    uint32_t ramdisk_type;   /* type of the ramdisk */\r\n    uint8_t ramdisk_name[VENDOR_RAMDISK_NAME_SIZE]; /* asciiz ramdisk name */\r\n\r\n    // Hardware identifiers describing the board, soc or platform which this\r\n    // ramdisk is intended to be loaded on.\r\n    uint32_t board_id[VENDOR_RAMDISK_TABLE_ENTRY_BOARD_ID_SIZE];\r\n} __attribute__((packed));\r\n\r\n/*******************************\r\n * Polymorphic Universal Header\r\n *******************************/\r\n\r\n#define decl_var(name, len) \\\r\nvirtual uint##len##_t &name() { j##len = 0; return j##len; }\r\n#define decl_val(name, type) \\\r\nvirtual type name() { return 0; }\r\n\r\nstruct dyn_img_hdr {\r\n\r\n    const bool is_vendor;\r\n\r\n    // Standard entries\r\n    decl_var(kernel_size, 32)\r\n    decl_var(ramdisk_size, 32)\r\n    decl_var(second_size, 32)\r\n    decl_val(page_size, uint32_t)\r\n    decl_val(header_version, uint32_t)\r\n    decl_var(extra_size, 32)\r\n    decl_var(os_version, 32)\r\n    decl_val(name, char *)\r\n    decl_val(cmdline, char *)\r\n    decl_val(id, char *)\r\n    decl_val(extra_cmdline, char *)\r\n    uint32_t kernel_dt_size = 0;\r\n\r\n    // v1/v2 specific\r\n    decl_var(recovery_dtbo_size, 32)\r\n    decl_var(recovery_dtbo_offset, 64)\r\n    decl_var(header_size, 32)\r\n    decl_var(dtb_size, 32)\r\n\r\n    // v4 specific\r\n    decl_val(signature_size, uint32_t)\r\n    decl_val(vendor_ramdisk_table_size, uint32_t)\r\n    decl_val(bootconfig_size, uint32_t)\r\n\r\n    virtual ~dyn_img_hdr() {\r\n        free(raw);\r\n    }\r\n\r\n    virtual size_t hdr_size() = 0;\r\n    virtual size_t hdr_space() { return page_size(); }\r\n    virtual dyn_img_hdr *clone() = 0;\r\n\r\n    const void *raw_hdr() const { return raw; }\r\n    void print();\r\n    void dump_hdr_file();\r\n    void load_hdr_file();\r\n\r\nprotected:\r\n    union {\r\n        boot_img_hdr_v2 *v2_hdr;     /* AOSP v2 header */\r\n        boot_img_hdr_v4 *v4_hdr;     /* AOSP v4 header */\r\n        boot_img_hdr_vnd_v4 *v4_vnd; /* AOSP vendor v4 header */\r\n        boot_img_hdr_pxa *hdr_pxa;   /* Samsung PXA header */\r\n        void *raw;                   /* Raw pointer */\r\n    };\r\n    dyn_img_hdr(bool b) : is_vendor(b) {}\r\n\r\nprivate:\r\n    // Junk for references\r\n    static uint32_t j32;\r\n    static uint64_t j64;\r\n};\r\n\r\n#undef decl_var\r\n#undef decl_val\r\n\r\n#define __impl_cls(name, hdr)           \\\r\nprotected: name() = default;            \\\r\npublic:                                 \\\r\nname(const void *ptr) {                 \\\r\n    raw = malloc(sizeof(hdr));          \\\r\n    memcpy(raw, ptr, sizeof(hdr));      \\\r\n}                                       \\\r\nsize_t hdr_size() override {            \\\r\n    return sizeof(hdr);                 \\\r\n}                                       \\\r\ndyn_img_hdr *clone() override {         \\\r\n    auto p = new name(raw);             \\\r\n    p->kernel_dt_size = kernel_dt_size; \\\r\n    return p;                           \\\r\n};\r\n\r\n#define __impl_val(name, hdr_name) \\\r\ndecltype(std::declval<dyn_img_hdr>().name()) name() override { return hdr_name->name; }\r\n\r\nstruct dyn_img_hdr_boot : public dyn_img_hdr {\r\nprotected:\r\n    dyn_img_hdr_boot() : dyn_img_hdr(false) {}\r\n};\r\n\r\n#define impl_cls(ver)  __impl_cls(dyn_img_##ver, boot_img_hdr_##ver)\r\n#define impl_val(name) __impl_val(name, v2_hdr)\r\n\r\nstruct dyn_img_common : public dyn_img_hdr_boot {\r\n    impl_val(kernel_size)\r\n    impl_val(ramdisk_size)\r\n    impl_val(second_size)\r\n};\r\n\r\nstruct dyn_img_v0 : public dyn_img_common {\r\n    impl_cls(v0)\r\n\r\n    impl_val(page_size)\r\n    impl_val(extra_size)\r\n    impl_val(os_version)\r\n    impl_val(name)\r\n    impl_val(cmdline)\r\n    impl_val(id)\r\n    impl_val(extra_cmdline)\r\n};\r\n\r\nstruct dyn_img_v1 : public dyn_img_v0 {\r\n    impl_cls(v1)\r\n\r\n    impl_val(header_version)\r\n    impl_val(recovery_dtbo_size)\r\n    impl_val(recovery_dtbo_offset)\r\n    impl_val(header_size)\r\n\r\n    uint32_t &extra_size() override { return dyn_img_hdr::extra_size(); }\r\n};\r\n\r\nstruct dyn_img_v2 : public dyn_img_v1 {\r\n    impl_cls(v2)\r\n\r\n    impl_val(dtb_size)\r\n};\r\n\r\n#undef impl_val\r\n#define impl_val(name) __impl_val(name, hdr_pxa)\r\n\r\nstruct dyn_img_pxa : public dyn_img_common {\r\n    impl_cls(pxa)\r\n\r\n    impl_val(extra_size)\r\n    impl_val(page_size)\r\n    impl_val(name)\r\n    impl_val(cmdline)\r\n    impl_val(id)\r\n    impl_val(extra_cmdline)\r\n};\r\n\r\n#undef impl_val\r\n#define impl_val(name) __impl_val(name, v4_hdr)\r\n\r\nstruct dyn_img_v3 : public dyn_img_hdr_boot {\r\n    impl_cls(v3)\r\n\r\n    impl_val(kernel_size)\r\n    impl_val(ramdisk_size)\r\n    impl_val(os_version)\r\n    impl_val(header_size)\r\n    impl_val(header_version)\r\n    impl_val(cmdline)\r\n\r\n    // Make API compatible\r\n    uint32_t page_size() override { return 4096; }\r\n    char *extra_cmdline() override { return &v4_hdr->cmdline[BOOT_ARGS_SIZE]; }\r\n};\r\n\r\nstruct dyn_img_v4 : public dyn_img_v3 {\r\n    impl_cls(v4)\r\n\r\n    impl_val(signature_size)\r\n};\r\n\r\nstruct dyn_img_hdr_vendor : public dyn_img_hdr {\r\nprotected:\r\n    dyn_img_hdr_vendor() : dyn_img_hdr(true) {}\r\n};\r\n\r\n#undef impl_val\r\n#define impl_val(name) __impl_val(name, v4_vnd)\r\n\r\nstruct dyn_img_vnd_v3 : public dyn_img_hdr_vendor {\r\n    impl_cls(vnd_v3)\r\n\r\n    impl_val(header_version)\r\n    impl_val(page_size)\r\n    impl_val(ramdisk_size)\r\n    impl_val(cmdline)\r\n    impl_val(name)\r\n    impl_val(header_size)\r\n    impl_val(dtb_size)\r\n\r\n    size_t hdr_space() override { return align_to(hdr_size(), page_size()); }\r\n\r\n    // Make API compatible\r\n    char *extra_cmdline() override { return &v4_vnd->cmdline[BOOT_ARGS_SIZE]; }\r\n};\r\n\r\nstruct dyn_img_vnd_v4 : public dyn_img_vnd_v3 {\r\n    impl_cls(vnd_v4)\r\n\r\n    impl_val(vendor_ramdisk_table_size)\r\n    impl_val(bootconfig_size)\r\n};\r\n\r\n#undef __impl_cls\r\n#undef __impl_val\r\n#undef impl_cls\r\n#undef impl_val\r\n\r\n/******************\r\n * Full Boot Image\r\n ******************/\r\n\r\nenum {\r\n    MTK_KERNEL,\r\n    MTK_RAMDISK,\r\n    CHROMEOS_FLAG,\r\n    DHTB_FLAG,\r\n    SEANDROID_FLAG,\r\n    LG_BUMP_FLAG,\r\n    SHA256_FLAG,\r\n    BLOB_FLAG,\r\n    NOOKHD_FLAG,\r\n    ACCLAIM_FLAG,\r\n    AMONET_FLAG,\r\n    AVB_FLAG,\r\n    ZIMAGE_KERNEL,\r\n    BOOT_FLAGS_MAX\r\n};\r\n\r\nstruct boot_img {\r\n    // Memory map of the whole image\r\n    mmap_data map;\r\n\r\n    // Android image header\r\n    dyn_img_hdr *hdr;\r\n\r\n    // Flags to indicate the state of current boot image\r\n    std::bitset<BOOT_FLAGS_MAX> flags;\r\n\r\n    // The format of kernel, ramdisk and extra\r\n    format_t k_fmt = UNKNOWN;\r\n    format_t r_fmt = UNKNOWN;\r\n    format_t e_fmt = UNKNOWN;\r\n\r\n    /*************************************************************\r\n     * Following pointers points within the read-only mmap region\r\n     *************************************************************/\r\n\r\n    // MTK headers\r\n    const mtk_hdr *k_hdr;\r\n    const mtk_hdr *r_hdr;\r\n\r\n    // The pointers/values after parse_image\r\n    // +---------------+\r\n    // | z_hdr         | z_info.hdr_sz\r\n    // +---------------+\r\n    // | kernel        | hdr->kernel_size()\r\n    // +---------------+\r\n    // | z_info.tail   | z_info.tail_sz\r\n    // +---------------+\r\n    const zimage_hdr *z_hdr;\r\n    struct {\r\n        uint32_t hdr_sz;\r\n        uint32_t tail_sz = 0;\r\n        const uint8_t *tail = nullptr;\r\n    } z_info;\r\n\r\n    // Pointer to dtb that is embedded in kernel\r\n    const uint8_t *kernel_dtb;\r\n\r\n    // Pointer to end of image\r\n    const uint8_t *tail;\r\n    size_t tail_size = 0;\r\n\r\n    // AVB structs\r\n    const AvbFooter *avb_footer;\r\n    const AvbVBMetaImageHeader *vbmeta;\r\n\r\n    // Pointers to blocks defined in header\r\n    const uint8_t *hdr_addr;\r\n    const uint8_t *kernel;\r\n    const uint8_t *ramdisk;\r\n    const uint8_t *second;\r\n    const uint8_t *extra;\r\n    const uint8_t *recovery_dtbo;\r\n    const uint8_t *dtb;\r\n\r\n    // Pointer to blocks defined in header, but we do not care\r\n    const uint8_t *ignore;\r\n    size_t ignore_size = 0;\r\n\r\n    boot_img(const char *);\r\n    ~boot_img();\r\n\r\n    void parse_image(const uint8_t *addr, format_t type);\r\n    dyn_img_hdr *create_hdr(const uint8_t *addr, format_t type);\r\n};"
  },
  {
    "path": "compress.cpp",
    "content": "#include <memory>\n#include <functional>\n\n#include <zlib.h>\n#include <bzlib.h>\n#include <lzma.h>\n#include <lz4.h>\n#include <lz4frame.h>\n#include <lz4hc.h>\n#include <zopfli/util.h>\n#include <zopfli/deflate.h>\n\n#include <base.hpp>\n\n#include \"magiskboot.hpp\"\n#include \"compress.hpp\"\n\nusing namespace std;\n\n#define bwrite this->base->write\n#ifdef SVB_WIN32\n#define crc32_z crc32\n#endif\n\nconstexpr size_t CHUNK = 0x40000;\nconstexpr size_t LZ4_UNCOMPRESSED = 0x800000;\nconstexpr size_t LZ4_COMPRESSED = LZ4_COMPRESSBOUND(LZ4_UNCOMPRESSED);\n\nclass out_stream : public filter_stream {\n    using filter_stream::filter_stream;\n    using stream::read;\n};\n\nclass gz_strm : public out_stream {\npublic:\n    bool write(const void *buf, size_t len) override {\n        return len == 0 || do_write(buf, len, Z_NO_FLUSH);\n    }\n\n    ~gz_strm() override {\n        do_write(nullptr, 0, Z_FINISH);\n        switch(mode) {\n        case DECODE:\n            inflateEnd(&strm);\n            break;\n        case ENCODE:\n            deflateEnd(&strm);\n            break;\n        default:\n            break;\n        }\n    }\n\nprotected:\n    enum mode_t {\n        DECODE,\n        ENCODE,\n        WAIT,\n        COPY\n    } mode;\n\n    gz_strm(mode_t mode, stream_ptr &&base) :\n        out_stream(std::move(base)), mode(mode), strm{}, outbuf{0} {\n        switch(mode) {\n        case DECODE:\n            inflateInit2(&strm, 15 | 16);\n            break;\n        case ENCODE:\n            deflateInit2(&strm, 9, Z_DEFLATED, 15 | 16, 8, Z_DEFAULT_STRATEGY);\n            break;\n        default:\n            break;\n        }\n    }\n\nprivate:\n    z_stream strm;\n    uint8_t outbuf[CHUNK];\n\n    bool do_write(const void *buf, size_t len, int flush) {\n        if (mode == WAIT) {\n            if (len == 0) return true;\n            Bytef b[1] = {0x1f};\n            if (*(Bytef *)buf == 0x8b) {\n                mode = DECODE;\n                inflateReset(&strm);\n                strm.next_in = b;\n                strm.avail_in = 1;\n                inflate(&strm, flush);\n            } else {\n                mode = COPY;\n                return true;\n            }\n        }\n        strm.next_in = (Bytef *) buf;\n        strm.avail_in = len;\n        do {\n            int code;\n            strm.next_out = outbuf;\n            strm.avail_out = sizeof(outbuf);\n            switch(mode) {\n                case DECODE:\n                    code = inflate(&strm, flush);\n                    break;\n                case ENCODE:\n                    code = deflate(&strm, flush);\n                    break;\n                case COPY:\n                    return true;\n                default:\n                    // should have been handled\n                    return false;\n            }\n            if (code == Z_STREAM_ERROR) {\n                LOGW(\"gzip %s failed (%d)\\n\", mode ? \"encode\" : \"decode\", code);\n                return false;\n            }\n            if (!bwrite(outbuf, sizeof(outbuf) - strm.avail_out))\n                return false;\n            if (mode == DECODE && code == Z_STREAM_END) {\n                if (strm.avail_in > 1) {\n                    if (strm.next_in[0] == 0x1f && strm.next_in[1] == 0x8b) {\n                        // There is still data in the stream, we need to reset the stream\n                        // and continue decoding\n                        inflateReset(&strm);\n                        strm.avail_out = 0;\n                        continue;\n                    }\n                } else if (strm.avail_in == 1) {\n                    if (strm.next_in[0] == 0x1f) {\n                        // If there is only one byte left, we need to wait for the next byte\n                        // to determine if it is a gzip header\n                        mode = WAIT;\n                        return true;\n                    }\n                } else {\n                    // The next inflate won't consume any data but fallback\n                    // to the previous two conditions\n                    return true;\n                }\n                // There is still data in the stream, we need to copy it\n                mode = COPY;\n                return true;\n            }\n        } while (strm.avail_out == 0);\n        return true;\n    }\n};\n\nclass gz_decoder : public gz_strm {\npublic:\n    explicit gz_decoder(stream_ptr &&base) : gz_strm(DECODE, std::move(base)) {};\n};\n\nclass gz_encoder : public gz_strm {\npublic:\n    explicit gz_encoder(stream_ptr &&base) : gz_strm(ENCODE, std::move(base)) {};\n};\n\nclass zopfli_encoder : public chunk_out_stream {\npublic:\n    explicit zopfli_encoder(stream_ptr &&base) :\n        chunk_out_stream(std::move(base), ZOPFLI_MASTER_BLOCK_SIZE),\n        zo{}, out(nullptr), outsize(0), crc(crc32_z(0L, Z_NULL, 0)), in_total(0), bp(0) {\n        ZopfliInitOptions(&zo);\n\n        // This config is already better than gzip -9\n        zo.numiterations = 1;\n        zo.blocksplitting = 0;\n\n        ZOPFLI_APPEND_DATA(31, &out, &outsize);  /* ID1 */\n        ZOPFLI_APPEND_DATA(139, &out, &outsize); /* ID2 */\n        ZOPFLI_APPEND_DATA(8, &out, &outsize);   /* CM */\n        ZOPFLI_APPEND_DATA(0, &out, &outsize);   /* FLG */\n        /* MTIME */\n        ZOPFLI_APPEND_DATA(0, &out, &outsize);\n        ZOPFLI_APPEND_DATA(0, &out, &outsize);\n        ZOPFLI_APPEND_DATA(0, &out, &outsize);\n        ZOPFLI_APPEND_DATA(0, &out, &outsize);\n\n        ZOPFLI_APPEND_DATA(2, &out, &outsize);  /* XFL, 2 indicates best compression. */\n        ZOPFLI_APPEND_DATA(3, &out, &outsize);  /* OS follows Unix conventions. */\n    }\n\n    ~zopfli_encoder() override {\n        finalize();\n\n        /* CRC */\n        ZOPFLI_APPEND_DATA(crc % 256, &out, &outsize);\n        ZOPFLI_APPEND_DATA((crc >> 8) % 256, &out, &outsize);\n        ZOPFLI_APPEND_DATA((crc >> 16) % 256, &out, &outsize);\n        ZOPFLI_APPEND_DATA((crc >> 24) % 256, &out, &outsize);\n\n        /* ISIZE */\n        ZOPFLI_APPEND_DATA(in_total % 256, &out, &outsize);\n        ZOPFLI_APPEND_DATA((in_total >> 8) % 256, &out, &outsize);\n        ZOPFLI_APPEND_DATA((in_total >> 16) % 256, &out, &outsize);\n        ZOPFLI_APPEND_DATA((in_total >> 24) % 256, &out, &outsize);\n\n        bwrite(out, outsize);\n        free(out);\n    }\n\nprotected:\n    bool write_chunk(const void *buf, size_t len, bool final) override {\n        if (len == 0)\n            return true;\n\n        auto in = static_cast<const unsigned char *>(buf);\n\n        in_total += len;\n        crc = crc32_z(crc, in, len);\n\n        ZopfliDeflatePart(&zo, 2, final, in, 0, len, &bp, &out, &outsize);\n\n        // ZOPFLI_APPEND_DATA is extremely dumb, so we always preserve the\n        // last byte to make sure that realloc is used instead of malloc\n        if (!bwrite(out, outsize - 1))\n            return false;\n        out[0] = out[outsize - 1];\n        outsize = 1;\n\n        return true;\n    }\n\nprivate:\n    ZopfliOptions zo;\n    unsigned char *out;\n    size_t outsize;\n    unsigned long crc;\n    uint32_t in_total;\n    unsigned char bp;\n};\n\nclass bz_strm : public out_stream {\npublic:\n    bool write(const void *buf, size_t len) override {\n        return len == 0 || do_write(buf, len, BZ_RUN);\n    }\n\n    ~bz_strm() override {\n        switch(mode) {\n            case DECODE:\n                BZ2_bzDecompressEnd(&strm);\n                break;\n            case ENCODE:\n                do_write(nullptr, 0, BZ_FINISH);\n                BZ2_bzCompressEnd(&strm);\n                break;\n        }\n    }\n\nprotected:\n    enum mode_t {\n        DECODE,\n        ENCODE\n    } mode;\n\n    bz_strm(mode_t mode, stream_ptr &&base) :\n        out_stream(std::move(base)), mode(mode), strm{}, outbuf{0} {\n        switch(mode) {\n        case DECODE:\n            BZ2_bzDecompressInit(&strm, 0, 0);\n            break;\n        case ENCODE:\n            BZ2_bzCompressInit(&strm, 9, 0, 0);\n            break;\n        }\n    }\n\nprivate:\n    bz_stream strm;\n    char outbuf[CHUNK];\n\n    bool do_write(const void *buf, size_t len, int flush) {\n        strm.next_in = (char *) buf;\n        strm.avail_in = len;\n        do {\n            int code;\n            strm.avail_out = sizeof(outbuf);\n            strm.next_out = outbuf;\n            switch(mode) {\n            case DECODE:\n                code = BZ2_bzDecompress(&strm);\n                break;\n            case ENCODE:\n                code = BZ2_bzCompress(&strm, flush);\n                break;\n            }\n            if (code < 0) {\n                LOGW(\"bzip2 %s failed (%d)\\n\", mode ? \"encode\" : \"decode\", code);\n                return false;\n            }\n            if (!bwrite(outbuf, sizeof(outbuf) - strm.avail_out))\n                return false;\n        } while (strm.avail_out == 0);\n        return true;\n    }\n};\n\nclass bz_decoder : public bz_strm {\npublic:\n    explicit bz_decoder(stream_ptr &&base) : bz_strm(DECODE, std::move(base)) {};\n};\n\nclass bz_encoder : public bz_strm {\npublic:\n    explicit bz_encoder(stream_ptr &&base) : bz_strm(ENCODE, std::move(base)) {};\n};\n\nclass lzma_strm : public out_stream {\npublic:\n    bool write(const void *buf, size_t len) override {\n        return len == 0 || do_write(buf, len, LZMA_RUN);\n    }\n\n    ~lzma_strm() override {\n        do_write(nullptr, 0, LZMA_FINISH);\n        lzma_end(&strm);\n    }\n\nprotected:\n    enum mode_t {\n        DECODE,\n        ENCODE_XZ,\n        ENCODE_LZMA\n    } mode;\n\n    lzma_strm(mode_t mode, stream_ptr &&base) :\n        out_stream(std::move(base)), mode(mode), strm(LZMA_STREAM_INIT), outbuf{0} {\n        lzma_options_lzma opt;\n\n        // Initialize preset\n        lzma_lzma_preset(&opt, 9);\n        lzma_filter filters[] = {\n            { .id = LZMA_FILTER_LZMA2, .options = &opt },\n            { .id = LZMA_VLI_UNKNOWN, .options = nullptr },\n        };\n\n        lzma_ret code;\n        switch(mode) {\n        case DECODE:\n            code = lzma_auto_decoder(&strm, UINT64_MAX, 0);\n            break;\n        case ENCODE_XZ:\n            code = lzma_stream_encoder(&strm, filters, LZMA_CHECK_CRC32);\n            break;\n        case ENCODE_LZMA:\n            code = lzma_alone_encoder(&strm, &opt);\n            break;\n        }\n        if (code != LZMA_OK) {\n            LOGE(\"LZMA initialization failed (%d)\\n\", code);\n        }\n    }\n\nprivate:\n    lzma_stream strm;\n    uint8_t outbuf[CHUNK];\n\n    bool do_write(const void *buf, size_t len, lzma_action flush) {\n        strm.next_in = (uint8_t *) buf;\n        strm.avail_in = len;\n        do {\n            strm.avail_out = sizeof(outbuf);\n            strm.next_out = outbuf;\n            int code = lzma_code(&strm, flush);\n            if (code != LZMA_OK && code != LZMA_STREAM_END) {\n                LOGW(\"LZMA %s failed (%d)\\n\", mode ? \"encode\" : \"decode\", code);\n                return false;\n            }\n            if (!bwrite(outbuf, sizeof(outbuf) - strm.avail_out))\n                return false;\n        } while (strm.avail_out == 0);\n        return true;\n    }\n};\n\nclass lzma_decoder : public lzma_strm {\npublic:\n    explicit lzma_decoder(stream_ptr &&base) : lzma_strm(DECODE, std::move(base)) {}\n};\n\nclass xz_encoder : public lzma_strm {\npublic:\n    explicit xz_encoder(stream_ptr &&base) : lzma_strm(ENCODE_XZ, std::move(base)) {}\n};\n\nclass lzma_encoder : public lzma_strm {\npublic:\n    explicit lzma_encoder(stream_ptr &&base) : lzma_strm(ENCODE_LZMA, std::move(base)) {}\n};\n\nclass LZ4F_decoder : public out_stream {\npublic:\n    explicit LZ4F_decoder(stream_ptr &&base) :\n        out_stream(std::move(base)), ctx(nullptr), outbuf(nullptr), outCapacity(0) {\n        LZ4F_createDecompressionContext(&ctx, LZ4F_VERSION);\n    }\n\n    ~LZ4F_decoder() override {\n        LZ4F_freeDecompressionContext(ctx);\n        delete[] outbuf;\n    }\n\n    bool write(const void *buf, size_t len) override {\n        auto in = reinterpret_cast<const uint8_t *>(buf);\n        if (!outbuf) {\n            size_t read = len;\n            LZ4F_frameInfo_t info;\n            LZ4F_getFrameInfo(ctx, &info, in, &read);\n            switch (info.blockSizeID) {\n            case LZ4F_default:\n            case LZ4F_max64KB:  outCapacity = 1 << 16; break;\n            case LZ4F_max256KB: outCapacity = 1 << 18; break;\n            case LZ4F_max1MB:   outCapacity = 1 << 20; break;\n            case LZ4F_max4MB:   outCapacity = 1 << 22; break;\n            }\n            outbuf = new uint8_t[outCapacity];\n            in += read;\n            len -= read;\n        }\n        size_t read, write;\n        LZ4F_errorCode_t code;\n        do {\n            read = len;\n            write = outCapacity;\n            code = LZ4F_decompress(ctx, outbuf, &write, in, &read, nullptr);\n            if (LZ4F_isError(code)) {\n                LOGW(\"LZ4F decode error: %s\\n\", LZ4F_getErrorName(code));\n                return false;\n            }\n            len -= read;\n            in += read;\n            if (!bwrite(outbuf, write))\n                return false;\n        } while (len != 0 || write != 0);\n        return true;\n    }\n\nprivate:\n    LZ4F_decompressionContext_t ctx;\n    uint8_t *outbuf;\n    size_t outCapacity;\n};\n\nclass LZ4F_encoder : public out_stream {\npublic:\n    explicit LZ4F_encoder(stream_ptr &&base) :\n        out_stream(std::move(base)), ctx(nullptr), out_buf(nullptr), outCapacity(0) {\n        LZ4F_createCompressionContext(&ctx, LZ4F_VERSION);\n    }\n\n    bool write(const void *buf, size_t len) override {\n        if (!out_buf) {\n            LZ4F_preferences_t prefs {\n                .frameInfo = {\n                    .blockSizeID = LZ4F_max4MB,\n                    .blockMode = LZ4F_blockIndependent,\n                    .contentChecksumFlag = LZ4F_contentChecksumEnabled,\n                    .blockChecksumFlag = LZ4F_noBlockChecksum,\n                },\n                .compressionLevel = 9,\n                .autoFlush = 1,\n            };\n            outCapacity = LZ4F_compressBound(BLOCK_SZ, &prefs);\n            out_buf = new uint8_t[outCapacity];\n            size_t write = LZ4F_compressBegin(ctx, out_buf, outCapacity, &prefs);\n            if (!bwrite(out_buf, write))\n                return false;\n        }\n        if (len == 0)\n            return true;\n\n        auto in = reinterpret_cast<const uint8_t *>(buf);\n        size_t read, write;\n        do {\n            read = len > BLOCK_SZ ? BLOCK_SZ : len;\n            write = LZ4F_compressUpdate(ctx, out_buf, outCapacity, in, read, nullptr);\n            if (LZ4F_isError(write)) {\n                LOGW(\"LZ4F encode error: %s\\n\", LZ4F_getErrorName(write));\n                return false;\n            }\n            len -= read;\n            in += read;\n            if (!bwrite(out_buf, write))\n                return false;\n        } while (len != 0);\n        return true;\n    }\n\n    ~LZ4F_encoder() override {\n        size_t len = LZ4F_compressEnd(ctx, out_buf, outCapacity, nullptr);\n        if (LZ4F_isError(len)) {\n            LOGE(\"LZ4F end of frame error: %s\\n\", LZ4F_getErrorName(len));\n        } else if (!bwrite(out_buf, len)) {\n            LOGE(\"LZ4F end of frame error: I/O error\\n\");\n        }\n        LZ4F_freeCompressionContext(ctx);\n        delete[] out_buf;\n    }\n\nprivate:\n    LZ4F_compressionContext_t ctx;\n    uint8_t *out_buf;\n    size_t outCapacity;\n\n    static constexpr size_t BLOCK_SZ = 1 << 22;\n};\n\nclass LZ4_decoder : public chunk_out_stream {\npublic:\n    explicit LZ4_decoder(stream_ptr &&base) :\n        chunk_out_stream(std::move(base), LZ4_COMPRESSED, sizeof(block_sz)),\n        out_buf(new char[LZ4_UNCOMPRESSED]), block_sz(0) {}\n\n    ~LZ4_decoder() override {\n        finalize();\n        delete[] out_buf;\n    }\n\nprotected:\n    bool write_chunk(const void *buf, size_t len, bool final) override {\n        // This is an error\n        if (len != chunk_sz)\n            return false;\n\n        auto in = reinterpret_cast<const char *>(buf);\n\n        if (block_sz == 0) {\n            memcpy(&block_sz, in, sizeof(block_sz));\n            if (block_sz == 0x184C2102) {\n                // This is actually the lz4 magic, read the next 4 bytes\n                block_sz = 0;\n                chunk_sz = sizeof(block_sz);\n                return true;\n            }\n            // Read the next block chunk\n            chunk_sz = block_sz;\n            return true;\n        } else {\n            int r = LZ4_decompress_safe(in, out_buf, block_sz, LZ4_UNCOMPRESSED);\n            chunk_sz = sizeof(block_sz);\n            block_sz = 0;\n            if (r < 0) {\n                LOGW(\"LZ4HC decompression failure (%d)\\n\", r);\n                return false;\n            }\n            return bwrite(out_buf, r);\n        }\n    }\n\nprivate:\n    char *out_buf;\n    uint32_t block_sz;\n};\n\nclass LZ4_encoder : public chunk_out_stream {\npublic:\n    explicit LZ4_encoder(stream_ptr &&base, bool lg) :\n        chunk_out_stream(std::move(base), LZ4_UNCOMPRESSED),\n        out_buf(new char[LZ4_COMPRESSED]), lg(lg), in_total(0) {\n        bwrite(\"\\x02\\x21\\x4c\\x18\", 4);\n    }\n\n    ~LZ4_encoder() override {\n        finalize();\n        if (lg)\n            bwrite(&in_total, sizeof(in_total));\n        delete[] out_buf;\n    }\n\nprotected:\n    bool write_chunk(const void *buf, size_t len, bool final) override {\n        auto in = static_cast<const char *>(buf);\n        uint32_t block_sz = LZ4_compress_HC(in, out_buf, len, LZ4_COMPRESSED, LZ4HC_CLEVEL_MAX);\n        if (block_sz == 0) {\n            LOGW(\"LZ4HC compression failure\\n\");\n            return false;\n        }\n        if (bwrite(&block_sz, sizeof(block_sz)) && bwrite(out_buf, block_sz)) {\n            in_total += len;\n            return true;\n        }\n        return false;\n    }\n\nprivate:\n    char *out_buf;\n    bool lg;\n    uint32_t in_total;\n};\n\nfilter_strm_ptr get_encoder(format_t type, stream_ptr &&base) {\n    switch (type) {\n        case XZ:\n            return make_unique<xz_encoder>(std::move(base));\n        case LZMA:\n            return make_unique<lzma_encoder>(std::move(base));\n        case BZIP2:\n            return make_unique<bz_encoder>(std::move(base));\n        case LZ4:\n            return make_unique<LZ4F_encoder>(std::move(base));\n        case LZ4_LEGACY:\n            return make_unique<LZ4_encoder>(std::move(base), false);\n        case LZ4_LG:\n            return make_unique<LZ4_encoder>(std::move(base), true);\n        case ZOPFLI:\n            return make_unique<zopfli_encoder>(std::move(base));\n        case GZIP:\n        default:\n            return make_unique<gz_encoder>(std::move(base));\n    }\n}\n\nfilter_strm_ptr get_decoder(format_t type, stream_ptr &&base) {\n    switch (type) {\n        case XZ:\n        case LZMA:\n            return make_unique<lzma_decoder>(std::move(base));\n        case BZIP2:\n            return make_unique<bz_decoder>(std::move(base));\n        case LZ4:\n            return make_unique<LZ4F_decoder>(std::move(base));\n        case LZ4_LEGACY:\n        case LZ4_LG:\n            return make_unique<LZ4_decoder>(std::move(base));\n        case ZOPFLI:\n        case GZIP:\n        default:\n            return make_unique<gz_decoder>(std::move(base));\n    }\n}\n\nvoid decompress(char *infile, const char *outfile) {\n    bool in_std = infile == \"-\"sv;\n    bool rm_in = false;\n\n    FILE *in_fp = in_std ? stdin : xfopen(infile, \"re\");\n    stream_ptr strm;\n\n    char buf[4096];\n    size_t len;\n    while ((len = fread(buf, 1, sizeof(buf), in_fp))) {\n        if (!strm) {\n            format_t type = check_fmt(buf, len);\n\n            fprintf(stderr, \"Detected format: [%s]\\n\", fmt2name[type]);\n\n            if (!COMPRESSED(type))\n                LOGE(\"Input file is not a supported compressed type!\\n\");\n\n            /* If user does not provide outfile, infile has to be either\n            * <path>.[ext], or '-'. Outfile will be either <path> or '-'.\n            * If the input does not have proper format, abort */\n\n            char *ext = nullptr;\n            if (outfile == nullptr) {\n                outfile = infile;\n                if (!in_std) {\n                    ext = strrchr(infile, '.');\n                    if (ext == nullptr || strcmp(ext, fmt2ext[type]) != 0)\n                        LOGE(\"Input file is not a supported type!\\n\");\n\n                    // Strip out extension and remove input\n                    *ext = '\\0';\n                    rm_in = true;\n                    fprintf(stderr, \"Decompressing to [%s]\\n\", outfile);\n                }\n            }\n\n            FILE *out_fp = outfile == \"-\"sv ? stdout : xfopen(outfile, \"we\");\n            strm = get_decoder(type, make_unique<fp_stream>(out_fp));\n            if (ext) *ext = '.';\n        }\n        if (!strm->write(buf, len))\n            LOGE(\"Decompression error!\\n\");\n    }\n\n    strm.reset(nullptr);\n    fclose(in_fp);\n\n    if (rm_in)\n        unlink(infile);\n}\n\nvoid compress(const char *method, const char *infile, const char *outfile) {\n    format_t fmt = name2fmt[method];\n    if (fmt == UNKNOWN)\n        LOGE(\"Unknown compression method: [%s]\\n\", method);\n\n    bool in_std = infile == \"-\"sv;\n    bool rm_in = false;\n\n    FILE *in_fp = in_std ? stdin : xfopen(infile, \"re\");\n    FILE *out_fp;\n\n    if (outfile == nullptr) {\n        if (in_std) {\n            out_fp = stdout;\n        } else {\n            /* If user does not provide outfile and infile is not\n             * STDIN, output to <infile>.[ext] */\n            string tmp(infile);\n            tmp += fmt2ext[fmt];\n            out_fp = xfopen(tmp.data(), \"we\");\n            fprintf(stderr, \"Compressing to [%s]\\n\", tmp.data());\n            rm_in = true;\n        }\n    } else {\n        out_fp = outfile == \"-\"sv ? stdout : xfopen(outfile, \"we\");\n    }\n\n    auto strm = get_encoder(fmt, make_unique<fp_stream>(out_fp));\n\n    char buf[4096];\n    size_t len;\n    while ((len = fread(buf, 1, sizeof(buf), in_fp))) {\n        if (!strm->write(buf, len))\n            LOGE(\"Compression error!\\n\");\n    }\n\n    strm.reset(nullptr);\n    fclose(in_fp);\n\n    if (rm_in)\n        unlink(infile);\n}\n"
  },
  {
    "path": "compress.hpp",
    "content": "#pragma once\n\n#include <stream.hpp>\n\n#include \"format.hpp\"\n\nfilter_strm_ptr get_encoder(format_t type, stream_ptr &&base);\n\nfilter_strm_ptr get_decoder(format_t type, stream_ptr &&base);\n\nvoid compress(const char *method, const char *infile, const char *outfile);\n\nvoid decompress(char *infile, const char *outfile);\n"
  },
  {
    "path": "cpio.cpp",
    "content": "#include <unistd.h>\r\n#include <fcntl.h>\r\n#include <libgen.h>\r\n#include <algorithm>\r\n\r\n#include <base.hpp>\r\n\r\n#include \"cpio.hpp\"\r\n\r\nusing namespace std;\r\n\r\nstruct cpio_newc_header {\r\n    char magic[6];\r\n    char ino[8];\r\n    char mode[8];\r\n    char uid[8];\r\n    char gid[8];\r\n    char nlink[8];\r\n    char mtime[8];\r\n    char filesize[8];\r\n    char devmajor[8];\r\n    char devminor[8];\r\n    char rdevmajor[8];\r\n    char rdevminor[8];\r\n    char namesize[8];\r\n    char check[8];\r\n} __attribute__((packed));\r\n\r\nstatic uint32_t x8u(const char *hex) {\r\n    uint32_t val, inpos = 8, outpos;\r\n    char pattern[6];\r\n\r\n    while (*hex == '0') {\r\n        hex++;\r\n        if (!--inpos) return 0;\r\n    }\r\n    // Because scanf gratuitously treats %*X differently than printf does.\r\n    sprintf(pattern, \"%%%dx%%n\", inpos);\r\n    sscanf(hex, pattern, &val, &outpos);\r\n    if (inpos != outpos)\r\n        LOGE(\"bad cpio header\\n\");\r\n\r\n    return val;\r\n}\r\n\r\ncpio_entry::cpio_entry(uint32_t mode) : mode(mode), uid(0), gid(0), filesize(0), data(nullptr) {}\r\n\r\ncpio_entry::cpio_entry(uint32_t mode, uint32_t uid, uint32_t gid) : mode(mode), uid(uid), gid(gid), filesize(0), data(nullptr) {}\r\n\r\ncpio_entry::cpio_entry(const cpio_newc_header *h) :\r\nmode(x8u(h->mode)), uid(x8u(h->uid)), gid(x8u(h->gid)), filesize(x8u(h->filesize)), data(nullptr)\r\n{}\r\n\r\nstatic void recursive_dir_iterator(cpio::entry_map &entries, const char* root, const char *sub = nullptr) {\r\n    auto path = sub ? sub : root;\r\n    auto cur = opendir(path);\r\n\r\n    if (errno || !cur)\r\n        return;\r\n\r\n    for (dirent *entry; (entry = xreaddir(cur));) {\r\n        char *filename = (char *)malloc(strlen(path) + 2 +\r\n#ifndef SVB_MINGW\r\n        strlen(entry->name));\r\n#else\r\n        entry->d_namlen);\r\n#endif\r\n        struct stat st;\r\n\r\n        if (sprintf(filename, \"%s/%s\", path, entry->d_name) < 0 ||\r\n            xlstat(filename, &st)) {\r\n            errno = EINVAL;\r\n            break;\r\n        }\r\n\r\n        auto e = new cpio_entry(st.st_mode, st.st_uid, st.st_gid);\r\n        auto name = filename + strlen(root) + 1;\r\n        auto type = st.st_mode & S_IFMT;\r\n\r\n        if (type == S_IFREG) {\r\n            auto m = mmap_data(filename);\r\n            e->filesize = m.sz;\r\n            e->data = xmalloc(m.sz);\r\n            memcpy(e->data, m.buf, m.sz);\r\n        } else if (type == S_IFLNK) {\r\n            char* ln_target = (char *)malloc(st.st_size + 1);\r\n            int read_cnt = xreadlink(filename, ln_target, st.st_size);\r\n\r\n            if (read_cnt == -1 || read_cnt > st.st_size) {\r\n                errno = EINVAL;\r\n                return;\r\n            }\r\n            e->filesize = st.st_size;\r\n            e->data = ln_target;\r\n        } else { // assume S_IFDIR\r\n            recursive_dir_iterator(entries, root, filename);\r\n        }\r\n\r\n        entries.emplace(name, e);\r\n        free(filename);\r\n    }\r\n\r\n    closedir(cur);\r\n}\r\n\r\nvoid cpio::dump(const char *file) {\r\n    fprintf(stderr, \"Dump cpio: [%s]\\n\", file);\r\n    dump(xfopen(file, \"we\"));\r\n}\r\n\r\nvoid cpio::rm(entry_map::iterator it) {\r\n    if (it == entries.end())\r\n        return;\r\n    fprintf(stderr, \"Remove [%s]\\n\", it->first.data());\r\n    entries.erase(it);\r\n}\r\n\r\nvoid cpio::rm(const char *name, bool r) {\r\n    size_t len = strlen(name);\r\n    for (auto it = entries.begin(); it != entries.end();) {\r\n        if (it->first.compare(0, len, name) == 0 &&\r\n            ((r && it->first[len] == '/') || it->first[len] == '\\0')) {\r\n            auto tmp = it;\r\n            ++it;\r\n            rm(tmp);\r\n            if (!r) return;\r\n        } else {\r\n            ++it;\r\n        }\r\n    }\r\n}\r\n\r\nvoid cpio::extract_entry(const entry_map::value_type &e, const char *file) {\r\n    fprintf(stderr, \"Extract [%s] to [%s]\\n\", e.first.data(), file);\r\n    unlink(file);\r\n    rmdir(file);\r\n    // Make sure parent folders exist\r\n    char *parent = dirname(strdup(file));\r\n    xmkdirs(parent, 0755);\r\n    if (S_ISDIR(e.second->mode)) {\r\n        xmkdir(file, e.second->mode & 0777);\r\n    } else if (S_ISREG(e.second->mode)) {\r\n        int fd = xopen(file, O_CREAT | O_WRONLY | O_TRUNC, e.second->mode & 0777);\r\n        xwrite(fd, e.second->data, e.second->filesize);\r\n#ifndef SVB_WIN32\r\n        fchown(fd, e.second->uid, e.second->gid);\r\n#endif\r\n        close(fd);\r\n    } else if (S_ISLNK(e.second->mode) && e.second->filesize < 4096) {\r\n        char target[4096];\r\n        memcpy(target, e.second->data, e.second->filesize);\r\n        target[e.second->filesize] = '\\0';\r\n        symlink(target, file);\r\n    }\r\n#ifdef SVB_WIN32\r\n    FILE *config = fopen(\"cpio\", \"a\");\r\n    fprintf(config, \"%s %o %u %u\\n\", e.first.data(), e.second->mode & 0777, e.second->uid, e.second->gid);\r\n    fclose(config);\r\n#endif\r\n}\r\n\r\nvoid cpio::extract() {\r\n    unlink(\"cpio\");\r\n    rmdir(\"ramdisk\");\r\n#ifdef SVB_MINGW\r\n    ::mkdir(\"ramdisk\");\r\n#else\r\n    ::mkdir(\"ramdisk\", 0744);\r\n#endif\r\n    for (auto &e : entries)\r\n        extract_entry(e, (\"ramdisk/\" + e.first).data());\r\n}\r\n\r\nvoid cpio::load_cpio(const char* dir, const char* config, bool sync) {\r\n    entry_map dentries;\r\n\r\n    recursive_dir_iterator(dentries, dir);\r\n\r\n    if (errno) {\r\n        PLOGE(\"%s [%s]\", sync ? \"Sync\" : \"Pack\", dir);\r\n        return;\r\n    }\r\n\r\n    file_readline(config, [&](string_view line) -> bool {\r\n        if (line.empty() || line[0] == '#')\r\n            return true;\r\n\r\n        auto tokens = split(string(line), \" \");\r\n\r\n        if (tokens.size() < 4) {\r\n            LOGE(\"Ill-formed line in [%s]\\n\", config);\r\n        }\r\n\r\n        auto it = dentries.find(tokens[0].data());\r\n        if (it != dentries.end()) {\r\n            it->second->mode &= S_IFMT;\r\n            it->second->mode |= static_cast<unsigned int>(strtol(tokens[1].data(), nullptr, 8)) & 0777;\r\n            it->second->uid = strtol(tokens[2].data(), nullptr, 10);\r\n            it->second->gid = strtol(tokens[3].data(), nullptr, 10);\r\n        }\r\n\r\n        return true;\r\n    });\r\n\r\n    if (!sync) {\r\n        entries = std::move(dentries);\r\n        return;\r\n    }\r\n\r\n    auto rhs = entries.begin();\r\n    auto lhs = dentries.begin();\r\n\r\n    while (rhs != entries.end() || lhs != dentries.end()) {\r\n        int res;\r\n        if (lhs != dentries.end() && rhs != entries.end()) {\r\n            res = rhs->first.compare(lhs->first);\r\n        } else if (rhs == entries.end()) {\r\n            res = 1;\r\n        } else {\r\n            res = -1;\r\n        }\r\n\r\n        bool is_new = res >= 0;\r\n\r\n        if (res < 0) { // smh is removed\r\n            rm(rhs++);\r\n        } else if (res == 0) { // smh is same, maybe\r\n            is_new = rhs->second->filesize != lhs->second->filesize ||\r\n                     rhs->second->mode != lhs->second->mode ||\r\n                     rhs->second->uid != lhs->second->uid ||\r\n                     rhs->second->gid != lhs->second->gid ||\r\n                     memcmp(lhs->second->data, rhs->second->data, lhs->second->filesize) != 0;\r\n        } // smh is added\r\n\r\n        if (is_new) {\r\n            fprintf(stderr, \"%s entry [%s] (%04o)\\n\", res > 0 ? \"Add new\" : \"Updated\", lhs->first.data(), lhs->second->mode & 0777);\r\n            insert(lhs->first, lhs->second.release());\r\n        }\r\n\r\n        if (res > 0) {\r\n            ++lhs;\r\n        } else if (res == 0)  {\r\n            ++lhs; ++rhs;\r\n        }\r\n    }\r\n}\r\n\r\nbool cpio::extract(const char *name, const char *file) {\r\n    auto it = entries.find(name);\r\n    if (it != entries.end()) {\r\n        extract_entry(*it, file);\r\n        return true;\r\n    }\r\n    fprintf(stderr, \"Cannot find the file entry [%s]\\n\", name);\r\n    return false;\r\n}\r\n\r\nbool cpio::exists(const char *name) {\r\n    return entries.count(name) != 0;\r\n}\r\n\r\n#define do_out(buf, len) pos += fwrite(buf, 1, len, out);\r\n#define out_align() do_out(zeros, align_padding(pos, 4))\r\nvoid cpio::dump(FILE *out) {\r\n    size_t pos = 0;\r\n    unsigned inode = 300000;\r\n    char header[111];\r\n    char zeros[4] = {0};\r\n    for (auto &e : entries) {\r\n        sprintf(header, \"070701%08x%08x%08x%08x%08x%08x%08x%08x%08x%08x%08x%08x%08x\",\r\n                inode++,    // e->ino\r\n                e.second->mode,\r\n                e.second->uid,\r\n                e.second->gid,\r\n                1,          // e->nlink\r\n                0,          // e->mtime\r\n                e.second->filesize,\r\n                0,          // e->devmajor\r\n                0,          // e->devminor\r\n                0,          // e->rdevmajor\r\n                0,          // e->rdevminor\r\n                (uint32_t) e.first.size() + 1,\r\n                0           // e->check\r\n        );\r\n        do_out(header, 110);\r\n        do_out(e.first.data(), e.first.size() + 1);\r\n        out_align();\r\n        if (e.second->filesize) {\r\n            do_out(e.second->data, e.second->filesize);\r\n            out_align();\r\n        }\r\n    }\r\n    // Write trailer\r\n    sprintf(header, \"070701%08x%08x%08x%08x%08x%08x%08x%08x%08x%08x%08x%08x%08x\",\r\n            inode++, 0755, 0, 0, 1, 0, 0, 0, 0, 0, 0, 11, 0);\r\n    do_out(header, 110);\r\n    do_out(\"TRAILER!!!\\0\", 11);\r\n    out_align();\r\n    fclose(out);\r\n}\r\n\r\nvoid cpio::load_cpio(const char *file) {\r\n    fprintf(stderr, \"Loading cpio: [%s]\\n\", file);\r\n    auto m = mmap_data(file);\r\n    load_cpio(reinterpret_cast<char *>(m.buf), m.sz);\r\n}\r\n\r\nvoid cpio::insert(string_view name, cpio_entry *e) {\r\n    auto it = entries.find(name);\r\n    if (it != entries.end()) {\r\n        it->second.reset(e);\r\n    } else {\r\n        entries.emplace(name, e);\r\n    }\r\n}\r\n\r\nvoid cpio::add(mode_t mode, const char *name, const char *file) {\r\n    auto m = mmap_data(file);\r\n    auto e = new cpio_entry(S_IFREG | mode);\r\n    e->filesize = m.sz;\r\n    e->data = xmalloc(m.sz);\r\n    memcpy(e->data, m.buf, m.sz);\r\n    insert(name, e);\r\n    fprintf(stderr, \"Add entry [%s] (%04o)\\n\", name, mode);\r\n}\r\n\r\nvoid cpio::mkdir(mode_t mode, const char *name) {\r\n    insert(name, new cpio_entry(S_IFDIR | mode));\r\n    fprintf(stderr, \"Create directory [%s] (%04o)\\n\", name, mode);\r\n}\r\n\r\nvoid cpio::ln(const char *target, const char *name) {\r\n    auto e = new cpio_entry(S_IFLNK);\r\n    e->filesize = strlen(target);\r\n    e->data = strdup(target);\r\n    insert(name, e);\r\n    fprintf(stderr, \"Create symlink [%s] -> [%s]\\n\", name, target);\r\n}\r\n\r\nvoid cpio::mv(entry_map::iterator it, const char *name) {\r\n    fprintf(stderr, \"Move [%s] -> [%s]\\n\", it->first.data(), name);\r\n    auto e = it->second.release();\r\n    entries.erase(it);\r\n    insert(name, e);\r\n}\r\n\r\nbool cpio::mv(const char *from, const char *to) {\r\n    auto it = entries.find(from);\r\n    if (it != entries.end()) {\r\n        mv(it, to);\r\n        return true;\r\n    }\r\n    fprintf(stderr, \"Cannot find entry %s\\n\", from);\r\n    return false;\r\n}\r\n\r\n#define pos_align(p) p = align_to(p, 4)\r\n\r\nvoid cpio::load_cpio(const char *buf, size_t sz) {\r\n    size_t pos = 0;\r\n    while (pos < sz) {\r\n        auto hdr = reinterpret_cast<const cpio_newc_header *>(buf + pos);\r\n        if (memcmp(hdr->magic, \"070701\", 6) != 0)\r\n            LOGE(\"bad cpio header\\n\");\r\n        pos += sizeof(cpio_newc_header);\r\n        string_view name(buf + pos);\r\n        pos += x8u(hdr->namesize);\r\n        pos_align(pos);\r\n        if (name == \".\" || name == \"..\")\r\n            continue;\r\n        if (name == \"TRAILER!!!\") {\r\n            // Android support multiple CPIO being concatenated\r\n            // Search for the next cpio header\r\n            auto next = static_cast<const char *>(memmem(buf + pos, sz - pos, \"070701\", 6));\r\n            if (next == nullptr)\r\n                break;\r\n            pos = next - buf;\r\n            continue;\r\n        }\r\n        auto entry = new cpio_entry(hdr);\r\n        entry->data = xmalloc(entry->filesize);\r\n        memcpy(entry->data, buf + pos, entry->filesize);\r\n        pos += entry->filesize;\r\n        insert(name, entry);\r\n        pos_align(pos);\r\n    }\r\n}\r\n"
  },
  {
    "path": "cpio.hpp",
    "content": "#pragma once\r\n\r\n#include <stdint.h>\r\n#include <string>\r\n#include <memory>\r\n#include <map>\r\n#include <string_view>\r\n\r\nstruct cpio_newc_header;\r\n\r\nstruct cpio_entry {\r\n    uint32_t mode;\r\n    uint32_t uid;\r\n    uint32_t gid;\r\n    uint32_t filesize;\r\n    void *data;\r\n\r\n    explicit cpio_entry(uint32_t mode = 0);\r\n    explicit cpio_entry(uint32_t mode, uint32_t uid, uint32_t gid);\r\n    explicit cpio_entry(const cpio_newc_header *h);\r\n    ~cpio_entry() { free(data); }\r\n};\r\n\r\nclass cpio {\r\npublic:\r\n    struct StringCmp {\r\n        using is_transparent = void;\r\n        bool operator()(std::string_view a, std::string_view b) const {\r\n            return a < b;\r\n        }\r\n    };\r\n    using entry_map = std::map<std::string, std::unique_ptr<cpio_entry>, StringCmp>;\r\n\r\n    void load_cpio(const char *file);\r\n    void load_cpio(const char* dir, const char* config, bool sync);\r\n    void dump(const char *file);\r\n    void rm(const char *name, bool r = false);\r\n    void extract();\r\n    bool extract(const char *name, const char *file);\r\n    bool exists(const char *name);\r\n    void add(mode_t mode, const char *name, const char *file);\r\n    void mkdir(mode_t mode, const char *name);\r\n    void ln(const char *target, const char *name);\r\n    bool mv(const char *from, const char *to);\r\n\r\nprotected:\r\n    entry_map entries;\r\n\r\n    static void extract_entry(const entry_map::value_type &e, const char *file);\r\n    void rm(entry_map::iterator it);\r\n    void mv(entry_map::iterator it, const char *name);\r\n\r\nprivate:\r\n    void dump(FILE *out);\r\n    void insert(std::string_view name, cpio_entry *e);\r\n    void load_cpio(const char *buf, size_t sz);\r\n};\r\n"
  },
  {
    "path": "dll.rc",
    "content": "#include <windows.h>\r\n\r\nVS_VERSION_INFO VERSIONINFO\r\nFILEVERSION     1,0,0,0\r\nPRODUCTVERSION  1,0,0,0\r\nFILEFLAGSMASK      VS_FFI_FILEFLAGSMASK\r\n#ifdef SVB_DEBUG\r\n  FILEFLAGS        VS_FF_DEBUG | VS_FF_PRERELEASE\r\n#else\r\n  FILEFLAGS        0\r\n#endif\r\nFILEOS             VOS_NT_WINDOWS32\r\nFILETYPE           VFT_DLL\r\nFILESUBTYPE        VFT2_UNKNOWN\r\nBEGIN\r\n  BLOCK \"StringFileInfo\"\r\n  BEGIN\r\n    BLOCK \"040904E4\"\r\n    BEGIN\r\n      VALUE \"FileDescription\", \"magiskboot library\"\r\n      VALUE \"FileVersion\", \"1.0.0.0\"\r\n      VALUE \"ProductVersion\", \"1.0.0.0\"\r\n    END\r\n  END\r\n  BLOCK \"VarFileInfo\"\r\n  BEGIN\r\n    VALUE \"Translation\", 0x809, 1200\r\n  END\r\nEND"
  },
  {
    "path": "dtb.cpp",
    "content": "#include <bitset>\n#include <vector>\n#include <map>\n#include <libfdt.h>\n\n#include <base.hpp>\n\n#include \"magiskboot.hpp\"\n#include \"dtb.hpp\"\n#include \"format.hpp\"\n\nusing namespace std;\n\nconstexpr int MAX_DEPTH = 32;\nstatic bitset<MAX_DEPTH> depth_set;\n\nstatic void pretty_node(int depth) {\n    if (depth == 0)\n        return;\n\n    for (int i = 0; i < depth - 1; ++i)\n        printf(depth_set[i] ? \"│   \" : \"    \");\n\n    printf(depth_set[depth - 1] ? \"├── \" : \"└── \");\n}\n\nstatic void pretty_prop(int depth) {\n    for (int i = 0; i < depth; ++i)\n        printf(depth_set[i] ? \"│   \" : \"    \");\n\n    printf(depth_set[depth] ? \"│  \" : \"   \");\n}\n\nstatic void print_node(const void *fdt, int node = 0, int depth = 0) {\n    // Print node itself\n    pretty_node(depth);\n    printf(\"#%d: %s\\n\", node, fdt_get_name(fdt, node, nullptr));\n\n    // Print properties\n    depth_set[depth] = fdt_first_subnode(fdt, node) >= 0;\n    int prop;\n    fdt_for_each_property_offset(prop, fdt, node) {\n        pretty_prop(depth);\n        int size;\n        const char *name;\n        auto value = static_cast<const char *>(fdt_getprop_by_offset(fdt, prop, &name, &size));\n\n        bool is_str = !(size > 1 && value[0] == 0);\n        if (is_str) {\n            // Scan through value to see if printable\n            for (int i = 0; i < size; ++i) {\n                char c = value[i];\n                if (i == size - 1) {\n                    // Make sure null terminate\n                    is_str = c == '\\0';\n                } else if ((c > 0 && c < 32) || c >= 127) {\n                    is_str = false;\n                    break;\n                }\n            }\n        }\n\n        if (is_str) {\n            printf(\"[%s]: [%s]\\n\", name, value);\n        } else {\n            printf(\"[%s]: <bytes>(%d)\\n\", name, size);\n        }\n    }\n\n    // Recursive\n    if (depth_set[depth]) {\n        int child;\n        int prev = -1;\n        fdt_for_each_subnode(child, fdt, node) {\n            if (prev >= 0)\n                print_node(fdt, prev, depth + 1);\n            prev = child;\n        }\n        depth_set[depth] = false;\n        print_node(fdt, prev, depth + 1);\n    }\n}\n\nstatic int find_fstab(const void *fdt, int node = 0) {\n    if (auto name = fdt_get_name(fdt, node, nullptr); name && name == \"fstab\"sv)\n        return node;\n    int child;\n    fdt_for_each_subnode(child, fdt, node) {\n        int fstab = find_fstab(fdt, child);\n        if (fstab >= 0)\n            return fstab;\n    }\n    return -1;\n}\n\ntemplate<typename Func>\nstatic void for_each_fdt(const char *file, bool rw, Func fn) {\n    auto m = mmap_data(file, rw);\n    uint8_t *end = m.buf + m.sz;\n    for (uint8_t *fdt = m.buf; fdt < end;) {\n        fdt = static_cast<uint8_t*>(memmem(fdt, end - fdt, DTB_MAGIC, sizeof(fdt32_t)));\n        if (fdt == nullptr)\n            break;\n        fn(fdt);\n        fdt += fdt_totalsize(fdt);\n    }\n}\n\nstatic void dtb_print(const char *file, bool fstab) {\n    fprintf(stderr, \"Loading dtbs from [%s]\\n\", file);\n    int dtb_num = 0;\n    for_each_fdt(file, false, [&](uint8_t *fdt) {\n        if (fstab) {\n            if (int node = find_fstab(fdt); node >= 0) {\n                fprintf(stderr, \"Found fstab in dtb.%04d\\n\", dtb_num);\n                print_node(fdt, node);\n            }\n        } else {\n            fprintf(stderr, \"Printing dtb.%04d\\n\", dtb_num);\n            print_node(fdt);\n        }\n        ++dtb_num;\n    });\n    fprintf(stderr, \"\\n\");\n}\n\nstatic bool dtb_patch(const char *file) {\n    fprintf(stderr, \"Loading dtbs from [%s]\\n\", file);\n\n    bool keep_verity = check_env(\"KEEPVERITY\");\n    bool patched = false;\n    for_each_fdt(file, true, [&](uint8_t *fdt) {\n        int node;\n        // Patch the chosen node for bootargs\n        fdt_for_each_subnode(node, fdt, 0) {\n            if (auto name = fdt_get_name(fdt, node, nullptr); !name || name != \"chosen\"sv)\n                continue;\n            int len;\n            if (auto value = fdt_getprop(fdt, node, \"bootargs\", &len)) {\n                if (void *skip = memmem(value, len, \"skip_initramfs\", 14)) {\n                    fprintf(stderr, \"Patch [skip_initramfs] -> [want_initramfs]\\n\");\n                    memcpy(skip, \"want\", 4);\n                    patched = true;\n                }\n            }\n            break;\n        }\n        if (!keep_verity) {\n            if (int fstab = find_fstab(fdt); fstab >= 0) {\n                fdt_for_each_subnode(node, fdt, fstab) {\n                    int len;\n                    char *value = (char *) fdt_getprop(fdt, node, \"fsmgr_flags\", &len);\n                    patched |= patch_verity(value, len) != len;\n                }\n            }\n        }\n    });\n    return patched;\n}\n\n[[noreturn]]\nstatic void dtb_test(const char *file) {\n    for_each_fdt(file, false, [&](uint8_t *fdt) {\n        // Find the system node in fstab\n        if (int fstab = find_fstab(fdt); fstab >= 0) {\n            int node;\n            fdt_for_each_subnode(node, fdt, fstab) {\n                if (auto name = fdt_get_name(fdt, node, nullptr); !name || name != \"system\"sv)\n                    continue;\n                int len;\n                if (auto value = fdt_getprop(fdt, node, \"mnt_point\", &len)) {\n                    // If mnt_point is set to /system_root, abort!\n                    if (strncmp(static_cast<const char *>(value), \"/system_root\", len) == 0) {\n                        exit(1);\n                    }\n                }\n            }\n        }\n    });\n    exit(0);\n}\n\nint dtb_commands(int argc, char *argv[]) {\n    char *dtb = argv[0];\n    ++argv;\n    --argc;\n\n    if (argv[0] == \"print\"sv) {\n        dtb_print(dtb, argc > 1 && argv[1] == \"-f\"sv);\n        return 0;\n    } else if (argv[0] == \"patch\"sv) {\n        if (!dtb_patch(dtb))\n            exit(1);\n        return 0;\n    } else if (argv[0] == \"test\"sv) {\n        dtb_test(dtb);\n    } else {\n        return 1;\n    }\n}\n\n// The following code is unused, left here for historical purpose. Since the code is\n// extremely complicated, I won't want to rewrite this whole thing if somehow we need\n// to use it in the future...\n\nnamespace {\n\nstruct fdt_blob {\n    void *fdt;\n    uint32_t offset;\n    uint32_t len;\n};\n\nstatic bool fdt_patch(void *fdt) {\n    int fstab = find_fstab(fdt);\n    if (fstab < 0)\n        return false;\n    bool modified = false;\n    int node;\n    fdt_for_each_subnode(node, fdt, fstab) {\n        const char *name = fdt_get_name(fdt, node, nullptr);\n        // Force remove AVB for 2SI since it may bootloop some devices\n        int len;\n        auto value = (const char *) fdt_getprop(fdt, node, \"fsmgr_flags\", &len);\n        string copy(value, len);\n        uint32_t new_len = patch_verity(copy.data(), len);\n        if (new_len != len) {\n            modified = true;\n            fdt_setprop(fdt, node, \"fsmgr_flags\", copy.data(), new_len);\n        }\n        if (name == \"system\"sv) {\n            fprintf(stderr, \"Setting [mnt_point] to [/system_root]\\n\");\n            fdt_setprop_string(fdt, node, \"mnt_point\", \"/system_root\");\n            modified = true;\n        }\n    }\n    return modified;\n}\n\n#define MAX_FDT_GROWTH 256\n\ntemplate <class Table, class Header>\nstatic bool dt_table_patch(const Header *hdr, const char *out) {\n    map<uint32_t, fdt_blob> dtb_map;\n    auto buf = reinterpret_cast<const uint8_t *>(hdr);\n    auto tables = reinterpret_cast<const Table *>(buf + sizeof(Header));\n\n    constexpr bool is_aosp = std::is_same_v<Header, dt_table_header>;\n\n    // AOSP DTB store ints in big endian\n    using endian_conv = uint32_t (*)(uint32_t);\n    endian_conv be_to_le;\n    endian_conv le_to_be;\n    if constexpr (is_aosp) {\n        be_to_le = fdt32_to_cpu;\n        le_to_be = cpu_to_fdt32;\n    } else {\n        be_to_le = le_to_be = [](uint32_t x) { return x; };\n    }\n\n    // Collect all dtbs\n    auto num_dtb = be_to_le(hdr->num_dtbs);\n    for (int i = 0; i < num_dtb; ++i) {\n        auto offset = be_to_le(tables[i].offset);\n        if (dtb_map.count(offset) == 0) {\n            auto blob = buf + offset;\n            uint32_t size = fdt_totalsize(blob);\n            auto fdt = xmalloc(size + MAX_FDT_GROWTH);\n            memcpy(fdt, blob, size);\n            fdt_open_into(fdt, fdt, size + MAX_FDT_GROWTH);\n            dtb_map[offset] = { fdt, offset };\n        }\n    }\n    if (dtb_map.empty())\n        return false;\n\n    // Patch fdt\n    bool modified = false;\n    for (auto &[_, blob] : dtb_map)\n        modified |= fdt_patch(blob.fdt);\n    if (!modified)\n        return false;\n\n    unlink(out);\n    int fd = xopen(out, O_RDWR | O_CREAT | O_CLOEXEC, 0644);\n\n    // This value is only used if AOSP DTB\n    uint32_t total_size = 0;\n\n    // Copy headers and tables\n    total_size += xwrite(fd, buf, dtb_map.begin()->first);\n\n    // mmap rw to patch table values retroactively\n    auto mmap_sz = lseek(fd, 0, SEEK_CUR);\n    auto addr = (uint8_t *) xmmap(nullptr, mmap_sz, PROT_READ | PROT_WRITE, MAP_SHARED, fd, 0);\n\n    // Guess alignment using gcd\n    uint32_t align = 1;\n    if constexpr (!is_aosp) {\n        auto it = dtb_map.begin();\n        align = (it++)->first;\n        for (; it != dtb_map.end(); ++it)\n            align = binary_gcd(align, it->first);\n    }\n\n    // Write dtbs\n    for (auto &val : dtb_map) {\n        val.second.offset = lseek(fd, 0, SEEK_CUR);\n        auto fdt = val.second.fdt;\n        fdt_pack(fdt);\n        auto size = fdt_totalsize(fdt);\n        total_size += xwrite(fd, fdt, size);\n        if constexpr (!is_aosp) {\n            val.second.len = align_to(size, align);\n            write_zero(fd, align_padding(lseek(fd, 0, SEEK_CUR), align));\n        }\n        free(fdt);\n    }\n\n    // Patch headers\n    if constexpr (is_aosp) {\n        auto hdr_rw = reinterpret_cast<Header *>(addr);\n        hdr_rw->total_size = le_to_be(total_size);\n    }\n    auto tables_rw = reinterpret_cast<Table *>(addr + sizeof(Header));\n    for (int i = 0; i < num_dtb; ++i) {\n        auto &blob = dtb_map[be_to_le(tables_rw[i].offset)];\n        tables_rw[i].offset = le_to_be(blob.offset);\n        tables_rw[i].len = le_to_be(blob.len);\n    }\n\n    munmap(addr, mmap_sz);\n    close(fd);\n\n    return true;\n}\n\nstatic bool blob_patch(uint8_t *dtb, size_t dtb_sz, const char *out) {\n    vector<uint8_t *> fdt_list;\n    vector<uint32_t> padding_list;\n\n    uint8_t * const end = dtb + dtb_sz;\n    for (uint8_t *curr = dtb; curr < end;) {\n        curr = static_cast<uint8_t*>(memmem(curr, end - curr, DTB_MAGIC, sizeof(fdt32_t)));\n        if (curr == nullptr)\n            break;\n        auto len = fdt_totalsize(curr);\n        auto fdt = static_cast<uint8_t *>(xmalloc(len + MAX_FDT_GROWTH));\n        memcpy(fdt, curr, len);\n        fdt_pack(fdt);\n        uint32_t padding = len - fdt_totalsize(fdt);\n        padding_list.push_back(padding);\n        fdt_open_into(fdt, fdt, len + MAX_FDT_GROWTH);\n        fdt_list.push_back(fdt);\n        curr += len;\n    }\n\n    bool modified = false;\n    for (auto fdt : fdt_list)\n        modified |= fdt_patch(fdt);\n    if (!modified)\n        return false;\n\n    unlink(out);\n    int fd = xopen(out, O_WRONLY | O_CREAT | O_CLOEXEC, 0644);\n\n    for (int i = 0; i < fdt_list.size(); ++i) {\n        auto fdt = fdt_list[i];\n        fdt_pack(fdt);\n        // Only add padding back if it is anything meaningful\n        if (padding_list[i] > 4) {\n            auto len = fdt_totalsize(fdt);\n            fdt_set_totalsize(fdt, len + padding_list[i]);\n        }\n        xwrite(fd, fdt, fdt_totalsize(fdt));\n        free(fdt);\n    }\n    close(fd);\n\n    return true;\n}\n\n#define DTB_MATCH(s) BUFFER_MATCH(dtb, s)\n\n[[maybe_unused]]\nstatic bool dtb_patch_rebuild(uint8_t *dtb, size_t dtb_sz, const char *file) {\n    if (DTB_MATCH(QCDT_MAGIC)) {\n        auto hdr = reinterpret_cast<qcdt_hdr*>(dtb);\n        switch (hdr->version) {\n            case 1:\n                fprintf(stderr, \"QCDT v1\\n\");\n                return dt_table_patch<qctable_v1>(hdr, file);\n            case 2:\n                fprintf(stderr, \"QCDT v2\\n\");\n                return dt_table_patch<qctable_v2>(hdr, file);\n            case 3:\n                fprintf(stderr, \"QCDT v3\\n\");\n                return dt_table_patch<qctable_v3>(hdr, file);\n            default:\n                return false;\n        }\n    } else if (DTB_MATCH(DTBH_MAGIC)) {\n        auto hdr = reinterpret_cast<dtbh_hdr *>(dtb);\n        switch (hdr->version) {\n            case 2:\n                fprintf(stderr, \"DTBH v2\\n\");\n                return dt_table_patch<bhtable_v2>(hdr, file);\n            default:\n                return false;\n        }\n    } else if (DTB_MATCH(PXADT_MAGIC)) {\n        auto hdr = reinterpret_cast<pxadt_hdr *>(dtb);\n        switch (hdr->version) {\n            case 1:\n                fprintf(stderr, \"PXA-DT v1\\n\");\n                return dt_table_patch<pxatable_v1>(hdr, file);\n            default:\n                return false;\n        }\n    } else if (DTB_MATCH(PXA19xx_MAGIC)) {\n        auto hdr = reinterpret_cast<pxa19xx_hdr *>(dtb);\n        switch (hdr->version) {\n            case 1:\n                fprintf(stderr, \"PXA-19xx v1\\n\");\n                return dt_table_patch<pxatable_v1>(hdr, file);\n            default:\n                return false;\n        }\n    } else if (DTB_MATCH(SPRD_MAGIC)) {\n        auto hdr = reinterpret_cast<sprd_hdr *>(dtb);\n        switch (hdr->version) {\n            case 1:\n                fprintf(stderr, \"SPRD v1\\n\");\n                return dt_table_patch<sprdtable_v1>(hdr, file);\n            default:\n                return false;\n        }\n    } else if (DTB_MATCH(DT_TABLE_MAGIC)) {\n        auto hdr = reinterpret_cast<dt_table_header *>(dtb);\n        switch (hdr->version) {\n            case 0:\n                fprintf(stderr, \"DT_TABLE v0\\n\");\n                return dt_table_patch<dt_table_entry>(hdr, file);\n            default:\n                return false;\n        }\n    } else {\n        return blob_patch(dtb, dtb_sz, file);\n    }\n}\n\n} // namespace\n"
  },
  {
    "path": "dtb.hpp",
    "content": "#pragma once\n\n#include <stdint.h>\n\n#define DT_TABLE_MAGIC  \"\\xd7\\xb7\\xab\\x1e\"\n#define QCDT_MAGIC      \"QCDT\"\n#define DTBH_MAGIC      \"DTBH\"\n#define PXADT_MAGIC     \"PXA-DT\"\n#define PXA19xx_MAGIC   \"PXA-19xx\"\n#define SPRD_MAGIC      \"SPRD\"\n\nstruct qcdt_hdr {\n    char magic[4];          /* \"QCDT\" */\n    uint32_t version;       /* QCDT version */\n    uint32_t num_dtbs;      /* Number of DTBs */\n} __attribute__((packed));\n\nstruct qctable_v1 {\n    uint32_t cpu_info[3];   /* Some CPU info */\n    uint32_t offset;        /* DTB offset in QCDT */\n    uint32_t len;           /* DTB size */\n} __attribute__((packed));\n\nstruct qctable_v2 {\n    uint32_t cpu_info[4];   /* Some CPU info */\n    uint32_t offset;        /* DTB offset in QCDT */\n    uint32_t len;           /* DTB size */\n} __attribute__((packed));\n\nstruct qctable_v3 {\n    uint32_t cpu_info[8];   /* Some CPU info */\n    uint32_t offset;        /* DTB offset in QCDT */\n    uint32_t len;           /* DTB size */\n} __attribute__((packed));\n\nstruct dtbh_hdr {\n    char magic[4];          /* \"DTBH\" */\n    uint32_t version;       /* DTBH version */\n    uint32_t num_dtbs;      /* Number of DTBs */\n} __attribute__((packed));\n\nstruct bhtable_v2 {\n    uint32_t cpu_info[5];   /* Some CPU info */\n    uint32_t offset;        /* DTB offset in DTBH */\n    uint32_t len;           /* DTB size */\n    uint32_t space;         /* 0x00000020 */\n} __attribute__((packed));\n\nstruct pxadt_hdr {\n    char magic[6];          /* \"PXA-DT\" */\n    uint32_t version;       /* PXA-* version */\n    uint32_t num_dtbs;      /* Number of DTBs */\n} __attribute__((packed));\n\nstruct pxa19xx_hdr {\n    char magic[8];          /* \"PXA-19xx\" */\n    uint32_t version;       /* PXA-* version */\n    uint32_t num_dtbs;      /* Number of DTBs */\n} __attribute__((packed));\n\nstruct pxatable_v1 {\n    uint32_t cpu_info[2];   /* Some CPU info */\n    uint32_t offset;        /* DTB offset in PXA-* */\n    uint32_t len;           /* DTB size */\n} __attribute__((packed));\n\nstruct sprd_hdr {\n    char magic[4];          /* \"SPRD\" */\n    uint32_t version;       /* SPRD version */\n    uint32_t num_dtbs;      /* Number of DTBs */\n} __attribute__((packed));\n\nstruct sprdtable_v1 {\n    uint32_t cpu_info[3];   /* Some CPU info */\n    uint32_t offset;        /* DTB offset in SPRD */\n    uint32_t len;           /* DTB size */\n} __attribute__((packed));\n\n/* AOSP DTB/DTBO partition layout */\n\nstruct dt_table_header {\n    uint32_t magic;             /* DT_TABLE_MAGIC */\n    uint32_t total_size;        /* includes dt_table_header + all dt_table_entry */\n    uint32_t header_size;       /* sizeof(dt_table_header) */\n\n    uint32_t dt_entry_size;     /* sizeof(dt_table_entry) */\n    uint32_t num_dtbs;          /* number of dt_table_entry */\n    uint32_t dt_entries_offset; /* offset to the first dt_table_entry */\n\n    uint32_t page_size;         /* flash page size we assume */\n    uint32_t version;           /* DTBO image version */\n} __attribute__((packed));\n\nstruct dt_table_entry {\n    uint32_t len;           /* DTB size */\n    uint32_t offset;\n\n    uint32_t id;\n    uint32_t rev;\n    uint32_t flags;\n\n    uint32_t custom[3];\n} __attribute__((packed));\n"
  },
  {
    "path": "external/bzip2/blocksort.c",
    "content": "\n/*-------------------------------------------------------------*/\n/*--- Block sorting machinery                               ---*/\n/*---                                           blocksort.c ---*/\n/*-------------------------------------------------------------*/\n\n/* ------------------------------------------------------------------\n   This file is part of bzip2/libbzip2, a program and library for\n   lossless, block-sorting data compression.\n\n   bzip2/libbzip2 version 1.0.6 of 6 September 2010\n   Copyright (C) 1996-2010 Julian Seward <jseward@bzip.org>\n\n   Please read the WARNING, DISCLAIMER and PATENTS sections in the \n   README file.\n\n   This program is released under the terms of the license contained\n   in the file LICENSE.\n   ------------------------------------------------------------------ */\n\n\n#include \"bzlib_private.h\"\n\n/*---------------------------------------------*/\n/*--- Fallback O(N log(N)^2) sorting        ---*/\n/*--- algorithm, for repetitive blocks      ---*/\n/*---------------------------------------------*/\n\n/*---------------------------------------------*/\nstatic \n__inline__\nvoid fallbackSimpleSort ( UInt32* fmap, \n                          UInt32* eclass, \n                          Int32   lo, \n                          Int32   hi )\n{\n   Int32 i, j, tmp;\n   UInt32 ec_tmp;\n\n   if (lo == hi) return;\n\n   if (hi - lo > 3) {\n      for ( i = hi-4; i >= lo; i-- ) {\n         tmp = fmap[i];\n         ec_tmp = eclass[tmp];\n         for ( j = i+4; j <= hi && ec_tmp > eclass[fmap[j]]; j += 4 )\n            fmap[j-4] = fmap[j];\n         fmap[j-4] = tmp;\n      }\n   }\n\n   for ( i = hi-1; i >= lo; i-- ) {\n      tmp = fmap[i];\n      ec_tmp = eclass[tmp];\n      for ( j = i+1; j <= hi && ec_tmp > eclass[fmap[j]]; j++ )\n         fmap[j-1] = fmap[j];\n      fmap[j-1] = tmp;\n   }\n}\n\n\n/*---------------------------------------------*/\n#define fswap(zz1, zz2) \\\n   { Int32 zztmp = zz1; zz1 = zz2; zz2 = zztmp; }\n\n#define fvswap(zzp1, zzp2, zzn)       \\\n{                                     \\\n   Int32 yyp1 = (zzp1);               \\\n   Int32 yyp2 = (zzp2);               \\\n   Int32 yyn  = (zzn);                \\\n   while (yyn > 0) {                  \\\n      fswap(fmap[yyp1], fmap[yyp2]);  \\\n      yyp1++; yyp2++; yyn--;          \\\n   }                                  \\\n}\n\n\n#define fmin(a,b) ((a) < (b)) ? (a) : (b)\n\n#define fpush(lz,hz) { stackLo[sp] = lz; \\\n                       stackHi[sp] = hz; \\\n                       sp++; }\n\n#define fpop(lz,hz) { sp--;              \\\n                      lz = stackLo[sp];  \\\n                      hz = stackHi[sp]; }\n\n#define FALLBACK_QSORT_SMALL_THRESH 10\n#define FALLBACK_QSORT_STACK_SIZE   100\n\n\nstatic\nvoid fallbackQSort3 ( UInt32* fmap, \n                      UInt32* eclass,\n                      Int32   loSt, \n                      Int32   hiSt )\n{\n   Int32 unLo, unHi, ltLo, gtHi, n, m;\n   Int32 sp, lo, hi;\n   UInt32 med, r, r3;\n   Int32 stackLo[FALLBACK_QSORT_STACK_SIZE];\n   Int32 stackHi[FALLBACK_QSORT_STACK_SIZE];\n\n   r = 0;\n\n   sp = 0;\n   fpush ( loSt, hiSt );\n\n   while (sp > 0) {\n\n      AssertH ( sp < FALLBACK_QSORT_STACK_SIZE - 1, 1004 );\n\n      fpop ( lo, hi );\n      if (hi - lo < FALLBACK_QSORT_SMALL_THRESH) {\n         fallbackSimpleSort ( fmap, eclass, lo, hi );\n         continue;\n      }\n\n      /* Random partitioning.  Median of 3 sometimes fails to\n         avoid bad cases.  Median of 9 seems to help but \n         looks rather expensive.  This too seems to work but\n         is cheaper.  Guidance for the magic constants \n         7621 and 32768 is taken from Sedgewick's algorithms\n         book, chapter 35.\n      */\n      r = ((r * 7621) + 1) % 32768;\n      r3 = r % 3;\n      if (r3 == 0) med = eclass[fmap[lo]]; else\n      if (r3 == 1) med = eclass[fmap[(lo+hi)>>1]]; else\n                   med = eclass[fmap[hi]];\n\n      unLo = ltLo = lo;\n      unHi = gtHi = hi;\n\n      while (1) {\n         while (1) {\n            if (unLo > unHi) break;\n            n = (Int32)eclass[fmap[unLo]] - (Int32)med;\n            if (n == 0) { \n               fswap(fmap[unLo], fmap[ltLo]); \n               ltLo++; unLo++; \n               continue; \n            };\n            if (n > 0) break;\n            unLo++;\n         }\n         while (1) {\n            if (unLo > unHi) break;\n            n = (Int32)eclass[fmap[unHi]] - (Int32)med;\n            if (n == 0) { \n               fswap(fmap[unHi], fmap[gtHi]); \n               gtHi--; unHi--; \n               continue; \n            };\n            if (n < 0) break;\n            unHi--;\n         }\n         if (unLo > unHi) break;\n         fswap(fmap[unLo], fmap[unHi]); unLo++; unHi--;\n      }\n\n      AssertD ( unHi == unLo-1, \"fallbackQSort3(2)\" );\n\n      if (gtHi < ltLo) continue;\n\n      n = fmin(ltLo-lo, unLo-ltLo); fvswap(lo, unLo-n, n);\n      m = fmin(hi-gtHi, gtHi-unHi); fvswap(unLo, hi-m+1, m);\n\n      n = lo + unLo - ltLo - 1;\n      m = hi - (gtHi - unHi) + 1;\n\n      if (n - lo > hi - m) {\n         fpush ( lo, n );\n         fpush ( m, hi );\n      } else {\n         fpush ( m, hi );\n         fpush ( lo, n );\n      }\n   }\n}\n\n#undef fmin\n#undef fpush\n#undef fpop\n#undef fswap\n#undef fvswap\n#undef FALLBACK_QSORT_SMALL_THRESH\n#undef FALLBACK_QSORT_STACK_SIZE\n\n\n/*---------------------------------------------*/\n/* Pre:\n      nblock > 0\n      eclass exists for [0 .. nblock-1]\n      ((UChar*)eclass) [0 .. nblock-1] holds block\n      ptr exists for [0 .. nblock-1]\n\n   Post:\n      ((UChar*)eclass) [0 .. nblock-1] holds block\n      All other areas of eclass destroyed\n      fmap [0 .. nblock-1] holds sorted order\n      bhtab [ 0 .. 2+(nblock/32) ] destroyed\n*/\n\n#define       SET_BH(zz)  bhtab[(zz) >> 5] |= (1 << ((zz) & 31))\n#define     CLEAR_BH(zz)  bhtab[(zz) >> 5] &= ~(1 << ((zz) & 31))\n#define     ISSET_BH(zz)  (bhtab[(zz) >> 5] & (1 << ((zz) & 31)))\n#define      WORD_BH(zz)  bhtab[(zz) >> 5]\n#define UNALIGNED_BH(zz)  ((zz) & 0x01f)\n\nstatic\nvoid fallbackSort ( UInt32* fmap, \n                    UInt32* eclass, \n                    UInt32* bhtab,\n                    Int32   nblock,\n                    Int32   verb )\n{\n   Int32 ftab[257];\n   Int32 ftabCopy[256];\n   Int32 H, i, j, k, l, r, cc, cc1;\n   Int32 nNotDone;\n   Int32 nBhtab;\n   UChar* eclass8 = (UChar*)eclass;\n\n   /*--\n      Initial 1-char radix sort to generate\n      initial fmap and initial BH bits.\n   --*/\n   if (verb >= 4)\n      VPrintf0 ( \"        bucket sorting ...\\n\" );\n   for (i = 0; i < 257;    i++) ftab[i] = 0;\n   for (i = 0; i < nblock; i++) ftab[eclass8[i]]++;\n   for (i = 0; i < 256;    i++) ftabCopy[i] = ftab[i];\n   for (i = 1; i < 257;    i++) ftab[i] += ftab[i-1];\n\n   for (i = 0; i < nblock; i++) {\n      j = eclass8[i];\n      k = ftab[j] - 1;\n      ftab[j] = k;\n      fmap[k] = i;\n   }\n\n   nBhtab = 2 + (nblock / 32);\n   for (i = 0; i < nBhtab; i++) bhtab[i] = 0;\n   for (i = 0; i < 256; i++) SET_BH(ftab[i]);\n\n   /*--\n      Inductively refine the buckets.  Kind-of an\n      \"exponential radix sort\" (!), inspired by the\n      Manber-Myers suffix array construction algorithm.\n   --*/\n\n   /*-- set sentinel bits for block-end detection --*/\n   for (i = 0; i < 32; i++) { \n      SET_BH(nblock + 2*i);\n      CLEAR_BH(nblock + 2*i + 1);\n   }\n\n   /*-- the log(N) loop --*/\n   H = 1;\n   while (1) {\n\n      if (verb >= 4) \n         VPrintf1 ( \"        depth %6d has \", H );\n\n      j = 0;\n      for (i = 0; i < nblock; i++) {\n         if (ISSET_BH(i)) j = i;\n         k = fmap[i] - H; if (k < 0) k += nblock;\n         eclass[k] = j;\n      }\n\n      nNotDone = 0;\n      r = -1;\n      while (1) {\n\n\t /*-- find the next non-singleton bucket --*/\n         k = r + 1;\n         while (ISSET_BH(k) && UNALIGNED_BH(k)) k++;\n         if (ISSET_BH(k)) {\n            while (WORD_BH(k) == 0xffffffff) k += 32;\n            while (ISSET_BH(k)) k++;\n         }\n         l = k - 1;\n         if (l >= nblock) break;\n         while (!ISSET_BH(k) && UNALIGNED_BH(k)) k++;\n         if (!ISSET_BH(k)) {\n            while (WORD_BH(k) == 0x00000000) k += 32;\n            while (!ISSET_BH(k)) k++;\n         }\n         r = k - 1;\n         if (r >= nblock) break;\n\n         /*-- now [l, r] bracket current bucket --*/\n         if (r > l) {\n            nNotDone += (r - l + 1);\n            fallbackQSort3 ( fmap, eclass, l, r );\n\n            /*-- scan bucket and generate header bits-- */\n            cc = -1;\n            for (i = l; i <= r; i++) {\n               cc1 = eclass[fmap[i]];\n               if (cc != cc1) { SET_BH(i); cc = cc1; };\n            }\n         }\n      }\n\n      if (verb >= 4) \n         VPrintf1 ( \"%6d unresolved strings\\n\", nNotDone );\n\n      H *= 2;\n      if (H > nblock || nNotDone == 0) break;\n   }\n\n   /*-- \n      Reconstruct the original block in\n      eclass8 [0 .. nblock-1], since the\n      previous phase destroyed it.\n   --*/\n   if (verb >= 4)\n      VPrintf0 ( \"        reconstructing block ...\\n\" );\n   j = 0;\n   for (i = 0; i < nblock; i++) {\n      while (ftabCopy[j] == 0) j++;\n      ftabCopy[j]--;\n      eclass8[fmap[i]] = (UChar)j;\n   }\n   AssertH ( j < 256, 1005 );\n}\n\n#undef       SET_BH\n#undef     CLEAR_BH\n#undef     ISSET_BH\n#undef      WORD_BH\n#undef UNALIGNED_BH\n\n\n/*---------------------------------------------*/\n/*--- The main, O(N^2 log(N)) sorting       ---*/\n/*--- algorithm.  Faster for \"normal\"       ---*/\n/*--- non-repetitive blocks.                ---*/\n/*---------------------------------------------*/\n\n/*---------------------------------------------*/\nstatic\n__inline__\nBool mainGtU ( UInt32  i1, \n               UInt32  i2,\n               UChar*  block, \n               UInt16* quadrant,\n               UInt32  nblock,\n               Int32*  budget )\n{\n   Int32  k;\n   UChar  c1, c2;\n   UInt16 s1, s2;\n\n   AssertD ( i1 != i2, \"mainGtU\" );\n   /* 1 */\n   c1 = block[i1]; c2 = block[i2];\n   if (c1 != c2) return (c1 > c2);\n   i1++; i2++;\n   /* 2 */\n   c1 = block[i1]; c2 = block[i2];\n   if (c1 != c2) return (c1 > c2);\n   i1++; i2++;\n   /* 3 */\n   c1 = block[i1]; c2 = block[i2];\n   if (c1 != c2) return (c1 > c2);\n   i1++; i2++;\n   /* 4 */\n   c1 = block[i1]; c2 = block[i2];\n   if (c1 != c2) return (c1 > c2);\n   i1++; i2++;\n   /* 5 */\n   c1 = block[i1]; c2 = block[i2];\n   if (c1 != c2) return (c1 > c2);\n   i1++; i2++;\n   /* 6 */\n   c1 = block[i1]; c2 = block[i2];\n   if (c1 != c2) return (c1 > c2);\n   i1++; i2++;\n   /* 7 */\n   c1 = block[i1]; c2 = block[i2];\n   if (c1 != c2) return (c1 > c2);\n   i1++; i2++;\n   /* 8 */\n   c1 = block[i1]; c2 = block[i2];\n   if (c1 != c2) return (c1 > c2);\n   i1++; i2++;\n   /* 9 */\n   c1 = block[i1]; c2 = block[i2];\n   if (c1 != c2) return (c1 > c2);\n   i1++; i2++;\n   /* 10 */\n   c1 = block[i1]; c2 = block[i2];\n   if (c1 != c2) return (c1 > c2);\n   i1++; i2++;\n   /* 11 */\n   c1 = block[i1]; c2 = block[i2];\n   if (c1 != c2) return (c1 > c2);\n   i1++; i2++;\n   /* 12 */\n   c1 = block[i1]; c2 = block[i2];\n   if (c1 != c2) return (c1 > c2);\n   i1++; i2++;\n\n   k = nblock + 8;\n\n   do {\n      /* 1 */\n      c1 = block[i1]; c2 = block[i2];\n      if (c1 != c2) return (c1 > c2);\n      s1 = quadrant[i1]; s2 = quadrant[i2];\n      if (s1 != s2) return (s1 > s2);\n      i1++; i2++;\n      /* 2 */\n      c1 = block[i1]; c2 = block[i2];\n      if (c1 != c2) return (c1 > c2);\n      s1 = quadrant[i1]; s2 = quadrant[i2];\n      if (s1 != s2) return (s1 > s2);\n      i1++; i2++;\n      /* 3 */\n      c1 = block[i1]; c2 = block[i2];\n      if (c1 != c2) return (c1 > c2);\n      s1 = quadrant[i1]; s2 = quadrant[i2];\n      if (s1 != s2) return (s1 > s2);\n      i1++; i2++;\n      /* 4 */\n      c1 = block[i1]; c2 = block[i2];\n      if (c1 != c2) return (c1 > c2);\n      s1 = quadrant[i1]; s2 = quadrant[i2];\n      if (s1 != s2) return (s1 > s2);\n      i1++; i2++;\n      /* 5 */\n      c1 = block[i1]; c2 = block[i2];\n      if (c1 != c2) return (c1 > c2);\n      s1 = quadrant[i1]; s2 = quadrant[i2];\n      if (s1 != s2) return (s1 > s2);\n      i1++; i2++;\n      /* 6 */\n      c1 = block[i1]; c2 = block[i2];\n      if (c1 != c2) return (c1 > c2);\n      s1 = quadrant[i1]; s2 = quadrant[i2];\n      if (s1 != s2) return (s1 > s2);\n      i1++; i2++;\n      /* 7 */\n      c1 = block[i1]; c2 = block[i2];\n      if (c1 != c2) return (c1 > c2);\n      s1 = quadrant[i1]; s2 = quadrant[i2];\n      if (s1 != s2) return (s1 > s2);\n      i1++; i2++;\n      /* 8 */\n      c1 = block[i1]; c2 = block[i2];\n      if (c1 != c2) return (c1 > c2);\n      s1 = quadrant[i1]; s2 = quadrant[i2];\n      if (s1 != s2) return (s1 > s2);\n      i1++; i2++;\n\n      if (i1 >= nblock) i1 -= nblock;\n      if (i2 >= nblock) i2 -= nblock;\n\n      k -= 8;\n      (*budget)--;\n   }\n      while (k >= 0);\n\n   return False;\n}\n\n\n/*---------------------------------------------*/\n/*--\n   Knuth's increments seem to work better\n   than Incerpi-Sedgewick here.  Possibly\n   because the number of elems to sort is\n   usually small, typically <= 20.\n--*/\nstatic\nInt32 incs[14] = { 1, 4, 13, 40, 121, 364, 1093, 3280,\n                   9841, 29524, 88573, 265720,\n                   797161, 2391484 };\n\nstatic\nvoid mainSimpleSort ( UInt32* ptr,\n                      UChar*  block,\n                      UInt16* quadrant,\n                      Int32   nblock,\n                      Int32   lo, \n                      Int32   hi, \n                      Int32   d,\n                      Int32*  budget )\n{\n   Int32 i, j, h, bigN, hp;\n   UInt32 v;\n\n   bigN = hi - lo + 1;\n   if (bigN < 2) return;\n\n   hp = 0;\n   while (incs[hp] < bigN) hp++;\n   hp--;\n\n   for (; hp >= 0; hp--) {\n      h = incs[hp];\n\n      i = lo + h;\n      while (True) {\n\n         /*-- copy 1 --*/\n         if (i > hi) break;\n         v = ptr[i];\n         j = i;\n         while ( mainGtU ( \n                    ptr[j-h]+d, v+d, block, quadrant, nblock, budget \n                 ) ) {\n            ptr[j] = ptr[j-h];\n            j = j - h;\n            if (j <= (lo + h - 1)) break;\n         }\n         ptr[j] = v;\n         i++;\n\n         /*-- copy 2 --*/\n         if (i > hi) break;\n         v = ptr[i];\n         j = i;\n         while ( mainGtU ( \n                    ptr[j-h]+d, v+d, block, quadrant, nblock, budget \n                 ) ) {\n            ptr[j] = ptr[j-h];\n            j = j - h;\n            if (j <= (lo + h - 1)) break;\n         }\n         ptr[j] = v;\n         i++;\n\n         /*-- copy 3 --*/\n         if (i > hi) break;\n         v = ptr[i];\n         j = i;\n         while ( mainGtU ( \n                    ptr[j-h]+d, v+d, block, quadrant, nblock, budget \n                 ) ) {\n            ptr[j] = ptr[j-h];\n            j = j - h;\n            if (j <= (lo + h - 1)) break;\n         }\n         ptr[j] = v;\n         i++;\n\n         if (*budget < 0) return;\n      }\n   }\n}\n\n\n/*---------------------------------------------*/\n/*--\n   The following is an implementation of\n   an elegant 3-way quicksort for strings,\n   described in a paper \"Fast Algorithms for\n   Sorting and Searching Strings\", by Robert\n   Sedgewick and Jon L. Bentley.\n--*/\n\n#define mswap(zz1, zz2) \\\n   { Int32 zztmp = zz1; zz1 = zz2; zz2 = zztmp; }\n\n#define mvswap(zzp1, zzp2, zzn)       \\\n{                                     \\\n   Int32 yyp1 = (zzp1);               \\\n   Int32 yyp2 = (zzp2);               \\\n   Int32 yyn  = (zzn);                \\\n   while (yyn > 0) {                  \\\n      mswap(ptr[yyp1], ptr[yyp2]);    \\\n      yyp1++; yyp2++; yyn--;          \\\n   }                                  \\\n}\n\nstatic \n__inline__\nUChar mmed3 ( UChar a, UChar b, UChar c )\n{\n   UChar t;\n   if (a > b) { t = a; a = b; b = t; };\n   if (b > c) { \n      b = c;\n      if (a > b) b = a;\n   }\n   return b;\n}\n\n#define mmin(a,b) ((a) < (b)) ? (a) : (b)\n\n#define mpush(lz,hz,dz) { stackLo[sp] = lz; \\\n                          stackHi[sp] = hz; \\\n                          stackD [sp] = dz; \\\n                          sp++; }\n\n#define mpop(lz,hz,dz) { sp--;             \\\n                         lz = stackLo[sp]; \\\n                         hz = stackHi[sp]; \\\n                         dz = stackD [sp]; }\n\n\n#define mnextsize(az) (nextHi[az]-nextLo[az])\n\n#define mnextswap(az,bz)                                        \\\n   { Int32 tz;                                                  \\\n     tz = nextLo[az]; nextLo[az] = nextLo[bz]; nextLo[bz] = tz; \\\n     tz = nextHi[az]; nextHi[az] = nextHi[bz]; nextHi[bz] = tz; \\\n     tz = nextD [az]; nextD [az] = nextD [bz]; nextD [bz] = tz; }\n\n\n#define MAIN_QSORT_SMALL_THRESH 20\n#define MAIN_QSORT_DEPTH_THRESH (BZ_N_RADIX + BZ_N_QSORT)\n#define MAIN_QSORT_STACK_SIZE 100\n\nstatic\nvoid mainQSort3 ( UInt32* ptr,\n                  UChar*  block,\n                  UInt16* quadrant,\n                  Int32   nblock,\n                  Int32   loSt, \n                  Int32   hiSt, \n                  Int32   dSt,\n                  Int32*  budget )\n{\n   Int32 unLo, unHi, ltLo, gtHi, n, m, med;\n   Int32 sp, lo, hi, d;\n\n   Int32 stackLo[MAIN_QSORT_STACK_SIZE];\n   Int32 stackHi[MAIN_QSORT_STACK_SIZE];\n   Int32 stackD [MAIN_QSORT_STACK_SIZE];\n\n   Int32 nextLo[3];\n   Int32 nextHi[3];\n   Int32 nextD [3];\n\n   sp = 0;\n   mpush ( loSt, hiSt, dSt );\n\n   while (sp > 0) {\n\n      AssertH ( sp < MAIN_QSORT_STACK_SIZE - 2, 1001 );\n\n      mpop ( lo, hi, d );\n      if (hi - lo < MAIN_QSORT_SMALL_THRESH || \n          d > MAIN_QSORT_DEPTH_THRESH) {\n         mainSimpleSort ( ptr, block, quadrant, nblock, lo, hi, d, budget );\n         if (*budget < 0) return;\n         continue;\n      }\n\n      med = (Int32) \n            mmed3 ( block[ptr[ lo         ]+d],\n                    block[ptr[ hi         ]+d],\n                    block[ptr[ (lo+hi)>>1 ]+d] );\n\n      unLo = ltLo = lo;\n      unHi = gtHi = hi;\n\n      while (True) {\n         while (True) {\n            if (unLo > unHi) break;\n            n = ((Int32)block[ptr[unLo]+d]) - med;\n            if (n == 0) { \n               mswap(ptr[unLo], ptr[ltLo]); \n               ltLo++; unLo++; continue; \n            };\n            if (n >  0) break;\n            unLo++;\n         }\n         while (True) {\n            if (unLo > unHi) break;\n            n = ((Int32)block[ptr[unHi]+d]) - med;\n            if (n == 0) { \n               mswap(ptr[unHi], ptr[gtHi]); \n               gtHi--; unHi--; continue; \n            };\n            if (n <  0) break;\n            unHi--;\n         }\n         if (unLo > unHi) break;\n         mswap(ptr[unLo], ptr[unHi]); unLo++; unHi--;\n      }\n\n      AssertD ( unHi == unLo-1, \"mainQSort3(2)\" );\n\n      if (gtHi < ltLo) {\n         mpush(lo, hi, d+1 );\n         continue;\n      }\n\n      n = mmin(ltLo-lo, unLo-ltLo); mvswap(lo, unLo-n, n);\n      m = mmin(hi-gtHi, gtHi-unHi); mvswap(unLo, hi-m+1, m);\n\n      n = lo + unLo - ltLo - 1;\n      m = hi - (gtHi - unHi) + 1;\n\n      nextLo[0] = lo;  nextHi[0] = n;   nextD[0] = d;\n      nextLo[1] = m;   nextHi[1] = hi;  nextD[1] = d;\n      nextLo[2] = n+1; nextHi[2] = m-1; nextD[2] = d+1;\n\n      if (mnextsize(0) < mnextsize(1)) mnextswap(0,1);\n      if (mnextsize(1) < mnextsize(2)) mnextswap(1,2);\n      if (mnextsize(0) < mnextsize(1)) mnextswap(0,1);\n\n      AssertD (mnextsize(0) >= mnextsize(1), \"mainQSort3(8)\" );\n      AssertD (mnextsize(1) >= mnextsize(2), \"mainQSort3(9)\" );\n\n      mpush (nextLo[0], nextHi[0], nextD[0]);\n      mpush (nextLo[1], nextHi[1], nextD[1]);\n      mpush (nextLo[2], nextHi[2], nextD[2]);\n   }\n}\n\n#undef mswap\n#undef mvswap\n#undef mpush\n#undef mpop\n#undef mmin\n#undef mnextsize\n#undef mnextswap\n#undef MAIN_QSORT_SMALL_THRESH\n#undef MAIN_QSORT_DEPTH_THRESH\n#undef MAIN_QSORT_STACK_SIZE\n\n\n/*---------------------------------------------*/\n/* Pre:\n      nblock > N_OVERSHOOT\n      block32 exists for [0 .. nblock-1 +N_OVERSHOOT]\n      ((UChar*)block32) [0 .. nblock-1] holds block\n      ptr exists for [0 .. nblock-1]\n\n   Post:\n      ((UChar*)block32) [0 .. nblock-1] holds block\n      All other areas of block32 destroyed\n      ftab [0 .. 65536 ] destroyed\n      ptr [0 .. nblock-1] holds sorted order\n      if (*budget < 0), sorting was abandoned\n*/\n\n#define BIGFREQ(b) (ftab[((b)+1) << 8] - ftab[(b) << 8])\n#define SETMASK (1 << 21)\n#define CLEARMASK (~(SETMASK))\n\nstatic\nvoid mainSort ( UInt32* ptr, \n                UChar*  block,\n                UInt16* quadrant, \n                UInt32* ftab,\n                Int32   nblock,\n                Int32   verb,\n                Int32*  budget )\n{\n   Int32  i, j, k, ss, sb;\n   Int32  runningOrder[256];\n   Bool   bigDone[256];\n   Int32  copyStart[256];\n   Int32  copyEnd  [256];\n   UChar  c1;\n   Int32  numQSorted;\n   UInt16 s;\n   if (verb >= 4) VPrintf0 ( \"        main sort initialise ...\\n\" );\n\n   /*-- set up the 2-byte frequency table --*/\n   for (i = 65536; i >= 0; i--) ftab[i] = 0;\n\n   j = block[0] << 8;\n   i = nblock-1;\n   for (; i >= 3; i -= 4) {\n      quadrant[i] = 0;\n      j = (j >> 8) | ( ((UInt16)block[i]) << 8);\n      ftab[j]++;\n      quadrant[i-1] = 0;\n      j = (j >> 8) | ( ((UInt16)block[i-1]) << 8);\n      ftab[j]++;\n      quadrant[i-2] = 0;\n      j = (j >> 8) | ( ((UInt16)block[i-2]) << 8);\n      ftab[j]++;\n      quadrant[i-3] = 0;\n      j = (j >> 8) | ( ((UInt16)block[i-3]) << 8);\n      ftab[j]++;\n   }\n   for (; i >= 0; i--) {\n      quadrant[i] = 0;\n      j = (j >> 8) | ( ((UInt16)block[i]) << 8);\n      ftab[j]++;\n   }\n\n   /*-- (emphasises close relationship of block & quadrant) --*/\n   for (i = 0; i < BZ_N_OVERSHOOT; i++) {\n      block   [nblock+i] = block[i];\n      quadrant[nblock+i] = 0;\n   }\n\n   if (verb >= 4) VPrintf0 ( \"        bucket sorting ...\\n\" );\n\n   /*-- Complete the initial radix sort --*/\n   for (i = 1; i <= 65536; i++) ftab[i] += ftab[i-1];\n\n   s = block[0] << 8;\n   i = nblock-1;\n   for (; i >= 3; i -= 4) {\n      s = (s >> 8) | (block[i] << 8);\n      j = ftab[s] -1;\n      ftab[s] = j;\n      ptr[j] = i;\n      s = (s >> 8) | (block[i-1] << 8);\n      j = ftab[s] -1;\n      ftab[s] = j;\n      ptr[j] = i-1;\n      s = (s >> 8) | (block[i-2] << 8);\n      j = ftab[s] -1;\n      ftab[s] = j;\n      ptr[j] = i-2;\n      s = (s >> 8) | (block[i-3] << 8);\n      j = ftab[s] -1;\n      ftab[s] = j;\n      ptr[j] = i-3;\n   }\n   for (; i >= 0; i--) {\n      s = (s >> 8) | (block[i] << 8);\n      j = ftab[s] -1;\n      ftab[s] = j;\n      ptr[j] = i;\n   }\n\n   /*--\n      Now ftab contains the first loc of every small bucket.\n      Calculate the running order, from smallest to largest\n      big bucket.\n   --*/\n   for (i = 0; i <= 255; i++) {\n      bigDone     [i] = False;\n      runningOrder[i] = i;\n   }\n\n   {\n      Int32 vv;\n      Int32 h = 1;\n      do h = 3 * h + 1; while (h <= 256);\n      do {\n         h = h / 3;\n         for (i = h; i <= 255; i++) {\n            vv = runningOrder[i];\n            j = i;\n            while ( BIGFREQ(runningOrder[j-h]) > BIGFREQ(vv) ) {\n               runningOrder[j] = runningOrder[j-h];\n               j = j - h;\n               if (j <= (h - 1)) goto zero;\n            }\n            zero:\n            runningOrder[j] = vv;\n         }\n      } while (h != 1);\n   }\n\n   /*--\n      The main sorting loop.\n   --*/\n\n   numQSorted = 0;\n\n   for (i = 0; i <= 255; i++) {\n\n      /*--\n         Process big buckets, starting with the least full.\n         Basically this is a 3-step process in which we call\n         mainQSort3 to sort the small buckets [ss, j], but\n         also make a big effort to avoid the calls if we can.\n      --*/\n      ss = runningOrder[i];\n\n      /*--\n         Step 1:\n         Complete the big bucket [ss] by quicksorting\n         any unsorted small buckets [ss, j], for j != ss.  \n         Hopefully previous pointer-scanning phases have already\n         completed many of the small buckets [ss, j], so\n         we don't have to sort them at all.\n      --*/\n      for (j = 0; j <= 255; j++) {\n         if (j != ss) {\n            sb = (ss << 8) + j;\n            if ( ! (ftab[sb] & SETMASK) ) {\n               Int32 lo = ftab[sb]   & CLEARMASK;\n               Int32 hi = (ftab[sb+1] & CLEARMASK) - 1;\n               if (hi > lo) {\n                  if (verb >= 4)\n                     VPrintf4 ( \"        qsort [0x%x, 0x%x]   \"\n                                \"done %d   this %d\\n\",\n                                ss, j, numQSorted, hi - lo + 1 );\n                  mainQSort3 ( \n                     ptr, block, quadrant, nblock, \n                     lo, hi, BZ_N_RADIX, budget \n                  );   \n                  numQSorted += (hi - lo + 1);\n                  if (*budget < 0) return;\n               }\n            }\n            ftab[sb] |= SETMASK;\n         }\n      }\n\n      AssertH ( !bigDone[ss], 1006 );\n\n      /*--\n         Step 2:\n         Now scan this big bucket [ss] so as to synthesise the\n         sorted order for small buckets [t, ss] for all t,\n         including, magically, the bucket [ss,ss] too.\n         This will avoid doing Real Work in subsequent Step 1's.\n      --*/\n      {\n         for (j = 0; j <= 255; j++) {\n            copyStart[j] =  ftab[(j << 8) + ss]     & CLEARMASK;\n            copyEnd  [j] = (ftab[(j << 8) + ss + 1] & CLEARMASK) - 1;\n         }\n         for (j = ftab[ss << 8] & CLEARMASK; j < copyStart[ss]; j++) {\n            k = ptr[j]-1; if (k < 0) k += nblock;\n            c1 = block[k];\n            if (!bigDone[c1])\n               ptr[ copyStart[c1]++ ] = k;\n         }\n         for (j = (ftab[(ss+1) << 8] & CLEARMASK) - 1; j > copyEnd[ss]; j--) {\n            k = ptr[j]-1; if (k < 0) k += nblock;\n            c1 = block[k];\n            if (!bigDone[c1]) \n               ptr[ copyEnd[c1]-- ] = k;\n         }\n      }\n\n      AssertH ( (copyStart[ss]-1 == copyEnd[ss])\n                || \n                /* Extremely rare case missing in bzip2-1.0.0 and 1.0.1.\n                   Necessity for this case is demonstrated by compressing \n                   a sequence of approximately 48.5 million of character \n                   251; 1.0.0/1.0.1 will then die here. */\n                (copyStart[ss] == 0 && copyEnd[ss] == nblock-1),\n                1007 )\n\n      for (j = 0; j <= 255; j++) ftab[(j << 8) + ss] |= SETMASK;\n\n      /*--\n         Step 3:\n         The [ss] big bucket is now done.  Record this fact,\n         and update the quadrant descriptors.  Remember to\n         update quadrants in the overshoot area too, if\n         necessary.  The \"if (i < 255)\" test merely skips\n         this updating for the last bucket processed, since\n         updating for the last bucket is pointless.\n\n         The quadrant array provides a way to incrementally\n         cache sort orderings, as they appear, so as to \n         make subsequent comparisons in fullGtU() complete\n         faster.  For repetitive blocks this makes a big\n         difference (but not big enough to be able to avoid\n         the fallback sorting mechanism, exponential radix sort).\n\n         The precise meaning is: at all times:\n\n            for 0 <= i < nblock and 0 <= j <= nblock\n\n            if block[i] != block[j], \n\n               then the relative values of quadrant[i] and \n                    quadrant[j] are meaningless.\n\n               else {\n                  if quadrant[i] < quadrant[j]\n                     then the string starting at i lexicographically\n                     precedes the string starting at j\n\n                  else if quadrant[i] > quadrant[j]\n                     then the string starting at j lexicographically\n                     precedes the string starting at i\n\n                  else\n                     the relative ordering of the strings starting\n                     at i and j has not yet been determined.\n               }\n      --*/\n      bigDone[ss] = True;\n\n      if (i < 255) {\n         Int32 bbStart  = ftab[ss << 8] & CLEARMASK;\n         Int32 bbSize   = (ftab[(ss+1) << 8] & CLEARMASK) - bbStart;\n         Int32 shifts   = 0;\n\n         while ((bbSize >> shifts) > 65534) shifts++;\n\n         for (j = bbSize-1; j >= 0; j--) {\n            Int32 a2update     = ptr[bbStart + j];\n            UInt16 qVal        = (UInt16)(j >> shifts);\n            quadrant[a2update] = qVal;\n            if (a2update < BZ_N_OVERSHOOT)\n               quadrant[a2update + nblock] = qVal;\n         }\n         AssertH ( ((bbSize-1) >> shifts) <= 65535, 1002 );\n      }\n\n   }\n\n   if (verb >= 4)\n      VPrintf3 ( \"        %d pointers, %d sorted, %d scanned\\n\",\n                 nblock, numQSorted, nblock - numQSorted );\n}\n\n#undef BIGFREQ\n#undef SETMASK\n#undef CLEARMASK\n\n\n/*---------------------------------------------*/\n/* Pre:\n      nblock > 0\n      arr2 exists for [0 .. nblock-1 +N_OVERSHOOT]\n      ((UChar*)arr2)  [0 .. nblock-1] holds block\n      arr1 exists for [0 .. nblock-1]\n\n   Post:\n      ((UChar*)arr2) [0 .. nblock-1] holds block\n      All other areas of block destroyed\n      ftab [ 0 .. 65536 ] destroyed\n      arr1 [0 .. nblock-1] holds sorted order\n*/\nvoid BZ2_blockSort ( EState* s )\n{\n   UInt32* ptr    = s->ptr; \n   UChar*  block  = s->block;\n   UInt32* ftab   = s->ftab;\n   Int32   nblock = s->nblock;\n   Int32   verb   = s->verbosity;\n   Int32   wfact  = s->workFactor;\n   UInt16* quadrant;\n   Int32   budget;\n   Int32   budgetInit;\n   Int32   i;\n\n   if (nblock < 10000) {\n      fallbackSort ( s->arr1, s->arr2, ftab, nblock, verb );\n   } else {\n      /* Calculate the location for quadrant, remembering to get\n         the alignment right.  Assumes that &(block[0]) is at least\n         2-byte aligned -- this should be ok since block is really\n         the first section of arr2.\n      */\n      i = nblock+BZ_N_OVERSHOOT;\n      if (i & 1) i++;\n      quadrant = (UInt16*)(&(block[i]));\n\n      /* (wfact-1) / 3 puts the default-factor-30\n         transition point at very roughly the same place as \n         with v0.1 and v0.9.0.  \n         Not that it particularly matters any more, since the\n         resulting compressed stream is now the same regardless\n         of whether or not we use the main sort or fallback sort.\n      */\n      if (wfact < 1  ) wfact = 1;\n      if (wfact > 100) wfact = 100;\n      budgetInit = nblock * ((wfact-1) / 3);\n      budget = budgetInit;\n\n      mainSort ( ptr, block, quadrant, ftab, nblock, verb, &budget );\n      if (verb >= 3) \n         VPrintf3 ( \"      %d work, %d block, ratio %5.2f\\n\",\n                    budgetInit - budget,\n                    nblock, \n                    (float)(budgetInit - budget) /\n                    (float)(nblock==0 ? 1 : nblock) ); \n      if (budget < 0) {\n         if (verb >= 2) \n            VPrintf0 ( \"    too repetitive; using fallback\"\n                       \" sorting algorithm\\n\" );\n         fallbackSort ( s->arr1, s->arr2, ftab, nblock, verb );\n      }\n   }\n\n   s->origPtr = -1;\n   for (i = 0; i < s->nblock; i++)\n      if (ptr[i] == 0)\n         { s->origPtr = i; break; };\n\n   AssertH( s->origPtr != -1, 1003 );\n}\n\n\n/*-------------------------------------------------------------*/\n/*--- end                                       blocksort.c ---*/\n/*-------------------------------------------------------------*/\n"
  },
  {
    "path": "external/bzip2/bzlib.c",
    "content": "\n/*-------------------------------------------------------------*/\n/*--- Library top-level functions.                          ---*/\n/*---                                               bzlib.c ---*/\n/*-------------------------------------------------------------*/\n\n/* ------------------------------------------------------------------\n   This file is part of bzip2/libbzip2, a program and library for\n   lossless, block-sorting data compression.\n\n   bzip2/libbzip2 version 1.0.6 of 6 September 2010\n   Copyright (C) 1996-2010 Julian Seward <jseward@bzip.org>\n\n   Please read the WARNING, DISCLAIMER and PATENTS sections in the \n   README file.\n\n   This program is released under the terms of the license contained\n   in the file LICENSE.\n   ------------------------------------------------------------------ */\n\n/* CHANGES\n   0.9.0    -- original version.\n   0.9.0a/b -- no changes in this file.\n   0.9.0c   -- made zero-length BZ_FLUSH work correctly in bzCompress().\n     fixed bzWrite/bzRead to ignore zero-length requests.\n     fixed bzread to correctly handle read requests after EOF.\n     wrong parameter order in call to bzDecompressInit in\n     bzBuffToBuffDecompress.  Fixed.\n*/\n\n#include \"bzlib_private.h\"\n\n\n/*---------------------------------------------------*/\n/*--- Compression stuff                           ---*/\n/*---------------------------------------------------*/\n\n\n/*---------------------------------------------------*/\n#ifndef BZ_NO_STDIO\nvoid BZ2_bz__AssertH__fail ( int errcode )\n{\n   fprintf(stderr, \n      \"\\n\\nbzip2/libbzip2: internal error number %d.\\n\"\n      \"This is a bug in bzip2/libbzip2, %s.\\n\"\n      \"Please report it to me at: jseward@bzip.org.  If this happened\\n\"\n      \"when you were using some program which uses libbzip2 as a\\n\"\n      \"component, you should also report this bug to the author(s)\\n\"\n      \"of that program.  Please make an effort to report this bug;\\n\"\n      \"timely and accurate bug reports eventually lead to higher\\n\"\n      \"quality software.  Thanks.  Julian Seward, 10 December 2007.\\n\\n\",\n      errcode,\n      BZ2_bzlibVersion()\n   );\n\n   if (errcode == 1007) {\n   fprintf(stderr,\n      \"\\n*** A special note about internal error number 1007 ***\\n\"\n      \"\\n\"\n      \"Experience suggests that a common cause of i.e. 1007\\n\"\n      \"is unreliable memory or other hardware.  The 1007 assertion\\n\"\n      \"just happens to cross-check the results of huge numbers of\\n\"\n      \"memory reads/writes, and so acts (unintendedly) as a stress\\n\"\n      \"test of your memory system.\\n\"\n      \"\\n\"\n      \"I suggest the following: try compressing the file again,\\n\"\n      \"possibly monitoring progress in detail with the -vv flag.\\n\"\n      \"\\n\"\n      \"* If the error cannot be reproduced, and/or happens at different\\n\"\n      \"  points in compression, you may have a flaky memory system.\\n\"\n      \"  Try a memory-test program.  I have used Memtest86\\n\"\n      \"  (www.memtest86.com).  At the time of writing it is free (GPLd).\\n\"\n      \"  Memtest86 tests memory much more thorougly than your BIOSs\\n\"\n      \"  power-on test, and may find failures that the BIOS doesn't.\\n\"\n      \"\\n\"\n      \"* If the error can be repeatably reproduced, this is a bug in\\n\"\n      \"  bzip2, and I would very much like to hear about it.  Please\\n\"\n      \"  let me know, and, ideally, save a copy of the file causing the\\n\"\n      \"  problem -- without which I will be unable to investigate it.\\n\"\n      \"\\n\"\n   );\n   }\n\n   exit(3);\n}\n#endif\n\n\n/*---------------------------------------------------*/\nstatic\nint bz_config_ok ( void )\n{\n   if (sizeof(int)   != 4) return 0;\n   if (sizeof(short) != 2) return 0;\n   if (sizeof(char)  != 1) return 0;\n   return 1;\n}\n\n\n/*---------------------------------------------------*/\nstatic\nvoid* default_bzalloc ( void* opaque, Int32 items, Int32 size )\n{\n   void* v = malloc ( items * size );\n   return v;\n}\n\nstatic\nvoid default_bzfree ( void* opaque, void* addr )\n{\n   if (addr != NULL) free ( addr );\n}\n\n\n/*---------------------------------------------------*/\nstatic\nvoid prepare_new_block ( EState* s )\n{\n   Int32 i;\n   s->nblock = 0;\n   s->numZ = 0;\n   s->state_out_pos = 0;\n   BZ_INITIALISE_CRC ( s->blockCRC );\n   for (i = 0; i < 256; i++) s->inUse[i] = False;\n   s->blockNo++;\n}\n\n\n/*---------------------------------------------------*/\nstatic\nvoid init_RL ( EState* s )\n{\n   s->state_in_ch  = 256;\n   s->state_in_len = 0;\n}\n\n\nstatic\nBool isempty_RL ( EState* s )\n{\n   if (s->state_in_ch < 256 && s->state_in_len > 0)\n      return False; else\n      return True;\n}\n\n\n/*---------------------------------------------------*/\nint BZ_API(BZ2_bzCompressInit) \n                    ( bz_stream* strm, \n                     int        blockSize100k,\n                     int        verbosity,\n                     int        workFactor )\n{\n   Int32   n;\n   EState* s;\n\n   if (!bz_config_ok()) return BZ_CONFIG_ERROR;\n\n   if (strm == NULL || \n       blockSize100k < 1 || blockSize100k > 9 ||\n       workFactor < 0 || workFactor > 250)\n     return BZ_PARAM_ERROR;\n\n   if (workFactor == 0) workFactor = 30;\n   if (strm->bzalloc == NULL) strm->bzalloc = default_bzalloc;\n   if (strm->bzfree == NULL) strm->bzfree = default_bzfree;\n\n   s = BZALLOC( sizeof(EState) );\n   if (s == NULL) return BZ_MEM_ERROR;\n   s->strm = strm;\n\n   s->arr1 = NULL;\n   s->arr2 = NULL;\n   s->ftab = NULL;\n\n   n       = 100000 * blockSize100k;\n   s->arr1 = BZALLOC( n                  * sizeof(UInt32) );\n   s->arr2 = BZALLOC( (n+BZ_N_OVERSHOOT) * sizeof(UInt32) );\n   s->ftab = BZALLOC( 65537              * sizeof(UInt32) );\n\n   if (s->arr1 == NULL || s->arr2 == NULL || s->ftab == NULL) {\n      if (s->arr1 != NULL) BZFREE(s->arr1);\n      if (s->arr2 != NULL) BZFREE(s->arr2);\n      if (s->ftab != NULL) BZFREE(s->ftab);\n      if (s       != NULL) BZFREE(s);\n      return BZ_MEM_ERROR;\n   }\n\n   s->blockNo           = 0;\n   s->state             = BZ_S_INPUT;\n   s->mode              = BZ_M_RUNNING;\n   s->combinedCRC       = 0;\n   s->blockSize100k     = blockSize100k;\n   s->nblockMAX         = 100000 * blockSize100k - 19;\n   s->verbosity         = verbosity;\n   s->workFactor        = workFactor;\n\n   s->block             = (UChar*)s->arr2;\n   s->mtfv              = (UInt16*)s->arr1;\n   s->zbits             = NULL;\n   s->ptr               = (UInt32*)s->arr1;\n\n   strm->state          = s;\n   strm->total_in_lo32  = 0;\n   strm->total_in_hi32  = 0;\n   strm->total_out_lo32 = 0;\n   strm->total_out_hi32 = 0;\n   init_RL ( s );\n   prepare_new_block ( s );\n   return BZ_OK;\n}\n\n\n/*---------------------------------------------------*/\nstatic\nvoid add_pair_to_block ( EState* s )\n{\n   Int32 i;\n   UChar ch = (UChar)(s->state_in_ch);\n   for (i = 0; i < s->state_in_len; i++) {\n      BZ_UPDATE_CRC( s->blockCRC, ch );\n   }\n   s->inUse[s->state_in_ch] = True;\n   switch (s->state_in_len) {\n      case 1:\n         s->block[s->nblock] = (UChar)ch; s->nblock++;\n         break;\n      case 2:\n         s->block[s->nblock] = (UChar)ch; s->nblock++;\n         s->block[s->nblock] = (UChar)ch; s->nblock++;\n         break;\n      case 3:\n         s->block[s->nblock] = (UChar)ch; s->nblock++;\n         s->block[s->nblock] = (UChar)ch; s->nblock++;\n         s->block[s->nblock] = (UChar)ch; s->nblock++;\n         break;\n      default:\n         s->inUse[s->state_in_len-4] = True;\n         s->block[s->nblock] = (UChar)ch; s->nblock++;\n         s->block[s->nblock] = (UChar)ch; s->nblock++;\n         s->block[s->nblock] = (UChar)ch; s->nblock++;\n         s->block[s->nblock] = (UChar)ch; s->nblock++;\n         s->block[s->nblock] = ((UChar)(s->state_in_len-4));\n         s->nblock++;\n         break;\n   }\n}\n\n\n/*---------------------------------------------------*/\nstatic\nvoid flush_RL ( EState* s )\n{\n   if (s->state_in_ch < 256) add_pair_to_block ( s );\n   init_RL ( s );\n}\n\n\n/*---------------------------------------------------*/\n#define ADD_CHAR_TO_BLOCK(zs,zchh0)               \\\n{                                                 \\\n   UInt32 zchh = (UInt32)(zchh0);                 \\\n   /*-- fast track the common case --*/           \\\n   if (zchh != zs->state_in_ch &&                 \\\n       zs->state_in_len == 1) {                   \\\n      UChar ch = (UChar)(zs->state_in_ch);        \\\n      BZ_UPDATE_CRC( zs->blockCRC, ch );          \\\n      zs->inUse[zs->state_in_ch] = True;          \\\n      zs->block[zs->nblock] = (UChar)ch;          \\\n      zs->nblock++;                               \\\n      zs->state_in_ch = zchh;                     \\\n   }                                              \\\n   else                                           \\\n   /*-- general, uncommon cases --*/              \\\n   if (zchh != zs->state_in_ch ||                 \\\n      zs->state_in_len == 255) {                  \\\n      if (zs->state_in_ch < 256)                  \\\n         add_pair_to_block ( zs );                \\\n      zs->state_in_ch = zchh;                     \\\n      zs->state_in_len = 1;                       \\\n   } else {                                       \\\n      zs->state_in_len++;                         \\\n   }                                              \\\n}\n\n\n/*---------------------------------------------------*/\nstatic\nBool copy_input_until_stop ( EState* s )\n{\n   Bool progress_in = False;\n\n   if (s->mode == BZ_M_RUNNING) {\n\n      /*-- fast track the common case --*/\n      while (True) {\n         /*-- block full? --*/\n         if (s->nblock >= s->nblockMAX) break;\n         /*-- no input? --*/\n         if (s->strm->avail_in == 0) break;\n         progress_in = True;\n         ADD_CHAR_TO_BLOCK ( s, (UInt32)(*((UChar*)(s->strm->next_in))) ); \n         s->strm->next_in++;\n         s->strm->avail_in--;\n         s->strm->total_in_lo32++;\n         if (s->strm->total_in_lo32 == 0) s->strm->total_in_hi32++;\n      }\n\n   } else {\n\n      /*-- general, uncommon case --*/\n      while (True) {\n         /*-- block full? --*/\n         if (s->nblock >= s->nblockMAX) break;\n         /*-- no input? --*/\n         if (s->strm->avail_in == 0) break;\n         /*-- flush/finish end? --*/\n         if (s->avail_in_expect == 0) break;\n         progress_in = True;\n         ADD_CHAR_TO_BLOCK ( s, (UInt32)(*((UChar*)(s->strm->next_in))) ); \n         s->strm->next_in++;\n         s->strm->avail_in--;\n         s->strm->total_in_lo32++;\n         if (s->strm->total_in_lo32 == 0) s->strm->total_in_hi32++;\n         s->avail_in_expect--;\n      }\n   }\n   return progress_in;\n}\n\n\n/*---------------------------------------------------*/\nstatic\nBool copy_output_until_stop ( EState* s )\n{\n   Bool progress_out = False;\n\n   while (True) {\n\n      /*-- no output space? --*/\n      if (s->strm->avail_out == 0) break;\n\n      /*-- block done? --*/\n      if (s->state_out_pos >= s->numZ) break;\n\n      progress_out = True;\n      *(s->strm->next_out) = s->zbits[s->state_out_pos];\n      s->state_out_pos++;\n      s->strm->avail_out--;\n      s->strm->next_out++;\n      s->strm->total_out_lo32++;\n      if (s->strm->total_out_lo32 == 0) s->strm->total_out_hi32++;\n   }\n\n   return progress_out;\n}\n\n\n/*---------------------------------------------------*/\nstatic\nBool handle_compress ( bz_stream* strm )\n{\n   Bool progress_in  = False;\n   Bool progress_out = False;\n   EState* s = strm->state;\n   \n   while (True) {\n\n      if (s->state == BZ_S_OUTPUT) {\n         progress_out |= copy_output_until_stop ( s );\n         if (s->state_out_pos < s->numZ) break;\n         if (s->mode == BZ_M_FINISHING && \n             s->avail_in_expect == 0 &&\n             isempty_RL(s)) break;\n         prepare_new_block ( s );\n         s->state = BZ_S_INPUT;\n         if (s->mode == BZ_M_FLUSHING && \n             s->avail_in_expect == 0 &&\n             isempty_RL(s)) break;\n      }\n\n      if (s->state == BZ_S_INPUT) {\n         progress_in |= copy_input_until_stop ( s );\n         if (s->mode != BZ_M_RUNNING && s->avail_in_expect == 0) {\n            flush_RL ( s );\n            BZ2_compressBlock ( s, (Bool)(s->mode == BZ_M_FINISHING) );\n            s->state = BZ_S_OUTPUT;\n         }\n         else\n         if (s->nblock >= s->nblockMAX) {\n            BZ2_compressBlock ( s, False );\n            s->state = BZ_S_OUTPUT;\n         }\n         else\n         if (s->strm->avail_in == 0) {\n            break;\n         }\n      }\n\n   }\n\n   return progress_in || progress_out;\n}\n\n\n/*---------------------------------------------------*/\nint BZ_API(BZ2_bzCompress) ( bz_stream *strm, int action )\n{\n   Bool progress;\n   EState* s;\n   if (strm == NULL) return BZ_PARAM_ERROR;\n   s = strm->state;\n   if (s == NULL) return BZ_PARAM_ERROR;\n   if (s->strm != strm) return BZ_PARAM_ERROR;\n\n   preswitch:\n   switch (s->mode) {\n\n      case BZ_M_IDLE:\n         return BZ_SEQUENCE_ERROR;\n\n      case BZ_M_RUNNING:\n         if (action == BZ_RUN) {\n            progress = handle_compress ( strm );\n            return progress ? BZ_RUN_OK : BZ_PARAM_ERROR;\n         } \n         else\n\t if (action == BZ_FLUSH) {\n            s->avail_in_expect = strm->avail_in;\n            s->mode = BZ_M_FLUSHING;\n            goto preswitch;\n         }\n         else\n         if (action == BZ_FINISH) {\n            s->avail_in_expect = strm->avail_in;\n            s->mode = BZ_M_FINISHING;\n            goto preswitch;\n         }\n         else \n            return BZ_PARAM_ERROR;\n\n      case BZ_M_FLUSHING:\n         if (action != BZ_FLUSH) return BZ_SEQUENCE_ERROR;\n         if (s->avail_in_expect != s->strm->avail_in) \n            return BZ_SEQUENCE_ERROR;\n         progress = handle_compress ( strm );\n         if (s->avail_in_expect > 0 || !isempty_RL(s) ||\n             s->state_out_pos < s->numZ) return BZ_FLUSH_OK;\n         s->mode = BZ_M_RUNNING;\n         return BZ_RUN_OK;\n\n      case BZ_M_FINISHING:\n         if (action != BZ_FINISH) return BZ_SEQUENCE_ERROR;\n         if (s->avail_in_expect != s->strm->avail_in) \n            return BZ_SEQUENCE_ERROR;\n         progress = handle_compress ( strm );\n         if (!progress) return BZ_SEQUENCE_ERROR;\n         if (s->avail_in_expect > 0 || !isempty_RL(s) ||\n             s->state_out_pos < s->numZ) return BZ_FINISH_OK;\n         s->mode = BZ_M_IDLE;\n         return BZ_STREAM_END;\n   }\n   return BZ_OK; /*--not reached--*/\n}\n\n\n/*---------------------------------------------------*/\nint BZ_API(BZ2_bzCompressEnd)  ( bz_stream *strm )\n{\n   EState* s;\n   if (strm == NULL) return BZ_PARAM_ERROR;\n   s = strm->state;\n   if (s == NULL) return BZ_PARAM_ERROR;\n   if (s->strm != strm) return BZ_PARAM_ERROR;\n\n   if (s->arr1 != NULL) BZFREE(s->arr1);\n   if (s->arr2 != NULL) BZFREE(s->arr2);\n   if (s->ftab != NULL) BZFREE(s->ftab);\n   BZFREE(strm->state);\n\n   strm->state = NULL;   \n\n   return BZ_OK;\n}\n\n\n/*---------------------------------------------------*/\n/*--- Decompression stuff                         ---*/\n/*---------------------------------------------------*/\n\n/*---------------------------------------------------*/\nint BZ_API(BZ2_bzDecompressInit) \n                     ( bz_stream* strm, \n                       int        verbosity,\n                       int        small )\n{\n   DState* s;\n\n   if (!bz_config_ok()) return BZ_CONFIG_ERROR;\n\n   if (strm == NULL) return BZ_PARAM_ERROR;\n   if (small != 0 && small != 1) return BZ_PARAM_ERROR;\n   if (verbosity < 0 || verbosity > 4) return BZ_PARAM_ERROR;\n\n   if (strm->bzalloc == NULL) strm->bzalloc = default_bzalloc;\n   if (strm->bzfree == NULL) strm->bzfree = default_bzfree;\n\n   s = BZALLOC( sizeof(DState) );\n   if (s == NULL) return BZ_MEM_ERROR;\n   s->strm                  = strm;\n   strm->state              = s;\n   s->state                 = BZ_X_MAGIC_1;\n   s->bsLive                = 0;\n   s->bsBuff                = 0;\n   s->calculatedCombinedCRC = 0;\n   strm->total_in_lo32      = 0;\n   strm->total_in_hi32      = 0;\n   strm->total_out_lo32     = 0;\n   strm->total_out_hi32     = 0;\n   s->smallDecompress       = (Bool)small;\n   s->ll4                   = NULL;\n   s->ll16                  = NULL;\n   s->tt                    = NULL;\n   s->currBlockNo           = 0;\n   s->verbosity             = verbosity;\n\n   return BZ_OK;\n}\n\n\n/*---------------------------------------------------*/\n/* Return  True iff data corruption is discovered.\n   Returns False if there is no problem.\n*/\nstatic\nBool unRLE_obuf_to_output_FAST ( DState* s )\n{\n   UChar k1;\n\n   if (s->blockRandomised) {\n\n      while (True) {\n         /* try to finish existing run */\n         while (True) {\n            if (s->strm->avail_out == 0) return False;\n            if (s->state_out_len == 0) break;\n            *( (UChar*)(s->strm->next_out) ) = s->state_out_ch;\n            BZ_UPDATE_CRC ( s->calculatedBlockCRC, s->state_out_ch );\n            s->state_out_len--;\n            s->strm->next_out++;\n            s->strm->avail_out--;\n            s->strm->total_out_lo32++;\n            if (s->strm->total_out_lo32 == 0) s->strm->total_out_hi32++;\n         }\n\n         /* can a new run be started? */\n         if (s->nblock_used == s->save_nblock+1) return False;\n               \n         /* Only caused by corrupt data stream? */\n         if (s->nblock_used > s->save_nblock+1)\n            return True;\n   \n         s->state_out_len = 1;\n         s->state_out_ch = s->k0;\n         BZ_GET_FAST(k1); BZ_RAND_UPD_MASK; \n         k1 ^= BZ_RAND_MASK; s->nblock_used++;\n         if (s->nblock_used == s->save_nblock+1) continue;\n         if (k1 != s->k0) { s->k0 = k1; continue; };\n   \n         s->state_out_len = 2;\n         BZ_GET_FAST(k1); BZ_RAND_UPD_MASK; \n         k1 ^= BZ_RAND_MASK; s->nblock_used++;\n         if (s->nblock_used == s->save_nblock+1) continue;\n         if (k1 != s->k0) { s->k0 = k1; continue; };\n   \n         s->state_out_len = 3;\n         BZ_GET_FAST(k1); BZ_RAND_UPD_MASK; \n         k1 ^= BZ_RAND_MASK; s->nblock_used++;\n         if (s->nblock_used == s->save_nblock+1) continue;\n         if (k1 != s->k0) { s->k0 = k1; continue; };\n   \n         BZ_GET_FAST(k1); BZ_RAND_UPD_MASK; \n         k1 ^= BZ_RAND_MASK; s->nblock_used++;\n         s->state_out_len = ((Int32)k1) + 4;\n         BZ_GET_FAST(s->k0); BZ_RAND_UPD_MASK; \n         s->k0 ^= BZ_RAND_MASK; s->nblock_used++;\n      }\n\n   } else {\n\n      /* restore */\n      UInt32        c_calculatedBlockCRC = s->calculatedBlockCRC;\n      UChar         c_state_out_ch       = s->state_out_ch;\n      Int32         c_state_out_len      = s->state_out_len;\n      Int32         c_nblock_used        = s->nblock_used;\n      Int32         c_k0                 = s->k0;\n      UInt32*       c_tt                 = s->tt;\n      UInt32        c_tPos               = s->tPos;\n      char*         cs_next_out          = s->strm->next_out;\n      unsigned int  cs_avail_out         = s->strm->avail_out;\n      Int32         ro_blockSize100k     = s->blockSize100k;\n      /* end restore */\n\n      UInt32       avail_out_INIT = cs_avail_out;\n      Int32        s_save_nblockPP = s->save_nblock+1;\n      unsigned int total_out_lo32_old;\n\n      while (True) {\n\n         /* try to finish existing run */\n         if (c_state_out_len > 0) {\n            while (True) {\n               if (cs_avail_out == 0) goto return_notr;\n               if (c_state_out_len == 1) break;\n               *( (UChar*)(cs_next_out) ) = c_state_out_ch;\n               BZ_UPDATE_CRC ( c_calculatedBlockCRC, c_state_out_ch );\n               c_state_out_len--;\n               cs_next_out++;\n               cs_avail_out--;\n            }\n            s_state_out_len_eq_one:\n            {\n               if (cs_avail_out == 0) { \n                  c_state_out_len = 1; goto return_notr;\n               };\n               *( (UChar*)(cs_next_out) ) = c_state_out_ch;\n               BZ_UPDATE_CRC ( c_calculatedBlockCRC, c_state_out_ch );\n               cs_next_out++;\n               cs_avail_out--;\n            }\n         }   \n         /* Only caused by corrupt data stream? */\n         if (c_nblock_used > s_save_nblockPP)\n            return True;\n\n         /* can a new run be started? */\n         if (c_nblock_used == s_save_nblockPP) {\n            c_state_out_len = 0; goto return_notr;\n         };   \n         c_state_out_ch = c_k0;\n         BZ_GET_FAST_C(k1); c_nblock_used++;\n         if (k1 != c_k0) { \n            c_k0 = k1; goto s_state_out_len_eq_one; \n         };\n         if (c_nblock_used == s_save_nblockPP) \n            goto s_state_out_len_eq_one;\n   \n         c_state_out_len = 2;\n         BZ_GET_FAST_C(k1); c_nblock_used++;\n         if (c_nblock_used == s_save_nblockPP) continue;\n         if (k1 != c_k0) { c_k0 = k1; continue; };\n   \n         c_state_out_len = 3;\n         BZ_GET_FAST_C(k1); c_nblock_used++;\n         if (c_nblock_used == s_save_nblockPP) continue;\n         if (k1 != c_k0) { c_k0 = k1; continue; };\n   \n         BZ_GET_FAST_C(k1); c_nblock_used++;\n         c_state_out_len = ((Int32)k1) + 4;\n         BZ_GET_FAST_C(c_k0); c_nblock_used++;\n      }\n\n      return_notr:\n      total_out_lo32_old = s->strm->total_out_lo32;\n      s->strm->total_out_lo32 += (avail_out_INIT - cs_avail_out);\n      if (s->strm->total_out_lo32 < total_out_lo32_old)\n         s->strm->total_out_hi32++;\n\n      /* save */\n      s->calculatedBlockCRC = c_calculatedBlockCRC;\n      s->state_out_ch       = c_state_out_ch;\n      s->state_out_len      = c_state_out_len;\n      s->nblock_used        = c_nblock_used;\n      s->k0                 = c_k0;\n      s->tt                 = c_tt;\n      s->tPos               = c_tPos;\n      s->strm->next_out     = cs_next_out;\n      s->strm->avail_out    = cs_avail_out;\n      /* end save */\n   }\n   return False;\n}\n\n\n\n/*---------------------------------------------------*/\n__inline__ Int32 BZ2_indexIntoF ( Int32 indx, Int32 *cftab )\n{\n   Int32 nb, na, mid;\n   nb = 0;\n   na = 256;\n   do {\n      mid = (nb + na) >> 1;\n      if (indx >= cftab[mid]) nb = mid; else na = mid;\n   }\n   while (na - nb != 1);\n   return nb;\n}\n\n\n/*---------------------------------------------------*/\n/* Return  True iff data corruption is discovered.\n   Returns False if there is no problem.\n*/\nstatic\nBool unRLE_obuf_to_output_SMALL ( DState* s )\n{\n   UChar k1;\n\n   if (s->blockRandomised) {\n\n      while (True) {\n         /* try to finish existing run */\n         while (True) {\n            if (s->strm->avail_out == 0) return False;\n            if (s->state_out_len == 0) break;\n            *( (UChar*)(s->strm->next_out) ) = s->state_out_ch;\n            BZ_UPDATE_CRC ( s->calculatedBlockCRC, s->state_out_ch );\n            s->state_out_len--;\n            s->strm->next_out++;\n            s->strm->avail_out--;\n            s->strm->total_out_lo32++;\n            if (s->strm->total_out_lo32 == 0) s->strm->total_out_hi32++;\n         }\n   \n         /* can a new run be started? */\n         if (s->nblock_used == s->save_nblock+1) return False;\n\n         /* Only caused by corrupt data stream? */\n         if (s->nblock_used > s->save_nblock+1)\n            return True;\n   \n         s->state_out_len = 1;\n         s->state_out_ch = s->k0;\n         BZ_GET_SMALL(k1); BZ_RAND_UPD_MASK; \n         k1 ^= BZ_RAND_MASK; s->nblock_used++;\n         if (s->nblock_used == s->save_nblock+1) continue;\n         if (k1 != s->k0) { s->k0 = k1; continue; };\n   \n         s->state_out_len = 2;\n         BZ_GET_SMALL(k1); BZ_RAND_UPD_MASK; \n         k1 ^= BZ_RAND_MASK; s->nblock_used++;\n         if (s->nblock_used == s->save_nblock+1) continue;\n         if (k1 != s->k0) { s->k0 = k1; continue; };\n   \n         s->state_out_len = 3;\n         BZ_GET_SMALL(k1); BZ_RAND_UPD_MASK; \n         k1 ^= BZ_RAND_MASK; s->nblock_used++;\n         if (s->nblock_used == s->save_nblock+1) continue;\n         if (k1 != s->k0) { s->k0 = k1; continue; };\n   \n         BZ_GET_SMALL(k1); BZ_RAND_UPD_MASK; \n         k1 ^= BZ_RAND_MASK; s->nblock_used++;\n         s->state_out_len = ((Int32)k1) + 4;\n         BZ_GET_SMALL(s->k0); BZ_RAND_UPD_MASK; \n         s->k0 ^= BZ_RAND_MASK; s->nblock_used++;\n      }\n\n   } else {\n\n      while (True) {\n         /* try to finish existing run */\n         while (True) {\n            if (s->strm->avail_out == 0) return False;\n            if (s->state_out_len == 0) break;\n            *( (UChar*)(s->strm->next_out) ) = s->state_out_ch;\n            BZ_UPDATE_CRC ( s->calculatedBlockCRC, s->state_out_ch );\n            s->state_out_len--;\n            s->strm->next_out++;\n            s->strm->avail_out--;\n            s->strm->total_out_lo32++;\n            if (s->strm->total_out_lo32 == 0) s->strm->total_out_hi32++;\n         }\n   \n         /* can a new run be started? */\n         if (s->nblock_used == s->save_nblock+1) return False;\n\n         /* Only caused by corrupt data stream? */\n         if (s->nblock_used > s->save_nblock+1)\n            return True;\n   \n         s->state_out_len = 1;\n         s->state_out_ch = s->k0;\n         BZ_GET_SMALL(k1); s->nblock_used++;\n         if (s->nblock_used == s->save_nblock+1) continue;\n         if (k1 != s->k0) { s->k0 = k1; continue; };\n   \n         s->state_out_len = 2;\n         BZ_GET_SMALL(k1); s->nblock_used++;\n         if (s->nblock_used == s->save_nblock+1) continue;\n         if (k1 != s->k0) { s->k0 = k1; continue; };\n   \n         s->state_out_len = 3;\n         BZ_GET_SMALL(k1); s->nblock_used++;\n         if (s->nblock_used == s->save_nblock+1) continue;\n         if (k1 != s->k0) { s->k0 = k1; continue; };\n   \n         BZ_GET_SMALL(k1); s->nblock_used++;\n         s->state_out_len = ((Int32)k1) + 4;\n         BZ_GET_SMALL(s->k0); s->nblock_used++;\n      }\n\n   }\n}\n\n\n/*---------------------------------------------------*/\nint BZ_API(BZ2_bzDecompress) ( bz_stream *strm )\n{\n   Bool    corrupt;\n   DState* s;\n   if (strm == NULL) return BZ_PARAM_ERROR;\n   s = strm->state;\n   if (s == NULL) return BZ_PARAM_ERROR;\n   if (s->strm != strm) return BZ_PARAM_ERROR;\n\n   while (True) {\n      if (s->state == BZ_X_IDLE) return BZ_SEQUENCE_ERROR;\n      if (s->state == BZ_X_OUTPUT) {\n         if (s->smallDecompress)\n            corrupt = unRLE_obuf_to_output_SMALL ( s ); else\n            corrupt = unRLE_obuf_to_output_FAST  ( s );\n         if (corrupt) return BZ_DATA_ERROR;\n         if (s->nblock_used == s->save_nblock+1 && s->state_out_len == 0) {\n            BZ_FINALISE_CRC ( s->calculatedBlockCRC );\n            if (s->verbosity >= 3) \n               VPrintf2 ( \" {0x%08x, 0x%08x}\", s->storedBlockCRC, \n                          s->calculatedBlockCRC );\n            if (s->verbosity >= 2) VPrintf0 ( \"]\" );\n            if (s->calculatedBlockCRC != s->storedBlockCRC)\n               return BZ_DATA_ERROR;\n            s->calculatedCombinedCRC \n               = (s->calculatedCombinedCRC << 1) | \n                    (s->calculatedCombinedCRC >> 31);\n            s->calculatedCombinedCRC ^= s->calculatedBlockCRC;\n            s->state = BZ_X_BLKHDR_1;\n         } else {\n            return BZ_OK;\n         }\n      }\n      if (s->state >= BZ_X_MAGIC_1) {\n         Int32 r = BZ2_decompress ( s );\n         if (r == BZ_STREAM_END) {\n            if (s->verbosity >= 3)\n               VPrintf2 ( \"\\n    combined CRCs: stored = 0x%08x, computed = 0x%08x\", \n                          s->storedCombinedCRC, s->calculatedCombinedCRC );\n            if (s->calculatedCombinedCRC != s->storedCombinedCRC)\n               return BZ_DATA_ERROR;\n            return r;\n         }\n         if (s->state != BZ_X_OUTPUT) return r;\n      }\n   }\n\n   AssertH ( 0, 6001 );\n\n   return 0;  /*NOTREACHED*/\n}\n\n\n/*---------------------------------------------------*/\nint BZ_API(BZ2_bzDecompressEnd)  ( bz_stream *strm )\n{\n   DState* s;\n   if (strm == NULL) return BZ_PARAM_ERROR;\n   s = strm->state;\n   if (s == NULL) return BZ_PARAM_ERROR;\n   if (s->strm != strm) return BZ_PARAM_ERROR;\n\n   if (s->tt   != NULL) BZFREE(s->tt);\n   if (s->ll16 != NULL) BZFREE(s->ll16);\n   if (s->ll4  != NULL) BZFREE(s->ll4);\n\n   BZFREE(strm->state);\n   strm->state = NULL;\n\n   return BZ_OK;\n}\n\n\n#ifndef BZ_NO_STDIO\n/*---------------------------------------------------*/\n/*--- File I/O stuff                              ---*/\n/*---------------------------------------------------*/\n\n#define BZ_SETERR(eee)                    \\\n{                                         \\\n   if (bzerror != NULL) *bzerror = eee;   \\\n   if (bzf != NULL) bzf->lastErr = eee;   \\\n}\n\ntypedef \n   struct {\n      FILE*     handle;\n      Char      buf[BZ_MAX_UNUSED];\n      Int32     bufN;\n      Bool      writing;\n      bz_stream strm;\n      Int32     lastErr;\n      Bool      initialisedOk;\n   }\n   bzFile;\n\n\n/*---------------------------------------------*/\nstatic Bool myfeof ( FILE* f )\n{\n   Int32 c = fgetc ( f );\n   if (c == EOF) return True;\n   ungetc ( c, f );\n   return False;\n}\n\n\n/*---------------------------------------------------*/\nBZFILE* BZ_API(BZ2_bzWriteOpen) \n                    ( int*  bzerror,      \n                      FILE* f, \n                      int   blockSize100k, \n                      int   verbosity,\n                      int   workFactor )\n{\n   Int32   ret;\n   bzFile* bzf = NULL;\n\n   BZ_SETERR(BZ_OK);\n\n   if (f == NULL ||\n       (blockSize100k < 1 || blockSize100k > 9) ||\n       (workFactor < 0 || workFactor > 250) ||\n       (verbosity < 0 || verbosity > 4))\n      { BZ_SETERR(BZ_PARAM_ERROR); return NULL; };\n\n   if (ferror(f))\n      { BZ_SETERR(BZ_IO_ERROR); return NULL; };\n\n   bzf = malloc ( sizeof(bzFile) );\n   if (bzf == NULL)\n      { BZ_SETERR(BZ_MEM_ERROR); return NULL; };\n\n   BZ_SETERR(BZ_OK);\n   bzf->initialisedOk = False;\n   bzf->bufN          = 0;\n   bzf->handle        = f;\n   bzf->writing       = True;\n   bzf->strm.bzalloc  = NULL;\n   bzf->strm.bzfree   = NULL;\n   bzf->strm.opaque   = NULL;\n\n   if (workFactor == 0) workFactor = 30;\n   ret = BZ2_bzCompressInit ( &(bzf->strm), blockSize100k, \n                              verbosity, workFactor );\n   if (ret != BZ_OK)\n      { BZ_SETERR(ret); free(bzf); return NULL; };\n\n   bzf->strm.avail_in = 0;\n   bzf->initialisedOk = True;\n   return bzf;   \n}\n\n\n\n/*---------------------------------------------------*/\nvoid BZ_API(BZ2_bzWrite)\n             ( int*    bzerror, \n               BZFILE* b, \n               void*   buf, \n               int     len )\n{\n   Int32 n, n2, ret;\n   bzFile* bzf = (bzFile*)b;\n\n   BZ_SETERR(BZ_OK);\n   if (bzf == NULL || buf == NULL || len < 0)\n      { BZ_SETERR(BZ_PARAM_ERROR); return; };\n   if (!(bzf->writing))\n      { BZ_SETERR(BZ_SEQUENCE_ERROR); return; };\n   if (ferror(bzf->handle))\n      { BZ_SETERR(BZ_IO_ERROR); return; };\n\n   if (len == 0)\n      { BZ_SETERR(BZ_OK); return; };\n\n   bzf->strm.avail_in = len;\n   bzf->strm.next_in  = buf;\n\n   while (True) {\n      bzf->strm.avail_out = BZ_MAX_UNUSED;\n      bzf->strm.next_out = bzf->buf;\n      ret = BZ2_bzCompress ( &(bzf->strm), BZ_RUN );\n      if (ret != BZ_RUN_OK)\n         { BZ_SETERR(ret); return; };\n\n      if (bzf->strm.avail_out < BZ_MAX_UNUSED) {\n         n = BZ_MAX_UNUSED - bzf->strm.avail_out;\n         n2 = fwrite ( (void*)(bzf->buf), sizeof(UChar), \n                       n, bzf->handle );\n         if (n != n2 || ferror(bzf->handle))\n            { BZ_SETERR(BZ_IO_ERROR); return; };\n      }\n\n      if (bzf->strm.avail_in == 0)\n         { BZ_SETERR(BZ_OK); return; };\n   }\n}\n\n\n/*---------------------------------------------------*/\nvoid BZ_API(BZ2_bzWriteClose)\n                  ( int*          bzerror, \n                    BZFILE*       b, \n                    int           abandon,\n                    unsigned int* nbytes_in,\n                    unsigned int* nbytes_out )\n{\n   BZ2_bzWriteClose64 ( bzerror, b, abandon, \n                        nbytes_in, NULL, nbytes_out, NULL );\n}\n\n\nvoid BZ_API(BZ2_bzWriteClose64)\n                  ( int*          bzerror, \n                    BZFILE*       b, \n                    int           abandon,\n                    unsigned int* nbytes_in_lo32,\n                    unsigned int* nbytes_in_hi32,\n                    unsigned int* nbytes_out_lo32,\n                    unsigned int* nbytes_out_hi32 )\n{\n   Int32   n, n2, ret;\n   bzFile* bzf = (bzFile*)b;\n\n   if (bzf == NULL)\n      { BZ_SETERR(BZ_OK); return; };\n   if (!(bzf->writing))\n      { BZ_SETERR(BZ_SEQUENCE_ERROR); return; };\n   if (ferror(bzf->handle))\n      { BZ_SETERR(BZ_IO_ERROR); return; };\n\n   if (nbytes_in_lo32 != NULL) *nbytes_in_lo32 = 0;\n   if (nbytes_in_hi32 != NULL) *nbytes_in_hi32 = 0;\n   if (nbytes_out_lo32 != NULL) *nbytes_out_lo32 = 0;\n   if (nbytes_out_hi32 != NULL) *nbytes_out_hi32 = 0;\n\n   if ((!abandon) && bzf->lastErr == BZ_OK) {\n      while (True) {\n         bzf->strm.avail_out = BZ_MAX_UNUSED;\n         bzf->strm.next_out = bzf->buf;\n         ret = BZ2_bzCompress ( &(bzf->strm), BZ_FINISH );\n         if (ret != BZ_FINISH_OK && ret != BZ_STREAM_END)\n            { BZ_SETERR(ret); return; };\n\n         if (bzf->strm.avail_out < BZ_MAX_UNUSED) {\n            n = BZ_MAX_UNUSED - bzf->strm.avail_out;\n            n2 = fwrite ( (void*)(bzf->buf), sizeof(UChar), \n                          n, bzf->handle );\n            if (n != n2 || ferror(bzf->handle))\n               { BZ_SETERR(BZ_IO_ERROR); return; };\n         }\n\n         if (ret == BZ_STREAM_END) break;\n      }\n   }\n\n   if ( !abandon && !ferror ( bzf->handle ) ) {\n      fflush ( bzf->handle );\n      if (ferror(bzf->handle))\n         { BZ_SETERR(BZ_IO_ERROR); return; };\n   }\n\n   if (nbytes_in_lo32 != NULL)\n      *nbytes_in_lo32 = bzf->strm.total_in_lo32;\n   if (nbytes_in_hi32 != NULL)\n      *nbytes_in_hi32 = bzf->strm.total_in_hi32;\n   if (nbytes_out_lo32 != NULL)\n      *nbytes_out_lo32 = bzf->strm.total_out_lo32;\n   if (nbytes_out_hi32 != NULL)\n      *nbytes_out_hi32 = bzf->strm.total_out_hi32;\n\n   BZ_SETERR(BZ_OK);\n   BZ2_bzCompressEnd ( &(bzf->strm) );\n   free ( bzf );\n}\n\n\n/*---------------------------------------------------*/\nBZFILE* BZ_API(BZ2_bzReadOpen) \n                   ( int*  bzerror, \n                     FILE* f, \n                     int   verbosity,\n                     int   small,\n                     void* unused,\n                     int   nUnused )\n{\n   bzFile* bzf = NULL;\n   int     ret;\n\n   BZ_SETERR(BZ_OK);\n\n   if (f == NULL || \n       (small != 0 && small != 1) ||\n       (verbosity < 0 || verbosity > 4) ||\n       (unused == NULL && nUnused != 0) ||\n       (unused != NULL && (nUnused < 0 || nUnused > BZ_MAX_UNUSED)))\n      { BZ_SETERR(BZ_PARAM_ERROR); return NULL; };\n\n   if (ferror(f))\n      { BZ_SETERR(BZ_IO_ERROR); return NULL; };\n\n   bzf = malloc ( sizeof(bzFile) );\n   if (bzf == NULL) \n      { BZ_SETERR(BZ_MEM_ERROR); return NULL; };\n\n   BZ_SETERR(BZ_OK);\n\n   bzf->initialisedOk = False;\n   bzf->handle        = f;\n   bzf->bufN          = 0;\n   bzf->writing       = False;\n   bzf->strm.bzalloc  = NULL;\n   bzf->strm.bzfree   = NULL;\n   bzf->strm.opaque   = NULL;\n   \n   while (nUnused > 0) {\n      bzf->buf[bzf->bufN] = *((UChar*)(unused)); bzf->bufN++;\n      unused = ((void*)( 1 + ((UChar*)(unused))  ));\n      nUnused--;\n   }\n\n   ret = BZ2_bzDecompressInit ( &(bzf->strm), verbosity, small );\n   if (ret != BZ_OK)\n      { BZ_SETERR(ret); free(bzf); return NULL; };\n\n   bzf->strm.avail_in = bzf->bufN;\n   bzf->strm.next_in  = bzf->buf;\n\n   bzf->initialisedOk = True;\n   return bzf;   \n}\n\n\n/*---------------------------------------------------*/\nvoid BZ_API(BZ2_bzReadClose) ( int *bzerror, BZFILE *b )\n{\n   bzFile* bzf = (bzFile*)b;\n\n   BZ_SETERR(BZ_OK);\n   if (bzf == NULL)\n      { BZ_SETERR(BZ_OK); return; };\n\n   if (bzf->writing)\n      { BZ_SETERR(BZ_SEQUENCE_ERROR); return; };\n\n   if (bzf->initialisedOk)\n      (void)BZ2_bzDecompressEnd ( &(bzf->strm) );\n   free ( bzf );\n}\n\n\n/*---------------------------------------------------*/\nint BZ_API(BZ2_bzRead) \n           ( int*    bzerror, \n             BZFILE* b, \n             void*   buf, \n             int     len )\n{\n   Int32   n, ret;\n   bzFile* bzf = (bzFile*)b;\n\n   BZ_SETERR(BZ_OK);\n\n   if (bzf == NULL || buf == NULL || len < 0)\n      { BZ_SETERR(BZ_PARAM_ERROR); return 0; };\n\n   if (bzf->writing)\n      { BZ_SETERR(BZ_SEQUENCE_ERROR); return 0; };\n\n   if (len == 0)\n      { BZ_SETERR(BZ_OK); return 0; };\n\n   bzf->strm.avail_out = len;\n   bzf->strm.next_out = buf;\n\n   while (True) {\n\n      if (ferror(bzf->handle)) \n         { BZ_SETERR(BZ_IO_ERROR); return 0; };\n\n      if (bzf->strm.avail_in == 0 && !myfeof(bzf->handle)) {\n         n = fread ( bzf->buf, sizeof(UChar), \n                     BZ_MAX_UNUSED, bzf->handle );\n         if (ferror(bzf->handle))\n            { BZ_SETERR(BZ_IO_ERROR); return 0; };\n         bzf->bufN = n;\n         bzf->strm.avail_in = bzf->bufN;\n         bzf->strm.next_in = bzf->buf;\n      }\n\n      ret = BZ2_bzDecompress ( &(bzf->strm) );\n\n      if (ret != BZ_OK && ret != BZ_STREAM_END)\n         { BZ_SETERR(ret); return 0; };\n\n      if (ret == BZ_OK && myfeof(bzf->handle) && \n          bzf->strm.avail_in == 0 && bzf->strm.avail_out > 0)\n         { BZ_SETERR(BZ_UNEXPECTED_EOF); return 0; };\n\n      if (ret == BZ_STREAM_END)\n         { BZ_SETERR(BZ_STREAM_END);\n           return len - bzf->strm.avail_out; };\n      if (bzf->strm.avail_out == 0)\n         { BZ_SETERR(BZ_OK); return len; };\n      \n   }\n\n   return 0; /*not reached*/\n}\n\n\n/*---------------------------------------------------*/\nvoid BZ_API(BZ2_bzReadGetUnused) \n                     ( int*    bzerror, \n                       BZFILE* b, \n                       void**  unused, \n                       int*    nUnused )\n{\n   bzFile* bzf = (bzFile*)b;\n   if (bzf == NULL)\n      { BZ_SETERR(BZ_PARAM_ERROR); return; };\n   if (bzf->lastErr != BZ_STREAM_END)\n      { BZ_SETERR(BZ_SEQUENCE_ERROR); return; };\n   if (unused == NULL || nUnused == NULL)\n      { BZ_SETERR(BZ_PARAM_ERROR); return; };\n\n   BZ_SETERR(BZ_OK);\n   *nUnused = bzf->strm.avail_in;\n   *unused = bzf->strm.next_in;\n}\n#endif\n\n\n/*---------------------------------------------------*/\n/*--- Misc convenience stuff                      ---*/\n/*---------------------------------------------------*/\n\n/*---------------------------------------------------*/\nint BZ_API(BZ2_bzBuffToBuffCompress) \n                         ( char*         dest, \n                           unsigned int* destLen,\n                           char*         source, \n                           unsigned int  sourceLen,\n                           int           blockSize100k, \n                           int           verbosity, \n                           int           workFactor )\n{\n   bz_stream strm;\n   int ret;\n\n   if (dest == NULL || destLen == NULL || \n       source == NULL ||\n       blockSize100k < 1 || blockSize100k > 9 ||\n       verbosity < 0 || verbosity > 4 ||\n       workFactor < 0 || workFactor > 250) \n      return BZ_PARAM_ERROR;\n\n   if (workFactor == 0) workFactor = 30;\n   strm.bzalloc = NULL;\n   strm.bzfree = NULL;\n   strm.opaque = NULL;\n   ret = BZ2_bzCompressInit ( &strm, blockSize100k, \n                              verbosity, workFactor );\n   if (ret != BZ_OK) return ret;\n\n   strm.next_in = source;\n   strm.next_out = dest;\n   strm.avail_in = sourceLen;\n   strm.avail_out = *destLen;\n\n   ret = BZ2_bzCompress ( &strm, BZ_FINISH );\n   if (ret == BZ_FINISH_OK) goto output_overflow;\n   if (ret != BZ_STREAM_END) goto errhandler;\n\n   /* normal termination */\n   *destLen -= strm.avail_out;   \n   BZ2_bzCompressEnd ( &strm );\n   return BZ_OK;\n\n   output_overflow:\n   BZ2_bzCompressEnd ( &strm );\n   return BZ_OUTBUFF_FULL;\n\n   errhandler:\n   BZ2_bzCompressEnd ( &strm );\n   return ret;\n}\n\n\n/*---------------------------------------------------*/\nint BZ_API(BZ2_bzBuffToBuffDecompress) \n                           ( char*         dest, \n                             unsigned int* destLen,\n                             char*         source, \n                             unsigned int  sourceLen,\n                             int           small,\n                             int           verbosity )\n{\n   bz_stream strm;\n   int ret;\n\n   if (dest == NULL || destLen == NULL || \n       source == NULL ||\n       (small != 0 && small != 1) ||\n       verbosity < 0 || verbosity > 4) \n          return BZ_PARAM_ERROR;\n\n   strm.bzalloc = NULL;\n   strm.bzfree = NULL;\n   strm.opaque = NULL;\n   ret = BZ2_bzDecompressInit ( &strm, verbosity, small );\n   if (ret != BZ_OK) return ret;\n\n   strm.next_in = source;\n   strm.next_out = dest;\n   strm.avail_in = sourceLen;\n   strm.avail_out = *destLen;\n\n   ret = BZ2_bzDecompress ( &strm );\n   if (ret == BZ_OK) goto output_overflow_or_eof;\n   if (ret != BZ_STREAM_END) goto errhandler;\n\n   /* normal termination */\n   *destLen -= strm.avail_out;\n   BZ2_bzDecompressEnd ( &strm );\n   return BZ_OK;\n\n   output_overflow_or_eof:\n   if (strm.avail_out > 0) {\n      BZ2_bzDecompressEnd ( &strm );\n      return BZ_UNEXPECTED_EOF;\n   } else {\n      BZ2_bzDecompressEnd ( &strm );\n      return BZ_OUTBUFF_FULL;\n   };      \n\n   errhandler:\n   BZ2_bzDecompressEnd ( &strm );\n   return ret; \n}\n\n\n/*---------------------------------------------------*/\n/*--\n   Code contributed by Yoshioka Tsuneo (tsuneo@rr.iij4u.or.jp)\n   to support better zlib compatibility.\n   This code is not _officially_ part of libbzip2 (yet);\n   I haven't tested it, documented it, or considered the\n   threading-safeness of it.\n   If this code breaks, please contact both Yoshioka and me.\n--*/\n/*---------------------------------------------------*/\n\n/*---------------------------------------------------*/\n/*--\n   return version like \"0.9.5d, 4-Sept-1999\".\n--*/\nconst char * BZ_API(BZ2_bzlibVersion)(void)\n{\n   return BZ_VERSION;\n}\n\n\n#ifndef BZ_NO_STDIO\n/*---------------------------------------------------*/\n\n#if defined(_WIN32) || defined(OS2) || defined(MSDOS)\n#   include <fcntl.h>\n#   include <io.h>\n#   define SET_BINARY_MODE(file) setmode(fileno(file),O_BINARY)\n#else\n#   define SET_BINARY_MODE(file)\n#endif\nstatic\nBZFILE * bzopen_or_bzdopen\n               ( const char *path,   /* no use when bzdopen */\n                 int fd,             /* no use when bzdopen */\n                 const char *mode,\n                 int open_mode)      /* bzopen: 0, bzdopen:1 */\n{\n   int    bzerr;\n   char   unused[BZ_MAX_UNUSED];\n   int    blockSize100k = 9;\n   int    writing       = 0;\n   char   mode2[10]     = \"\";\n   FILE   *fp           = NULL;\n   BZFILE *bzfp         = NULL;\n   int    verbosity     = 0;\n   int    workFactor    = 30;\n   int    smallMode     = 0;\n   int    nUnused       = 0; \n\n   if (mode == NULL) return NULL;\n   while (*mode) {\n      switch (*mode) {\n      case 'r':\n         writing = 0; break;\n      case 'w':\n         writing = 1; break;\n      case 's':\n         smallMode = 1; break;\n      default:\n         if (isdigit((int)(*mode))) {\n            blockSize100k = *mode-BZ_HDR_0;\n         }\n      }\n      mode++;\n   }\n   strcat(mode2, writing ? \"w\" : \"r\" );\n   strcat(mode2,\"b\");   /* binary mode */\n\n   if (open_mode==0) {\n      if (path==NULL || strcmp(path,\"\")==0) {\n        fp = (writing ? stdout : stdin);\n        SET_BINARY_MODE(fp);\n      } else {\n        fp = fopen(path,mode2);\n      }\n   } else {\n#ifdef BZ_STRICT_ANSI\n      fp = NULL;\n#else\n      fp = fdopen(fd,mode2);\n#endif\n   }\n   if (fp == NULL) return NULL;\n\n   if (writing) {\n      /* Guard against total chaos and anarchy -- JRS */\n      if (blockSize100k < 1) blockSize100k = 1;\n      if (blockSize100k > 9) blockSize100k = 9; \n      bzfp = BZ2_bzWriteOpen(&bzerr,fp,blockSize100k,\n                             verbosity,workFactor);\n   } else {\n      bzfp = BZ2_bzReadOpen(&bzerr,fp,verbosity,smallMode,\n                            unused,nUnused);\n   }\n   if (bzfp == NULL) {\n      if (fp != stdin && fp != stdout) fclose(fp);\n      return NULL;\n   }\n   return bzfp;\n}\n\n\n/*---------------------------------------------------*/\n/*--\n   open file for read or write.\n      ex) bzopen(\"file\",\"w9\")\n      case path=\"\" or NULL => use stdin or stdout.\n--*/\nBZFILE * BZ_API(BZ2_bzopen)\n               ( const char *path,\n                 const char *mode )\n{\n   return bzopen_or_bzdopen(path,-1,mode,/*bzopen*/0);\n}\n\n\n/*---------------------------------------------------*/\nBZFILE * BZ_API(BZ2_bzdopen)\n               ( int fd,\n                 const char *mode )\n{\n   return bzopen_or_bzdopen(NULL,fd,mode,/*bzdopen*/1);\n}\n\n\n/*---------------------------------------------------*/\nint BZ_API(BZ2_bzread) (BZFILE* b, void* buf, int len )\n{\n   int bzerr, nread;\n   if (((bzFile*)b)->lastErr == BZ_STREAM_END) return 0;\n   nread = BZ2_bzRead(&bzerr,b,buf,len);\n   if (bzerr == BZ_OK || bzerr == BZ_STREAM_END) {\n      return nread;\n   } else {\n      return -1;\n   }\n}\n\n\n/*---------------------------------------------------*/\nint BZ_API(BZ2_bzwrite) (BZFILE* b, void* buf, int len )\n{\n   int bzerr;\n\n   BZ2_bzWrite(&bzerr,b,buf,len);\n   if(bzerr == BZ_OK){\n      return len;\n   }else{\n      return -1;\n   }\n}\n\n\n/*---------------------------------------------------*/\nint BZ_API(BZ2_bzflush) (BZFILE *b)\n{\n   /* do nothing now... */\n   return 0;\n}\n\n\n/*---------------------------------------------------*/\nvoid BZ_API(BZ2_bzclose) (BZFILE* b)\n{\n   int bzerr;\n   FILE *fp;\n   \n   if (b==NULL) {return;}\n   fp = ((bzFile *)b)->handle;\n   if(((bzFile*)b)->writing){\n      BZ2_bzWriteClose(&bzerr,b,0,NULL,NULL);\n      if(bzerr != BZ_OK){\n         BZ2_bzWriteClose(NULL,b,1,NULL,NULL);\n      }\n   }else{\n      BZ2_bzReadClose(&bzerr,b);\n   }\n   if(fp!=stdin && fp!=stdout){\n      fclose(fp);\n   }\n}\n\n\n/*---------------------------------------------------*/\n/*--\n   return last error code \n--*/\nstatic const char *bzerrorstrings[] = {\n       \"OK\"\n      ,\"SEQUENCE_ERROR\"\n      ,\"PARAM_ERROR\"\n      ,\"MEM_ERROR\"\n      ,\"DATA_ERROR\"\n      ,\"DATA_ERROR_MAGIC\"\n      ,\"IO_ERROR\"\n      ,\"UNEXPECTED_EOF\"\n      ,\"OUTBUFF_FULL\"\n      ,\"CONFIG_ERROR\"\n      ,\"???\"   /* for future */\n      ,\"???\"   /* for future */\n      ,\"???\"   /* for future */\n      ,\"???\"   /* for future */\n      ,\"???\"   /* for future */\n      ,\"???\"   /* for future */\n};\n\n\nconst char * BZ_API(BZ2_bzerror) (BZFILE *b, int *errnum)\n{\n   int err = ((bzFile *)b)->lastErr;\n\n   if(err>0) err = 0;\n   *errnum = err;\n   return bzerrorstrings[err*-1];\n}\n#endif\n\n\n/*-------------------------------------------------------------*/\n/*--- end                                           bzlib.c ---*/\n/*-------------------------------------------------------------*/\n"
  },
  {
    "path": "external/bzip2/bzlib.h",
    "content": "\n/*-------------------------------------------------------------*/\n/*--- Public header file for the library.                   ---*/\n/*---                                               bzlib.h ---*/\n/*-------------------------------------------------------------*/\n\n/* ------------------------------------------------------------------\n   This file is part of bzip2/libbzip2, a program and library for\n   lossless, block-sorting data compression.\n\n   bzip2/libbzip2 version 1.0.6 of 6 September 2010\n   Copyright (C) 1996-2010 Julian Seward <jseward@bzip.org>\n\n   Please read the WARNING, DISCLAIMER and PATENTS sections in the \n   README file.\n\n   This program is released under the terms of the license contained\n   in the file LICENSE.\n   ------------------------------------------------------------------ */\n\n\n#ifndef _BZLIB_H\n#define _BZLIB_H\n\n#ifdef __cplusplus\nextern \"C\" {\n#endif\n\n#define BZ_RUN               0\n#define BZ_FLUSH             1\n#define BZ_FINISH            2\n\n#define BZ_OK                0\n#define BZ_RUN_OK            1\n#define BZ_FLUSH_OK          2\n#define BZ_FINISH_OK         3\n#define BZ_STREAM_END        4\n#define BZ_SEQUENCE_ERROR    (-1)\n#define BZ_PARAM_ERROR       (-2)\n#define BZ_MEM_ERROR         (-3)\n#define BZ_DATA_ERROR        (-4)\n#define BZ_DATA_ERROR_MAGIC  (-5)\n#define BZ_IO_ERROR          (-6)\n#define BZ_UNEXPECTED_EOF    (-7)\n#define BZ_OUTBUFF_FULL      (-8)\n#define BZ_CONFIG_ERROR      (-9)\n\ntypedef \n   struct {\n      char *next_in;\n      unsigned int avail_in;\n      unsigned int total_in_lo32;\n      unsigned int total_in_hi32;\n\n      char *next_out;\n      unsigned int avail_out;\n      unsigned int total_out_lo32;\n      unsigned int total_out_hi32;\n\n      void *state;\n\n      void *(*bzalloc)(void *,int,int);\n      void (*bzfree)(void *,void *);\n      void *opaque;\n   } \n   bz_stream;\n\n\n#ifndef BZ_IMPORT\n#define BZ_EXPORT\n#endif\n\n#ifndef BZ_NO_STDIO\n/* Need a definitition for FILE */\n#include <stdio.h>\n#endif\n\n#ifdef _WIN32\n#   include <windows.h>\n#   ifdef small\n      /* windows.h define small to char */\n#      undef small\n#   endif\n#   ifdef BZ_EXPORT\n#   define BZ_API(func) WINAPI func\n#   define BZ_EXTERN extern\n#   else\n   /* import windows dll dynamically */\n#   define BZ_API(func) (WINAPI * func)\n#   define BZ_EXTERN\n#   endif\n#else\n#   define BZ_API(func) func\n#   define BZ_EXTERN extern\n#endif\n\n\n/*-- Core (low-level) library functions --*/\n\nBZ_EXTERN int BZ_API(BZ2_bzCompressInit) ( \n      bz_stream* strm, \n      int        blockSize100k, \n      int        verbosity, \n      int        workFactor \n   );\n\nBZ_EXTERN int BZ_API(BZ2_bzCompress) ( \n      bz_stream* strm, \n      int action \n   );\n\nBZ_EXTERN int BZ_API(BZ2_bzCompressEnd) ( \n      bz_stream* strm \n   );\n\nBZ_EXTERN int BZ_API(BZ2_bzDecompressInit) ( \n      bz_stream *strm, \n      int       verbosity, \n      int       small\n   );\n\nBZ_EXTERN int BZ_API(BZ2_bzDecompress) ( \n      bz_stream* strm \n   );\n\nBZ_EXTERN int BZ_API(BZ2_bzDecompressEnd) ( \n      bz_stream *strm \n   );\n\n\n\n/*-- High(er) level library functions --*/\n\n#ifndef BZ_NO_STDIO\n#define BZ_MAX_UNUSED 5000\n\ntypedef void BZFILE;\n\nBZ_EXTERN BZFILE* BZ_API(BZ2_bzReadOpen) ( \n      int*  bzerror,   \n      FILE* f, \n      int   verbosity, \n      int   small,\n      void* unused,    \n      int   nUnused \n   );\n\nBZ_EXTERN void BZ_API(BZ2_bzReadClose) ( \n      int*    bzerror, \n      BZFILE* b \n   );\n\nBZ_EXTERN void BZ_API(BZ2_bzReadGetUnused) ( \n      int*    bzerror, \n      BZFILE* b, \n      void**  unused,  \n      int*    nUnused \n   );\n\nBZ_EXTERN int BZ_API(BZ2_bzRead) ( \n      int*    bzerror, \n      BZFILE* b, \n      void*   buf, \n      int     len \n   );\n\nBZ_EXTERN BZFILE* BZ_API(BZ2_bzWriteOpen) ( \n      int*  bzerror,      \n      FILE* f, \n      int   blockSize100k, \n      int   verbosity, \n      int   workFactor \n   );\n\nBZ_EXTERN void BZ_API(BZ2_bzWrite) ( \n      int*    bzerror, \n      BZFILE* b, \n      void*   buf, \n      int     len \n   );\n\nBZ_EXTERN void BZ_API(BZ2_bzWriteClose) ( \n      int*          bzerror, \n      BZFILE*       b, \n      int           abandon, \n      unsigned int* nbytes_in, \n      unsigned int* nbytes_out \n   );\n\nBZ_EXTERN void BZ_API(BZ2_bzWriteClose64) ( \n      int*          bzerror, \n      BZFILE*       b, \n      int           abandon, \n      unsigned int* nbytes_in_lo32, \n      unsigned int* nbytes_in_hi32, \n      unsigned int* nbytes_out_lo32, \n      unsigned int* nbytes_out_hi32\n   );\n#endif\n\n\n/*-- Utility functions --*/\n\nBZ_EXTERN int BZ_API(BZ2_bzBuffToBuffCompress) ( \n      char*         dest, \n      unsigned int* destLen,\n      char*         source, \n      unsigned int  sourceLen,\n      int           blockSize100k, \n      int           verbosity, \n      int           workFactor \n   );\n\nBZ_EXTERN int BZ_API(BZ2_bzBuffToBuffDecompress) ( \n      char*         dest, \n      unsigned int* destLen,\n      char*         source, \n      unsigned int  sourceLen,\n      int           small, \n      int           verbosity \n   );\n\n\n/*--\n   Code contributed by Yoshioka Tsuneo (tsuneo@rr.iij4u.or.jp)\n   to support better zlib compatibility.\n   This code is not _officially_ part of libbzip2 (yet);\n   I haven't tested it, documented it, or considered the\n   threading-safeness of it.\n   If this code breaks, please contact both Yoshioka and me.\n--*/\n\nBZ_EXTERN const char * BZ_API(BZ2_bzlibVersion) (\n      void\n   );\n\n#ifndef BZ_NO_STDIO\nBZ_EXTERN BZFILE * BZ_API(BZ2_bzopen) (\n      const char *path,\n      const char *mode\n   );\n\nBZ_EXTERN BZFILE * BZ_API(BZ2_bzdopen) (\n      int        fd,\n      const char *mode\n   );\n         \nBZ_EXTERN int BZ_API(BZ2_bzread) (\n      BZFILE* b, \n      void* buf, \n      int len \n   );\n\nBZ_EXTERN int BZ_API(BZ2_bzwrite) (\n      BZFILE* b, \n      void*   buf, \n      int     len \n   );\n\nBZ_EXTERN int BZ_API(BZ2_bzflush) (\n      BZFILE* b\n   );\n\nBZ_EXTERN void BZ_API(BZ2_bzclose) (\n      BZFILE* b\n   );\n\nBZ_EXTERN const char * BZ_API(BZ2_bzerror) (\n      BZFILE *b, \n      int    *errnum\n   );\n#endif\n\n#ifdef __cplusplus\n}\n#endif\n\n#endif\n\n/*-------------------------------------------------------------*/\n/*--- end                                           bzlib.h ---*/\n/*-------------------------------------------------------------*/\n"
  },
  {
    "path": "external/bzip2/bzlib_private.h",
    "content": "\n/*-------------------------------------------------------------*/\n/*--- Private header file for the library.                  ---*/\n/*---                                       bzlib_private.h ---*/\n/*-------------------------------------------------------------*/\n\n/* ------------------------------------------------------------------\n   This file is part of bzip2/libbzip2, a program and library for\n   lossless, block-sorting data compression.\n\n   bzip2/libbzip2 version 1.0.6 of 6 September 2010\n   Copyright (C) 1996-2010 Julian Seward <jseward@bzip.org>\n\n   Please read the WARNING, DISCLAIMER and PATENTS sections in the \n   README file.\n\n   This program is released under the terms of the license contained\n   in the file LICENSE.\n   ------------------------------------------------------------------ */\n\n\n#ifndef _BZLIB_PRIVATE_H\n#define _BZLIB_PRIVATE_H\n\n#include <stdlib.h>\n\n#ifndef BZ_NO_STDIO\n#include <stdio.h>\n#include <ctype.h>\n#include <string.h>\n#endif\n\n#include \"bzlib.h\"\n\n\n\n/*-- General stuff. --*/\n\n#define BZ_VERSION  \"1.0.6, 6-Sept-2010\"\n\ntypedef char            Char;\ntypedef unsigned char   Bool;\ntypedef unsigned char   UChar;\ntypedef int             Int32;\ntypedef unsigned int    UInt32;\ntypedef short           Int16;\ntypedef unsigned short  UInt16;\n\n#define True  ((Bool)1)\n#define False ((Bool)0)\n\n#ifndef __GNUC__\n#define __inline__  /* */\n#endif \n\n#ifndef BZ_NO_STDIO\n\nextern void BZ2_bz__AssertH__fail ( int errcode );\n#define AssertH(cond,errcode) \\\n   { if (!(cond)) BZ2_bz__AssertH__fail ( errcode ); }\n\n#if BZ_DEBUG\n#define AssertD(cond,msg) \\\n   { if (!(cond)) {       \\\n      fprintf ( stderr,   \\\n        \"\\n\\nlibbzip2(debug build): internal error\\n\\t%s\\n\", msg );\\\n      exit(1); \\\n   }}\n#else\n#define AssertD(cond,msg) /* */\n#endif\n\n#define VPrintf0(zf) \\\n   fprintf(stderr,zf)\n#define VPrintf1(zf,za1) \\\n   fprintf(stderr,zf,za1)\n#define VPrintf2(zf,za1,za2) \\\n   fprintf(stderr,zf,za1,za2)\n#define VPrintf3(zf,za1,za2,za3) \\\n   fprintf(stderr,zf,za1,za2,za3)\n#define VPrintf4(zf,za1,za2,za3,za4) \\\n   fprintf(stderr,zf,za1,za2,za3,za4)\n#define VPrintf5(zf,za1,za2,za3,za4,za5) \\\n   fprintf(stderr,zf,za1,za2,za3,za4,za5)\n\n#else\n\nextern void bz_internal_error ( int errcode );\n#define AssertH(cond,errcode) \\\n   { if (!(cond)) bz_internal_error ( errcode ); }\n#define AssertD(cond,msg)                do { } while (0)\n#define VPrintf0(zf)                     do { } while (0)\n#define VPrintf1(zf,za1)                 do { } while (0)\n#define VPrintf2(zf,za1,za2)             do { } while (0)\n#define VPrintf3(zf,za1,za2,za3)         do { } while (0)\n#define VPrintf4(zf,za1,za2,za3,za4)     do { } while (0)\n#define VPrintf5(zf,za1,za2,za3,za4,za5) do { } while (0)\n\n#endif\n\n\n#define BZALLOC(nnn) (strm->bzalloc)(strm->opaque,(nnn),1)\n#define BZFREE(ppp)  (strm->bzfree)(strm->opaque,(ppp))\n\n\n/*-- Header bytes. --*/\n\n#define BZ_HDR_B 0x42   /* 'B' */\n#define BZ_HDR_Z 0x5a   /* 'Z' */\n#define BZ_HDR_h 0x68   /* 'h' */\n#define BZ_HDR_0 0x30   /* '0' */\n  \n/*-- Constants for the back end. --*/\n\n#define BZ_MAX_ALPHA_SIZE 258\n#define BZ_MAX_CODE_LEN    23\n\n#define BZ_RUNA 0\n#define BZ_RUNB 1\n\n#define BZ_N_GROUPS 6\n#define BZ_G_SIZE   50\n#define BZ_N_ITERS  4\n\n#define BZ_MAX_SELECTORS (2 + (900000 / BZ_G_SIZE))\n\n\n\n/*-- Stuff for randomising repetitive blocks. --*/\n\nextern Int32 BZ2_rNums[512];\n\n#define BZ_RAND_DECLS                          \\\n   Int32 rNToGo;                               \\\n   Int32 rTPos                                 \\\n\n#define BZ_RAND_INIT_MASK                      \\\n   s->rNToGo = 0;                              \\\n   s->rTPos  = 0                               \\\n\n#define BZ_RAND_MASK ((s->rNToGo == 1) ? 1 : 0)\n\n#define BZ_RAND_UPD_MASK                       \\\n   if (s->rNToGo == 0) {                       \\\n      s->rNToGo = BZ2_rNums[s->rTPos];         \\\n      s->rTPos++;                              \\\n      if (s->rTPos == 512) s->rTPos = 0;       \\\n   }                                           \\\n   s->rNToGo--;\n\n\n\n/*-- Stuff for doing CRCs. --*/\n\nextern UInt32 BZ2_crc32Table[256];\n\n#define BZ_INITIALISE_CRC(crcVar)              \\\n{                                              \\\n   crcVar = 0xffffffffL;                       \\\n}\n\n#define BZ_FINALISE_CRC(crcVar)                \\\n{                                              \\\n   crcVar = ~(crcVar);                         \\\n}\n\n#define BZ_UPDATE_CRC(crcVar,cha)              \\\n{                                              \\\n   crcVar = (crcVar << 8) ^                    \\\n            BZ2_crc32Table[(crcVar >> 24) ^    \\\n                           ((UChar)cha)];      \\\n}\n\n\n\n/*-- States and modes for compression. --*/\n\n#define BZ_M_IDLE      1\n#define BZ_M_RUNNING   2\n#define BZ_M_FLUSHING  3\n#define BZ_M_FINISHING 4\n\n#define BZ_S_OUTPUT    1\n#define BZ_S_INPUT     2\n\n#define BZ_N_RADIX 2\n#define BZ_N_QSORT 12\n#define BZ_N_SHELL 18\n#define BZ_N_OVERSHOOT (BZ_N_RADIX + BZ_N_QSORT + BZ_N_SHELL + 2)\n\n\n\n\n/*-- Structure holding all the compression-side stuff. --*/\n\ntypedef\n   struct {\n      /* pointer back to the struct bz_stream */\n      bz_stream* strm;\n\n      /* mode this stream is in, and whether inputting */\n      /* or outputting data */\n      Int32    mode;\n      Int32    state;\n\n      /* remembers avail_in when flush/finish requested */\n      UInt32   avail_in_expect;\n\n      /* for doing the block sorting */\n      UInt32*  arr1;\n      UInt32*  arr2;\n      UInt32*  ftab;\n      Int32    origPtr;\n\n      /* aliases for arr1 and arr2 */\n      UInt32*  ptr;\n      UChar*   block;\n      UInt16*  mtfv;\n      UChar*   zbits;\n\n      /* for deciding when to use the fallback sorting algorithm */\n      Int32    workFactor;\n\n      /* run-length-encoding of the input */\n      UInt32   state_in_ch;\n      Int32    state_in_len;\n      BZ_RAND_DECLS;\n\n      /* input and output limits and current posns */\n      Int32    nblock;\n      Int32    nblockMAX;\n      Int32    numZ;\n      Int32    state_out_pos;\n\n      /* map of bytes used in block */\n      Int32    nInUse;\n      Bool     inUse[256];\n      UChar    unseqToSeq[256];\n\n      /* the buffer for bit stream creation */\n      UInt32   bsBuff;\n      Int32    bsLive;\n\n      /* block and combined CRCs */\n      UInt32   blockCRC;\n      UInt32   combinedCRC;\n\n      /* misc administratium */\n      Int32    verbosity;\n      Int32    blockNo;\n      Int32    blockSize100k;\n\n      /* stuff for coding the MTF values */\n      Int32    nMTF;\n      Int32    mtfFreq    [BZ_MAX_ALPHA_SIZE];\n      UChar    selector   [BZ_MAX_SELECTORS];\n      UChar    selectorMtf[BZ_MAX_SELECTORS];\n\n      UChar    len     [BZ_N_GROUPS][BZ_MAX_ALPHA_SIZE];\n      Int32    code    [BZ_N_GROUPS][BZ_MAX_ALPHA_SIZE];\n      Int32    rfreq   [BZ_N_GROUPS][BZ_MAX_ALPHA_SIZE];\n      /* second dimension: only 3 needed; 4 makes index calculations faster */\n      UInt32   len_pack[BZ_MAX_ALPHA_SIZE][4];\n\n   }\n   EState;\n\n\n\n/*-- externs for compression. --*/\n\nextern void \nBZ2_blockSort ( EState* );\n\nextern void \nBZ2_compressBlock ( EState*, Bool );\n\nextern void \nBZ2_bsInitWrite ( EState* );\n\nextern void \nBZ2_hbAssignCodes ( Int32*, UChar*, Int32, Int32, Int32 );\n\nextern void \nBZ2_hbMakeCodeLengths ( UChar*, Int32*, Int32, Int32 );\n\n\n\n/*-- states for decompression. --*/\n\n#define BZ_X_IDLE        1\n#define BZ_X_OUTPUT      2\n\n#define BZ_X_MAGIC_1     10\n#define BZ_X_MAGIC_2     11\n#define BZ_X_MAGIC_3     12\n#define BZ_X_MAGIC_4     13\n#define BZ_X_BLKHDR_1    14\n#define BZ_X_BLKHDR_2    15\n#define BZ_X_BLKHDR_3    16\n#define BZ_X_BLKHDR_4    17\n#define BZ_X_BLKHDR_5    18\n#define BZ_X_BLKHDR_6    19\n#define BZ_X_BCRC_1      20\n#define BZ_X_BCRC_2      21\n#define BZ_X_BCRC_3      22\n#define BZ_X_BCRC_4      23\n#define BZ_X_RANDBIT     24\n#define BZ_X_ORIGPTR_1   25\n#define BZ_X_ORIGPTR_2   26\n#define BZ_X_ORIGPTR_3   27\n#define BZ_X_MAPPING_1   28\n#define BZ_X_MAPPING_2   29\n#define BZ_X_SELECTOR_1  30\n#define BZ_X_SELECTOR_2  31\n#define BZ_X_SELECTOR_3  32\n#define BZ_X_CODING_1    33\n#define BZ_X_CODING_2    34\n#define BZ_X_CODING_3    35\n#define BZ_X_MTF_1       36\n#define BZ_X_MTF_2       37\n#define BZ_X_MTF_3       38\n#define BZ_X_MTF_4       39\n#define BZ_X_MTF_5       40\n#define BZ_X_MTF_6       41\n#define BZ_X_ENDHDR_2    42\n#define BZ_X_ENDHDR_3    43\n#define BZ_X_ENDHDR_4    44\n#define BZ_X_ENDHDR_5    45\n#define BZ_X_ENDHDR_6    46\n#define BZ_X_CCRC_1      47\n#define BZ_X_CCRC_2      48\n#define BZ_X_CCRC_3      49\n#define BZ_X_CCRC_4      50\n\n\n\n/*-- Constants for the fast MTF decoder. --*/\n\n#define MTFA_SIZE 4096\n#define MTFL_SIZE 16\n\n\n\n/*-- Structure holding all the decompression-side stuff. --*/\n\ntypedef\n   struct {\n      /* pointer back to the struct bz_stream */\n      bz_stream* strm;\n\n      /* state indicator for this stream */\n      Int32    state;\n\n      /* for doing the final run-length decoding */\n      UChar    state_out_ch;\n      Int32    state_out_len;\n      Bool     blockRandomised;\n      BZ_RAND_DECLS;\n\n      /* the buffer for bit stream reading */\n      UInt32   bsBuff;\n      Int32    bsLive;\n\n      /* misc administratium */\n      Int32    blockSize100k;\n      Bool     smallDecompress;\n      Int32    currBlockNo;\n      Int32    verbosity;\n\n      /* for undoing the Burrows-Wheeler transform */\n      Int32    origPtr;\n      UInt32   tPos;\n      Int32    k0;\n      Int32    unzftab[256];\n      Int32    nblock_used;\n      Int32    cftab[257];\n      Int32    cftabCopy[257];\n\n      /* for undoing the Burrows-Wheeler transform (FAST) */\n      UInt32   *tt;\n\n      /* for undoing the Burrows-Wheeler transform (SMALL) */\n      UInt16   *ll16;\n      UChar    *ll4;\n\n      /* stored and calculated CRCs */\n      UInt32   storedBlockCRC;\n      UInt32   storedCombinedCRC;\n      UInt32   calculatedBlockCRC;\n      UInt32   calculatedCombinedCRC;\n\n      /* map of bytes used in block */\n      Int32    nInUse;\n      Bool     inUse[256];\n      Bool     inUse16[16];\n      UChar    seqToUnseq[256];\n\n      /* for decoding the MTF values */\n      UChar    mtfa   [MTFA_SIZE];\n      Int32    mtfbase[256 / MTFL_SIZE];\n      UChar    selector   [BZ_MAX_SELECTORS];\n      UChar    selectorMtf[BZ_MAX_SELECTORS];\n      UChar    len  [BZ_N_GROUPS][BZ_MAX_ALPHA_SIZE];\n\n      Int32    limit  [BZ_N_GROUPS][BZ_MAX_ALPHA_SIZE];\n      Int32    base   [BZ_N_GROUPS][BZ_MAX_ALPHA_SIZE];\n      Int32    perm   [BZ_N_GROUPS][BZ_MAX_ALPHA_SIZE];\n      Int32    minLens[BZ_N_GROUPS];\n\n      /* save area for scalars in the main decompress code */\n      Int32    save_i;\n      Int32    save_j;\n      Int32    save_t;\n      Int32    save_alphaSize;\n      Int32    save_nGroups;\n      Int32    save_nSelectors;\n      Int32    save_EOB;\n      Int32    save_groupNo;\n      Int32    save_groupPos;\n      Int32    save_nextSym;\n      Int32    save_nblockMAX;\n      Int32    save_nblock;\n      Int32    save_es;\n      Int32    save_N;\n      Int32    save_curr;\n      Int32    save_zt;\n      Int32    save_zn; \n      Int32    save_zvec;\n      Int32    save_zj;\n      Int32    save_gSel;\n      Int32    save_gMinlen;\n      Int32*   save_gLimit;\n      Int32*   save_gBase;\n      Int32*   save_gPerm;\n\n   }\n   DState;\n\n\n\n/*-- Macros for decompression. --*/\n\n#define BZ_GET_FAST(cccc)                     \\\n    /* c_tPos is unsigned, hence test < 0 is pointless. */ \\\n    if (s->tPos >= (UInt32)100000 * (UInt32)s->blockSize100k) return True; \\\n    s->tPos = s->tt[s->tPos];                 \\\n    cccc = (UChar)(s->tPos & 0xff);           \\\n    s->tPos >>= 8;\n\n#define BZ_GET_FAST_C(cccc)                   \\\n    /* c_tPos is unsigned, hence test < 0 is pointless. */ \\\n    if (c_tPos >= (UInt32)100000 * (UInt32)ro_blockSize100k) return True; \\\n    c_tPos = c_tt[c_tPos];                    \\\n    cccc = (UChar)(c_tPos & 0xff);            \\\n    c_tPos >>= 8;\n\n#define SET_LL4(i,n)                                          \\\n   { if (((i) & 0x1) == 0)                                    \\\n        s->ll4[(i) >> 1] = (s->ll4[(i) >> 1] & 0xf0) | (n); else    \\\n        s->ll4[(i) >> 1] = (s->ll4[(i) >> 1] & 0x0f) | ((n) << 4);  \\\n   }\n\n#define GET_LL4(i)                             \\\n   ((((UInt32)(s->ll4[(i) >> 1])) >> (((i) << 2) & 0x4)) & 0xF)\n\n#define SET_LL(i,n)                          \\\n   { s->ll16[i] = (UInt16)(n & 0x0000ffff);  \\\n     SET_LL4(i, n >> 16);                    \\\n   }\n\n#define GET_LL(i) \\\n   (((UInt32)s->ll16[i]) | (GET_LL4(i) << 16))\n\n#define BZ_GET_SMALL(cccc)                            \\\n    /* c_tPos is unsigned, hence test < 0 is pointless. */ \\\n    if (s->tPos >= (UInt32)100000 * (UInt32)s->blockSize100k) return True; \\\n    cccc = BZ2_indexIntoF ( s->tPos, s->cftab );    \\\n    s->tPos = GET_LL(s->tPos);\n\n\n/*-- externs for decompression. --*/\n\nextern Int32 \nBZ2_indexIntoF ( Int32, Int32* );\n\nextern Int32 \nBZ2_decompress ( DState* );\n\nextern void \nBZ2_hbCreateDecodeTables ( Int32*, Int32*, Int32*, UChar*,\n                           Int32,  Int32, Int32 );\n\n\n#endif\n\n\n/*-- BZ_NO_STDIO seems to make NULL disappear on some platforms. --*/\n\n#ifdef BZ_NO_STDIO\n#ifndef NULL\n#define NULL 0\n#endif\n#endif\n\n\n/*-------------------------------------------------------------*/\n/*--- end                                   bzlib_private.h ---*/\n/*-------------------------------------------------------------*/\n"
  },
  {
    "path": "external/bzip2/compress.c",
    "content": "\n/*-------------------------------------------------------------*/\n/*--- Compression machinery (not incl block sorting)        ---*/\n/*---                                            compress.c ---*/\n/*-------------------------------------------------------------*/\n\n/* ------------------------------------------------------------------\n   This file is part of bzip2/libbzip2, a program and library for\n   lossless, block-sorting data compression.\n\n   bzip2/libbzip2 version 1.0.6 of 6 September 2010\n   Copyright (C) 1996-2010 Julian Seward <jseward@bzip.org>\n\n   Please read the WARNING, DISCLAIMER and PATENTS sections in the \n   README file.\n\n   This program is released under the terms of the license contained\n   in the file LICENSE.\n   ------------------------------------------------------------------ */\n\n\n/* CHANGES\n    0.9.0    -- original version.\n    0.9.0a/b -- no changes in this file.\n    0.9.0c   -- changed setting of nGroups in sendMTFValues() \n                so as to do a bit better on small files\n*/\n\n#include \"bzlib_private.h\"\n\n\n/*---------------------------------------------------*/\n/*--- Bit stream I/O                              ---*/\n/*---------------------------------------------------*/\n\n/*---------------------------------------------------*/\nvoid BZ2_bsInitWrite ( EState* s )\n{\n   s->bsLive = 0;\n   s->bsBuff = 0;\n}\n\n\n/*---------------------------------------------------*/\nstatic\nvoid bsFinishWrite ( EState* s )\n{\n   while (s->bsLive > 0) {\n      s->zbits[s->numZ] = (UChar)(s->bsBuff >> 24);\n      s->numZ++;\n      s->bsBuff <<= 8;\n      s->bsLive -= 8;\n   }\n}\n\n\n/*---------------------------------------------------*/\n#define bsNEEDW(nz)                           \\\n{                                             \\\n   while (s->bsLive >= 8) {                   \\\n      s->zbits[s->numZ]                       \\\n         = (UChar)(s->bsBuff >> 24);          \\\n      s->numZ++;                              \\\n      s->bsBuff <<= 8;                        \\\n      s->bsLive -= 8;                         \\\n   }                                          \\\n}\n\n\n/*---------------------------------------------------*/\nstatic\n__inline__\nvoid bsW ( EState* s, Int32 n, UInt32 v )\n{\n   bsNEEDW ( n );\n   s->bsBuff |= (v << (32 - s->bsLive - n));\n   s->bsLive += n;\n}\n\n\n/*---------------------------------------------------*/\nstatic\nvoid bsPutUInt32 ( EState* s, UInt32 u )\n{\n   bsW ( s, 8, (u >> 24) & 0xffL );\n   bsW ( s, 8, (u >> 16) & 0xffL );\n   bsW ( s, 8, (u >>  8) & 0xffL );\n   bsW ( s, 8,  u        & 0xffL );\n}\n\n\n/*---------------------------------------------------*/\nstatic\nvoid bsPutUChar ( EState* s, UChar c )\n{\n   bsW( s, 8, (UInt32)c );\n}\n\n\n/*---------------------------------------------------*/\n/*--- The back end proper                         ---*/\n/*---------------------------------------------------*/\n\n/*---------------------------------------------------*/\nstatic\nvoid makeMaps_e ( EState* s )\n{\n   Int32 i;\n   s->nInUse = 0;\n   for (i = 0; i < 256; i++)\n      if (s->inUse[i]) {\n         s->unseqToSeq[i] = s->nInUse;\n         s->nInUse++;\n      }\n}\n\n\n/*---------------------------------------------------*/\nstatic\nvoid generateMTFValues ( EState* s )\n{\n   UChar   yy[256];\n   Int32   i, j;\n   Int32   zPend;\n   Int32   wr;\n   Int32   EOB;\n\n   /* \n      After sorting (eg, here),\n         s->arr1 [ 0 .. s->nblock-1 ] holds sorted order,\n         and\n         ((UChar*)s->arr2) [ 0 .. s->nblock-1 ] \n         holds the original block data.\n\n      The first thing to do is generate the MTF values,\n      and put them in\n         ((UInt16*)s->arr1) [ 0 .. s->nblock-1 ].\n      Because there are strictly fewer or equal MTF values\n      than block values, ptr values in this area are overwritten\n      with MTF values only when they are no longer needed.\n\n      The final compressed bitstream is generated into the\n      area starting at\n         (UChar*) (&((UChar*)s->arr2)[s->nblock])\n\n      These storage aliases are set up in bzCompressInit(),\n      except for the last one, which is arranged in \n      compressBlock().\n   */\n   UInt32* ptr   = s->ptr;\n   UChar* block  = s->block;\n   UInt16* mtfv  = s->mtfv;\n\n   makeMaps_e ( s );\n   EOB = s->nInUse+1;\n\n   for (i = 0; i <= EOB; i++) s->mtfFreq[i] = 0;\n\n   wr = 0;\n   zPend = 0;\n   for (i = 0; i < s->nInUse; i++) yy[i] = (UChar) i;\n\n   for (i = 0; i < s->nblock; i++) {\n      UChar ll_i;\n      AssertD ( wr <= i, \"generateMTFValues(1)\" );\n      j = ptr[i]-1; if (j < 0) j += s->nblock;\n      ll_i = s->unseqToSeq[block[j]];\n      AssertD ( ll_i < s->nInUse, \"generateMTFValues(2a)\" );\n\n      if (yy[0] == ll_i) { \n         zPend++;\n      } else {\n\n         if (zPend > 0) {\n            zPend--;\n            while (True) {\n               if (zPend & 1) {\n                  mtfv[wr] = BZ_RUNB; wr++; \n                  s->mtfFreq[BZ_RUNB]++; \n               } else {\n                  mtfv[wr] = BZ_RUNA; wr++; \n                  s->mtfFreq[BZ_RUNA]++; \n               }\n               if (zPend < 2) break;\n               zPend = (zPend - 2) / 2;\n            };\n            zPend = 0;\n         }\n         {\n            register UChar  rtmp;\n            register UChar* ryy_j;\n            register UChar  rll_i;\n            rtmp  = yy[1];\n            yy[1] = yy[0];\n            ryy_j = &(yy[1]);\n            rll_i = ll_i;\n            while ( rll_i != rtmp ) {\n               register UChar rtmp2;\n               ryy_j++;\n               rtmp2  = rtmp;\n               rtmp   = *ryy_j;\n               *ryy_j = rtmp2;\n            };\n            yy[0] = rtmp;\n            j = ryy_j - &(yy[0]);\n            mtfv[wr] = j+1; wr++; s->mtfFreq[j+1]++;\n         }\n\n      }\n   }\n\n   if (zPend > 0) {\n      zPend--;\n      while (True) {\n         if (zPend & 1) {\n            mtfv[wr] = BZ_RUNB; wr++; \n            s->mtfFreq[BZ_RUNB]++; \n         } else {\n            mtfv[wr] = BZ_RUNA; wr++; \n            s->mtfFreq[BZ_RUNA]++; \n         }\n         if (zPend < 2) break;\n         zPend = (zPend - 2) / 2;\n      };\n      zPend = 0;\n   }\n\n   mtfv[wr] = EOB; wr++; s->mtfFreq[EOB]++;\n\n   s->nMTF = wr;\n}\n\n\n/*---------------------------------------------------*/\n#define BZ_LESSER_ICOST  0\n#define BZ_GREATER_ICOST 15\n\nstatic\nvoid sendMTFValues ( EState* s )\n{\n   Int32 v, t, i, j, gs, ge, totc, bt, bc, iter;\n   Int32 nSelectors, alphaSize, minLen, maxLen, selCtr;\n   Int32 nGroups, nBytes;\n\n   /*--\n   UChar  len [BZ_N_GROUPS][BZ_MAX_ALPHA_SIZE];\n   is a global since the decoder also needs it.\n\n   Int32  code[BZ_N_GROUPS][BZ_MAX_ALPHA_SIZE];\n   Int32  rfreq[BZ_N_GROUPS][BZ_MAX_ALPHA_SIZE];\n   are also globals only used in this proc.\n   Made global to keep stack frame size small.\n   --*/\n\n\n   UInt16 cost[BZ_N_GROUPS];\n   Int32  fave[BZ_N_GROUPS];\n\n   UInt16* mtfv = s->mtfv;\n\n   if (s->verbosity >= 3)\n      VPrintf3( \"      %d in block, %d after MTF & 1-2 coding, \"\n                \"%d+2 syms in use\\n\", \n                s->nblock, s->nMTF, s->nInUse );\n\n   alphaSize = s->nInUse+2;\n   for (t = 0; t < BZ_N_GROUPS; t++)\n      for (v = 0; v < alphaSize; v++)\n         s->len[t][v] = BZ_GREATER_ICOST;\n\n   /*--- Decide how many coding tables to use ---*/\n   AssertH ( s->nMTF > 0, 3001 );\n   if (s->nMTF < 200)  nGroups = 2; else\n   if (s->nMTF < 600)  nGroups = 3; else\n   if (s->nMTF < 1200) nGroups = 4; else\n   if (s->nMTF < 2400) nGroups = 5; else\n                       nGroups = 6;\n\n   /*--- Generate an initial set of coding tables ---*/\n   { \n      Int32 nPart, remF, tFreq, aFreq;\n\n      nPart = nGroups;\n      remF  = s->nMTF;\n      gs = 0;\n      while (nPart > 0) {\n         tFreq = remF / nPart;\n         ge = gs-1;\n         aFreq = 0;\n         while (aFreq < tFreq && ge < alphaSize-1) {\n            ge++;\n            aFreq += s->mtfFreq[ge];\n         }\n\n         if (ge > gs \n             && nPart != nGroups && nPart != 1 \n             && ((nGroups-nPart) % 2 == 1)) {\n            aFreq -= s->mtfFreq[ge];\n            ge--;\n         }\n\n         if (s->verbosity >= 3)\n            VPrintf5( \"      initial group %d, [%d .. %d], \"\n                      \"has %d syms (%4.1f%%)\\n\",\n                      nPart, gs, ge, aFreq, \n                      (100.0 * (float)aFreq) / (float)(s->nMTF) );\n \n         for (v = 0; v < alphaSize; v++)\n            if (v >= gs && v <= ge) \n               s->len[nPart-1][v] = BZ_LESSER_ICOST; else\n               s->len[nPart-1][v] = BZ_GREATER_ICOST;\n \n         nPart--;\n         gs = ge+1;\n         remF -= aFreq;\n      }\n   }\n\n   /*--- \n      Iterate up to BZ_N_ITERS times to improve the tables.\n   ---*/\n   for (iter = 0; iter < BZ_N_ITERS; iter++) {\n\n      for (t = 0; t < nGroups; t++) fave[t] = 0;\n\n      for (t = 0; t < nGroups; t++)\n         for (v = 0; v < alphaSize; v++)\n            s->rfreq[t][v] = 0;\n\n      /*---\n        Set up an auxiliary length table which is used to fast-track\n\tthe common case (nGroups == 6). \n      ---*/\n      if (nGroups == 6) {\n         for (v = 0; v < alphaSize; v++) {\n            s->len_pack[v][0] = (s->len[1][v] << 16) | s->len[0][v];\n            s->len_pack[v][1] = (s->len[3][v] << 16) | s->len[2][v];\n            s->len_pack[v][2] = (s->len[5][v] << 16) | s->len[4][v];\n\t }\n      }\n\n      nSelectors = 0;\n      totc = 0;\n      gs = 0;\n      while (True) {\n\n         /*--- Set group start & end marks. --*/\n         if (gs >= s->nMTF) break;\n         ge = gs + BZ_G_SIZE - 1; \n         if (ge >= s->nMTF) ge = s->nMTF-1;\n\n         /*-- \n            Calculate the cost of this group as coded\n            by each of the coding tables.\n         --*/\n         for (t = 0; t < nGroups; t++) cost[t] = 0;\n\n         if (nGroups == 6 && 50 == ge-gs+1) {\n            /*--- fast track the common case ---*/\n            register UInt32 cost01, cost23, cost45;\n            register UInt16 icv;\n            cost01 = cost23 = cost45 = 0;\n\n#           define BZ_ITER(nn)                \\\n               icv = mtfv[gs+(nn)];           \\\n               cost01 += s->len_pack[icv][0]; \\\n               cost23 += s->len_pack[icv][1]; \\\n               cost45 += s->len_pack[icv][2]; \\\n\n            BZ_ITER(0);  BZ_ITER(1);  BZ_ITER(2);  BZ_ITER(3);  BZ_ITER(4);\n            BZ_ITER(5);  BZ_ITER(6);  BZ_ITER(7);  BZ_ITER(8);  BZ_ITER(9);\n            BZ_ITER(10); BZ_ITER(11); BZ_ITER(12); BZ_ITER(13); BZ_ITER(14);\n            BZ_ITER(15); BZ_ITER(16); BZ_ITER(17); BZ_ITER(18); BZ_ITER(19);\n            BZ_ITER(20); BZ_ITER(21); BZ_ITER(22); BZ_ITER(23); BZ_ITER(24);\n            BZ_ITER(25); BZ_ITER(26); BZ_ITER(27); BZ_ITER(28); BZ_ITER(29);\n            BZ_ITER(30); BZ_ITER(31); BZ_ITER(32); BZ_ITER(33); BZ_ITER(34);\n            BZ_ITER(35); BZ_ITER(36); BZ_ITER(37); BZ_ITER(38); BZ_ITER(39);\n            BZ_ITER(40); BZ_ITER(41); BZ_ITER(42); BZ_ITER(43); BZ_ITER(44);\n            BZ_ITER(45); BZ_ITER(46); BZ_ITER(47); BZ_ITER(48); BZ_ITER(49);\n\n#           undef BZ_ITER\n\n            cost[0] = cost01 & 0xffff; cost[1] = cost01 >> 16;\n            cost[2] = cost23 & 0xffff; cost[3] = cost23 >> 16;\n            cost[4] = cost45 & 0xffff; cost[5] = cost45 >> 16;\n\n         } else {\n\t    /*--- slow version which correctly handles all situations ---*/\n            for (i = gs; i <= ge; i++) { \n               UInt16 icv = mtfv[i];\n               for (t = 0; t < nGroups; t++) cost[t] += s->len[t][icv];\n            }\n         }\n \n         /*-- \n            Find the coding table which is best for this group,\n            and record its identity in the selector table.\n         --*/\n         bc = 999999999; bt = -1;\n         for (t = 0; t < nGroups; t++)\n            if (cost[t] < bc) { bc = cost[t]; bt = t; };\n         totc += bc;\n         fave[bt]++;\n         s->selector[nSelectors] = bt;\n         nSelectors++;\n\n         /*-- \n            Increment the symbol frequencies for the selected table.\n          --*/\n         if (nGroups == 6 && 50 == ge-gs+1) {\n            /*--- fast track the common case ---*/\n\n#           define BZ_ITUR(nn) s->rfreq[bt][ mtfv[gs+(nn)] ]++\n\n            BZ_ITUR(0);  BZ_ITUR(1);  BZ_ITUR(2);  BZ_ITUR(3);  BZ_ITUR(4);\n            BZ_ITUR(5);  BZ_ITUR(6);  BZ_ITUR(7);  BZ_ITUR(8);  BZ_ITUR(9);\n            BZ_ITUR(10); BZ_ITUR(11); BZ_ITUR(12); BZ_ITUR(13); BZ_ITUR(14);\n            BZ_ITUR(15); BZ_ITUR(16); BZ_ITUR(17); BZ_ITUR(18); BZ_ITUR(19);\n            BZ_ITUR(20); BZ_ITUR(21); BZ_ITUR(22); BZ_ITUR(23); BZ_ITUR(24);\n            BZ_ITUR(25); BZ_ITUR(26); BZ_ITUR(27); BZ_ITUR(28); BZ_ITUR(29);\n            BZ_ITUR(30); BZ_ITUR(31); BZ_ITUR(32); BZ_ITUR(33); BZ_ITUR(34);\n            BZ_ITUR(35); BZ_ITUR(36); BZ_ITUR(37); BZ_ITUR(38); BZ_ITUR(39);\n            BZ_ITUR(40); BZ_ITUR(41); BZ_ITUR(42); BZ_ITUR(43); BZ_ITUR(44);\n            BZ_ITUR(45); BZ_ITUR(46); BZ_ITUR(47); BZ_ITUR(48); BZ_ITUR(49);\n\n#           undef BZ_ITUR\n\n         } else {\n\t    /*--- slow version which correctly handles all situations ---*/\n            for (i = gs; i <= ge; i++)\n               s->rfreq[bt][ mtfv[i] ]++;\n         }\n\n         gs = ge+1;\n      }\n      if (s->verbosity >= 3) {\n         VPrintf2 ( \"      pass %d: size is %d, grp uses are \", \n                   iter+1, totc/8 );\n         for (t = 0; t < nGroups; t++)\n            VPrintf1 ( \"%d \", fave[t] );\n         VPrintf0 ( \"\\n\" );\n      }\n\n      /*--\n        Recompute the tables based on the accumulated frequencies.\n      --*/\n      /* maxLen was changed from 20 to 17 in bzip2-1.0.3.  See \n         comment in huffman.c for details. */\n      for (t = 0; t < nGroups; t++)\n         BZ2_hbMakeCodeLengths ( &(s->len[t][0]), &(s->rfreq[t][0]), \n                                 alphaSize, 17 /*20*/ );\n   }\n\n\n   AssertH( nGroups < 8, 3002 );\n   AssertH( nSelectors < 32768 &&\n            nSelectors <= (2 + (900000 / BZ_G_SIZE)),\n            3003 );\n\n\n   /*--- Compute MTF values for the selectors. ---*/\n   {\n      UChar pos[BZ_N_GROUPS], ll_i, tmp2, tmp;\n      for (i = 0; i < nGroups; i++) pos[i] = i;\n      for (i = 0; i < nSelectors; i++) {\n         ll_i = s->selector[i];\n         j = 0;\n         tmp = pos[j];\n         while ( ll_i != tmp ) {\n            j++;\n            tmp2 = tmp;\n            tmp = pos[j];\n            pos[j] = tmp2;\n         };\n         pos[0] = tmp;\n         s->selectorMtf[i] = j;\n      }\n   };\n\n   /*--- Assign actual codes for the tables. --*/\n   for (t = 0; t < nGroups; t++) {\n      minLen = 32;\n      maxLen = 0;\n      for (i = 0; i < alphaSize; i++) {\n         if (s->len[t][i] > maxLen) maxLen = s->len[t][i];\n         if (s->len[t][i] < minLen) minLen = s->len[t][i];\n      }\n      AssertH ( !(maxLen > 17 /*20*/ ), 3004 );\n      AssertH ( !(minLen < 1),  3005 );\n      BZ2_hbAssignCodes ( &(s->code[t][0]), &(s->len[t][0]), \n                          minLen, maxLen, alphaSize );\n   }\n\n   /*--- Transmit the mapping table. ---*/\n   { \n      Bool inUse16[16];\n      for (i = 0; i < 16; i++) {\n          inUse16[i] = False;\n          for (j = 0; j < 16; j++)\n             if (s->inUse[i * 16 + j]) inUse16[i] = True;\n      }\n     \n      nBytes = s->numZ;\n      for (i = 0; i < 16; i++)\n         if (inUse16[i]) bsW(s,1,1); else bsW(s,1,0);\n\n      for (i = 0; i < 16; i++)\n         if (inUse16[i])\n            for (j = 0; j < 16; j++) {\n               if (s->inUse[i * 16 + j]) bsW(s,1,1); else bsW(s,1,0);\n            }\n\n      if (s->verbosity >= 3) \n         VPrintf1( \"      bytes: mapping %d, \", s->numZ-nBytes );\n   }\n\n   /*--- Now the selectors. ---*/\n   nBytes = s->numZ;\n   bsW ( s, 3, nGroups );\n   bsW ( s, 15, nSelectors );\n   for (i = 0; i < nSelectors; i++) { \n      for (j = 0; j < s->selectorMtf[i]; j++) bsW(s,1,1);\n      bsW(s,1,0);\n   }\n   if (s->verbosity >= 3)\n      VPrintf1( \"selectors %d, \", s->numZ-nBytes );\n\n   /*--- Now the coding tables. ---*/\n   nBytes = s->numZ;\n\n   for (t = 0; t < nGroups; t++) {\n      Int32 curr = s->len[t][0];\n      bsW ( s, 5, curr );\n      for (i = 0; i < alphaSize; i++) {\n         while (curr < s->len[t][i]) { bsW(s,2,2); curr++; /* 10 */ };\n         while (curr > s->len[t][i]) { bsW(s,2,3); curr--; /* 11 */ };\n         bsW ( s, 1, 0 );\n      }\n   }\n\n   if (s->verbosity >= 3)\n      VPrintf1 ( \"code lengths %d, \", s->numZ-nBytes );\n\n   /*--- And finally, the block data proper ---*/\n   nBytes = s->numZ;\n   selCtr = 0;\n   gs = 0;\n   while (True) {\n      if (gs >= s->nMTF) break;\n      ge = gs + BZ_G_SIZE - 1; \n      if (ge >= s->nMTF) ge = s->nMTF-1;\n      AssertH ( s->selector[selCtr] < nGroups, 3006 );\n\n      if (nGroups == 6 && 50 == ge-gs+1) {\n            /*--- fast track the common case ---*/\n            UInt16 mtfv_i;\n            UChar* s_len_sel_selCtr \n               = &(s->len[s->selector[selCtr]][0]);\n            Int32* s_code_sel_selCtr\n               = &(s->code[s->selector[selCtr]][0]);\n\n#           define BZ_ITAH(nn)                      \\\n               mtfv_i = mtfv[gs+(nn)];              \\\n               bsW ( s,                             \\\n                     s_len_sel_selCtr[mtfv_i],      \\\n                     s_code_sel_selCtr[mtfv_i] )\n\n            BZ_ITAH(0);  BZ_ITAH(1);  BZ_ITAH(2);  BZ_ITAH(3);  BZ_ITAH(4);\n            BZ_ITAH(5);  BZ_ITAH(6);  BZ_ITAH(7);  BZ_ITAH(8);  BZ_ITAH(9);\n            BZ_ITAH(10); BZ_ITAH(11); BZ_ITAH(12); BZ_ITAH(13); BZ_ITAH(14);\n            BZ_ITAH(15); BZ_ITAH(16); BZ_ITAH(17); BZ_ITAH(18); BZ_ITAH(19);\n            BZ_ITAH(20); BZ_ITAH(21); BZ_ITAH(22); BZ_ITAH(23); BZ_ITAH(24);\n            BZ_ITAH(25); BZ_ITAH(26); BZ_ITAH(27); BZ_ITAH(28); BZ_ITAH(29);\n            BZ_ITAH(30); BZ_ITAH(31); BZ_ITAH(32); BZ_ITAH(33); BZ_ITAH(34);\n            BZ_ITAH(35); BZ_ITAH(36); BZ_ITAH(37); BZ_ITAH(38); BZ_ITAH(39);\n            BZ_ITAH(40); BZ_ITAH(41); BZ_ITAH(42); BZ_ITAH(43); BZ_ITAH(44);\n            BZ_ITAH(45); BZ_ITAH(46); BZ_ITAH(47); BZ_ITAH(48); BZ_ITAH(49);\n\n#           undef BZ_ITAH\n\n      } else {\n\t /*--- slow version which correctly handles all situations ---*/\n         for (i = gs; i <= ge; i++) {\n            bsW ( s, \n                  s->len  [s->selector[selCtr]] [mtfv[i]],\n                  s->code [s->selector[selCtr]] [mtfv[i]] );\n         }\n      }\n\n\n      gs = ge+1;\n      selCtr++;\n   }\n   AssertH( selCtr == nSelectors, 3007 );\n\n   if (s->verbosity >= 3)\n      VPrintf1( \"codes %d\\n\", s->numZ-nBytes );\n}\n\n\n/*---------------------------------------------------*/\nvoid BZ2_compressBlock ( EState* s, Bool is_last_block )\n{\n   if (s->nblock > 0) {\n\n      BZ_FINALISE_CRC ( s->blockCRC );\n      s->combinedCRC = (s->combinedCRC << 1) | (s->combinedCRC >> 31);\n      s->combinedCRC ^= s->blockCRC;\n      if (s->blockNo > 1) s->numZ = 0;\n\n      if (s->verbosity >= 2)\n         VPrintf4( \"    block %d: crc = 0x%08x, \"\n                   \"combined CRC = 0x%08x, size = %d\\n\",\n                   s->blockNo, s->blockCRC, s->combinedCRC, s->nblock );\n\n      BZ2_blockSort ( s );\n   }\n\n   s->zbits = (UChar*) (&((UChar*)s->arr2)[s->nblock]);\n\n   /*-- If this is the first block, create the stream header. --*/\n   if (s->blockNo == 1) {\n      BZ2_bsInitWrite ( s );\n      bsPutUChar ( s, BZ_HDR_B );\n      bsPutUChar ( s, BZ_HDR_Z );\n      bsPutUChar ( s, BZ_HDR_h );\n      bsPutUChar ( s, (UChar)(BZ_HDR_0 + s->blockSize100k) );\n   }\n\n   if (s->nblock > 0) {\n\n      bsPutUChar ( s, 0x31 ); bsPutUChar ( s, 0x41 );\n      bsPutUChar ( s, 0x59 ); bsPutUChar ( s, 0x26 );\n      bsPutUChar ( s, 0x53 ); bsPutUChar ( s, 0x59 );\n\n      /*-- Now the block's CRC, so it is in a known place. --*/\n      bsPutUInt32 ( s, s->blockCRC );\n\n      /*-- \n         Now a single bit indicating (non-)randomisation. \n         As of version 0.9.5, we use a better sorting algorithm\n         which makes randomisation unnecessary.  So always set\n         the randomised bit to 'no'.  Of course, the decoder\n         still needs to be able to handle randomised blocks\n         so as to maintain backwards compatibility with\n         older versions of bzip2.\n      --*/\n      bsW(s,1,0);\n\n      bsW ( s, 24, s->origPtr );\n      generateMTFValues ( s );\n      sendMTFValues ( s );\n   }\n\n\n   /*-- If this is the last block, add the stream trailer. --*/\n   if (is_last_block) {\n\n      bsPutUChar ( s, 0x17 ); bsPutUChar ( s, 0x72 );\n      bsPutUChar ( s, 0x45 ); bsPutUChar ( s, 0x38 );\n      bsPutUChar ( s, 0x50 ); bsPutUChar ( s, 0x90 );\n      bsPutUInt32 ( s, s->combinedCRC );\n      if (s->verbosity >= 2)\n         VPrintf1( \"    final combined CRC = 0x%08x\\n   \", s->combinedCRC );\n      bsFinishWrite ( s );\n   }\n}\n\n\n/*-------------------------------------------------------------*/\n/*--- end                                        compress.c ---*/\n/*-------------------------------------------------------------*/\n"
  },
  {
    "path": "external/bzip2/crctable.c",
    "content": "\n/*-------------------------------------------------------------*/\n/*--- Table for doing CRCs                                  ---*/\n/*---                                            crctable.c ---*/\n/*-------------------------------------------------------------*/\n\n/* ------------------------------------------------------------------\n   This file is part of bzip2/libbzip2, a program and library for\n   lossless, block-sorting data compression.\n\n   bzip2/libbzip2 version 1.0.6 of 6 September 2010\n   Copyright (C) 1996-2010 Julian Seward <jseward@bzip.org>\n\n   Please read the WARNING, DISCLAIMER and PATENTS sections in the \n   README file.\n\n   This program is released under the terms of the license contained\n   in the file LICENSE.\n   ------------------------------------------------------------------ */\n\n\n#include \"bzlib_private.h\"\n\n/*--\n  I think this is an implementation of the AUTODIN-II,\n  Ethernet & FDDI 32-bit CRC standard.  Vaguely derived\n  from code by Rob Warnock, in Section 51 of the\n  comp.compression FAQ.\n--*/\n\nUInt32 BZ2_crc32Table[256] = {\n\n   /*-- Ugly, innit? --*/\n\n   0x00000000L, 0x04c11db7L, 0x09823b6eL, 0x0d4326d9L,\n   0x130476dcL, 0x17c56b6bL, 0x1a864db2L, 0x1e475005L,\n   0x2608edb8L, 0x22c9f00fL, 0x2f8ad6d6L, 0x2b4bcb61L,\n   0x350c9b64L, 0x31cd86d3L, 0x3c8ea00aL, 0x384fbdbdL,\n   0x4c11db70L, 0x48d0c6c7L, 0x4593e01eL, 0x4152fda9L,\n   0x5f15adacL, 0x5bd4b01bL, 0x569796c2L, 0x52568b75L,\n   0x6a1936c8L, 0x6ed82b7fL, 0x639b0da6L, 0x675a1011L,\n   0x791d4014L, 0x7ddc5da3L, 0x709f7b7aL, 0x745e66cdL,\n   0x9823b6e0L, 0x9ce2ab57L, 0x91a18d8eL, 0x95609039L,\n   0x8b27c03cL, 0x8fe6dd8bL, 0x82a5fb52L, 0x8664e6e5L,\n   0xbe2b5b58L, 0xbaea46efL, 0xb7a96036L, 0xb3687d81L,\n   0xad2f2d84L, 0xa9ee3033L, 0xa4ad16eaL, 0xa06c0b5dL,\n   0xd4326d90L, 0xd0f37027L, 0xddb056feL, 0xd9714b49L,\n   0xc7361b4cL, 0xc3f706fbL, 0xceb42022L, 0xca753d95L,\n   0xf23a8028L, 0xf6fb9d9fL, 0xfbb8bb46L, 0xff79a6f1L,\n   0xe13ef6f4L, 0xe5ffeb43L, 0xe8bccd9aL, 0xec7dd02dL,\n   0x34867077L, 0x30476dc0L, 0x3d044b19L, 0x39c556aeL,\n   0x278206abL, 0x23431b1cL, 0x2e003dc5L, 0x2ac12072L,\n   0x128e9dcfL, 0x164f8078L, 0x1b0ca6a1L, 0x1fcdbb16L,\n   0x018aeb13L, 0x054bf6a4L, 0x0808d07dL, 0x0cc9cdcaL,\n   0x7897ab07L, 0x7c56b6b0L, 0x71159069L, 0x75d48ddeL,\n   0x6b93dddbL, 0x6f52c06cL, 0x6211e6b5L, 0x66d0fb02L,\n   0x5e9f46bfL, 0x5a5e5b08L, 0x571d7dd1L, 0x53dc6066L,\n   0x4d9b3063L, 0x495a2dd4L, 0x44190b0dL, 0x40d816baL,\n   0xaca5c697L, 0xa864db20L, 0xa527fdf9L, 0xa1e6e04eL,\n   0xbfa1b04bL, 0xbb60adfcL, 0xb6238b25L, 0xb2e29692L,\n   0x8aad2b2fL, 0x8e6c3698L, 0x832f1041L, 0x87ee0df6L,\n   0x99a95df3L, 0x9d684044L, 0x902b669dL, 0x94ea7b2aL,\n   0xe0b41de7L, 0xe4750050L, 0xe9362689L, 0xedf73b3eL,\n   0xf3b06b3bL, 0xf771768cL, 0xfa325055L, 0xfef34de2L,\n   0xc6bcf05fL, 0xc27dede8L, 0xcf3ecb31L, 0xcbffd686L,\n   0xd5b88683L, 0xd1799b34L, 0xdc3abdedL, 0xd8fba05aL,\n   0x690ce0eeL, 0x6dcdfd59L, 0x608edb80L, 0x644fc637L,\n   0x7a089632L, 0x7ec98b85L, 0x738aad5cL, 0x774bb0ebL,\n   0x4f040d56L, 0x4bc510e1L, 0x46863638L, 0x42472b8fL,\n   0x5c007b8aL, 0x58c1663dL, 0x558240e4L, 0x51435d53L,\n   0x251d3b9eL, 0x21dc2629L, 0x2c9f00f0L, 0x285e1d47L,\n   0x36194d42L, 0x32d850f5L, 0x3f9b762cL, 0x3b5a6b9bL,\n   0x0315d626L, 0x07d4cb91L, 0x0a97ed48L, 0x0e56f0ffL,\n   0x1011a0faL, 0x14d0bd4dL, 0x19939b94L, 0x1d528623L,\n   0xf12f560eL, 0xf5ee4bb9L, 0xf8ad6d60L, 0xfc6c70d7L,\n   0xe22b20d2L, 0xe6ea3d65L, 0xeba91bbcL, 0xef68060bL,\n   0xd727bbb6L, 0xd3e6a601L, 0xdea580d8L, 0xda649d6fL,\n   0xc423cd6aL, 0xc0e2d0ddL, 0xcda1f604L, 0xc960ebb3L,\n   0xbd3e8d7eL, 0xb9ff90c9L, 0xb4bcb610L, 0xb07daba7L,\n   0xae3afba2L, 0xaafbe615L, 0xa7b8c0ccL, 0xa379dd7bL,\n   0x9b3660c6L, 0x9ff77d71L, 0x92b45ba8L, 0x9675461fL,\n   0x8832161aL, 0x8cf30badL, 0x81b02d74L, 0x857130c3L,\n   0x5d8a9099L, 0x594b8d2eL, 0x5408abf7L, 0x50c9b640L,\n   0x4e8ee645L, 0x4a4ffbf2L, 0x470cdd2bL, 0x43cdc09cL,\n   0x7b827d21L, 0x7f436096L, 0x7200464fL, 0x76c15bf8L,\n   0x68860bfdL, 0x6c47164aL, 0x61043093L, 0x65c52d24L,\n   0x119b4be9L, 0x155a565eL, 0x18197087L, 0x1cd86d30L,\n   0x029f3d35L, 0x065e2082L, 0x0b1d065bL, 0x0fdc1becL,\n   0x3793a651L, 0x3352bbe6L, 0x3e119d3fL, 0x3ad08088L,\n   0x2497d08dL, 0x2056cd3aL, 0x2d15ebe3L, 0x29d4f654L,\n   0xc5a92679L, 0xc1683bceL, 0xcc2b1d17L, 0xc8ea00a0L,\n   0xd6ad50a5L, 0xd26c4d12L, 0xdf2f6bcbL, 0xdbee767cL,\n   0xe3a1cbc1L, 0xe760d676L, 0xea23f0afL, 0xeee2ed18L,\n   0xf0a5bd1dL, 0xf464a0aaL, 0xf9278673L, 0xfde69bc4L,\n   0x89b8fd09L, 0x8d79e0beL, 0x803ac667L, 0x84fbdbd0L,\n   0x9abc8bd5L, 0x9e7d9662L, 0x933eb0bbL, 0x97ffad0cL,\n   0xafb010b1L, 0xab710d06L, 0xa6322bdfL, 0xa2f33668L,\n   0xbcb4666dL, 0xb8757bdaL, 0xb5365d03L, 0xb1f740b4L\n};\n\n\n/*-------------------------------------------------------------*/\n/*--- end                                        crctable.c ---*/\n/*-------------------------------------------------------------*/\n"
  },
  {
    "path": "external/bzip2/decompress.c",
    "content": "\n/*-------------------------------------------------------------*/\n/*--- Decompression machinery                               ---*/\n/*---                                          decompress.c ---*/\n/*-------------------------------------------------------------*/\n\n/* ------------------------------------------------------------------\n   This file is part of bzip2/libbzip2, a program and library for\n   lossless, block-sorting data compression.\n\n   bzip2/libbzip2 version 1.0.6 of 6 September 2010\n   Copyright (C) 1996-2010 Julian Seward <jseward@bzip.org>\n\n   Please read the WARNING, DISCLAIMER and PATENTS sections in the \n   README file.\n\n   This program is released under the terms of the license contained\n   in the file LICENSE.\n   ------------------------------------------------------------------ */\n\n\n#include \"bzlib_private.h\"\n\n\n/*---------------------------------------------------*/\nstatic\nvoid makeMaps_d ( DState* s )\n{\n   Int32 i;\n   s->nInUse = 0;\n   for (i = 0; i < 256; i++)\n      if (s->inUse[i]) {\n         s->seqToUnseq[s->nInUse] = i;\n         s->nInUse++;\n      }\n}\n\n\n/*---------------------------------------------------*/\n#define RETURN(rrr)                               \\\n   { retVal = rrr; goto save_state_and_return; };\n\n#define GET_BITS(lll,vvv,nnn)                     \\\n   case lll: s->state = lll;                      \\\n   while (True) {                                 \\\n      if (s->bsLive >= nnn) {                     \\\n         UInt32 v;                                \\\n         v = (s->bsBuff >>                        \\\n             (s->bsLive-nnn)) & ((1 << nnn)-1);   \\\n         s->bsLive -= nnn;                        \\\n         vvv = v;                                 \\\n         break;                                   \\\n      }                                           \\\n      if (s->strm->avail_in == 0) RETURN(BZ_OK);  \\\n      s->bsBuff                                   \\\n         = (s->bsBuff << 8) |                     \\\n           ((UInt32)                              \\\n              (*((UChar*)(s->strm->next_in))));   \\\n      s->bsLive += 8;                             \\\n      s->strm->next_in++;                         \\\n      s->strm->avail_in--;                        \\\n      s->strm->total_in_lo32++;                   \\\n      if (s->strm->total_in_lo32 == 0)            \\\n         s->strm->total_in_hi32++;                \\\n   }\n\n#define GET_UCHAR(lll,uuu)                        \\\n   GET_BITS(lll,uuu,8)\n\n#define GET_BIT(lll,uuu)                          \\\n   GET_BITS(lll,uuu,1)\n\n/*---------------------------------------------------*/\n#define GET_MTF_VAL(label1,label2,lval)           \\\n{                                                 \\\n   if (groupPos == 0) {                           \\\n      groupNo++;                                  \\\n      if (groupNo >= nSelectors)                  \\\n         RETURN(BZ_DATA_ERROR);                   \\\n      groupPos = BZ_G_SIZE;                       \\\n      gSel = s->selector[groupNo];                \\\n      gMinlen = s->minLens[gSel];                 \\\n      gLimit = &(s->limit[gSel][0]);              \\\n      gPerm = &(s->perm[gSel][0]);                \\\n      gBase = &(s->base[gSel][0]);                \\\n   }                                              \\\n   groupPos--;                                    \\\n   zn = gMinlen;                                  \\\n   GET_BITS(label1, zvec, zn);                    \\\n   while (1) {                                    \\\n      if (zn > 20 /* the longest code */)         \\\n         RETURN(BZ_DATA_ERROR);                   \\\n      if (zvec <= gLimit[zn]) break;              \\\n      zn++;                                       \\\n      GET_BIT(label2, zj);                        \\\n      zvec = (zvec << 1) | zj;                    \\\n   };                                             \\\n   if (zvec - gBase[zn] < 0                       \\\n       || zvec - gBase[zn] >= BZ_MAX_ALPHA_SIZE)  \\\n      RETURN(BZ_DATA_ERROR);                      \\\n   lval = gPerm[zvec - gBase[zn]];                \\\n}\n\n\n/*---------------------------------------------------*/\nInt32 BZ2_decompress ( DState* s )\n{\n   UChar      uc;\n   Int32      retVal;\n   Int32      minLen, maxLen;\n   bz_stream* strm = s->strm;\n\n   /* stuff that needs to be saved/restored */\n   Int32  i;\n   Int32  j;\n   Int32  t;\n   Int32  alphaSize;\n   Int32  nGroups;\n   Int32  nSelectors;\n   Int32  EOB;\n   Int32  groupNo;\n   Int32  groupPos;\n   Int32  nextSym;\n   Int32  nblockMAX;\n   Int32  nblock;\n   Int32  es;\n   Int32  N;\n   Int32  curr;\n   Int32  zt;\n   Int32  zn; \n   Int32  zvec;\n   Int32  zj;\n   Int32  gSel;\n   Int32  gMinlen;\n   Int32* gLimit;\n   Int32* gBase;\n   Int32* gPerm;\n\n   if (s->state == BZ_X_MAGIC_1) {\n      /*initialise the save area*/\n      s->save_i           = 0;\n      s->save_j           = 0;\n      s->save_t           = 0;\n      s->save_alphaSize   = 0;\n      s->save_nGroups     = 0;\n      s->save_nSelectors  = 0;\n      s->save_EOB         = 0;\n      s->save_groupNo     = 0;\n      s->save_groupPos    = 0;\n      s->save_nextSym     = 0;\n      s->save_nblockMAX   = 0;\n      s->save_nblock      = 0;\n      s->save_es          = 0;\n      s->save_N           = 0;\n      s->save_curr        = 0;\n      s->save_zt          = 0;\n      s->save_zn          = 0;\n      s->save_zvec        = 0;\n      s->save_zj          = 0;\n      s->save_gSel        = 0;\n      s->save_gMinlen     = 0;\n      s->save_gLimit      = NULL;\n      s->save_gBase       = NULL;\n      s->save_gPerm       = NULL;\n   }\n\n   /*restore from the save area*/\n   i           = s->save_i;\n   j           = s->save_j;\n   t           = s->save_t;\n   alphaSize   = s->save_alphaSize;\n   nGroups     = s->save_nGroups;\n   nSelectors  = s->save_nSelectors;\n   EOB         = s->save_EOB;\n   groupNo     = s->save_groupNo;\n   groupPos    = s->save_groupPos;\n   nextSym     = s->save_nextSym;\n   nblockMAX   = s->save_nblockMAX;\n   nblock      = s->save_nblock;\n   es          = s->save_es;\n   N           = s->save_N;\n   curr        = s->save_curr;\n   zt          = s->save_zt;\n   zn          = s->save_zn; \n   zvec        = s->save_zvec;\n   zj          = s->save_zj;\n   gSel        = s->save_gSel;\n   gMinlen     = s->save_gMinlen;\n   gLimit      = s->save_gLimit;\n   gBase       = s->save_gBase;\n   gPerm       = s->save_gPerm;\n\n   retVal = BZ_OK;\n\n   switch (s->state) {\n\n      GET_UCHAR(BZ_X_MAGIC_1, uc);\n      if (uc != BZ_HDR_B) RETURN(BZ_DATA_ERROR_MAGIC);\n\n      GET_UCHAR(BZ_X_MAGIC_2, uc);\n      if (uc != BZ_HDR_Z) RETURN(BZ_DATA_ERROR_MAGIC);\n\n      GET_UCHAR(BZ_X_MAGIC_3, uc)\n      if (uc != BZ_HDR_h) RETURN(BZ_DATA_ERROR_MAGIC);\n\n      GET_BITS(BZ_X_MAGIC_4, s->blockSize100k, 8)\n      if (s->blockSize100k < (BZ_HDR_0 + 1) || \n          s->blockSize100k > (BZ_HDR_0 + 9)) RETURN(BZ_DATA_ERROR_MAGIC);\n      s->blockSize100k -= BZ_HDR_0;\n\n      if (s->smallDecompress) {\n         s->ll16 = BZALLOC( s->blockSize100k * 100000 * sizeof(UInt16) );\n         s->ll4  = BZALLOC( \n                      ((1 + s->blockSize100k * 100000) >> 1) * sizeof(UChar) \n                   );\n         if (s->ll16 == NULL || s->ll4 == NULL) RETURN(BZ_MEM_ERROR);\n      } else {\n         s->tt  = BZALLOC( s->blockSize100k * 100000 * sizeof(Int32) );\n         if (s->tt == NULL) RETURN(BZ_MEM_ERROR);\n      }\n\n      GET_UCHAR(BZ_X_BLKHDR_1, uc);\n\n      if (uc == 0x17) goto endhdr_2;\n      if (uc != 0x31) RETURN(BZ_DATA_ERROR);\n      GET_UCHAR(BZ_X_BLKHDR_2, uc);\n      if (uc != 0x41) RETURN(BZ_DATA_ERROR);\n      GET_UCHAR(BZ_X_BLKHDR_3, uc);\n      if (uc != 0x59) RETURN(BZ_DATA_ERROR);\n      GET_UCHAR(BZ_X_BLKHDR_4, uc);\n      if (uc != 0x26) RETURN(BZ_DATA_ERROR);\n      GET_UCHAR(BZ_X_BLKHDR_5, uc);\n      if (uc != 0x53) RETURN(BZ_DATA_ERROR);\n      GET_UCHAR(BZ_X_BLKHDR_6, uc);\n      if (uc != 0x59) RETURN(BZ_DATA_ERROR);\n\n      s->currBlockNo++;\n      if (s->verbosity >= 2)\n         VPrintf1 ( \"\\n    [%d: huff+mtf \", s->currBlockNo );\n \n      s->storedBlockCRC = 0;\n      GET_UCHAR(BZ_X_BCRC_1, uc);\n      s->storedBlockCRC = (s->storedBlockCRC << 8) | ((UInt32)uc);\n      GET_UCHAR(BZ_X_BCRC_2, uc);\n      s->storedBlockCRC = (s->storedBlockCRC << 8) | ((UInt32)uc);\n      GET_UCHAR(BZ_X_BCRC_3, uc);\n      s->storedBlockCRC = (s->storedBlockCRC << 8) | ((UInt32)uc);\n      GET_UCHAR(BZ_X_BCRC_4, uc);\n      s->storedBlockCRC = (s->storedBlockCRC << 8) | ((UInt32)uc);\n\n      GET_BITS(BZ_X_RANDBIT, s->blockRandomised, 1);\n\n      s->origPtr = 0;\n      GET_UCHAR(BZ_X_ORIGPTR_1, uc);\n      s->origPtr = (s->origPtr << 8) | ((Int32)uc);\n      GET_UCHAR(BZ_X_ORIGPTR_2, uc);\n      s->origPtr = (s->origPtr << 8) | ((Int32)uc);\n      GET_UCHAR(BZ_X_ORIGPTR_3, uc);\n      s->origPtr = (s->origPtr << 8) | ((Int32)uc);\n\n      if (s->origPtr < 0)\n         RETURN(BZ_DATA_ERROR);\n      if (s->origPtr > 10 + 100000*s->blockSize100k) \n         RETURN(BZ_DATA_ERROR);\n\n      /*--- Receive the mapping table ---*/\n      for (i = 0; i < 16; i++) {\n         GET_BIT(BZ_X_MAPPING_1, uc);\n         if (uc == 1) \n            s->inUse16[i] = True; else \n            s->inUse16[i] = False;\n      }\n\n      for (i = 0; i < 256; i++) s->inUse[i] = False;\n\n      for (i = 0; i < 16; i++)\n         if (s->inUse16[i])\n            for (j = 0; j < 16; j++) {\n               GET_BIT(BZ_X_MAPPING_2, uc);\n               if (uc == 1) s->inUse[i * 16 + j] = True;\n            }\n      makeMaps_d ( s );\n      if (s->nInUse == 0) RETURN(BZ_DATA_ERROR);\n      alphaSize = s->nInUse+2;\n\n      /*--- Now the selectors ---*/\n      GET_BITS(BZ_X_SELECTOR_1, nGroups, 3);\n      if (nGroups < 2 || nGroups > 6) RETURN(BZ_DATA_ERROR);\n      GET_BITS(BZ_X_SELECTOR_2, nSelectors, 15);\n      if (nSelectors < 1) RETURN(BZ_DATA_ERROR);\n      for (i = 0; i < nSelectors; i++) {\n         j = 0;\n         while (True) {\n            GET_BIT(BZ_X_SELECTOR_3, uc);\n            if (uc == 0) break;\n            j++;\n            if (j >= nGroups) RETURN(BZ_DATA_ERROR);\n         }\n         s->selectorMtf[i] = j;\n      }\n\n      /*--- Undo the MTF values for the selectors. ---*/\n      {\n         UChar pos[BZ_N_GROUPS], tmp, v;\n         for (v = 0; v < nGroups; v++) pos[v] = v;\n   \n         for (i = 0; i < nSelectors; i++) {\n            v = s->selectorMtf[i];\n            tmp = pos[v];\n            while (v > 0) { pos[v] = pos[v-1]; v--; }\n            pos[0] = tmp;\n            s->selector[i] = tmp;\n         }\n      }\n\n      /*--- Now the coding tables ---*/\n      for (t = 0; t < nGroups; t++) {\n         GET_BITS(BZ_X_CODING_1, curr, 5);\n         for (i = 0; i < alphaSize; i++) {\n            while (True) {\n               if (curr < 1 || curr > 20) RETURN(BZ_DATA_ERROR);\n               GET_BIT(BZ_X_CODING_2, uc);\n               if (uc == 0) break;\n               GET_BIT(BZ_X_CODING_3, uc);\n               if (uc == 0) curr++; else curr--;\n            }\n            s->len[t][i] = curr;\n         }\n      }\n\n      /*--- Create the Huffman decoding tables ---*/\n      for (t = 0; t < nGroups; t++) {\n         minLen = 32;\n         maxLen = 0;\n         for (i = 0; i < alphaSize; i++) {\n            if (s->len[t][i] > maxLen) maxLen = s->len[t][i];\n            if (s->len[t][i] < minLen) minLen = s->len[t][i];\n         }\n         BZ2_hbCreateDecodeTables ( \n            &(s->limit[t][0]), \n            &(s->base[t][0]), \n            &(s->perm[t][0]), \n            &(s->len[t][0]),\n            minLen, maxLen, alphaSize\n         );\n         s->minLens[t] = minLen;\n      }\n\n      /*--- Now the MTF values ---*/\n\n      EOB      = s->nInUse+1;\n      nblockMAX = 100000 * s->blockSize100k;\n      groupNo  = -1;\n      groupPos = 0;\n\n      for (i = 0; i <= 255; i++) s->unzftab[i] = 0;\n\n      /*-- MTF init --*/\n      {\n         Int32 ii, jj, kk;\n         kk = MTFA_SIZE-1;\n         for (ii = 256 / MTFL_SIZE - 1; ii >= 0; ii--) {\n            for (jj = MTFL_SIZE-1; jj >= 0; jj--) {\n               s->mtfa[kk] = (UChar)(ii * MTFL_SIZE + jj);\n               kk--;\n            }\n            s->mtfbase[ii] = kk + 1;\n         }\n      }\n      /*-- end MTF init --*/\n\n      nblock = 0;\n      GET_MTF_VAL(BZ_X_MTF_1, BZ_X_MTF_2, nextSym);\n\n      while (True) {\n\n         if (nextSym == EOB) break;\n\n         if (nextSym == BZ_RUNA || nextSym == BZ_RUNB) {\n\n            es = -1;\n            N = 1;\n            do {\n               /* Check that N doesn't get too big, so that es doesn't\n                  go negative.  The maximum value that can be\n                  RUNA/RUNB encoded is equal to the block size (post\n                  the initial RLE), viz, 900k, so bounding N at 2\n                  million should guard against overflow without\n                  rejecting any legitimate inputs. */\n               if (N >= 2*1024*1024) RETURN(BZ_DATA_ERROR);\n               if (nextSym == BZ_RUNA) es = es + (0+1) * N; else\n               if (nextSym == BZ_RUNB) es = es + (1+1) * N;\n               N = N * 2;\n               GET_MTF_VAL(BZ_X_MTF_3, BZ_X_MTF_4, nextSym);\n            }\n               while (nextSym == BZ_RUNA || nextSym == BZ_RUNB);\n\n            es++;\n            uc = s->seqToUnseq[ s->mtfa[s->mtfbase[0]] ];\n            s->unzftab[uc] += es;\n\n            if (s->smallDecompress)\n               while (es > 0) {\n                  if (nblock >= nblockMAX) RETURN(BZ_DATA_ERROR);\n                  s->ll16[nblock] = (UInt16)uc;\n                  nblock++;\n                  es--;\n               }\n            else\n               while (es > 0) {\n                  if (nblock >= nblockMAX) RETURN(BZ_DATA_ERROR);\n                  s->tt[nblock] = (UInt32)uc;\n                  nblock++;\n                  es--;\n               };\n\n            continue;\n\n         } else {\n\n            if (nblock >= nblockMAX) RETURN(BZ_DATA_ERROR);\n\n            /*-- uc = MTF ( nextSym-1 ) --*/\n            {\n               Int32 ii, jj, kk, pp, lno, off;\n               UInt32 nn;\n               nn = (UInt32)(nextSym - 1);\n\n               if (nn < MTFL_SIZE) {\n                  /* avoid general-case expense */\n                  pp = s->mtfbase[0];\n                  uc = s->mtfa[pp+nn];\n                  while (nn > 3) {\n                     Int32 z = pp+nn;\n                     s->mtfa[(z)  ] = s->mtfa[(z)-1];\n                     s->mtfa[(z)-1] = s->mtfa[(z)-2];\n                     s->mtfa[(z)-2] = s->mtfa[(z)-3];\n                     s->mtfa[(z)-3] = s->mtfa[(z)-4];\n                     nn -= 4;\n                  }\n                  while (nn > 0) { \n                     s->mtfa[(pp+nn)] = s->mtfa[(pp+nn)-1]; nn--; \n                  };\n                  s->mtfa[pp] = uc;\n               } else { \n                  /* general case */\n                  lno = nn / MTFL_SIZE;\n                  off = nn % MTFL_SIZE;\n                  pp = s->mtfbase[lno] + off;\n                  uc = s->mtfa[pp];\n                  while (pp > s->mtfbase[lno]) { \n                     s->mtfa[pp] = s->mtfa[pp-1]; pp--; \n                  };\n                  s->mtfbase[lno]++;\n                  while (lno > 0) {\n                     s->mtfbase[lno]--;\n                     s->mtfa[s->mtfbase[lno]] \n                        = s->mtfa[s->mtfbase[lno-1] + MTFL_SIZE - 1];\n                     lno--;\n                  }\n                  s->mtfbase[0]--;\n                  s->mtfa[s->mtfbase[0]] = uc;\n                  if (s->mtfbase[0] == 0) {\n                     kk = MTFA_SIZE-1;\n                     for (ii = 256 / MTFL_SIZE-1; ii >= 0; ii--) {\n                        for (jj = MTFL_SIZE-1; jj >= 0; jj--) {\n                           s->mtfa[kk] = s->mtfa[s->mtfbase[ii] + jj];\n                           kk--;\n                        }\n                        s->mtfbase[ii] = kk + 1;\n                     }\n                  }\n               }\n            }\n            /*-- end uc = MTF ( nextSym-1 ) --*/\n\n            s->unzftab[s->seqToUnseq[uc]]++;\n            if (s->smallDecompress)\n               s->ll16[nblock] = (UInt16)(s->seqToUnseq[uc]); else\n               s->tt[nblock]   = (UInt32)(s->seqToUnseq[uc]);\n            nblock++;\n\n            GET_MTF_VAL(BZ_X_MTF_5, BZ_X_MTF_6, nextSym);\n            continue;\n         }\n      }\n\n      /* Now we know what nblock is, we can do a better sanity\n         check on s->origPtr.\n      */\n      if (s->origPtr < 0 || s->origPtr >= nblock)\n         RETURN(BZ_DATA_ERROR);\n\n      /*-- Set up cftab to facilitate generation of T^(-1) --*/\n      /* Check: unzftab entries in range. */\n      for (i = 0; i <= 255; i++) {\n         if (s->unzftab[i] < 0 || s->unzftab[i] > nblock)\n            RETURN(BZ_DATA_ERROR);\n      }\n      /* Actually generate cftab. */\n      s->cftab[0] = 0;\n      for (i = 1; i <= 256; i++) s->cftab[i] = s->unzftab[i-1];\n      for (i = 1; i <= 256; i++) s->cftab[i] += s->cftab[i-1];\n      /* Check: cftab entries in range. */\n      for (i = 0; i <= 256; i++) {\n         if (s->cftab[i] < 0 || s->cftab[i] > nblock) {\n            /* s->cftab[i] can legitimately be == nblock */\n            RETURN(BZ_DATA_ERROR);\n         }\n      }\n      /* Check: cftab entries non-descending. */\n      for (i = 1; i <= 256; i++) {\n         if (s->cftab[i-1] > s->cftab[i]) {\n            RETURN(BZ_DATA_ERROR);\n         }\n      }\n\n      s->state_out_len = 0;\n      s->state_out_ch  = 0;\n      BZ_INITIALISE_CRC ( s->calculatedBlockCRC );\n      s->state = BZ_X_OUTPUT;\n      if (s->verbosity >= 2) VPrintf0 ( \"rt+rld\" );\n\n      if (s->smallDecompress) {\n\n         /*-- Make a copy of cftab, used in generation of T --*/\n         for (i = 0; i <= 256; i++) s->cftabCopy[i] = s->cftab[i];\n\n         /*-- compute the T vector --*/\n         for (i = 0; i < nblock; i++) {\n            uc = (UChar)(s->ll16[i]);\n            SET_LL(i, s->cftabCopy[uc]);\n            s->cftabCopy[uc]++;\n         }\n\n         /*-- Compute T^(-1) by pointer reversal on T --*/\n         i = s->origPtr;\n         j = GET_LL(i);\n         do {\n            Int32 tmp = GET_LL(j);\n            SET_LL(j, i);\n            i = j;\n            j = tmp;\n         }\n            while (i != s->origPtr);\n\n         s->tPos = s->origPtr;\n         s->nblock_used = 0;\n         if (s->blockRandomised) {\n            BZ_RAND_INIT_MASK;\n            BZ_GET_SMALL(s->k0); s->nblock_used++;\n            BZ_RAND_UPD_MASK; s->k0 ^= BZ_RAND_MASK; \n         } else {\n            BZ_GET_SMALL(s->k0); s->nblock_used++;\n         }\n\n      } else {\n\n         /*-- compute the T^(-1) vector --*/\n         for (i = 0; i < nblock; i++) {\n            uc = (UChar)(s->tt[i] & 0xff);\n            s->tt[s->cftab[uc]] |= (i << 8);\n            s->cftab[uc]++;\n         }\n\n         s->tPos = s->tt[s->origPtr] >> 8;\n         s->nblock_used = 0;\n         if (s->blockRandomised) {\n            BZ_RAND_INIT_MASK;\n            BZ_GET_FAST(s->k0); s->nblock_used++;\n            BZ_RAND_UPD_MASK; s->k0 ^= BZ_RAND_MASK; \n         } else {\n            BZ_GET_FAST(s->k0); s->nblock_used++;\n         }\n\n      }\n\n      RETURN(BZ_OK);\n\n\n\n    endhdr_2:\n\n      GET_UCHAR(BZ_X_ENDHDR_2, uc);\n      if (uc != 0x72) RETURN(BZ_DATA_ERROR);\n      GET_UCHAR(BZ_X_ENDHDR_3, uc);\n      if (uc != 0x45) RETURN(BZ_DATA_ERROR);\n      GET_UCHAR(BZ_X_ENDHDR_4, uc);\n      if (uc != 0x38) RETURN(BZ_DATA_ERROR);\n      GET_UCHAR(BZ_X_ENDHDR_5, uc);\n      if (uc != 0x50) RETURN(BZ_DATA_ERROR);\n      GET_UCHAR(BZ_X_ENDHDR_6, uc);\n      if (uc != 0x90) RETURN(BZ_DATA_ERROR);\n\n      s->storedCombinedCRC = 0;\n      GET_UCHAR(BZ_X_CCRC_1, uc);\n      s->storedCombinedCRC = (s->storedCombinedCRC << 8) | ((UInt32)uc);\n      GET_UCHAR(BZ_X_CCRC_2, uc);\n      s->storedCombinedCRC = (s->storedCombinedCRC << 8) | ((UInt32)uc);\n      GET_UCHAR(BZ_X_CCRC_3, uc);\n      s->storedCombinedCRC = (s->storedCombinedCRC << 8) | ((UInt32)uc);\n      GET_UCHAR(BZ_X_CCRC_4, uc);\n      s->storedCombinedCRC = (s->storedCombinedCRC << 8) | ((UInt32)uc);\n\n      s->state = BZ_X_IDLE;\n      RETURN(BZ_STREAM_END);\n\n      default: AssertH ( False, 4001 );\n   }\n\n   AssertH ( False, 4002 );\n\n   save_state_and_return:\n\n   s->save_i           = i;\n   s->save_j           = j;\n   s->save_t           = t;\n   s->save_alphaSize   = alphaSize;\n   s->save_nGroups     = nGroups;\n   s->save_nSelectors  = nSelectors;\n   s->save_EOB         = EOB;\n   s->save_groupNo     = groupNo;\n   s->save_groupPos    = groupPos;\n   s->save_nextSym     = nextSym;\n   s->save_nblockMAX   = nblockMAX;\n   s->save_nblock      = nblock;\n   s->save_es          = es;\n   s->save_N           = N;\n   s->save_curr        = curr;\n   s->save_zt          = zt;\n   s->save_zn          = zn;\n   s->save_zvec        = zvec;\n   s->save_zj          = zj;\n   s->save_gSel        = gSel;\n   s->save_gMinlen     = gMinlen;\n   s->save_gLimit      = gLimit;\n   s->save_gBase       = gBase;\n   s->save_gPerm       = gPerm;\n\n   return retVal;   \n}\n\n\n/*-------------------------------------------------------------*/\n/*--- end                                      decompress.c ---*/\n/*-------------------------------------------------------------*/\n"
  },
  {
    "path": "external/bzip2/huffman.c",
    "content": "\n/*-------------------------------------------------------------*/\n/*--- Huffman coding low-level stuff                        ---*/\n/*---                                             huffman.c ---*/\n/*-------------------------------------------------------------*/\n\n/* ------------------------------------------------------------------\n   This file is part of bzip2/libbzip2, a program and library for\n   lossless, block-sorting data compression.\n\n   bzip2/libbzip2 version 1.0.6 of 6 September 2010\n   Copyright (C) 1996-2010 Julian Seward <jseward@bzip.org>\n\n   Please read the WARNING, DISCLAIMER and PATENTS sections in the \n   README file.\n\n   This program is released under the terms of the license contained\n   in the file LICENSE.\n   ------------------------------------------------------------------ */\n\n\n#include \"bzlib_private.h\"\n\n/*---------------------------------------------------*/\n#define WEIGHTOF(zz0)  ((zz0) & 0xffffff00)\n#define DEPTHOF(zz1)   ((zz1) & 0x000000ff)\n#define MYMAX(zz2,zz3) ((zz2) > (zz3) ? (zz2) : (zz3))\n\n#define ADDWEIGHTS(zw1,zw2)                           \\\n   (WEIGHTOF(zw1)+WEIGHTOF(zw2)) |                    \\\n   (1 + MYMAX(DEPTHOF(zw1),DEPTHOF(zw2)))\n\n#define UPHEAP(z)                                     \\\n{                                                     \\\n   Int32 zz, tmp;                                     \\\n   zz = z; tmp = heap[zz];                            \\\n   while (weight[tmp] < weight[heap[zz >> 1]]) {      \\\n      heap[zz] = heap[zz >> 1];                       \\\n      zz >>= 1;                                       \\\n   }                                                  \\\n   heap[zz] = tmp;                                    \\\n}\n\n#define DOWNHEAP(z)                                   \\\n{                                                     \\\n   Int32 zz, yy, tmp;                                 \\\n   zz = z; tmp = heap[zz];                            \\\n   while (True) {                                     \\\n      yy = zz << 1;                                   \\\n      if (yy > nHeap) break;                          \\\n      if (yy < nHeap &&                               \\\n          weight[heap[yy+1]] < weight[heap[yy]])      \\\n         yy++;                                        \\\n      if (weight[tmp] < weight[heap[yy]]) break;      \\\n      heap[zz] = heap[yy];                            \\\n      zz = yy;                                        \\\n   }                                                  \\\n   heap[zz] = tmp;                                    \\\n}\n\n\n/*---------------------------------------------------*/\nvoid BZ2_hbMakeCodeLengths ( UChar *len, \n                             Int32 *freq,\n                             Int32 alphaSize,\n                             Int32 maxLen )\n{\n   /*--\n      Nodes and heap entries run from 1.  Entry 0\n      for both the heap and nodes is a sentinel.\n   --*/\n   Int32 nNodes, nHeap, n1, n2, i, j, k;\n   Bool  tooLong;\n\n   Int32 heap   [ BZ_MAX_ALPHA_SIZE + 2 ];\n   Int32 weight [ BZ_MAX_ALPHA_SIZE * 2 ];\n   Int32 parent [ BZ_MAX_ALPHA_SIZE * 2 ]; \n\n   for (i = 0; i < alphaSize; i++)\n      weight[i+1] = (freq[i] == 0 ? 1 : freq[i]) << 8;\n\n   while (True) {\n\n      nNodes = alphaSize;\n      nHeap = 0;\n\n      heap[0] = 0;\n      weight[0] = 0;\n      parent[0] = -2;\n\n      for (i = 1; i <= alphaSize; i++) {\n         parent[i] = -1;\n         nHeap++;\n         heap[nHeap] = i;\n         UPHEAP(nHeap);\n      }\n\n      AssertH( nHeap < (BZ_MAX_ALPHA_SIZE+2), 2001 );\n   \n      while (nHeap > 1) {\n         n1 = heap[1]; heap[1] = heap[nHeap]; nHeap--; DOWNHEAP(1);\n         n2 = heap[1]; heap[1] = heap[nHeap]; nHeap--; DOWNHEAP(1);\n         nNodes++;\n         parent[n1] = parent[n2] = nNodes;\n         weight[nNodes] = ADDWEIGHTS(weight[n1], weight[n2]);\n         parent[nNodes] = -1;\n         nHeap++;\n         heap[nHeap] = nNodes;\n         UPHEAP(nHeap);\n      }\n\n      AssertH( nNodes < (BZ_MAX_ALPHA_SIZE * 2), 2002 );\n\n      tooLong = False;\n      for (i = 1; i <= alphaSize; i++) {\n         j = 0;\n         k = i;\n         while (parent[k] >= 0) { k = parent[k]; j++; }\n         len[i-1] = j;\n         if (j > maxLen) tooLong = True;\n      }\n      \n      if (! tooLong) break;\n\n      /* 17 Oct 04: keep-going condition for the following loop used\n         to be 'i < alphaSize', which missed the last element,\n         theoretically leading to the possibility of the compressor\n         looping.  However, this count-scaling step is only needed if\n         one of the generated Huffman code words is longer than\n         maxLen, which up to and including version 1.0.2 was 20 bits,\n         which is extremely unlikely.  In version 1.0.3 maxLen was\n         changed to 17 bits, which has minimal effect on compression\n         ratio, but does mean this scaling step is used from time to\n         time, enough to verify that it works.\n\n         This means that bzip2-1.0.3 and later will only produce\n         Huffman codes with a maximum length of 17 bits.  However, in\n         order to preserve backwards compatibility with bitstreams\n         produced by versions pre-1.0.3, the decompressor must still\n         handle lengths of up to 20. */\n\n      for (i = 1; i <= alphaSize; i++) {\n         j = weight[i] >> 8;\n         j = 1 + (j / 2);\n         weight[i] = j << 8;\n      }\n   }\n}\n\n\n/*---------------------------------------------------*/\nvoid BZ2_hbAssignCodes ( Int32 *code,\n                         UChar *length,\n                         Int32 minLen,\n                         Int32 maxLen,\n                         Int32 alphaSize )\n{\n   Int32 n, vec, i;\n\n   vec = 0;\n   for (n = minLen; n <= maxLen; n++) {\n      for (i = 0; i < alphaSize; i++)\n         if (length[i] == n) { code[i] = vec; vec++; };\n      vec <<= 1;\n   }\n}\n\n\n/*---------------------------------------------------*/\nvoid BZ2_hbCreateDecodeTables ( Int32 *limit,\n                                Int32 *base,\n                                Int32 *perm,\n                                UChar *length,\n                                Int32 minLen,\n                                Int32 maxLen,\n                                Int32 alphaSize )\n{\n   Int32 pp, i, j, vec;\n\n   pp = 0;\n   for (i = minLen; i <= maxLen; i++)\n      for (j = 0; j < alphaSize; j++)\n         if (length[j] == i) { perm[pp] = j; pp++; };\n\n   for (i = 0; i < BZ_MAX_CODE_LEN; i++) base[i] = 0;\n   for (i = 0; i < alphaSize; i++) base[length[i]+1]++;\n\n   for (i = 1; i < BZ_MAX_CODE_LEN; i++) base[i] += base[i-1];\n\n   for (i = 0; i < BZ_MAX_CODE_LEN; i++) limit[i] = 0;\n   vec = 0;\n\n   for (i = minLen; i <= maxLen; i++) {\n      vec += (base[i+1] - base[i]);\n      limit[i] = vec-1;\n      vec <<= 1;\n   }\n   for (i = minLen + 1; i <= maxLen; i++)\n      base[i] = ((limit[i-1] + 1) << 1) - base[i];\n}\n\n\n/*-------------------------------------------------------------*/\n/*--- end                                         huffman.c ---*/\n/*-------------------------------------------------------------*/\n"
  },
  {
    "path": "external/bzip2/randtable.c",
    "content": "\n/*-------------------------------------------------------------*/\n/*--- Table for randomising repetitive blocks               ---*/\n/*---                                           randtable.c ---*/\n/*-------------------------------------------------------------*/\n\n/* ------------------------------------------------------------------\n   This file is part of bzip2/libbzip2, a program and library for\n   lossless, block-sorting data compression.\n\n   bzip2/libbzip2 version 1.0.6 of 6 September 2010\n   Copyright (C) 1996-2010 Julian Seward <jseward@bzip.org>\n\n   Please read the WARNING, DISCLAIMER and PATENTS sections in the \n   README file.\n\n   This program is released under the terms of the license contained\n   in the file LICENSE.\n   ------------------------------------------------------------------ */\n\n\n#include \"bzlib_private.h\"\n\n\n/*---------------------------------------------*/\nInt32 BZ2_rNums[512] = { \n   619, 720, 127, 481, 931, 816, 813, 233, 566, 247, \n   985, 724, 205, 454, 863, 491, 741, 242, 949, 214, \n   733, 859, 335, 708, 621, 574, 73, 654, 730, 472, \n   419, 436, 278, 496, 867, 210, 399, 680, 480, 51, \n   878, 465, 811, 169, 869, 675, 611, 697, 867, 561, \n   862, 687, 507, 283, 482, 129, 807, 591, 733, 623, \n   150, 238, 59, 379, 684, 877, 625, 169, 643, 105, \n   170, 607, 520, 932, 727, 476, 693, 425, 174, 647, \n   73, 122, 335, 530, 442, 853, 695, 249, 445, 515, \n   909, 545, 703, 919, 874, 474, 882, 500, 594, 612, \n   641, 801, 220, 162, 819, 984, 589, 513, 495, 799, \n   161, 604, 958, 533, 221, 400, 386, 867, 600, 782, \n   382, 596, 414, 171, 516, 375, 682, 485, 911, 276, \n   98, 553, 163, 354, 666, 933, 424, 341, 533, 870, \n   227, 730, 475, 186, 263, 647, 537, 686, 600, 224, \n   469, 68, 770, 919, 190, 373, 294, 822, 808, 206, \n   184, 943, 795, 384, 383, 461, 404, 758, 839, 887, \n   715, 67, 618, 276, 204, 918, 873, 777, 604, 560, \n   951, 160, 578, 722, 79, 804, 96, 409, 713, 940, \n   652, 934, 970, 447, 318, 353, 859, 672, 112, 785, \n   645, 863, 803, 350, 139, 93, 354, 99, 820, 908, \n   609, 772, 154, 274, 580, 184, 79, 626, 630, 742, \n   653, 282, 762, 623, 680, 81, 927, 626, 789, 125, \n   411, 521, 938, 300, 821, 78, 343, 175, 128, 250, \n   170, 774, 972, 275, 999, 639, 495, 78, 352, 126, \n   857, 956, 358, 619, 580, 124, 737, 594, 701, 612, \n   669, 112, 134, 694, 363, 992, 809, 743, 168, 974, \n   944, 375, 748, 52, 600, 747, 642, 182, 862, 81, \n   344, 805, 988, 739, 511, 655, 814, 334, 249, 515, \n   897, 955, 664, 981, 649, 113, 974, 459, 893, 228, \n   433, 837, 553, 268, 926, 240, 102, 654, 459, 51, \n   686, 754, 806, 760, 493, 403, 415, 394, 687, 700, \n   946, 670, 656, 610, 738, 392, 760, 799, 887, 653, \n   978, 321, 576, 617, 626, 502, 894, 679, 243, 440, \n   680, 879, 194, 572, 640, 724, 926, 56, 204, 700, \n   707, 151, 457, 449, 797, 195, 791, 558, 945, 679, \n   297, 59, 87, 824, 713, 663, 412, 693, 342, 606, \n   134, 108, 571, 364, 631, 212, 174, 643, 304, 329, \n   343, 97, 430, 751, 497, 314, 983, 374, 822, 928, \n   140, 206, 73, 263, 980, 736, 876, 478, 430, 305, \n   170, 514, 364, 692, 829, 82, 855, 953, 676, 246, \n   369, 970, 294, 750, 807, 827, 150, 790, 288, 923, \n   804, 378, 215, 828, 592, 281, 565, 555, 710, 82, \n   896, 831, 547, 261, 524, 462, 293, 465, 502, 56, \n   661, 821, 976, 991, 658, 869, 905, 758, 745, 193, \n   768, 550, 608, 933, 378, 286, 215, 979, 792, 961, \n   61, 688, 793, 644, 986, 403, 106, 366, 905, 644, \n   372, 567, 466, 434, 645, 210, 389, 550, 919, 135, \n   780, 773, 635, 389, 707, 100, 626, 958, 165, 504, \n   920, 176, 193, 713, 857, 265, 203, 50, 668, 108, \n   645, 990, 626, 197, 510, 357, 358, 850, 858, 364, \n   936, 638\n};\n\n\n/*-------------------------------------------------------------*/\n/*--- end                                       randtable.c ---*/\n/*-------------------------------------------------------------*/\n"
  },
  {
    "path": "external/libfdt/fdt.c",
    "content": "// SPDX-License-Identifier: (GPL-2.0-or-later OR BSD-2-Clause)\n/*\n * libfdt - Flat Device Tree manipulation\n * Copyright (C) 2006 David Gibson, IBM Corporation.\n */\n#include \"libfdt_env.h\"\n\n#include <fdt.h>\n#include <libfdt.h>\n\n#include \"libfdt_internal.h\"\n\n/*\n * Minimal sanity check for a read-only tree. fdt_ro_probe_() checks\n * that the given buffer contains what appears to be a flattened\n * device tree with sane information in its header.\n */\nint32_t fdt_ro_probe_(const void *fdt)\n{\n\tuint32_t totalsize = fdt_totalsize(fdt);\n\n\tif (can_assume(VALID_DTB))\n\t\treturn totalsize;\n\n\t/* The device tree must be at an 8-byte aligned address */\n\tif ((uintptr_t)fdt & 7)\n\t\treturn -FDT_ERR_ALIGNMENT;\n\n\tif (fdt_magic(fdt) == FDT_MAGIC) {\n\t\t/* Complete tree */\n\t\tif (!can_assume(LATEST)) {\n\t\t\tif (fdt_version(fdt) < FDT_FIRST_SUPPORTED_VERSION)\n\t\t\t\treturn -FDT_ERR_BADVERSION;\n\t\t\tif (fdt_last_comp_version(fdt) >\n\t\t\t\t\tFDT_LAST_SUPPORTED_VERSION)\n\t\t\t\treturn -FDT_ERR_BADVERSION;\n\t\t}\n\t} else if (fdt_magic(fdt) == FDT_SW_MAGIC) {\n\t\t/* Unfinished sequential-write blob */\n\t\tif (!can_assume(VALID_INPUT) && fdt_size_dt_struct(fdt) == 0)\n\t\t\treturn -FDT_ERR_BADSTATE;\n\t} else {\n\t\treturn -FDT_ERR_BADMAGIC;\n\t}\n\n\tif (totalsize < INT32_MAX)\n\t\treturn totalsize;\n\telse\n\t\treturn -FDT_ERR_TRUNCATED;\n}\n\nstatic int check_off_(uint32_t hdrsize, uint32_t totalsize, uint32_t off)\n{\n\treturn (off >= hdrsize) && (off <= totalsize);\n}\n\nstatic int check_block_(uint32_t hdrsize, uint32_t totalsize,\n\t\t\tuint32_t base, uint32_t size)\n{\n\tif (!check_off_(hdrsize, totalsize, base))\n\t\treturn 0; /* block start out of bounds */\n\tif ((base + size) < base)\n\t\treturn 0; /* overflow */\n\tif (!check_off_(hdrsize, totalsize, base + size))\n\t\treturn 0; /* block end out of bounds */\n\treturn 1;\n}\n\nsize_t fdt_header_size_(uint32_t version)\n{\n\tif (version <= 1)\n\t\treturn FDT_V1_SIZE;\n\telse if (version <= 2)\n\t\treturn FDT_V2_SIZE;\n\telse if (version <= 3)\n\t\treturn FDT_V3_SIZE;\n\telse if (version <= 16)\n\t\treturn FDT_V16_SIZE;\n\telse\n\t\treturn FDT_V17_SIZE;\n}\n\nsize_t fdt_header_size(const void *fdt)\n{\n\treturn can_assume(LATEST) ? FDT_V17_SIZE :\n\t\tfdt_header_size_(fdt_version(fdt));\n}\n\nint fdt_check_header(const void *fdt)\n{\n\tsize_t hdrsize;\n\n\t/* The device tree must be at an 8-byte aligned address */\n\tif ((uintptr_t)fdt & 7)\n\t\treturn -FDT_ERR_ALIGNMENT;\n\n\tif (fdt_magic(fdt) != FDT_MAGIC)\n\t\treturn -FDT_ERR_BADMAGIC;\n\tif (!can_assume(LATEST)) {\n\t\tif ((fdt_version(fdt) < FDT_FIRST_SUPPORTED_VERSION)\n\t\t    || (fdt_last_comp_version(fdt) >\n\t\t\tFDT_LAST_SUPPORTED_VERSION))\n\t\t\treturn -FDT_ERR_BADVERSION;\n\t\tif (fdt_version(fdt) < fdt_last_comp_version(fdt))\n\t\t\treturn -FDT_ERR_BADVERSION;\n\t}\n\thdrsize = fdt_header_size(fdt);\n\tif (!can_assume(VALID_DTB)) {\n\n\t\tif ((fdt_totalsize(fdt) < hdrsize)\n\t\t    || (fdt_totalsize(fdt) > INT_MAX))\n\t\t\treturn -FDT_ERR_TRUNCATED;\n\n\t\t/* Bounds check memrsv block */\n\t\tif (!check_off_(hdrsize, fdt_totalsize(fdt),\n\t\t\t\tfdt_off_mem_rsvmap(fdt)))\n\t\t\treturn -FDT_ERR_TRUNCATED;\n\t}\n\n\tif (!can_assume(VALID_DTB)) {\n\t\t/* Bounds check structure block */\n\t\tif (!can_assume(LATEST) && fdt_version(fdt) < 17) {\n\t\t\tif (!check_off_(hdrsize, fdt_totalsize(fdt),\n\t\t\t\t\tfdt_off_dt_struct(fdt)))\n\t\t\t\treturn -FDT_ERR_TRUNCATED;\n\t\t} else {\n\t\t\tif (!check_block_(hdrsize, fdt_totalsize(fdt),\n\t\t\t\t\t  fdt_off_dt_struct(fdt),\n\t\t\t\t\t  fdt_size_dt_struct(fdt)))\n\t\t\t\treturn -FDT_ERR_TRUNCATED;\n\t\t}\n\n\t\t/* Bounds check strings block */\n\t\tif (!check_block_(hdrsize, fdt_totalsize(fdt),\n\t\t\t\t  fdt_off_dt_strings(fdt),\n\t\t\t\t  fdt_size_dt_strings(fdt)))\n\t\t\treturn -FDT_ERR_TRUNCATED;\n\t}\n\n\treturn 0;\n}\n\nconst void *fdt_offset_ptr(const void *fdt, int offset, unsigned int len)\n{\n\tunsigned int uoffset = offset;\n\tunsigned int absoffset = offset + fdt_off_dt_struct(fdt);\n\n\tif (offset < 0)\n\t\treturn NULL;\n\n\tif (!can_assume(VALID_INPUT))\n\t\tif ((absoffset < uoffset)\n\t\t    || ((absoffset + len) < absoffset)\n\t\t    || (absoffset + len) > fdt_totalsize(fdt))\n\t\t\treturn NULL;\n\n\tif (can_assume(LATEST) || fdt_version(fdt) >= 0x11)\n\t\tif (((uoffset + len) < uoffset)\n\t\t    || ((offset + len) > fdt_size_dt_struct(fdt)))\n\t\t\treturn NULL;\n\n\treturn fdt_offset_ptr_(fdt, offset);\n}\n\nuint32_t fdt_next_tag(const void *fdt, int startoffset, int *nextoffset)\n{\n\tconst fdt32_t *tagp, *lenp;\n\tuint32_t tag;\n\tint offset = startoffset;\n\tconst char *p;\n\n\t*nextoffset = -FDT_ERR_TRUNCATED;\n\ttagp = fdt_offset_ptr(fdt, offset, FDT_TAGSIZE);\n\tif (!can_assume(VALID_DTB) && !tagp)\n\t\treturn FDT_END; /* premature end */\n\ttag = fdt32_to_cpu(*tagp);\n\toffset += FDT_TAGSIZE;\n\n\t*nextoffset = -FDT_ERR_BADSTRUCTURE;\n\tswitch (tag) {\n\tcase FDT_BEGIN_NODE:\n\t\t/* skip name */\n\t\tdo {\n\t\t\tp = fdt_offset_ptr(fdt, offset++, 1);\n\t\t} while (p && (*p != '\\0'));\n\t\tif (!can_assume(VALID_DTB) && !p)\n\t\t\treturn FDT_END; /* premature end */\n\t\tbreak;\n\n\tcase FDT_PROP:\n\t\tlenp = fdt_offset_ptr(fdt, offset, sizeof(*lenp));\n\t\tif (!can_assume(VALID_DTB) && !lenp)\n\t\t\treturn FDT_END; /* premature end */\n\t\t/* skip-name offset, length and value */\n\t\toffset += sizeof(struct fdt_property) - FDT_TAGSIZE\n\t\t\t+ fdt32_to_cpu(*lenp);\n\t\tif (!can_assume(LATEST) &&\n\t\t    fdt_version(fdt) < 0x10 && fdt32_to_cpu(*lenp) >= 8 &&\n\t\t    ((offset - fdt32_to_cpu(*lenp)) % 8) != 0)\n\t\t\toffset += 4;\n\t\tbreak;\n\n\tcase FDT_END:\n\tcase FDT_END_NODE:\n\tcase FDT_NOP:\n\t\tbreak;\n\n\tdefault:\n\t\treturn FDT_END;\n\t}\n\n\tif (!fdt_offset_ptr(fdt, startoffset, offset - startoffset))\n\t\treturn FDT_END; /* premature end */\n\n\t*nextoffset = FDT_TAGALIGN(offset);\n\treturn tag;\n}\n\nint fdt_check_node_offset_(const void *fdt, int offset)\n{\n\tif (!can_assume(VALID_INPUT)\n\t    && ((offset < 0) || (offset % FDT_TAGSIZE)))\n\t\treturn -FDT_ERR_BADOFFSET;\n\n\tif (fdt_next_tag(fdt, offset, &offset) != FDT_BEGIN_NODE)\n\t\treturn -FDT_ERR_BADOFFSET;\n\n\treturn offset;\n}\n\nint fdt_check_prop_offset_(const void *fdt, int offset)\n{\n\tif (!can_assume(VALID_INPUT)\n\t    && ((offset < 0) || (offset % FDT_TAGSIZE)))\n\t\treturn -FDT_ERR_BADOFFSET;\n\n\tif (fdt_next_tag(fdt, offset, &offset) != FDT_PROP)\n\t\treturn -FDT_ERR_BADOFFSET;\n\n\treturn offset;\n}\n\nint fdt_next_node(const void *fdt, int offset, int *depth)\n{\n\tint nextoffset = 0;\n\tuint32_t tag;\n\n\tif (offset >= 0)\n\t\tif ((nextoffset = fdt_check_node_offset_(fdt, offset)) < 0)\n\t\t\treturn nextoffset;\n\n\tdo {\n\t\toffset = nextoffset;\n\t\ttag = fdt_next_tag(fdt, offset, &nextoffset);\n\n\t\tswitch (tag) {\n\t\tcase FDT_PROP:\n\t\tcase FDT_NOP:\n\t\t\tbreak;\n\n\t\tcase FDT_BEGIN_NODE:\n\t\t\tif (depth)\n\t\t\t\t(*depth)++;\n\t\t\tbreak;\n\n\t\tcase FDT_END_NODE:\n\t\t\tif (depth && ((--(*depth)) < 0))\n\t\t\t\treturn nextoffset;\n\t\t\tbreak;\n\n\t\tcase FDT_END:\n\t\t\tif ((nextoffset >= 0)\n\t\t\t    || ((nextoffset == -FDT_ERR_TRUNCATED) && !depth))\n\t\t\t\treturn -FDT_ERR_NOTFOUND;\n\t\t\telse\n\t\t\t\treturn nextoffset;\n\t\t}\n\t} while (tag != FDT_BEGIN_NODE);\n\n\treturn offset;\n}\n\nint fdt_first_subnode(const void *fdt, int offset)\n{\n\tint depth = 0;\n\n\toffset = fdt_next_node(fdt, offset, &depth);\n\tif (offset < 0 || depth != 1)\n\t\treturn -FDT_ERR_NOTFOUND;\n\n\treturn offset;\n}\n\nint fdt_next_subnode(const void *fdt, int offset)\n{\n\tint depth = 1;\n\n\t/*\n\t * With respect to the parent, the depth of the next subnode will be\n\t * the same as the last.\n\t */\n\tdo {\n\t\toffset = fdt_next_node(fdt, offset, &depth);\n\t\tif (offset < 0 || depth < 1)\n\t\t\treturn -FDT_ERR_NOTFOUND;\n\t} while (depth > 1);\n\n\treturn offset;\n}\n\nconst char *fdt_find_string_(const char *strtab, int tabsize, const char *s)\n{\n\tint len = strlen(s) + 1;\n\tconst char *last = strtab + tabsize - len;\n\tconst char *p;\n\n\tfor (p = strtab; p <= last; p++)\n\t\tif (memcmp(p, s, len) == 0)\n\t\t\treturn p;\n\treturn NULL;\n}\n\nint fdt_move(const void *fdt, void *buf, int bufsize)\n{\n\tif (!can_assume(VALID_INPUT) && bufsize < 0)\n\t\treturn -FDT_ERR_NOSPACE;\n\n\tFDT_RO_PROBE(fdt);\n\n\tif (fdt_totalsize(fdt) > (unsigned int)bufsize)\n\t\treturn -FDT_ERR_NOSPACE;\n\n\tmemmove(buf, fdt, fdt_totalsize(fdt));\n\treturn 0;\n}\n"
  },
  {
    "path": "external/libfdt/fdt.h",
    "content": "/* SPDX-License-Identifier: (GPL-2.0-or-later OR BSD-2-Clause) */\n#ifndef FDT_H\n#define FDT_H\n/*\n * libfdt - Flat Device Tree manipulation\n * Copyright (C) 2006 David Gibson, IBM Corporation.\n * Copyright 2012 Kim Phillips, Freescale Semiconductor.\n */\n\n#ifndef __ASSEMBLY__\n\nstruct fdt_header {\n\tfdt32_t magic;\t\t\t /* magic word FDT_MAGIC */\n\tfdt32_t totalsize;\t\t /* total size of DT block */\n\tfdt32_t off_dt_struct;\t\t /* offset to structure */\n\tfdt32_t off_dt_strings;\t\t /* offset to strings */\n\tfdt32_t off_mem_rsvmap;\t\t /* offset to memory reserve map */\n\tfdt32_t version;\t\t /* format version */\n\tfdt32_t last_comp_version;\t /* last compatible version */\n\n\t/* version 2 fields below */\n\tfdt32_t boot_cpuid_phys;\t /* Which physical CPU id we're\n\t\t\t\t\t    booting on */\n\t/* version 3 fields below */\n\tfdt32_t size_dt_strings;\t /* size of the strings block */\n\n\t/* version 17 fields below */\n\tfdt32_t size_dt_struct;\t\t /* size of the structure block */\n};\n\nstruct fdt_reserve_entry {\n\tfdt64_t address;\n\tfdt64_t size;\n};\n\nstruct fdt_node_header {\n\tfdt32_t tag;\n\tchar name[0];\n};\n\nstruct fdt_property {\n\tfdt32_t tag;\n\tfdt32_t len;\n\tfdt32_t nameoff;\n\tchar data[0];\n};\n\n#endif /* !__ASSEMBLY */\n\n#define FDT_MAGIC\t0xd00dfeed\t/* 4: version, 4: total size */\n#define FDT_TAGSIZE\tsizeof(fdt32_t)\n\n#define FDT_BEGIN_NODE\t0x1\t\t/* Start node: full name */\n#define FDT_END_NODE\t0x2\t\t/* End node */\n#define FDT_PROP\t0x3\t\t/* Property: name off,\n\t\t\t\t\t   size, content */\n#define FDT_NOP\t\t0x4\t\t/* nop */\n#define FDT_END\t\t0x9\n\n#define FDT_V1_SIZE\t(7*sizeof(fdt32_t))\n#define FDT_V2_SIZE\t(FDT_V1_SIZE + sizeof(fdt32_t))\n#define FDT_V3_SIZE\t(FDT_V2_SIZE + sizeof(fdt32_t))\n#define FDT_V16_SIZE\tFDT_V3_SIZE\n#define FDT_V17_SIZE\t(FDT_V16_SIZE + sizeof(fdt32_t))\n\n#endif /* FDT_H */\n"
  },
  {
    "path": "external/libfdt/fdt_addresses.c",
    "content": "// SPDX-License-Identifier: (GPL-2.0-or-later OR BSD-2-Clause)\n/*\n * libfdt - Flat Device Tree manipulation\n * Copyright (C) 2014 David Gibson <david@gibson.dropbear.id.au>\n * Copyright (C) 2018 embedded brains GmbH\n */\n#include \"libfdt_env.h\"\n\n#include <fdt.h>\n#include <libfdt.h>\n\n#include \"libfdt_internal.h\"\n\nstatic int fdt_cells(const void *fdt, int nodeoffset, const char *name)\n{\n\tconst fdt32_t *c;\n\tuint32_t val;\n\tint len;\n\n\tc = fdt_getprop(fdt, nodeoffset, name, &len);\n\tif (!c)\n\t\treturn len;\n\n\tif (len != sizeof(*c))\n\t\treturn -FDT_ERR_BADNCELLS;\n\n\tval = fdt32_to_cpu(*c);\n\tif (val > FDT_MAX_NCELLS)\n\t\treturn -FDT_ERR_BADNCELLS;\n\n\treturn (int)val;\n}\n\nint fdt_address_cells(const void *fdt, int nodeoffset)\n{\n\tint val;\n\n\tval = fdt_cells(fdt, nodeoffset, \"#address-cells\");\n\tif (val == 0)\n\t\treturn -FDT_ERR_BADNCELLS;\n\tif (val == -FDT_ERR_NOTFOUND)\n\t\treturn 2;\n\treturn val;\n}\n\nint fdt_size_cells(const void *fdt, int nodeoffset)\n{\n\tint val;\n\n\tval = fdt_cells(fdt, nodeoffset, \"#size-cells\");\n\tif (val == -FDT_ERR_NOTFOUND)\n\t\treturn 1;\n\treturn val;\n}\n\n/* This function assumes that [address|size]_cells is 1 or 2 */\nint fdt_appendprop_addrrange(void *fdt, int parent, int nodeoffset,\n\t\t\t     const char *name, uint64_t addr, uint64_t size)\n{\n\tint addr_cells, size_cells, ret;\n\tuint8_t data[sizeof(fdt64_t) * 2], *prop;\n\n\tret = fdt_address_cells(fdt, parent);\n\tif (ret < 0)\n\t\treturn ret;\n\taddr_cells = ret;\n\n\tret = fdt_size_cells(fdt, parent);\n\tif (ret < 0)\n\t\treturn ret;\n\tsize_cells = ret;\n\n\t/* check validity of address */\n\tprop = data;\n\tif (addr_cells == 1) {\n\t\tif ((addr > UINT32_MAX) || (((uint64_t) UINT32_MAX + 1 - addr) < size))\n\t\t\treturn -FDT_ERR_BADVALUE;\n\n\t\tfdt32_st(prop, (uint32_t)addr);\n\t} else if (addr_cells == 2) {\n\t\tfdt64_st(prop, addr);\n\t} else {\n\t\treturn -FDT_ERR_BADNCELLS;\n\t}\n\n\t/* check validity of size */\n\tprop += addr_cells * sizeof(fdt32_t);\n\tif (size_cells == 1) {\n\t\tif (size > UINT32_MAX)\n\t\t\treturn -FDT_ERR_BADVALUE;\n\n\t\tfdt32_st(prop, (uint32_t)size);\n\t} else if (size_cells == 2) {\n\t\tfdt64_st(prop, size);\n\t} else {\n\t\treturn -FDT_ERR_BADNCELLS;\n\t}\n\n\treturn fdt_appendprop(fdt, nodeoffset, name, data,\n\t\t\t      (addr_cells + size_cells) * sizeof(fdt32_t));\n}\n"
  },
  {
    "path": "external/libfdt/fdt_empty_tree.c",
    "content": "// SPDX-License-Identifier: (GPL-2.0-or-later OR BSD-2-Clause)\n/*\n * libfdt - Flat Device Tree manipulation\n * Copyright (C) 2012 David Gibson, IBM Corporation.\n */\n#include \"libfdt_env.h\"\n\n#include <fdt.h>\n#include <libfdt.h>\n\n#include \"libfdt_internal.h\"\n\nint fdt_create_empty_tree(void *buf, int bufsize)\n{\n\tint err;\n\n\terr = fdt_create(buf, bufsize);\n\tif (err)\n\t\treturn err;\n\n\terr = fdt_finish_reservemap(buf);\n\tif (err)\n\t\treturn err;\n\n\terr = fdt_begin_node(buf, \"\");\n\tif (err)\n\t\treturn err;\n\n\terr =  fdt_end_node(buf);\n\tif (err)\n\t\treturn err;\n\n\terr = fdt_finish(buf);\n\tif (err)\n\t\treturn err;\n\n\treturn fdt_open_into(buf, buf, bufsize);\n}\n"
  },
  {
    "path": "external/libfdt/fdt_overlay.c",
    "content": "// SPDX-License-Identifier: (GPL-2.0-or-later OR BSD-2-Clause)\n/*\n * libfdt - Flat Device Tree manipulation\n * Copyright (C) 2016 Free Electrons\n * Copyright (C) 2016 NextThing Co.\n */\n#include \"libfdt_env.h\"\n\n#include <fdt.h>\n#include <libfdt.h>\n\n#include \"libfdt_internal.h\"\n\n/**\n * overlay_get_target_phandle - retrieves the target phandle of a fragment\n * @fdto: pointer to the device tree overlay blob\n * @fragment: node offset of the fragment in the overlay\n *\n * overlay_get_target_phandle() retrieves the target phandle of an\n * overlay fragment when that fragment uses a phandle (target\n * property) instead of a path (target-path property).\n *\n * returns:\n *      the phandle pointed by the target property\n *      0, if the phandle was not found\n *\t-1, if the phandle was malformed\n */\nstatic uint32_t overlay_get_target_phandle(const void *fdto, int fragment)\n{\n\tconst fdt32_t *val;\n\tint len;\n\n\tval = fdt_getprop(fdto, fragment, \"target\", &len);\n\tif (!val)\n\t\treturn 0;\n\n\tif ((len != sizeof(*val)) || (fdt32_to_cpu(*val) == (uint32_t)-1))\n\t\treturn (uint32_t)-1;\n\n\treturn fdt32_to_cpu(*val);\n}\n\nint fdt_overlay_target_offset(const void *fdt, const void *fdto,\n\t\t\t      int fragment_offset, char const **pathp)\n{\n\tuint32_t phandle;\n\tconst char *path = NULL;\n\tint path_len = 0, ret;\n\n\t/* Try first to do a phandle based lookup */\n\tphandle = overlay_get_target_phandle(fdto, fragment_offset);\n\tif (phandle == (uint32_t)-1)\n\t\treturn -FDT_ERR_BADPHANDLE;\n\n\t/* no phandle, try path */\n\tif (!phandle) {\n\t\t/* And then a path based lookup */\n\t\tpath = fdt_getprop(fdto, fragment_offset, \"target-path\", &path_len);\n\t\tif (path)\n\t\t\tret = fdt_path_offset(fdt, path);\n\t\telse\n\t\t\tret = path_len;\n\t} else\n\t\tret = fdt_node_offset_by_phandle(fdt, phandle);\n\n\t/*\n\t* If we haven't found either a target or a\n\t* target-path property in a node that contains a\n\t* __overlay__ subnode (we wouldn't be called\n\t* otherwise), consider it a improperly written\n\t* overlay\n\t*/\n\tif (ret < 0 && path_len == -FDT_ERR_NOTFOUND)\n\t\tret = -FDT_ERR_BADOVERLAY;\n\n\t/* return on error */\n\tif (ret < 0)\n\t\treturn ret;\n\n\t/* return pointer to path (if available) */\n\tif (pathp)\n\t\t*pathp = path ? path : NULL;\n\n\treturn ret;\n}\n\n/**\n * overlay_phandle_add_offset - Increases a phandle by an offset\n * @fdt: Base device tree blob\n * @node: Device tree overlay blob\n * @name: Name of the property to modify (phandle or linux,phandle)\n * @delta: offset to apply\n *\n * overlay_phandle_add_offset() increments a node phandle by a given\n * offset.\n *\n * returns:\n *      0 on success.\n *      Negative error code on error\n */\nstatic int overlay_phandle_add_offset(void *fdt, int node,\n\t\t\t\t      const char *name, uint32_t delta)\n{\n\tconst fdt32_t *val;\n\tuint32_t adj_val;\n\tint len;\n\n\tval = fdt_getprop(fdt, node, name, &len);\n\tif (!val)\n\t\treturn len;\n\n\tif (len != sizeof(*val))\n\t\treturn -FDT_ERR_BADPHANDLE;\n\n\tadj_val = fdt32_to_cpu(*val);\n\tif ((adj_val + delta) < adj_val)\n\t\treturn -FDT_ERR_NOPHANDLES;\n\n\tadj_val += delta;\n\tif (adj_val == (uint32_t)-1)\n\t\treturn -FDT_ERR_NOPHANDLES;\n\n\treturn fdt_setprop_inplace_u32(fdt, node, name, adj_val);\n}\n\n/**\n * overlay_adjust_node_phandles - Offsets the phandles of a node\n * @fdto: Device tree overlay blob\n * @node: Offset of the node we want to adjust\n * @delta: Offset to shift the phandles of\n *\n * overlay_adjust_node_phandles() adds a constant to all the phandles\n * of a given node. This is mainly use as part of the overlay\n * application process, when we want to update all the overlay\n * phandles to not conflict with the overlays of the base device tree.\n *\n * returns:\n *      0 on success\n *      Negative error code on failure\n */\nstatic int overlay_adjust_node_phandles(void *fdto, int node,\n\t\t\t\t\tuint32_t delta)\n{\n\tint child;\n\tint ret;\n\n\tret = overlay_phandle_add_offset(fdto, node, \"phandle\", delta);\n\tif (ret && ret != -FDT_ERR_NOTFOUND)\n\t\treturn ret;\n\n\tret = overlay_phandle_add_offset(fdto, node, \"linux,phandle\", delta);\n\tif (ret && ret != -FDT_ERR_NOTFOUND)\n\t\treturn ret;\n\n\tfdt_for_each_subnode(child, fdto, node) {\n\t\tret = overlay_adjust_node_phandles(fdto, child, delta);\n\t\tif (ret)\n\t\t\treturn ret;\n\t}\n\n\treturn 0;\n}\n\n/**\n * overlay_adjust_local_phandles - Adjust the phandles of a whole overlay\n * @fdto: Device tree overlay blob\n * @delta: Offset to shift the phandles of\n *\n * overlay_adjust_local_phandles() adds a constant to all the\n * phandles of an overlay. This is mainly use as part of the overlay\n * application process, when we want to update all the overlay\n * phandles to not conflict with the overlays of the base device tree.\n *\n * returns:\n *      0 on success\n *      Negative error code on failure\n */\nstatic int overlay_adjust_local_phandles(void *fdto, uint32_t delta)\n{\n\t/*\n\t * Start adjusting the phandles from the overlay root\n\t */\n\treturn overlay_adjust_node_phandles(fdto, 0, delta);\n}\n\n/**\n * overlay_update_local_node_references - Adjust the overlay references\n * @fdto: Device tree overlay blob\n * @tree_node: Node offset of the node to operate on\n * @fixup_node: Node offset of the matching local fixups node\n * @delta: Offset to shift the phandles of\n *\n * overlay_update_local_nodes_references() update the phandles\n * pointing to a node within the device tree overlay by adding a\n * constant delta.\n *\n * This is mainly used as part of a device tree application process,\n * where you want the device tree overlays phandles to not conflict\n * with the ones from the base device tree before merging them.\n *\n * returns:\n *      0 on success\n *      Negative error code on failure\n */\nstatic int overlay_update_local_node_references(void *fdto,\n\t\t\t\t\t\tint tree_node,\n\t\t\t\t\t\tint fixup_node,\n\t\t\t\t\t\tuint32_t delta)\n{\n\tint fixup_prop;\n\tint fixup_child;\n\tint ret;\n\n\tfdt_for_each_property_offset(fixup_prop, fdto, fixup_node) {\n\t\tconst fdt32_t *fixup_val;\n\t\tconst char *tree_val;\n\t\tconst char *name;\n\t\tint fixup_len;\n\t\tint tree_len;\n\t\tint i;\n\n\t\tfixup_val = fdt_getprop_by_offset(fdto, fixup_prop,\n\t\t\t\t\t\t  &name, &fixup_len);\n\t\tif (!fixup_val)\n\t\t\treturn fixup_len;\n\n\t\tif (fixup_len % sizeof(uint32_t))\n\t\t\treturn -FDT_ERR_BADOVERLAY;\n\t\tfixup_len /= sizeof(uint32_t);\n\n\t\ttree_val = fdt_getprop(fdto, tree_node, name, &tree_len);\n\t\tif (!tree_val) {\n\t\t\tif (tree_len == -FDT_ERR_NOTFOUND)\n\t\t\t\treturn -FDT_ERR_BADOVERLAY;\n\n\t\t\treturn tree_len;\n\t\t}\n\n\t\tfor (i = 0; i < fixup_len; i++) {\n\t\t\tfdt32_t adj_val;\n\t\t\tuint32_t poffset;\n\n\t\t\tpoffset = fdt32_to_cpu(fixup_val[i]);\n\n\t\t\t/*\n\t\t\t * phandles to fixup can be unaligned.\n\t\t\t *\n\t\t\t * Use a memcpy for the architectures that do\n\t\t\t * not support unaligned accesses.\n\t\t\t */\n\t\t\tmemcpy(&adj_val, tree_val + poffset, sizeof(adj_val));\n\n\t\t\tadj_val = cpu_to_fdt32(fdt32_to_cpu(adj_val) + delta);\n\n\t\t\tret = fdt_setprop_inplace_namelen_partial(fdto,\n\t\t\t\t\t\t\t\t  tree_node,\n\t\t\t\t\t\t\t\t  name,\n\t\t\t\t\t\t\t\t  strlen(name),\n\t\t\t\t\t\t\t\t  poffset,\n\t\t\t\t\t\t\t\t  &adj_val,\n\t\t\t\t\t\t\t\t  sizeof(adj_val));\n\t\t\tif (ret == -FDT_ERR_NOSPACE)\n\t\t\t\treturn -FDT_ERR_BADOVERLAY;\n\n\t\t\tif (ret)\n\t\t\t\treturn ret;\n\t\t}\n\t}\n\n\tfdt_for_each_subnode(fixup_child, fdto, fixup_node) {\n\t\tconst char *fixup_child_name = fdt_get_name(fdto, fixup_child,\n\t\t\t\t\t\t\t    NULL);\n\t\tint tree_child;\n\n\t\ttree_child = fdt_subnode_offset(fdto, tree_node,\n\t\t\t\t\t\tfixup_child_name);\n\t\tif (tree_child == -FDT_ERR_NOTFOUND)\n\t\t\treturn -FDT_ERR_BADOVERLAY;\n\t\tif (tree_child < 0)\n\t\t\treturn tree_child;\n\n\t\tret = overlay_update_local_node_references(fdto,\n\t\t\t\t\t\t\t   tree_child,\n\t\t\t\t\t\t\t   fixup_child,\n\t\t\t\t\t\t\t   delta);\n\t\tif (ret)\n\t\t\treturn ret;\n\t}\n\n\treturn 0;\n}\n\n/**\n * overlay_update_local_references - Adjust the overlay references\n * @fdto: Device tree overlay blob\n * @delta: Offset to shift the phandles of\n *\n * overlay_update_local_references() update all the phandles pointing\n * to a node within the device tree overlay by adding a constant\n * delta to not conflict with the base overlay.\n *\n * This is mainly used as part of a device tree application process,\n * where you want the device tree overlays phandles to not conflict\n * with the ones from the base device tree before merging them.\n *\n * returns:\n *      0 on success\n *      Negative error code on failure\n */\nstatic int overlay_update_local_references(void *fdto, uint32_t delta)\n{\n\tint fixups;\n\n\tfixups = fdt_path_offset(fdto, \"/__local_fixups__\");\n\tif (fixups < 0) {\n\t\t/* There's no local phandles to adjust, bail out */\n\t\tif (fixups == -FDT_ERR_NOTFOUND)\n\t\t\treturn 0;\n\n\t\treturn fixups;\n\t}\n\n\t/*\n\t * Update our local references from the root of the tree\n\t */\n\treturn overlay_update_local_node_references(fdto, 0, fixups,\n\t\t\t\t\t\t    delta);\n}\n\n/**\n * overlay_fixup_one_phandle - Set an overlay phandle to the base one\n * @fdt: Base Device Tree blob\n * @fdto: Device tree overlay blob\n * @symbols_off: Node offset of the symbols node in the base device tree\n * @path: Path to a node holding a phandle in the overlay\n * @path_len: number of path characters to consider\n * @name: Name of the property holding the phandle reference in the overlay\n * @name_len: number of name characters to consider\n * @poffset: Offset within the overlay property where the phandle is stored\n * @label: Label of the node referenced by the phandle\n *\n * overlay_fixup_one_phandle() resolves an overlay phandle pointing to\n * a node in the base device tree.\n *\n * This is part of the device tree overlay application process, when\n * you want all the phandles in the overlay to point to the actual\n * base dt nodes.\n *\n * returns:\n *      0 on success\n *      Negative error code on failure\n */\nstatic int overlay_fixup_one_phandle(void *fdt, void *fdto,\n\t\t\t\t     int symbols_off,\n\t\t\t\t     const char *path, uint32_t path_len,\n\t\t\t\t     const char *name, uint32_t name_len,\n\t\t\t\t     int poffset, const char *label)\n{\n\tconst char *symbol_path;\n\tuint32_t phandle;\n\tfdt32_t phandle_prop;\n\tint symbol_off, fixup_off;\n\tint prop_len;\n\n\tif (symbols_off < 0)\n\t\treturn symbols_off;\n\n\tsymbol_path = fdt_getprop(fdt, symbols_off, label,\n\t\t\t\t  &prop_len);\n\tif (!symbol_path)\n\t\treturn prop_len;\n\n\tsymbol_off = fdt_path_offset(fdt, symbol_path);\n\tif (symbol_off < 0)\n\t\treturn symbol_off;\n\n\tphandle = fdt_get_phandle(fdt, symbol_off);\n\tif (!phandle)\n\t\treturn -FDT_ERR_NOTFOUND;\n\n\tfixup_off = fdt_path_offset_namelen(fdto, path, path_len);\n\tif (fixup_off == -FDT_ERR_NOTFOUND)\n\t\treturn -FDT_ERR_BADOVERLAY;\n\tif (fixup_off < 0)\n\t\treturn fixup_off;\n\n\tphandle_prop = cpu_to_fdt32(phandle);\n\treturn fdt_setprop_inplace_namelen_partial(fdto, fixup_off,\n\t\t\t\t\t\t   name, name_len, poffset,\n\t\t\t\t\t\t   &phandle_prop,\n\t\t\t\t\t\t   sizeof(phandle_prop));\n};\n\n/**\n * overlay_fixup_phandle - Set an overlay phandle to the base one\n * @fdt: Base Device Tree blob\n * @fdto: Device tree overlay blob\n * @symbols_off: Node offset of the symbols node in the base device tree\n * @property: Property offset in the overlay holding the list of fixups\n *\n * overlay_fixup_phandle() resolves all the overlay phandles pointed\n * to in a __fixups__ property, and updates them to match the phandles\n * in use in the base device tree.\n *\n * This is part of the device tree overlay application process, when\n * you want all the phandles in the overlay to point to the actual\n * base dt nodes.\n *\n * returns:\n *      0 on success\n *      Negative error code on failure\n */\nstatic int overlay_fixup_phandle(void *fdt, void *fdto, int symbols_off,\n\t\t\t\t int property)\n{\n\tconst char *value;\n\tconst char *label;\n\tint len;\n\n\tvalue = fdt_getprop_by_offset(fdto, property,\n\t\t\t\t      &label, &len);\n\tif (!value) {\n\t\tif (len == -FDT_ERR_NOTFOUND)\n\t\t\treturn -FDT_ERR_INTERNAL;\n\n\t\treturn len;\n\t}\n\n\tdo {\n\t\tconst char *path, *name, *fixup_end;\n\t\tconst char *fixup_str = value;\n\t\tuint32_t path_len, name_len;\n\t\tuint32_t fixup_len;\n\t\tchar *sep, *endptr;\n\t\tint poffset, ret;\n\n\t\tfixup_end = memchr(value, '\\0', len);\n\t\tif (!fixup_end)\n\t\t\treturn -FDT_ERR_BADOVERLAY;\n\t\tfixup_len = fixup_end - fixup_str;\n\n\t\tlen -= fixup_len + 1;\n\t\tvalue += fixup_len + 1;\n\n\t\tpath = fixup_str;\n\t\tsep = memchr(fixup_str, ':', fixup_len);\n\t\tif (!sep || *sep != ':')\n\t\t\treturn -FDT_ERR_BADOVERLAY;\n\n\t\tpath_len = sep - path;\n\t\tif (path_len == (fixup_len - 1))\n\t\t\treturn -FDT_ERR_BADOVERLAY;\n\n\t\tfixup_len -= path_len + 1;\n\t\tname = sep + 1;\n\t\tsep = memchr(name, ':', fixup_len);\n\t\tif (!sep || *sep != ':')\n\t\t\treturn -FDT_ERR_BADOVERLAY;\n\n\t\tname_len = sep - name;\n\t\tif (!name_len)\n\t\t\treturn -FDT_ERR_BADOVERLAY;\n\n\t\tpoffset = strtoul(sep + 1, &endptr, 10);\n\t\tif ((*endptr != '\\0') || (endptr <= (sep + 1)))\n\t\t\treturn -FDT_ERR_BADOVERLAY;\n\n\t\tret = overlay_fixup_one_phandle(fdt, fdto, symbols_off,\n\t\t\t\t\t\tpath, path_len, name, name_len,\n\t\t\t\t\t\tpoffset, label);\n\t\tif (ret)\n\t\t\treturn ret;\n\t} while (len > 0);\n\n\treturn 0;\n}\n\n/**\n * overlay_fixup_phandles - Resolve the overlay phandles to the base\n *                          device tree\n * @fdt: Base Device Tree blob\n * @fdto: Device tree overlay blob\n *\n * overlay_fixup_phandles() resolves all the overlay phandles pointing\n * to nodes in the base device tree.\n *\n * This is one of the steps of the device tree overlay application\n * process, when you want all the phandles in the overlay to point to\n * the actual base dt nodes.\n *\n * returns:\n *      0 on success\n *      Negative error code on failure\n */\nstatic int overlay_fixup_phandles(void *fdt, void *fdto)\n{\n\tint fixups_off, symbols_off;\n\tint property;\n\n\t/* We can have overlays without any fixups */\n\tfixups_off = fdt_path_offset(fdto, \"/__fixups__\");\n\tif (fixups_off == -FDT_ERR_NOTFOUND)\n\t\treturn 0; /* nothing to do */\n\tif (fixups_off < 0)\n\t\treturn fixups_off;\n\n\t/* And base DTs without symbols */\n\tsymbols_off = fdt_path_offset(fdt, \"/__symbols__\");\n\tif ((symbols_off < 0 && (symbols_off != -FDT_ERR_NOTFOUND)))\n\t\treturn symbols_off;\n\n\tfdt_for_each_property_offset(property, fdto, fixups_off) {\n\t\tint ret;\n\n\t\tret = overlay_fixup_phandle(fdt, fdto, symbols_off, property);\n\t\tif (ret)\n\t\t\treturn ret;\n\t}\n\n\treturn 0;\n}\n\n/**\n * overlay_apply_node - Merges a node into the base device tree\n * @fdt: Base Device Tree blob\n * @target: Node offset in the base device tree to apply the fragment to\n * @fdto: Device tree overlay blob\n * @node: Node offset in the overlay holding the changes to merge\n *\n * overlay_apply_node() merges a node into a target base device tree\n * node pointed.\n *\n * This is part of the final step in the device tree overlay\n * application process, when all the phandles have been adjusted and\n * resolved and you just have to merge overlay into the base device\n * tree.\n *\n * returns:\n *      0 on success\n *      Negative error code on failure\n */\nstatic int overlay_apply_node(void *fdt, int target,\n\t\t\t      void *fdto, int node)\n{\n\tint property;\n\tint subnode;\n\n\tfdt_for_each_property_offset(property, fdto, node) {\n\t\tconst char *name;\n\t\tconst void *prop;\n\t\tint prop_len;\n\t\tint ret;\n\n\t\tprop = fdt_getprop_by_offset(fdto, property, &name,\n\t\t\t\t\t     &prop_len);\n\t\tif (prop_len == -FDT_ERR_NOTFOUND)\n\t\t\treturn -FDT_ERR_INTERNAL;\n\t\tif (prop_len < 0)\n\t\t\treturn prop_len;\n\n\t\tret = fdt_setprop(fdt, target, name, prop, prop_len);\n\t\tif (ret)\n\t\t\treturn ret;\n\t}\n\n\tfdt_for_each_subnode(subnode, fdto, node) {\n\t\tconst char *name = fdt_get_name(fdto, subnode, NULL);\n\t\tint nnode;\n\t\tint ret;\n\n\t\tnnode = fdt_add_subnode(fdt, target, name);\n\t\tif (nnode == -FDT_ERR_EXISTS) {\n\t\t\tnnode = fdt_subnode_offset(fdt, target, name);\n\t\t\tif (nnode == -FDT_ERR_NOTFOUND)\n\t\t\t\treturn -FDT_ERR_INTERNAL;\n\t\t}\n\n\t\tif (nnode < 0)\n\t\t\treturn nnode;\n\n\t\tret = overlay_apply_node(fdt, nnode, fdto, subnode);\n\t\tif (ret)\n\t\t\treturn ret;\n\t}\n\n\treturn 0;\n}\n\n/**\n * overlay_merge - Merge an overlay into its base device tree\n * @fdt: Base Device Tree blob\n * @fdto: Device tree overlay blob\n *\n * overlay_merge() merges an overlay into its base device tree.\n *\n * This is the next to last step in the device tree overlay application\n * process, when all the phandles have been adjusted and resolved and\n * you just have to merge overlay into the base device tree.\n *\n * returns:\n *      0 on success\n *      Negative error code on failure\n */\nstatic int overlay_merge(void *fdt, void *fdto)\n{\n\tint fragment;\n\n\tfdt_for_each_subnode(fragment, fdto, 0) {\n\t\tint overlay;\n\t\tint target;\n\t\tint ret;\n\n\t\t/*\n\t\t * Each fragments will have an __overlay__ node. If\n\t\t * they don't, it's not supposed to be merged\n\t\t */\n\t\toverlay = fdt_subnode_offset(fdto, fragment, \"__overlay__\");\n\t\tif (overlay == -FDT_ERR_NOTFOUND)\n\t\t\tcontinue;\n\n\t\tif (overlay < 0)\n\t\t\treturn overlay;\n\n\t\ttarget = fdt_overlay_target_offset(fdt, fdto, fragment, NULL);\n\t\tif (target < 0)\n\t\t\treturn target;\n\n\t\tret = overlay_apply_node(fdt, target, fdto, overlay);\n\t\tif (ret)\n\t\t\treturn ret;\n\t}\n\n\treturn 0;\n}\n\nstatic int get_path_len(const void *fdt, int nodeoffset)\n{\n\tint len = 0, namelen;\n\tconst char *name;\n\n\tFDT_RO_PROBE(fdt);\n\n\tfor (;;) {\n\t\tname = fdt_get_name(fdt, nodeoffset, &namelen);\n\t\tif (!name)\n\t\t\treturn namelen;\n\n\t\t/* root? we're done */\n\t\tif (namelen == 0)\n\t\t\tbreak;\n\n\t\tnodeoffset = fdt_parent_offset(fdt, nodeoffset);\n\t\tif (nodeoffset < 0)\n\t\t\treturn nodeoffset;\n\t\tlen += namelen + 1;\n\t}\n\n\t/* in case of root pretend it's \"/\" */\n\tif (len == 0)\n\t\tlen++;\n\treturn len;\n}\n\n/**\n * overlay_symbol_update - Update the symbols of base tree after a merge\n * @fdt: Base Device Tree blob\n * @fdto: Device tree overlay blob\n *\n * overlay_symbol_update() updates the symbols of the base tree with the\n * symbols of the applied overlay\n *\n * This is the last step in the device tree overlay application\n * process, allowing the reference of overlay symbols by subsequent\n * overlay operations.\n *\n * returns:\n *      0 on success\n *      Negative error code on failure\n */\nstatic int overlay_symbol_update(void *fdt, void *fdto)\n{\n\tint root_sym, ov_sym, prop, path_len, fragment, target;\n\tint len, frag_name_len, ret, rel_path_len;\n\tconst char *s, *e;\n\tconst char *path;\n\tconst char *name;\n\tconst char *frag_name;\n\tconst char *rel_path;\n\tconst char *target_path;\n\tchar *buf;\n\tvoid *p;\n\n\tov_sym = fdt_subnode_offset(fdto, 0, \"__symbols__\");\n\n\t/* if no overlay symbols exist no problem */\n\tif (ov_sym < 0)\n\t\treturn 0;\n\n\troot_sym = fdt_subnode_offset(fdt, 0, \"__symbols__\");\n\n\t/* it no root symbols exist we should create them */\n\tif (root_sym == -FDT_ERR_NOTFOUND)\n\t\troot_sym = fdt_add_subnode(fdt, 0, \"__symbols__\");\n\n\t/* any error is fatal now */\n\tif (root_sym < 0)\n\t\treturn root_sym;\n\n\t/* iterate over each overlay symbol */\n\tfdt_for_each_property_offset(prop, fdto, ov_sym) {\n\t\tpath = fdt_getprop_by_offset(fdto, prop, &name, &path_len);\n\t\tif (!path)\n\t\t\treturn path_len;\n\n\t\t/* verify it's a string property (terminated by a single \\0) */\n\t\tif (path_len < 1 || memchr(path, '\\0', path_len) != &path[path_len - 1])\n\t\t\treturn -FDT_ERR_BADVALUE;\n\n\t\t/* keep end marker to avoid strlen() */\n\t\te = path + path_len;\n\n\t\tif (*path != '/')\n\t\t\treturn -FDT_ERR_BADVALUE;\n\n\t\t/* get fragment name first */\n\t\ts = strchr(path + 1, '/');\n\t\tif (!s) {\n\t\t\t/* Symbol refers to something that won't end\n\t\t\t * up in the target tree */\n\t\t\tcontinue;\n\t\t}\n\n\t\tfrag_name = path + 1;\n\t\tfrag_name_len = s - path - 1;\n\n\t\t/* verify format; safe since \"s\" lies in \\0 terminated prop */\n\t\tlen = sizeof(\"/__overlay__/\") - 1;\n\t\tif ((e - s) > len && (memcmp(s, \"/__overlay__/\", len) == 0)) {\n\t\t\t/* /<fragment-name>/__overlay__/<relative-subnode-path> */\n\t\t\trel_path = s + len;\n\t\t\trel_path_len = e - rel_path - 1;\n\t\t} else if ((e - s) == len\n\t\t\t   && (memcmp(s, \"/__overlay__\", len - 1) == 0)) {\n\t\t\t/* /<fragment-name>/__overlay__ */\n\t\t\trel_path = \"\";\n\t\t\trel_path_len = 0;\n\t\t} else {\n\t\t\t/* Symbol refers to something that won't end\n\t\t\t * up in the target tree */\n\t\t\tcontinue;\n\t\t}\n\n\t\t/* find the fragment index in which the symbol lies */\n\t\tret = fdt_subnode_offset_namelen(fdto, 0, frag_name,\n\t\t\t\t\t       frag_name_len);\n\t\t/* not found? */\n\t\tif (ret < 0)\n\t\t\treturn -FDT_ERR_BADOVERLAY;\n\t\tfragment = ret;\n\n\t\t/* an __overlay__ subnode must exist */\n\t\tret = fdt_subnode_offset(fdto, fragment, \"__overlay__\");\n\t\tif (ret < 0)\n\t\t\treturn -FDT_ERR_BADOVERLAY;\n\n\t\t/* get the target of the fragment */\n\t\tret = fdt_overlay_target_offset(fdt, fdto, fragment, &target_path);\n\t\tif (ret < 0)\n\t\t\treturn ret;\n\t\ttarget = ret;\n\n\t\t/* if we have a target path use */\n\t\tif (!target_path) {\n\t\t\tret = get_path_len(fdt, target);\n\t\t\tif (ret < 0)\n\t\t\t\treturn ret;\n\t\t\tlen = ret;\n\t\t} else {\n\t\t\tlen = strlen(target_path);\n\t\t}\n\n\t\tret = fdt_setprop_placeholder(fdt, root_sym, name,\n\t\t\t\tlen + (len > 1) + rel_path_len + 1, &p);\n\t\tif (ret < 0)\n\t\t\treturn ret;\n\n\t\tif (!target_path) {\n\t\t\t/* again in case setprop_placeholder changed it */\n\t\t\tret = fdt_overlay_target_offset(fdt, fdto, fragment, &target_path);\n\t\t\tif (ret < 0)\n\t\t\t\treturn ret;\n\t\t\ttarget = ret;\n\t\t}\n\n\t\tbuf = p;\n\t\tif (len > 1) { /* target is not root */\n\t\t\tif (!target_path) {\n\t\t\t\tret = fdt_get_path(fdt, target, buf, len + 1);\n\t\t\t\tif (ret < 0)\n\t\t\t\t\treturn ret;\n\t\t\t} else\n\t\t\t\tmemcpy(buf, target_path, len + 1);\n\n\t\t} else\n\t\t\tlen--;\n\n\t\tbuf[len] = '/';\n\t\tmemcpy(buf + len + 1, rel_path, rel_path_len);\n\t\tbuf[len + 1 + rel_path_len] = '\\0';\n\t}\n\n\treturn 0;\n}\n\nint fdt_overlay_apply(void *fdt, void *fdto)\n{\n\tuint32_t delta;\n\tint ret;\n\n\tFDT_RO_PROBE(fdt);\n\tFDT_RO_PROBE(fdto);\n\n\tret = fdt_find_max_phandle(fdt, &delta);\n\tif (ret)\n\t\tgoto err;\n\n\tret = overlay_adjust_local_phandles(fdto, delta);\n\tif (ret)\n\t\tgoto err;\n\n\tret = overlay_update_local_references(fdto, delta);\n\tif (ret)\n\t\tgoto err;\n\n\tret = overlay_fixup_phandles(fdt, fdto);\n\tif (ret)\n\t\tgoto err;\n\n\tret = overlay_merge(fdt, fdto);\n\tif (ret)\n\t\tgoto err;\n\n\tret = overlay_symbol_update(fdt, fdto);\n\tif (ret)\n\t\tgoto err;\n\n\t/*\n\t * The overlay has been damaged, erase its magic.\n\t */\n\tfdt_set_magic(fdto, ~0);\n\n\treturn 0;\n\nerr:\n\t/*\n\t * The overlay might have been damaged, erase its magic.\n\t */\n\tfdt_set_magic(fdto, ~0);\n\n\t/*\n\t * The base device tree might have been damaged, erase its\n\t * magic.\n\t */\n\tfdt_set_magic(fdt, ~0);\n\n\treturn ret;\n}\n"
  },
  {
    "path": "external/libfdt/fdt_ro.c",
    "content": "// SPDX-License-Identifier: (GPL-2.0-or-later OR BSD-2-Clause)\n/*\n * libfdt - Flat Device Tree manipulation\n * Copyright (C) 2006 David Gibson, IBM Corporation.\n */\n#include \"libfdt_env.h\"\n\n#include <fdt.h>\n#include <libfdt.h>\n\n#include \"libfdt_internal.h\"\n\nstatic int fdt_nodename_eq_(const void *fdt, int offset,\n\t\t\t    const char *s, int len)\n{\n\tint olen;\n\tconst char *p = fdt_get_name(fdt, offset, &olen);\n\n\tif (!p || olen < len)\n\t\t/* short match */\n\t\treturn 0;\n\n\tif (memcmp(p, s, len) != 0)\n\t\treturn 0;\n\n\tif (p[len] == '\\0')\n\t\treturn 1;\n\telse if (!memchr(s, '@', len) && (p[len] == '@'))\n\t\treturn 1;\n\telse\n\t\treturn 0;\n}\n\nconst char *fdt_get_string(const void *fdt, int stroffset, int *lenp)\n{\n\tint32_t totalsize;\n\tuint32_t absoffset;\n\tsize_t len;\n\tint err;\n\tconst char *s, *n;\n\n\tif (can_assume(VALID_INPUT)) {\n\t\ts = (const char *)fdt + fdt_off_dt_strings(fdt) + stroffset;\n\n\t\tif (lenp)\n\t\t\t*lenp = strlen(s);\n\t\treturn s;\n\t}\n\ttotalsize = fdt_ro_probe_(fdt);\n\terr = totalsize;\n\tif (totalsize < 0)\n\t\tgoto fail;\n\n\terr = -FDT_ERR_BADOFFSET;\n\tabsoffset = stroffset + fdt_off_dt_strings(fdt);\n\tif (absoffset >= (unsigned)totalsize)\n\t\tgoto fail;\n\tlen = totalsize - absoffset;\n\n\tif (fdt_magic(fdt) == FDT_MAGIC) {\n\t\tif (stroffset < 0)\n\t\t\tgoto fail;\n\t\tif (can_assume(LATEST) || fdt_version(fdt) >= 17) {\n\t\t\tif ((unsigned)stroffset >= fdt_size_dt_strings(fdt))\n\t\t\t\tgoto fail;\n\t\t\tif ((fdt_size_dt_strings(fdt) - stroffset) < len)\n\t\t\t\tlen = fdt_size_dt_strings(fdt) - stroffset;\n\t\t}\n\t} else if (fdt_magic(fdt) == FDT_SW_MAGIC) {\n\t\tunsigned int sw_stroffset = -stroffset;\n\n\t\tif ((stroffset >= 0) ||\n\t\t    (sw_stroffset > fdt_size_dt_strings(fdt)))\n\t\t\tgoto fail;\n\t\tif (sw_stroffset < len)\n\t\t\tlen = sw_stroffset;\n\t} else {\n\t\terr = -FDT_ERR_INTERNAL;\n\t\tgoto fail;\n\t}\n\n\ts = (const char *)fdt + absoffset;\n\tn = memchr(s, '\\0', len);\n\tif (!n) {\n\t\t/* missing terminating NULL */\n\t\terr = -FDT_ERR_TRUNCATED;\n\t\tgoto fail;\n\t}\n\n\tif (lenp)\n\t\t*lenp = n - s;\n\treturn s;\n\nfail:\n\tif (lenp)\n\t\t*lenp = err;\n\treturn NULL;\n}\n\nconst char *fdt_string(const void *fdt, int stroffset)\n{\n\treturn fdt_get_string(fdt, stroffset, NULL);\n}\n\nstatic int fdt_string_eq_(const void *fdt, int stroffset,\n\t\t\t  const char *s, int len)\n{\n\tint slen;\n\tconst char *p = fdt_get_string(fdt, stroffset, &slen);\n\n\treturn p && (slen == len) && (memcmp(p, s, len) == 0);\n}\n\nint fdt_find_max_phandle(const void *fdt, uint32_t *phandle)\n{\n\tuint32_t max = 0;\n\tint offset = -1;\n\n\twhile (true) {\n\t\tuint32_t value;\n\n\t\toffset = fdt_next_node(fdt, offset, NULL);\n\t\tif (offset < 0) {\n\t\t\tif (offset == -FDT_ERR_NOTFOUND)\n\t\t\t\tbreak;\n\n\t\t\treturn offset;\n\t\t}\n\n\t\tvalue = fdt_get_phandle(fdt, offset);\n\n\t\tif (value > max)\n\t\t\tmax = value;\n\t}\n\n\tif (phandle)\n\t\t*phandle = max;\n\n\treturn 0;\n}\n\nint fdt_generate_phandle(const void *fdt, uint32_t *phandle)\n{\n\tuint32_t max;\n\tint err;\n\n\terr = fdt_find_max_phandle(fdt, &max);\n\tif (err < 0)\n\t\treturn err;\n\n\tif (max == FDT_MAX_PHANDLE)\n\t\treturn -FDT_ERR_NOPHANDLES;\n\n\tif (phandle)\n\t\t*phandle = max + 1;\n\n\treturn 0;\n}\n\nstatic const struct fdt_reserve_entry *fdt_mem_rsv(const void *fdt, int n)\n{\n\tunsigned int offset = n * sizeof(struct fdt_reserve_entry);\n\tunsigned int absoffset = fdt_off_mem_rsvmap(fdt) + offset;\n\n\tif (!can_assume(VALID_INPUT)) {\n\t\tif (absoffset < fdt_off_mem_rsvmap(fdt))\n\t\t\treturn NULL;\n\t\tif (absoffset > fdt_totalsize(fdt) -\n\t\t    sizeof(struct fdt_reserve_entry))\n\t\t\treturn NULL;\n\t}\n\treturn fdt_mem_rsv_(fdt, n);\n}\n\nint fdt_get_mem_rsv(const void *fdt, int n, uint64_t *address, uint64_t *size)\n{\n\tconst struct fdt_reserve_entry *re;\n\n\tFDT_RO_PROBE(fdt);\n\tre = fdt_mem_rsv(fdt, n);\n\tif (!can_assume(VALID_INPUT) && !re)\n\t\treturn -FDT_ERR_BADOFFSET;\n\n\t*address = fdt64_ld_(&re->address);\n\t*size = fdt64_ld_(&re->size);\n\treturn 0;\n}\n\nint fdt_num_mem_rsv(const void *fdt)\n{\n\tint i;\n\tconst struct fdt_reserve_entry *re;\n\n\tfor (i = 0; (re = fdt_mem_rsv(fdt, i)) != NULL; i++) {\n\t\tif (fdt64_ld_(&re->size) == 0)\n\t\t\treturn i;\n\t}\n\treturn -FDT_ERR_TRUNCATED;\n}\n\nstatic int nextprop_(const void *fdt, int offset)\n{\n\tuint32_t tag;\n\tint nextoffset;\n\n\tdo {\n\t\ttag = fdt_next_tag(fdt, offset, &nextoffset);\n\n\t\tswitch (tag) {\n\t\tcase FDT_END:\n\t\t\tif (nextoffset >= 0)\n\t\t\t\treturn -FDT_ERR_BADSTRUCTURE;\n\t\t\telse\n\t\t\t\treturn nextoffset;\n\n\t\tcase FDT_PROP:\n\t\t\treturn offset;\n\t\t}\n\t\toffset = nextoffset;\n\t} while (tag == FDT_NOP);\n\n\treturn -FDT_ERR_NOTFOUND;\n}\n\nint fdt_subnode_offset_namelen(const void *fdt, int offset,\n\t\t\t       const char *name, int namelen)\n{\n\tint depth;\n\n\tFDT_RO_PROBE(fdt);\n\n\tfor (depth = 0;\n\t     (offset >= 0) && (depth >= 0);\n\t     offset = fdt_next_node(fdt, offset, &depth))\n\t\tif ((depth == 1)\n\t\t    && fdt_nodename_eq_(fdt, offset, name, namelen))\n\t\t\treturn offset;\n\n\tif (depth < 0)\n\t\treturn -FDT_ERR_NOTFOUND;\n\treturn offset; /* error */\n}\n\nint fdt_subnode_offset(const void *fdt, int parentoffset,\n\t\t       const char *name)\n{\n\treturn fdt_subnode_offset_namelen(fdt, parentoffset, name, strlen(name));\n}\n\nint fdt_path_offset_namelen(const void *fdt, const char *path, int namelen)\n{\n\tconst char *end = path + namelen;\n\tconst char *p = path;\n\tint offset = 0;\n\n\tFDT_RO_PROBE(fdt);\n\n\t/* see if we have an alias */\n\tif (*path != '/') {\n\t\tconst char *q = memchr(path, '/', end - p);\n\n\t\tif (!q)\n\t\t\tq = end;\n\n\t\tp = fdt_get_alias_namelen(fdt, p, q - p);\n\t\tif (!p)\n\t\t\treturn -FDT_ERR_BADPATH;\n\t\toffset = fdt_path_offset(fdt, p);\n\n\t\tp = q;\n\t}\n\n\twhile (p < end) {\n\t\tconst char *q;\n\n\t\twhile (*p == '/') {\n\t\t\tp++;\n\t\t\tif (p == end)\n\t\t\t\treturn offset;\n\t\t}\n\t\tq = memchr(p, '/', end - p);\n\t\tif (! q)\n\t\t\tq = end;\n\n\t\toffset = fdt_subnode_offset_namelen(fdt, offset, p, q-p);\n\t\tif (offset < 0)\n\t\t\treturn offset;\n\n\t\tp = q;\n\t}\n\n\treturn offset;\n}\n\nint fdt_path_offset(const void *fdt, const char *path)\n{\n\treturn fdt_path_offset_namelen(fdt, path, strlen(path));\n}\n\nconst char *fdt_get_name(const void *fdt, int nodeoffset, int *len)\n{\n\tconst struct fdt_node_header *nh = fdt_offset_ptr_(fdt, nodeoffset);\n\tconst char *nameptr;\n\tint err;\n\n\tif (((err = fdt_ro_probe_(fdt)) < 0)\n\t    || ((err = fdt_check_node_offset_(fdt, nodeoffset)) < 0))\n\t\t\tgoto fail;\n\n\tnameptr = nh->name;\n\n\tif (!can_assume(LATEST) && fdt_version(fdt) < 0x10) {\n\t\t/*\n\t\t * For old FDT versions, match the naming conventions of V16:\n\t\t * give only the leaf name (after all /). The actual tree\n\t\t * contents are loosely checked.\n\t\t */\n\t\tconst char *leaf;\n\t\tleaf = strrchr(nameptr, '/');\n\t\tif (leaf == NULL) {\n\t\t\terr = -FDT_ERR_BADSTRUCTURE;\n\t\t\tgoto fail;\n\t\t}\n\t\tnameptr = leaf+1;\n\t}\n\n\tif (len)\n\t\t*len = strlen(nameptr);\n\n\treturn nameptr;\n\n fail:\n\tif (len)\n\t\t*len = err;\n\treturn NULL;\n}\n\nint fdt_first_property_offset(const void *fdt, int nodeoffset)\n{\n\tint offset;\n\n\tif ((offset = fdt_check_node_offset_(fdt, nodeoffset)) < 0)\n\t\treturn offset;\n\n\treturn nextprop_(fdt, offset);\n}\n\nint fdt_next_property_offset(const void *fdt, int offset)\n{\n\tif ((offset = fdt_check_prop_offset_(fdt, offset)) < 0)\n\t\treturn offset;\n\n\treturn nextprop_(fdt, offset);\n}\n\nstatic const struct fdt_property *fdt_get_property_by_offset_(const void *fdt,\n\t\t\t\t\t\t              int offset,\n\t\t\t\t\t\t              int *lenp)\n{\n\tint err;\n\tconst struct fdt_property *prop;\n\n\tif (!can_assume(VALID_INPUT) &&\n\t    (err = fdt_check_prop_offset_(fdt, offset)) < 0) {\n\t\tif (lenp)\n\t\t\t*lenp = err;\n\t\treturn NULL;\n\t}\n\n\tprop = fdt_offset_ptr_(fdt, offset);\n\n\tif (lenp)\n\t\t*lenp = fdt32_ld_(&prop->len);\n\n\treturn prop;\n}\n\nconst struct fdt_property *fdt_get_property_by_offset(const void *fdt,\n\t\t\t\t\t\t      int offset,\n\t\t\t\t\t\t      int *lenp)\n{\n\t/* Prior to version 16, properties may need realignment\n\t * and this API does not work. fdt_getprop_*() will, however. */\n\n\tif (!can_assume(LATEST) && fdt_version(fdt) < 0x10) {\n\t\tif (lenp)\n\t\t\t*lenp = -FDT_ERR_BADVERSION;\n\t\treturn NULL;\n\t}\n\n\treturn fdt_get_property_by_offset_(fdt, offset, lenp);\n}\n\nstatic const struct fdt_property *fdt_get_property_namelen_(const void *fdt,\n\t\t\t\t\t\t            int offset,\n\t\t\t\t\t\t            const char *name,\n\t\t\t\t\t\t            int namelen,\n\t\t\t\t\t\t\t    int *lenp,\n\t\t\t\t\t\t\t    int *poffset)\n{\n\tfor (offset = fdt_first_property_offset(fdt, offset);\n\t     (offset >= 0);\n\t     (offset = fdt_next_property_offset(fdt, offset))) {\n\t\tconst struct fdt_property *prop;\n\n\t\tprop = fdt_get_property_by_offset_(fdt, offset, lenp);\n\t\tif (!can_assume(LIBFDT_FLAWLESS) && !prop) {\n\t\t\toffset = -FDT_ERR_INTERNAL;\n\t\t\tbreak;\n\t\t}\n\t\tif (fdt_string_eq_(fdt, fdt32_ld_(&prop->nameoff),\n\t\t\t\t   name, namelen)) {\n\t\t\tif (poffset)\n\t\t\t\t*poffset = offset;\n\t\t\treturn prop;\n\t\t}\n\t}\n\n\tif (lenp)\n\t\t*lenp = offset;\n\treturn NULL;\n}\n\n\nconst struct fdt_property *fdt_get_property_namelen(const void *fdt,\n\t\t\t\t\t\t    int offset,\n\t\t\t\t\t\t    const char *name,\n\t\t\t\t\t\t    int namelen, int *lenp)\n{\n\t/* Prior to version 16, properties may need realignment\n\t * and this API does not work. fdt_getprop_*() will, however. */\n\tif (!can_assume(LATEST) && fdt_version(fdt) < 0x10) {\n\t\tif (lenp)\n\t\t\t*lenp = -FDT_ERR_BADVERSION;\n\t\treturn NULL;\n\t}\n\n\treturn fdt_get_property_namelen_(fdt, offset, name, namelen, lenp,\n\t\t\t\t\t NULL);\n}\n\n\nconst struct fdt_property *fdt_get_property(const void *fdt,\n\t\t\t\t\t    int nodeoffset,\n\t\t\t\t\t    const char *name, int *lenp)\n{\n\treturn fdt_get_property_namelen(fdt, nodeoffset, name,\n\t\t\t\t\tstrlen(name), lenp);\n}\n\nconst void *fdt_getprop_namelen(const void *fdt, int nodeoffset,\n\t\t\t\tconst char *name, int namelen, int *lenp)\n{\n\tint poffset;\n\tconst struct fdt_property *prop;\n\n\tprop = fdt_get_property_namelen_(fdt, nodeoffset, name, namelen, lenp,\n\t\t\t\t\t &poffset);\n\tif (!prop)\n\t\treturn NULL;\n\n\t/* Handle realignment */\n\tif (!can_assume(LATEST) && fdt_version(fdt) < 0x10 &&\n\t    (poffset + sizeof(*prop)) % 8 && fdt32_ld_(&prop->len) >= 8)\n\t\treturn prop->data + 4;\n\treturn prop->data;\n}\n\nconst void *fdt_getprop_by_offset(const void *fdt, int offset,\n\t\t\t\t  const char **namep, int *lenp)\n{\n\tconst struct fdt_property *prop;\n\n\tprop = fdt_get_property_by_offset_(fdt, offset, lenp);\n\tif (!prop)\n\t\treturn NULL;\n\tif (namep) {\n\t\tconst char *name;\n\t\tint namelen;\n\n\t\tif (!can_assume(VALID_INPUT)) {\n\t\t\tname = fdt_get_string(fdt, fdt32_ld_(&prop->nameoff),\n\t\t\t\t\t      &namelen);\n\t\t\t*namep = name;\n\t\t\tif (!name) {\n\t\t\t\tif (lenp)\n\t\t\t\t\t*lenp = namelen;\n\t\t\t\treturn NULL;\n\t\t\t}\n\t\t} else {\n\t\t\t*namep = fdt_string(fdt, fdt32_ld_(&prop->nameoff));\n\t\t}\n\t}\n\n\t/* Handle realignment */\n\tif (!can_assume(LATEST) && fdt_version(fdt) < 0x10 &&\n\t    (offset + sizeof(*prop)) % 8 && fdt32_ld_(&prop->len) >= 8)\n\t\treturn prop->data + 4;\n\treturn prop->data;\n}\n\nconst void *fdt_getprop(const void *fdt, int nodeoffset,\n\t\t\tconst char *name, int *lenp)\n{\n\treturn fdt_getprop_namelen(fdt, nodeoffset, name, strlen(name), lenp);\n}\n\nuint32_t fdt_get_phandle(const void *fdt, int nodeoffset)\n{\n\tconst fdt32_t *php;\n\tint len;\n\n\t/* FIXME: This is a bit sub-optimal, since we potentially scan\n\t * over all the properties twice. */\n\tphp = fdt_getprop(fdt, nodeoffset, \"phandle\", &len);\n\tif (!php || (len != sizeof(*php))) {\n\t\tphp = fdt_getprop(fdt, nodeoffset, \"linux,phandle\", &len);\n\t\tif (!php || (len != sizeof(*php)))\n\t\t\treturn 0;\n\t}\n\n\treturn fdt32_ld_(php);\n}\n\nconst char *fdt_get_alias_namelen(const void *fdt,\n\t\t\t\t  const char *name, int namelen)\n{\n\tint aliasoffset;\n\n\taliasoffset = fdt_path_offset(fdt, \"/aliases\");\n\tif (aliasoffset < 0)\n\t\treturn NULL;\n\n\treturn fdt_getprop_namelen(fdt, aliasoffset, name, namelen, NULL);\n}\n\nconst char *fdt_get_alias(const void *fdt, const char *name)\n{\n\treturn fdt_get_alias_namelen(fdt, name, strlen(name));\n}\n\nint fdt_get_path(const void *fdt, int nodeoffset, char *buf, int buflen)\n{\n\tint pdepth = 0, p = 0;\n\tint offset, depth, namelen;\n\tconst char *name;\n\n\tFDT_RO_PROBE(fdt);\n\n\tif (buflen < 2)\n\t\treturn -FDT_ERR_NOSPACE;\n\n\tfor (offset = 0, depth = 0;\n\t     (offset >= 0) && (offset <= nodeoffset);\n\t     offset = fdt_next_node(fdt, offset, &depth)) {\n\t\twhile (pdepth > depth) {\n\t\t\tdo {\n\t\t\t\tp--;\n\t\t\t} while (buf[p-1] != '/');\n\t\t\tpdepth--;\n\t\t}\n\n\t\tif (pdepth >= depth) {\n\t\t\tname = fdt_get_name(fdt, offset, &namelen);\n\t\t\tif (!name)\n\t\t\t\treturn namelen;\n\t\t\tif ((p + namelen + 1) <= buflen) {\n\t\t\t\tmemcpy(buf + p, name, namelen);\n\t\t\t\tp += namelen;\n\t\t\t\tbuf[p++] = '/';\n\t\t\t\tpdepth++;\n\t\t\t}\n\t\t}\n\n\t\tif (offset == nodeoffset) {\n\t\t\tif (pdepth < (depth + 1))\n\t\t\t\treturn -FDT_ERR_NOSPACE;\n\n\t\t\tif (p > 1) /* special case so that root path is \"/\", not \"\" */\n\t\t\t\tp--;\n\t\t\tbuf[p] = '\\0';\n\t\t\treturn 0;\n\t\t}\n\t}\n\n\tif ((offset == -FDT_ERR_NOTFOUND) || (offset >= 0))\n\t\treturn -FDT_ERR_BADOFFSET;\n\telse if (offset == -FDT_ERR_BADOFFSET)\n\t\treturn -FDT_ERR_BADSTRUCTURE;\n\n\treturn offset; /* error from fdt_next_node() */\n}\n\nint fdt_supernode_atdepth_offset(const void *fdt, int nodeoffset,\n\t\t\t\t int supernodedepth, int *nodedepth)\n{\n\tint offset, depth;\n\tint supernodeoffset = -FDT_ERR_INTERNAL;\n\n\tFDT_RO_PROBE(fdt);\n\n\tif (supernodedepth < 0)\n\t\treturn -FDT_ERR_NOTFOUND;\n\n\tfor (offset = 0, depth = 0;\n\t     (offset >= 0) && (offset <= nodeoffset);\n\t     offset = fdt_next_node(fdt, offset, &depth)) {\n\t\tif (depth == supernodedepth)\n\t\t\tsupernodeoffset = offset;\n\n\t\tif (offset == nodeoffset) {\n\t\t\tif (nodedepth)\n\t\t\t\t*nodedepth = depth;\n\n\t\t\tif (supernodedepth > depth)\n\t\t\t\treturn -FDT_ERR_NOTFOUND;\n\t\t\telse\n\t\t\t\treturn supernodeoffset;\n\t\t}\n\t}\n\n\tif (!can_assume(VALID_INPUT)) {\n\t\tif ((offset == -FDT_ERR_NOTFOUND) || (offset >= 0))\n\t\t\treturn -FDT_ERR_BADOFFSET;\n\t\telse if (offset == -FDT_ERR_BADOFFSET)\n\t\t\treturn -FDT_ERR_BADSTRUCTURE;\n\t}\n\n\treturn offset; /* error from fdt_next_node() */\n}\n\nint fdt_node_depth(const void *fdt, int nodeoffset)\n{\n\tint nodedepth;\n\tint err;\n\n\terr = fdt_supernode_atdepth_offset(fdt, nodeoffset, 0, &nodedepth);\n\tif (err)\n\t\treturn (can_assume(LIBFDT_FLAWLESS) || err < 0) ? err :\n\t\t\t-FDT_ERR_INTERNAL;\n\treturn nodedepth;\n}\n\nint fdt_parent_offset(const void *fdt, int nodeoffset)\n{\n\tint nodedepth = fdt_node_depth(fdt, nodeoffset);\n\n\tif (nodedepth < 0)\n\t\treturn nodedepth;\n\treturn fdt_supernode_atdepth_offset(fdt, nodeoffset,\n\t\t\t\t\t    nodedepth - 1, NULL);\n}\n\nint fdt_node_offset_by_prop_value(const void *fdt, int startoffset,\n\t\t\t\t  const char *propname,\n\t\t\t\t  const void *propval, int proplen)\n{\n\tint offset;\n\tconst void *val;\n\tint len;\n\n\tFDT_RO_PROBE(fdt);\n\n\t/* FIXME: The algorithm here is pretty horrible: we scan each\n\t * property of a node in fdt_getprop(), then if that didn't\n\t * find what we want, we scan over them again making our way\n\t * to the next node.  Still it's the easiest to implement\n\t * approach; performance can come later. */\n\tfor (offset = fdt_next_node(fdt, startoffset, NULL);\n\t     offset >= 0;\n\t     offset = fdt_next_node(fdt, offset, NULL)) {\n\t\tval = fdt_getprop(fdt, offset, propname, &len);\n\t\tif (val && (len == proplen)\n\t\t    && (memcmp(val, propval, len) == 0))\n\t\t\treturn offset;\n\t}\n\n\treturn offset; /* error from fdt_next_node() */\n}\n\nint fdt_node_offset_by_phandle(const void *fdt, uint32_t phandle)\n{\n\tint offset;\n\n\tif ((phandle == 0) || (phandle == ~0U))\n\t\treturn -FDT_ERR_BADPHANDLE;\n\n\tFDT_RO_PROBE(fdt);\n\n\t/* FIXME: The algorithm here is pretty horrible: we\n\t * potentially scan each property of a node in\n\t * fdt_get_phandle(), then if that didn't find what\n\t * we want, we scan over them again making our way to the next\n\t * node.  Still it's the easiest to implement approach;\n\t * performance can come later. */\n\tfor (offset = fdt_next_node(fdt, -1, NULL);\n\t     offset >= 0;\n\t     offset = fdt_next_node(fdt, offset, NULL)) {\n\t\tif (fdt_get_phandle(fdt, offset) == phandle)\n\t\t\treturn offset;\n\t}\n\n\treturn offset; /* error from fdt_next_node() */\n}\n\nint fdt_stringlist_contains(const char *strlist, int listlen, const char *str)\n{\n\tint len = strlen(str);\n\tconst char *p;\n\n\twhile (listlen >= len) {\n\t\tif (memcmp(str, strlist, len+1) == 0)\n\t\t\treturn 1;\n\t\tp = memchr(strlist, '\\0', listlen);\n\t\tif (!p)\n\t\t\treturn 0; /* malformed strlist.. */\n\t\tlistlen -= (p-strlist) + 1;\n\t\tstrlist = p + 1;\n\t}\n\treturn 0;\n}\n\nint fdt_stringlist_count(const void *fdt, int nodeoffset, const char *property)\n{\n\tconst char *list, *end;\n\tint length, count = 0;\n\n\tlist = fdt_getprop(fdt, nodeoffset, property, &length);\n\tif (!list)\n\t\treturn length;\n\n\tend = list + length;\n\n\twhile (list < end) {\n\t\tlength = strnlen(list, end - list) + 1;\n\n\t\t/* Abort if the last string isn't properly NUL-terminated. */\n\t\tif (list + length > end)\n\t\t\treturn -FDT_ERR_BADVALUE;\n\n\t\tlist += length;\n\t\tcount++;\n\t}\n\n\treturn count;\n}\n\nint fdt_stringlist_search(const void *fdt, int nodeoffset, const char *property,\n\t\t\t  const char *string)\n{\n\tint length, len, idx = 0;\n\tconst char *list, *end;\n\n\tlist = fdt_getprop(fdt, nodeoffset, property, &length);\n\tif (!list)\n\t\treturn length;\n\n\tlen = strlen(string) + 1;\n\tend = list + length;\n\n\twhile (list < end) {\n\t\tlength = strnlen(list, end - list) + 1;\n\n\t\t/* Abort if the last string isn't properly NUL-terminated. */\n\t\tif (list + length > end)\n\t\t\treturn -FDT_ERR_BADVALUE;\n\n\t\tif (length == len && memcmp(list, string, length) == 0)\n\t\t\treturn idx;\n\n\t\tlist += length;\n\t\tidx++;\n\t}\n\n\treturn -FDT_ERR_NOTFOUND;\n}\n\nconst char *fdt_stringlist_get(const void *fdt, int nodeoffset,\n\t\t\t       const char *property, int idx,\n\t\t\t       int *lenp)\n{\n\tconst char *list, *end;\n\tint length;\n\n\tlist = fdt_getprop(fdt, nodeoffset, property, &length);\n\tif (!list) {\n\t\tif (lenp)\n\t\t\t*lenp = length;\n\n\t\treturn NULL;\n\t}\n\n\tend = list + length;\n\n\twhile (list < end) {\n\t\tlength = strnlen(list, end - list) + 1;\n\n\t\t/* Abort if the last string isn't properly NUL-terminated. */\n\t\tif (list + length > end) {\n\t\t\tif (lenp)\n\t\t\t\t*lenp = -FDT_ERR_BADVALUE;\n\n\t\t\treturn NULL;\n\t\t}\n\n\t\tif (idx == 0) {\n\t\t\tif (lenp)\n\t\t\t\t*lenp = length - 1;\n\n\t\t\treturn list;\n\t\t}\n\n\t\tlist += length;\n\t\tidx--;\n\t}\n\n\tif (lenp)\n\t\t*lenp = -FDT_ERR_NOTFOUND;\n\n\treturn NULL;\n}\n\nint fdt_node_check_compatible(const void *fdt, int nodeoffset,\n\t\t\t      const char *compatible)\n{\n\tconst void *prop;\n\tint len;\n\n\tprop = fdt_getprop(fdt, nodeoffset, \"compatible\", &len);\n\tif (!prop)\n\t\treturn len;\n\n\treturn !fdt_stringlist_contains(prop, len, compatible);\n}\n\nint fdt_node_offset_by_compatible(const void *fdt, int startoffset,\n\t\t\t\t  const char *compatible)\n{\n\tint offset, err;\n\n\tFDT_RO_PROBE(fdt);\n\n\t/* FIXME: The algorithm here is pretty horrible: we scan each\n\t * property of a node in fdt_node_check_compatible(), then if\n\t * that didn't find what we want, we scan over them again\n\t * making our way to the next node.  Still it's the easiest to\n\t * implement approach; performance can come later. */\n\tfor (offset = fdt_next_node(fdt, startoffset, NULL);\n\t     offset >= 0;\n\t     offset = fdt_next_node(fdt, offset, NULL)) {\n\t\terr = fdt_node_check_compatible(fdt, offset, compatible);\n\t\tif ((err < 0) && (err != -FDT_ERR_NOTFOUND))\n\t\t\treturn err;\n\t\telse if (err == 0)\n\t\t\treturn offset;\n\t}\n\n\treturn offset; /* error from fdt_next_node() */\n}\n"
  },
  {
    "path": "external/libfdt/fdt_rw.c",
    "content": "// SPDX-License-Identifier: (GPL-2.0-or-later OR BSD-2-Clause)\n/*\n * libfdt - Flat Device Tree manipulation\n * Copyright (C) 2006 David Gibson, IBM Corporation.\n */\n#include \"libfdt_env.h\"\n\n#include <fdt.h>\n#include <libfdt.h>\n\n#include \"libfdt_internal.h\"\n\nstatic int fdt_blocks_misordered_(const void *fdt,\n\t\t\t\t  int mem_rsv_size, int struct_size)\n{\n\treturn (fdt_off_mem_rsvmap(fdt) < FDT_ALIGN(sizeof(struct fdt_header), 8))\n\t\t|| (fdt_off_dt_struct(fdt) <\n\t\t    (fdt_off_mem_rsvmap(fdt) + mem_rsv_size))\n\t\t|| (fdt_off_dt_strings(fdt) <\n\t\t    (fdt_off_dt_struct(fdt) + struct_size))\n\t\t|| (fdt_totalsize(fdt) <\n\t\t    (fdt_off_dt_strings(fdt) + fdt_size_dt_strings(fdt)));\n}\n\nstatic int fdt_rw_probe_(void *fdt)\n{\n\tif (can_assume(VALID_DTB))\n\t\treturn 0;\n\tFDT_RO_PROBE(fdt);\n\n\tif (!can_assume(LATEST) && fdt_version(fdt) < 17)\n\t\treturn -FDT_ERR_BADVERSION;\n\tif (fdt_blocks_misordered_(fdt, sizeof(struct fdt_reserve_entry),\n\t\t\t\t   fdt_size_dt_struct(fdt)))\n\t\treturn -FDT_ERR_BADLAYOUT;\n\tif (!can_assume(LATEST) && fdt_version(fdt) > 17)\n\t\tfdt_set_version(fdt, 17);\n\n\treturn 0;\n}\n\n#define FDT_RW_PROBE(fdt) \\\n\t{ \\\n\t\tint err_; \\\n\t\tif ((err_ = fdt_rw_probe_(fdt)) != 0) \\\n\t\t\treturn err_; \\\n\t}\n\nstatic inline unsigned int fdt_data_size_(void *fdt)\n{\n\treturn fdt_off_dt_strings(fdt) + fdt_size_dt_strings(fdt);\n}\n\nstatic int fdt_splice_(void *fdt, void *splicepoint, int oldlen, int newlen)\n{\n\tchar *p = splicepoint;\n\tunsigned int dsize = fdt_data_size_(fdt);\n\tsize_t soff = p - (char *)fdt;\n\n\tif ((oldlen < 0) || (soff + oldlen < soff) || (soff + oldlen > dsize))\n\t\treturn -FDT_ERR_BADOFFSET;\n\tif ((p < (char *)fdt) || (dsize + newlen < (unsigned)oldlen))\n\t\treturn -FDT_ERR_BADOFFSET;\n\tif (dsize - oldlen + newlen > fdt_totalsize(fdt))\n\t\treturn -FDT_ERR_NOSPACE;\n\tmemmove(p + newlen, p + oldlen, ((char *)fdt + dsize) - (p + oldlen));\n\treturn 0;\n}\n\nstatic int fdt_splice_mem_rsv_(void *fdt, struct fdt_reserve_entry *p,\n\t\t\t       int oldn, int newn)\n{\n\tint delta = (newn - oldn) * sizeof(*p);\n\tint err;\n\terr = fdt_splice_(fdt, p, oldn * sizeof(*p), newn * sizeof(*p));\n\tif (err)\n\t\treturn err;\n\tfdt_set_off_dt_struct(fdt, fdt_off_dt_struct(fdt) + delta);\n\tfdt_set_off_dt_strings(fdt, fdt_off_dt_strings(fdt) + delta);\n\treturn 0;\n}\n\nstatic int fdt_splice_struct_(void *fdt, void *p,\n\t\t\t      int oldlen, int newlen)\n{\n\tint delta = newlen - oldlen;\n\tint err;\n\n\tif ((err = fdt_splice_(fdt, p, oldlen, newlen)))\n\t\treturn err;\n\n\tfdt_set_size_dt_struct(fdt, fdt_size_dt_struct(fdt) + delta);\n\tfdt_set_off_dt_strings(fdt, fdt_off_dt_strings(fdt) + delta);\n\treturn 0;\n}\n\n/* Must only be used to roll back in case of error */\nstatic void fdt_del_last_string_(void *fdt, const char *s)\n{\n\tint newlen = strlen(s) + 1;\n\n\tfdt_set_size_dt_strings(fdt, fdt_size_dt_strings(fdt) - newlen);\n}\n\nstatic int fdt_splice_string_(void *fdt, int newlen)\n{\n\tvoid *p = (char *)fdt\n\t\t+ fdt_off_dt_strings(fdt) + fdt_size_dt_strings(fdt);\n\tint err;\n\n\tif ((err = fdt_splice_(fdt, p, 0, newlen)))\n\t\treturn err;\n\n\tfdt_set_size_dt_strings(fdt, fdt_size_dt_strings(fdt) + newlen);\n\treturn 0;\n}\n\n/**\n * fdt_find_add_string_() - Find or allocate a string\n *\n * @fdt: pointer to the device tree to check/adjust\n * @s: string to find/add\n * @allocated: Set to 0 if the string was found, 1 if not found and so\n *\tallocated. Ignored if can_assume(NO_ROLLBACK)\n * @return offset of string in the string table (whether found or added)\n */\nstatic int fdt_find_add_string_(void *fdt, const char *s, int *allocated)\n{\n\tchar *strtab = (char *)fdt + fdt_off_dt_strings(fdt);\n\tconst char *p;\n\tchar *new;\n\tint len = strlen(s) + 1;\n\tint err;\n\n\tif (!can_assume(NO_ROLLBACK))\n\t\t*allocated = 0;\n\n\tp = fdt_find_string_(strtab, fdt_size_dt_strings(fdt), s);\n\tif (p)\n\t\t/* found it */\n\t\treturn (p - strtab);\n\n\tnew = strtab + fdt_size_dt_strings(fdt);\n\terr = fdt_splice_string_(fdt, len);\n\tif (err)\n\t\treturn err;\n\n\tif (!can_assume(NO_ROLLBACK))\n\t\t*allocated = 1;\n\n\tmemcpy(new, s, len);\n\treturn (new - strtab);\n}\n\nint fdt_add_mem_rsv(void *fdt, uint64_t address, uint64_t size)\n{\n\tstruct fdt_reserve_entry *re;\n\tint err;\n\n\tFDT_RW_PROBE(fdt);\n\n\tre = fdt_mem_rsv_w_(fdt, fdt_num_mem_rsv(fdt));\n\terr = fdt_splice_mem_rsv_(fdt, re, 0, 1);\n\tif (err)\n\t\treturn err;\n\n\tre->address = cpu_to_fdt64(address);\n\tre->size = cpu_to_fdt64(size);\n\treturn 0;\n}\n\nint fdt_del_mem_rsv(void *fdt, int n)\n{\n\tstruct fdt_reserve_entry *re = fdt_mem_rsv_w_(fdt, n);\n\n\tFDT_RW_PROBE(fdt);\n\n\tif (n >= fdt_num_mem_rsv(fdt))\n\t\treturn -FDT_ERR_NOTFOUND;\n\n\treturn fdt_splice_mem_rsv_(fdt, re, 1, 0);\n}\n\nstatic int fdt_resize_property_(void *fdt, int nodeoffset, const char *name,\n\t\t\t\tint len, struct fdt_property **prop)\n{\n\tint oldlen;\n\tint err;\n\n\t*prop = fdt_get_property_w(fdt, nodeoffset, name, &oldlen);\n\tif (!*prop)\n\t\treturn oldlen;\n\n\tif ((err = fdt_splice_struct_(fdt, (*prop)->data, FDT_TAGALIGN(oldlen),\n\t\t\t\t      FDT_TAGALIGN(len))))\n\t\treturn err;\n\n\t(*prop)->len = cpu_to_fdt32(len);\n\treturn 0;\n}\n\nstatic int fdt_add_property_(void *fdt, int nodeoffset, const char *name,\n\t\t\t     int len, struct fdt_property **prop)\n{\n\tint proplen;\n\tint nextoffset;\n\tint namestroff;\n\tint err;\n\tint allocated;\n\n\tif ((nextoffset = fdt_check_node_offset_(fdt, nodeoffset)) < 0)\n\t\treturn nextoffset;\n\n\tnamestroff = fdt_find_add_string_(fdt, name, &allocated);\n\tif (namestroff < 0)\n\t\treturn namestroff;\n\n\t*prop = fdt_offset_ptr_w_(fdt, nextoffset);\n\tproplen = sizeof(**prop) + FDT_TAGALIGN(len);\n\n\terr = fdt_splice_struct_(fdt, *prop, 0, proplen);\n\tif (err) {\n\t\t/* Delete the string if we failed to add it */\n\t\tif (!can_assume(NO_ROLLBACK) && allocated)\n\t\t\tfdt_del_last_string_(fdt, name);\n\t\treturn err;\n\t}\n\n\t(*prop)->tag = cpu_to_fdt32(FDT_PROP);\n\t(*prop)->nameoff = cpu_to_fdt32(namestroff);\n\t(*prop)->len = cpu_to_fdt32(len);\n\treturn 0;\n}\n\nint fdt_set_name(void *fdt, int nodeoffset, const char *name)\n{\n\tchar *namep;\n\tint oldlen, newlen;\n\tint err;\n\n\tFDT_RW_PROBE(fdt);\n\n\tnamep = (char *)(uintptr_t)fdt_get_name(fdt, nodeoffset, &oldlen);\n\tif (!namep)\n\t\treturn oldlen;\n\n\tnewlen = strlen(name);\n\n\terr = fdt_splice_struct_(fdt, namep, FDT_TAGALIGN(oldlen+1),\n\t\t\t\t FDT_TAGALIGN(newlen+1));\n\tif (err)\n\t\treturn err;\n\n\tmemcpy(namep, name, newlen+1);\n\treturn 0;\n}\n\nint fdt_setprop_placeholder(void *fdt, int nodeoffset, const char *name,\n\t\t\t    int len, void **prop_data)\n{\n\tstruct fdt_property *prop;\n\tint err;\n\n\tFDT_RW_PROBE(fdt);\n\n\terr = fdt_resize_property_(fdt, nodeoffset, name, len, &prop);\n\tif (err == -FDT_ERR_NOTFOUND)\n\t\terr = fdt_add_property_(fdt, nodeoffset, name, len, &prop);\n\tif (err)\n\t\treturn err;\n\n\t*prop_data = prop->data;\n\treturn 0;\n}\n\nint fdt_setprop(void *fdt, int nodeoffset, const char *name,\n\t\tconst void *val, int len)\n{\n\tvoid *prop_data;\n\tint err;\n\n\terr = fdt_setprop_placeholder(fdt, nodeoffset, name, len, &prop_data);\n\tif (err)\n\t\treturn err;\n\n\tif (len)\n\t\tmemcpy(prop_data, val, len);\n\treturn 0;\n}\n\nint fdt_appendprop(void *fdt, int nodeoffset, const char *name,\n\t\t   const void *val, int len)\n{\n\tstruct fdt_property *prop;\n\tint err, oldlen, newlen;\n\n\tFDT_RW_PROBE(fdt);\n\n\tprop = fdt_get_property_w(fdt, nodeoffset, name, &oldlen);\n\tif (prop) {\n\t\tnewlen = len + oldlen;\n\t\terr = fdt_splice_struct_(fdt, prop->data,\n\t\t\t\t\t FDT_TAGALIGN(oldlen),\n\t\t\t\t\t FDT_TAGALIGN(newlen));\n\t\tif (err)\n\t\t\treturn err;\n\t\tprop->len = cpu_to_fdt32(newlen);\n\t\tmemcpy(prop->data + oldlen, val, len);\n\t} else {\n\t\terr = fdt_add_property_(fdt, nodeoffset, name, len, &prop);\n\t\tif (err)\n\t\t\treturn err;\n\t\tmemcpy(prop->data, val, len);\n\t}\n\treturn 0;\n}\n\nint fdt_delprop(void *fdt, int nodeoffset, const char *name)\n{\n\tstruct fdt_property *prop;\n\tint len, proplen;\n\n\tFDT_RW_PROBE(fdt);\n\n\tprop = fdt_get_property_w(fdt, nodeoffset, name, &len);\n\tif (!prop)\n\t\treturn len;\n\n\tproplen = sizeof(*prop) + FDT_TAGALIGN(len);\n\treturn fdt_splice_struct_(fdt, prop, proplen, 0);\n}\n\nint fdt_add_subnode_namelen(void *fdt, int parentoffset,\n\t\t\t    const char *name, int namelen)\n{\n\tstruct fdt_node_header *nh;\n\tint offset, nextoffset;\n\tint nodelen;\n\tint err;\n\tuint32_t tag;\n\tfdt32_t *endtag;\n\n\tFDT_RW_PROBE(fdt);\n\n\toffset = fdt_subnode_offset_namelen(fdt, parentoffset, name, namelen);\n\tif (offset >= 0)\n\t\treturn -FDT_ERR_EXISTS;\n\telse if (offset != -FDT_ERR_NOTFOUND)\n\t\treturn offset;\n\n\t/* Try to place the new node after the parent's properties */\n\ttag = fdt_next_tag(fdt, parentoffset, &nextoffset);\n\t/* the fdt_subnode_offset_namelen() should ensure this never hits */\n\tif (!can_assume(LIBFDT_FLAWLESS) && (tag != FDT_BEGIN_NODE))\n\t\treturn -FDT_ERR_INTERNAL;\n\tdo {\n\t\toffset = nextoffset;\n\t\ttag = fdt_next_tag(fdt, offset, &nextoffset);\n\t} while ((tag == FDT_PROP) || (tag == FDT_NOP));\n\n\tnh = fdt_offset_ptr_w_(fdt, offset);\n\tnodelen = sizeof(*nh) + FDT_TAGALIGN(namelen+1) + FDT_TAGSIZE;\n\n\terr = fdt_splice_struct_(fdt, nh, 0, nodelen);\n\tif (err)\n\t\treturn err;\n\n\tnh->tag = cpu_to_fdt32(FDT_BEGIN_NODE);\n\tmemset(nh->name, 0, FDT_TAGALIGN(namelen+1));\n\tmemcpy(nh->name, name, namelen);\n\tendtag = (fdt32_t *)((char *)nh + nodelen - FDT_TAGSIZE);\n\t*endtag = cpu_to_fdt32(FDT_END_NODE);\n\n\treturn offset;\n}\n\nint fdt_add_subnode(void *fdt, int parentoffset, const char *name)\n{\n\treturn fdt_add_subnode_namelen(fdt, parentoffset, name, strlen(name));\n}\n\nint fdt_del_node(void *fdt, int nodeoffset)\n{\n\tint endoffset;\n\n\tFDT_RW_PROBE(fdt);\n\n\tendoffset = fdt_node_end_offset_(fdt, nodeoffset);\n\tif (endoffset < 0)\n\t\treturn endoffset;\n\n\treturn fdt_splice_struct_(fdt, fdt_offset_ptr_w_(fdt, nodeoffset),\n\t\t\t\t  endoffset - nodeoffset, 0);\n}\n\nstatic void fdt_packblocks_(const char *old, char *new,\n\t\t\t    int mem_rsv_size,\n\t\t\t    int struct_size,\n\t\t\t    int strings_size)\n{\n\tint mem_rsv_off, struct_off, strings_off;\n\n\tmem_rsv_off = FDT_ALIGN(sizeof(struct fdt_header), 8);\n\tstruct_off = mem_rsv_off + mem_rsv_size;\n\tstrings_off = struct_off + struct_size;\n\n\tmemmove(new + mem_rsv_off, old + fdt_off_mem_rsvmap(old), mem_rsv_size);\n\tfdt_set_off_mem_rsvmap(new, mem_rsv_off);\n\n\tmemmove(new + struct_off, old + fdt_off_dt_struct(old), struct_size);\n\tfdt_set_off_dt_struct(new, struct_off);\n\tfdt_set_size_dt_struct(new, struct_size);\n\n\tmemmove(new + strings_off, old + fdt_off_dt_strings(old), strings_size);\n\tfdt_set_off_dt_strings(new, strings_off);\n\tfdt_set_size_dt_strings(new, fdt_size_dt_strings(old));\n}\n\nint fdt_open_into(const void *fdt, void *buf, int bufsize)\n{\n\tint err;\n\tint mem_rsv_size, struct_size;\n\tint newsize;\n\tconst char *fdtstart = fdt;\n\tconst char *fdtend = fdtstart + fdt_totalsize(fdt);\n\tchar *tmp;\n\n\tFDT_RO_PROBE(fdt);\n\n\tmem_rsv_size = (fdt_num_mem_rsv(fdt)+1)\n\t\t* sizeof(struct fdt_reserve_entry);\n\n\tif (can_assume(LATEST) || fdt_version(fdt) >= 17) {\n\t\tstruct_size = fdt_size_dt_struct(fdt);\n\t} else if (fdt_version(fdt) == 16) {\n\t\tstruct_size = 0;\n\t\twhile (fdt_next_tag(fdt, struct_size, &struct_size) != FDT_END)\n\t\t\t;\n\t\tif (struct_size < 0)\n\t\t\treturn struct_size;\n\t} else {\n\t\treturn -FDT_ERR_BADVERSION;\n\t}\n\n\tif (can_assume(LIBFDT_ORDER) ||\n\t    !fdt_blocks_misordered_(fdt, mem_rsv_size, struct_size)) {\n\t\t/* no further work necessary */\n\t\terr = fdt_move(fdt, buf, bufsize);\n\t\tif (err)\n\t\t\treturn err;\n\t\tfdt_set_version(buf, 17);\n\t\tfdt_set_size_dt_struct(buf, struct_size);\n\t\tfdt_set_totalsize(buf, bufsize);\n\t\treturn 0;\n\t}\n\n\t/* Need to reorder */\n\tnewsize = FDT_ALIGN(sizeof(struct fdt_header), 8) + mem_rsv_size\n\t\t+ struct_size + fdt_size_dt_strings(fdt);\n\n\tif (bufsize < newsize)\n\t\treturn -FDT_ERR_NOSPACE;\n\n\t/* First attempt to build converted tree at beginning of buffer */\n\ttmp = buf;\n\t/* But if that overlaps with the old tree... */\n\tif (((tmp + newsize) > fdtstart) && (tmp < fdtend)) {\n\t\t/* Try right after the old tree instead */\n\t\ttmp = (char *)(uintptr_t)fdtend;\n\t\tif ((tmp + newsize) > ((char *)buf + bufsize))\n\t\t\treturn -FDT_ERR_NOSPACE;\n\t}\n\n\tfdt_packblocks_(fdt, tmp, mem_rsv_size, struct_size,\n\t\t\tfdt_size_dt_strings(fdt));\n\tmemmove(buf, tmp, newsize);\n\n\tfdt_set_magic(buf, FDT_MAGIC);\n\tfdt_set_totalsize(buf, bufsize);\n\tfdt_set_version(buf, 17);\n\tfdt_set_last_comp_version(buf, 16);\n\tfdt_set_boot_cpuid_phys(buf, fdt_boot_cpuid_phys(fdt));\n\n\treturn 0;\n}\n\nint fdt_pack(void *fdt)\n{\n\tint mem_rsv_size;\n\n\tFDT_RW_PROBE(fdt);\n\n\tmem_rsv_size = (fdt_num_mem_rsv(fdt)+1)\n\t\t* sizeof(struct fdt_reserve_entry);\n\tfdt_packblocks_(fdt, fdt, mem_rsv_size, fdt_size_dt_struct(fdt),\n\t\t\tfdt_size_dt_strings(fdt));\n\tfdt_set_totalsize(fdt, fdt_data_size_(fdt));\n\n\treturn 0;\n}\n"
  },
  {
    "path": "external/libfdt/fdt_strerror.c",
    "content": "// SPDX-License-Identifier: (GPL-2.0-or-later OR BSD-2-Clause)\n/*\n * libfdt - Flat Device Tree manipulation\n * Copyright (C) 2006 David Gibson, IBM Corporation.\n *     EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n */\n#include \"libfdt_env.h\"\n\n#include <fdt.h>\n#include <libfdt.h>\n\n#include \"libfdt_internal.h\"\n\nstruct fdt_errtabent {\n\tconst char *str;\n};\n\n#define FDT_ERRTABENT(val) \\\n\t[(val)] = { .str = #val, }\n\nstatic struct fdt_errtabent fdt_errtable[] = {\n\tFDT_ERRTABENT(FDT_ERR_NOTFOUND),\n\tFDT_ERRTABENT(FDT_ERR_EXISTS),\n\tFDT_ERRTABENT(FDT_ERR_NOSPACE),\n\n\tFDT_ERRTABENT(FDT_ERR_BADOFFSET),\n\tFDT_ERRTABENT(FDT_ERR_BADPATH),\n\tFDT_ERRTABENT(FDT_ERR_BADPHANDLE),\n\tFDT_ERRTABENT(FDT_ERR_BADSTATE),\n\n\tFDT_ERRTABENT(FDT_ERR_TRUNCATED),\n\tFDT_ERRTABENT(FDT_ERR_BADMAGIC),\n\tFDT_ERRTABENT(FDT_ERR_BADVERSION),\n\tFDT_ERRTABENT(FDT_ERR_BADSTRUCTURE),\n\tFDT_ERRTABENT(FDT_ERR_BADLAYOUT),\n\tFDT_ERRTABENT(FDT_ERR_INTERNAL),\n\tFDT_ERRTABENT(FDT_ERR_BADNCELLS),\n\tFDT_ERRTABENT(FDT_ERR_BADVALUE),\n\tFDT_ERRTABENT(FDT_ERR_BADOVERLAY),\n\tFDT_ERRTABENT(FDT_ERR_NOPHANDLES),\n\tFDT_ERRTABENT(FDT_ERR_BADFLAGS),\n\tFDT_ERRTABENT(FDT_ERR_ALIGNMENT),\n};\n#define FDT_ERRTABSIZE\t((int)(sizeof(fdt_errtable) / sizeof(fdt_errtable[0])))\n\nconst char *fdt_strerror(int errval)\n{\n\tif (errval > 0)\n\t\treturn \"<valid offset/length>\";\n\telse if (errval == 0)\n\t\treturn \"<no error>\";\n\telse if (-errval < FDT_ERRTABSIZE) {\n\t\tconst char *s = fdt_errtable[-errval].str;\n\n\t\tif (s)\n\t\t\treturn s;\n\t}\n\n\treturn \"<unknown error>\";\n}\n"
  },
  {
    "path": "external/libfdt/fdt_sw.c",
    "content": "// SPDX-License-Identifier: (GPL-2.0-or-later OR BSD-2-Clause)\n/*\n * libfdt - Flat Device Tree manipulation\n * Copyright (C) 2006 David Gibson, IBM Corporation.\n */\n#include \"libfdt_env.h\"\n\n#include <fdt.h>\n#include <libfdt.h>\n\n#include \"libfdt_internal.h\"\n\nstatic int fdt_sw_probe_(void *fdt)\n{\n\tif (!can_assume(VALID_INPUT)) {\n\t\tif (fdt_magic(fdt) == FDT_MAGIC)\n\t\t\treturn -FDT_ERR_BADSTATE;\n\t\telse if (fdt_magic(fdt) != FDT_SW_MAGIC)\n\t\t\treturn -FDT_ERR_BADMAGIC;\n\t}\n\n\treturn 0;\n}\n\n#define FDT_SW_PROBE(fdt) \\\n\t{ \\\n\t\tint err; \\\n\t\tif ((err = fdt_sw_probe_(fdt)) != 0) \\\n\t\t\treturn err; \\\n\t}\n\n/* 'memrsv' state:\tInitial state after fdt_create()\n *\n * Allowed functions:\n *\tfdt_add_reservemap_entry()\n *\tfdt_finish_reservemap()\t\t[moves to 'struct' state]\n */\nstatic int fdt_sw_probe_memrsv_(void *fdt)\n{\n\tint err = fdt_sw_probe_(fdt);\n\tif (err)\n\t\treturn err;\n\n\tif (!can_assume(VALID_INPUT) && fdt_off_dt_strings(fdt) != 0)\n\t\treturn -FDT_ERR_BADSTATE;\n\treturn 0;\n}\n\n#define FDT_SW_PROBE_MEMRSV(fdt) \\\n\t{ \\\n\t\tint err; \\\n\t\tif ((err = fdt_sw_probe_memrsv_(fdt)) != 0) \\\n\t\t\treturn err; \\\n\t}\n\n/* 'struct' state:\tEnter this state after fdt_finish_reservemap()\n *\n * Allowed functions:\n *\tfdt_begin_node()\n *\tfdt_end_node()\n *\tfdt_property*()\n *\tfdt_finish()\t\t\t[moves to 'complete' state]\n */\nstatic int fdt_sw_probe_struct_(void *fdt)\n{\n\tint err = fdt_sw_probe_(fdt);\n\tif (err)\n\t\treturn err;\n\n\tif (!can_assume(VALID_INPUT) &&\n\t    fdt_off_dt_strings(fdt) != fdt_totalsize(fdt))\n\t\treturn -FDT_ERR_BADSTATE;\n\treturn 0;\n}\n\n#define FDT_SW_PROBE_STRUCT(fdt) \\\n\t{ \\\n\t\tint err; \\\n\t\tif ((err = fdt_sw_probe_struct_(fdt)) != 0) \\\n\t\t\treturn err; \\\n\t}\n\nstatic inline uint32_t sw_flags(void *fdt)\n{\n\t/* assert: (fdt_magic(fdt) == FDT_SW_MAGIC) */\n\treturn fdt_last_comp_version(fdt);\n}\n\n/* 'complete' state:\tEnter this state after fdt_finish()\n *\n * Allowed functions: none\n */\n\nstatic void *fdt_grab_space_(void *fdt, size_t len)\n{\n\tunsigned int offset = fdt_size_dt_struct(fdt);\n\tunsigned int spaceleft;\n\n\tspaceleft = fdt_totalsize(fdt) - fdt_off_dt_struct(fdt)\n\t\t- fdt_size_dt_strings(fdt);\n\n\tif ((offset + len < offset) || (offset + len > spaceleft))\n\t\treturn NULL;\n\n\tfdt_set_size_dt_struct(fdt, offset + len);\n\treturn fdt_offset_ptr_w_(fdt, offset);\n}\n\nint fdt_create_with_flags(void *buf, int bufsize, uint32_t flags)\n{\n\tconst int hdrsize = FDT_ALIGN(sizeof(struct fdt_header),\n\t\t\t\t      sizeof(struct fdt_reserve_entry));\n\tvoid *fdt = buf;\n\n\tif (bufsize < hdrsize)\n\t\treturn -FDT_ERR_NOSPACE;\n\n\tif (flags & ~FDT_CREATE_FLAGS_ALL)\n\t\treturn -FDT_ERR_BADFLAGS;\n\n\tmemset(buf, 0, bufsize);\n\n\t/*\n\t * magic and last_comp_version keep intermediate state during the fdt\n\t * creation process, which is replaced with the proper FDT format by\n\t * fdt_finish().\n\t *\n\t * flags should be accessed with sw_flags().\n\t */\n\tfdt_set_magic(fdt, FDT_SW_MAGIC);\n\tfdt_set_version(fdt, FDT_LAST_SUPPORTED_VERSION);\n\tfdt_set_last_comp_version(fdt, flags);\n\n\tfdt_set_totalsize(fdt,  bufsize);\n\n\tfdt_set_off_mem_rsvmap(fdt, hdrsize);\n\tfdt_set_off_dt_struct(fdt, fdt_off_mem_rsvmap(fdt));\n\tfdt_set_off_dt_strings(fdt, 0);\n\n\treturn 0;\n}\n\nint fdt_create(void *buf, int bufsize)\n{\n\treturn fdt_create_with_flags(buf, bufsize, 0);\n}\n\nint fdt_resize(void *fdt, void *buf, int bufsize)\n{\n\tsize_t headsize, tailsize;\n\tchar *oldtail, *newtail;\n\n\tFDT_SW_PROBE(fdt);\n\n\tif (bufsize < 0)\n\t\treturn -FDT_ERR_NOSPACE;\n\n\theadsize = fdt_off_dt_struct(fdt) + fdt_size_dt_struct(fdt);\n\ttailsize = fdt_size_dt_strings(fdt);\n\n\tif (!can_assume(VALID_DTB) &&\n\t    headsize + tailsize > fdt_totalsize(fdt))\n\t\treturn -FDT_ERR_INTERNAL;\n\n\tif ((headsize + tailsize) > (unsigned)bufsize)\n\t\treturn -FDT_ERR_NOSPACE;\n\n\toldtail = (char *)fdt + fdt_totalsize(fdt) - tailsize;\n\tnewtail = (char *)buf + bufsize - tailsize;\n\n\t/* Two cases to avoid clobbering data if the old and new\n\t * buffers partially overlap */\n\tif (buf <= fdt) {\n\t\tmemmove(buf, fdt, headsize);\n\t\tmemmove(newtail, oldtail, tailsize);\n\t} else {\n\t\tmemmove(newtail, oldtail, tailsize);\n\t\tmemmove(buf, fdt, headsize);\n\t}\n\n\tfdt_set_totalsize(buf, bufsize);\n\tif (fdt_off_dt_strings(buf))\n\t\tfdt_set_off_dt_strings(buf, bufsize);\n\n\treturn 0;\n}\n\nint fdt_add_reservemap_entry(void *fdt, uint64_t addr, uint64_t size)\n{\n\tstruct fdt_reserve_entry *re;\n\tint offset;\n\n\tFDT_SW_PROBE_MEMRSV(fdt);\n\n\toffset = fdt_off_dt_struct(fdt);\n\tif ((offset + sizeof(*re)) > fdt_totalsize(fdt))\n\t\treturn -FDT_ERR_NOSPACE;\n\n\tre = (struct fdt_reserve_entry *)((char *)fdt + offset);\n\tre->address = cpu_to_fdt64(addr);\n\tre->size = cpu_to_fdt64(size);\n\n\tfdt_set_off_dt_struct(fdt, offset + sizeof(*re));\n\n\treturn 0;\n}\n\nint fdt_finish_reservemap(void *fdt)\n{\n\tint err = fdt_add_reservemap_entry(fdt, 0, 0);\n\n\tif (err)\n\t\treturn err;\n\n\tfdt_set_off_dt_strings(fdt, fdt_totalsize(fdt));\n\treturn 0;\n}\n\nint fdt_begin_node(void *fdt, const char *name)\n{\n\tstruct fdt_node_header *nh;\n\tint namelen;\n\n\tFDT_SW_PROBE_STRUCT(fdt);\n\n\tnamelen = strlen(name) + 1;\n\tnh = fdt_grab_space_(fdt, sizeof(*nh) + FDT_TAGALIGN(namelen));\n\tif (! nh)\n\t\treturn -FDT_ERR_NOSPACE;\n\n\tnh->tag = cpu_to_fdt32(FDT_BEGIN_NODE);\n\tmemcpy(nh->name, name, namelen);\n\treturn 0;\n}\n\nint fdt_end_node(void *fdt)\n{\n\tfdt32_t *en;\n\n\tFDT_SW_PROBE_STRUCT(fdt);\n\n\ten = fdt_grab_space_(fdt, FDT_TAGSIZE);\n\tif (! en)\n\t\treturn -FDT_ERR_NOSPACE;\n\n\t*en = cpu_to_fdt32(FDT_END_NODE);\n\treturn 0;\n}\n\nstatic int fdt_add_string_(void *fdt, const char *s)\n{\n\tchar *strtab = (char *)fdt + fdt_totalsize(fdt);\n\tunsigned int strtabsize = fdt_size_dt_strings(fdt);\n\tunsigned int len = strlen(s) + 1;\n\tunsigned int struct_top, offset;\n\n\toffset = strtabsize + len;\n\tstruct_top = fdt_off_dt_struct(fdt) + fdt_size_dt_struct(fdt);\n\tif (fdt_totalsize(fdt) - offset < struct_top)\n\t\treturn 0; /* no more room :( */\n\n\tmemcpy(strtab - offset, s, len);\n\tfdt_set_size_dt_strings(fdt, strtabsize + len);\n\treturn -offset;\n}\n\n/* Must only be used to roll back in case of error */\nstatic void fdt_del_last_string_(void *fdt, const char *s)\n{\n\tint strtabsize = fdt_size_dt_strings(fdt);\n\tint len = strlen(s) + 1;\n\n\tfdt_set_size_dt_strings(fdt, strtabsize - len);\n}\n\nstatic int fdt_find_add_string_(void *fdt, const char *s, int *allocated)\n{\n\tchar *strtab = (char *)fdt + fdt_totalsize(fdt);\n\tint strtabsize = fdt_size_dt_strings(fdt);\n\tconst char *p;\n\n\t*allocated = 0;\n\n\tp = fdt_find_string_(strtab - strtabsize, strtabsize, s);\n\tif (p)\n\t\treturn p - strtab;\n\n\t*allocated = 1;\n\n\treturn fdt_add_string_(fdt, s);\n}\n\nint fdt_property_placeholder(void *fdt, const char *name, int len, void **valp)\n{\n\tstruct fdt_property *prop;\n\tint nameoff;\n\tint allocated;\n\n\tFDT_SW_PROBE_STRUCT(fdt);\n\n\t/* String de-duplication can be slow, _NO_NAME_DEDUP skips it */\n\tif (sw_flags(fdt) & FDT_CREATE_FLAG_NO_NAME_DEDUP) {\n\t\tallocated = 1;\n\t\tnameoff = fdt_add_string_(fdt, name);\n\t} else {\n\t\tnameoff = fdt_find_add_string_(fdt, name, &allocated);\n\t}\n\tif (nameoff == 0)\n\t\treturn -FDT_ERR_NOSPACE;\n\n\tprop = fdt_grab_space_(fdt, sizeof(*prop) + FDT_TAGALIGN(len));\n\tif (! prop) {\n\t\tif (allocated)\n\t\t\tfdt_del_last_string_(fdt, name);\n\t\treturn -FDT_ERR_NOSPACE;\n\t}\n\n\tprop->tag = cpu_to_fdt32(FDT_PROP);\n\tprop->nameoff = cpu_to_fdt32(nameoff);\n\tprop->len = cpu_to_fdt32(len);\n\t*valp = prop->data;\n\treturn 0;\n}\n\nint fdt_property(void *fdt, const char *name, const void *val, int len)\n{\n\tvoid *ptr;\n\tint ret;\n\n\tret = fdt_property_placeholder(fdt, name, len, &ptr);\n\tif (ret)\n\t\treturn ret;\n\tmemcpy(ptr, val, len);\n\treturn 0;\n}\n\nint fdt_finish(void *fdt)\n{\n\tchar *p = (char *)fdt;\n\tfdt32_t *end;\n\tint oldstroffset, newstroffset;\n\tuint32_t tag;\n\tint offset, nextoffset;\n\n\tFDT_SW_PROBE_STRUCT(fdt);\n\n\t/* Add terminator */\n\tend = fdt_grab_space_(fdt, sizeof(*end));\n\tif (! end)\n\t\treturn -FDT_ERR_NOSPACE;\n\t*end = cpu_to_fdt32(FDT_END);\n\n\t/* Relocate the string table */\n\toldstroffset = fdt_totalsize(fdt) - fdt_size_dt_strings(fdt);\n\tnewstroffset = fdt_off_dt_struct(fdt) + fdt_size_dt_struct(fdt);\n\tmemmove(p + newstroffset, p + oldstroffset, fdt_size_dt_strings(fdt));\n\tfdt_set_off_dt_strings(fdt, newstroffset);\n\n\t/* Walk the structure, correcting string offsets */\n\toffset = 0;\n\twhile ((tag = fdt_next_tag(fdt, offset, &nextoffset)) != FDT_END) {\n\t\tif (tag == FDT_PROP) {\n\t\t\tstruct fdt_property *prop =\n\t\t\t\tfdt_offset_ptr_w_(fdt, offset);\n\t\t\tint nameoff;\n\n\t\t\tnameoff = fdt32_to_cpu(prop->nameoff);\n\t\t\tnameoff += fdt_size_dt_strings(fdt);\n\t\t\tprop->nameoff = cpu_to_fdt32(nameoff);\n\t\t}\n\t\toffset = nextoffset;\n\t}\n\tif (nextoffset < 0)\n\t\treturn nextoffset;\n\n\t/* Finally, adjust the header */\n\tfdt_set_totalsize(fdt, newstroffset + fdt_size_dt_strings(fdt));\n\n\t/* And fix up fields that were keeping intermediate state. */\n\tfdt_set_last_comp_version(fdt, FDT_LAST_COMPATIBLE_VERSION);\n\tfdt_set_magic(fdt, FDT_MAGIC);\n\n\treturn 0;\n}\n"
  },
  {
    "path": "external/libfdt/fdt_wip.c",
    "content": "// SPDX-License-Identifier: (GPL-2.0-or-later OR BSD-2-Clause)\n/*\n * libfdt - Flat Device Tree manipulation\n * Copyright (C) 2006 David Gibson, IBM Corporation.\n */\n#include \"libfdt_env.h\"\n\n#include <fdt.h>\n#include <libfdt.h>\n\n#include \"libfdt_internal.h\"\n\nint fdt_setprop_inplace_namelen_partial(void *fdt, int nodeoffset,\n\t\t\t\t\tconst char *name, int namelen,\n\t\t\t\t\tuint32_t idx, const void *val,\n\t\t\t\t\tint len)\n{\n\tvoid *propval;\n\tint proplen;\n\n\tpropval = fdt_getprop_namelen_w(fdt, nodeoffset, name, namelen,\n\t\t\t\t\t&proplen);\n\tif (!propval)\n\t\treturn proplen;\n\n\tif ((unsigned)proplen < (len + idx))\n\t\treturn -FDT_ERR_NOSPACE;\n\n\tmemcpy((char *)propval + idx, val, len);\n\treturn 0;\n}\n\nint fdt_setprop_inplace(void *fdt, int nodeoffset, const char *name,\n\t\t\tconst void *val, int len)\n{\n\tconst void *propval;\n\tint proplen;\n\n\tpropval = fdt_getprop(fdt, nodeoffset, name, &proplen);\n\tif (!propval)\n\t\treturn proplen;\n\n\tif (proplen != len)\n\t\treturn -FDT_ERR_NOSPACE;\n\n\treturn fdt_setprop_inplace_namelen_partial(fdt, nodeoffset, name,\n\t\t\t\t\t\t   strlen(name), 0,\n\t\t\t\t\t\t   val, len);\n}\n\nstatic void fdt_nop_region_(void *start, int len)\n{\n\tfdt32_t *p;\n\n\tfor (p = start; (char *)p < ((char *)start + len); p++)\n\t\t*p = cpu_to_fdt32(FDT_NOP);\n}\n\nint fdt_nop_property(void *fdt, int nodeoffset, const char *name)\n{\n\tstruct fdt_property *prop;\n\tint len;\n\n\tprop = fdt_get_property_w(fdt, nodeoffset, name, &len);\n\tif (!prop)\n\t\treturn len;\n\n\tfdt_nop_region_(prop, len + sizeof(*prop));\n\n\treturn 0;\n}\n\nint fdt_node_end_offset_(void *fdt, int offset)\n{\n\tint depth = 0;\n\n\twhile ((offset >= 0) && (depth >= 0))\n\t\toffset = fdt_next_node(fdt, offset, &depth);\n\n\treturn offset;\n}\n\nint fdt_nop_node(void *fdt, int nodeoffset)\n{\n\tint endoffset;\n\n\tendoffset = fdt_node_end_offset_(fdt, nodeoffset);\n\tif (endoffset < 0)\n\t\treturn endoffset;\n\n\tfdt_nop_region_(fdt_offset_ptr_w(fdt, nodeoffset, 0),\n\t\t\tendoffset - nodeoffset);\n\treturn 0;\n}\n"
  },
  {
    "path": "external/libfdt/libfdt.h",
    "content": "/* SPDX-License-Identifier: (GPL-2.0-or-later OR BSD-2-Clause) */\n#ifndef LIBFDT_H\n#define LIBFDT_H\n/*\n * libfdt - Flat Device Tree manipulation\n * Copyright (C) 2006 David Gibson, IBM Corporation.\n */\n\n#include <libfdt_env.h>\n#include <fdt.h>\n\n#ifdef __cplusplus\nextern \"C\" {\n#endif\n\n#define FDT_FIRST_SUPPORTED_VERSION\t0x02\n#define FDT_LAST_COMPATIBLE_VERSION 0x10\n#define FDT_LAST_SUPPORTED_VERSION\t0x11\n\n/* Error codes: informative error codes */\n#define FDT_ERR_NOTFOUND\t1\n\t/* FDT_ERR_NOTFOUND: The requested node or property does not exist */\n#define FDT_ERR_EXISTS\t\t2\n\t/* FDT_ERR_EXISTS: Attempted to create a node or property which\n\t * already exists */\n#define FDT_ERR_NOSPACE\t\t3\n\t/* FDT_ERR_NOSPACE: Operation needed to expand the device\n\t * tree, but its buffer did not have sufficient space to\n\t * contain the expanded tree. Use fdt_open_into() to move the\n\t * device tree to a buffer with more space. */\n\n/* Error codes: codes for bad parameters */\n#define FDT_ERR_BADOFFSET\t4\n\t/* FDT_ERR_BADOFFSET: Function was passed a structure block\n\t * offset which is out-of-bounds, or which points to an\n\t * unsuitable part of the structure for the operation. */\n#define FDT_ERR_BADPATH\t\t5\n\t/* FDT_ERR_BADPATH: Function was passed a badly formatted path\n\t * (e.g. missing a leading / for a function which requires an\n\t * absolute path) */\n#define FDT_ERR_BADPHANDLE\t6\n\t/* FDT_ERR_BADPHANDLE: Function was passed an invalid phandle.\n\t * This can be caused either by an invalid phandle property\n\t * length, or the phandle value was either 0 or -1, which are\n\t * not permitted. */\n#define FDT_ERR_BADSTATE\t7\n\t/* FDT_ERR_BADSTATE: Function was passed an incomplete device\n\t * tree created by the sequential-write functions, which is\n\t * not sufficiently complete for the requested operation. */\n\n/* Error codes: codes for bad device tree blobs */\n#define FDT_ERR_TRUNCATED\t8\n\t/* FDT_ERR_TRUNCATED: FDT or a sub-block is improperly\n\t * terminated (overflows, goes outside allowed bounds, or\n\t * isn't properly terminated).  */\n#define FDT_ERR_BADMAGIC\t9\n\t/* FDT_ERR_BADMAGIC: Given \"device tree\" appears not to be a\n\t * device tree at all - it is missing the flattened device\n\t * tree magic number. */\n#define FDT_ERR_BADVERSION\t10\n\t/* FDT_ERR_BADVERSION: Given device tree has a version which\n\t * can't be handled by the requested operation.  For\n\t * read-write functions, this may mean that fdt_open_into() is\n\t * required to convert the tree to the expected version. */\n#define FDT_ERR_BADSTRUCTURE\t11\n\t/* FDT_ERR_BADSTRUCTURE: Given device tree has a corrupt\n\t * structure block or other serious error (e.g. misnested\n\t * nodes, or subnodes preceding properties). */\n#define FDT_ERR_BADLAYOUT\t12\n\t/* FDT_ERR_BADLAYOUT: For read-write functions, the given\n\t * device tree has it's sub-blocks in an order that the\n\t * function can't handle (memory reserve map, then structure,\n\t * then strings).  Use fdt_open_into() to reorganize the tree\n\t * into a form suitable for the read-write operations. */\n\n/* \"Can't happen\" error indicating a bug in libfdt */\n#define FDT_ERR_INTERNAL\t13\n\t/* FDT_ERR_INTERNAL: libfdt has failed an internal assertion.\n\t * Should never be returned, if it is, it indicates a bug in\n\t * libfdt itself. */\n\n/* Errors in device tree content */\n#define FDT_ERR_BADNCELLS\t14\n\t/* FDT_ERR_BADNCELLS: Device tree has a #address-cells, #size-cells\n\t * or similar property with a bad format or value */\n\n#define FDT_ERR_BADVALUE\t15\n\t/* FDT_ERR_BADVALUE: Device tree has a property with an unexpected\n\t * value. For example: a property expected to contain a string list\n\t * is not NUL-terminated within the length of its value. */\n\n#define FDT_ERR_BADOVERLAY\t16\n\t/* FDT_ERR_BADOVERLAY: The device tree overlay, while\n\t * correctly structured, cannot be applied due to some\n\t * unexpected or missing value, property or node. */\n\n#define FDT_ERR_NOPHANDLES\t17\n\t/* FDT_ERR_NOPHANDLES: The device tree doesn't have any\n\t * phandle available anymore without causing an overflow */\n\n#define FDT_ERR_BADFLAGS\t18\n\t/* FDT_ERR_BADFLAGS: The function was passed a flags field that\n\t * contains invalid flags or an invalid combination of flags. */\n\n#define FDT_ERR_ALIGNMENT\t19\n\t/* FDT_ERR_ALIGNMENT: The device tree base address is not 8-byte\n\t * aligned. */\n\n#define FDT_ERR_MAX\t\t19\n\n/* constants */\n#define FDT_MAX_PHANDLE 0xfffffffe\n\t/* Valid values for phandles range from 1 to 2^32-2. */\n\n/**********************************************************************/\n/* Low-level functions (you probably don't need these)                */\n/**********************************************************************/\n\n#ifndef SWIG /* This function is not useful in Python */\nconst void *fdt_offset_ptr(const void *fdt, int offset, unsigned int checklen);\n#endif\nstatic inline void *fdt_offset_ptr_w(void *fdt, int offset, int checklen)\n{\n\treturn (void *)(uintptr_t)fdt_offset_ptr(fdt, offset, checklen);\n}\n\nuint32_t fdt_next_tag(const void *fdt, int offset, int *nextoffset);\n\n/*\n * External helpers to access words from a device tree blob. They're built\n * to work even with unaligned pointers on platforms (such as ARMv5) that don't\n * like unaligned loads and stores.\n */\nstatic inline uint16_t fdt16_ld(const fdt16_t *p)\n{\n\tconst uint8_t *bp = (const uint8_t *)p;\n\n\treturn ((uint16_t)bp[0] << 8) | bp[1];\n}\n\nstatic inline uint32_t fdt32_ld(const fdt32_t *p)\n{\n\tconst uint8_t *bp = (const uint8_t *)p;\n\n\treturn ((uint32_t)bp[0] << 24)\n\t\t| ((uint32_t)bp[1] << 16)\n\t\t| ((uint32_t)bp[2] << 8)\n\t\t| bp[3];\n}\n\nstatic inline void fdt32_st(void *property, uint32_t value)\n{\n\tuint8_t *bp = (uint8_t *)property;\n\n\tbp[0] = value >> 24;\n\tbp[1] = (value >> 16) & 0xff;\n\tbp[2] = (value >> 8) & 0xff;\n\tbp[3] = value & 0xff;\n}\n\nstatic inline uint64_t fdt64_ld(const fdt64_t *p)\n{\n\tconst uint8_t *bp = (const uint8_t *)p;\n\n\treturn ((uint64_t)bp[0] << 56)\n\t\t| ((uint64_t)bp[1] << 48)\n\t\t| ((uint64_t)bp[2] << 40)\n\t\t| ((uint64_t)bp[3] << 32)\n\t\t| ((uint64_t)bp[4] << 24)\n\t\t| ((uint64_t)bp[5] << 16)\n\t\t| ((uint64_t)bp[6] << 8)\n\t\t| bp[7];\n}\n\nstatic inline void fdt64_st(void *property, uint64_t value)\n{\n\tuint8_t *bp = (uint8_t *)property;\n\n\tbp[0] = value >> 56;\n\tbp[1] = (value >> 48) & 0xff;\n\tbp[2] = (value >> 40) & 0xff;\n\tbp[3] = (value >> 32) & 0xff;\n\tbp[4] = (value >> 24) & 0xff;\n\tbp[5] = (value >> 16) & 0xff;\n\tbp[6] = (value >> 8) & 0xff;\n\tbp[7] = value & 0xff;\n}\n\n/**********************************************************************/\n/* Traversal functions                                                */\n/**********************************************************************/\n\nint fdt_next_node(const void *fdt, int offset, int *depth);\n\n/**\n * fdt_first_subnode() - get offset of first direct subnode\n * @fdt:\tFDT blob\n * @offset:\tOffset of node to check\n *\n * Return: offset of first subnode, or -FDT_ERR_NOTFOUND if there is none\n */\nint fdt_first_subnode(const void *fdt, int offset);\n\n/**\n * fdt_next_subnode() - get offset of next direct subnode\n * @fdt:\tFDT blob\n * @offset:\tOffset of previous subnode\n *\n * After first calling fdt_first_subnode(), call this function repeatedly to\n * get direct subnodes of a parent node.\n *\n * Return: offset of next subnode, or -FDT_ERR_NOTFOUND if there are no more\n *         subnodes\n */\nint fdt_next_subnode(const void *fdt, int offset);\n\n/**\n * fdt_for_each_subnode - iterate over all subnodes of a parent\n *\n * @node:\tchild node (int, lvalue)\n * @fdt:\tFDT blob (const void *)\n * @parent:\tparent node (int)\n *\n * This is actually a wrapper around a for loop and would be used like so:\n *\n *\tfdt_for_each_subnode(node, fdt, parent) {\n *\t\tUse node\n *\t\t...\n *\t}\n *\n *\tif ((node < 0) && (node != -FDT_ERR_NOTFOUND)) {\n *\t\tError handling\n *\t}\n *\n * Note that this is implemented as a macro and @node is used as\n * iterator in the loop. The parent variable be constant or even a\n * literal.\n */\n#define fdt_for_each_subnode(node, fdt, parent)\t\t\\\n\tfor (node = fdt_first_subnode(fdt, parent);\t\\\n\t     node >= 0;\t\t\t\t\t\\\n\t     node = fdt_next_subnode(fdt, node))\n\n/**********************************************************************/\n/* General functions                                                  */\n/**********************************************************************/\n#define fdt_get_header(fdt, field) \\\n\t(fdt32_ld(&((const struct fdt_header *)(fdt))->field))\n#define fdt_magic(fdt)\t\t\t(fdt_get_header(fdt, magic))\n#define fdt_totalsize(fdt)\t\t(fdt_get_header(fdt, totalsize))\n#define fdt_off_dt_struct(fdt)\t\t(fdt_get_header(fdt, off_dt_struct))\n#define fdt_off_dt_strings(fdt)\t\t(fdt_get_header(fdt, off_dt_strings))\n#define fdt_off_mem_rsvmap(fdt)\t\t(fdt_get_header(fdt, off_mem_rsvmap))\n#define fdt_version(fdt)\t\t(fdt_get_header(fdt, version))\n#define fdt_last_comp_version(fdt)\t(fdt_get_header(fdt, last_comp_version))\n#define fdt_boot_cpuid_phys(fdt)\t(fdt_get_header(fdt, boot_cpuid_phys))\n#define fdt_size_dt_strings(fdt)\t(fdt_get_header(fdt, size_dt_strings))\n#define fdt_size_dt_struct(fdt)\t\t(fdt_get_header(fdt, size_dt_struct))\n\n#define fdt_set_hdr_(name) \\\n\tstatic inline void fdt_set_##name(void *fdt, uint32_t val) \\\n\t{ \\\n\t\tstruct fdt_header *fdth = (struct fdt_header *)fdt; \\\n\t\tfdth->name = cpu_to_fdt32(val); \\\n\t}\nfdt_set_hdr_(magic);\nfdt_set_hdr_(totalsize);\nfdt_set_hdr_(off_dt_struct);\nfdt_set_hdr_(off_dt_strings);\nfdt_set_hdr_(off_mem_rsvmap);\nfdt_set_hdr_(version);\nfdt_set_hdr_(last_comp_version);\nfdt_set_hdr_(boot_cpuid_phys);\nfdt_set_hdr_(size_dt_strings);\nfdt_set_hdr_(size_dt_struct);\n#undef fdt_set_hdr_\n\n/**\n * fdt_header_size - return the size of the tree's header\n * @fdt: pointer to a flattened device tree\n *\n * Return: size of DTB header in bytes\n */\nsize_t fdt_header_size(const void *fdt);\n\n/**\n * fdt_header_size_ - internal function to get header size from a version number\n * @version: devicetree version number\n *\n * Return: size of DTB header in bytes\n */\nsize_t fdt_header_size_(uint32_t version);\n\n/**\n * fdt_check_header - sanity check a device tree header\n * @fdt: pointer to data which might be a flattened device tree\n *\n * fdt_check_header() checks that the given buffer contains what\n * appears to be a flattened device tree, and that the header contains\n * valid information (to the extent that can be determined from the\n * header alone).\n *\n * returns:\n *     0, if the buffer appears to contain a valid device tree\n *     -FDT_ERR_BADMAGIC,\n *     -FDT_ERR_BADVERSION,\n *     -FDT_ERR_BADSTATE,\n *     -FDT_ERR_TRUNCATED, standard meanings, as above\n */\nint fdt_check_header(const void *fdt);\n\n/**\n * fdt_move - move a device tree around in memory\n * @fdt: pointer to the device tree to move\n * @buf: pointer to memory where the device is to be moved\n * @bufsize: size of the memory space at buf\n *\n * fdt_move() relocates, if possible, the device tree blob located at\n * fdt to the buffer at buf of size bufsize.  The buffer may overlap\n * with the existing device tree blob at fdt.  Therefore,\n *     fdt_move(fdt, fdt, fdt_totalsize(fdt))\n * should always succeed.\n *\n * returns:\n *     0, on success\n *     -FDT_ERR_NOSPACE, bufsize is insufficient to contain the device tree\n *     -FDT_ERR_BADMAGIC,\n *     -FDT_ERR_BADVERSION,\n *     -FDT_ERR_BADSTATE, standard meanings\n */\nint fdt_move(const void *fdt, void *buf, int bufsize);\n\n/**********************************************************************/\n/* Read-only functions                                                */\n/**********************************************************************/\n\nint fdt_check_full(const void *fdt, size_t bufsize);\n\n/**\n * fdt_get_string - retrieve a string from the strings block of a device tree\n * @fdt: pointer to the device tree blob\n * @stroffset: offset of the string within the strings block (native endian)\n * @lenp: optional pointer to return the string's length\n *\n * fdt_get_string() retrieves a pointer to a single string from the\n * strings block of the device tree blob at fdt, and optionally also\n * returns the string's length in *lenp.\n *\n * returns:\n *     a pointer to the string, on success\n *     NULL, if stroffset is out of bounds, or doesn't point to a valid string\n */\nconst char *fdt_get_string(const void *fdt, int stroffset, int *lenp);\n\n/**\n * fdt_string - retrieve a string from the strings block of a device tree\n * @fdt: pointer to the device tree blob\n * @stroffset: offset of the string within the strings block (native endian)\n *\n * fdt_string() retrieves a pointer to a single string from the\n * strings block of the device tree blob at fdt.\n *\n * returns:\n *     a pointer to the string, on success\n *     NULL, if stroffset is out of bounds, or doesn't point to a valid string\n */\nconst char *fdt_string(const void *fdt, int stroffset);\n\n/**\n * fdt_find_max_phandle - find and return the highest phandle in a tree\n * @fdt: pointer to the device tree blob\n * @phandle: return location for the highest phandle value found in the tree\n *\n * fdt_find_max_phandle() finds the highest phandle value in the given device\n * tree. The value returned in @phandle is only valid if the function returns\n * success.\n *\n * returns:\n *     0 on success or a negative error code on failure\n */\nint fdt_find_max_phandle(const void *fdt, uint32_t *phandle);\n\n/**\n * fdt_get_max_phandle - retrieves the highest phandle in a tree\n * @fdt: pointer to the device tree blob\n *\n * fdt_get_max_phandle retrieves the highest phandle in the given\n * device tree. This will ignore badly formatted phandles, or phandles\n * with a value of 0 or -1.\n *\n * This function is deprecated in favour of fdt_find_max_phandle().\n *\n * returns:\n *      the highest phandle on success\n *      0, if no phandle was found in the device tree\n *      -1, if an error occurred\n */\nstatic inline uint32_t fdt_get_max_phandle(const void *fdt)\n{\n\tuint32_t phandle;\n\tint err;\n\n\terr = fdt_find_max_phandle(fdt, &phandle);\n\tif (err < 0)\n\t\treturn (uint32_t)-1;\n\n\treturn phandle;\n}\n\n/**\n * fdt_generate_phandle - return a new, unused phandle for a device tree blob\n * @fdt: pointer to the device tree blob\n * @phandle: return location for the new phandle\n *\n * Walks the device tree blob and looks for the highest phandle value. On\n * success, the new, unused phandle value (one higher than the previously\n * highest phandle value in the device tree blob) will be returned in the\n * @phandle parameter.\n *\n * Return: 0 on success or a negative error-code on failure\n */\nint fdt_generate_phandle(const void *fdt, uint32_t *phandle);\n\n/**\n * fdt_num_mem_rsv - retrieve the number of memory reserve map entries\n * @fdt: pointer to the device tree blob\n *\n * Returns the number of entries in the device tree blob's memory\n * reservation map.  This does not include the terminating 0,0 entry\n * or any other (0,0) entries reserved for expansion.\n *\n * returns:\n *     the number of entries\n */\nint fdt_num_mem_rsv(const void *fdt);\n\n/**\n * fdt_get_mem_rsv - retrieve one memory reserve map entry\n * @fdt: pointer to the device tree blob\n * @n: index of reserve map entry\n * @address: pointer to 64-bit variable to hold the start address\n * @size: pointer to 64-bit variable to hold the size of the entry\n *\n * On success, @address and @size will contain the address and size of\n * the n-th reserve map entry from the device tree blob, in\n * native-endian format.\n *\n * returns:\n *     0, on success\n *     -FDT_ERR_BADMAGIC,\n *     -FDT_ERR_BADVERSION,\n *     -FDT_ERR_BADSTATE, standard meanings\n */\nint fdt_get_mem_rsv(const void *fdt, int n, uint64_t *address, uint64_t *size);\n\n/**\n * fdt_subnode_offset_namelen - find a subnode based on substring\n * @fdt: pointer to the device tree blob\n * @parentoffset: structure block offset of a node\n * @name: name of the subnode to locate\n * @namelen: number of characters of name to consider\n *\n * Identical to fdt_subnode_offset(), but only examine the first\n * namelen characters of name for matching the subnode name.  This is\n * useful for finding subnodes based on a portion of a larger string,\n * such as a full path.\n *\n * Return: offset of the subnode or -FDT_ERR_NOTFOUND if name not found.\n */\n#ifndef SWIG /* Not available in Python */\nint fdt_subnode_offset_namelen(const void *fdt, int parentoffset,\n\t\t\t       const char *name, int namelen);\n#endif\n/**\n * fdt_subnode_offset - find a subnode of a given node\n * @fdt: pointer to the device tree blob\n * @parentoffset: structure block offset of a node\n * @name: name of the subnode to locate\n *\n * fdt_subnode_offset() finds a subnode of the node at structure block\n * offset parentoffset with the given name.  name may include a unit\n * address, in which case fdt_subnode_offset() will find the subnode\n * with that unit address, or the unit address may be omitted, in\n * which case fdt_subnode_offset() will find an arbitrary subnode\n * whose name excluding unit address matches the given name.\n *\n * returns:\n *\tstructure block offset of the requested subnode (>=0), on success\n *\t-FDT_ERR_NOTFOUND, if the requested subnode does not exist\n *\t-FDT_ERR_BADOFFSET, if parentoffset did not point to an FDT_BEGIN_NODE\n *\t\ttag\n *\t-FDT_ERR_BADMAGIC,\n *\t-FDT_ERR_BADVERSION,\n *\t-FDT_ERR_BADSTATE,\n *\t-FDT_ERR_BADSTRUCTURE,\n *\t-FDT_ERR_TRUNCATED, standard meanings.\n */\nint fdt_subnode_offset(const void *fdt, int parentoffset, const char *name);\n\n/**\n * fdt_path_offset_namelen - find a tree node by its full path\n * @fdt: pointer to the device tree blob\n * @path: full path of the node to locate\n * @namelen: number of characters of path to consider\n *\n * Identical to fdt_path_offset(), but only consider the first namelen\n * characters of path as the path name.\n *\n * Return: offset of the node or negative libfdt error value otherwise\n */\n#ifndef SWIG /* Not available in Python */\nint fdt_path_offset_namelen(const void *fdt, const char *path, int namelen);\n#endif\n\n/**\n * fdt_path_offset - find a tree node by its full path\n * @fdt: pointer to the device tree blob\n * @path: full path of the node to locate\n *\n * fdt_path_offset() finds a node of a given path in the device tree.\n * Each path component may omit the unit address portion, but the\n * results of this are undefined if any such path component is\n * ambiguous (that is if there are multiple nodes at the relevant\n * level matching the given component, differentiated only by unit\n * address).\n *\n * returns:\n *\tstructure block offset of the node with the requested path (>=0), on\n *\t\tsuccess\n *\t-FDT_ERR_BADPATH, given path does not begin with '/' or is invalid\n *\t-FDT_ERR_NOTFOUND, if the requested node does not exist\n *      -FDT_ERR_BADMAGIC,\n *\t-FDT_ERR_BADVERSION,\n *\t-FDT_ERR_BADSTATE,\n *\t-FDT_ERR_BADSTRUCTURE,\n *\t-FDT_ERR_TRUNCATED, standard meanings.\n */\nint fdt_path_offset(const void *fdt, const char *path);\n\n/**\n * fdt_get_name - retrieve the name of a given node\n * @fdt: pointer to the device tree blob\n * @nodeoffset: structure block offset of the starting node\n * @lenp: pointer to an integer variable (will be overwritten) or NULL\n *\n * fdt_get_name() retrieves the name (including unit address) of the\n * device tree node at structure block offset nodeoffset.  If lenp is\n * non-NULL, the length of this name is also returned, in the integer\n * pointed to by lenp.\n *\n * returns:\n *\tpointer to the node's name, on success\n *\t\tIf lenp is non-NULL, *lenp contains the length of that name\n *\t\t\t(>=0)\n *\tNULL, on error\n *\t\tif lenp is non-NULL *lenp contains an error code (<0):\n *\t\t-FDT_ERR_BADOFFSET, nodeoffset did not point to FDT_BEGIN_NODE\n *\t\t\ttag\n *\t\t-FDT_ERR_BADMAGIC,\n *\t\t-FDT_ERR_BADVERSION,\n *\t\t-FDT_ERR_BADSTATE, standard meanings\n */\nconst char *fdt_get_name(const void *fdt, int nodeoffset, int *lenp);\n\n/**\n * fdt_first_property_offset - find the offset of a node's first property\n * @fdt: pointer to the device tree blob\n * @nodeoffset: structure block offset of a node\n *\n * fdt_first_property_offset() finds the first property of the node at\n * the given structure block offset.\n *\n * returns:\n *\tstructure block offset of the property (>=0), on success\n *\t-FDT_ERR_NOTFOUND, if the requested node has no properties\n *\t-FDT_ERR_BADOFFSET, if nodeoffset did not point to an FDT_BEGIN_NODE tag\n *      -FDT_ERR_BADMAGIC,\n *\t-FDT_ERR_BADVERSION,\n *\t-FDT_ERR_BADSTATE,\n *\t-FDT_ERR_BADSTRUCTURE,\n *\t-FDT_ERR_TRUNCATED, standard meanings.\n */\nint fdt_first_property_offset(const void *fdt, int nodeoffset);\n\n/**\n * fdt_next_property_offset - step through a node's properties\n * @fdt: pointer to the device tree blob\n * @offset: structure block offset of a property\n *\n * fdt_next_property_offset() finds the property immediately after the\n * one at the given structure block offset.  This will be a property\n * of the same node as the given property.\n *\n * returns:\n *\tstructure block offset of the next property (>=0), on success\n *\t-FDT_ERR_NOTFOUND, if the given property is the last in its node\n *\t-FDT_ERR_BADOFFSET, if nodeoffset did not point to an FDT_PROP tag\n *      -FDT_ERR_BADMAGIC,\n *\t-FDT_ERR_BADVERSION,\n *\t-FDT_ERR_BADSTATE,\n *\t-FDT_ERR_BADSTRUCTURE,\n *\t-FDT_ERR_TRUNCATED, standard meanings.\n */\nint fdt_next_property_offset(const void *fdt, int offset);\n\n/**\n * fdt_for_each_property_offset - iterate over all properties of a node\n *\n * @property:\tproperty offset (int, lvalue)\n * @fdt:\tFDT blob (const void *)\n * @node:\tnode offset (int)\n *\n * This is actually a wrapper around a for loop and would be used like so:\n *\n *\tfdt_for_each_property_offset(property, fdt, node) {\n *\t\tUse property\n *\t\t...\n *\t}\n *\n *\tif ((property < 0) && (property != -FDT_ERR_NOTFOUND)) {\n *\t\tError handling\n *\t}\n *\n * Note that this is implemented as a macro and property is used as\n * iterator in the loop. The node variable can be constant or even a\n * literal.\n */\n#define fdt_for_each_property_offset(property, fdt, node)\t\\\n\tfor (property = fdt_first_property_offset(fdt, node);\t\\\n\t     property >= 0;\t\t\t\t\t\\\n\t     property = fdt_next_property_offset(fdt, property))\n\n/**\n * fdt_get_property_by_offset - retrieve the property at a given offset\n * @fdt: pointer to the device tree blob\n * @offset: offset of the property to retrieve\n * @lenp: pointer to an integer variable (will be overwritten) or NULL\n *\n * fdt_get_property_by_offset() retrieves a pointer to the\n * fdt_property structure within the device tree blob at the given\n * offset.  If lenp is non-NULL, the length of the property value is\n * also returned, in the integer pointed to by lenp.\n *\n * Note that this code only works on device tree versions >= 16. fdt_getprop()\n * works on all versions.\n *\n * returns:\n *\tpointer to the structure representing the property\n *\t\tif lenp is non-NULL, *lenp contains the length of the property\n *\t\tvalue (>=0)\n *\tNULL, on error\n *\t\tif lenp is non-NULL, *lenp contains an error code (<0):\n *\t\t-FDT_ERR_BADOFFSET, nodeoffset did not point to FDT_PROP tag\n *\t\t-FDT_ERR_BADMAGIC,\n *\t\t-FDT_ERR_BADVERSION,\n *\t\t-FDT_ERR_BADSTATE,\n *\t\t-FDT_ERR_BADSTRUCTURE,\n *\t\t-FDT_ERR_TRUNCATED, standard meanings\n */\nconst struct fdt_property *fdt_get_property_by_offset(const void *fdt,\n\t\t\t\t\t\t      int offset,\n\t\t\t\t\t\t      int *lenp);\n\n/**\n * fdt_get_property_namelen - find a property based on substring\n * @fdt: pointer to the device tree blob\n * @nodeoffset: offset of the node whose property to find\n * @name: name of the property to find\n * @namelen: number of characters of name to consider\n * @lenp: pointer to an integer variable (will be overwritten) or NULL\n *\n * Identical to fdt_get_property(), but only examine the first namelen\n * characters of name for matching the property name.\n *\n * Return: pointer to the structure representing the property, or NULL\n *         if not found\n */\n#ifndef SWIG /* Not available in Python */\nconst struct fdt_property *fdt_get_property_namelen(const void *fdt,\n\t\t\t\t\t\t    int nodeoffset,\n\t\t\t\t\t\t    const char *name,\n\t\t\t\t\t\t    int namelen, int *lenp);\n#endif\n\n/**\n * fdt_get_property - find a given property in a given node\n * @fdt: pointer to the device tree blob\n * @nodeoffset: offset of the node whose property to find\n * @name: name of the property to find\n * @lenp: pointer to an integer variable (will be overwritten) or NULL\n *\n * fdt_get_property() retrieves a pointer to the fdt_property\n * structure within the device tree blob corresponding to the property\n * named 'name' of the node at offset nodeoffset.  If lenp is\n * non-NULL, the length of the property value is also returned, in the\n * integer pointed to by lenp.\n *\n * returns:\n *\tpointer to the structure representing the property\n *\t\tif lenp is non-NULL, *lenp contains the length of the property\n *\t\tvalue (>=0)\n *\tNULL, on error\n *\t\tif lenp is non-NULL, *lenp contains an error code (<0):\n *\t\t-FDT_ERR_NOTFOUND, node does not have named property\n *\t\t-FDT_ERR_BADOFFSET, nodeoffset did not point to FDT_BEGIN_NODE\n *\t\t\ttag\n *\t\t-FDT_ERR_BADMAGIC,\n *\t\t-FDT_ERR_BADVERSION,\n *\t\t-FDT_ERR_BADSTATE,\n *\t\t-FDT_ERR_BADSTRUCTURE,\n *\t\t-FDT_ERR_TRUNCATED, standard meanings\n */\nconst struct fdt_property *fdt_get_property(const void *fdt, int nodeoffset,\n\t\t\t\t\t    const char *name, int *lenp);\nstatic inline struct fdt_property *fdt_get_property_w(void *fdt, int nodeoffset,\n\t\t\t\t\t\t      const char *name,\n\t\t\t\t\t\t      int *lenp)\n{\n\treturn (struct fdt_property *)(uintptr_t)\n\t\tfdt_get_property(fdt, nodeoffset, name, lenp);\n}\n\n/**\n * fdt_getprop_by_offset - retrieve the value of a property at a given offset\n * @fdt: pointer to the device tree blob\n * @offset: offset of the property to read\n * @namep: pointer to a string variable (will be overwritten) or NULL\n * @lenp: pointer to an integer variable (will be overwritten) or NULL\n *\n * fdt_getprop_by_offset() retrieves a pointer to the value of the\n * property at structure block offset 'offset' (this will be a pointer\n * to within the device blob itself, not a copy of the value).  If\n * lenp is non-NULL, the length of the property value is also\n * returned, in the integer pointed to by lenp.  If namep is non-NULL,\n * the property's namne will also be returned in the char * pointed to\n * by namep (this will be a pointer to within the device tree's string\n * block, not a new copy of the name).\n *\n * returns:\n *\tpointer to the property's value\n *\t\tif lenp is non-NULL, *lenp contains the length of the property\n *\t\tvalue (>=0)\n *\t\tif namep is non-NULL *namep contiains a pointer to the property\n *\t\tname.\n *\tNULL, on error\n *\t\tif lenp is non-NULL, *lenp contains an error code (<0):\n *\t\t-FDT_ERR_BADOFFSET, nodeoffset did not point to FDT_PROP tag\n *\t\t-FDT_ERR_BADMAGIC,\n *\t\t-FDT_ERR_BADVERSION,\n *\t\t-FDT_ERR_BADSTATE,\n *\t\t-FDT_ERR_BADSTRUCTURE,\n *\t\t-FDT_ERR_TRUNCATED, standard meanings\n */\n#ifndef SWIG /* This function is not useful in Python */\nconst void *fdt_getprop_by_offset(const void *fdt, int offset,\n\t\t\t\t  const char **namep, int *lenp);\n#endif\n\n/**\n * fdt_getprop_namelen - get property value based on substring\n * @fdt: pointer to the device tree blob\n * @nodeoffset: offset of the node whose property to find\n * @name: name of the property to find\n * @namelen: number of characters of name to consider\n * @lenp: pointer to an integer variable (will be overwritten) or NULL\n *\n * Identical to fdt_getprop(), but only examine the first namelen\n * characters of name for matching the property name.\n *\n * Return: pointer to the property's value or NULL on error\n */\n#ifndef SWIG /* Not available in Python */\nconst void *fdt_getprop_namelen(const void *fdt, int nodeoffset,\n\t\t\t\tconst char *name, int namelen, int *lenp);\nstatic inline void *fdt_getprop_namelen_w(void *fdt, int nodeoffset,\n\t\t\t\t\t  const char *name, int namelen,\n\t\t\t\t\t  int *lenp)\n{\n\treturn (void *)(uintptr_t)fdt_getprop_namelen(fdt, nodeoffset, name,\n\t\t\t\t\t\t      namelen, lenp);\n}\n#endif\n\n/**\n * fdt_getprop - retrieve the value of a given property\n * @fdt: pointer to the device tree blob\n * @nodeoffset: offset of the node whose property to find\n * @name: name of the property to find\n * @lenp: pointer to an integer variable (will be overwritten) or NULL\n *\n * fdt_getprop() retrieves a pointer to the value of the property\n * named @name of the node at offset @nodeoffset (this will be a\n * pointer to within the device blob itself, not a copy of the value).\n * If @lenp is non-NULL, the length of the property value is also\n * returned, in the integer pointed to by @lenp.\n *\n * returns:\n *\tpointer to the property's value\n *\t\tif lenp is non-NULL, *lenp contains the length of the property\n *\t\tvalue (>=0)\n *\tNULL, on error\n *\t\tif lenp is non-NULL, *lenp contains an error code (<0):\n *\t\t-FDT_ERR_NOTFOUND, node does not have named property\n *\t\t-FDT_ERR_BADOFFSET, nodeoffset did not point to FDT_BEGIN_NODE\n *\t\t\ttag\n *\t\t-FDT_ERR_BADMAGIC,\n *\t\t-FDT_ERR_BADVERSION,\n *\t\t-FDT_ERR_BADSTATE,\n *\t\t-FDT_ERR_BADSTRUCTURE,\n *\t\t-FDT_ERR_TRUNCATED, standard meanings\n */\nconst void *fdt_getprop(const void *fdt, int nodeoffset,\n\t\t\tconst char *name, int *lenp);\nstatic inline void *fdt_getprop_w(void *fdt, int nodeoffset,\n\t\t\t\t  const char *name, int *lenp)\n{\n\treturn (void *)(uintptr_t)fdt_getprop(fdt, nodeoffset, name, lenp);\n}\n\n/**\n * fdt_get_phandle - retrieve the phandle of a given node\n * @fdt: pointer to the device tree blob\n * @nodeoffset: structure block offset of the node\n *\n * fdt_get_phandle() retrieves the phandle of the device tree node at\n * structure block offset nodeoffset.\n *\n * returns:\n *\tthe phandle of the node at nodeoffset, on success (!= 0, != -1)\n *\t0, if the node has no phandle, or another error occurs\n */\nuint32_t fdt_get_phandle(const void *fdt, int nodeoffset);\n\n/**\n * fdt_get_alias_namelen - get alias based on substring\n * @fdt: pointer to the device tree blob\n * @name: name of the alias th look up\n * @namelen: number of characters of name to consider\n *\n * Identical to fdt_get_alias(), but only examine the first @namelen\n * characters of @name for matching the alias name.\n *\n * Return: a pointer to the expansion of the alias named @name, if it exists,\n *\t   NULL otherwise\n */\n#ifndef SWIG /* Not available in Python */\nconst char *fdt_get_alias_namelen(const void *fdt,\n\t\t\t\t  const char *name, int namelen);\n#endif\n\n/**\n * fdt_get_alias - retrieve the path referenced by a given alias\n * @fdt: pointer to the device tree blob\n * @name: name of the alias th look up\n *\n * fdt_get_alias() retrieves the value of a given alias.  That is, the\n * value of the property named @name in the node /aliases.\n *\n * returns:\n *\ta pointer to the expansion of the alias named 'name', if it exists\n *\tNULL, if the given alias or the /aliases node does not exist\n */\nconst char *fdt_get_alias(const void *fdt, const char *name);\n\n/**\n * fdt_get_path - determine the full path of a node\n * @fdt: pointer to the device tree blob\n * @nodeoffset: offset of the node whose path to find\n * @buf: character buffer to contain the returned path (will be overwritten)\n * @buflen: size of the character buffer at buf\n *\n * fdt_get_path() computes the full path of the node at offset\n * nodeoffset, and records that path in the buffer at buf.\n *\n * NOTE: This function is expensive, as it must scan the device tree\n * structure from the start to nodeoffset.\n *\n * returns:\n *\t0, on success\n *\t\tbuf contains the absolute path of the node at\n *\t\tnodeoffset, as a NUL-terminated string.\n *\t-FDT_ERR_BADOFFSET, nodeoffset does not refer to a BEGIN_NODE tag\n *\t-FDT_ERR_NOSPACE, the path of the given node is longer than (bufsize-1)\n *\t\tcharacters and will not fit in the given buffer.\n *\t-FDT_ERR_BADMAGIC,\n *\t-FDT_ERR_BADVERSION,\n *\t-FDT_ERR_BADSTATE,\n *\t-FDT_ERR_BADSTRUCTURE, standard meanings\n */\nint fdt_get_path(const void *fdt, int nodeoffset, char *buf, int buflen);\n\n/**\n * fdt_supernode_atdepth_offset - find a specific ancestor of a node\n * @fdt: pointer to the device tree blob\n * @nodeoffset: offset of the node whose parent to find\n * @supernodedepth: depth of the ancestor to find\n * @nodedepth: pointer to an integer variable (will be overwritten) or NULL\n *\n * fdt_supernode_atdepth_offset() finds an ancestor of the given node\n * at a specific depth from the root (where the root itself has depth\n * 0, its immediate subnodes depth 1 and so forth).  So\n *\tfdt_supernode_atdepth_offset(fdt, nodeoffset, 0, NULL);\n * will always return 0, the offset of the root node.  If the node at\n * nodeoffset has depth D, then:\n *\tfdt_supernode_atdepth_offset(fdt, nodeoffset, D, NULL);\n * will return nodeoffset itself.\n *\n * NOTE: This function is expensive, as it must scan the device tree\n * structure from the start to nodeoffset.\n *\n * returns:\n *\tstructure block offset of the node at node offset's ancestor\n *\t\tof depth supernodedepth (>=0), on success\n *\t-FDT_ERR_BADOFFSET, nodeoffset does not refer to a BEGIN_NODE tag\n *\t-FDT_ERR_NOTFOUND, supernodedepth was greater than the depth of\n *\t\tnodeoffset\n *\t-FDT_ERR_BADMAGIC,\n *\t-FDT_ERR_BADVERSION,\n *\t-FDT_ERR_BADSTATE,\n *\t-FDT_ERR_BADSTRUCTURE, standard meanings\n */\nint fdt_supernode_atdepth_offset(const void *fdt, int nodeoffset,\n\t\t\t\t int supernodedepth, int *nodedepth);\n\n/**\n * fdt_node_depth - find the depth of a given node\n * @fdt: pointer to the device tree blob\n * @nodeoffset: offset of the node whose parent to find\n *\n * fdt_node_depth() finds the depth of a given node.  The root node\n * has depth 0, its immediate subnodes depth 1 and so forth.\n *\n * NOTE: This function is expensive, as it must scan the device tree\n * structure from the start to nodeoffset.\n *\n * returns:\n *\tdepth of the node at nodeoffset (>=0), on success\n *\t-FDT_ERR_BADOFFSET, nodeoffset does not refer to a BEGIN_NODE tag\n *\t-FDT_ERR_BADMAGIC,\n *\t-FDT_ERR_BADVERSION,\n *\t-FDT_ERR_BADSTATE,\n *\t-FDT_ERR_BADSTRUCTURE, standard meanings\n */\nint fdt_node_depth(const void *fdt, int nodeoffset);\n\n/**\n * fdt_parent_offset - find the parent of a given node\n * @fdt: pointer to the device tree blob\n * @nodeoffset: offset of the node whose parent to find\n *\n * fdt_parent_offset() locates the parent node of a given node (that\n * is, it finds the offset of the node which contains the node at\n * nodeoffset as a subnode).\n *\n * NOTE: This function is expensive, as it must scan the device tree\n * structure from the start to nodeoffset, *twice*.\n *\n * returns:\n *\tstructure block offset of the parent of the node at nodeoffset\n *\t\t(>=0), on success\n *\t-FDT_ERR_BADOFFSET, nodeoffset does not refer to a BEGIN_NODE tag\n *\t-FDT_ERR_BADMAGIC,\n *\t-FDT_ERR_BADVERSION,\n *\t-FDT_ERR_BADSTATE,\n *\t-FDT_ERR_BADSTRUCTURE, standard meanings\n */\nint fdt_parent_offset(const void *fdt, int nodeoffset);\n\n/**\n * fdt_node_offset_by_prop_value - find nodes with a given property value\n * @fdt: pointer to the device tree blob\n * @startoffset: only find nodes after this offset\n * @propname: property name to check\n * @propval: property value to search for\n * @proplen: length of the value in propval\n *\n * fdt_node_offset_by_prop_value() returns the offset of the first\n * node after startoffset, which has a property named propname whose\n * value is of length proplen and has value equal to propval; or if\n * startoffset is -1, the very first such node in the tree.\n *\n * To iterate through all nodes matching the criterion, the following\n * idiom can be used:\n *\toffset = fdt_node_offset_by_prop_value(fdt, -1, propname,\n *\t\t\t\t\t       propval, proplen);\n *\twhile (offset != -FDT_ERR_NOTFOUND) {\n *\t\t// other code here\n *\t\toffset = fdt_node_offset_by_prop_value(fdt, offset, propname,\n *\t\t\t\t\t\t       propval, proplen);\n *\t}\n *\n * Note the -1 in the first call to the function, if 0 is used here\n * instead, the function will never locate the root node, even if it\n * matches the criterion.\n *\n * returns:\n *\tstructure block offset of the located node (>= 0, >startoffset),\n *\t\t on success\n *\t-FDT_ERR_NOTFOUND, no node matching the criterion exists in the\n *\t\ttree after startoffset\n *\t-FDT_ERR_BADOFFSET, nodeoffset does not refer to a BEGIN_NODE tag\n *\t-FDT_ERR_BADMAGIC,\n *\t-FDT_ERR_BADVERSION,\n *\t-FDT_ERR_BADSTATE,\n *\t-FDT_ERR_BADSTRUCTURE, standard meanings\n */\nint fdt_node_offset_by_prop_value(const void *fdt, int startoffset,\n\t\t\t\t  const char *propname,\n\t\t\t\t  const void *propval, int proplen);\n\n/**\n * fdt_node_offset_by_phandle - find the node with a given phandle\n * @fdt: pointer to the device tree blob\n * @phandle: phandle value\n *\n * fdt_node_offset_by_phandle() returns the offset of the node\n * which has the given phandle value.  If there is more than one node\n * in the tree with the given phandle (an invalid tree), results are\n * undefined.\n *\n * returns:\n *\tstructure block offset of the located node (>= 0), on success\n *\t-FDT_ERR_NOTFOUND, no node with that phandle exists\n *\t-FDT_ERR_BADPHANDLE, given phandle value was invalid (0 or -1)\n *\t-FDT_ERR_BADMAGIC,\n *\t-FDT_ERR_BADVERSION,\n *\t-FDT_ERR_BADSTATE,\n *\t-FDT_ERR_BADSTRUCTURE, standard meanings\n */\nint fdt_node_offset_by_phandle(const void *fdt, uint32_t phandle);\n\n/**\n * fdt_node_check_compatible - check a node's compatible property\n * @fdt: pointer to the device tree blob\n * @nodeoffset: offset of a tree node\n * @compatible: string to match against\n *\n * fdt_node_check_compatible() returns 0 if the given node contains a\n * @compatible property with the given string as one of its elements,\n * it returns non-zero otherwise, or on error.\n *\n * returns:\n *\t0, if the node has a 'compatible' property listing the given string\n *\t1, if the node has a 'compatible' property, but it does not list\n *\t\tthe given string\n *\t-FDT_ERR_NOTFOUND, if the given node has no 'compatible' property\n *\t-FDT_ERR_BADOFFSET, if nodeoffset does not refer to a BEGIN_NODE tag\n *\t-FDT_ERR_BADMAGIC,\n *\t-FDT_ERR_BADVERSION,\n *\t-FDT_ERR_BADSTATE,\n *\t-FDT_ERR_BADSTRUCTURE, standard meanings\n */\nint fdt_node_check_compatible(const void *fdt, int nodeoffset,\n\t\t\t      const char *compatible);\n\n/**\n * fdt_node_offset_by_compatible - find nodes with a given 'compatible' value\n * @fdt: pointer to the device tree blob\n * @startoffset: only find nodes after this offset\n * @compatible: 'compatible' string to match against\n *\n * fdt_node_offset_by_compatible() returns the offset of the first\n * node after startoffset, which has a 'compatible' property which\n * lists the given compatible string; or if startoffset is -1, the\n * very first such node in the tree.\n *\n * To iterate through all nodes matching the criterion, the following\n * idiom can be used:\n *\toffset = fdt_node_offset_by_compatible(fdt, -1, compatible);\n *\twhile (offset != -FDT_ERR_NOTFOUND) {\n *\t\t// other code here\n *\t\toffset = fdt_node_offset_by_compatible(fdt, offset, compatible);\n *\t}\n *\n * Note the -1 in the first call to the function, if 0 is used here\n * instead, the function will never locate the root node, even if it\n * matches the criterion.\n *\n * returns:\n *\tstructure block offset of the located node (>= 0, >startoffset),\n *\t\t on success\n *\t-FDT_ERR_NOTFOUND, no node matching the criterion exists in the\n *\t\ttree after startoffset\n *\t-FDT_ERR_BADOFFSET, nodeoffset does not refer to a BEGIN_NODE tag\n *\t-FDT_ERR_BADMAGIC,\n *\t-FDT_ERR_BADVERSION,\n *\t-FDT_ERR_BADSTATE,\n *\t-FDT_ERR_BADSTRUCTURE, standard meanings\n */\nint fdt_node_offset_by_compatible(const void *fdt, int startoffset,\n\t\t\t\t  const char *compatible);\n\n/**\n * fdt_stringlist_contains - check a string list property for a string\n * @strlist: Property containing a list of strings to check\n * @listlen: Length of property\n * @str: String to search for\n *\n * This is a utility function provided for convenience. The list contains\n * one or more strings, each terminated by \\0, as is found in a device tree\n * \"compatible\" property.\n *\n * Return: 1 if the string is found in the list, 0 not found, or invalid list\n */\nint fdt_stringlist_contains(const char *strlist, int listlen, const char *str);\n\n/**\n * fdt_stringlist_count - count the number of strings in a string list\n * @fdt: pointer to the device tree blob\n * @nodeoffset: offset of a tree node\n * @property: name of the property containing the string list\n *\n * Return:\n *   the number of strings in the given property\n *   -FDT_ERR_BADVALUE if the property value is not NUL-terminated\n *   -FDT_ERR_NOTFOUND if the property does not exist\n */\nint fdt_stringlist_count(const void *fdt, int nodeoffset, const char *property);\n\n/**\n * fdt_stringlist_search - find a string in a string list and return its index\n * @fdt: pointer to the device tree blob\n * @nodeoffset: offset of a tree node\n * @property: name of the property containing the string list\n * @string: string to look up in the string list\n *\n * Note that it is possible for this function to succeed on property values\n * that are not NUL-terminated. That's because the function will stop after\n * finding the first occurrence of @string. This can for example happen with\n * small-valued cell properties, such as #address-cells, when searching for\n * the empty string.\n *\n * return:\n *   the index of the string in the list of strings\n *   -FDT_ERR_BADVALUE if the property value is not NUL-terminated\n *   -FDT_ERR_NOTFOUND if the property does not exist or does not contain\n *                     the given string\n */\nint fdt_stringlist_search(const void *fdt, int nodeoffset, const char *property,\n\t\t\t  const char *string);\n\n/**\n * fdt_stringlist_get() - obtain the string at a given index in a string list\n * @fdt: pointer to the device tree blob\n * @nodeoffset: offset of a tree node\n * @property: name of the property containing the string list\n * @index: index of the string to return\n * @lenp: return location for the string length or an error code on failure\n *\n * Note that this will successfully extract strings from properties with\n * non-NUL-terminated values. For example on small-valued cell properties\n * this function will return the empty string.\n *\n * If non-NULL, the length of the string (on success) or a negative error-code\n * (on failure) will be stored in the integer pointer to by lenp.\n *\n * Return:\n *   A pointer to the string at the given index in the string list or NULL on\n *   failure. On success the length of the string will be stored in the memory\n *   location pointed to by the lenp parameter, if non-NULL. On failure one of\n *   the following negative error codes will be returned in the lenp parameter\n *   (if non-NULL):\n *     -FDT_ERR_BADVALUE if the property value is not NUL-terminated\n *     -FDT_ERR_NOTFOUND if the property does not exist\n */\nconst char *fdt_stringlist_get(const void *fdt, int nodeoffset,\n\t\t\t       const char *property, int index,\n\t\t\t       int *lenp);\n\n/**********************************************************************/\n/* Read-only functions (addressing related)                           */\n/**********************************************************************/\n\n/**\n * FDT_MAX_NCELLS - maximum value for #address-cells and #size-cells\n *\n * This is the maximum value for #address-cells, #size-cells and\n * similar properties that will be processed by libfdt.  IEE1275\n * requires that OF implementations handle values up to 4.\n * Implementations may support larger values, but in practice higher\n * values aren't used.\n */\n#define FDT_MAX_NCELLS\t\t4\n\n/**\n * fdt_address_cells - retrieve address size for a bus represented in the tree\n * @fdt: pointer to the device tree blob\n * @nodeoffset: offset of the node to find the address size for\n *\n * When the node has a valid #address-cells property, returns its value.\n *\n * returns:\n *\t0 <= n < FDT_MAX_NCELLS, on success\n *      2, if the node has no #address-cells property\n *      -FDT_ERR_BADNCELLS, if the node has a badly formatted or invalid\n *\t\t#address-cells property\n *\t-FDT_ERR_BADMAGIC,\n *\t-FDT_ERR_BADVERSION,\n *\t-FDT_ERR_BADSTATE,\n *\t-FDT_ERR_BADSTRUCTURE,\n *\t-FDT_ERR_TRUNCATED, standard meanings\n */\nint fdt_address_cells(const void *fdt, int nodeoffset);\n\n/**\n * fdt_size_cells - retrieve address range size for a bus represented in the\n *                  tree\n * @fdt: pointer to the device tree blob\n * @nodeoffset: offset of the node to find the address range size for\n *\n * When the node has a valid #size-cells property, returns its value.\n *\n * returns:\n *\t0 <= n < FDT_MAX_NCELLS, on success\n *      1, if the node has no #size-cells property\n *      -FDT_ERR_BADNCELLS, if the node has a badly formatted or invalid\n *\t\t#size-cells property\n *\t-FDT_ERR_BADMAGIC,\n *\t-FDT_ERR_BADVERSION,\n *\t-FDT_ERR_BADSTATE,\n *\t-FDT_ERR_BADSTRUCTURE,\n *\t-FDT_ERR_TRUNCATED, standard meanings\n */\nint fdt_size_cells(const void *fdt, int nodeoffset);\n\n\n/**********************************************************************/\n/* Write-in-place functions                                           */\n/**********************************************************************/\n\n/**\n * fdt_setprop_inplace_namelen_partial - change a property's value,\n *                                       but not its size\n * @fdt: pointer to the device tree blob\n * @nodeoffset: offset of the node whose property to change\n * @name: name of the property to change\n * @namelen: number of characters of name to consider\n * @idx: index of the property to change in the array\n * @val: pointer to data to replace the property value with\n * @len: length of the property value\n *\n * Identical to fdt_setprop_inplace(), but modifies the given property\n * starting from the given index, and using only the first characters\n * of the name. It is useful when you want to manipulate only one value of\n * an array and you have a string that doesn't end with \\0.\n *\n * Return: 0 on success, negative libfdt error value otherwise\n */\n#ifndef SWIG /* Not available in Python */\nint fdt_setprop_inplace_namelen_partial(void *fdt, int nodeoffset,\n\t\t\t\t\tconst char *name, int namelen,\n\t\t\t\t\tuint32_t idx, const void *val,\n\t\t\t\t\tint len);\n#endif\n\n/**\n * fdt_setprop_inplace - change a property's value, but not its size\n * @fdt: pointer to the device tree blob\n * @nodeoffset: offset of the node whose property to change\n * @name: name of the property to change\n * @val: pointer to data to replace the property value with\n * @len: length of the property value\n *\n * fdt_setprop_inplace() replaces the value of a given property with\n * the data in val, of length len.  This function cannot change the\n * size of a property, and so will only work if len is equal to the\n * current length of the property.\n *\n * This function will alter only the bytes in the blob which contain\n * the given property value, and will not alter or move any other part\n * of the tree.\n *\n * returns:\n *\t0, on success\n *\t-FDT_ERR_NOSPACE, if len is not equal to the property's current length\n *\t-FDT_ERR_NOTFOUND, node does not have the named property\n *\t-FDT_ERR_BADOFFSET, nodeoffset did not point to FDT_BEGIN_NODE tag\n *\t-FDT_ERR_BADMAGIC,\n *\t-FDT_ERR_BADVERSION,\n *\t-FDT_ERR_BADSTATE,\n *\t-FDT_ERR_BADSTRUCTURE,\n *\t-FDT_ERR_TRUNCATED, standard meanings\n */\n#ifndef SWIG /* Not available in Python */\nint fdt_setprop_inplace(void *fdt, int nodeoffset, const char *name,\n\t\t\tconst void *val, int len);\n#endif\n\n/**\n * fdt_setprop_inplace_u32 - change the value of a 32-bit integer property\n * @fdt: pointer to the device tree blob\n * @nodeoffset: offset of the node whose property to change\n * @name: name of the property to change\n * @val: 32-bit integer value to replace the property with\n *\n * fdt_setprop_inplace_u32() replaces the value of a given property\n * with the 32-bit integer value in val, converting val to big-endian\n * if necessary.  This function cannot change the size of a property,\n * and so will only work if the property already exists and has length\n * 4.\n *\n * This function will alter only the bytes in the blob which contain\n * the given property value, and will not alter or move any other part\n * of the tree.\n *\n * returns:\n *\t0, on success\n *\t-FDT_ERR_NOSPACE, if the property's length is not equal to 4\n *\t-FDT_ERR_NOTFOUND, node does not have the named property\n *\t-FDT_ERR_BADOFFSET, nodeoffset did not point to FDT_BEGIN_NODE tag\n *\t-FDT_ERR_BADMAGIC,\n *\t-FDT_ERR_BADVERSION,\n *\t-FDT_ERR_BADSTATE,\n *\t-FDT_ERR_BADSTRUCTURE,\n *\t-FDT_ERR_TRUNCATED, standard meanings\n */\nstatic inline int fdt_setprop_inplace_u32(void *fdt, int nodeoffset,\n\t\t\t\t\t  const char *name, uint32_t val)\n{\n\tfdt32_t tmp = cpu_to_fdt32(val);\n\treturn fdt_setprop_inplace(fdt, nodeoffset, name, &tmp, sizeof(tmp));\n}\n\n/**\n * fdt_setprop_inplace_u64 - change the value of a 64-bit integer property\n * @fdt: pointer to the device tree blob\n * @nodeoffset: offset of the node whose property to change\n * @name: name of the property to change\n * @val: 64-bit integer value to replace the property with\n *\n * fdt_setprop_inplace_u64() replaces the value of a given property\n * with the 64-bit integer value in val, converting val to big-endian\n * if necessary.  This function cannot change the size of a property,\n * and so will only work if the property already exists and has length\n * 8.\n *\n * This function will alter only the bytes in the blob which contain\n * the given property value, and will not alter or move any other part\n * of the tree.\n *\n * returns:\n *\t0, on success\n *\t-FDT_ERR_NOSPACE, if the property's length is not equal to 8\n *\t-FDT_ERR_NOTFOUND, node does not have the named property\n *\t-FDT_ERR_BADOFFSET, nodeoffset did not point to FDT_BEGIN_NODE tag\n *\t-FDT_ERR_BADMAGIC,\n *\t-FDT_ERR_BADVERSION,\n *\t-FDT_ERR_BADSTATE,\n *\t-FDT_ERR_BADSTRUCTURE,\n *\t-FDT_ERR_TRUNCATED, standard meanings\n */\nstatic inline int fdt_setprop_inplace_u64(void *fdt, int nodeoffset,\n\t\t\t\t\t  const char *name, uint64_t val)\n{\n\tfdt64_t tmp = cpu_to_fdt64(val);\n\treturn fdt_setprop_inplace(fdt, nodeoffset, name, &tmp, sizeof(tmp));\n}\n\n/**\n * fdt_setprop_inplace_cell - change the value of a single-cell property\n * @fdt: pointer to the device tree blob\n * @nodeoffset: offset of the node containing the property\n * @name: name of the property to change the value of\n * @val: new value of the 32-bit cell\n *\n * This is an alternative name for fdt_setprop_inplace_u32()\n * Return: 0 on success, negative libfdt error number otherwise.\n */\nstatic inline int fdt_setprop_inplace_cell(void *fdt, int nodeoffset,\n\t\t\t\t\t   const char *name, uint32_t val)\n{\n\treturn fdt_setprop_inplace_u32(fdt, nodeoffset, name, val);\n}\n\n/**\n * fdt_nop_property - replace a property with nop tags\n * @fdt: pointer to the device tree blob\n * @nodeoffset: offset of the node whose property to nop\n * @name: name of the property to nop\n *\n * fdt_nop_property() will replace a given property's representation\n * in the blob with FDT_NOP tags, effectively removing it from the\n * tree.\n *\n * This function will alter only the bytes in the blob which contain\n * the property, and will not alter or move any other part of the\n * tree.\n *\n * returns:\n *\t0, on success\n *\t-FDT_ERR_NOTFOUND, node does not have the named property\n *\t-FDT_ERR_BADOFFSET, nodeoffset did not point to FDT_BEGIN_NODE tag\n *\t-FDT_ERR_BADMAGIC,\n *\t-FDT_ERR_BADVERSION,\n *\t-FDT_ERR_BADSTATE,\n *\t-FDT_ERR_BADSTRUCTURE,\n *\t-FDT_ERR_TRUNCATED, standard meanings\n */\nint fdt_nop_property(void *fdt, int nodeoffset, const char *name);\n\n/**\n * fdt_nop_node - replace a node (subtree) with nop tags\n * @fdt: pointer to the device tree blob\n * @nodeoffset: offset of the node to nop\n *\n * fdt_nop_node() will replace a given node's representation in the\n * blob, including all its subnodes, if any, with FDT_NOP tags,\n * effectively removing it from the tree.\n *\n * This function will alter only the bytes in the blob which contain\n * the node and its properties and subnodes, and will not alter or\n * move any other part of the tree.\n *\n * returns:\n *\t0, on success\n *\t-FDT_ERR_BADOFFSET, nodeoffset did not point to FDT_BEGIN_NODE tag\n *\t-FDT_ERR_BADMAGIC,\n *\t-FDT_ERR_BADVERSION,\n *\t-FDT_ERR_BADSTATE,\n *\t-FDT_ERR_BADSTRUCTURE,\n *\t-FDT_ERR_TRUNCATED, standard meanings\n */\nint fdt_nop_node(void *fdt, int nodeoffset);\n\n/**********************************************************************/\n/* Sequential write functions                                         */\n/**********************************************************************/\n\n/* fdt_create_with_flags flags */\n#define FDT_CREATE_FLAG_NO_NAME_DEDUP 0x1\n\t/* FDT_CREATE_FLAG_NO_NAME_DEDUP: Do not try to de-duplicate property\n\t * names in the fdt. This can result in faster creation times, but\n\t * a larger fdt. */\n\n#define FDT_CREATE_FLAGS_ALL\t(FDT_CREATE_FLAG_NO_NAME_DEDUP)\n\n/**\n * fdt_create_with_flags - begin creation of a new fdt\n * @buf: pointer to memory allocated where fdt will be created\n * @bufsize: size of the memory space at fdt\n * @flags: a valid combination of FDT_CREATE_FLAG_ flags, or 0.\n *\n * fdt_create_with_flags() begins the process of creating a new fdt with\n * the sequential write interface.\n *\n * fdt creation process must end with fdt_finished() to produce a valid fdt.\n *\n * returns:\n *\t0, on success\n *\t-FDT_ERR_NOSPACE, bufsize is insufficient for a minimal fdt\n *\t-FDT_ERR_BADFLAGS, flags is not valid\n */\nint fdt_create_with_flags(void *buf, int bufsize, uint32_t flags);\n\n/**\n * fdt_create - begin creation of a new fdt\n * @buf: pointer to memory allocated where fdt will be created\n * @bufsize: size of the memory space at fdt\n *\n * fdt_create() is equivalent to fdt_create_with_flags() with flags=0.\n *\n * returns:\n *\t0, on success\n *\t-FDT_ERR_NOSPACE, bufsize is insufficient for a minimal fdt\n */\nint fdt_create(void *buf, int bufsize);\n\nint fdt_resize(void *fdt, void *buf, int bufsize);\nint fdt_add_reservemap_entry(void *fdt, uint64_t addr, uint64_t size);\nint fdt_finish_reservemap(void *fdt);\nint fdt_begin_node(void *fdt, const char *name);\nint fdt_property(void *fdt, const char *name, const void *val, int len);\nstatic inline int fdt_property_u32(void *fdt, const char *name, uint32_t val)\n{\n\tfdt32_t tmp = cpu_to_fdt32(val);\n\treturn fdt_property(fdt, name, &tmp, sizeof(tmp));\n}\nstatic inline int fdt_property_u64(void *fdt, const char *name, uint64_t val)\n{\n\tfdt64_t tmp = cpu_to_fdt64(val);\n\treturn fdt_property(fdt, name, &tmp, sizeof(tmp));\n}\n\n#ifndef SWIG /* Not available in Python */\nstatic inline int fdt_property_cell(void *fdt, const char *name, uint32_t val)\n{\n\treturn fdt_property_u32(fdt, name, val);\n}\n#endif\n\n/**\n * fdt_property_placeholder - add a new property and return a ptr to its value\n *\n * @fdt: pointer to the device tree blob\n * @name: name of property to add\n * @len: length of property value in bytes\n * @valp: returns a pointer to where where the value should be placed\n *\n * returns:\n *\t0, on success\n *\t-FDT_ERR_BADMAGIC,\n *\t-FDT_ERR_NOSPACE, standard meanings\n */\nint fdt_property_placeholder(void *fdt, const char *name, int len, void **valp);\n\n#define fdt_property_string(fdt, name, str) \\\n\tfdt_property(fdt, name, str, strlen(str)+1)\nint fdt_end_node(void *fdt);\nint fdt_finish(void *fdt);\n\n/**********************************************************************/\n/* Read-write functions                                               */\n/**********************************************************************/\n\nint fdt_create_empty_tree(void *buf, int bufsize);\nint fdt_open_into(const void *fdt, void *buf, int bufsize);\nint fdt_pack(void *fdt);\n\n/**\n * fdt_add_mem_rsv - add one memory reserve map entry\n * @fdt: pointer to the device tree blob\n * @address: 64-bit start address of the reserve map entry\n * @size: 64-bit size of the reserved region\n *\n * Adds a reserve map entry to the given blob reserving a region at\n * address address of length size.\n *\n * This function will insert data into the reserve map and will\n * therefore change the indexes of some entries in the table.\n *\n * returns:\n *\t0, on success\n *\t-FDT_ERR_NOSPACE, there is insufficient free space in the blob to\n *\t\tcontain the new reservation entry\n *\t-FDT_ERR_BADMAGIC,\n *\t-FDT_ERR_BADVERSION,\n *\t-FDT_ERR_BADSTATE,\n *\t-FDT_ERR_BADSTRUCTURE,\n *\t-FDT_ERR_BADLAYOUT,\n *\t-FDT_ERR_TRUNCATED, standard meanings\n */\nint fdt_add_mem_rsv(void *fdt, uint64_t address, uint64_t size);\n\n/**\n * fdt_del_mem_rsv - remove a memory reserve map entry\n * @fdt: pointer to the device tree blob\n * @n: entry to remove\n *\n * fdt_del_mem_rsv() removes the n-th memory reserve map entry from\n * the blob.\n *\n * This function will delete data from the reservation table and will\n * therefore change the indexes of some entries in the table.\n *\n * returns:\n *\t0, on success\n *\t-FDT_ERR_NOTFOUND, there is no entry of the given index (i.e. there\n *\t\tare less than n+1 reserve map entries)\n *\t-FDT_ERR_BADMAGIC,\n *\t-FDT_ERR_BADVERSION,\n *\t-FDT_ERR_BADSTATE,\n *\t-FDT_ERR_BADSTRUCTURE,\n *\t-FDT_ERR_BADLAYOUT,\n *\t-FDT_ERR_TRUNCATED, standard meanings\n */\nint fdt_del_mem_rsv(void *fdt, int n);\n\n/**\n * fdt_set_name - change the name of a given node\n * @fdt: pointer to the device tree blob\n * @nodeoffset: structure block offset of a node\n * @name: name to give the node\n *\n * fdt_set_name() replaces the name (including unit address, if any)\n * of the given node with the given string.  NOTE: this function can't\n * efficiently check if the new name is unique amongst the given\n * node's siblings; results are undefined if this function is invoked\n * with a name equal to one of the given node's siblings.\n *\n * This function may insert or delete data from the blob, and will\n * therefore change the offsets of some existing nodes.\n *\n * returns:\n *\t0, on success\n *\t-FDT_ERR_NOSPACE, there is insufficient free space in the blob\n *\t\tto contain the new name\n *\t-FDT_ERR_BADOFFSET, nodeoffset did not point to FDT_BEGIN_NODE tag\n *\t-FDT_ERR_BADMAGIC,\n *\t-FDT_ERR_BADVERSION,\n *\t-FDT_ERR_BADSTATE, standard meanings\n */\nint fdt_set_name(void *fdt, int nodeoffset, const char *name);\n\n/**\n * fdt_setprop - create or change a property\n * @fdt: pointer to the device tree blob\n * @nodeoffset: offset of the node whose property to change\n * @name: name of the property to change\n * @val: pointer to data to set the property value to\n * @len: length of the property value\n *\n * fdt_setprop() sets the value of the named property in the given\n * node to the given value and length, creating the property if it\n * does not already exist.\n *\n * This function may insert or delete data from the blob, and will\n * therefore change the offsets of some existing nodes.\n *\n * returns:\n *\t0, on success\n *\t-FDT_ERR_NOSPACE, there is insufficient free space in the blob to\n *\t\tcontain the new property value\n *\t-FDT_ERR_BADOFFSET, nodeoffset did not point to FDT_BEGIN_NODE tag\n *\t-FDT_ERR_BADLAYOUT,\n *\t-FDT_ERR_BADMAGIC,\n *\t-FDT_ERR_BADVERSION,\n *\t-FDT_ERR_BADSTATE,\n *\t-FDT_ERR_BADSTRUCTURE,\n *\t-FDT_ERR_BADLAYOUT,\n *\t-FDT_ERR_TRUNCATED, standard meanings\n */\nint fdt_setprop(void *fdt, int nodeoffset, const char *name,\n\t\tconst void *val, int len);\n\n/**\n * fdt_setprop_placeholder - allocate space for a property\n * @fdt: pointer to the device tree blob\n * @nodeoffset: offset of the node whose property to change\n * @name: name of the property to change\n * @len: length of the property value\n * @prop_data: return pointer to property data\n *\n * fdt_setprop_placeholer() allocates the named property in the given node.\n * If the property exists it is resized. In either case a pointer to the\n * property data is returned.\n *\n * This function may insert or delete data from the blob, and will\n * therefore change the offsets of some existing nodes.\n *\n * returns:\n *\t0, on success\n *\t-FDT_ERR_NOSPACE, there is insufficient free space in the blob to\n *\t\tcontain the new property value\n *\t-FDT_ERR_BADOFFSET, nodeoffset did not point to FDT_BEGIN_NODE tag\n *\t-FDT_ERR_BADLAYOUT,\n *\t-FDT_ERR_BADMAGIC,\n *\t-FDT_ERR_BADVERSION,\n *\t-FDT_ERR_BADSTATE,\n *\t-FDT_ERR_BADSTRUCTURE,\n *\t-FDT_ERR_BADLAYOUT,\n *\t-FDT_ERR_TRUNCATED, standard meanings\n */\nint fdt_setprop_placeholder(void *fdt, int nodeoffset, const char *name,\n\t\t\t    int len, void **prop_data);\n\n/**\n * fdt_setprop_u32 - set a property to a 32-bit integer\n * @fdt: pointer to the device tree blob\n * @nodeoffset: offset of the node whose property to change\n * @name: name of the property to change\n * @val: 32-bit integer value for the property (native endian)\n *\n * fdt_setprop_u32() sets the value of the named property in the given\n * node to the given 32-bit integer value (converting to big-endian if\n * necessary), or creates a new property with that value if it does\n * not already exist.\n *\n * This function may insert or delete data from the blob, and will\n * therefore change the offsets of some existing nodes.\n *\n * returns:\n *\t0, on success\n *\t-FDT_ERR_NOSPACE, there is insufficient free space in the blob to\n *\t\tcontain the new property value\n *\t-FDT_ERR_BADOFFSET, nodeoffset did not point to FDT_BEGIN_NODE tag\n *\t-FDT_ERR_BADLAYOUT,\n *\t-FDT_ERR_BADMAGIC,\n *\t-FDT_ERR_BADVERSION,\n *\t-FDT_ERR_BADSTATE,\n *\t-FDT_ERR_BADSTRUCTURE,\n *\t-FDT_ERR_BADLAYOUT,\n *\t-FDT_ERR_TRUNCATED, standard meanings\n */\nstatic inline int fdt_setprop_u32(void *fdt, int nodeoffset, const char *name,\n\t\t\t\t  uint32_t val)\n{\n\tfdt32_t tmp = cpu_to_fdt32(val);\n\treturn fdt_setprop(fdt, nodeoffset, name, &tmp, sizeof(tmp));\n}\n\n/**\n * fdt_setprop_u64 - set a property to a 64-bit integer\n * @fdt: pointer to the device tree blob\n * @nodeoffset: offset of the node whose property to change\n * @name: name of the property to change\n * @val: 64-bit integer value for the property (native endian)\n *\n * fdt_setprop_u64() sets the value of the named property in the given\n * node to the given 64-bit integer value (converting to big-endian if\n * necessary), or creates a new property with that value if it does\n * not already exist.\n *\n * This function may insert or delete data from the blob, and will\n * therefore change the offsets of some existing nodes.\n *\n * returns:\n *\t0, on success\n *\t-FDT_ERR_NOSPACE, there is insufficient free space in the blob to\n *\t\tcontain the new property value\n *\t-FDT_ERR_BADOFFSET, nodeoffset did not point to FDT_BEGIN_NODE tag\n *\t-FDT_ERR_BADLAYOUT,\n *\t-FDT_ERR_BADMAGIC,\n *\t-FDT_ERR_BADVERSION,\n *\t-FDT_ERR_BADSTATE,\n *\t-FDT_ERR_BADSTRUCTURE,\n *\t-FDT_ERR_BADLAYOUT,\n *\t-FDT_ERR_TRUNCATED, standard meanings\n */\nstatic inline int fdt_setprop_u64(void *fdt, int nodeoffset, const char *name,\n\t\t\t\t  uint64_t val)\n{\n\tfdt64_t tmp = cpu_to_fdt64(val);\n\treturn fdt_setprop(fdt, nodeoffset, name, &tmp, sizeof(tmp));\n}\n\n/**\n * fdt_setprop_cell - set a property to a single cell value\n * @fdt: pointer to the device tree blob\n * @nodeoffset: offset of the node whose property to change\n * @name: name of the property to change\n * @val: 32-bit integer value for the property (native endian)\n *\n * This is an alternative name for fdt_setprop_u32()\n *\n * Return: 0 on success, negative libfdt error value otherwise.\n */\nstatic inline int fdt_setprop_cell(void *fdt, int nodeoffset, const char *name,\n\t\t\t\t   uint32_t val)\n{\n\treturn fdt_setprop_u32(fdt, nodeoffset, name, val);\n}\n\n/**\n * fdt_setprop_string - set a property to a string value\n * @fdt: pointer to the device tree blob\n * @nodeoffset: offset of the node whose property to change\n * @name: name of the property to change\n * @str: string value for the property\n *\n * fdt_setprop_string() sets the value of the named property in the\n * given node to the given string value (using the length of the\n * string to determine the new length of the property), or creates a\n * new property with that value if it does not already exist.\n *\n * This function may insert or delete data from the blob, and will\n * therefore change the offsets of some existing nodes.\n *\n * returns:\n *\t0, on success\n *\t-FDT_ERR_NOSPACE, there is insufficient free space in the blob to\n *\t\tcontain the new property value\n *\t-FDT_ERR_BADOFFSET, nodeoffset did not point to FDT_BEGIN_NODE tag\n *\t-FDT_ERR_BADLAYOUT,\n *\t-FDT_ERR_BADMAGIC,\n *\t-FDT_ERR_BADVERSION,\n *\t-FDT_ERR_BADSTATE,\n *\t-FDT_ERR_BADSTRUCTURE,\n *\t-FDT_ERR_BADLAYOUT,\n *\t-FDT_ERR_TRUNCATED, standard meanings\n */\n#define fdt_setprop_string(fdt, nodeoffset, name, str) \\\n\tfdt_setprop((fdt), (nodeoffset), (name), (str), strlen(str)+1)\n\n\n/**\n * fdt_setprop_empty - set a property to an empty value\n * @fdt: pointer to the device tree blob\n * @nodeoffset: offset of the node whose property to change\n * @name: name of the property to change\n *\n * fdt_setprop_empty() sets the value of the named property in the\n * given node to an empty (zero length) value, or creates a new empty\n * property if it does not already exist.\n *\n * This function may insert or delete data from the blob, and will\n * therefore change the offsets of some existing nodes.\n *\n * returns:\n *\t0, on success\n *\t-FDT_ERR_NOSPACE, there is insufficient free space in the blob to\n *\t\tcontain the new property value\n *\t-FDT_ERR_BADOFFSET, nodeoffset did not point to FDT_BEGIN_NODE tag\n *\t-FDT_ERR_BADLAYOUT,\n *\t-FDT_ERR_BADMAGIC,\n *\t-FDT_ERR_BADVERSION,\n *\t-FDT_ERR_BADSTATE,\n *\t-FDT_ERR_BADSTRUCTURE,\n *\t-FDT_ERR_BADLAYOUT,\n *\t-FDT_ERR_TRUNCATED, standard meanings\n */\n#define fdt_setprop_empty(fdt, nodeoffset, name) \\\n\tfdt_setprop((fdt), (nodeoffset), (name), NULL, 0)\n\n/**\n * fdt_appendprop - append to or create a property\n * @fdt: pointer to the device tree blob\n * @nodeoffset: offset of the node whose property to change\n * @name: name of the property to append to\n * @val: pointer to data to append to the property value\n * @len: length of the data to append to the property value\n *\n * fdt_appendprop() appends the value to the named property in the\n * given node, creating the property if it does not already exist.\n *\n * This function may insert data into the blob, and will therefore\n * change the offsets of some existing nodes.\n *\n * returns:\n *\t0, on success\n *\t-FDT_ERR_NOSPACE, there is insufficient free space in the blob to\n *\t\tcontain the new property value\n *\t-FDT_ERR_BADOFFSET, nodeoffset did not point to FDT_BEGIN_NODE tag\n *\t-FDT_ERR_BADLAYOUT,\n *\t-FDT_ERR_BADMAGIC,\n *\t-FDT_ERR_BADVERSION,\n *\t-FDT_ERR_BADSTATE,\n *\t-FDT_ERR_BADSTRUCTURE,\n *\t-FDT_ERR_BADLAYOUT,\n *\t-FDT_ERR_TRUNCATED, standard meanings\n */\nint fdt_appendprop(void *fdt, int nodeoffset, const char *name,\n\t\t   const void *val, int len);\n\n/**\n * fdt_appendprop_u32 - append a 32-bit integer value to a property\n * @fdt: pointer to the device tree blob\n * @nodeoffset: offset of the node whose property to change\n * @name: name of the property to change\n * @val: 32-bit integer value to append to the property (native endian)\n *\n * fdt_appendprop_u32() appends the given 32-bit integer value\n * (converting to big-endian if necessary) to the value of the named\n * property in the given node, or creates a new property with that\n * value if it does not already exist.\n *\n * This function may insert data into the blob, and will therefore\n * change the offsets of some existing nodes.\n *\n * returns:\n *\t0, on success\n *\t-FDT_ERR_NOSPACE, there is insufficient free space in the blob to\n *\t\tcontain the new property value\n *\t-FDT_ERR_BADOFFSET, nodeoffset did not point to FDT_BEGIN_NODE tag\n *\t-FDT_ERR_BADLAYOUT,\n *\t-FDT_ERR_BADMAGIC,\n *\t-FDT_ERR_BADVERSION,\n *\t-FDT_ERR_BADSTATE,\n *\t-FDT_ERR_BADSTRUCTURE,\n *\t-FDT_ERR_BADLAYOUT,\n *\t-FDT_ERR_TRUNCATED, standard meanings\n */\nstatic inline int fdt_appendprop_u32(void *fdt, int nodeoffset,\n\t\t\t\t     const char *name, uint32_t val)\n{\n\tfdt32_t tmp = cpu_to_fdt32(val);\n\treturn fdt_appendprop(fdt, nodeoffset, name, &tmp, sizeof(tmp));\n}\n\n/**\n * fdt_appendprop_u64 - append a 64-bit integer value to a property\n * @fdt: pointer to the device tree blob\n * @nodeoffset: offset of the node whose property to change\n * @name: name of the property to change\n * @val: 64-bit integer value to append to the property (native endian)\n *\n * fdt_appendprop_u64() appends the given 64-bit integer value\n * (converting to big-endian if necessary) to the value of the named\n * property in the given node, or creates a new property with that\n * value if it does not already exist.\n *\n * This function may insert data into the blob, and will therefore\n * change the offsets of some existing nodes.\n *\n * returns:\n *\t0, on success\n *\t-FDT_ERR_NOSPACE, there is insufficient free space in the blob to\n *\t\tcontain the new property value\n *\t-FDT_ERR_BADOFFSET, nodeoffset did not point to FDT_BEGIN_NODE tag\n *\t-FDT_ERR_BADLAYOUT,\n *\t-FDT_ERR_BADMAGIC,\n *\t-FDT_ERR_BADVERSION,\n *\t-FDT_ERR_BADSTATE,\n *\t-FDT_ERR_BADSTRUCTURE,\n *\t-FDT_ERR_BADLAYOUT,\n *\t-FDT_ERR_TRUNCATED, standard meanings\n */\nstatic inline int fdt_appendprop_u64(void *fdt, int nodeoffset,\n\t\t\t\t     const char *name, uint64_t val)\n{\n\tfdt64_t tmp = cpu_to_fdt64(val);\n\treturn fdt_appendprop(fdt, nodeoffset, name, &tmp, sizeof(tmp));\n}\n\n/**\n * fdt_appendprop_cell - append a single cell value to a property\n * @fdt: pointer to the device tree blob\n * @nodeoffset: offset of the node whose property to change\n * @name: name of the property to change\n * @val: 32-bit integer value to append to the property (native endian)\n *\n * This is an alternative name for fdt_appendprop_u32()\n *\n * Return: 0 on success, negative libfdt error value otherwise.\n */\nstatic inline int fdt_appendprop_cell(void *fdt, int nodeoffset,\n\t\t\t\t      const char *name, uint32_t val)\n{\n\treturn fdt_appendprop_u32(fdt, nodeoffset, name, val);\n}\n\n/**\n * fdt_appendprop_string - append a string to a property\n * @fdt: pointer to the device tree blob\n * @nodeoffset: offset of the node whose property to change\n * @name: name of the property to change\n * @str: string value to append to the property\n *\n * fdt_appendprop_string() appends the given string to the value of\n * the named property in the given node, or creates a new property\n * with that value if it does not already exist.\n *\n * This function may insert data into the blob, and will therefore\n * change the offsets of some existing nodes.\n *\n * returns:\n *\t0, on success\n *\t-FDT_ERR_NOSPACE, there is insufficient free space in the blob to\n *\t\tcontain the new property value\n *\t-FDT_ERR_BADOFFSET, nodeoffset did not point to FDT_BEGIN_NODE tag\n *\t-FDT_ERR_BADLAYOUT,\n *\t-FDT_ERR_BADMAGIC,\n *\t-FDT_ERR_BADVERSION,\n *\t-FDT_ERR_BADSTATE,\n *\t-FDT_ERR_BADSTRUCTURE,\n *\t-FDT_ERR_BADLAYOUT,\n *\t-FDT_ERR_TRUNCATED, standard meanings\n */\n#define fdt_appendprop_string(fdt, nodeoffset, name, str) \\\n\tfdt_appendprop((fdt), (nodeoffset), (name), (str), strlen(str)+1)\n\n/**\n * fdt_appendprop_addrrange - append a address range property\n * @fdt: pointer to the device tree blob\n * @parent: offset of the parent node\n * @nodeoffset: offset of the node to add a property at\n * @name: name of property\n * @addr: start address of a given range\n * @size: size of a given range\n *\n * fdt_appendprop_addrrange() appends an address range value (start\n * address and size) to the value of the named property in the given\n * node, or creates a new property with that value if it does not\n * already exist.\n * If \"name\" is not specified, a default \"reg\" is used.\n * Cell sizes are determined by parent's #address-cells and #size-cells.\n *\n * This function may insert data into the blob, and will therefore\n * change the offsets of some existing nodes.\n *\n * returns:\n *\t0, on success\n *\t-FDT_ERR_BADLAYOUT,\n *\t-FDT_ERR_BADMAGIC,\n *\t-FDT_ERR_BADNCELLS, if the node has a badly formatted or invalid\n *\t\t#address-cells property\n *\t-FDT_ERR_BADOFFSET, nodeoffset did not point to FDT_BEGIN_NODE tag\n *\t-FDT_ERR_BADSTATE,\n *\t-FDT_ERR_BADSTRUCTURE,\n *\t-FDT_ERR_BADVERSION,\n *\t-FDT_ERR_BADVALUE, addr or size doesn't fit to respective cells size\n *\t-FDT_ERR_NOSPACE, there is insufficient free space in the blob to\n *\t\tcontain a new property\n *\t-FDT_ERR_TRUNCATED, standard meanings\n */\nint fdt_appendprop_addrrange(void *fdt, int parent, int nodeoffset,\n\t\t\t     const char *name, uint64_t addr, uint64_t size);\n\n/**\n * fdt_delprop - delete a property\n * @fdt: pointer to the device tree blob\n * @nodeoffset: offset of the node whose property to nop\n * @name: name of the property to nop\n *\n * fdt_del_property() will delete the given property.\n *\n * This function will delete data from the blob, and will therefore\n * change the offsets of some existing nodes.\n *\n * returns:\n *\t0, on success\n *\t-FDT_ERR_NOTFOUND, node does not have the named property\n *\t-FDT_ERR_BADOFFSET, nodeoffset did not point to FDT_BEGIN_NODE tag\n *\t-FDT_ERR_BADLAYOUT,\n *\t-FDT_ERR_BADMAGIC,\n *\t-FDT_ERR_BADVERSION,\n *\t-FDT_ERR_BADSTATE,\n *\t-FDT_ERR_BADSTRUCTURE,\n *\t-FDT_ERR_TRUNCATED, standard meanings\n */\nint fdt_delprop(void *fdt, int nodeoffset, const char *name);\n\n/**\n * fdt_add_subnode_namelen - creates a new node based on substring\n * @fdt: pointer to the device tree blob\n * @parentoffset: structure block offset of a node\n * @name: name of the subnode to create\n * @namelen: number of characters of name to consider\n *\n * Identical to fdt_add_subnode(), but use only the first @namelen\n * characters of @name as the name of the new node.  This is useful for\n * creating subnodes based on a portion of a larger string, such as a\n * full path.\n *\n * Return: structure block offset of the created subnode (>=0),\n *\t   negative libfdt error value otherwise\n */\n#ifndef SWIG /* Not available in Python */\nint fdt_add_subnode_namelen(void *fdt, int parentoffset,\n\t\t\t    const char *name, int namelen);\n#endif\n\n/**\n * fdt_add_subnode - creates a new node\n * @fdt: pointer to the device tree blob\n * @parentoffset: structure block offset of a node\n * @name: name of the subnode to locate\n *\n * fdt_add_subnode() creates a new node as a subnode of the node at\n * structure block offset parentoffset, with the given name (which\n * should include the unit address, if any).\n *\n * This function will insert data into the blob, and will therefore\n * change the offsets of some existing nodes.\n *\n * returns:\n *\tstructure block offset of the created nodeequested subnode (>=0), on\n *\t\tsuccess\n *\t-FDT_ERR_NOTFOUND, if the requested subnode does not exist\n *\t-FDT_ERR_BADOFFSET, if parentoffset did not point to an FDT_BEGIN_NODE\n *\t\ttag\n *\t-FDT_ERR_EXISTS, if the node at parentoffset already has a subnode of\n *\t\tthe given name\n *\t-FDT_ERR_NOSPACE, if there is insufficient free space in the\n *\t\tblob to contain the new node\n *\t-FDT_ERR_NOSPACE\n *\t-FDT_ERR_BADLAYOUT\n *      -FDT_ERR_BADMAGIC,\n *\t-FDT_ERR_BADVERSION,\n *\t-FDT_ERR_BADSTATE,\n *\t-FDT_ERR_BADSTRUCTURE,\n *\t-FDT_ERR_TRUNCATED, standard meanings.\n */\nint fdt_add_subnode(void *fdt, int parentoffset, const char *name);\n\n/**\n * fdt_del_node - delete a node (subtree)\n * @fdt: pointer to the device tree blob\n * @nodeoffset: offset of the node to nop\n *\n * fdt_del_node() will remove the given node, including all its\n * subnodes if any, from the blob.\n *\n * This function will delete data from the blob, and will therefore\n * change the offsets of some existing nodes.\n *\n * returns:\n *\t0, on success\n *\t-FDT_ERR_BADOFFSET, nodeoffset did not point to FDT_BEGIN_NODE tag\n *\t-FDT_ERR_BADLAYOUT,\n *\t-FDT_ERR_BADMAGIC,\n *\t-FDT_ERR_BADVERSION,\n *\t-FDT_ERR_BADSTATE,\n *\t-FDT_ERR_BADSTRUCTURE,\n *\t-FDT_ERR_TRUNCATED, standard meanings\n */\nint fdt_del_node(void *fdt, int nodeoffset);\n\n/**\n * fdt_overlay_apply - Applies a DT overlay on a base DT\n * @fdt: pointer to the base device tree blob\n * @fdto: pointer to the device tree overlay blob\n *\n * fdt_overlay_apply() will apply the given device tree overlay on the\n * given base device tree.\n *\n * Expect the base device tree to be modified, even if the function\n * returns an error.\n *\n * returns:\n *\t0, on success\n *\t-FDT_ERR_NOSPACE, there's not enough space in the base device tree\n *\t-FDT_ERR_NOTFOUND, the overlay points to some inexistant nodes or\n *\t\tproperties in the base DT\n *\t-FDT_ERR_BADPHANDLE,\n *\t-FDT_ERR_BADOVERLAY,\n *\t-FDT_ERR_NOPHANDLES,\n *\t-FDT_ERR_INTERNAL,\n *\t-FDT_ERR_BADLAYOUT,\n *\t-FDT_ERR_BADMAGIC,\n *\t-FDT_ERR_BADOFFSET,\n *\t-FDT_ERR_BADPATH,\n *\t-FDT_ERR_BADVERSION,\n *\t-FDT_ERR_BADSTRUCTURE,\n *\t-FDT_ERR_BADSTATE,\n *\t-FDT_ERR_TRUNCATED, standard meanings\n */\nint fdt_overlay_apply(void *fdt, void *fdto);\n\n/**\n * fdt_overlay_target_offset - retrieves the offset of a fragment's target\n * @fdt: Base device tree blob\n * @fdto: Device tree overlay blob\n * @fragment_offset: node offset of the fragment in the overlay\n * @pathp: pointer which receives the path of the target (or NULL)\n *\n * fdt_overlay_target_offset() retrieves the target offset in the base\n * device tree of a fragment, no matter how the actual targeting is\n * done (through a phandle or a path)\n *\n * returns:\n *      the targeted node offset in the base device tree\n *      Negative error code on error\n */\nint fdt_overlay_target_offset(const void *fdt, const void *fdto,\n\t\t\t      int fragment_offset, char const **pathp);\n\n/**********************************************************************/\n/* Debugging / informational functions                                */\n/**********************************************************************/\n\nconst char *fdt_strerror(int errval);\n\n#ifdef __cplusplus\n}\n#endif\n\n#endif /* LIBFDT_H */\n"
  },
  {
    "path": "external/libfdt/libfdt_env.h",
    "content": "/* SPDX-License-Identifier: (GPL-2.0-or-later OR BSD-2-Clause) */\n#ifndef LIBFDT_ENV_H\n#define LIBFDT_ENV_H\n/*\n * libfdt - Flat Device Tree manipulation\n * Copyright (C) 2006 David Gibson, IBM Corporation.\n * Copyright 2012 Kim Phillips, Freescale Semiconductor.\n */\n\n#include <stdbool.h>\n#include <stddef.h>\n#include <stdint.h>\n#include <stdlib.h>\n#include <string.h>\n#include <limits.h>\n\n#ifdef __CHECKER__\n#define FDT_FORCE __attribute__((force))\n#define FDT_BITWISE __attribute__((bitwise))\n#else\n#define FDT_FORCE\n#define FDT_BITWISE\n#endif\n\ntypedef uint16_t FDT_BITWISE fdt16_t;\ntypedef uint32_t FDT_BITWISE fdt32_t;\ntypedef uint64_t FDT_BITWISE fdt64_t;\n\n#define EXTRACT_BYTE(x, n)\t((unsigned long long)((uint8_t *)&x)[n])\n#define CPU_TO_FDT16(x) ((EXTRACT_BYTE(x, 0) << 8) | EXTRACT_BYTE(x, 1))\n#define CPU_TO_FDT32(x) ((EXTRACT_BYTE(x, 0) << 24) | (EXTRACT_BYTE(x, 1) << 16) | \\\n\t\t\t (EXTRACT_BYTE(x, 2) << 8) | EXTRACT_BYTE(x, 3))\n#define CPU_TO_FDT64(x) ((EXTRACT_BYTE(x, 0) << 56) | (EXTRACT_BYTE(x, 1) << 48) | \\\n\t\t\t (EXTRACT_BYTE(x, 2) << 40) | (EXTRACT_BYTE(x, 3) << 32) | \\\n\t\t\t (EXTRACT_BYTE(x, 4) << 24) | (EXTRACT_BYTE(x, 5) << 16) | \\\n\t\t\t (EXTRACT_BYTE(x, 6) << 8) | EXTRACT_BYTE(x, 7))\n\nstatic inline uint16_t fdt16_to_cpu(fdt16_t x)\n{\n\treturn (FDT_FORCE uint16_t)CPU_TO_FDT16(x);\n}\nstatic inline fdt16_t cpu_to_fdt16(uint16_t x)\n{\n\treturn (FDT_FORCE fdt16_t)CPU_TO_FDT16(x);\n}\n\nstatic inline uint32_t fdt32_to_cpu(fdt32_t x)\n{\n\treturn (FDT_FORCE uint32_t)CPU_TO_FDT32(x);\n}\nstatic inline fdt32_t cpu_to_fdt32(uint32_t x)\n{\n\treturn (FDT_FORCE fdt32_t)CPU_TO_FDT32(x);\n}\n\nstatic inline uint64_t fdt64_to_cpu(fdt64_t x)\n{\n\treturn (FDT_FORCE uint64_t)CPU_TO_FDT64(x);\n}\nstatic inline fdt64_t cpu_to_fdt64(uint64_t x)\n{\n\treturn (FDT_FORCE fdt64_t)CPU_TO_FDT64(x);\n}\n#undef CPU_TO_FDT64\n#undef CPU_TO_FDT32\n#undef CPU_TO_FDT16\n#undef EXTRACT_BYTE\n\n#ifdef __APPLE__\n#include <AvailabilityMacros.h>\n\n/* strnlen() is not available on Mac OS < 10.7 */\n# if !defined(MAC_OS_X_VERSION_10_7) || (MAC_OS_X_VERSION_MAX_ALLOWED < \\\n                                         MAC_OS_X_VERSION_10_7)\n\n#define strnlen fdt_strnlen\n\n/*\n * fdt_strnlen: returns the length of a string or max_count - which ever is\n * smallest.\n * Input 1 string: the string whose size is to be determined\n * Input 2 max_count: the maximum value returned by this function\n * Output: length of the string or max_count (the smallest of the two)\n */\nstatic inline size_t fdt_strnlen(const char *string, size_t max_count)\n{\n    const char *p = memchr(string, 0, max_count);\n    return p ? p - string : max_count;\n}\n\n#endif /* !defined(MAC_OS_X_VERSION_10_7) || (MAC_OS_X_VERSION_MAX_ALLOWED <\n          MAC_OS_X_VERSION_10_7) */\n\n#endif /* __APPLE__ */\n\n#endif /* LIBFDT_ENV_H */\n"
  },
  {
    "path": "external/libfdt/libfdt_internal.h",
    "content": "/* SPDX-License-Identifier: (GPL-2.0-or-later OR BSD-2-Clause) */\n#ifndef LIBFDT_INTERNAL_H\n#define LIBFDT_INTERNAL_H\n/*\n * libfdt - Flat Device Tree manipulation\n * Copyright (C) 2006 David Gibson, IBM Corporation.\n */\n#include <fdt.h>\n\n#define FDT_ALIGN(x, a)\t\t(((x) + (a) - 1) & ~((a) - 1))\n#define FDT_TAGALIGN(x)\t\t(FDT_ALIGN((x), FDT_TAGSIZE))\n\nint32_t fdt_ro_probe_(const void *fdt);\n#define FDT_RO_PROBE(fdt)\t\t\t\t\t\\\n\t{\t\t\t\t\t\t\t\\\n\t\tint32_t totalsize_;\t\t\t\t\\\n\t\tif ((totalsize_ = fdt_ro_probe_(fdt)) < 0)\t\\\n\t\t\treturn totalsize_;\t\t\t\\\n\t}\n\nint fdt_check_node_offset_(const void *fdt, int offset);\nint fdt_check_prop_offset_(const void *fdt, int offset);\nconst char *fdt_find_string_(const char *strtab, int tabsize, const char *s);\nint fdt_node_end_offset_(void *fdt, int nodeoffset);\n\nstatic inline const void *fdt_offset_ptr_(const void *fdt, int offset)\n{\n\treturn (const char *)fdt + fdt_off_dt_struct(fdt) + offset;\n}\n\nstatic inline void *fdt_offset_ptr_w_(void *fdt, int offset)\n{\n\treturn (void *)(uintptr_t)fdt_offset_ptr_(fdt, offset);\n}\n\nstatic inline const struct fdt_reserve_entry *fdt_mem_rsv_(const void *fdt, int n)\n{\n\tconst struct fdt_reserve_entry *rsv_table =\n\t\t(const struct fdt_reserve_entry *)\n\t\t((const char *)fdt + fdt_off_mem_rsvmap(fdt));\n\n\treturn rsv_table + n;\n}\nstatic inline struct fdt_reserve_entry *fdt_mem_rsv_w_(void *fdt, int n)\n{\n\treturn (void *)(uintptr_t)fdt_mem_rsv_(fdt, n);\n}\n\n/*\n * Internal helpers to access tructural elements of the device tree\n * blob (rather than for exaple reading integers from within property\n * values).  We assume that we are either given a naturally aligned\n * address for the platform or if we are not, we are on a platform\n * where unaligned memory reads will be handled in a graceful manner.\n * If not the external helpers fdtXX_ld() from libfdt.h can be used\n * instead.\n */\nstatic inline uint32_t fdt32_ld_(const fdt32_t *p)\n{\n\treturn fdt32_to_cpu(*p);\n}\n\nstatic inline uint64_t fdt64_ld_(const fdt64_t *p)\n{\n\treturn fdt64_to_cpu(*p);\n}\n\n#define FDT_SW_MAGIC\t\t(~FDT_MAGIC)\n\n/**********************************************************************/\n/* Checking controls                                                  */\n/**********************************************************************/\n\n#ifndef FDT_ASSUME_MASK\n#define FDT_ASSUME_MASK 0\n#endif\n\n/*\n * Defines assumptions which can be enabled. Each of these can be enabled\n * individually. For maximum safety, don't enable any assumptions!\n *\n * For minimal code size and no safety, use ASSUME_PERFECT at your own risk.\n * You should have another method of validating the device tree, such as a\n * signature or hash check before using libfdt.\n *\n * For situations where security is not a concern it may be safe to enable\n * ASSUME_SANE.\n */\nenum {\n\t/*\n\t * This does essentially no checks. Only the latest device-tree\n\t * version is correctly handled. Inconsistencies or errors in the device\n\t * tree may cause undefined behaviour or crashes. Invalid parameters\n\t * passed to libfdt may do the same.\n\t *\n\t * If an error occurs when modifying the tree it may leave the tree in\n\t * an intermediate (but valid) state. As an example, adding a property\n\t * where there is insufficient space may result in the property name\n\t * being added to the string table even though the property itself is\n\t * not added to the struct section.\n\t *\n\t * Only use this if you have a fully validated device tree with\n\t * the latest supported version and wish to minimise code size.\n\t */\n\tASSUME_PERFECT\t\t= 0xff,\n\n\t/*\n\t * This assumes that the device tree is sane. i.e. header metadata\n\t * and basic hierarchy are correct.\n\t *\n\t * With this assumption enabled, normal device trees produced by libfdt\n\t * and the compiler should be handled safely. Malicious device trees and\n\t * complete garbage may cause libfdt to behave badly or crash. Truncated\n\t * device trees (e.g. those only partially loaded) can also cause\n\t * problems.\n\t *\n\t * Note: Only checks that relate exclusively to the device tree itself\n\t * (not the parameters passed to libfdt) are disabled by this\n\t * assumption. This includes checking headers, tags and the like.\n\t */\n\tASSUME_VALID_DTB\t= 1 << 0,\n\n\t/*\n\t * This builds on ASSUME_VALID_DTB and further assumes that libfdt\n\t * functions are called with valid parameters, i.e. not trigger\n\t * FDT_ERR_BADOFFSET or offsets that are out of bounds. It disables any\n\t * extensive checking of parameters and the device tree, making various\n\t * assumptions about correctness.\n\t *\n\t * It doesn't make sense to enable this assumption unless\n\t * ASSUME_VALID_DTB is also enabled.\n\t */\n\tASSUME_VALID_INPUT\t= 1 << 1,\n\n\t/*\n\t * This disables checks for device-tree version and removes all code\n\t * which handles older versions.\n\t *\n\t * Only enable this if you know you have a device tree with the latest\n\t * version.\n\t */\n\tASSUME_LATEST\t\t= 1 << 2,\n\n\t/*\n\t * This assumes that it is OK for a failed addition to the device tree,\n\t * due to lack of space or some other problem, to skip any rollback\n\t * steps (such as dropping the property name from the string table).\n\t * This is safe to enable in most circumstances, even though it may\n\t * leave the tree in a sub-optimal state.\n\t */\n\tASSUME_NO_ROLLBACK\t= 1 << 3,\n\n\t/*\n\t * This assumes that the device tree components appear in a 'convenient'\n\t * order, i.e. the memory reservation block first, then the structure\n\t * block and finally the string block.\n\t *\n\t * This order is not specified by the device-tree specification,\n\t * but is expected by libfdt. The device-tree compiler always created\n\t * device trees with this order.\n\t *\n\t * This assumption disables a check in fdt_open_into() and removes the\n\t * ability to fix the problem there. This is safe if you know that the\n\t * device tree is correctly ordered. See fdt_blocks_misordered_().\n\t */\n\tASSUME_LIBFDT_ORDER\t= 1 << 4,\n\n\t/*\n\t * This assumes that libfdt itself does not have any internal bugs. It\n\t * drops certain checks that should never be needed unless libfdt has an\n\t * undiscovered bug.\n\t *\n\t * This can generally be considered safe to enable.\n\t */\n\tASSUME_LIBFDT_FLAWLESS\t= 1 << 5,\n};\n\n/**\n * can_assume_() - check if a particular assumption is enabled\n *\n * @mask: Mask to check (ASSUME_...)\n * @return true if that assumption is enabled, else false\n */\nstatic inline bool can_assume_(int mask)\n{\n\treturn FDT_ASSUME_MASK & mask;\n}\n\n/** helper macros for checking assumptions */\n#define can_assume(_assume)\tcan_assume_(ASSUME_ ## _assume)\n\n#endif /* LIBFDT_INTERNAL_H */\n"
  },
  {
    "path": "external/lz4/lz4.c",
    "content": "/*\n   LZ4 - Fast LZ compression algorithm\n   Copyright (C) 2011-present, Yann Collet.\n\n   BSD 2-Clause License (http://www.opensource.org/licenses/bsd-license.php)\n\n   Redistribution and use in source and binary forms, with or without\n   modification, are permitted provided that the following conditions are\n   met:\n\n       * Redistributions of source code must retain the above copyright\n   notice, this list of conditions and the following disclaimer.\n       * Redistributions in binary form must reproduce the above\n   copyright notice, this list of conditions and the following disclaimer\n   in the documentation and/or other materials provided with the\n   distribution.\n\n   THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\n   \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\n   LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR\n   A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT\n   OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,\n   SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT\n   LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,\n   DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY\n   THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\n   (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE\n   OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n\n   You can contact the author at :\n    - LZ4 homepage : http://www.lz4.org\n    - LZ4 source repository : https://github.com/lz4/lz4\n*/\n\n/*-************************************\n*  Tuning parameters\n**************************************/\n/*\n * LZ4_HEAPMODE :\n * Select how default compression functions will allocate memory for their hash table,\n * in memory stack (0:default, fastest), or in memory heap (1:requires malloc()).\n */\n#ifndef LZ4_HEAPMODE\n#  define LZ4_HEAPMODE 0\n#endif\n\n/*\n * LZ4_ACCELERATION_DEFAULT :\n * Select \"acceleration\" for LZ4_compress_fast() when parameter value <= 0\n */\n#define LZ4_ACCELERATION_DEFAULT 1\n/*\n * LZ4_ACCELERATION_MAX :\n * Any \"acceleration\" value higher than this threshold\n * get treated as LZ4_ACCELERATION_MAX instead (fix #876)\n */\n#define LZ4_ACCELERATION_MAX 65537\n\n\n/*-************************************\n*  CPU Feature Detection\n**************************************/\n/* LZ4_FORCE_MEMORY_ACCESS\n * By default, access to unaligned memory is controlled by `memcpy()`, which is safe and portable.\n * Unfortunately, on some target/compiler combinations, the generated assembly is sub-optimal.\n * The below switch allow to select different access method for improved performance.\n * Method 0 (default) : use `memcpy()`. Safe and portable.\n * Method 1 : `__packed` statement. It depends on compiler extension (ie, not portable).\n *            This method is safe if your compiler supports it, and *generally* as fast or faster than `memcpy`.\n * Method 2 : direct access. This method is portable but violate C standard.\n *            It can generate buggy code on targets which assembly generation depends on alignment.\n *            But in some circumstances, it's the only known way to get the most performance (ie GCC + ARMv6)\n * See https://fastcompression.blogspot.fr/2015/08/accessing-unaligned-memory.html for details.\n * Prefer these methods in priority order (0 > 1 > 2)\n */\n#ifndef LZ4_FORCE_MEMORY_ACCESS   /* can be defined externally */\n#  if defined(__GNUC__) && \\\n  ( defined(__ARM_ARCH_6__) || defined(__ARM_ARCH_6J__) || defined(__ARM_ARCH_6K__) \\\n  || defined(__ARM_ARCH_6Z__) || defined(__ARM_ARCH_6ZK__) || defined(__ARM_ARCH_6T2__) )\n#    define LZ4_FORCE_MEMORY_ACCESS 2\n#  elif (defined(__INTEL_COMPILER) && !defined(_WIN32)) || defined(__GNUC__)\n#    define LZ4_FORCE_MEMORY_ACCESS 1\n#  endif\n#endif\n\n/*\n * LZ4_FORCE_SW_BITCOUNT\n * Define this parameter if your target system or compiler does not support hardware bit count\n */\n#if defined(_MSC_VER) && defined(_WIN32_WCE)   /* Visual Studio for WinCE doesn't support Hardware bit count */\n#  undef  LZ4_FORCE_SW_BITCOUNT  /* avoid double def */\n#  define LZ4_FORCE_SW_BITCOUNT\n#endif\n\n\n\n/*-************************************\n*  Dependency\n**************************************/\n/*\n * LZ4_SRC_INCLUDED:\n * Amalgamation flag, whether lz4.c is included\n */\n#ifndef LZ4_SRC_INCLUDED\n#  define LZ4_SRC_INCLUDED 1\n#endif\n\n#ifndef LZ4_STATIC_LINKING_ONLY\n#define LZ4_STATIC_LINKING_ONLY\n#endif\n\n#ifndef LZ4_DISABLE_DEPRECATE_WARNINGS\n#define LZ4_DISABLE_DEPRECATE_WARNINGS /* due to LZ4_decompress_safe_withPrefix64k */\n#endif\n\n#define LZ4_STATIC_LINKING_ONLY  /* LZ4_DISTANCE_MAX */\n#include \"lz4.h\"\n/* see also \"memory routines\" below */\n\n\n/*-************************************\n*  Compiler Options\n**************************************/\n#if defined(_MSC_VER) && (_MSC_VER >= 1400)  /* Visual Studio 2005+ */\n#  include <intrin.h>               /* only present in VS2005+ */\n#  pragma warning(disable : 4127)   /* disable: C4127: conditional expression is constant */\n#endif  /* _MSC_VER */\n\n#ifndef LZ4_FORCE_INLINE\n#  ifdef _MSC_VER    /* Visual Studio */\n#    define LZ4_FORCE_INLINE static __forceinline\n#  else\n#    if defined (__cplusplus) || defined (__STDC_VERSION__) && __STDC_VERSION__ >= 199901L   /* C99 */\n#      ifdef __GNUC__\n#        define LZ4_FORCE_INLINE static inline __attribute__((always_inline))\n#      else\n#        define LZ4_FORCE_INLINE static inline\n#      endif\n#    else\n#      define LZ4_FORCE_INLINE static\n#    endif /* __STDC_VERSION__ */\n#  endif  /* _MSC_VER */\n#endif /* LZ4_FORCE_INLINE */\n\n/* LZ4_FORCE_O2 and LZ4_FORCE_INLINE\n * gcc on ppc64le generates an unrolled SIMDized loop for LZ4_wildCopy8,\n * together with a simple 8-byte copy loop as a fall-back path.\n * However, this optimization hurts the decompression speed by >30%,\n * because the execution does not go to the optimized loop\n * for typical compressible data, and all of the preamble checks\n * before going to the fall-back path become useless overhead.\n * This optimization happens only with the -O3 flag, and -O2 generates\n * a simple 8-byte copy loop.\n * With gcc on ppc64le, all of the LZ4_decompress_* and LZ4_wildCopy8\n * functions are annotated with __attribute__((optimize(\"O2\"))),\n * and also LZ4_wildCopy8 is forcibly inlined, so that the O2 attribute\n * of LZ4_wildCopy8 does not affect the compression speed.\n */\n#if defined(__PPC64__) && defined(__LITTLE_ENDIAN__) && defined(__GNUC__) && !defined(__clang__)\n#  define LZ4_FORCE_O2  __attribute__((optimize(\"O2\")))\n#  undef LZ4_FORCE_INLINE\n#  define LZ4_FORCE_INLINE  static __inline __attribute__((optimize(\"O2\"),always_inline))\n#else\n#  define LZ4_FORCE_O2\n#endif\n\n#if (defined(__GNUC__) && (__GNUC__ >= 3)) || (defined(__INTEL_COMPILER) && (__INTEL_COMPILER >= 800)) || defined(__clang__)\n#  define expect(expr,value)    (__builtin_expect ((expr),(value)) )\n#else\n#  define expect(expr,value)    (expr)\n#endif\n\n#ifndef likely\n#define likely(expr)     expect((expr) != 0, 1)\n#endif\n#ifndef unlikely\n#define unlikely(expr)   expect((expr) != 0, 0)\n#endif\n\n/* Should the alignment test prove unreliable, for some reason,\n * it can be disabled by setting LZ4_ALIGN_TEST to 0 */\n#ifndef LZ4_ALIGN_TEST  /* can be externally provided */\n# define LZ4_ALIGN_TEST 1\n#endif\n\n\n/*-************************************\n*  Memory routines\n**************************************/\n#ifdef LZ4_USER_MEMORY_FUNCTIONS\n/* memory management functions can be customized by user project.\n * Below functions must exist somewhere in the Project\n * and be available at link time */\nvoid* LZ4_malloc(size_t s);\nvoid* LZ4_calloc(size_t n, size_t s);\nvoid  LZ4_free(void* p);\n# define ALLOC(s)          LZ4_malloc(s)\n# define ALLOC_AND_ZERO(s) LZ4_calloc(1,s)\n# define FREEMEM(p)        LZ4_free(p)\n#else\n# include <stdlib.h>   /* malloc, calloc, free */\n# define ALLOC(s)          malloc(s)\n# define ALLOC_AND_ZERO(s) calloc(1,s)\n# define FREEMEM(p)        free(p)\n#endif\n\n#include <string.h>   /* memset, memcpy */\n#define MEM_INIT(p,v,s)   memset((p),(v),(s))\n\n\n/*-************************************\n*  Common Constants\n**************************************/\n#define MINMATCH 4\n\n#define WILDCOPYLENGTH 8\n#define LASTLITERALS   5   /* see ../doc/lz4_Block_format.md#parsing-restrictions */\n#define MFLIMIT       12   /* see ../doc/lz4_Block_format.md#parsing-restrictions */\n#define MATCH_SAFEGUARD_DISTANCE  ((2*WILDCOPYLENGTH) - MINMATCH)   /* ensure it's possible to write 2 x wildcopyLength without overflowing output buffer */\n#define FASTLOOP_SAFE_DISTANCE 64\nstatic const int LZ4_minLength = (MFLIMIT+1);\n\n#define KB *(1 <<10)\n#define MB *(1 <<20)\n#define GB *(1U<<30)\n\n#define LZ4_DISTANCE_ABSOLUTE_MAX 65535\n#if (LZ4_DISTANCE_MAX > LZ4_DISTANCE_ABSOLUTE_MAX)   /* max supported by LZ4 format */\n#  error \"LZ4_DISTANCE_MAX is too big : must be <= 65535\"\n#endif\n\n#define ML_BITS  4\n#define ML_MASK  ((1U<<ML_BITS)-1)\n#define RUN_BITS (8-ML_BITS)\n#define RUN_MASK ((1U<<RUN_BITS)-1)\n\n\n/*-************************************\n*  Error detection\n**************************************/\n#if defined(LZ4_DEBUG) && (LZ4_DEBUG>=1)\n#  include <assert.h>\n#else\n#  ifndef assert\n#    define assert(condition) ((void)0)\n#  endif\n#endif\n\n#define LZ4_STATIC_ASSERT(c)   { enum { LZ4_static_assert = 1/(int)(!!(c)) }; }   /* use after variable declarations */\n\n#if defined(LZ4_DEBUG) && (LZ4_DEBUG>=2)\n#  include <stdio.h>\n   static int g_debuglog_enable = 1;\n#  define DEBUGLOG(l, ...) {                          \\\n        if ((g_debuglog_enable) && (l<=LZ4_DEBUG)) {  \\\n            fprintf(stderr, __FILE__ \": \");           \\\n            fprintf(stderr, __VA_ARGS__);             \\\n            fprintf(stderr, \" \\n\");                   \\\n    }   }\n#else\n#  define DEBUGLOG(l, ...) {}    /* disabled */\n#endif\n\nstatic int LZ4_isAligned(const void* ptr, size_t alignment)\n{\n    return ((size_t)ptr & (alignment -1)) == 0;\n}\n\n\n/*-************************************\n*  Types\n**************************************/\n#include <limits.h>\n#if defined(__cplusplus) || (defined (__STDC_VERSION__) && (__STDC_VERSION__ >= 199901L) /* C99 */)\n# include <stdint.h>\n  typedef  uint8_t BYTE;\n  typedef uint16_t U16;\n  typedef uint32_t U32;\n  typedef  int32_t S32;\n  typedef uint64_t U64;\n  typedef uintptr_t uptrval;\n#else\n# if UINT_MAX != 4294967295UL\n#   error \"LZ4 code (when not C++ or C99) assumes that sizeof(int) == 4\"\n# endif\n  typedef unsigned char       BYTE;\n  typedef unsigned short      U16;\n  typedef unsigned int        U32;\n  typedef   signed int        S32;\n  typedef unsigned long long  U64;\n  typedef size_t              uptrval;   /* generally true, except OpenVMS-64 */\n#endif\n\n#if defined(__x86_64__)\n  typedef U64    reg_t;   /* 64-bits in x32 mode */\n#else\n  typedef size_t reg_t;   /* 32-bits in x32 mode */\n#endif\n\ntypedef enum {\n    notLimited = 0,\n    limitedOutput = 1,\n    fillOutput = 2\n} limitedOutput_directive;\n\n\n/*-************************************\n*  Reading and writing into memory\n**************************************/\n\n/**\n * LZ4 relies on memcpy with a constant size being inlined. In freestanding\n * environments, the compiler can't assume the implementation of memcpy() is\n * standard compliant, so it can't apply its specialized memcpy() inlining\n * logic. When possible, use __builtin_memcpy() to tell the compiler to analyze\n * memcpy() as if it were standard compliant, so it can inline it in freestanding\n * environments. This is needed when decompressing the Linux Kernel, for example.\n */\n#if defined(__GNUC__) && (__GNUC__ >= 4)\n#define LZ4_memcpy(dst, src, size) __builtin_memcpy(dst, src, size)\n#else\n#define LZ4_memcpy(dst, src, size) memcpy(dst, src, size)\n#endif\n\nstatic unsigned LZ4_isLittleEndian(void)\n{\n    const union { U32 u; BYTE c[4]; } one = { 1 };   /* don't use static : performance detrimental */\n    return one.c[0];\n}\n\n\n#if defined(LZ4_FORCE_MEMORY_ACCESS) && (LZ4_FORCE_MEMORY_ACCESS==2)\n/* lie to the compiler about data alignment; use with caution */\n\nstatic U16 LZ4_read16(const void* memPtr) { return *(const U16*) memPtr; }\nstatic U32 LZ4_read32(const void* memPtr) { return *(const U32*) memPtr; }\nstatic reg_t LZ4_read_ARCH(const void* memPtr) { return *(const reg_t*) memPtr; }\n\nstatic void LZ4_write16(void* memPtr, U16 value) { *(U16*)memPtr = value; }\nstatic void LZ4_write32(void* memPtr, U32 value) { *(U32*)memPtr = value; }\n\n#elif defined(LZ4_FORCE_MEMORY_ACCESS) && (LZ4_FORCE_MEMORY_ACCESS==1)\n\n/* __pack instructions are safer, but compiler specific, hence potentially problematic for some compilers */\n/* currently only defined for gcc and icc */\ntypedef union { U16 u16; U32 u32; reg_t uArch; } __attribute__((packed)) unalign;\n\nstatic U16 LZ4_read16(const void* ptr) { return ((const unalign*)ptr)->u16; }\nstatic U32 LZ4_read32(const void* ptr) { return ((const unalign*)ptr)->u32; }\nstatic reg_t LZ4_read_ARCH(const void* ptr) { return ((const unalign*)ptr)->uArch; }\n\nstatic void LZ4_write16(void* memPtr, U16 value) { ((unalign*)memPtr)->u16 = value; }\nstatic void LZ4_write32(void* memPtr, U32 value) { ((unalign*)memPtr)->u32 = value; }\n\n#else  /* safe and portable access using memcpy() */\n\nstatic U16 LZ4_read16(const void* memPtr)\n{\n    U16 val; LZ4_memcpy(&val, memPtr, sizeof(val)); return val;\n}\n\nstatic U32 LZ4_read32(const void* memPtr)\n{\n    U32 val; LZ4_memcpy(&val, memPtr, sizeof(val)); return val;\n}\n\nstatic reg_t LZ4_read_ARCH(const void* memPtr)\n{\n    reg_t val; LZ4_memcpy(&val, memPtr, sizeof(val)); return val;\n}\n\nstatic void LZ4_write16(void* memPtr, U16 value)\n{\n    LZ4_memcpy(memPtr, &value, sizeof(value));\n}\n\nstatic void LZ4_write32(void* memPtr, U32 value)\n{\n    LZ4_memcpy(memPtr, &value, sizeof(value));\n}\n\n#endif /* LZ4_FORCE_MEMORY_ACCESS */\n\n\nstatic U16 LZ4_readLE16(const void* memPtr)\n{\n    if (LZ4_isLittleEndian()) {\n        return LZ4_read16(memPtr);\n    } else {\n        const BYTE* p = (const BYTE*)memPtr;\n        return (U16)((U16)p[0] + (p[1]<<8));\n    }\n}\n\nstatic void LZ4_writeLE16(void* memPtr, U16 value)\n{\n    if (LZ4_isLittleEndian()) {\n        LZ4_write16(memPtr, value);\n    } else {\n        BYTE* p = (BYTE*)memPtr;\n        p[0] = (BYTE) value;\n        p[1] = (BYTE)(value>>8);\n    }\n}\n\n/* customized variant of memcpy, which can overwrite up to 8 bytes beyond dstEnd */\nLZ4_FORCE_INLINE\nvoid LZ4_wildCopy8(void* dstPtr, const void* srcPtr, void* dstEnd)\n{\n    BYTE* d = (BYTE*)dstPtr;\n    const BYTE* s = (const BYTE*)srcPtr;\n    BYTE* const e = (BYTE*)dstEnd;\n\n    do { LZ4_memcpy(d,s,8); d+=8; s+=8; } while (d<e);\n}\n\nstatic const unsigned inc32table[8] = {0, 1, 2,  1,  0,  4, 4, 4};\nstatic const int      dec64table[8] = {0, 0, 0, -1, -4,  1, 2, 3};\n\n\n#ifndef LZ4_FAST_DEC_LOOP\n#  if defined __i386__ || defined _M_IX86 || defined __x86_64__ || defined _M_X64\n#    define LZ4_FAST_DEC_LOOP 1\n#  elif defined(__aarch64__) && !defined(__clang__)\n     /* On aarch64, we disable this optimization for clang because on certain\n      * mobile chipsets, performance is reduced with clang. For information\n      * refer to https://github.com/lz4/lz4/pull/707 */\n#    define LZ4_FAST_DEC_LOOP 1\n#  else\n#    define LZ4_FAST_DEC_LOOP 0\n#  endif\n#endif\n\n#if LZ4_FAST_DEC_LOOP\n\nLZ4_FORCE_INLINE void\nLZ4_memcpy_using_offset_base(BYTE* dstPtr, const BYTE* srcPtr, BYTE* dstEnd, const size_t offset)\n{\n    assert(srcPtr + offset == dstPtr);\n    if (offset < 8) {\n        LZ4_write32(dstPtr, 0);   /* silence an msan warning when offset==0 */\n        dstPtr[0] = srcPtr[0];\n        dstPtr[1] = srcPtr[1];\n        dstPtr[2] = srcPtr[2];\n        dstPtr[3] = srcPtr[3];\n        srcPtr += inc32table[offset];\n        LZ4_memcpy(dstPtr+4, srcPtr, 4);\n        srcPtr -= dec64table[offset];\n        dstPtr += 8;\n    } else {\n        LZ4_memcpy(dstPtr, srcPtr, 8);\n        dstPtr += 8;\n        srcPtr += 8;\n    }\n\n    LZ4_wildCopy8(dstPtr, srcPtr, dstEnd);\n}\n\n/* customized variant of memcpy, which can overwrite up to 32 bytes beyond dstEnd\n * this version copies two times 16 bytes (instead of one time 32 bytes)\n * because it must be compatible with offsets >= 16. */\nLZ4_FORCE_INLINE void\nLZ4_wildCopy32(void* dstPtr, const void* srcPtr, void* dstEnd)\n{\n    BYTE* d = (BYTE*)dstPtr;\n    const BYTE* s = (const BYTE*)srcPtr;\n    BYTE* const e = (BYTE*)dstEnd;\n\n    do { LZ4_memcpy(d,s,16); LZ4_memcpy(d+16,s+16,16); d+=32; s+=32; } while (d<e);\n}\n\n/* LZ4_memcpy_using_offset()  presumes :\n * - dstEnd >= dstPtr + MINMATCH\n * - there is at least 8 bytes available to write after dstEnd */\nLZ4_FORCE_INLINE void\nLZ4_memcpy_using_offset(BYTE* dstPtr, const BYTE* srcPtr, BYTE* dstEnd, const size_t offset)\n{\n    BYTE v[8];\n\n    assert(dstEnd >= dstPtr + MINMATCH);\n\n    switch(offset) {\n    case 1:\n        MEM_INIT(v, *srcPtr, 8);\n        break;\n    case 2:\n        LZ4_memcpy(v, srcPtr, 2);\n        LZ4_memcpy(&v[2], srcPtr, 2);\n        LZ4_memcpy(&v[4], v, 4);\n        break;\n    case 4:\n        LZ4_memcpy(v, srcPtr, 4);\n        LZ4_memcpy(&v[4], srcPtr, 4);\n        break;\n    default:\n        LZ4_memcpy_using_offset_base(dstPtr, srcPtr, dstEnd, offset);\n        return;\n    }\n\n    LZ4_memcpy(dstPtr, v, 8);\n    dstPtr += 8;\n    while (dstPtr < dstEnd) {\n        LZ4_memcpy(dstPtr, v, 8);\n        dstPtr += 8;\n    }\n}\n#endif\n\n\n/*-************************************\n*  Common functions\n**************************************/\nstatic unsigned LZ4_NbCommonBytes (reg_t val)\n{\n    assert(val != 0);\n    if (LZ4_isLittleEndian()) {\n        if (sizeof(val) == 8) {\n#       if defined(_MSC_VER) && (_MSC_VER >= 1800) && defined(_M_AMD64) && !defined(LZ4_FORCE_SW_BITCOUNT)\n            /* x64 CPUS without BMI support interpret `TZCNT` as `REP BSF` */\n            return (unsigned)_tzcnt_u64(val) >> 3;\n#       elif defined(_MSC_VER) && defined(_WIN64) && !defined(LZ4_FORCE_SW_BITCOUNT)\n            unsigned long r = 0;\n            _BitScanForward64(&r, (U64)val);\n            return (unsigned)r >> 3;\n#       elif (defined(__clang__) || (defined(__GNUC__) && ((__GNUC__ > 3) || \\\n                            ((__GNUC__ == 3) && (__GNUC_MINOR__ >= 4))))) && \\\n                                        !defined(LZ4_FORCE_SW_BITCOUNT)\n            return (unsigned)__builtin_ctzll((U64)val) >> 3;\n#       else\n            const U64 m = 0x0101010101010101ULL;\n            val ^= val - 1;\n            return (unsigned)(((U64)((val & (m - 1)) * m)) >> 56);\n#       endif\n        } else /* 32 bits */ {\n#       if defined(_MSC_VER) && (_MSC_VER >= 1400) && !defined(LZ4_FORCE_SW_BITCOUNT)\n            unsigned long r;\n            _BitScanForward(&r, (U32)val);\n            return (unsigned)r >> 3;\n#       elif (defined(__clang__) || (defined(__GNUC__) && ((__GNUC__ > 3) || \\\n                            ((__GNUC__ == 3) && (__GNUC_MINOR__ >= 4))))) && \\\n                        !defined(__TINYC__) && !defined(LZ4_FORCE_SW_BITCOUNT)\n            return (unsigned)__builtin_ctz((U32)val) >> 3;\n#       else\n            const U32 m = 0x01010101;\n            return (unsigned)((((val - 1) ^ val) & (m - 1)) * m) >> 24;\n#       endif\n        }\n    } else   /* Big Endian CPU */ {\n        if (sizeof(val)==8) {\n#       if (defined(__clang__) || (defined(__GNUC__) && ((__GNUC__ > 3) || \\\n                            ((__GNUC__ == 3) && (__GNUC_MINOR__ >= 4))))) && \\\n                        !defined(__TINYC__) && !defined(LZ4_FORCE_SW_BITCOUNT)\n            return (unsigned)__builtin_clzll((U64)val) >> 3;\n#       else\n#if 1\n            /* this method is probably faster,\n             * but adds a 128 bytes lookup table */\n            static const unsigned char ctz7_tab[128] = {\n                7, 0, 1, 0, 2, 0, 1, 0, 3, 0, 1, 0, 2, 0, 1, 0,\n                4, 0, 1, 0, 2, 0, 1, 0, 3, 0, 1, 0, 2, 0, 1, 0,\n                5, 0, 1, 0, 2, 0, 1, 0, 3, 0, 1, 0, 2, 0, 1, 0,\n                4, 0, 1, 0, 2, 0, 1, 0, 3, 0, 1, 0, 2, 0, 1, 0,\n                6, 0, 1, 0, 2, 0, 1, 0, 3, 0, 1, 0, 2, 0, 1, 0,\n                4, 0, 1, 0, 2, 0, 1, 0, 3, 0, 1, 0, 2, 0, 1, 0,\n                5, 0, 1, 0, 2, 0, 1, 0, 3, 0, 1, 0, 2, 0, 1, 0,\n                4, 0, 1, 0, 2, 0, 1, 0, 3, 0, 1, 0, 2, 0, 1, 0,\n            };\n            U64 const mask = 0x0101010101010101ULL;\n            U64 const t = (((val >> 8) - mask) | val) & mask;\n            return ctz7_tab[(t * 0x0080402010080402ULL) >> 57];\n#else\n            /* this method doesn't consume memory space like the previous one,\n             * but it contains several branches,\n             * that may end up slowing execution */\n            static const U32 by32 = sizeof(val)*4;  /* 32 on 64 bits (goal), 16 on 32 bits.\n            Just to avoid some static analyzer complaining about shift by 32 on 32-bits target.\n            Note that this code path is never triggered in 32-bits mode. */\n            unsigned r;\n            if (!(val>>by32)) { r=4; } else { r=0; val>>=by32; }\n            if (!(val>>16)) { r+=2; val>>=8; } else { val>>=24; }\n            r += (!val);\n            return r;\n#endif\n#       endif\n        } else /* 32 bits */ {\n#       if (defined(__clang__) || (defined(__GNUC__) && ((__GNUC__ > 3) || \\\n                            ((__GNUC__ == 3) && (__GNUC_MINOR__ >= 4))))) && \\\n                                        !defined(LZ4_FORCE_SW_BITCOUNT)\n            return (unsigned)__builtin_clz((U32)val) >> 3;\n#       else\n            val >>= 8;\n            val = ((((val + 0x00FFFF00) | 0x00FFFFFF) + val) |\n              (val + 0x00FF0000)) >> 24;\n            return (unsigned)val ^ 3;\n#       endif\n        }\n    }\n}\n\n\n#define STEPSIZE sizeof(reg_t)\nLZ4_FORCE_INLINE\nunsigned LZ4_count(const BYTE* pIn, const BYTE* pMatch, const BYTE* pInLimit)\n{\n    const BYTE* const pStart = pIn;\n\n    if (likely(pIn < pInLimit-(STEPSIZE-1))) {\n        reg_t const diff = LZ4_read_ARCH(pMatch) ^ LZ4_read_ARCH(pIn);\n        if (!diff) {\n            pIn+=STEPSIZE; pMatch+=STEPSIZE;\n        } else {\n            return LZ4_NbCommonBytes(diff);\n    }   }\n\n    while (likely(pIn < pInLimit-(STEPSIZE-1))) {\n        reg_t const diff = LZ4_read_ARCH(pMatch) ^ LZ4_read_ARCH(pIn);\n        if (!diff) { pIn+=STEPSIZE; pMatch+=STEPSIZE; continue; }\n        pIn += LZ4_NbCommonBytes(diff);\n        return (unsigned)(pIn - pStart);\n    }\n\n    if ((STEPSIZE==8) && (pIn<(pInLimit-3)) && (LZ4_read32(pMatch) == LZ4_read32(pIn))) { pIn+=4; pMatch+=4; }\n    if ((pIn<(pInLimit-1)) && (LZ4_read16(pMatch) == LZ4_read16(pIn))) { pIn+=2; pMatch+=2; }\n    if ((pIn<pInLimit) && (*pMatch == *pIn)) pIn++;\n    return (unsigned)(pIn - pStart);\n}\n\n\n#ifndef LZ4_COMMONDEFS_ONLY\n/*-************************************\n*  Local Constants\n**************************************/\nstatic const int LZ4_64Klimit = ((64 KB) + (MFLIMIT-1));\nstatic const U32 LZ4_skipTrigger = 6;  /* Increase this value ==> compression run slower on incompressible data */\n\n\n/*-************************************\n*  Local Structures and types\n**************************************/\ntypedef enum { clearedTable = 0, byPtr, byU32, byU16 } tableType_t;\n\n/**\n * This enum distinguishes several different modes of accessing previous\n * content in the stream.\n *\n * - noDict        : There is no preceding content.\n * - withPrefix64k : Table entries up to ctx->dictSize before the current blob\n *                   blob being compressed are valid and refer to the preceding\n *                   content (of length ctx->dictSize), which is available\n *                   contiguously preceding in memory the content currently\n *                   being compressed.\n * - usingExtDict  : Like withPrefix64k, but the preceding content is somewhere\n *                   else in memory, starting at ctx->dictionary with length\n *                   ctx->dictSize.\n * - usingDictCtx  : Like usingExtDict, but everything concerning the preceding\n *                   content is in a separate context, pointed to by\n *                   ctx->dictCtx. ctx->dictionary, ctx->dictSize, and table\n *                   entries in the current context that refer to positions\n *                   preceding the beginning of the current compression are\n *                   ignored. Instead, ctx->dictCtx->dictionary and ctx->dictCtx\n *                   ->dictSize describe the location and size of the preceding\n *                   content, and matches are found by looking in the ctx\n *                   ->dictCtx->hashTable.\n */\ntypedef enum { noDict = 0, withPrefix64k, usingExtDict, usingDictCtx } dict_directive;\ntypedef enum { noDictIssue = 0, dictSmall } dictIssue_directive;\n\n\n/*-************************************\n*  Local Utils\n**************************************/\nint LZ4_versionNumber (void) { return LZ4_VERSION_NUMBER; }\nconst char* LZ4_versionString(void) { return LZ4_VERSION_STRING; }\nint LZ4_compressBound(int isize)  { return LZ4_COMPRESSBOUND(isize); }\nint LZ4_sizeofState(void) { return LZ4_STREAMSIZE; }\n\n\n/*-************************************\n*  Internal Definitions used in Tests\n**************************************/\n#if defined (__cplusplus)\nextern \"C\" {\n#endif\n\nint LZ4_compress_forceExtDict (LZ4_stream_t* LZ4_dict, const char* source, char* dest, int srcSize);\n\nint LZ4_decompress_safe_forceExtDict(const char* source, char* dest,\n                                     int compressedSize, int maxOutputSize,\n                                     const void* dictStart, size_t dictSize);\n\n#if defined (__cplusplus)\n}\n#endif\n\n/*-******************************\n*  Compression functions\n********************************/\nLZ4_FORCE_INLINE U32 LZ4_hash4(U32 sequence, tableType_t const tableType)\n{\n    if (tableType == byU16)\n        return ((sequence * 2654435761U) >> ((MINMATCH*8)-(LZ4_HASHLOG+1)));\n    else\n        return ((sequence * 2654435761U) >> ((MINMATCH*8)-LZ4_HASHLOG));\n}\n\nLZ4_FORCE_INLINE U32 LZ4_hash5(U64 sequence, tableType_t const tableType)\n{\n    const U32 hashLog = (tableType == byU16) ? LZ4_HASHLOG+1 : LZ4_HASHLOG;\n    if (LZ4_isLittleEndian()) {\n        const U64 prime5bytes = 889523592379ULL;\n        return (U32)(((sequence << 24) * prime5bytes) >> (64 - hashLog));\n    } else {\n        const U64 prime8bytes = 11400714785074694791ULL;\n        return (U32)(((sequence >> 24) * prime8bytes) >> (64 - hashLog));\n    }\n}\n\nLZ4_FORCE_INLINE U32 LZ4_hashPosition(const void* const p, tableType_t const tableType)\n{\n    if ((sizeof(reg_t)==8) && (tableType != byU16)) return LZ4_hash5(LZ4_read_ARCH(p), tableType);\n    return LZ4_hash4(LZ4_read32(p), tableType);\n}\n\nLZ4_FORCE_INLINE void LZ4_clearHash(U32 h, void* tableBase, tableType_t const tableType)\n{\n    switch (tableType)\n    {\n    default: /* fallthrough */\n    case clearedTable: { /* illegal! */ assert(0); return; }\n    case byPtr: { const BYTE** hashTable = (const BYTE**)tableBase; hashTable[h] = NULL; return; }\n    case byU32: { U32* hashTable = (U32*) tableBase; hashTable[h] = 0; return; }\n    case byU16: { U16* hashTable = (U16*) tableBase; hashTable[h] = 0; return; }\n    }\n}\n\nLZ4_FORCE_INLINE void LZ4_putIndexOnHash(U32 idx, U32 h, void* tableBase, tableType_t const tableType)\n{\n    switch (tableType)\n    {\n    default: /* fallthrough */\n    case clearedTable: /* fallthrough */\n    case byPtr: { /* illegal! */ assert(0); return; }\n    case byU32: { U32* hashTable = (U32*) tableBase; hashTable[h] = idx; return; }\n    case byU16: { U16* hashTable = (U16*) tableBase; assert(idx < 65536); hashTable[h] = (U16)idx; return; }\n    }\n}\n\nLZ4_FORCE_INLINE void LZ4_putPositionOnHash(const BYTE* p, U32 h,\n                                  void* tableBase, tableType_t const tableType,\n                            const BYTE* srcBase)\n{\n    switch (tableType)\n    {\n    case clearedTable: { /* illegal! */ assert(0); return; }\n    case byPtr: { const BYTE** hashTable = (const BYTE**)tableBase; hashTable[h] = p; return; }\n    case byU32: { U32* hashTable = (U32*) tableBase; hashTable[h] = (U32)(p-srcBase); return; }\n    case byU16: { U16* hashTable = (U16*) tableBase; hashTable[h] = (U16)(p-srcBase); return; }\n    }\n}\n\nLZ4_FORCE_INLINE void LZ4_putPosition(const BYTE* p, void* tableBase, tableType_t tableType, const BYTE* srcBase)\n{\n    U32 const h = LZ4_hashPosition(p, tableType);\n    LZ4_putPositionOnHash(p, h, tableBase, tableType, srcBase);\n}\n\n/* LZ4_getIndexOnHash() :\n * Index of match position registered in hash table.\n * hash position must be calculated by using base+index, or dictBase+index.\n * Assumption 1 : only valid if tableType == byU32 or byU16.\n * Assumption 2 : h is presumed valid (within limits of hash table)\n */\nLZ4_FORCE_INLINE U32 LZ4_getIndexOnHash(U32 h, const void* tableBase, tableType_t tableType)\n{\n    LZ4_STATIC_ASSERT(LZ4_MEMORY_USAGE > 2);\n    if (tableType == byU32) {\n        const U32* const hashTable = (const U32*) tableBase;\n        assert(h < (1U << (LZ4_MEMORY_USAGE-2)));\n        return hashTable[h];\n    }\n    if (tableType == byU16) {\n        const U16* const hashTable = (const U16*) tableBase;\n        assert(h < (1U << (LZ4_MEMORY_USAGE-1)));\n        return hashTable[h];\n    }\n    assert(0); return 0;  /* forbidden case */\n}\n\nstatic const BYTE* LZ4_getPositionOnHash(U32 h, const void* tableBase, tableType_t tableType, const BYTE* srcBase)\n{\n    if (tableType == byPtr) { const BYTE* const* hashTable = (const BYTE* const*) tableBase; return hashTable[h]; }\n    if (tableType == byU32) { const U32* const hashTable = (const U32*) tableBase; return hashTable[h] + srcBase; }\n    { const U16* const hashTable = (const U16*) tableBase; return hashTable[h] + srcBase; }   /* default, to ensure a return */\n}\n\nLZ4_FORCE_INLINE const BYTE*\nLZ4_getPosition(const BYTE* p,\n                const void* tableBase, tableType_t tableType,\n                const BYTE* srcBase)\n{\n    U32 const h = LZ4_hashPosition(p, tableType);\n    return LZ4_getPositionOnHash(h, tableBase, tableType, srcBase);\n}\n\nLZ4_FORCE_INLINE void\nLZ4_prepareTable(LZ4_stream_t_internal* const cctx,\n           const int inputSize,\n           const tableType_t tableType) {\n    /* If the table hasn't been used, it's guaranteed to be zeroed out, and is\n     * therefore safe to use no matter what mode we're in. Otherwise, we figure\n     * out if it's safe to leave as is or whether it needs to be reset.\n     */\n    if ((tableType_t)cctx->tableType != clearedTable) {\n        assert(inputSize >= 0);\n        if ((tableType_t)cctx->tableType != tableType\n          || ((tableType == byU16) && cctx->currentOffset + (unsigned)inputSize >= 0xFFFFU)\n          || ((tableType == byU32) && cctx->currentOffset > 1 GB)\n          || tableType == byPtr\n          || inputSize >= 4 KB)\n        {\n            DEBUGLOG(4, \"LZ4_prepareTable: Resetting table in %p\", cctx);\n            MEM_INIT(cctx->hashTable, 0, LZ4_HASHTABLESIZE);\n            cctx->currentOffset = 0;\n            cctx->tableType = (U32)clearedTable;\n        } else {\n            DEBUGLOG(4, \"LZ4_prepareTable: Re-use hash table (no reset)\");\n        }\n    }\n\n    /* Adding a gap, so all previous entries are > LZ4_DISTANCE_MAX back, is faster\n     * than compressing without a gap. However, compressing with\n     * currentOffset == 0 is faster still, so we preserve that case.\n     */\n    if (cctx->currentOffset != 0 && tableType == byU32) {\n        DEBUGLOG(5, \"LZ4_prepareTable: adding 64KB to currentOffset\");\n        cctx->currentOffset += 64 KB;\n    }\n\n    /* Finally, clear history */\n    cctx->dictCtx = NULL;\n    cctx->dictionary = NULL;\n    cctx->dictSize = 0;\n}\n\n/** LZ4_compress_generic() :\n *  inlined, to ensure branches are decided at compilation time.\n *  Presumed already validated at this stage:\n *  - source != NULL\n *  - inputSize > 0\n */\nLZ4_FORCE_INLINE int LZ4_compress_generic_validated(\n                 LZ4_stream_t_internal* const cctx,\n                 const char* const source,\n                 char* const dest,\n                 const int inputSize,\n                 int *inputConsumed, /* only written when outputDirective == fillOutput */\n                 const int maxOutputSize,\n                 const limitedOutput_directive outputDirective,\n                 const tableType_t tableType,\n                 const dict_directive dictDirective,\n                 const dictIssue_directive dictIssue,\n                 const int acceleration)\n{\n    int result;\n    const BYTE* ip = (const BYTE*) source;\n\n    U32 const startIndex = cctx->currentOffset;\n    const BYTE* base = (const BYTE*) source - startIndex;\n    const BYTE* lowLimit;\n\n    const LZ4_stream_t_internal* dictCtx = (const LZ4_stream_t_internal*) cctx->dictCtx;\n    const BYTE* const dictionary =\n        dictDirective == usingDictCtx ? dictCtx->dictionary : cctx->dictionary;\n    const U32 dictSize =\n        dictDirective == usingDictCtx ? dictCtx->dictSize : cctx->dictSize;\n    const U32 dictDelta = (dictDirective == usingDictCtx) ? startIndex - dictCtx->currentOffset : 0;   /* make indexes in dictCtx comparable with index in current context */\n\n    int const maybe_extMem = (dictDirective == usingExtDict) || (dictDirective == usingDictCtx);\n    U32 const prefixIdxLimit = startIndex - dictSize;   /* used when dictDirective == dictSmall */\n    const BYTE* const dictEnd = dictionary ? dictionary + dictSize : dictionary;\n    const BYTE* anchor = (const BYTE*) source;\n    const BYTE* const iend = ip + inputSize;\n    const BYTE* const mflimitPlusOne = iend - MFLIMIT + 1;\n    const BYTE* const matchlimit = iend - LASTLITERALS;\n\n    /* the dictCtx currentOffset is indexed on the start of the dictionary,\n     * while a dictionary in the current context precedes the currentOffset */\n    const BYTE* dictBase = !dictionary ? NULL : (dictDirective == usingDictCtx) ?\n                            dictionary + dictSize - dictCtx->currentOffset :\n                            dictionary + dictSize - startIndex;\n\n    BYTE* op = (BYTE*) dest;\n    BYTE* const olimit = op + maxOutputSize;\n\n    U32 offset = 0;\n    U32 forwardH;\n\n    DEBUGLOG(5, \"LZ4_compress_generic_validated: srcSize=%i, tableType=%u\", inputSize, tableType);\n    assert(ip != NULL);\n    /* If init conditions are not met, we don't have to mark stream\n     * as having dirty context, since no action was taken yet */\n    if (outputDirective == fillOutput && maxOutputSize < 1) { return 0; } /* Impossible to store anything */\n    if ((tableType == byU16) && (inputSize>=LZ4_64Klimit)) { return 0; }  /* Size too large (not within 64K limit) */\n    if (tableType==byPtr) assert(dictDirective==noDict);      /* only supported use case with byPtr */\n    assert(acceleration >= 1);\n\n    lowLimit = (const BYTE*)source - (dictDirective == withPrefix64k ? dictSize : 0);\n\n    /* Update context state */\n    if (dictDirective == usingDictCtx) {\n        /* Subsequent linked blocks can't use the dictionary. */\n        /* Instead, they use the block we just compressed. */\n        cctx->dictCtx = NULL;\n        cctx->dictSize = (U32)inputSize;\n    } else {\n        cctx->dictSize += (U32)inputSize;\n    }\n    cctx->currentOffset += (U32)inputSize;\n    cctx->tableType = (U32)tableType;\n\n    if (inputSize<LZ4_minLength) goto _last_literals;        /* Input too small, no compression (all literals) */\n\n    /* First Byte */\n    LZ4_putPosition(ip, cctx->hashTable, tableType, base);\n    ip++; forwardH = LZ4_hashPosition(ip, tableType);\n\n    /* Main Loop */\n    for ( ; ; ) {\n        const BYTE* match;\n        BYTE* token;\n        const BYTE* filledIp;\n\n        /* Find a match */\n        if (tableType == byPtr) {\n            const BYTE* forwardIp = ip;\n            int step = 1;\n            int searchMatchNb = acceleration << LZ4_skipTrigger;\n            do {\n                U32 const h = forwardH;\n                ip = forwardIp;\n                forwardIp += step;\n                step = (searchMatchNb++ >> LZ4_skipTrigger);\n\n                if (unlikely(forwardIp > mflimitPlusOne)) goto _last_literals;\n                assert(ip < mflimitPlusOne);\n\n                match = LZ4_getPositionOnHash(h, cctx->hashTable, tableType, base);\n                forwardH = LZ4_hashPosition(forwardIp, tableType);\n                LZ4_putPositionOnHash(ip, h, cctx->hashTable, tableType, base);\n\n            } while ( (match+LZ4_DISTANCE_MAX < ip)\n                   || (LZ4_read32(match) != LZ4_read32(ip)) );\n\n        } else {   /* byU32, byU16 */\n\n            const BYTE* forwardIp = ip;\n            int step = 1;\n            int searchMatchNb = acceleration << LZ4_skipTrigger;\n            do {\n                U32 const h = forwardH;\n                U32 const current = (U32)(forwardIp - base);\n                U32 matchIndex = LZ4_getIndexOnHash(h, cctx->hashTable, tableType);\n                assert(matchIndex <= current);\n                assert(forwardIp - base < (ptrdiff_t)(2 GB - 1));\n                ip = forwardIp;\n                forwardIp += step;\n                step = (searchMatchNb++ >> LZ4_skipTrigger);\n\n                if (unlikely(forwardIp > mflimitPlusOne)) goto _last_literals;\n                assert(ip < mflimitPlusOne);\n\n                if (dictDirective == usingDictCtx) {\n                    if (matchIndex < startIndex) {\n                        /* there was no match, try the dictionary */\n                        assert(tableType == byU32);\n                        matchIndex = LZ4_getIndexOnHash(h, dictCtx->hashTable, byU32);\n                        match = dictBase + matchIndex;\n                        matchIndex += dictDelta;   /* make dictCtx index comparable with current context */\n                        lowLimit = dictionary;\n                    } else {\n                        match = base + matchIndex;\n                        lowLimit = (const BYTE*)source;\n                    }\n                } else if (dictDirective==usingExtDict) {\n                    if (matchIndex < startIndex) {\n                        DEBUGLOG(7, \"extDict candidate: matchIndex=%5u  <  startIndex=%5u\", matchIndex, startIndex);\n                        assert(startIndex - matchIndex >= MINMATCH);\n                        match = dictBase + matchIndex;\n                        lowLimit = dictionary;\n                    } else {\n                        match = base + matchIndex;\n                        lowLimit = (const BYTE*)source;\n                    }\n                } else {   /* single continuous memory segment */\n                    match = base + matchIndex;\n                }\n                forwardH = LZ4_hashPosition(forwardIp, tableType);\n                LZ4_putIndexOnHash(current, h, cctx->hashTable, tableType);\n\n                DEBUGLOG(7, \"candidate at pos=%u  (offset=%u \\n\", matchIndex, current - matchIndex);\n                if ((dictIssue == dictSmall) && (matchIndex < prefixIdxLimit)) { continue; }    /* match outside of valid area */\n                assert(matchIndex < current);\n                if ( ((tableType != byU16) || (LZ4_DISTANCE_MAX < LZ4_DISTANCE_ABSOLUTE_MAX))\n                  && (matchIndex+LZ4_DISTANCE_MAX < current)) {\n                    continue;\n                } /* too far */\n                assert((current - matchIndex) <= LZ4_DISTANCE_MAX);  /* match now expected within distance */\n\n                if (LZ4_read32(match) == LZ4_read32(ip)) {\n                    if (maybe_extMem) offset = current - matchIndex;\n                    break;   /* match found */\n                }\n\n            } while(1);\n        }\n\n        /* Catch up */\n        filledIp = ip;\n        while (((ip>anchor) & (match > lowLimit)) && (unlikely(ip[-1]==match[-1]))) { ip--; match--; }\n\n        /* Encode Literals */\n        {   unsigned const litLength = (unsigned)(ip - anchor);\n            token = op++;\n            if ((outputDirective == limitedOutput) &&  /* Check output buffer overflow */\n                (unlikely(op + litLength + (2 + 1 + LASTLITERALS) + (litLength/255) > olimit)) ) {\n                return 0;   /* cannot compress within `dst` budget. Stored indexes in hash table are nonetheless fine */\n            }\n            if ((outputDirective == fillOutput) &&\n                (unlikely(op + (litLength+240)/255 /* litlen */ + litLength /* literals */ + 2 /* offset */ + 1 /* token */ + MFLIMIT - MINMATCH /* min last literals so last match is <= end - MFLIMIT */ > olimit))) {\n                op--;\n                goto _last_literals;\n            }\n            if (litLength >= RUN_MASK) {\n                int len = (int)(litLength - RUN_MASK);\n                *token = (RUN_MASK<<ML_BITS);\n                for(; len >= 255 ; len-=255) *op++ = 255;\n                *op++ = (BYTE)len;\n            }\n            else *token = (BYTE)(litLength<<ML_BITS);\n\n            /* Copy Literals */\n            LZ4_wildCopy8(op, anchor, op+litLength);\n            op+=litLength;\n            DEBUGLOG(6, \"seq.start:%i, literals=%u, match.start:%i\",\n                        (int)(anchor-(const BYTE*)source), litLength, (int)(ip-(const BYTE*)source));\n        }\n\n_next_match:\n        /* at this stage, the following variables must be correctly set :\n         * - ip : at start of LZ operation\n         * - match : at start of previous pattern occurence; can be within current prefix, or within extDict\n         * - offset : if maybe_ext_memSegment==1 (constant)\n         * - lowLimit : must be == dictionary to mean \"match is within extDict\"; must be == source otherwise\n         * - token and *token : position to write 4-bits for match length; higher 4-bits for literal length supposed already written\n         */\n\n        if ((outputDirective == fillOutput) &&\n            (op + 2 /* offset */ + 1 /* token */ + MFLIMIT - MINMATCH /* min last literals so last match is <= end - MFLIMIT */ > olimit)) {\n            /* the match was too close to the end, rewind and go to last literals */\n            op = token;\n            goto _last_literals;\n        }\n\n        /* Encode Offset */\n        if (maybe_extMem) {   /* static test */\n            DEBUGLOG(6, \"             with offset=%u  (ext if > %i)\", offset, (int)(ip - (const BYTE*)source));\n            assert(offset <= LZ4_DISTANCE_MAX && offset > 0);\n            LZ4_writeLE16(op, (U16)offset); op+=2;\n        } else  {\n            DEBUGLOG(6, \"             with offset=%u  (same segment)\", (U32)(ip - match));\n            assert(ip-match <= LZ4_DISTANCE_MAX);\n            LZ4_writeLE16(op, (U16)(ip - match)); op+=2;\n        }\n\n        /* Encode MatchLength */\n        {   unsigned matchCode;\n\n            if ( (dictDirective==usingExtDict || dictDirective==usingDictCtx)\n              && (lowLimit==dictionary) /* match within extDict */ ) {\n                const BYTE* limit = ip + (dictEnd-match);\n                assert(dictEnd > match);\n                if (limit > matchlimit) limit = matchlimit;\n                matchCode = LZ4_count(ip+MINMATCH, match+MINMATCH, limit);\n                ip += (size_t)matchCode + MINMATCH;\n                if (ip==limit) {\n                    unsigned const more = LZ4_count(limit, (const BYTE*)source, matchlimit);\n                    matchCode += more;\n                    ip += more;\n                }\n                DEBUGLOG(6, \"             with matchLength=%u starting in extDict\", matchCode+MINMATCH);\n            } else {\n                matchCode = LZ4_count(ip+MINMATCH, match+MINMATCH, matchlimit);\n                ip += (size_t)matchCode + MINMATCH;\n                DEBUGLOG(6, \"             with matchLength=%u\", matchCode+MINMATCH);\n            }\n\n            if ((outputDirective) &&    /* Check output buffer overflow */\n                (unlikely(op + (1 + LASTLITERALS) + (matchCode+240)/255 > olimit)) ) {\n                if (outputDirective == fillOutput) {\n                    /* Match description too long : reduce it */\n                    U32 newMatchCode = 15 /* in token */ - 1 /* to avoid needing a zero byte */ + ((U32)(olimit - op) - 1 - LASTLITERALS) * 255;\n                    ip -= matchCode - newMatchCode;\n                    assert(newMatchCode < matchCode);\n                    matchCode = newMatchCode;\n                    if (unlikely(ip <= filledIp)) {\n                        /* We have already filled up to filledIp so if ip ends up less than filledIp\n                         * we have positions in the hash table beyond the current position. This is\n                         * a problem if we reuse the hash table. So we have to remove these positions\n                         * from the hash table.\n                         */\n                        const BYTE* ptr;\n                        DEBUGLOG(5, \"Clearing %u positions\", (U32)(filledIp - ip));\n                        for (ptr = ip; ptr <= filledIp; ++ptr) {\n                            U32 const h = LZ4_hashPosition(ptr, tableType);\n                            LZ4_clearHash(h, cctx->hashTable, tableType);\n                        }\n                    }\n                } else {\n                    assert(outputDirective == limitedOutput);\n                    return 0;   /* cannot compress within `dst` budget. Stored indexes in hash table are nonetheless fine */\n                }\n            }\n            if (matchCode >= ML_MASK) {\n                *token += ML_MASK;\n                matchCode -= ML_MASK;\n                LZ4_write32(op, 0xFFFFFFFF);\n                while (matchCode >= 4*255) {\n                    op+=4;\n                    LZ4_write32(op, 0xFFFFFFFF);\n                    matchCode -= 4*255;\n                }\n                op += matchCode / 255;\n                *op++ = (BYTE)(matchCode % 255);\n            } else\n                *token += (BYTE)(matchCode);\n        }\n        /* Ensure we have enough space for the last literals. */\n        assert(!(outputDirective == fillOutput && op + 1 + LASTLITERALS > olimit));\n\n        anchor = ip;\n\n        /* Test end of chunk */\n        if (ip >= mflimitPlusOne) break;\n\n        /* Fill table */\n        LZ4_putPosition(ip-2, cctx->hashTable, tableType, base);\n\n        /* Test next position */\n        if (tableType == byPtr) {\n\n            match = LZ4_getPosition(ip, cctx->hashTable, tableType, base);\n            LZ4_putPosition(ip, cctx->hashTable, tableType, base);\n            if ( (match+LZ4_DISTANCE_MAX >= ip)\n              && (LZ4_read32(match) == LZ4_read32(ip)) )\n            { token=op++; *token=0; goto _next_match; }\n\n        } else {   /* byU32, byU16 */\n\n            U32 const h = LZ4_hashPosition(ip, tableType);\n            U32 const current = (U32)(ip-base);\n            U32 matchIndex = LZ4_getIndexOnHash(h, cctx->hashTable, tableType);\n            assert(matchIndex < current);\n            if (dictDirective == usingDictCtx) {\n                if (matchIndex < startIndex) {\n                    /* there was no match, try the dictionary */\n                    matchIndex = LZ4_getIndexOnHash(h, dictCtx->hashTable, byU32);\n                    match = dictBase + matchIndex;\n                    lowLimit = dictionary;   /* required for match length counter */\n                    matchIndex += dictDelta;\n                } else {\n                    match = base + matchIndex;\n                    lowLimit = (const BYTE*)source;  /* required for match length counter */\n                }\n            } else if (dictDirective==usingExtDict) {\n                if (matchIndex < startIndex) {\n                    match = dictBase + matchIndex;\n                    lowLimit = dictionary;   /* required for match length counter */\n                } else {\n                    match = base + matchIndex;\n                    lowLimit = (const BYTE*)source;   /* required for match length counter */\n                }\n            } else {   /* single memory segment */\n                match = base + matchIndex;\n            }\n            LZ4_putIndexOnHash(current, h, cctx->hashTable, tableType);\n            assert(matchIndex < current);\n            if ( ((dictIssue==dictSmall) ? (matchIndex >= prefixIdxLimit) : 1)\n              && (((tableType==byU16) && (LZ4_DISTANCE_MAX == LZ4_DISTANCE_ABSOLUTE_MAX)) ? 1 : (matchIndex+LZ4_DISTANCE_MAX >= current))\n              && (LZ4_read32(match) == LZ4_read32(ip)) ) {\n                token=op++;\n                *token=0;\n                if (maybe_extMem) offset = current - matchIndex;\n                DEBUGLOG(6, \"seq.start:%i, literals=%u, match.start:%i\",\n                            (int)(anchor-(const BYTE*)source), 0, (int)(ip-(const BYTE*)source));\n                goto _next_match;\n            }\n        }\n\n        /* Prepare next loop */\n        forwardH = LZ4_hashPosition(++ip, tableType);\n\n    }\n\n_last_literals:\n    /* Encode Last Literals */\n    {   size_t lastRun = (size_t)(iend - anchor);\n        if ( (outputDirective) &&  /* Check output buffer overflow */\n            (op + lastRun + 1 + ((lastRun+255-RUN_MASK)/255) > olimit)) {\n            if (outputDirective == fillOutput) {\n                /* adapt lastRun to fill 'dst' */\n                assert(olimit >= op);\n                lastRun  = (size_t)(olimit-op) - 1/*token*/;\n                lastRun -= (lastRun + 256 - RUN_MASK) / 256;  /*additional length tokens*/\n            } else {\n                assert(outputDirective == limitedOutput);\n                return 0;   /* cannot compress within `dst` budget. Stored indexes in hash table are nonetheless fine */\n            }\n        }\n        DEBUGLOG(6, \"Final literal run : %i literals\", (int)lastRun);\n        if (lastRun >= RUN_MASK) {\n            size_t accumulator = lastRun - RUN_MASK;\n            *op++ = RUN_MASK << ML_BITS;\n            for(; accumulator >= 255 ; accumulator-=255) *op++ = 255;\n            *op++ = (BYTE) accumulator;\n        } else {\n            *op++ = (BYTE)(lastRun<<ML_BITS);\n        }\n        LZ4_memcpy(op, anchor, lastRun);\n        ip = anchor + lastRun;\n        op += lastRun;\n    }\n\n    if (outputDirective == fillOutput) {\n        *inputConsumed = (int) (((const char*)ip)-source);\n    }\n    result = (int)(((char*)op) - dest);\n    assert(result > 0);\n    DEBUGLOG(5, \"LZ4_compress_generic: compressed %i bytes into %i bytes\", inputSize, result);\n    return result;\n}\n\n/** LZ4_compress_generic() :\n *  inlined, to ensure branches are decided at compilation time;\n *  takes care of src == (NULL, 0)\n *  and forward the rest to LZ4_compress_generic_validated */\nLZ4_FORCE_INLINE int LZ4_compress_generic(\n                 LZ4_stream_t_internal* const cctx,\n                 const char* const src,\n                 char* const dst,\n                 const int srcSize,\n                 int *inputConsumed, /* only written when outputDirective == fillOutput */\n                 const int dstCapacity,\n                 const limitedOutput_directive outputDirective,\n                 const tableType_t tableType,\n                 const dict_directive dictDirective,\n                 const dictIssue_directive dictIssue,\n                 const int acceleration)\n{\n    DEBUGLOG(5, \"LZ4_compress_generic: srcSize=%i, dstCapacity=%i\",\n                srcSize, dstCapacity);\n\n    if ((U32)srcSize > (U32)LZ4_MAX_INPUT_SIZE) { return 0; }  /* Unsupported srcSize, too large (or negative) */\n    if (srcSize == 0) {   /* src == NULL supported if srcSize == 0 */\n        if (outputDirective != notLimited && dstCapacity <= 0) return 0;  /* no output, can't write anything */\n        DEBUGLOG(5, \"Generating an empty block\");\n        assert(outputDirective == notLimited || dstCapacity >= 1);\n        assert(dst != NULL);\n        dst[0] = 0;\n        if (outputDirective == fillOutput) {\n            assert (inputConsumed != NULL);\n            *inputConsumed = 0;\n        }\n        return 1;\n    }\n    assert(src != NULL);\n\n    return LZ4_compress_generic_validated(cctx, src, dst, srcSize,\n                inputConsumed, /* only written into if outputDirective == fillOutput */\n                dstCapacity, outputDirective,\n                tableType, dictDirective, dictIssue, acceleration);\n}\n\n\nint LZ4_compress_fast_extState(void* state, const char* source, char* dest, int inputSize, int maxOutputSize, int acceleration)\n{\n    LZ4_stream_t_internal* const ctx = & LZ4_initStream(state, sizeof(LZ4_stream_t)) -> internal_donotuse;\n    assert(ctx != NULL);\n    if (acceleration < 1) acceleration = LZ4_ACCELERATION_DEFAULT;\n    if (acceleration > LZ4_ACCELERATION_MAX) acceleration = LZ4_ACCELERATION_MAX;\n    if (maxOutputSize >= LZ4_compressBound(inputSize)) {\n        if (inputSize < LZ4_64Klimit) {\n            return LZ4_compress_generic(ctx, source, dest, inputSize, NULL, 0, notLimited, byU16, noDict, noDictIssue, acceleration);\n        } else {\n            const tableType_t tableType = ((sizeof(void*)==4) && ((uptrval)source > LZ4_DISTANCE_MAX)) ? byPtr : byU32;\n            return LZ4_compress_generic(ctx, source, dest, inputSize, NULL, 0, notLimited, tableType, noDict, noDictIssue, acceleration);\n        }\n    } else {\n        if (inputSize < LZ4_64Klimit) {\n            return LZ4_compress_generic(ctx, source, dest, inputSize, NULL, maxOutputSize, limitedOutput, byU16, noDict, noDictIssue, acceleration);\n        } else {\n            const tableType_t tableType = ((sizeof(void*)==4) && ((uptrval)source > LZ4_DISTANCE_MAX)) ? byPtr : byU32;\n            return LZ4_compress_generic(ctx, source, dest, inputSize, NULL, maxOutputSize, limitedOutput, tableType, noDict, noDictIssue, acceleration);\n        }\n    }\n}\n\n/**\n * LZ4_compress_fast_extState_fastReset() :\n * A variant of LZ4_compress_fast_extState().\n *\n * Using this variant avoids an expensive initialization step. It is only safe\n * to call if the state buffer is known to be correctly initialized already\n * (see comment in lz4.h on LZ4_resetStream_fast() for a definition of\n * \"correctly initialized\").\n */\nint LZ4_compress_fast_extState_fastReset(void* state, const char* src, char* dst, int srcSize, int dstCapacity, int acceleration)\n{\n    LZ4_stream_t_internal* ctx = &((LZ4_stream_t*)state)->internal_donotuse;\n    if (acceleration < 1) acceleration = LZ4_ACCELERATION_DEFAULT;\n    if (acceleration > LZ4_ACCELERATION_MAX) acceleration = LZ4_ACCELERATION_MAX;\n\n    if (dstCapacity >= LZ4_compressBound(srcSize)) {\n        if (srcSize < LZ4_64Klimit) {\n            const tableType_t tableType = byU16;\n            LZ4_prepareTable(ctx, srcSize, tableType);\n            if (ctx->currentOffset) {\n                return LZ4_compress_generic(ctx, src, dst, srcSize, NULL, 0, notLimited, tableType, noDict, dictSmall, acceleration);\n            } else {\n                return LZ4_compress_generic(ctx, src, dst, srcSize, NULL, 0, notLimited, tableType, noDict, noDictIssue, acceleration);\n            }\n        } else {\n            const tableType_t tableType = ((sizeof(void*)==4) && ((uptrval)src > LZ4_DISTANCE_MAX)) ? byPtr : byU32;\n            LZ4_prepareTable(ctx, srcSize, tableType);\n            return LZ4_compress_generic(ctx, src, dst, srcSize, NULL, 0, notLimited, tableType, noDict, noDictIssue, acceleration);\n        }\n    } else {\n        if (srcSize < LZ4_64Klimit) {\n            const tableType_t tableType = byU16;\n            LZ4_prepareTable(ctx, srcSize, tableType);\n            if (ctx->currentOffset) {\n                return LZ4_compress_generic(ctx, src, dst, srcSize, NULL, dstCapacity, limitedOutput, tableType, noDict, dictSmall, acceleration);\n            } else {\n                return LZ4_compress_generic(ctx, src, dst, srcSize, NULL, dstCapacity, limitedOutput, tableType, noDict, noDictIssue, acceleration);\n            }\n        } else {\n            const tableType_t tableType = ((sizeof(void*)==4) && ((uptrval)src > LZ4_DISTANCE_MAX)) ? byPtr : byU32;\n            LZ4_prepareTable(ctx, srcSize, tableType);\n            return LZ4_compress_generic(ctx, src, dst, srcSize, NULL, dstCapacity, limitedOutput, tableType, noDict, noDictIssue, acceleration);\n        }\n    }\n}\n\n\nint LZ4_compress_fast(const char* source, char* dest, int inputSize, int maxOutputSize, int acceleration)\n{\n    int result;\n#if (LZ4_HEAPMODE)\n    LZ4_stream_t* ctxPtr = ALLOC(sizeof(LZ4_stream_t));   /* malloc-calloc always properly aligned */\n    if (ctxPtr == NULL) return 0;\n#else\n    LZ4_stream_t ctx;\n    LZ4_stream_t* const ctxPtr = &ctx;\n#endif\n    result = LZ4_compress_fast_extState(ctxPtr, source, dest, inputSize, maxOutputSize, acceleration);\n\n#if (LZ4_HEAPMODE)\n    FREEMEM(ctxPtr);\n#endif\n    return result;\n}\n\n\nint LZ4_compress_default(const char* src, char* dst, int srcSize, int maxOutputSize)\n{\n    return LZ4_compress_fast(src, dst, srcSize, maxOutputSize, 1);\n}\n\n\n/* Note!: This function leaves the stream in an unclean/broken state!\n * It is not safe to subsequently use the same state with a _fastReset() or\n * _continue() call without resetting it. */\nstatic int LZ4_compress_destSize_extState (LZ4_stream_t* state, const char* src, char* dst, int* srcSizePtr, int targetDstSize)\n{\n    void* const s = LZ4_initStream(state, sizeof (*state));\n    assert(s != NULL); (void)s;\n\n    if (targetDstSize >= LZ4_compressBound(*srcSizePtr)) {  /* compression success is guaranteed */\n        return LZ4_compress_fast_extState(state, src, dst, *srcSizePtr, targetDstSize, 1);\n    } else {\n        if (*srcSizePtr < LZ4_64Klimit) {\n            return LZ4_compress_generic(&state->internal_donotuse, src, dst, *srcSizePtr, srcSizePtr, targetDstSize, fillOutput, byU16, noDict, noDictIssue, 1);\n        } else {\n            tableType_t const addrMode = ((sizeof(void*)==4) && ((uptrval)src > LZ4_DISTANCE_MAX)) ? byPtr : byU32;\n            return LZ4_compress_generic(&state->internal_donotuse, src, dst, *srcSizePtr, srcSizePtr, targetDstSize, fillOutput, addrMode, noDict, noDictIssue, 1);\n    }   }\n}\n\n\nint LZ4_compress_destSize(const char* src, char* dst, int* srcSizePtr, int targetDstSize)\n{\n#if (LZ4_HEAPMODE)\n    LZ4_stream_t* ctx = (LZ4_stream_t*)ALLOC(sizeof(LZ4_stream_t));   /* malloc-calloc always properly aligned */\n    if (ctx == NULL) return 0;\n#else\n    LZ4_stream_t ctxBody;\n    LZ4_stream_t* ctx = &ctxBody;\n#endif\n\n    int result = LZ4_compress_destSize_extState(ctx, src, dst, srcSizePtr, targetDstSize);\n\n#if (LZ4_HEAPMODE)\n    FREEMEM(ctx);\n#endif\n    return result;\n}\n\n\n\n/*-******************************\n*  Streaming functions\n********************************/\n\nLZ4_stream_t* LZ4_createStream(void)\n{\n    LZ4_stream_t* const lz4s = (LZ4_stream_t*)ALLOC(sizeof(LZ4_stream_t));\n    LZ4_STATIC_ASSERT(LZ4_STREAMSIZE >= sizeof(LZ4_stream_t_internal));    /* A compilation error here means LZ4_STREAMSIZE is not large enough */\n    DEBUGLOG(4, \"LZ4_createStream %p\", lz4s);\n    if (lz4s == NULL) return NULL;\n    LZ4_initStream(lz4s, sizeof(*lz4s));\n    return lz4s;\n}\n\nstatic size_t LZ4_stream_t_alignment(void)\n{\n#if LZ4_ALIGN_TEST\n    typedef struct { char c; LZ4_stream_t t; } t_a;\n    return sizeof(t_a) - sizeof(LZ4_stream_t);\n#else\n    return 1;  /* effectively disabled */\n#endif\n}\n\nLZ4_stream_t* LZ4_initStream (void* buffer, size_t size)\n{\n    DEBUGLOG(5, \"LZ4_initStream\");\n    if (buffer == NULL) { return NULL; }\n    if (size < sizeof(LZ4_stream_t)) { return NULL; }\n    if (!LZ4_isAligned(buffer, LZ4_stream_t_alignment())) return NULL;\n    MEM_INIT(buffer, 0, sizeof(LZ4_stream_t_internal));\n    return (LZ4_stream_t*)buffer;\n}\n\n/* resetStream is now deprecated,\n * prefer initStream() which is more general */\nvoid LZ4_resetStream (LZ4_stream_t* LZ4_stream)\n{\n    DEBUGLOG(5, \"LZ4_resetStream (ctx:%p)\", LZ4_stream);\n    MEM_INIT(LZ4_stream, 0, sizeof(LZ4_stream_t_internal));\n}\n\nvoid LZ4_resetStream_fast(LZ4_stream_t* ctx) {\n    LZ4_prepareTable(&(ctx->internal_donotuse), 0, byU32);\n}\n\nint LZ4_freeStream (LZ4_stream_t* LZ4_stream)\n{\n    if (!LZ4_stream) return 0;   /* support free on NULL */\n    DEBUGLOG(5, \"LZ4_freeStream %p\", LZ4_stream);\n    FREEMEM(LZ4_stream);\n    return (0);\n}\n\n\n#define HASH_UNIT sizeof(reg_t)\nint LZ4_loadDict (LZ4_stream_t* LZ4_dict, const char* dictionary, int dictSize)\n{\n    LZ4_stream_t_internal* dict = &LZ4_dict->internal_donotuse;\n    const tableType_t tableType = byU32;\n    const BYTE* p = (const BYTE*)dictionary;\n    const BYTE* const dictEnd = p + dictSize;\n    const BYTE* base;\n\n    DEBUGLOG(4, \"LZ4_loadDict (%i bytes from %p into %p)\", dictSize, dictionary, LZ4_dict);\n\n    /* It's necessary to reset the context,\n     * and not just continue it with prepareTable()\n     * to avoid any risk of generating overflowing matchIndex\n     * when compressing using this dictionary */\n    LZ4_resetStream(LZ4_dict);\n\n    /* We always increment the offset by 64 KB, since, if the dict is longer,\n     * we truncate it to the last 64k, and if it's shorter, we still want to\n     * advance by a whole window length so we can provide the guarantee that\n     * there are only valid offsets in the window, which allows an optimization\n     * in LZ4_compress_fast_continue() where it uses noDictIssue even when the\n     * dictionary isn't a full 64k. */\n    dict->currentOffset += 64 KB;\n\n    if (dictSize < (int)HASH_UNIT) {\n        return 0;\n    }\n\n    if ((dictEnd - p) > 64 KB) p = dictEnd - 64 KB;\n    base = dictEnd - dict->currentOffset;\n    dict->dictionary = p;\n    dict->dictSize = (U32)(dictEnd - p);\n    dict->tableType = (U32)tableType;\n\n    while (p <= dictEnd-HASH_UNIT) {\n        LZ4_putPosition(p, dict->hashTable, tableType, base);\n        p+=3;\n    }\n\n    return (int)dict->dictSize;\n}\n\nvoid LZ4_attach_dictionary(LZ4_stream_t* workingStream, const LZ4_stream_t* dictionaryStream) {\n    const LZ4_stream_t_internal* dictCtx = dictionaryStream == NULL ? NULL :\n        &(dictionaryStream->internal_donotuse);\n\n    DEBUGLOG(4, \"LZ4_attach_dictionary (%p, %p, size %u)\",\n             workingStream, dictionaryStream,\n             dictCtx != NULL ? dictCtx->dictSize : 0);\n\n    if (dictCtx != NULL) {\n        /* If the current offset is zero, we will never look in the\n         * external dictionary context, since there is no value a table\n         * entry can take that indicate a miss. In that case, we need\n         * to bump the offset to something non-zero.\n         */\n        if (workingStream->internal_donotuse.currentOffset == 0) {\n            workingStream->internal_donotuse.currentOffset = 64 KB;\n        }\n\n        /* Don't actually attach an empty dictionary.\n         */\n        if (dictCtx->dictSize == 0) {\n            dictCtx = NULL;\n        }\n    }\n    workingStream->internal_donotuse.dictCtx = dictCtx;\n}\n\n\nstatic void LZ4_renormDictT(LZ4_stream_t_internal* LZ4_dict, int nextSize)\n{\n    assert(nextSize >= 0);\n    if (LZ4_dict->currentOffset + (unsigned)nextSize > 0x80000000) {   /* potential ptrdiff_t overflow (32-bits mode) */\n        /* rescale hash table */\n        U32 const delta = LZ4_dict->currentOffset - 64 KB;\n        const BYTE* dictEnd = LZ4_dict->dictionary + LZ4_dict->dictSize;\n        int i;\n        DEBUGLOG(4, \"LZ4_renormDictT\");\n        for (i=0; i<LZ4_HASH_SIZE_U32; i++) {\n            if (LZ4_dict->hashTable[i] < delta) LZ4_dict->hashTable[i]=0;\n            else LZ4_dict->hashTable[i] -= delta;\n        }\n        LZ4_dict->currentOffset = 64 KB;\n        if (LZ4_dict->dictSize > 64 KB) LZ4_dict->dictSize = 64 KB;\n        LZ4_dict->dictionary = dictEnd - LZ4_dict->dictSize;\n    }\n}\n\n\nint LZ4_compress_fast_continue (LZ4_stream_t* LZ4_stream,\n                                const char* source, char* dest,\n                                int inputSize, int maxOutputSize,\n                                int acceleration)\n{\n    const tableType_t tableType = byU32;\n    LZ4_stream_t_internal* streamPtr = &LZ4_stream->internal_donotuse;\n    const BYTE* dictEnd = streamPtr->dictionary + streamPtr->dictSize;\n\n    DEBUGLOG(5, \"LZ4_compress_fast_continue (inputSize=%i)\", inputSize);\n\n    LZ4_renormDictT(streamPtr, inputSize);   /* avoid index overflow */\n    if (acceleration < 1) acceleration = LZ4_ACCELERATION_DEFAULT;\n    if (acceleration > LZ4_ACCELERATION_MAX) acceleration = LZ4_ACCELERATION_MAX;\n\n    /* invalidate tiny dictionaries */\n    if ( (streamPtr->dictSize-1 < 4-1)   /* intentional underflow */\n      && (dictEnd != (const BYTE*)source) ) {\n        DEBUGLOG(5, \"LZ4_compress_fast_continue: dictSize(%u) at addr:%p is too small\", streamPtr->dictSize, streamPtr->dictionary);\n        streamPtr->dictSize = 0;\n        streamPtr->dictionary = (const BYTE*)source;\n        dictEnd = (const BYTE*)source;\n    }\n\n    /* Check overlapping input/dictionary space */\n    {   const BYTE* sourceEnd = (const BYTE*) source + inputSize;\n        if ((sourceEnd > streamPtr->dictionary) && (sourceEnd < dictEnd)) {\n            streamPtr->dictSize = (U32)(dictEnd - sourceEnd);\n            if (streamPtr->dictSize > 64 KB) streamPtr->dictSize = 64 KB;\n            if (streamPtr->dictSize < 4) streamPtr->dictSize = 0;\n            streamPtr->dictionary = dictEnd - streamPtr->dictSize;\n        }\n    }\n\n    /* prefix mode : source data follows dictionary */\n    if (dictEnd == (const BYTE*)source) {\n        if ((streamPtr->dictSize < 64 KB) && (streamPtr->dictSize < streamPtr->currentOffset))\n            return LZ4_compress_generic(streamPtr, source, dest, inputSize, NULL, maxOutputSize, limitedOutput, tableType, withPrefix64k, dictSmall, acceleration);\n        else\n            return LZ4_compress_generic(streamPtr, source, dest, inputSize, NULL, maxOutputSize, limitedOutput, tableType, withPrefix64k, noDictIssue, acceleration);\n    }\n\n    /* external dictionary mode */\n    {   int result;\n        if (streamPtr->dictCtx) {\n            /* We depend here on the fact that dictCtx'es (produced by\n             * LZ4_loadDict) guarantee that their tables contain no references\n             * to offsets between dictCtx->currentOffset - 64 KB and\n             * dictCtx->currentOffset - dictCtx->dictSize. This makes it safe\n             * to use noDictIssue even when the dict isn't a full 64 KB.\n             */\n            if (inputSize > 4 KB) {\n                /* For compressing large blobs, it is faster to pay the setup\n                 * cost to copy the dictionary's tables into the active context,\n                 * so that the compression loop is only looking into one table.\n                 */\n                LZ4_memcpy(streamPtr, streamPtr->dictCtx, sizeof(*streamPtr));\n                result = LZ4_compress_generic(streamPtr, source, dest, inputSize, NULL, maxOutputSize, limitedOutput, tableType, usingExtDict, noDictIssue, acceleration);\n            } else {\n                result = LZ4_compress_generic(streamPtr, source, dest, inputSize, NULL, maxOutputSize, limitedOutput, tableType, usingDictCtx, noDictIssue, acceleration);\n            }\n        } else {\n            if ((streamPtr->dictSize < 64 KB) && (streamPtr->dictSize < streamPtr->currentOffset)) {\n                result = LZ4_compress_generic(streamPtr, source, dest, inputSize, NULL, maxOutputSize, limitedOutput, tableType, usingExtDict, dictSmall, acceleration);\n            } else {\n                result = LZ4_compress_generic(streamPtr, source, dest, inputSize, NULL, maxOutputSize, limitedOutput, tableType, usingExtDict, noDictIssue, acceleration);\n            }\n        }\n        streamPtr->dictionary = (const BYTE*)source;\n        streamPtr->dictSize = (U32)inputSize;\n        return result;\n    }\n}\n\n\n/* Hidden debug function, to force-test external dictionary mode */\nint LZ4_compress_forceExtDict (LZ4_stream_t* LZ4_dict, const char* source, char* dest, int srcSize)\n{\n    LZ4_stream_t_internal* streamPtr = &LZ4_dict->internal_donotuse;\n    int result;\n\n    LZ4_renormDictT(streamPtr, srcSize);\n\n    if ((streamPtr->dictSize < 64 KB) && (streamPtr->dictSize < streamPtr->currentOffset)) {\n        result = LZ4_compress_generic(streamPtr, source, dest, srcSize, NULL, 0, notLimited, byU32, usingExtDict, dictSmall, 1);\n    } else {\n        result = LZ4_compress_generic(streamPtr, source, dest, srcSize, NULL, 0, notLimited, byU32, usingExtDict, noDictIssue, 1);\n    }\n\n    streamPtr->dictionary = (const BYTE*)source;\n    streamPtr->dictSize = (U32)srcSize;\n\n    return result;\n}\n\n\n/*! LZ4_saveDict() :\n *  If previously compressed data block is not guaranteed to remain available at its memory location,\n *  save it into a safer place (char* safeBuffer).\n *  Note : you don't need to call LZ4_loadDict() afterwards,\n *         dictionary is immediately usable, you can therefore call LZ4_compress_fast_continue().\n *  Return : saved dictionary size in bytes (necessarily <= dictSize), or 0 if error.\n */\nint LZ4_saveDict (LZ4_stream_t* LZ4_dict, char* safeBuffer, int dictSize)\n{\n    LZ4_stream_t_internal* const dict = &LZ4_dict->internal_donotuse;\n    const BYTE* const previousDictEnd = dict->dictionary + dict->dictSize;\n\n    if ((U32)dictSize > 64 KB) { dictSize = 64 KB; } /* useless to define a dictionary > 64 KB */\n    if ((U32)dictSize > dict->dictSize) { dictSize = (int)dict->dictSize; }\n\n    if (safeBuffer == NULL) assert(dictSize == 0);\n    if (dictSize > 0)\n        memmove(safeBuffer, previousDictEnd - dictSize, dictSize);\n\n    dict->dictionary = (const BYTE*)safeBuffer;\n    dict->dictSize = (U32)dictSize;\n\n    return dictSize;\n}\n\n\n\n/*-*******************************\n *  Decompression functions\n ********************************/\n\ntypedef enum { endOnOutputSize = 0, endOnInputSize = 1 } endCondition_directive;\ntypedef enum { decode_full_block = 0, partial_decode = 1 } earlyEnd_directive;\n\n#undef MIN\n#define MIN(a,b)    ( (a) < (b) ? (a) : (b) )\n\n/* Read the variable-length literal or match length.\n *\n * ip - pointer to use as input.\n * lencheck - end ip.  Return an error if ip advances >= lencheck.\n * loop_check - check ip >= lencheck in body of loop.  Returns loop_error if so.\n * initial_check - check ip >= lencheck before start of loop.  Returns initial_error if so.\n * error (output) - error code.  Should be set to 0 before call.\n */\ntypedef enum { loop_error = -2, initial_error = -1, ok = 0 } variable_length_error;\nLZ4_FORCE_INLINE unsigned\nread_variable_length(const BYTE**ip, const BYTE* lencheck,\n                     int loop_check, int initial_check,\n                     variable_length_error* error)\n{\n    U32 length = 0;\n    U32 s;\n    if (initial_check && unlikely((*ip) >= lencheck)) {    /* overflow detection */\n        *error = initial_error;\n        return length;\n    }\n    do {\n        s = **ip;\n        (*ip)++;\n        length += s;\n        if (loop_check && unlikely((*ip) >= lencheck)) {    /* overflow detection */\n            *error = loop_error;\n            return length;\n        }\n    } while (s==255);\n\n    return length;\n}\n\n/*! LZ4_decompress_generic() :\n *  This generic decompression function covers all use cases.\n *  It shall be instantiated several times, using different sets of directives.\n *  Note that it is important for performance that this function really get inlined,\n *  in order to remove useless branches during compilation optimization.\n */\nLZ4_FORCE_INLINE int\nLZ4_decompress_generic(\n                 const char* const src,\n                 char* const dst,\n                 int srcSize,\n                 int outputSize,         /* If endOnInput==endOnInputSize, this value is `dstCapacity` */\n\n                 endCondition_directive endOnInput,   /* endOnOutputSize, endOnInputSize */\n                 earlyEnd_directive partialDecoding,  /* full, partial */\n                 dict_directive dict,                 /* noDict, withPrefix64k, usingExtDict */\n                 const BYTE* const lowPrefix,  /* always <= dst, == dst when no prefix */\n                 const BYTE* const dictStart,  /* only if dict==usingExtDict */\n                 const size_t dictSize         /* note : = 0 if noDict */\n                 )\n{\n    if (src == NULL) { return -1; }\n\n    {   const BYTE* ip = (const BYTE*) src;\n        const BYTE* const iend = ip + srcSize;\n\n        BYTE* op = (BYTE*) dst;\n        BYTE* const oend = op + outputSize;\n        BYTE* cpy;\n\n        const BYTE* const dictEnd = (dictStart == NULL) ? NULL : dictStart + dictSize;\n\n        const int safeDecode = (endOnInput==endOnInputSize);\n        const int checkOffset = ((safeDecode) && (dictSize < (int)(64 KB)));\n\n\n        /* Set up the \"end\" pointers for the shortcut. */\n        const BYTE* const shortiend = iend - (endOnInput ? 14 : 8) /*maxLL*/ - 2 /*offset*/;\n        const BYTE* const shortoend = oend - (endOnInput ? 14 : 8) /*maxLL*/ - 18 /*maxML*/;\n\n        const BYTE* match;\n        size_t offset;\n        unsigned token;\n        size_t length;\n\n\n        DEBUGLOG(5, \"LZ4_decompress_generic (srcSize:%i, dstSize:%i)\", srcSize, outputSize);\n\n        /* Special cases */\n        assert(lowPrefix <= op);\n        if ((endOnInput) && (unlikely(outputSize==0))) {\n            /* Empty output buffer */\n            if (partialDecoding) return 0;\n            return ((srcSize==1) && (*ip==0)) ? 0 : -1;\n        }\n        if ((!endOnInput) && (unlikely(outputSize==0))) { return (*ip==0 ? 1 : -1); }\n        if ((endOnInput) && unlikely(srcSize==0)) { return -1; }\n\n\t/* Currently the fast loop shows a regression on qualcomm arm chips. */\n#if LZ4_FAST_DEC_LOOP\n        if ((oend - op) < FASTLOOP_SAFE_DISTANCE) {\n            DEBUGLOG(6, \"skip fast decode loop\");\n            goto safe_decode;\n        }\n\n        /* Fast loop : decode sequences as long as output < iend-FASTLOOP_SAFE_DISTANCE */\n        while (1) {\n            /* Main fastloop assertion: We can always wildcopy FASTLOOP_SAFE_DISTANCE */\n            assert(oend - op >= FASTLOOP_SAFE_DISTANCE);\n            if (endOnInput) { assert(ip < iend); }\n            token = *ip++;\n            length = token >> ML_BITS;  /* literal length */\n\n            assert(!endOnInput || ip <= iend); /* ip < iend before the increment */\n\n            /* decode literal length */\n            if (length == RUN_MASK) {\n                variable_length_error error = ok;\n                length += read_variable_length(&ip, iend-RUN_MASK, (int)endOnInput, (int)endOnInput, &error);\n                if (error == initial_error) { goto _output_error; }\n                if ((safeDecode) && unlikely((uptrval)(op)+length<(uptrval)(op))) { goto _output_error; } /* overflow detection */\n                if ((safeDecode) && unlikely((uptrval)(ip)+length<(uptrval)(ip))) { goto _output_error; } /* overflow detection */\n\n                /* copy literals */\n                cpy = op+length;\n                LZ4_STATIC_ASSERT(MFLIMIT >= WILDCOPYLENGTH);\n                if (endOnInput) {  /* LZ4_decompress_safe() */\n                    if ((cpy>oend-32) || (ip+length>iend-32)) { goto safe_literal_copy; }\n                    LZ4_wildCopy32(op, ip, cpy);\n                } else {   /* LZ4_decompress_fast() */\n                    if (cpy>oend-8) { goto safe_literal_copy; }\n                    LZ4_wildCopy8(op, ip, cpy); /* LZ4_decompress_fast() cannot copy more than 8 bytes at a time :\n                                                 * it doesn't know input length, and only relies on end-of-block properties */\n                }\n                ip += length; op = cpy;\n            } else {\n                cpy = op+length;\n                if (endOnInput) {  /* LZ4_decompress_safe() */\n                    DEBUGLOG(7, \"copy %u bytes in a 16-bytes stripe\", (unsigned)length);\n                    /* We don't need to check oend, since we check it once for each loop below */\n                    if (ip > iend-(16 + 1/*max lit + offset + nextToken*/)) { goto safe_literal_copy; }\n                    /* Literals can only be 14, but hope compilers optimize if we copy by a register size */\n                    LZ4_memcpy(op, ip, 16);\n                } else {  /* LZ4_decompress_fast() */\n                    /* LZ4_decompress_fast() cannot copy more than 8 bytes at a time :\n                     * it doesn't know input length, and relies on end-of-block properties */\n                    LZ4_memcpy(op, ip, 8);\n                    if (length > 8) { LZ4_memcpy(op+8, ip+8, 8); }\n                }\n                ip += length; op = cpy;\n            }\n\n            /* get offset */\n            offset = LZ4_readLE16(ip); ip+=2;\n            match = op - offset;\n            assert(match <= op);\n\n            /* get matchlength */\n            length = token & ML_MASK;\n\n            if (length == ML_MASK) {\n                variable_length_error error = ok;\n                if ((checkOffset) && (unlikely(match + dictSize < lowPrefix))) { goto _output_error; } /* Error : offset outside buffers */\n                length += read_variable_length(&ip, iend - LASTLITERALS + 1, (int)endOnInput, 0, &error);\n                if (error != ok) { goto _output_error; }\n                if ((safeDecode) && unlikely((uptrval)(op)+length<(uptrval)op)) { goto _output_error; } /* overflow detection */\n                length += MINMATCH;\n                if (op + length >= oend - FASTLOOP_SAFE_DISTANCE) {\n                    goto safe_match_copy;\n                }\n            } else {\n                length += MINMATCH;\n                if (op + length >= oend - FASTLOOP_SAFE_DISTANCE) {\n                    goto safe_match_copy;\n                }\n\n                /* Fastpath check: Avoids a branch in LZ4_wildCopy32 if true */\n                if ((dict == withPrefix64k) || (match >= lowPrefix)) {\n                    if (offset >= 8) {\n                        assert(match >= lowPrefix);\n                        assert(match <= op);\n                        assert(op + 18 <= oend);\n\n                        LZ4_memcpy(op, match, 8);\n                        LZ4_memcpy(op+8, match+8, 8);\n                        LZ4_memcpy(op+16, match+16, 2);\n                        op += length;\n                        continue;\n            }   }   }\n\n            if (checkOffset && (unlikely(match + dictSize < lowPrefix))) { goto _output_error; } /* Error : offset outside buffers */\n            /* match starting within external dictionary */\n            if ((dict==usingExtDict) && (match < lowPrefix)) {\n                if (unlikely(op+length > oend-LASTLITERALS)) {\n                    if (partialDecoding) {\n                        DEBUGLOG(7, \"partialDecoding: dictionary match, close to dstEnd\");\n                        length = MIN(length, (size_t)(oend-op));\n                    } else {\n                        goto _output_error;  /* end-of-block condition violated */\n                }   }\n\n                if (length <= (size_t)(lowPrefix-match)) {\n                    /* match fits entirely within external dictionary : just copy */\n                    memmove(op, dictEnd - (lowPrefix-match), length);\n                    op += length;\n                } else {\n                    /* match stretches into both external dictionary and current block */\n                    size_t const copySize = (size_t)(lowPrefix - match);\n                    size_t const restSize = length - copySize;\n                    LZ4_memcpy(op, dictEnd - copySize, copySize);\n                    op += copySize;\n                    if (restSize > (size_t)(op - lowPrefix)) {  /* overlap copy */\n                        BYTE* const endOfMatch = op + restSize;\n                        const BYTE* copyFrom = lowPrefix;\n                        while (op < endOfMatch) { *op++ = *copyFrom++; }\n                    } else {\n                        LZ4_memcpy(op, lowPrefix, restSize);\n                        op += restSize;\n                }   }\n                continue;\n            }\n\n            /* copy match within block */\n            cpy = op + length;\n\n            assert((op <= oend) && (oend-op >= 32));\n            if (unlikely(offset<16)) {\n                LZ4_memcpy_using_offset(op, match, cpy, offset);\n            } else {\n                LZ4_wildCopy32(op, match, cpy);\n            }\n\n            op = cpy;   /* wildcopy correction */\n        }\n    safe_decode:\n#endif\n\n        /* Main Loop : decode remaining sequences where output < FASTLOOP_SAFE_DISTANCE */\n        while (1) {\n            token = *ip++;\n            length = token >> ML_BITS;  /* literal length */\n\n            assert(!endOnInput || ip <= iend); /* ip < iend before the increment */\n\n            /* A two-stage shortcut for the most common case:\n             * 1) If the literal length is 0..14, and there is enough space,\n             * enter the shortcut and copy 16 bytes on behalf of the literals\n             * (in the fast mode, only 8 bytes can be safely copied this way).\n             * 2) Further if the match length is 4..18, copy 18 bytes in a similar\n             * manner; but we ensure that there's enough space in the output for\n             * those 18 bytes earlier, upon entering the shortcut (in other words,\n             * there is a combined check for both stages).\n             */\n            if ( (endOnInput ? length != RUN_MASK : length <= 8)\n                /* strictly \"less than\" on input, to re-enter the loop with at least one byte */\n              && likely((endOnInput ? ip < shortiend : 1) & (op <= shortoend)) ) {\n                /* Copy the literals */\n                LZ4_memcpy(op, ip, endOnInput ? 16 : 8);\n                op += length; ip += length;\n\n                /* The second stage: prepare for match copying, decode full info.\n                 * If it doesn't work out, the info won't be wasted. */\n                length = token & ML_MASK; /* match length */\n                offset = LZ4_readLE16(ip); ip += 2;\n                match = op - offset;\n                assert(match <= op); /* check overflow */\n\n                /* Do not deal with overlapping matches. */\n                if ( (length != ML_MASK)\n                  && (offset >= 8)\n                  && (dict==withPrefix64k || match >= lowPrefix) ) {\n                    /* Copy the match. */\n                    LZ4_memcpy(op + 0, match + 0, 8);\n                    LZ4_memcpy(op + 8, match + 8, 8);\n                    LZ4_memcpy(op +16, match +16, 2);\n                    op += length + MINMATCH;\n                    /* Both stages worked, load the next token. */\n                    continue;\n                }\n\n                /* The second stage didn't work out, but the info is ready.\n                 * Propel it right to the point of match copying. */\n                goto _copy_match;\n            }\n\n            /* decode literal length */\n            if (length == RUN_MASK) {\n                variable_length_error error = ok;\n                length += read_variable_length(&ip, iend-RUN_MASK, (int)endOnInput, (int)endOnInput, &error);\n                if (error == initial_error) { goto _output_error; }\n                if ((safeDecode) && unlikely((uptrval)(op)+length<(uptrval)(op))) { goto _output_error; } /* overflow detection */\n                if ((safeDecode) && unlikely((uptrval)(ip)+length<(uptrval)(ip))) { goto _output_error; } /* overflow detection */\n            }\n\n            /* copy literals */\n            cpy = op+length;\n#if LZ4_FAST_DEC_LOOP\n        safe_literal_copy:\n#endif\n            LZ4_STATIC_ASSERT(MFLIMIT >= WILDCOPYLENGTH);\n            if ( ((endOnInput) && ((cpy>oend-MFLIMIT) || (ip+length>iend-(2+1+LASTLITERALS))) )\n              || ((!endOnInput) && (cpy>oend-WILDCOPYLENGTH)) )\n            {\n                /* We've either hit the input parsing restriction or the output parsing restriction.\n                 * In the normal scenario, decoding a full block, it must be the last sequence,\n                 * otherwise it's an error (invalid input or dimensions).\n                 * In partialDecoding scenario, it's necessary to ensure there is no buffer overflow.\n                 */\n                if (partialDecoding) {\n                    /* Since we are partial decoding we may be in this block because of the output parsing\n                     * restriction, which is not valid since the output buffer is allowed to be undersized.\n                     */\n                    assert(endOnInput);\n                    DEBUGLOG(7, \"partialDecoding: copying literals, close to input or output end\")\n                    DEBUGLOG(7, \"partialDecoding: literal length = %u\", (unsigned)length);\n                    DEBUGLOG(7, \"partialDecoding: remaining space in dstBuffer : %i\", (int)(oend - op));\n                    DEBUGLOG(7, \"partialDecoding: remaining space in srcBuffer : %i\", (int)(iend - ip));\n                    /* Finishing in the middle of a literals segment,\n                     * due to lack of input.\n                     */\n                    if (ip+length > iend) {\n                        length = (size_t)(iend-ip);\n                        cpy = op + length;\n                    }\n                    /* Finishing in the middle of a literals segment,\n                     * due to lack of output space.\n                     */\n                    if (cpy > oend) {\n                        cpy = oend;\n                        assert(op<=oend);\n                        length = (size_t)(oend-op);\n                    }\n                } else {\n                    /* We must be on the last sequence because of the parsing limitations so check\n                     * that we exactly regenerate the original size (must be exact when !endOnInput).\n                     */\n                    if ((!endOnInput) && (cpy != oend)) { goto _output_error; }\n                     /* We must be on the last sequence (or invalid) because of the parsing limitations\n                      * so check that we exactly consume the input and don't overrun the output buffer.\n                      */\n                    if ((endOnInput) && ((ip+length != iend) || (cpy > oend))) {\n                        DEBUGLOG(6, \"should have been last run of literals\")\n                        DEBUGLOG(6, \"ip(%p) + length(%i) = %p != iend (%p)\", ip, (int)length, ip+length, iend);\n                        DEBUGLOG(6, \"or cpy(%p) > oend(%p)\", cpy, oend);\n                        goto _output_error;\n                    }\n                }\n                memmove(op, ip, length);  /* supports overlapping memory regions; only matters for in-place decompression scenarios */\n                ip += length;\n                op += length;\n                /* Necessarily EOF when !partialDecoding.\n                 * When partialDecoding, it is EOF if we've either\n                 * filled the output buffer or\n                 * can't proceed with reading an offset for following match.\n                 */\n                if (!partialDecoding || (cpy == oend) || (ip >= (iend-2))) {\n                    break;\n                }\n            } else {\n                LZ4_wildCopy8(op, ip, cpy);   /* may overwrite up to WILDCOPYLENGTH beyond cpy */\n                ip += length; op = cpy;\n            }\n\n            /* get offset */\n            offset = LZ4_readLE16(ip); ip+=2;\n            match = op - offset;\n\n            /* get matchlength */\n            length = token & ML_MASK;\n\n    _copy_match:\n            if (length == ML_MASK) {\n              variable_length_error error = ok;\n              length += read_variable_length(&ip, iend - LASTLITERALS + 1, (int)endOnInput, 0, &error);\n              if (error != ok) goto _output_error;\n                if ((safeDecode) && unlikely((uptrval)(op)+length<(uptrval)op)) goto _output_error;   /* overflow detection */\n            }\n            length += MINMATCH;\n\n#if LZ4_FAST_DEC_LOOP\n        safe_match_copy:\n#endif\n            if ((checkOffset) && (unlikely(match + dictSize < lowPrefix))) goto _output_error;   /* Error : offset outside buffers */\n            /* match starting within external dictionary */\n            if ((dict==usingExtDict) && (match < lowPrefix)) {\n                if (unlikely(op+length > oend-LASTLITERALS)) {\n                    if (partialDecoding) length = MIN(length, (size_t)(oend-op));\n                    else goto _output_error;   /* doesn't respect parsing restriction */\n                }\n\n                if (length <= (size_t)(lowPrefix-match)) {\n                    /* match fits entirely within external dictionary : just copy */\n                    memmove(op, dictEnd - (lowPrefix-match), length);\n                    op += length;\n                } else {\n                    /* match stretches into both external dictionary and current block */\n                    size_t const copySize = (size_t)(lowPrefix - match);\n                    size_t const restSize = length - copySize;\n                    LZ4_memcpy(op, dictEnd - copySize, copySize);\n                    op += copySize;\n                    if (restSize > (size_t)(op - lowPrefix)) {  /* overlap copy */\n                        BYTE* const endOfMatch = op + restSize;\n                        const BYTE* copyFrom = lowPrefix;\n                        while (op < endOfMatch) *op++ = *copyFrom++;\n                    } else {\n                        LZ4_memcpy(op, lowPrefix, restSize);\n                        op += restSize;\n                }   }\n                continue;\n            }\n            assert(match >= lowPrefix);\n\n            /* copy match within block */\n            cpy = op + length;\n\n            /* partialDecoding : may end anywhere within the block */\n            assert(op<=oend);\n            if (partialDecoding && (cpy > oend-MATCH_SAFEGUARD_DISTANCE)) {\n                size_t const mlen = MIN(length, (size_t)(oend-op));\n                const BYTE* const matchEnd = match + mlen;\n                BYTE* const copyEnd = op + mlen;\n                if (matchEnd > op) {   /* overlap copy */\n                    while (op < copyEnd) { *op++ = *match++; }\n                } else {\n                    LZ4_memcpy(op, match, mlen);\n                }\n                op = copyEnd;\n                if (op == oend) { break; }\n                continue;\n            }\n\n            if (unlikely(offset<8)) {\n                LZ4_write32(op, 0);   /* silence msan warning when offset==0 */\n                op[0] = match[0];\n                op[1] = match[1];\n                op[2] = match[2];\n                op[3] = match[3];\n                match += inc32table[offset];\n                LZ4_memcpy(op+4, match, 4);\n                match -= dec64table[offset];\n            } else {\n                LZ4_memcpy(op, match, 8);\n                match += 8;\n            }\n            op += 8;\n\n            if (unlikely(cpy > oend-MATCH_SAFEGUARD_DISTANCE)) {\n                BYTE* const oCopyLimit = oend - (WILDCOPYLENGTH-1);\n                if (cpy > oend-LASTLITERALS) { goto _output_error; } /* Error : last LASTLITERALS bytes must be literals (uncompressed) */\n                if (op < oCopyLimit) {\n                    LZ4_wildCopy8(op, match, oCopyLimit);\n                    match += oCopyLimit - op;\n                    op = oCopyLimit;\n                }\n                while (op < cpy) { *op++ = *match++; }\n            } else {\n                LZ4_memcpy(op, match, 8);\n                if (length > 16)  { LZ4_wildCopy8(op+8, match+8, cpy); }\n            }\n            op = cpy;   /* wildcopy correction */\n        }\n\n        /* end of decoding */\n        if (endOnInput) {\n            DEBUGLOG(5, \"decoded %i bytes\", (int) (((char*)op)-dst));\n           return (int) (((char*)op)-dst);     /* Nb of output bytes decoded */\n       } else {\n           return (int) (((const char*)ip)-src);   /* Nb of input bytes read */\n       }\n\n        /* Overflow error detected */\n    _output_error:\n        return (int) (-(((const char*)ip)-src))-1;\n    }\n}\n\n\n/*===== Instantiate the API decoding functions. =====*/\n\nLZ4_FORCE_O2\nint LZ4_decompress_safe(const char* source, char* dest, int compressedSize, int maxDecompressedSize)\n{\n    return LZ4_decompress_generic(source, dest, compressedSize, maxDecompressedSize,\n                                  endOnInputSize, decode_full_block, noDict,\n                                  (BYTE*)dest, NULL, 0);\n}\n\nLZ4_FORCE_O2\nint LZ4_decompress_safe_partial(const char* src, char* dst, int compressedSize, int targetOutputSize, int dstCapacity)\n{\n    dstCapacity = MIN(targetOutputSize, dstCapacity);\n    return LZ4_decompress_generic(src, dst, compressedSize, dstCapacity,\n                                  endOnInputSize, partial_decode,\n                                  noDict, (BYTE*)dst, NULL, 0);\n}\n\nLZ4_FORCE_O2\nint LZ4_decompress_fast(const char* source, char* dest, int originalSize)\n{\n    return LZ4_decompress_generic(source, dest, 0, originalSize,\n                                  endOnOutputSize, decode_full_block, withPrefix64k,\n                                  (BYTE*)dest - 64 KB, NULL, 0);\n}\n\n/*===== Instantiate a few more decoding cases, used more than once. =====*/\n\nLZ4_FORCE_O2 /* Exported, an obsolete API function. */\nint LZ4_decompress_safe_withPrefix64k(const char* source, char* dest, int compressedSize, int maxOutputSize)\n{\n    return LZ4_decompress_generic(source, dest, compressedSize, maxOutputSize,\n                                  endOnInputSize, decode_full_block, withPrefix64k,\n                                  (BYTE*)dest - 64 KB, NULL, 0);\n}\n\n/* Another obsolete API function, paired with the previous one. */\nint LZ4_decompress_fast_withPrefix64k(const char* source, char* dest, int originalSize)\n{\n    /* LZ4_decompress_fast doesn't validate match offsets,\n     * and thus serves well with any prefixed dictionary. */\n    return LZ4_decompress_fast(source, dest, originalSize);\n}\n\nLZ4_FORCE_O2\nstatic int LZ4_decompress_safe_withSmallPrefix(const char* source, char* dest, int compressedSize, int maxOutputSize,\n                                               size_t prefixSize)\n{\n    return LZ4_decompress_generic(source, dest, compressedSize, maxOutputSize,\n                                  endOnInputSize, decode_full_block, noDict,\n                                  (BYTE*)dest-prefixSize, NULL, 0);\n}\n\nLZ4_FORCE_O2\nint LZ4_decompress_safe_forceExtDict(const char* source, char* dest,\n                                     int compressedSize, int maxOutputSize,\n                                     const void* dictStart, size_t dictSize)\n{\n    return LZ4_decompress_generic(source, dest, compressedSize, maxOutputSize,\n                                  endOnInputSize, decode_full_block, usingExtDict,\n                                  (BYTE*)dest, (const BYTE*)dictStart, dictSize);\n}\n\nLZ4_FORCE_O2\nstatic int LZ4_decompress_fast_extDict(const char* source, char* dest, int originalSize,\n                                       const void* dictStart, size_t dictSize)\n{\n    return LZ4_decompress_generic(source, dest, 0, originalSize,\n                                  endOnOutputSize, decode_full_block, usingExtDict,\n                                  (BYTE*)dest, (const BYTE*)dictStart, dictSize);\n}\n\n/* The \"double dictionary\" mode, for use with e.g. ring buffers: the first part\n * of the dictionary is passed as prefix, and the second via dictStart + dictSize.\n * These routines are used only once, in LZ4_decompress_*_continue().\n */\nLZ4_FORCE_INLINE\nint LZ4_decompress_safe_doubleDict(const char* source, char* dest, int compressedSize, int maxOutputSize,\n                                   size_t prefixSize, const void* dictStart, size_t dictSize)\n{\n    return LZ4_decompress_generic(source, dest, compressedSize, maxOutputSize,\n                                  endOnInputSize, decode_full_block, usingExtDict,\n                                  (BYTE*)dest-prefixSize, (const BYTE*)dictStart, dictSize);\n}\n\nLZ4_FORCE_INLINE\nint LZ4_decompress_fast_doubleDict(const char* source, char* dest, int originalSize,\n                                   size_t prefixSize, const void* dictStart, size_t dictSize)\n{\n    return LZ4_decompress_generic(source, dest, 0, originalSize,\n                                  endOnOutputSize, decode_full_block, usingExtDict,\n                                  (BYTE*)dest-prefixSize, (const BYTE*)dictStart, dictSize);\n}\n\n/*===== streaming decompression functions =====*/\n\nLZ4_streamDecode_t* LZ4_createStreamDecode(void)\n{\n    LZ4_streamDecode_t* lz4s = (LZ4_streamDecode_t*) ALLOC_AND_ZERO(sizeof(LZ4_streamDecode_t));\n    LZ4_STATIC_ASSERT(LZ4_STREAMDECODESIZE >= sizeof(LZ4_streamDecode_t_internal));    /* A compilation error here means LZ4_STREAMDECODESIZE is not large enough */\n    return lz4s;\n}\n\nint LZ4_freeStreamDecode (LZ4_streamDecode_t* LZ4_stream)\n{\n    if (LZ4_stream == NULL) { return 0; }  /* support free on NULL */\n    FREEMEM(LZ4_stream);\n    return 0;\n}\n\n/*! LZ4_setStreamDecode() :\n *  Use this function to instruct where to find the dictionary.\n *  This function is not necessary if previous data is still available where it was decoded.\n *  Loading a size of 0 is allowed (same effect as no dictionary).\n * @return : 1 if OK, 0 if error\n */\nint LZ4_setStreamDecode (LZ4_streamDecode_t* LZ4_streamDecode, const char* dictionary, int dictSize)\n{\n    LZ4_streamDecode_t_internal* lz4sd = &LZ4_streamDecode->internal_donotuse;\n    lz4sd->prefixSize = (size_t) dictSize;\n    lz4sd->prefixEnd = (const BYTE*) dictionary + dictSize;\n    lz4sd->externalDict = NULL;\n    lz4sd->extDictSize  = 0;\n    return 1;\n}\n\n/*! LZ4_decoderRingBufferSize() :\n *  when setting a ring buffer for streaming decompression (optional scenario),\n *  provides the minimum size of this ring buffer\n *  to be compatible with any source respecting maxBlockSize condition.\n *  Note : in a ring buffer scenario,\n *  blocks are presumed decompressed next to each other.\n *  When not enough space remains for next block (remainingSize < maxBlockSize),\n *  decoding resumes from beginning of ring buffer.\n * @return : minimum ring buffer size,\n *           or 0 if there is an error (invalid maxBlockSize).\n */\nint LZ4_decoderRingBufferSize(int maxBlockSize)\n{\n    if (maxBlockSize < 0) return 0;\n    if (maxBlockSize > LZ4_MAX_INPUT_SIZE) return 0;\n    if (maxBlockSize < 16) maxBlockSize = 16;\n    return LZ4_DECODER_RING_BUFFER_SIZE(maxBlockSize);\n}\n\n/*\n*_continue() :\n    These decoding functions allow decompression of multiple blocks in \"streaming\" mode.\n    Previously decoded blocks must still be available at the memory position where they were decoded.\n    If it's not possible, save the relevant part of decoded data into a safe buffer,\n    and indicate where it stands using LZ4_setStreamDecode()\n*/\nLZ4_FORCE_O2\nint LZ4_decompress_safe_continue (LZ4_streamDecode_t* LZ4_streamDecode, const char* source, char* dest, int compressedSize, int maxOutputSize)\n{\n    LZ4_streamDecode_t_internal* lz4sd = &LZ4_streamDecode->internal_donotuse;\n    int result;\n\n    if (lz4sd->prefixSize == 0) {\n        /* The first call, no dictionary yet. */\n        assert(lz4sd->extDictSize == 0);\n        result = LZ4_decompress_safe(source, dest, compressedSize, maxOutputSize);\n        if (result <= 0) return result;\n        lz4sd->prefixSize = (size_t)result;\n        lz4sd->prefixEnd = (BYTE*)dest + result;\n    } else if (lz4sd->prefixEnd == (BYTE*)dest) {\n        /* They're rolling the current segment. */\n        if (lz4sd->prefixSize >= 64 KB - 1)\n            result = LZ4_decompress_safe_withPrefix64k(source, dest, compressedSize, maxOutputSize);\n        else if (lz4sd->extDictSize == 0)\n            result = LZ4_decompress_safe_withSmallPrefix(source, dest, compressedSize, maxOutputSize,\n                                                         lz4sd->prefixSize);\n        else\n            result = LZ4_decompress_safe_doubleDict(source, dest, compressedSize, maxOutputSize,\n                                                    lz4sd->prefixSize, lz4sd->externalDict, lz4sd->extDictSize);\n        if (result <= 0) return result;\n        lz4sd->prefixSize += (size_t)result;\n        lz4sd->prefixEnd  += result;\n    } else {\n        /* The buffer wraps around, or they're switching to another buffer. */\n        lz4sd->extDictSize = lz4sd->prefixSize;\n        lz4sd->externalDict = lz4sd->prefixEnd - lz4sd->extDictSize;\n        result = LZ4_decompress_safe_forceExtDict(source, dest, compressedSize, maxOutputSize,\n                                                  lz4sd->externalDict, lz4sd->extDictSize);\n        if (result <= 0) return result;\n        lz4sd->prefixSize = (size_t)result;\n        lz4sd->prefixEnd  = (BYTE*)dest + result;\n    }\n\n    return result;\n}\n\nLZ4_FORCE_O2\nint LZ4_decompress_fast_continue (LZ4_streamDecode_t* LZ4_streamDecode, const char* source, char* dest, int originalSize)\n{\n    LZ4_streamDecode_t_internal* lz4sd = &LZ4_streamDecode->internal_donotuse;\n    int result;\n    assert(originalSize >= 0);\n\n    if (lz4sd->prefixSize == 0) {\n        assert(lz4sd->extDictSize == 0);\n        result = LZ4_decompress_fast(source, dest, originalSize);\n        if (result <= 0) return result;\n        lz4sd->prefixSize = (size_t)originalSize;\n        lz4sd->prefixEnd = (BYTE*)dest + originalSize;\n    } else if (lz4sd->prefixEnd == (BYTE*)dest) {\n        if (lz4sd->prefixSize >= 64 KB - 1 || lz4sd->extDictSize == 0)\n            result = LZ4_decompress_fast(source, dest, originalSize);\n        else\n            result = LZ4_decompress_fast_doubleDict(source, dest, originalSize,\n                                                    lz4sd->prefixSize, lz4sd->externalDict, lz4sd->extDictSize);\n        if (result <= 0) return result;\n        lz4sd->prefixSize += (size_t)originalSize;\n        lz4sd->prefixEnd  += originalSize;\n    } else {\n        lz4sd->extDictSize = lz4sd->prefixSize;\n        lz4sd->externalDict = lz4sd->prefixEnd - lz4sd->extDictSize;\n        result = LZ4_decompress_fast_extDict(source, dest, originalSize,\n                                             lz4sd->externalDict, lz4sd->extDictSize);\n        if (result <= 0) return result;\n        lz4sd->prefixSize = (size_t)originalSize;\n        lz4sd->prefixEnd  = (BYTE*)dest + originalSize;\n    }\n\n    return result;\n}\n\n\n/*\nAdvanced decoding functions :\n*_usingDict() :\n    These decoding functions work the same as \"_continue\" ones,\n    the dictionary must be explicitly provided within parameters\n*/\n\nint LZ4_decompress_safe_usingDict(const char* source, char* dest, int compressedSize, int maxOutputSize, const char* dictStart, int dictSize)\n{\n    if (dictSize==0)\n        return LZ4_decompress_safe(source, dest, compressedSize, maxOutputSize);\n    if (dictStart+dictSize == dest) {\n        if (dictSize >= 64 KB - 1) {\n            return LZ4_decompress_safe_withPrefix64k(source, dest, compressedSize, maxOutputSize);\n        }\n        assert(dictSize >= 0);\n        return LZ4_decompress_safe_withSmallPrefix(source, dest, compressedSize, maxOutputSize, (size_t)dictSize);\n    }\n    assert(dictSize >= 0);\n    return LZ4_decompress_safe_forceExtDict(source, dest, compressedSize, maxOutputSize, dictStart, (size_t)dictSize);\n}\n\nint LZ4_decompress_fast_usingDict(const char* source, char* dest, int originalSize, const char* dictStart, int dictSize)\n{\n    if (dictSize==0 || dictStart+dictSize == dest)\n        return LZ4_decompress_fast(source, dest, originalSize);\n    assert(dictSize >= 0);\n    return LZ4_decompress_fast_extDict(source, dest, originalSize, dictStart, (size_t)dictSize);\n}\n\n\n/*=*************************************************\n*  Obsolete Functions\n***************************************************/\n/* obsolete compression functions */\nint LZ4_compress_limitedOutput(const char* source, char* dest, int inputSize, int maxOutputSize)\n{\n    return LZ4_compress_default(source, dest, inputSize, maxOutputSize);\n}\nint LZ4_compress(const char* src, char* dest, int srcSize)\n{\n    return LZ4_compress_default(src, dest, srcSize, LZ4_compressBound(srcSize));\n}\nint LZ4_compress_limitedOutput_withState (void* state, const char* src, char* dst, int srcSize, int dstSize)\n{\n    return LZ4_compress_fast_extState(state, src, dst, srcSize, dstSize, 1);\n}\nint LZ4_compress_withState (void* state, const char* src, char* dst, int srcSize)\n{\n    return LZ4_compress_fast_extState(state, src, dst, srcSize, LZ4_compressBound(srcSize), 1);\n}\nint LZ4_compress_limitedOutput_continue (LZ4_stream_t* LZ4_stream, const char* src, char* dst, int srcSize, int dstCapacity)\n{\n    return LZ4_compress_fast_continue(LZ4_stream, src, dst, srcSize, dstCapacity, 1);\n}\nint LZ4_compress_continue (LZ4_stream_t* LZ4_stream, const char* source, char* dest, int inputSize)\n{\n    return LZ4_compress_fast_continue(LZ4_stream, source, dest, inputSize, LZ4_compressBound(inputSize), 1);\n}\n\n/*\nThese decompression functions are deprecated and should no longer be used.\nThey are only provided here for compatibility with older user programs.\n- LZ4_uncompress is totally equivalent to LZ4_decompress_fast\n- LZ4_uncompress_unknownOutputSize is totally equivalent to LZ4_decompress_safe\n*/\nint LZ4_uncompress (const char* source, char* dest, int outputSize)\n{\n    return LZ4_decompress_fast(source, dest, outputSize);\n}\nint LZ4_uncompress_unknownOutputSize (const char* source, char* dest, int isize, int maxOutputSize)\n{\n    return LZ4_decompress_safe(source, dest, isize, maxOutputSize);\n}\n\n/* Obsolete Streaming functions */\n\nint LZ4_sizeofStreamState(void) { return LZ4_STREAMSIZE; }\n\nint LZ4_resetStreamState(void* state, char* inputBuffer)\n{\n    (void)inputBuffer;\n    LZ4_resetStream((LZ4_stream_t*)state);\n    return 0;\n}\n\nvoid* LZ4_create (char* inputBuffer)\n{\n    (void)inputBuffer;\n    return LZ4_createStream();\n}\n\nchar* LZ4_slideInputBuffer (void* state)\n{\n    /* avoid const char * -> char * conversion warning */\n    return (char *)(uptrval)((LZ4_stream_t*)state)->internal_donotuse.dictionary;\n}\n\n#endif   /* LZ4_COMMONDEFS_ONLY */\n"
  },
  {
    "path": "external/lz4/lz4.h",
    "content": "/*\n *  LZ4 - Fast LZ compression algorithm\n *  Header File\n *  Copyright (C) 2011-present, Yann Collet.\n\n   BSD 2-Clause License (http://www.opensource.org/licenses/bsd-license.php)\n\n   Redistribution and use in source and binary forms, with or without\n   modification, are permitted provided that the following conditions are\n   met:\n\n       * Redistributions of source code must retain the above copyright\n   notice, this list of conditions and the following disclaimer.\n       * Redistributions in binary form must reproduce the above\n   copyright notice, this list of conditions and the following disclaimer\n   in the documentation and/or other materials provided with the\n   distribution.\n\n   THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\n   \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\n   LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR\n   A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT\n   OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,\n   SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT\n   LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,\n   DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY\n   THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\n   (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE\n   OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n\n   You can contact the author at :\n    - LZ4 homepage : http://www.lz4.org\n    - LZ4 source repository : https://github.com/lz4/lz4\n*/\n#if defined (__cplusplus)\nextern \"C\" {\n#endif\n\n#ifndef LZ4_H_2983827168210\n#define LZ4_H_2983827168210\n\n/* --- Dependency --- */\n#include <stddef.h>   /* size_t */\n\n\n/**\n  Introduction\n\n  LZ4 is lossless compression algorithm, providing compression speed >500 MB/s per core,\n  scalable with multi-cores CPU. It features an extremely fast decoder, with speed in\n  multiple GB/s per core, typically reaching RAM speed limits on multi-core systems.\n\n  The LZ4 compression library provides in-memory compression and decompression functions.\n  It gives full buffer control to user.\n  Compression can be done in:\n    - a single step (described as Simple Functions)\n    - a single step, reusing a context (described in Advanced Functions)\n    - unbounded multiple steps (described as Streaming compression)\n\n  lz4.h generates and decodes LZ4-compressed blocks (doc/lz4_Block_format.md).\n  Decompressing such a compressed block requires additional metadata.\n  Exact metadata depends on exact decompression function.\n  For the typical case of LZ4_decompress_safe(),\n  metadata includes block's compressed size, and maximum bound of decompressed size.\n  Each application is free to encode and pass such metadata in whichever way it wants.\n\n  lz4.h only handle blocks, it can not generate Frames.\n\n  Blocks are different from Frames (doc/lz4_Frame_format.md).\n  Frames bundle both blocks and metadata in a specified manner.\n  Embedding metadata is required for compressed data to be self-contained and portable.\n  Frame format is delivered through a companion API, declared in lz4frame.h.\n  The `lz4` CLI can only manage frames.\n*/\n\n/*^***************************************************************\n*  Export parameters\n*****************************************************************/\n/*\n*  LZ4_DLL_EXPORT :\n*  Enable exporting of functions when building a Windows DLL\n*  LZ4LIB_VISIBILITY :\n*  Control library symbols visibility.\n*/\n#ifndef LZ4LIB_VISIBILITY\n#  if defined(__GNUC__) && (__GNUC__ >= 4)\n#    define LZ4LIB_VISIBILITY __attribute__ ((visibility (\"default\")))\n#  else\n#    define LZ4LIB_VISIBILITY\n#  endif\n#endif\n#if defined(LZ4_DLL_EXPORT) && (LZ4_DLL_EXPORT==1)\n#  define LZ4LIB_API __declspec(dllexport) LZ4LIB_VISIBILITY\n#elif defined(LZ4_DLL_IMPORT) && (LZ4_DLL_IMPORT==1)\n#  define LZ4LIB_API __declspec(dllimport) LZ4LIB_VISIBILITY /* It isn't required but allows to generate better code, saving a function pointer load from the IAT and an indirect jump.*/\n#else\n#  define LZ4LIB_API LZ4LIB_VISIBILITY\n#endif\n\n/*------   Version   ------*/\n#define LZ4_VERSION_MAJOR    1    /* for breaking interface changes  */\n#define LZ4_VERSION_MINOR    9    /* for new (non-breaking) interface capabilities */\n#define LZ4_VERSION_RELEASE  3    /* for tweaks, bug-fixes, or development */\n\n#define LZ4_VERSION_NUMBER (LZ4_VERSION_MAJOR *100*100 + LZ4_VERSION_MINOR *100 + LZ4_VERSION_RELEASE)\n\n#define LZ4_LIB_VERSION LZ4_VERSION_MAJOR.LZ4_VERSION_MINOR.LZ4_VERSION_RELEASE\n#define LZ4_QUOTE(str) #str\n#define LZ4_EXPAND_AND_QUOTE(str) LZ4_QUOTE(str)\n#define LZ4_VERSION_STRING LZ4_EXPAND_AND_QUOTE(LZ4_LIB_VERSION)\n\nLZ4LIB_API int LZ4_versionNumber (void);  /**< library version number; useful to check dll version */\nLZ4LIB_API const char* LZ4_versionString (void);   /**< library version string; useful to check dll version */\n\n\n/*-************************************\n*  Tuning parameter\n**************************************/\n/*!\n * LZ4_MEMORY_USAGE :\n * Memory usage formula : N->2^N Bytes (examples : 10 -> 1KB; 12 -> 4KB ; 16 -> 64KB; 20 -> 1MB; etc.)\n * Increasing memory usage improves compression ratio.\n * Reduced memory usage may improve speed, thanks to better cache locality.\n * Default value is 14, for 16KB, which nicely fits into Intel x86 L1 cache\n */\n#ifndef LZ4_MEMORY_USAGE\n# define LZ4_MEMORY_USAGE 14\n#endif\n\n\n/*-************************************\n*  Simple Functions\n**************************************/\n/*! LZ4_compress_default() :\n *  Compresses 'srcSize' bytes from buffer 'src'\n *  into already allocated 'dst' buffer of size 'dstCapacity'.\n *  Compression is guaranteed to succeed if 'dstCapacity' >= LZ4_compressBound(srcSize).\n *  It also runs faster, so it's a recommended setting.\n *  If the function cannot compress 'src' into a more limited 'dst' budget,\n *  compression stops *immediately*, and the function result is zero.\n *  In which case, 'dst' content is undefined (invalid).\n *      srcSize : max supported value is LZ4_MAX_INPUT_SIZE.\n *      dstCapacity : size of buffer 'dst' (which must be already allocated)\n *     @return  : the number of bytes written into buffer 'dst' (necessarily <= dstCapacity)\n *                or 0 if compression fails\n * Note : This function is protected against buffer overflow scenarios (never writes outside 'dst' buffer, nor read outside 'source' buffer).\n */\nLZ4LIB_API int LZ4_compress_default(const char* src, char* dst, int srcSize, int dstCapacity);\n\n/*! LZ4_decompress_safe() :\n *  compressedSize : is the exact complete size of the compressed block.\n *  dstCapacity : is the size of destination buffer (which must be already allocated), presumed an upper bound of decompressed size.\n * @return : the number of bytes decompressed into destination buffer (necessarily <= dstCapacity)\n *           If destination buffer is not large enough, decoding will stop and output an error code (negative value).\n *           If the source stream is detected malformed, the function will stop decoding and return a negative result.\n * Note 1 : This function is protected against malicious data packets :\n *          it will never writes outside 'dst' buffer, nor read outside 'source' buffer,\n *          even if the compressed block is maliciously modified to order the decoder to do these actions.\n *          In such case, the decoder stops immediately, and considers the compressed block malformed.\n * Note 2 : compressedSize and dstCapacity must be provided to the function, the compressed block does not contain them.\n *          The implementation is free to send / store / derive this information in whichever way is most beneficial.\n *          If there is a need for a different format which bundles together both compressed data and its metadata, consider looking at lz4frame.h instead.\n */\nLZ4LIB_API int LZ4_decompress_safe (const char* src, char* dst, int compressedSize, int dstCapacity);\n\n\n/*-************************************\n*  Advanced Functions\n**************************************/\n#define LZ4_MAX_INPUT_SIZE        0x7E000000   /* 2 113 929 216 bytes */\n#define LZ4_COMPRESSBOUND(isize)  ((unsigned)(isize) > (unsigned)LZ4_MAX_INPUT_SIZE ? 0 : (isize) + ((isize)/255) + 16)\n\n/*! LZ4_compressBound() :\n    Provides the maximum size that LZ4 compression may output in a \"worst case\" scenario (input data not compressible)\n    This function is primarily useful for memory allocation purposes (destination buffer size).\n    Macro LZ4_COMPRESSBOUND() is also provided for compilation-time evaluation (stack memory allocation for example).\n    Note that LZ4_compress_default() compresses faster when dstCapacity is >= LZ4_compressBound(srcSize)\n        inputSize  : max supported value is LZ4_MAX_INPUT_SIZE\n        return : maximum output size in a \"worst case\" scenario\n              or 0, if input size is incorrect (too large or negative)\n*/\nLZ4LIB_API int LZ4_compressBound(int inputSize);\n\n/*! LZ4_compress_fast() :\n    Same as LZ4_compress_default(), but allows selection of \"acceleration\" factor.\n    The larger the acceleration value, the faster the algorithm, but also the lesser the compression.\n    It's a trade-off. It can be fine tuned, with each successive value providing roughly +~3% to speed.\n    An acceleration value of \"1\" is the same as regular LZ4_compress_default()\n    Values <= 0 will be replaced by LZ4_ACCELERATION_DEFAULT (currently == 1, see lz4.c).\n    Values > LZ4_ACCELERATION_MAX will be replaced by LZ4_ACCELERATION_MAX (currently == 65537, see lz4.c).\n*/\nLZ4LIB_API int LZ4_compress_fast (const char* src, char* dst, int srcSize, int dstCapacity, int acceleration);\n\n\n/*! LZ4_compress_fast_extState() :\n *  Same as LZ4_compress_fast(), using an externally allocated memory space for its state.\n *  Use LZ4_sizeofState() to know how much memory must be allocated,\n *  and allocate it on 8-bytes boundaries (using `malloc()` typically).\n *  Then, provide this buffer as `void* state` to compression function.\n */\nLZ4LIB_API int LZ4_sizeofState(void);\nLZ4LIB_API int LZ4_compress_fast_extState (void* state, const char* src, char* dst, int srcSize, int dstCapacity, int acceleration);\n\n\n/*! LZ4_compress_destSize() :\n *  Reverse the logic : compresses as much data as possible from 'src' buffer\n *  into already allocated buffer 'dst', of size >= 'targetDestSize'.\n *  This function either compresses the entire 'src' content into 'dst' if it's large enough,\n *  or fill 'dst' buffer completely with as much data as possible from 'src'.\n *  note: acceleration parameter is fixed to \"default\".\n *\n * *srcSizePtr : will be modified to indicate how many bytes where read from 'src' to fill 'dst'.\n *               New value is necessarily <= input value.\n * @return : Nb bytes written into 'dst' (necessarily <= targetDestSize)\n *           or 0 if compression fails.\n *\n * Note : from v1.8.2 to v1.9.1, this function had a bug (fixed un v1.9.2+):\n *        the produced compressed content could, in specific circumstances,\n *        require to be decompressed into a destination buffer larger\n *        by at least 1 byte than the content to decompress.\n *        If an application uses `LZ4_compress_destSize()`,\n *        it's highly recommended to update liblz4 to v1.9.2 or better.\n *        If this can't be done or ensured,\n *        the receiving decompression function should provide\n *        a dstCapacity which is > decompressedSize, by at least 1 byte.\n *        See https://github.com/lz4/lz4/issues/859 for details\n */\nLZ4LIB_API int LZ4_compress_destSize (const char* src, char* dst, int* srcSizePtr, int targetDstSize);\n\n\n/*! LZ4_decompress_safe_partial() :\n *  Decompress an LZ4 compressed block, of size 'srcSize' at position 'src',\n *  into destination buffer 'dst' of size 'dstCapacity'.\n *  Up to 'targetOutputSize' bytes will be decoded.\n *  The function stops decoding on reaching this objective.\n *  This can be useful to boost performance\n *  whenever only the beginning of a block is required.\n *\n * @return : the number of bytes decoded in `dst` (necessarily <= targetOutputSize)\n *           If source stream is detected malformed, function returns a negative result.\n *\n *  Note 1 : @return can be < targetOutputSize, if compressed block contains less data.\n *\n *  Note 2 : targetOutputSize must be <= dstCapacity\n *\n *  Note 3 : this function effectively stops decoding on reaching targetOutputSize,\n *           so dstCapacity is kind of redundant.\n *           This is because in older versions of this function,\n *           decoding operation would still write complete sequences.\n *           Therefore, there was no guarantee that it would stop writing at exactly targetOutputSize,\n *           it could write more bytes, though only up to dstCapacity.\n *           Some \"margin\" used to be required for this operation to work properly.\n *           Thankfully, this is no longer necessary.\n *           The function nonetheless keeps the same signature, in an effort to preserve API compatibility.\n *\n *  Note 4 : If srcSize is the exact size of the block,\n *           then targetOutputSize can be any value,\n *           including larger than the block's decompressed size.\n *           The function will, at most, generate block's decompressed size.\n *\n *  Note 5 : If srcSize is _larger_ than block's compressed size,\n *           then targetOutputSize **MUST** be <= block's decompressed size.\n *           Otherwise, *silent corruption will occur*.\n */\nLZ4LIB_API int LZ4_decompress_safe_partial (const char* src, char* dst, int srcSize, int targetOutputSize, int dstCapacity);\n\n\n/*-*********************************************\n*  Streaming Compression Functions\n***********************************************/\ntypedef union LZ4_stream_u LZ4_stream_t;  /* incomplete type (defined later) */\n\nLZ4LIB_API LZ4_stream_t* LZ4_createStream(void);\nLZ4LIB_API int           LZ4_freeStream (LZ4_stream_t* streamPtr);\n\n/*! LZ4_resetStream_fast() : v1.9.0+\n *  Use this to prepare an LZ4_stream_t for a new chain of dependent blocks\n *  (e.g., LZ4_compress_fast_continue()).\n *\n *  An LZ4_stream_t must be initialized once before usage.\n *  This is automatically done when created by LZ4_createStream().\n *  However, should the LZ4_stream_t be simply declared on stack (for example),\n *  it's necessary to initialize it first, using LZ4_initStream().\n *\n *  After init, start any new stream with LZ4_resetStream_fast().\n *  A same LZ4_stream_t can be re-used multiple times consecutively\n *  and compress multiple streams,\n *  provided that it starts each new stream with LZ4_resetStream_fast().\n *\n *  LZ4_resetStream_fast() is much faster than LZ4_initStream(),\n *  but is not compatible with memory regions containing garbage data.\n *\n *  Note: it's only useful to call LZ4_resetStream_fast()\n *        in the context of streaming compression.\n *        The *extState* functions perform their own resets.\n *        Invoking LZ4_resetStream_fast() before is redundant, and even counterproductive.\n */\nLZ4LIB_API void LZ4_resetStream_fast (LZ4_stream_t* streamPtr);\n\n/*! LZ4_loadDict() :\n *  Use this function to reference a static dictionary into LZ4_stream_t.\n *  The dictionary must remain available during compression.\n *  LZ4_loadDict() triggers a reset, so any previous data will be forgotten.\n *  The same dictionary will have to be loaded on decompression side for successful decoding.\n *  Dictionary are useful for better compression of small data (KB range).\n *  While LZ4 accept any input as dictionary,\n *  results are generally better when using Zstandard's Dictionary Builder.\n *  Loading a size of 0 is allowed, and is the same as reset.\n * @return : loaded dictionary size, in bytes (necessarily <= 64 KB)\n */\nLZ4LIB_API int LZ4_loadDict (LZ4_stream_t* streamPtr, const char* dictionary, int dictSize);\n\n/*! LZ4_compress_fast_continue() :\n *  Compress 'src' content using data from previously compressed blocks, for better compression ratio.\n * 'dst' buffer must be already allocated.\n *  If dstCapacity >= LZ4_compressBound(srcSize), compression is guaranteed to succeed, and runs faster.\n *\n * @return : size of compressed block\n *           or 0 if there is an error (typically, cannot fit into 'dst').\n *\n *  Note 1 : Each invocation to LZ4_compress_fast_continue() generates a new block.\n *           Each block has precise boundaries.\n *           Each block must be decompressed separately, calling LZ4_decompress_*() with relevant metadata.\n *           It's not possible to append blocks together and expect a single invocation of LZ4_decompress_*() to decompress them together.\n *\n *  Note 2 : The previous 64KB of source data is __assumed__ to remain present, unmodified, at same address in memory !\n *\n *  Note 3 : When input is structured as a double-buffer, each buffer can have any size, including < 64 KB.\n *           Make sure that buffers are separated, by at least one byte.\n *           This construction ensures that each block only depends on previous block.\n *\n *  Note 4 : If input buffer is a ring-buffer, it can have any size, including < 64 KB.\n *\n *  Note 5 : After an error, the stream status is undefined (invalid), it can only be reset or freed.\n */\nLZ4LIB_API int LZ4_compress_fast_continue (LZ4_stream_t* streamPtr, const char* src, char* dst, int srcSize, int dstCapacity, int acceleration);\n\n/*! LZ4_saveDict() :\n *  If last 64KB data cannot be guaranteed to remain available at its current memory location,\n *  save it into a safer place (char* safeBuffer).\n *  This is schematically equivalent to a memcpy() followed by LZ4_loadDict(),\n *  but is much faster, because LZ4_saveDict() doesn't need to rebuild tables.\n * @return : saved dictionary size in bytes (necessarily <= maxDictSize), or 0 if error.\n */\nLZ4LIB_API int LZ4_saveDict (LZ4_stream_t* streamPtr, char* safeBuffer, int maxDictSize);\n\n\n/*-**********************************************\n*  Streaming Decompression Functions\n*  Bufferless synchronous API\n************************************************/\ntypedef union LZ4_streamDecode_u LZ4_streamDecode_t;   /* tracking context */\n\n/*! LZ4_createStreamDecode() and LZ4_freeStreamDecode() :\n *  creation / destruction of streaming decompression tracking context.\n *  A tracking context can be re-used multiple times.\n */\nLZ4LIB_API LZ4_streamDecode_t* LZ4_createStreamDecode(void);\nLZ4LIB_API int                 LZ4_freeStreamDecode (LZ4_streamDecode_t* LZ4_stream);\n\n/*! LZ4_setStreamDecode() :\n *  An LZ4_streamDecode_t context can be allocated once and re-used multiple times.\n *  Use this function to start decompression of a new stream of blocks.\n *  A dictionary can optionally be set. Use NULL or size 0 for a reset order.\n *  Dictionary is presumed stable : it must remain accessible and unmodified during next decompression.\n * @return : 1 if OK, 0 if error\n */\nLZ4LIB_API int LZ4_setStreamDecode (LZ4_streamDecode_t* LZ4_streamDecode, const char* dictionary, int dictSize);\n\n/*! LZ4_decoderRingBufferSize() : v1.8.2+\n *  Note : in a ring buffer scenario (optional),\n *  blocks are presumed decompressed next to each other\n *  up to the moment there is not enough remaining space for next block (remainingSize < maxBlockSize),\n *  at which stage it resumes from beginning of ring buffer.\n *  When setting such a ring buffer for streaming decompression,\n *  provides the minimum size of this ring buffer\n *  to be compatible with any source respecting maxBlockSize condition.\n * @return : minimum ring buffer size,\n *           or 0 if there is an error (invalid maxBlockSize).\n */\nLZ4LIB_API int LZ4_decoderRingBufferSize(int maxBlockSize);\n#define LZ4_DECODER_RING_BUFFER_SIZE(maxBlockSize) (65536 + 14 + (maxBlockSize))  /* for static allocation; maxBlockSize presumed valid */\n\n/*! LZ4_decompress_*_continue() :\n *  These decoding functions allow decompression of consecutive blocks in \"streaming\" mode.\n *  A block is an unsplittable entity, it must be presented entirely to a decompression function.\n *  Decompression functions only accepts one block at a time.\n *  The last 64KB of previously decoded data *must* remain available and unmodified at the memory position where they were decoded.\n *  If less than 64KB of data has been decoded, all the data must be present.\n *\n *  Special : if decompression side sets a ring buffer, it must respect one of the following conditions :\n *  - Decompression buffer size is _at least_ LZ4_decoderRingBufferSize(maxBlockSize).\n *    maxBlockSize is the maximum size of any single block. It can have any value > 16 bytes.\n *    In which case, encoding and decoding buffers do not need to be synchronized.\n *    Actually, data can be produced by any source compliant with LZ4 format specification, and respecting maxBlockSize.\n *  - Synchronized mode :\n *    Decompression buffer size is _exactly_ the same as compression buffer size,\n *    and follows exactly same update rule (block boundaries at same positions),\n *    and decoding function is provided with exact decompressed size of each block (exception for last block of the stream),\n *    _then_ decoding & encoding ring buffer can have any size, including small ones ( < 64 KB).\n *  - Decompression buffer is larger than encoding buffer, by a minimum of maxBlockSize more bytes.\n *    In which case, encoding and decoding buffers do not need to be synchronized,\n *    and encoding ring buffer can have any size, including small ones ( < 64 KB).\n *\n *  Whenever these conditions are not possible,\n *  save the last 64KB of decoded data into a safe buffer where it can't be modified during decompression,\n *  then indicate where this data is saved using LZ4_setStreamDecode(), before decompressing next block.\n*/\nLZ4LIB_API int LZ4_decompress_safe_continue (LZ4_streamDecode_t* LZ4_streamDecode, const char* src, char* dst, int srcSize, int dstCapacity);\n\n\n/*! LZ4_decompress_*_usingDict() :\n *  These decoding functions work the same as\n *  a combination of LZ4_setStreamDecode() followed by LZ4_decompress_*_continue()\n *  They are stand-alone, and don't need an LZ4_streamDecode_t structure.\n *  Dictionary is presumed stable : it must remain accessible and unmodified during decompression.\n *  Performance tip : Decompression speed can be substantially increased\n *                    when dst == dictStart + dictSize.\n */\nLZ4LIB_API int LZ4_decompress_safe_usingDict (const char* src, char* dst, int srcSize, int dstCapcity, const char* dictStart, int dictSize);\n\n#endif /* LZ4_H_2983827168210 */\n\n\n/*^*************************************\n * !!!!!!   STATIC LINKING ONLY   !!!!!!\n ***************************************/\n\n/*-****************************************************************************\n * Experimental section\n *\n * Symbols declared in this section must be considered unstable. Their\n * signatures or semantics may change, or they may be removed altogether in the\n * future. They are therefore only safe to depend on when the caller is\n * statically linked against the library.\n *\n * To protect against unsafe usage, not only are the declarations guarded,\n * the definitions are hidden by default\n * when building LZ4 as a shared/dynamic library.\n *\n * In order to access these declarations,\n * define LZ4_STATIC_LINKING_ONLY in your application\n * before including LZ4's headers.\n *\n * In order to make their implementations accessible dynamically, you must\n * define LZ4_PUBLISH_STATIC_FUNCTIONS when building the LZ4 library.\n ******************************************************************************/\n\n#ifdef LZ4_STATIC_LINKING_ONLY\n\n#ifndef LZ4_STATIC_3504398509\n#define LZ4_STATIC_3504398509\n\n#ifdef LZ4_PUBLISH_STATIC_FUNCTIONS\n#define LZ4LIB_STATIC_API LZ4LIB_API\n#else\n#define LZ4LIB_STATIC_API\n#endif\n\n\n/*! LZ4_compress_fast_extState_fastReset() :\n *  A variant of LZ4_compress_fast_extState().\n *\n *  Using this variant avoids an expensive initialization step.\n *  It is only safe to call if the state buffer is known to be correctly initialized already\n *  (see above comment on LZ4_resetStream_fast() for a definition of \"correctly initialized\").\n *  From a high level, the difference is that\n *  this function initializes the provided state with a call to something like LZ4_resetStream_fast()\n *  while LZ4_compress_fast_extState() starts with a call to LZ4_resetStream().\n */\nLZ4LIB_STATIC_API int LZ4_compress_fast_extState_fastReset (void* state, const char* src, char* dst, int srcSize, int dstCapacity, int acceleration);\n\n/*! LZ4_attach_dictionary() :\n *  This is an experimental API that allows\n *  efficient use of a static dictionary many times.\n *\n *  Rather than re-loading the dictionary buffer into a working context before\n *  each compression, or copying a pre-loaded dictionary's LZ4_stream_t into a\n *  working LZ4_stream_t, this function introduces a no-copy setup mechanism,\n *  in which the working stream references the dictionary stream in-place.\n *\n *  Several assumptions are made about the state of the dictionary stream.\n *  Currently, only streams which have been prepared by LZ4_loadDict() should\n *  be expected to work.\n *\n *  Alternatively, the provided dictionaryStream may be NULL,\n *  in which case any existing dictionary stream is unset.\n *\n *  If a dictionary is provided, it replaces any pre-existing stream history.\n *  The dictionary contents are the only history that can be referenced and\n *  logically immediately precede the data compressed in the first subsequent\n *  compression call.\n *\n *  The dictionary will only remain attached to the working stream through the\n *  first compression call, at the end of which it is cleared. The dictionary\n *  stream (and source buffer) must remain in-place / accessible / unchanged\n *  through the completion of the first compression call on the stream.\n */\nLZ4LIB_STATIC_API void LZ4_attach_dictionary(LZ4_stream_t* workingStream, const LZ4_stream_t* dictionaryStream);\n\n\n/*! In-place compression and decompression\n *\n * It's possible to have input and output sharing the same buffer,\n * for highly contrained memory environments.\n * In both cases, it requires input to lay at the end of the buffer,\n * and decompression to start at beginning of the buffer.\n * Buffer size must feature some margin, hence be larger than final size.\n *\n * |<------------------------buffer--------------------------------->|\n *                             |<-----------compressed data--------->|\n * |<-----------decompressed size------------------>|\n *                                                  |<----margin---->|\n *\n * This technique is more useful for decompression,\n * since decompressed size is typically larger,\n * and margin is short.\n *\n * In-place decompression will work inside any buffer\n * which size is >= LZ4_DECOMPRESS_INPLACE_BUFFER_SIZE(decompressedSize).\n * This presumes that decompressedSize > compressedSize.\n * Otherwise, it means compression actually expanded data,\n * and it would be more efficient to store such data with a flag indicating it's not compressed.\n * This can happen when data is not compressible (already compressed, or encrypted).\n *\n * For in-place compression, margin is larger, as it must be able to cope with both\n * history preservation, requiring input data to remain unmodified up to LZ4_DISTANCE_MAX,\n * and data expansion, which can happen when input is not compressible.\n * As a consequence, buffer size requirements are much higher,\n * and memory savings offered by in-place compression are more limited.\n *\n * There are ways to limit this cost for compression :\n * - Reduce history size, by modifying LZ4_DISTANCE_MAX.\n *   Note that it is a compile-time constant, so all compressions will apply this limit.\n *   Lower values will reduce compression ratio, except when input_size < LZ4_DISTANCE_MAX,\n *   so it's a reasonable trick when inputs are known to be small.\n * - Require the compressor to deliver a \"maximum compressed size\".\n *   This is the `dstCapacity` parameter in `LZ4_compress*()`.\n *   When this size is < LZ4_COMPRESSBOUND(inputSize), then compression can fail,\n *   in which case, the return code will be 0 (zero).\n *   The caller must be ready for these cases to happen,\n *   and typically design a backup scheme to send data uncompressed.\n * The combination of both techniques can significantly reduce\n * the amount of margin required for in-place compression.\n *\n * In-place compression can work in any buffer\n * which size is >= (maxCompressedSize)\n * with maxCompressedSize == LZ4_COMPRESSBOUND(srcSize) for guaranteed compression success.\n * LZ4_COMPRESS_INPLACE_BUFFER_SIZE() depends on both maxCompressedSize and LZ4_DISTANCE_MAX,\n * so it's possible to reduce memory requirements by playing with them.\n */\n\n#define LZ4_DECOMPRESS_INPLACE_MARGIN(compressedSize)          (((compressedSize) >> 8) + 32)\n#define LZ4_DECOMPRESS_INPLACE_BUFFER_SIZE(decompressedSize)   ((decompressedSize) + LZ4_DECOMPRESS_INPLACE_MARGIN(decompressedSize))  /**< note: presumes that compressedSize < decompressedSize. note2: margin is overestimated a bit, since it could use compressedSize instead */\n\n#ifndef LZ4_DISTANCE_MAX   /* history window size; can be user-defined at compile time */\n#  define LZ4_DISTANCE_MAX 65535   /* set to maximum value by default */\n#endif\n\n#define LZ4_COMPRESS_INPLACE_MARGIN                           (LZ4_DISTANCE_MAX + 32)   /* LZ4_DISTANCE_MAX can be safely replaced by srcSize when it's smaller */\n#define LZ4_COMPRESS_INPLACE_BUFFER_SIZE(maxCompressedSize)   ((maxCompressedSize) + LZ4_COMPRESS_INPLACE_MARGIN)  /**< maxCompressedSize is generally LZ4_COMPRESSBOUND(inputSize), but can be set to any lower value, with the risk that compression can fail (return code 0(zero)) */\n\n#endif   /* LZ4_STATIC_3504398509 */\n#endif   /* LZ4_STATIC_LINKING_ONLY */\n\n\n\n#ifndef LZ4_H_98237428734687\n#define LZ4_H_98237428734687\n\n/*-************************************************************\n *  Private Definitions\n **************************************************************\n * Do not use these definitions directly.\n * They are only exposed to allow static allocation of `LZ4_stream_t` and `LZ4_streamDecode_t`.\n * Accessing members will expose user code to API and/or ABI break in future versions of the library.\n **************************************************************/\n#define LZ4_HASHLOG   (LZ4_MEMORY_USAGE-2)\n#define LZ4_HASHTABLESIZE (1 << LZ4_MEMORY_USAGE)\n#define LZ4_HASH_SIZE_U32 (1 << LZ4_HASHLOG)       /* required as macro for static allocation */\n\n#if defined(__cplusplus) || (defined (__STDC_VERSION__) && (__STDC_VERSION__ >= 199901L) /* C99 */)\n# include <stdint.h>\n  typedef  int8_t  LZ4_i8;\n  typedef uint8_t  LZ4_byte;\n  typedef uint16_t LZ4_u16;\n  typedef uint32_t LZ4_u32;\n#else\n  typedef   signed char  LZ4_i8;\n  typedef unsigned char  LZ4_byte;\n  typedef unsigned short LZ4_u16;\n  typedef unsigned int   LZ4_u32;\n#endif\n\ntypedef struct LZ4_stream_t_internal LZ4_stream_t_internal;\nstruct LZ4_stream_t_internal {\n    LZ4_u32 hashTable[LZ4_HASH_SIZE_U32];\n    LZ4_u32 currentOffset;\n    LZ4_u32 tableType;\n    const LZ4_byte* dictionary;\n    const LZ4_stream_t_internal* dictCtx;\n    LZ4_u32 dictSize;\n};\n\ntypedef struct {\n    const LZ4_byte* externalDict;\n    size_t extDictSize;\n    const LZ4_byte* prefixEnd;\n    size_t prefixSize;\n} LZ4_streamDecode_t_internal;\n\n\n/*! LZ4_stream_t :\n *  Do not use below internal definitions directly !\n *  Declare or allocate an LZ4_stream_t instead.\n *  LZ4_stream_t can also be created using LZ4_createStream(), which is recommended.\n *  The structure definition can be convenient for static allocation\n *  (on stack, or as part of larger structure).\n *  Init this structure with LZ4_initStream() before first use.\n *  note : only use this definition in association with static linking !\n *  this definition is not API/ABI safe, and may change in future versions.\n */\n#define LZ4_STREAMSIZE       16416  /* static size, for inter-version compatibility */\n#define LZ4_STREAMSIZE_VOIDP (LZ4_STREAMSIZE / sizeof(void*))\nunion LZ4_stream_u {\n    void* table[LZ4_STREAMSIZE_VOIDP];\n    LZ4_stream_t_internal internal_donotuse;\n}; /* previously typedef'd to LZ4_stream_t */\n\n\n/*! LZ4_initStream() : v1.9.0+\n *  An LZ4_stream_t structure must be initialized at least once.\n *  This is automatically done when invoking LZ4_createStream(),\n *  but it's not when the structure is simply declared on stack (for example).\n *\n *  Use LZ4_initStream() to properly initialize a newly declared LZ4_stream_t.\n *  It can also initialize any arbitrary buffer of sufficient size,\n *  and will @return a pointer of proper type upon initialization.\n *\n *  Note : initialization fails if size and alignment conditions are not respected.\n *         In which case, the function will @return NULL.\n *  Note2: An LZ4_stream_t structure guarantees correct alignment and size.\n *  Note3: Before v1.9.0, use LZ4_resetStream() instead\n */\nLZ4LIB_API LZ4_stream_t* LZ4_initStream (void* buffer, size_t size);\n\n\n/*! LZ4_streamDecode_t :\n *  information structure to track an LZ4 stream during decompression.\n *  init this structure  using LZ4_setStreamDecode() before first use.\n *  note : only use in association with static linking !\n *         this definition is not API/ABI safe,\n *         and may change in a future version !\n */\n#define LZ4_STREAMDECODESIZE_U64 (4 + ((sizeof(void*)==16) ? 2 : 0) /*AS-400*/ )\n#define LZ4_STREAMDECODESIZE     (LZ4_STREAMDECODESIZE_U64 * sizeof(unsigned long long))\nunion LZ4_streamDecode_u {\n    unsigned long long table[LZ4_STREAMDECODESIZE_U64];\n    LZ4_streamDecode_t_internal internal_donotuse;\n} ;   /* previously typedef'd to LZ4_streamDecode_t */\n\n\n\n/*-************************************\n*  Obsolete Functions\n**************************************/\n\n/*! Deprecation warnings\n *\n *  Deprecated functions make the compiler generate a warning when invoked.\n *  This is meant to invite users to update their source code.\n *  Should deprecation warnings be a problem, it is generally possible to disable them,\n *  typically with -Wno-deprecated-declarations for gcc\n *  or _CRT_SECURE_NO_WARNINGS in Visual.\n *\n *  Another method is to define LZ4_DISABLE_DEPRECATE_WARNINGS\n *  before including the header file.\n */\n#ifdef LZ4_DISABLE_DEPRECATE_WARNINGS\n#  define LZ4_DEPRECATED(message)   /* disable deprecation warnings */\n#else\n#  if defined (__cplusplus) && (__cplusplus >= 201402) /* C++14 or greater */\n#    define LZ4_DEPRECATED(message) [[deprecated(message)]]\n#  elif defined(_MSC_VER)\n#    define LZ4_DEPRECATED(message) __declspec(deprecated(message))\n#  elif defined(__clang__) || (defined(__GNUC__) && (__GNUC__ * 10 + __GNUC_MINOR__ >= 45))\n#    define LZ4_DEPRECATED(message) __attribute__((deprecated(message)))\n#  elif defined(__GNUC__) && (__GNUC__ * 10 + __GNUC_MINOR__ >= 31)\n#    define LZ4_DEPRECATED(message) __attribute__((deprecated))\n#  else\n#    pragma message(\"WARNING: LZ4_DEPRECATED needs custom implementation for this compiler\")\n#    define LZ4_DEPRECATED(message)   /* disabled */\n#  endif\n#endif /* LZ4_DISABLE_DEPRECATE_WARNINGS */\n\n/*! Obsolete compression functions (since v1.7.3) */\nLZ4_DEPRECATED(\"use LZ4_compress_default() instead\")       LZ4LIB_API int LZ4_compress               (const char* src, char* dest, int srcSize);\nLZ4_DEPRECATED(\"use LZ4_compress_default() instead\")       LZ4LIB_API int LZ4_compress_limitedOutput (const char* src, char* dest, int srcSize, int maxOutputSize);\nLZ4_DEPRECATED(\"use LZ4_compress_fast_extState() instead\") LZ4LIB_API int LZ4_compress_withState               (void* state, const char* source, char* dest, int inputSize);\nLZ4_DEPRECATED(\"use LZ4_compress_fast_extState() instead\") LZ4LIB_API int LZ4_compress_limitedOutput_withState (void* state, const char* source, char* dest, int inputSize, int maxOutputSize);\nLZ4_DEPRECATED(\"use LZ4_compress_fast_continue() instead\") LZ4LIB_API int LZ4_compress_continue                (LZ4_stream_t* LZ4_streamPtr, const char* source, char* dest, int inputSize);\nLZ4_DEPRECATED(\"use LZ4_compress_fast_continue() instead\") LZ4LIB_API int LZ4_compress_limitedOutput_continue  (LZ4_stream_t* LZ4_streamPtr, const char* source, char* dest, int inputSize, int maxOutputSize);\n\n/*! Obsolete decompression functions (since v1.8.0) */\nLZ4_DEPRECATED(\"use LZ4_decompress_fast() instead\") LZ4LIB_API int LZ4_uncompress (const char* source, char* dest, int outputSize);\nLZ4_DEPRECATED(\"use LZ4_decompress_safe() instead\") LZ4LIB_API int LZ4_uncompress_unknownOutputSize (const char* source, char* dest, int isize, int maxOutputSize);\n\n/* Obsolete streaming functions (since v1.7.0)\n * degraded functionality; do not use!\n *\n * In order to perform streaming compression, these functions depended on data\n * that is no longer tracked in the state. They have been preserved as well as\n * possible: using them will still produce a correct output. However, they don't\n * actually retain any history between compression calls. The compression ratio\n * achieved will therefore be no better than compressing each chunk\n * independently.\n */\nLZ4_DEPRECATED(\"Use LZ4_createStream() instead\") LZ4LIB_API void* LZ4_create (char* inputBuffer);\nLZ4_DEPRECATED(\"Use LZ4_createStream() instead\") LZ4LIB_API int   LZ4_sizeofStreamState(void);\nLZ4_DEPRECATED(\"Use LZ4_resetStream() instead\")  LZ4LIB_API int   LZ4_resetStreamState(void* state, char* inputBuffer);\nLZ4_DEPRECATED(\"Use LZ4_saveDict() instead\")     LZ4LIB_API char* LZ4_slideInputBuffer (void* state);\n\n/*! Obsolete streaming decoding functions (since v1.7.0) */\nLZ4_DEPRECATED(\"use LZ4_decompress_safe_usingDict() instead\") LZ4LIB_API int LZ4_decompress_safe_withPrefix64k (const char* src, char* dst, int compressedSize, int maxDstSize);\nLZ4_DEPRECATED(\"use LZ4_decompress_fast_usingDict() instead\") LZ4LIB_API int LZ4_decompress_fast_withPrefix64k (const char* src, char* dst, int originalSize);\n\n/*! Obsolete LZ4_decompress_fast variants (since v1.9.0) :\n *  These functions used to be faster than LZ4_decompress_safe(),\n *  but this is no longer the case. They are now slower.\n *  This is because LZ4_decompress_fast() doesn't know the input size,\n *  and therefore must progress more cautiously into the input buffer to not read beyond the end of block.\n *  On top of that `LZ4_decompress_fast()` is not protected vs malformed or malicious inputs, making it a security liability.\n *  As a consequence, LZ4_decompress_fast() is strongly discouraged, and deprecated.\n *\n *  The last remaining LZ4_decompress_fast() specificity is that\n *  it can decompress a block without knowing its compressed size.\n *  Such functionality can be achieved in a more secure manner\n *  by employing LZ4_decompress_safe_partial().\n *\n *  Parameters:\n *  originalSize : is the uncompressed size to regenerate.\n *                 `dst` must be already allocated, its size must be >= 'originalSize' bytes.\n * @return : number of bytes read from source buffer (== compressed size).\n *           The function expects to finish at block's end exactly.\n *           If the source stream is detected malformed, the function stops decoding and returns a negative result.\n *  note : LZ4_decompress_fast*() requires originalSize. Thanks to this information, it never writes past the output buffer.\n *         However, since it doesn't know its 'src' size, it may read an unknown amount of input, past input buffer bounds.\n *         Also, since match offsets are not validated, match reads from 'src' may underflow too.\n *         These issues never happen if input (compressed) data is correct.\n *         But they may happen if input data is invalid (error or intentional tampering).\n *         As a consequence, use these functions in trusted environments with trusted data **only**.\n */\nLZ4_DEPRECATED(\"This function is deprecated and unsafe. Consider using LZ4_decompress_safe() instead\")\nLZ4LIB_API int LZ4_decompress_fast (const char* src, char* dst, int originalSize);\nLZ4_DEPRECATED(\"This function is deprecated and unsafe. Consider using LZ4_decompress_safe_continue() instead\")\nLZ4LIB_API int LZ4_decompress_fast_continue (LZ4_streamDecode_t* LZ4_streamDecode, const char* src, char* dst, int originalSize);\nLZ4_DEPRECATED(\"This function is deprecated and unsafe. Consider using LZ4_decompress_safe_usingDict() instead\")\nLZ4LIB_API int LZ4_decompress_fast_usingDict (const char* src, char* dst, int originalSize, const char* dictStart, int dictSize);\n\n/*! LZ4_resetStream() :\n *  An LZ4_stream_t structure must be initialized at least once.\n *  This is done with LZ4_initStream(), or LZ4_resetStream().\n *  Consider switching to LZ4_initStream(),\n *  invoking LZ4_resetStream() will trigger deprecation warnings in the future.\n */\nLZ4LIB_API void LZ4_resetStream (LZ4_stream_t* streamPtr);\n\n\n#endif /* LZ4_H_98237428734687 */\n\n\n#if defined (__cplusplus)\n}\n#endif\n"
  },
  {
    "path": "external/lz4/lz4frame.c",
    "content": "/*\n * LZ4 auto-framing library\n * Copyright (C) 2011-2016, Yann Collet.\n *\n * BSD 2-Clause License (http://www.opensource.org/licenses/bsd-license.php)\n *\n * Redistribution and use in source and binary forms, with or without\n * modification, are permitted provided that the following conditions are\n * met:\n *\n * - Redistributions of source code must retain the above copyright\n *   notice, this list of conditions and the following disclaimer.\n * - Redistributions in binary form must reproduce the above\n *   copyright notice, this list of conditions and the following disclaimer\n *   in the documentation and/or other materials provided with the\n *   distribution.\n *\n * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\n * \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\n * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR\n * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT\n * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,\n * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT\n * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,\n * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY\n * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\n * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE\n * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n *\n * You can contact the author at :\n * - LZ4 homepage : http://www.lz4.org\n * - LZ4 source repository : https://github.com/lz4/lz4\n */\n\n/* LZ4F is a stand-alone API to create LZ4-compressed Frames\n * in full conformance with specification v1.6.1 .\n * This library rely upon memory management capabilities (malloc, free)\n * provided either by <stdlib.h>,\n * or redirected towards another library of user's choice\n * (see Memory Routines below).\n */\n\n\n/*-************************************\n*  Compiler Options\n**************************************/\n#ifdef _MSC_VER    /* Visual Studio */\n#  pragma warning(disable : 4127)        /* disable: C4127: conditional expression is constant */\n#endif\n\n\n/*-************************************\n*  Tuning parameters\n**************************************/\n/*\n * LZ4F_HEAPMODE :\n * Select how default compression functions will allocate memory for their hash table,\n * in memory stack (0:default, fastest), or in memory heap (1:requires malloc()).\n */\n#ifndef LZ4F_HEAPMODE\n#  define LZ4F_HEAPMODE 0\n#endif\n\n\n/*-************************************\n*  Memory routines\n**************************************/\n/*\n * User may redirect invocations of\n * malloc(), calloc() and free()\n * towards another library or solution of their choice\n * by modifying below section.\n */\n#ifndef LZ4_SRC_INCLUDED   /* avoid redefinition when sources are coalesced */\n#  include <stdlib.h>   /* malloc, calloc, free */\n#  define ALLOC(s)          malloc(s)\n#  define ALLOC_AND_ZERO(s) calloc(1,(s))\n#  define FREEMEM(p)        free(p)\n#endif\n\n#include <string.h>   /* memset, memcpy, memmove */\n#ifndef LZ4_SRC_INCLUDED  /* avoid redefinition when sources are coalesced */\n#  define MEM_INIT(p,v,s)   memset((p),(v),(s))\n#endif\n\n\n/*-************************************\n*  Library declarations\n**************************************/\n#define LZ4F_STATIC_LINKING_ONLY\n#include \"lz4frame.h\"\n#define LZ4_STATIC_LINKING_ONLY\n#include \"lz4.h\"\n#define LZ4_HC_STATIC_LINKING_ONLY\n#include \"lz4hc.h\"\n#define XXH_STATIC_LINKING_ONLY\n#include \"xxhash.h\"\n\n\n/*-************************************\n*  Debug\n**************************************/\n#if defined(LZ4_DEBUG) && (LZ4_DEBUG>=1)\n#  include <assert.h>\n#else\n#  ifndef assert\n#    define assert(condition) ((void)0)\n#  endif\n#endif\n\n#define LZ4F_STATIC_ASSERT(c)    { enum { LZ4F_static_assert = 1/(int)(!!(c)) }; }   /* use only *after* variable declarations */\n\n#if defined(LZ4_DEBUG) && (LZ4_DEBUG>=2) && !defined(DEBUGLOG)\n#  include <stdio.h>\nstatic int g_debuglog_enable = 1;\n#  define DEBUGLOG(l, ...) {                                  \\\n                if ((g_debuglog_enable) && (l<=LZ4_DEBUG)) {  \\\n                    fprintf(stderr, __FILE__ \": \");           \\\n                    fprintf(stderr, __VA_ARGS__);             \\\n                    fprintf(stderr, \" \\n\");                   \\\n            }   }\n#else\n#  define DEBUGLOG(l, ...)      {}    /* disabled */\n#endif\n\n\n/*-************************************\n*  Basic Types\n**************************************/\n#if !defined (__VMS) && (defined (__cplusplus) || (defined (__STDC_VERSION__) && (__STDC_VERSION__ >= 199901L) /* C99 */) )\n# include <stdint.h>\n  typedef  uint8_t BYTE;\n  typedef uint16_t U16;\n  typedef uint32_t U32;\n  typedef  int32_t S32;\n  typedef uint64_t U64;\n#else\n  typedef unsigned char       BYTE;\n  typedef unsigned short      U16;\n  typedef unsigned int        U32;\n  typedef   signed int        S32;\n  typedef unsigned long long  U64;\n#endif\n\n\n/* unoptimized version; solves endianess & alignment issues */\nstatic U32 LZ4F_readLE32 (const void* src)\n{\n    const BYTE* const srcPtr = (const BYTE*)src;\n    U32 value32 = srcPtr[0];\n    value32 += ((U32)srcPtr[1])<< 8;\n    value32 += ((U32)srcPtr[2])<<16;\n    value32 += ((U32)srcPtr[3])<<24;\n    return value32;\n}\n\nstatic void LZ4F_writeLE32 (void* dst, U32 value32)\n{\n    BYTE* const dstPtr = (BYTE*)dst;\n    dstPtr[0] = (BYTE)value32;\n    dstPtr[1] = (BYTE)(value32 >> 8);\n    dstPtr[2] = (BYTE)(value32 >> 16);\n    dstPtr[3] = (BYTE)(value32 >> 24);\n}\n\nstatic U64 LZ4F_readLE64 (const void* src)\n{\n    const BYTE* const srcPtr = (const BYTE*)src;\n    U64 value64 = srcPtr[0];\n    value64 += ((U64)srcPtr[1]<<8);\n    value64 += ((U64)srcPtr[2]<<16);\n    value64 += ((U64)srcPtr[3]<<24);\n    value64 += ((U64)srcPtr[4]<<32);\n    value64 += ((U64)srcPtr[5]<<40);\n    value64 += ((U64)srcPtr[6]<<48);\n    value64 += ((U64)srcPtr[7]<<56);\n    return value64;\n}\n\nstatic void LZ4F_writeLE64 (void* dst, U64 value64)\n{\n    BYTE* const dstPtr = (BYTE*)dst;\n    dstPtr[0] = (BYTE)value64;\n    dstPtr[1] = (BYTE)(value64 >> 8);\n    dstPtr[2] = (BYTE)(value64 >> 16);\n    dstPtr[3] = (BYTE)(value64 >> 24);\n    dstPtr[4] = (BYTE)(value64 >> 32);\n    dstPtr[5] = (BYTE)(value64 >> 40);\n    dstPtr[6] = (BYTE)(value64 >> 48);\n    dstPtr[7] = (BYTE)(value64 >> 56);\n}\n\n\n/*-************************************\n*  Constants\n**************************************/\n#ifndef LZ4_SRC_INCLUDED   /* avoid double definition */\n#  define KB *(1<<10)\n#  define MB *(1<<20)\n#  define GB *(1<<30)\n#endif\n\n#define _1BIT  0x01\n#define _2BITS 0x03\n#define _3BITS 0x07\n#define _4BITS 0x0F\n#define _8BITS 0xFF\n\n#define LZ4F_MAGIC_SKIPPABLE_START 0x184D2A50U\n#define LZ4F_MAGICNUMBER 0x184D2204U\n#define LZ4F_BLOCKUNCOMPRESSED_FLAG 0x80000000U\n#define LZ4F_BLOCKSIZEID_DEFAULT LZ4F_max64KB\n\nstatic const size_t minFHSize = LZ4F_HEADER_SIZE_MIN;   /*  7 */\nstatic const size_t maxFHSize = LZ4F_HEADER_SIZE_MAX;   /* 19 */\nstatic const size_t BHSize = LZ4F_BLOCK_HEADER_SIZE;  /* block header : size, and compress flag */\nstatic const size_t BFSize = LZ4F_BLOCK_CHECKSUM_SIZE;  /* block footer : checksum (optional) */\n\n\n/*-************************************\n*  Structures and local types\n**************************************/\ntypedef struct LZ4F_cctx_s\n{\n    LZ4F_preferences_t prefs;\n    U32    version;\n    U32    cStage;\n    const LZ4F_CDict* cdict;\n    size_t maxBlockSize;\n    size_t maxBufferSize;\n    BYTE*  tmpBuff;\n    BYTE*  tmpIn;\n    size_t tmpInSize;\n    U64    totalInSize;\n    XXH32_state_t xxh;\n    void*  lz4CtxPtr;\n    U16    lz4CtxAlloc; /* sized for: 0 = none, 1 = lz4 ctx, 2 = lz4hc ctx */\n    U16    lz4CtxState; /* in use as: 0 = none, 1 = lz4 ctx, 2 = lz4hc ctx */\n} LZ4F_cctx_t;\n\n\n/*-************************************\n*  Error management\n**************************************/\n#define LZ4F_GENERATE_STRING(STRING) #STRING,\nstatic const char* LZ4F_errorStrings[] = { LZ4F_LIST_ERRORS(LZ4F_GENERATE_STRING) };\n\n\nunsigned LZ4F_isError(LZ4F_errorCode_t code)\n{\n    return (code > (LZ4F_errorCode_t)(-LZ4F_ERROR_maxCode));\n}\n\nconst char* LZ4F_getErrorName(LZ4F_errorCode_t code)\n{\n    static const char* codeError = \"Unspecified error code\";\n    if (LZ4F_isError(code)) return LZ4F_errorStrings[-(int)(code)];\n    return codeError;\n}\n\nLZ4F_errorCodes LZ4F_getErrorCode(size_t functionResult)\n{\n    if (!LZ4F_isError(functionResult)) return LZ4F_OK_NoError;\n    return (LZ4F_errorCodes)(-(ptrdiff_t)functionResult);\n}\n\nstatic LZ4F_errorCode_t err0r(LZ4F_errorCodes code)\n{\n    /* A compilation error here means sizeof(ptrdiff_t) is not large enough */\n    LZ4F_STATIC_ASSERT(sizeof(ptrdiff_t) >= sizeof(size_t));\n    return (LZ4F_errorCode_t)-(ptrdiff_t)code;\n}\n\nunsigned LZ4F_getVersion(void) { return LZ4F_VERSION; }\n\nint LZ4F_compressionLevel_max(void) { return LZ4HC_CLEVEL_MAX; }\n\nsize_t LZ4F_getBlockSize(unsigned blockSizeID)\n{\n    static const size_t blockSizes[4] = { 64 KB, 256 KB, 1 MB, 4 MB };\n\n    if (blockSizeID == 0) blockSizeID = LZ4F_BLOCKSIZEID_DEFAULT;\n    if (blockSizeID < LZ4F_max64KB || blockSizeID > LZ4F_max4MB)\n        return err0r(LZ4F_ERROR_maxBlockSize_invalid);\n    blockSizeID -= LZ4F_max64KB;\n    return blockSizes[blockSizeID];\n}\n\n/*-************************************\n*  Private functions\n**************************************/\n#define MIN(a,b)   ( (a) < (b) ? (a) : (b) )\n\nstatic BYTE LZ4F_headerChecksum (const void* header, size_t length)\n{\n    U32 const xxh = XXH32(header, length, 0);\n    return (BYTE)(xxh >> 8);\n}\n\n\n/*-************************************\n*  Simple-pass compression functions\n**************************************/\nstatic LZ4F_blockSizeID_t LZ4F_optimalBSID(const LZ4F_blockSizeID_t requestedBSID,\n                                           const size_t srcSize)\n{\n    LZ4F_blockSizeID_t proposedBSID = LZ4F_max64KB;\n    size_t maxBlockSize = 64 KB;\n    while (requestedBSID > proposedBSID) {\n        if (srcSize <= maxBlockSize)\n            return proposedBSID;\n        proposedBSID = (LZ4F_blockSizeID_t)((int)proposedBSID + 1);\n        maxBlockSize <<= 2;\n    }\n    return requestedBSID;\n}\n\n/*! LZ4F_compressBound_internal() :\n *  Provides dstCapacity given a srcSize to guarantee operation success in worst case situations.\n *  prefsPtr is optional : if NULL is provided, preferences will be set to cover worst case scenario.\n * @return is always the same for a srcSize and prefsPtr, so it can be relied upon to size reusable buffers.\n *  When srcSize==0, LZ4F_compressBound() provides an upper bound for LZ4F_flush() and LZ4F_compressEnd() operations.\n */\nstatic size_t LZ4F_compressBound_internal(size_t srcSize,\n                                    const LZ4F_preferences_t* preferencesPtr,\n                                          size_t alreadyBuffered)\n{\n    LZ4F_preferences_t prefsNull = LZ4F_INIT_PREFERENCES;\n    prefsNull.frameInfo.contentChecksumFlag = LZ4F_contentChecksumEnabled;   /* worst case */\n    prefsNull.frameInfo.blockChecksumFlag = LZ4F_blockChecksumEnabled;   /* worst case */\n    {   const LZ4F_preferences_t* const prefsPtr = (preferencesPtr==NULL) ? &prefsNull : preferencesPtr;\n        U32 const flush = prefsPtr->autoFlush | (srcSize==0);\n        LZ4F_blockSizeID_t const blockID = prefsPtr->frameInfo.blockSizeID;\n        size_t const blockSize = LZ4F_getBlockSize(blockID);\n        size_t const maxBuffered = blockSize - 1;\n        size_t const bufferedSize = MIN(alreadyBuffered, maxBuffered);\n        size_t const maxSrcSize = srcSize + bufferedSize;\n        unsigned const nbFullBlocks = (unsigned)(maxSrcSize / blockSize);\n        size_t const partialBlockSize = maxSrcSize & (blockSize-1);\n        size_t const lastBlockSize = flush ? partialBlockSize : 0;\n        unsigned const nbBlocks = nbFullBlocks + (lastBlockSize>0);\n\n        size_t const blockCRCSize = BFSize * prefsPtr->frameInfo.blockChecksumFlag;\n        size_t const frameEnd = BHSize + (prefsPtr->frameInfo.contentChecksumFlag*BFSize);\n\n        return ((BHSize + blockCRCSize) * nbBlocks) +\n               (blockSize * nbFullBlocks) + lastBlockSize + frameEnd;\n    }\n}\n\nsize_t LZ4F_compressFrameBound(size_t srcSize, const LZ4F_preferences_t* preferencesPtr)\n{\n    LZ4F_preferences_t prefs;\n    size_t const headerSize = maxFHSize;      /* max header size, including optional fields */\n\n    if (preferencesPtr!=NULL) prefs = *preferencesPtr;\n    else MEM_INIT(&prefs, 0, sizeof(prefs));\n    prefs.autoFlush = 1;\n\n    return headerSize + LZ4F_compressBound_internal(srcSize, &prefs, 0);;\n}\n\n\n/*! LZ4F_compressFrame_usingCDict() :\n *  Compress srcBuffer using a dictionary, in a single step.\n *  cdict can be NULL, in which case, no dictionary is used.\n *  dstBuffer MUST be >= LZ4F_compressFrameBound(srcSize, preferencesPtr).\n *  The LZ4F_preferences_t structure is optional : you may provide NULL as argument,\n *  however, it's the only way to provide a dictID, so it's not recommended.\n * @return : number of bytes written into dstBuffer,\n *           or an error code if it fails (can be tested using LZ4F_isError())\n */\nsize_t LZ4F_compressFrame_usingCDict(LZ4F_cctx* cctx,\n                                     void* dstBuffer, size_t dstCapacity,\n                               const void* srcBuffer, size_t srcSize,\n                               const LZ4F_CDict* cdict,\n                               const LZ4F_preferences_t* preferencesPtr)\n{\n    LZ4F_preferences_t prefs;\n    LZ4F_compressOptions_t options;\n    BYTE* const dstStart = (BYTE*) dstBuffer;\n    BYTE* dstPtr = dstStart;\n    BYTE* const dstEnd = dstStart + dstCapacity;\n\n    if (preferencesPtr!=NULL)\n        prefs = *preferencesPtr;\n    else\n        MEM_INIT(&prefs, 0, sizeof(prefs));\n    if (prefs.frameInfo.contentSize != 0)\n        prefs.frameInfo.contentSize = (U64)srcSize;   /* auto-correct content size if selected (!=0) */\n\n    prefs.frameInfo.blockSizeID = LZ4F_optimalBSID(prefs.frameInfo.blockSizeID, srcSize);\n    prefs.autoFlush = 1;\n    if (srcSize <= LZ4F_getBlockSize(prefs.frameInfo.blockSizeID))\n        prefs.frameInfo.blockMode = LZ4F_blockIndependent;   /* only one block => no need for inter-block link */\n\n    MEM_INIT(&options, 0, sizeof(options));\n    options.stableSrc = 1;\n\n    if (dstCapacity < LZ4F_compressFrameBound(srcSize, &prefs))  /* condition to guarantee success */\n        return err0r(LZ4F_ERROR_dstMaxSize_tooSmall);\n\n    { size_t const headerSize = LZ4F_compressBegin_usingCDict(cctx, dstBuffer, dstCapacity, cdict, &prefs);  /* write header */\n      if (LZ4F_isError(headerSize)) return headerSize;\n      dstPtr += headerSize;   /* header size */ }\n\n    assert(dstEnd >= dstPtr);\n    { size_t const cSize = LZ4F_compressUpdate(cctx, dstPtr, (size_t)(dstEnd-dstPtr), srcBuffer, srcSize, &options);\n      if (LZ4F_isError(cSize)) return cSize;\n      dstPtr += cSize; }\n\n    assert(dstEnd >= dstPtr);\n    { size_t const tailSize = LZ4F_compressEnd(cctx, dstPtr, (size_t)(dstEnd-dstPtr), &options);   /* flush last block, and generate suffix */\n      if (LZ4F_isError(tailSize)) return tailSize;\n      dstPtr += tailSize; }\n\n    assert(dstEnd >= dstStart);\n    return (size_t)(dstPtr - dstStart);\n}\n\n\n/*! LZ4F_compressFrame() :\n *  Compress an entire srcBuffer into a valid LZ4 frame, in a single step.\n *  dstBuffer MUST be >= LZ4F_compressFrameBound(srcSize, preferencesPtr).\n *  The LZ4F_preferences_t structure is optional : you can provide NULL as argument. All preferences will be set to default.\n * @return : number of bytes written into dstBuffer.\n *           or an error code if it fails (can be tested using LZ4F_isError())\n */\nsize_t LZ4F_compressFrame(void* dstBuffer, size_t dstCapacity,\n                    const void* srcBuffer, size_t srcSize,\n                    const LZ4F_preferences_t* preferencesPtr)\n{\n    size_t result;\n#if (LZ4F_HEAPMODE)\n    LZ4F_cctx_t *cctxPtr;\n    result = LZ4F_createCompressionContext(&cctxPtr, LZ4F_VERSION);\n    if (LZ4F_isError(result)) return result;\n#else\n    LZ4F_cctx_t cctx;\n    LZ4_stream_t lz4ctx;\n    LZ4F_cctx_t *cctxPtr = &cctx;\n\n    DEBUGLOG(4, \"LZ4F_compressFrame\");\n    MEM_INIT(&cctx, 0, sizeof(cctx));\n    cctx.version = LZ4F_VERSION;\n    cctx.maxBufferSize = 5 MB;   /* mess with real buffer size to prevent dynamic allocation; works only because autoflush==1 & stableSrc==1 */\n    if (preferencesPtr == NULL ||\n        preferencesPtr->compressionLevel < LZ4HC_CLEVEL_MIN)\n    {\n        LZ4_initStream(&lz4ctx, sizeof(lz4ctx));\n        cctxPtr->lz4CtxPtr = &lz4ctx;\n        cctxPtr->lz4CtxAlloc = 1;\n        cctxPtr->lz4CtxState = 1;\n    }\n#endif\n\n    result = LZ4F_compressFrame_usingCDict(cctxPtr, dstBuffer, dstCapacity,\n                                           srcBuffer, srcSize,\n                                           NULL, preferencesPtr);\n\n#if (LZ4F_HEAPMODE)\n    LZ4F_freeCompressionContext(cctxPtr);\n#else\n    if (preferencesPtr != NULL &&\n        preferencesPtr->compressionLevel >= LZ4HC_CLEVEL_MIN)\n    {\n        FREEMEM(cctxPtr->lz4CtxPtr);\n    }\n#endif\n    return result;\n}\n\n\n/*-***************************************************\n*   Dictionary compression\n*****************************************************/\n\nstruct LZ4F_CDict_s {\n    void* dictContent;\n    LZ4_stream_t* fastCtx;\n    LZ4_streamHC_t* HCCtx;\n}; /* typedef'd to LZ4F_CDict within lz4frame_static.h */\n\n/*! LZ4F_createCDict() :\n *  When compressing multiple messages / blocks with the same dictionary, it's recommended to load it just once.\n *  LZ4F_createCDict() will create a digested dictionary, ready to start future compression operations without startup delay.\n *  LZ4F_CDict can be created once and shared by multiple threads concurrently, since its usage is read-only.\n * `dictBuffer` can be released after LZ4F_CDict creation, since its content is copied within CDict\n * @return : digested dictionary for compression, or NULL if failed */\nLZ4F_CDict* LZ4F_createCDict(const void* dictBuffer, size_t dictSize)\n{\n    const char* dictStart = (const char*)dictBuffer;\n    LZ4F_CDict* cdict = (LZ4F_CDict*) ALLOC(sizeof(*cdict));\n    DEBUGLOG(4, \"LZ4F_createCDict\");\n    if (!cdict) return NULL;\n    if (dictSize > 64 KB) {\n        dictStart += dictSize - 64 KB;\n        dictSize = 64 KB;\n    }\n    cdict->dictContent = ALLOC(dictSize);\n    cdict->fastCtx = LZ4_createStream();\n    cdict->HCCtx = LZ4_createStreamHC();\n    if (!cdict->dictContent || !cdict->fastCtx || !cdict->HCCtx) {\n        LZ4F_freeCDict(cdict);\n        return NULL;\n    }\n    memcpy(cdict->dictContent, dictStart, dictSize);\n    LZ4_loadDict (cdict->fastCtx, (const char*)cdict->dictContent, (int)dictSize);\n    LZ4_setCompressionLevel(cdict->HCCtx, LZ4HC_CLEVEL_DEFAULT);\n    LZ4_loadDictHC(cdict->HCCtx, (const char*)cdict->dictContent, (int)dictSize);\n    return cdict;\n}\n\nvoid LZ4F_freeCDict(LZ4F_CDict* cdict)\n{\n    if (cdict==NULL) return;  /* support free on NULL */\n    FREEMEM(cdict->dictContent);\n    LZ4_freeStream(cdict->fastCtx);\n    LZ4_freeStreamHC(cdict->HCCtx);\n    FREEMEM(cdict);\n}\n\n\n/*-*********************************\n*  Advanced compression functions\n***********************************/\n\n/*! LZ4F_createCompressionContext() :\n *  The first thing to do is to create a compressionContext object, which will be used in all compression operations.\n *  This is achieved using LZ4F_createCompressionContext(), which takes as argument a version and an LZ4F_preferences_t structure.\n *  The version provided MUST be LZ4F_VERSION. It is intended to track potential incompatible differences between different binaries.\n *  The function will provide a pointer to an allocated LZ4F_compressionContext_t object.\n *  If the result LZ4F_errorCode_t is not OK_NoError, there was an error during context creation.\n *  Object can release its memory using LZ4F_freeCompressionContext();\n */\nLZ4F_errorCode_t LZ4F_createCompressionContext(LZ4F_cctx** LZ4F_compressionContextPtr, unsigned version)\n{\n    LZ4F_cctx_t* const cctxPtr = (LZ4F_cctx_t*)ALLOC_AND_ZERO(sizeof(LZ4F_cctx_t));\n    if (cctxPtr==NULL) return err0r(LZ4F_ERROR_allocation_failed);\n\n    cctxPtr->version = version;\n    cctxPtr->cStage = 0;   /* Next stage : init stream */\n\n    *LZ4F_compressionContextPtr = cctxPtr;\n\n    return LZ4F_OK_NoError;\n}\n\n\nLZ4F_errorCode_t LZ4F_freeCompressionContext(LZ4F_cctx* cctxPtr)\n{\n    if (cctxPtr != NULL) {  /* support free on NULL */\n       FREEMEM(cctxPtr->lz4CtxPtr);  /* note: LZ4_streamHC_t and LZ4_stream_t are simple POD types */\n       FREEMEM(cctxPtr->tmpBuff);\n       FREEMEM(cctxPtr);\n    }\n\n    return LZ4F_OK_NoError;\n}\n\n\n/**\n * This function prepares the internal LZ4(HC) stream for a new compression,\n * resetting the context and attaching the dictionary, if there is one.\n *\n * It needs to be called at the beginning of each independent compression\n * stream (i.e., at the beginning of a frame in blockLinked mode, or at the\n * beginning of each block in blockIndependent mode).\n */\nstatic void LZ4F_initStream(void* ctx,\n                            const LZ4F_CDict* cdict,\n                            int level,\n                            LZ4F_blockMode_t blockMode) {\n    if (level < LZ4HC_CLEVEL_MIN) {\n        if (cdict != NULL || blockMode == LZ4F_blockLinked) {\n            /* In these cases, we will call LZ4_compress_fast_continue(),\n             * which needs an already reset context. Otherwise, we'll call a\n             * one-shot API. The non-continued APIs internally perform their own\n             * resets at the beginning of their calls, where they know what\n             * tableType they need the context to be in. So in that case this\n             * would be misguided / wasted work. */\n            LZ4_resetStream_fast((LZ4_stream_t*)ctx);\n        }\n        LZ4_attach_dictionary((LZ4_stream_t *)ctx, cdict ? cdict->fastCtx : NULL);\n    } else {\n        LZ4_resetStreamHC_fast((LZ4_streamHC_t*)ctx, level);\n        LZ4_attach_HC_dictionary((LZ4_streamHC_t *)ctx, cdict ? cdict->HCCtx : NULL);\n    }\n}\n\n\n/*! LZ4F_compressBegin_usingCDict() :\n *  init streaming compression and writes frame header into dstBuffer.\n *  dstBuffer must be >= LZ4F_HEADER_SIZE_MAX bytes.\n * @return : number of bytes written into dstBuffer for the header\n *           or an error code (can be tested using LZ4F_isError())\n */\nsize_t LZ4F_compressBegin_usingCDict(LZ4F_cctx* cctxPtr,\n                          void* dstBuffer, size_t dstCapacity,\n                          const LZ4F_CDict* cdict,\n                          const LZ4F_preferences_t* preferencesPtr)\n{\n    LZ4F_preferences_t prefNull;\n    BYTE* const dstStart = (BYTE*)dstBuffer;\n    BYTE* dstPtr = dstStart;\n    BYTE* headerStart;\n\n    if (dstCapacity < maxFHSize) return err0r(LZ4F_ERROR_dstMaxSize_tooSmall);\n    MEM_INIT(&prefNull, 0, sizeof(prefNull));\n    if (preferencesPtr == NULL) preferencesPtr = &prefNull;\n    cctxPtr->prefs = *preferencesPtr;\n\n    /* Ctx Management */\n    {   U16 const ctxTypeID = (cctxPtr->prefs.compressionLevel < LZ4HC_CLEVEL_MIN) ? 1 : 2;\n        if (cctxPtr->lz4CtxAlloc < ctxTypeID) {\n            FREEMEM(cctxPtr->lz4CtxPtr);\n            if (cctxPtr->prefs.compressionLevel < LZ4HC_CLEVEL_MIN) {\n                cctxPtr->lz4CtxPtr = LZ4_createStream();\n            } else {\n                cctxPtr->lz4CtxPtr = LZ4_createStreamHC();\n            }\n            if (cctxPtr->lz4CtxPtr == NULL)\n                return err0r(LZ4F_ERROR_allocation_failed);\n            cctxPtr->lz4CtxAlloc = ctxTypeID;\n            cctxPtr->lz4CtxState = ctxTypeID;\n        } else if (cctxPtr->lz4CtxState != ctxTypeID) {\n            /* otherwise, a sufficient buffer is allocated, but we need to\n             * reset it to the correct context type */\n            if (cctxPtr->prefs.compressionLevel < LZ4HC_CLEVEL_MIN) {\n                LZ4_initStream((LZ4_stream_t *) cctxPtr->lz4CtxPtr, sizeof (LZ4_stream_t));\n            } else {\n                LZ4_initStreamHC((LZ4_streamHC_t *) cctxPtr->lz4CtxPtr, sizeof(LZ4_streamHC_t));\n                LZ4_setCompressionLevel((LZ4_streamHC_t *) cctxPtr->lz4CtxPtr, cctxPtr->prefs.compressionLevel);\n            }\n            cctxPtr->lz4CtxState = ctxTypeID;\n        }\n    }\n\n    /* Buffer Management */\n    if (cctxPtr->prefs.frameInfo.blockSizeID == 0)\n        cctxPtr->prefs.frameInfo.blockSizeID = LZ4F_BLOCKSIZEID_DEFAULT;\n    cctxPtr->maxBlockSize = LZ4F_getBlockSize(cctxPtr->prefs.frameInfo.blockSizeID);\n\n    {   size_t const requiredBuffSize = preferencesPtr->autoFlush ?\n                ((cctxPtr->prefs.frameInfo.blockMode == LZ4F_blockLinked) ? 64 KB : 0) :  /* only needs past data up to window size */\n                cctxPtr->maxBlockSize + ((cctxPtr->prefs.frameInfo.blockMode == LZ4F_blockLinked) ? 128 KB : 0);\n\n        if (cctxPtr->maxBufferSize < requiredBuffSize) {\n            cctxPtr->maxBufferSize = 0;\n            FREEMEM(cctxPtr->tmpBuff);\n            cctxPtr->tmpBuff = (BYTE*)ALLOC_AND_ZERO(requiredBuffSize);\n            if (cctxPtr->tmpBuff == NULL) return err0r(LZ4F_ERROR_allocation_failed);\n            cctxPtr->maxBufferSize = requiredBuffSize;\n    }   }\n    cctxPtr->tmpIn = cctxPtr->tmpBuff;\n    cctxPtr->tmpInSize = 0;\n    (void)XXH32_reset(&(cctxPtr->xxh), 0);\n\n    /* context init */\n    cctxPtr->cdict = cdict;\n    if (cctxPtr->prefs.frameInfo.blockMode == LZ4F_blockLinked) {\n        /* frame init only for blockLinked : blockIndependent will be init at each block */\n        LZ4F_initStream(cctxPtr->lz4CtxPtr, cdict, cctxPtr->prefs.compressionLevel, LZ4F_blockLinked);\n    }\n    if (preferencesPtr->compressionLevel >= LZ4HC_CLEVEL_MIN) {\n        LZ4_favorDecompressionSpeed((LZ4_streamHC_t*)cctxPtr->lz4CtxPtr, (int)preferencesPtr->favorDecSpeed);\n    }\n\n    /* Magic Number */\n    LZ4F_writeLE32(dstPtr, LZ4F_MAGICNUMBER);\n    dstPtr += 4;\n    headerStart = dstPtr;\n\n    /* FLG Byte */\n    *dstPtr++ = (BYTE)(((1 & _2BITS) << 6)    /* Version('01') */\n        + ((cctxPtr->prefs.frameInfo.blockMode & _1BIT ) << 5)\n        + ((cctxPtr->prefs.frameInfo.blockChecksumFlag & _1BIT ) << 4)\n        + ((unsigned)(cctxPtr->prefs.frameInfo.contentSize > 0) << 3)\n        + ((cctxPtr->prefs.frameInfo.contentChecksumFlag & _1BIT ) << 2)\n        +  (cctxPtr->prefs.frameInfo.dictID > 0) );\n    /* BD Byte */\n    *dstPtr++ = (BYTE)((cctxPtr->prefs.frameInfo.blockSizeID & _3BITS) << 4);\n    /* Optional Frame content size field */\n    if (cctxPtr->prefs.frameInfo.contentSize) {\n        LZ4F_writeLE64(dstPtr, cctxPtr->prefs.frameInfo.contentSize);\n        dstPtr += 8;\n        cctxPtr->totalInSize = 0;\n    }\n    /* Optional dictionary ID field */\n    if (cctxPtr->prefs.frameInfo.dictID) {\n        LZ4F_writeLE32(dstPtr, cctxPtr->prefs.frameInfo.dictID);\n        dstPtr += 4;\n    }\n    /* Header CRC Byte */\n    *dstPtr = LZ4F_headerChecksum(headerStart, (size_t)(dstPtr - headerStart));\n    dstPtr++;\n\n    cctxPtr->cStage = 1;   /* header written, now request input data block */\n    return (size_t)(dstPtr - dstStart);\n}\n\n\n/*! LZ4F_compressBegin() :\n *  init streaming compression and writes frame header into dstBuffer.\n *  dstBuffer must be >= LZ4F_HEADER_SIZE_MAX bytes.\n *  preferencesPtr can be NULL, in which case default parameters are selected.\n * @return : number of bytes written into dstBuffer for the header\n *        or an error code (can be tested using LZ4F_isError())\n */\nsize_t LZ4F_compressBegin(LZ4F_cctx* cctxPtr,\n                          void* dstBuffer, size_t dstCapacity,\n                          const LZ4F_preferences_t* preferencesPtr)\n{\n    return LZ4F_compressBegin_usingCDict(cctxPtr, dstBuffer, dstCapacity,\n                                         NULL, preferencesPtr);\n}\n\n\n/*  LZ4F_compressBound() :\n * @return minimum capacity of dstBuffer for a given srcSize to handle worst case scenario.\n *  LZ4F_preferences_t structure is optional : if NULL, preferences will be set to cover worst case scenario.\n *  This function cannot fail.\n */\nsize_t LZ4F_compressBound(size_t srcSize, const LZ4F_preferences_t* preferencesPtr)\n{\n    if (preferencesPtr && preferencesPtr->autoFlush) {\n        return LZ4F_compressBound_internal(srcSize, preferencesPtr, 0);\n    }\n    return LZ4F_compressBound_internal(srcSize, preferencesPtr, (size_t)-1);\n}\n\n\ntypedef int (*compressFunc_t)(void* ctx, const char* src, char* dst, int srcSize, int dstSize, int level, const LZ4F_CDict* cdict);\n\n\n/*! LZ4F_makeBlock():\n *  compress a single block, add header and optional checksum.\n *  assumption : dst buffer capacity is >= BHSize + srcSize + crcSize\n */\nstatic size_t LZ4F_makeBlock(void* dst,\n                       const void* src, size_t srcSize,\n                             compressFunc_t compress, void* lz4ctx, int level,\n                       const LZ4F_CDict* cdict,\n                             LZ4F_blockChecksum_t crcFlag)\n{\n    BYTE* const cSizePtr = (BYTE*)dst;\n    U32 cSize = (U32)compress(lz4ctx, (const char*)src, (char*)(cSizePtr+BHSize),\n                                      (int)(srcSize), (int)(srcSize-1),\n                                      level, cdict);\n    if (cSize == 0) {  /* compression failed */\n        DEBUGLOG(5, \"LZ4F_makeBlock: compression failed, creating a raw block (size %u)\", (U32)srcSize);\n        cSize = (U32)srcSize;\n        LZ4F_writeLE32(cSizePtr, cSize | LZ4F_BLOCKUNCOMPRESSED_FLAG);\n        memcpy(cSizePtr+BHSize, src, srcSize);\n    } else {\n        LZ4F_writeLE32(cSizePtr, cSize);\n    }\n    if (crcFlag) {\n        U32 const crc32 = XXH32(cSizePtr+BHSize, cSize, 0);  /* checksum of compressed data */\n        LZ4F_writeLE32(cSizePtr+BHSize+cSize, crc32);\n    }\n    return BHSize + cSize + ((U32)crcFlag)*BFSize;\n}\n\n\nstatic int LZ4F_compressBlock(void* ctx, const char* src, char* dst, int srcSize, int dstCapacity, int level, const LZ4F_CDict* cdict)\n{\n    int const acceleration = (level < 0) ? -level + 1 : 1;\n    LZ4F_initStream(ctx, cdict, level, LZ4F_blockIndependent);\n    if (cdict) {\n        return LZ4_compress_fast_continue((LZ4_stream_t*)ctx, src, dst, srcSize, dstCapacity, acceleration);\n    } else {\n        return LZ4_compress_fast_extState_fastReset(ctx, src, dst, srcSize, dstCapacity, acceleration);\n    }\n}\n\nstatic int LZ4F_compressBlock_continue(void* ctx, const char* src, char* dst, int srcSize, int dstCapacity, int level, const LZ4F_CDict* cdict)\n{\n    int const acceleration = (level < 0) ? -level + 1 : 1;\n    (void)cdict; /* init once at beginning of frame */\n    return LZ4_compress_fast_continue((LZ4_stream_t*)ctx, src, dst, srcSize, dstCapacity, acceleration);\n}\n\nstatic int LZ4F_compressBlockHC(void* ctx, const char* src, char* dst, int srcSize, int dstCapacity, int level, const LZ4F_CDict* cdict)\n{\n    LZ4F_initStream(ctx, cdict, level, LZ4F_blockIndependent);\n    if (cdict) {\n        return LZ4_compress_HC_continue((LZ4_streamHC_t*)ctx, src, dst, srcSize, dstCapacity);\n    }\n    return LZ4_compress_HC_extStateHC_fastReset(ctx, src, dst, srcSize, dstCapacity, level);\n}\n\nstatic int LZ4F_compressBlockHC_continue(void* ctx, const char* src, char* dst, int srcSize, int dstCapacity, int level, const LZ4F_CDict* cdict)\n{\n    (void)level; (void)cdict; /* init once at beginning of frame */\n    return LZ4_compress_HC_continue((LZ4_streamHC_t*)ctx, src, dst, srcSize, dstCapacity);\n}\n\nstatic compressFunc_t LZ4F_selectCompression(LZ4F_blockMode_t blockMode, int level)\n{\n    if (level < LZ4HC_CLEVEL_MIN) {\n        if (blockMode == LZ4F_blockIndependent) return LZ4F_compressBlock;\n        return LZ4F_compressBlock_continue;\n    }\n    if (blockMode == LZ4F_blockIndependent) return LZ4F_compressBlockHC;\n    return LZ4F_compressBlockHC_continue;\n}\n\nstatic int LZ4F_localSaveDict(LZ4F_cctx_t* cctxPtr)\n{\n    if (cctxPtr->prefs.compressionLevel < LZ4HC_CLEVEL_MIN)\n        return LZ4_saveDict ((LZ4_stream_t*)(cctxPtr->lz4CtxPtr), (char*)(cctxPtr->tmpBuff), 64 KB);\n    return LZ4_saveDictHC ((LZ4_streamHC_t*)(cctxPtr->lz4CtxPtr), (char*)(cctxPtr->tmpBuff), 64 KB);\n}\n\ntypedef enum { notDone, fromTmpBuffer, fromSrcBuffer } LZ4F_lastBlockStatus;\n\n/*! LZ4F_compressUpdate() :\n *  LZ4F_compressUpdate() can be called repetitively to compress as much data as necessary.\n *  dstBuffer MUST be >= LZ4F_compressBound(srcSize, preferencesPtr).\n *  LZ4F_compressOptions_t structure is optional : you can provide NULL as argument.\n * @return : the number of bytes written into dstBuffer. It can be zero, meaning input data was just buffered.\n *           or an error code if it fails (which can be tested using LZ4F_isError())\n */\nsize_t LZ4F_compressUpdate(LZ4F_cctx* cctxPtr,\n                           void* dstBuffer, size_t dstCapacity,\n                     const void* srcBuffer, size_t srcSize,\n                     const LZ4F_compressOptions_t* compressOptionsPtr)\n{\n    LZ4F_compressOptions_t cOptionsNull;\n    size_t const blockSize = cctxPtr->maxBlockSize;\n    const BYTE* srcPtr = (const BYTE*)srcBuffer;\n    const BYTE* const srcEnd = srcPtr + srcSize;\n    BYTE* const dstStart = (BYTE*)dstBuffer;\n    BYTE* dstPtr = dstStart;\n    LZ4F_lastBlockStatus lastBlockCompressed = notDone;\n    compressFunc_t const compress = LZ4F_selectCompression(cctxPtr->prefs.frameInfo.blockMode, cctxPtr->prefs.compressionLevel);\n\n    DEBUGLOG(4, \"LZ4F_compressUpdate (srcSize=%zu)\", srcSize);\n\n    if (cctxPtr->cStage != 1) return err0r(LZ4F_ERROR_GENERIC);\n    if (dstCapacity < LZ4F_compressBound_internal(srcSize, &(cctxPtr->prefs), cctxPtr->tmpInSize))\n        return err0r(LZ4F_ERROR_dstMaxSize_tooSmall);\n    MEM_INIT(&cOptionsNull, 0, sizeof(cOptionsNull));\n    if (compressOptionsPtr == NULL) compressOptionsPtr = &cOptionsNull;\n\n    /* complete tmp buffer */\n    if (cctxPtr->tmpInSize > 0) {   /* some data already within tmp buffer */\n        size_t const sizeToCopy = blockSize - cctxPtr->tmpInSize;\n        if (sizeToCopy > srcSize) {\n            /* add src to tmpIn buffer */\n            memcpy(cctxPtr->tmpIn + cctxPtr->tmpInSize, srcBuffer, srcSize);\n            srcPtr = srcEnd;\n            cctxPtr->tmpInSize += srcSize;\n            /* still needs some CRC */\n        } else {\n            /* complete tmpIn block and then compress it */\n            lastBlockCompressed = fromTmpBuffer;\n            memcpy(cctxPtr->tmpIn + cctxPtr->tmpInSize, srcBuffer, sizeToCopy);\n            srcPtr += sizeToCopy;\n\n            dstPtr += LZ4F_makeBlock(dstPtr,\n                                     cctxPtr->tmpIn, blockSize,\n                                     compress, cctxPtr->lz4CtxPtr, cctxPtr->prefs.compressionLevel,\n                                     cctxPtr->cdict,\n                                     cctxPtr->prefs.frameInfo.blockChecksumFlag);\n\n            if (cctxPtr->prefs.frameInfo.blockMode==LZ4F_blockLinked) cctxPtr->tmpIn += blockSize;\n            cctxPtr->tmpInSize = 0;\n        }\n    }\n\n    while ((size_t)(srcEnd - srcPtr) >= blockSize) {\n        /* compress full blocks */\n        lastBlockCompressed = fromSrcBuffer;\n        dstPtr += LZ4F_makeBlock(dstPtr,\n                                 srcPtr, blockSize,\n                                 compress, cctxPtr->lz4CtxPtr, cctxPtr->prefs.compressionLevel,\n                                 cctxPtr->cdict,\n                                 cctxPtr->prefs.frameInfo.blockChecksumFlag);\n        srcPtr += blockSize;\n    }\n\n    if ((cctxPtr->prefs.autoFlush) && (srcPtr < srcEnd)) {\n        /* compress remaining input < blockSize */\n        lastBlockCompressed = fromSrcBuffer;\n        dstPtr += LZ4F_makeBlock(dstPtr,\n                                 srcPtr, (size_t)(srcEnd - srcPtr),\n                                 compress, cctxPtr->lz4CtxPtr, cctxPtr->prefs.compressionLevel,\n                                 cctxPtr->cdict,\n                                 cctxPtr->prefs.frameInfo.blockChecksumFlag);\n        srcPtr  = srcEnd;\n    }\n\n    /* preserve dictionary if necessary */\n    if ((cctxPtr->prefs.frameInfo.blockMode==LZ4F_blockLinked) && (lastBlockCompressed==fromSrcBuffer)) {\n        if (compressOptionsPtr->stableSrc) {\n            cctxPtr->tmpIn = cctxPtr->tmpBuff;\n        } else {\n            int const realDictSize = LZ4F_localSaveDict(cctxPtr);\n            if (realDictSize==0) return err0r(LZ4F_ERROR_GENERIC);\n            cctxPtr->tmpIn = cctxPtr->tmpBuff + realDictSize;\n        }\n    }\n\n    /* keep tmpIn within limits */\n    if ((cctxPtr->tmpIn + blockSize) > (cctxPtr->tmpBuff + cctxPtr->maxBufferSize)   /* necessarily LZ4F_blockLinked && lastBlockCompressed==fromTmpBuffer */\n        && !(cctxPtr->prefs.autoFlush))\n    {\n        int const realDictSize = LZ4F_localSaveDict(cctxPtr);\n        cctxPtr->tmpIn = cctxPtr->tmpBuff + realDictSize;\n    }\n\n    /* some input data left, necessarily < blockSize */\n    if (srcPtr < srcEnd) {\n        /* fill tmp buffer */\n        size_t const sizeToCopy = (size_t)(srcEnd - srcPtr);\n        memcpy(cctxPtr->tmpIn, srcPtr, sizeToCopy);\n        cctxPtr->tmpInSize = sizeToCopy;\n    }\n\n    if (cctxPtr->prefs.frameInfo.contentChecksumFlag == LZ4F_contentChecksumEnabled)\n        (void)XXH32_update(&(cctxPtr->xxh), srcBuffer, srcSize);\n\n    cctxPtr->totalInSize += srcSize;\n    return (size_t)(dstPtr - dstStart);\n}\n\n\n/*! LZ4F_flush() :\n *  When compressed data must be sent immediately, without waiting for a block to be filled,\n *  invoke LZ4_flush(), which will immediately compress any remaining data stored within LZ4F_cctx.\n *  The result of the function is the number of bytes written into dstBuffer.\n *  It can be zero, this means there was no data left within LZ4F_cctx.\n *  The function outputs an error code if it fails (can be tested using LZ4F_isError())\n *  LZ4F_compressOptions_t* is optional. NULL is a valid argument.\n */\nsize_t LZ4F_flush(LZ4F_cctx* cctxPtr,\n                  void* dstBuffer, size_t dstCapacity,\n            const LZ4F_compressOptions_t* compressOptionsPtr)\n{\n    BYTE* const dstStart = (BYTE*)dstBuffer;\n    BYTE* dstPtr = dstStart;\n    compressFunc_t compress;\n\n    if (cctxPtr->tmpInSize == 0) return 0;   /* nothing to flush */\n    if (cctxPtr->cStage != 1) return err0r(LZ4F_ERROR_GENERIC);\n    if (dstCapacity < (cctxPtr->tmpInSize + BHSize + BFSize))\n        return err0r(LZ4F_ERROR_dstMaxSize_tooSmall);\n    (void)compressOptionsPtr;   /* not yet useful */\n\n    /* select compression function */\n    compress = LZ4F_selectCompression(cctxPtr->prefs.frameInfo.blockMode, cctxPtr->prefs.compressionLevel);\n\n    /* compress tmp buffer */\n    dstPtr += LZ4F_makeBlock(dstPtr,\n                             cctxPtr->tmpIn, cctxPtr->tmpInSize,\n                             compress, cctxPtr->lz4CtxPtr, cctxPtr->prefs.compressionLevel,\n                             cctxPtr->cdict,\n                             cctxPtr->prefs.frameInfo.blockChecksumFlag);\n    assert(((void)\"flush overflows dstBuffer!\", (size_t)(dstPtr - dstStart) <= dstCapacity));\n\n    if (cctxPtr->prefs.frameInfo.blockMode == LZ4F_blockLinked)\n        cctxPtr->tmpIn += cctxPtr->tmpInSize;\n    cctxPtr->tmpInSize = 0;\n\n    /* keep tmpIn within limits */\n    if ((cctxPtr->tmpIn + cctxPtr->maxBlockSize) > (cctxPtr->tmpBuff + cctxPtr->maxBufferSize)) {  /* necessarily LZ4F_blockLinked */\n        int const realDictSize = LZ4F_localSaveDict(cctxPtr);\n        cctxPtr->tmpIn = cctxPtr->tmpBuff + realDictSize;\n    }\n\n    return (size_t)(dstPtr - dstStart);\n}\n\n\n/*! LZ4F_compressEnd() :\n *  When you want to properly finish the compressed frame, just call LZ4F_compressEnd().\n *  It will flush whatever data remained within compressionContext (like LZ4_flush())\n *  but also properly finalize the frame, with an endMark and an (optional) checksum.\n *  LZ4F_compressOptions_t structure is optional : you can provide NULL as argument.\n * @return: the number of bytes written into dstBuffer (necessarily >= 4 (endMark size))\n *       or an error code if it fails (can be tested using LZ4F_isError())\n *  The context can then be used again to compress a new frame, starting with LZ4F_compressBegin().\n */\nsize_t LZ4F_compressEnd(LZ4F_cctx* cctxPtr,\n                        void* dstBuffer, size_t dstCapacity,\n                  const LZ4F_compressOptions_t* compressOptionsPtr)\n{\n    BYTE* const dstStart = (BYTE*)dstBuffer;\n    BYTE* dstPtr = dstStart;\n\n    size_t const flushSize = LZ4F_flush(cctxPtr, dstBuffer, dstCapacity, compressOptionsPtr);\n    DEBUGLOG(5,\"LZ4F_compressEnd: dstCapacity=%u\", (unsigned)dstCapacity);\n    if (LZ4F_isError(flushSize)) return flushSize;\n    dstPtr += flushSize;\n\n    assert(flushSize <= dstCapacity);\n    dstCapacity -= flushSize;\n\n    if (dstCapacity < 4) return err0r(LZ4F_ERROR_dstMaxSize_tooSmall);\n    LZ4F_writeLE32(dstPtr, 0);\n    dstPtr += 4;   /* endMark */\n\n    if (cctxPtr->prefs.frameInfo.contentChecksumFlag == LZ4F_contentChecksumEnabled) {\n        U32 const xxh = XXH32_digest(&(cctxPtr->xxh));\n        if (dstCapacity < 8) return err0r(LZ4F_ERROR_dstMaxSize_tooSmall);\n        DEBUGLOG(5,\"Writing 32-bit content checksum\");\n        LZ4F_writeLE32(dstPtr, xxh);\n        dstPtr+=4;   /* content Checksum */\n    }\n\n    cctxPtr->cStage = 0;   /* state is now re-usable (with identical preferences) */\n    cctxPtr->maxBufferSize = 0;  /* reuse HC context */\n\n    if (cctxPtr->prefs.frameInfo.contentSize) {\n        if (cctxPtr->prefs.frameInfo.contentSize != cctxPtr->totalInSize)\n            return err0r(LZ4F_ERROR_frameSize_wrong);\n    }\n\n    return (size_t)(dstPtr - dstStart);\n}\n\n\n/*-***************************************************\n*   Frame Decompression\n*****************************************************/\n\ntypedef enum {\n    dstage_getFrameHeader=0, dstage_storeFrameHeader,\n    dstage_init,\n    dstage_getBlockHeader, dstage_storeBlockHeader,\n    dstage_copyDirect, dstage_getBlockChecksum,\n    dstage_getCBlock, dstage_storeCBlock,\n    dstage_flushOut,\n    dstage_getSuffix, dstage_storeSuffix,\n    dstage_getSFrameSize, dstage_storeSFrameSize,\n    dstage_skipSkippable\n} dStage_t;\n\nstruct LZ4F_dctx_s {\n    LZ4F_frameInfo_t frameInfo;\n    U32    version;\n    dStage_t dStage;\n    U64    frameRemainingSize;\n    size_t maxBlockSize;\n    size_t maxBufferSize;\n    BYTE*  tmpIn;\n    size_t tmpInSize;\n    size_t tmpInTarget;\n    BYTE*  tmpOutBuffer;\n    const BYTE* dict;\n    size_t dictSize;\n    BYTE*  tmpOut;\n    size_t tmpOutSize;\n    size_t tmpOutStart;\n    XXH32_state_t xxh;\n    XXH32_state_t blockChecksum;\n    BYTE   header[LZ4F_HEADER_SIZE_MAX];\n};  /* typedef'd to LZ4F_dctx in lz4frame.h */\n\n\n/*! LZ4F_createDecompressionContext() :\n *  Create a decompressionContext object, which will track all decompression operations.\n *  Provides a pointer to a fully allocated and initialized LZ4F_decompressionContext object.\n *  Object can later be released using LZ4F_freeDecompressionContext().\n * @return : if != 0, there was an error during context creation.\n */\nLZ4F_errorCode_t LZ4F_createDecompressionContext(LZ4F_dctx** LZ4F_decompressionContextPtr, unsigned versionNumber)\n{\n    LZ4F_dctx* const dctx = (LZ4F_dctx*)ALLOC_AND_ZERO(sizeof(LZ4F_dctx));\n    if (dctx == NULL) {  /* failed allocation */\n        *LZ4F_decompressionContextPtr = NULL;\n        return err0r(LZ4F_ERROR_allocation_failed);\n    }\n\n    dctx->version = versionNumber;\n    *LZ4F_decompressionContextPtr = dctx;\n    return LZ4F_OK_NoError;\n}\n\nLZ4F_errorCode_t LZ4F_freeDecompressionContext(LZ4F_dctx* dctx)\n{\n    LZ4F_errorCode_t result = LZ4F_OK_NoError;\n    if (dctx != NULL) {   /* can accept NULL input, like free() */\n      result = (LZ4F_errorCode_t)dctx->dStage;\n      FREEMEM(dctx->tmpIn);\n      FREEMEM(dctx->tmpOutBuffer);\n      FREEMEM(dctx);\n    }\n    return result;\n}\n\n\n/*==---   Streaming Decompression operations   ---==*/\n\nvoid LZ4F_resetDecompressionContext(LZ4F_dctx* dctx)\n{\n    dctx->dStage = dstage_getFrameHeader;\n    dctx->dict = NULL;\n    dctx->dictSize = 0;\n}\n\n\n/*! LZ4F_decodeHeader() :\n *  input   : `src` points at the **beginning of the frame**\n *  output  : set internal values of dctx, such as\n *            dctx->frameInfo and dctx->dStage.\n *            Also allocates internal buffers.\n *  @return : nb Bytes read from src (necessarily <= srcSize)\n *            or an error code (testable with LZ4F_isError())\n */\nstatic size_t LZ4F_decodeHeader(LZ4F_dctx* dctx, const void* src, size_t srcSize)\n{\n    unsigned blockMode, blockChecksumFlag, contentSizeFlag, contentChecksumFlag, dictIDFlag, blockSizeID;\n    size_t frameHeaderSize;\n    const BYTE* srcPtr = (const BYTE*)src;\n\n    DEBUGLOG(5, \"LZ4F_decodeHeader\");\n    /* need to decode header to get frameInfo */\n    if (srcSize < minFHSize) return err0r(LZ4F_ERROR_frameHeader_incomplete);   /* minimal frame header size */\n    MEM_INIT(&(dctx->frameInfo), 0, sizeof(dctx->frameInfo));\n\n    /* special case : skippable frames */\n    if ((LZ4F_readLE32(srcPtr) & 0xFFFFFFF0U) == LZ4F_MAGIC_SKIPPABLE_START) {\n        dctx->frameInfo.frameType = LZ4F_skippableFrame;\n        if (src == (void*)(dctx->header)) {\n            dctx->tmpInSize = srcSize;\n            dctx->tmpInTarget = 8;\n            dctx->dStage = dstage_storeSFrameSize;\n            return srcSize;\n        } else {\n            dctx->dStage = dstage_getSFrameSize;\n            return 4;\n        }\n    }\n\n    /* control magic number */\n#ifndef FUZZING_BUILD_MODE_UNSAFE_FOR_PRODUCTION\n    if (LZ4F_readLE32(srcPtr) != LZ4F_MAGICNUMBER) {\n        DEBUGLOG(4, \"frame header error : unknown magic number\");\n        return err0r(LZ4F_ERROR_frameType_unknown);\n    }\n#endif\n    dctx->frameInfo.frameType = LZ4F_frame;\n\n    /* Flags */\n    {   U32 const FLG = srcPtr[4];\n        U32 const version = (FLG>>6) & _2BITS;\n        blockChecksumFlag = (FLG>>4) & _1BIT;\n        blockMode = (FLG>>5) & _1BIT;\n        contentSizeFlag = (FLG>>3) & _1BIT;\n        contentChecksumFlag = (FLG>>2) & _1BIT;\n        dictIDFlag = FLG & _1BIT;\n        /* validate */\n        if (((FLG>>1)&_1BIT) != 0) return err0r(LZ4F_ERROR_reservedFlag_set); /* Reserved bit */\n        if (version != 1) return err0r(LZ4F_ERROR_headerVersion_wrong);        /* Version Number, only supported value */\n    }\n\n    /* Frame Header Size */\n    frameHeaderSize = minFHSize + (contentSizeFlag?8:0) + (dictIDFlag?4:0);\n\n    if (srcSize < frameHeaderSize) {\n        /* not enough input to fully decode frame header */\n        if (srcPtr != dctx->header)\n            memcpy(dctx->header, srcPtr, srcSize);\n        dctx->tmpInSize = srcSize;\n        dctx->tmpInTarget = frameHeaderSize;\n        dctx->dStage = dstage_storeFrameHeader;\n        return srcSize;\n    }\n\n    {   U32 const BD = srcPtr[5];\n        blockSizeID = (BD>>4) & _3BITS;\n        /* validate */\n        if (((BD>>7)&_1BIT) != 0) return err0r(LZ4F_ERROR_reservedFlag_set);   /* Reserved bit */\n        if (blockSizeID < 4) return err0r(LZ4F_ERROR_maxBlockSize_invalid);    /* 4-7 only supported values for the time being */\n        if (((BD>>0)&_4BITS) != 0) return err0r(LZ4F_ERROR_reservedFlag_set);  /* Reserved bits */\n    }\n\n    /* check header */\n    assert(frameHeaderSize > 5);\n#ifndef FUZZING_BUILD_MODE_UNSAFE_FOR_PRODUCTION\n    {   BYTE const HC = LZ4F_headerChecksum(srcPtr+4, frameHeaderSize-5);\n        if (HC != srcPtr[frameHeaderSize-1])\n            return err0r(LZ4F_ERROR_headerChecksum_invalid);\n    }\n#endif\n\n    /* save */\n    dctx->frameInfo.blockMode = (LZ4F_blockMode_t)blockMode;\n    dctx->frameInfo.blockChecksumFlag = (LZ4F_blockChecksum_t)blockChecksumFlag;\n    dctx->frameInfo.contentChecksumFlag = (LZ4F_contentChecksum_t)contentChecksumFlag;\n    dctx->frameInfo.blockSizeID = (LZ4F_blockSizeID_t)blockSizeID;\n    dctx->maxBlockSize = LZ4F_getBlockSize(blockSizeID);\n    if (contentSizeFlag)\n        dctx->frameRemainingSize =\n            dctx->frameInfo.contentSize = LZ4F_readLE64(srcPtr+6);\n    if (dictIDFlag)\n        dctx->frameInfo.dictID = LZ4F_readLE32(srcPtr + frameHeaderSize - 5);\n\n    dctx->dStage = dstage_init;\n\n    return frameHeaderSize;\n}\n\n\n/*! LZ4F_headerSize() :\n * @return : size of frame header\n *           or an error code, which can be tested using LZ4F_isError()\n */\nsize_t LZ4F_headerSize(const void* src, size_t srcSize)\n{\n    if (src == NULL) return err0r(LZ4F_ERROR_srcPtr_wrong);\n\n    /* minimal srcSize to determine header size */\n    if (srcSize < LZ4F_MIN_SIZE_TO_KNOW_HEADER_LENGTH)\n        return err0r(LZ4F_ERROR_frameHeader_incomplete);\n\n    /* special case : skippable frames */\n    if ((LZ4F_readLE32(src) & 0xFFFFFFF0U) == LZ4F_MAGIC_SKIPPABLE_START)\n        return 8;\n\n    /* control magic number */\n#ifndef FUZZING_BUILD_MODE_UNSAFE_FOR_PRODUCTION\n    if (LZ4F_readLE32(src) != LZ4F_MAGICNUMBER)\n        return err0r(LZ4F_ERROR_frameType_unknown);\n#endif\n\n    /* Frame Header Size */\n    {   BYTE const FLG = ((const BYTE*)src)[4];\n        U32 const contentSizeFlag = (FLG>>3) & _1BIT;\n        U32 const dictIDFlag = FLG & _1BIT;\n        return minFHSize + (contentSizeFlag?8:0) + (dictIDFlag?4:0);\n    }\n}\n\n/*! LZ4F_getFrameInfo() :\n *  This function extracts frame parameters (max blockSize, frame checksum, etc.).\n *  Usage is optional. Objective is to provide relevant information for allocation purposes.\n *  This function works in 2 situations :\n *   - At the beginning of a new frame, in which case it will decode this information from `srcBuffer`, and start the decoding process.\n *     Amount of input data provided must be large enough to successfully decode the frame header.\n *     A header size is variable, but is guaranteed to be <= LZ4F_HEADER_SIZE_MAX bytes. It's possible to provide more input data than this minimum.\n *   - After decoding has been started. In which case, no input is read, frame parameters are extracted from dctx.\n *  The number of bytes consumed from srcBuffer will be updated within *srcSizePtr (necessarily <= original value).\n *  Decompression must resume from (srcBuffer + *srcSizePtr).\n * @return : an hint about how many srcSize bytes LZ4F_decompress() expects for next call,\n *           or an error code which can be tested using LZ4F_isError()\n *  note 1 : in case of error, dctx is not modified. Decoding operations can resume from where they stopped.\n *  note 2 : frame parameters are *copied into* an already allocated LZ4F_frameInfo_t structure.\n */\nLZ4F_errorCode_t LZ4F_getFrameInfo(LZ4F_dctx* dctx,\n                                   LZ4F_frameInfo_t* frameInfoPtr,\n                             const void* srcBuffer, size_t* srcSizePtr)\n{\n    LZ4F_STATIC_ASSERT(dstage_getFrameHeader < dstage_storeFrameHeader);\n    if (dctx->dStage > dstage_storeFrameHeader) {\n        /* frameInfo already decoded */\n        size_t o=0, i=0;\n        *srcSizePtr = 0;\n        *frameInfoPtr = dctx->frameInfo;\n        /* returns : recommended nb of bytes for LZ4F_decompress() */\n        return LZ4F_decompress(dctx, NULL, &o, NULL, &i, NULL);\n    } else {\n        if (dctx->dStage == dstage_storeFrameHeader) {\n            /* frame decoding already started, in the middle of header => automatic fail */\n            *srcSizePtr = 0;\n            return err0r(LZ4F_ERROR_frameDecoding_alreadyStarted);\n        } else {\n            size_t const hSize = LZ4F_headerSize(srcBuffer, *srcSizePtr);\n            if (LZ4F_isError(hSize)) { *srcSizePtr=0; return hSize; }\n            if (*srcSizePtr < hSize) {\n                *srcSizePtr=0;\n                return err0r(LZ4F_ERROR_frameHeader_incomplete);\n            }\n\n            {   size_t decodeResult = LZ4F_decodeHeader(dctx, srcBuffer, hSize);\n                if (LZ4F_isError(decodeResult)) {\n                    *srcSizePtr = 0;\n                } else {\n                    *srcSizePtr = decodeResult;\n                    decodeResult = BHSize;   /* block header size */\n                }\n                *frameInfoPtr = dctx->frameInfo;\n                return decodeResult;\n    }   }   }\n}\n\n\n/* LZ4F_updateDict() :\n * only used for LZ4F_blockLinked mode\n * Condition : dstPtr != NULL\n */\nstatic void LZ4F_updateDict(LZ4F_dctx* dctx,\n                      const BYTE* dstPtr, size_t dstSize, const BYTE* dstBufferStart,\n                      unsigned withinTmp)\n{\n    assert(dstPtr != NULL);\n    if (dctx->dictSize==0) {\n        dctx->dict = (const BYTE*)dstPtr;   /* priority to prefix mode */\n    }\n    assert(dctx->dict != NULL);\n\n    if (dctx->dict + dctx->dictSize == dstPtr) {  /* prefix mode, everything within dstBuffer */\n        dctx->dictSize += dstSize;\n        return;\n    }\n\n    assert(dstPtr >= dstBufferStart);\n    if ((size_t)(dstPtr - dstBufferStart) + dstSize >= 64 KB) {  /* history in dstBuffer becomes large enough to become dictionary */\n        dctx->dict = (const BYTE*)dstBufferStart;\n        dctx->dictSize = (size_t)(dstPtr - dstBufferStart) + dstSize;\n        return;\n    }\n\n    assert(dstSize < 64 KB);   /* if dstSize >= 64 KB, dictionary would be set into dstBuffer directly */\n\n    /* dstBuffer does not contain whole useful history (64 KB), so it must be saved within tmpOutBuffer */\n    assert(dctx->tmpOutBuffer != NULL);\n\n    if (withinTmp && (dctx->dict == dctx->tmpOutBuffer)) {   /* continue history within tmpOutBuffer */\n        /* withinTmp expectation : content of [dstPtr,dstSize] is same as [dict+dictSize,dstSize], so we just extend it */\n        assert(dctx->dict + dctx->dictSize == dctx->tmpOut + dctx->tmpOutStart);\n        dctx->dictSize += dstSize;\n        return;\n    }\n\n    if (withinTmp) { /* copy relevant dict portion in front of tmpOut within tmpOutBuffer */\n        size_t const preserveSize = (size_t)(dctx->tmpOut - dctx->tmpOutBuffer);\n        size_t copySize = 64 KB - dctx->tmpOutSize;\n        const BYTE* const oldDictEnd = dctx->dict + dctx->dictSize - dctx->tmpOutStart;\n        if (dctx->tmpOutSize > 64 KB) copySize = 0;\n        if (copySize > preserveSize) copySize = preserveSize;\n\n        memcpy(dctx->tmpOutBuffer + preserveSize - copySize, oldDictEnd - copySize, copySize);\n\n        dctx->dict = dctx->tmpOutBuffer;\n        dctx->dictSize = preserveSize + dctx->tmpOutStart + dstSize;\n        return;\n    }\n\n    if (dctx->dict == dctx->tmpOutBuffer) {    /* copy dst into tmp to complete dict */\n        if (dctx->dictSize + dstSize > dctx->maxBufferSize) {  /* tmp buffer not large enough */\n            size_t const preserveSize = 64 KB - dstSize;\n            memcpy(dctx->tmpOutBuffer, dctx->dict + dctx->dictSize - preserveSize, preserveSize);\n            dctx->dictSize = preserveSize;\n        }\n        memcpy(dctx->tmpOutBuffer + dctx->dictSize, dstPtr, dstSize);\n        dctx->dictSize += dstSize;\n        return;\n    }\n\n    /* join dict & dest into tmp */\n    {   size_t preserveSize = 64 KB - dstSize;\n        if (preserveSize > dctx->dictSize) preserveSize = dctx->dictSize;\n        memcpy(dctx->tmpOutBuffer, dctx->dict + dctx->dictSize - preserveSize, preserveSize);\n        memcpy(dctx->tmpOutBuffer + preserveSize, dstPtr, dstSize);\n        dctx->dict = dctx->tmpOutBuffer;\n        dctx->dictSize = preserveSize + dstSize;\n    }\n}\n\n\n\n/*! LZ4F_decompress() :\n *  Call this function repetitively to regenerate compressed data in srcBuffer.\n *  The function will attempt to decode up to *srcSizePtr bytes from srcBuffer\n *  into dstBuffer of capacity *dstSizePtr.\n *\n *  The number of bytes regenerated into dstBuffer will be provided within *dstSizePtr (necessarily <= original value).\n *\n *  The number of bytes effectively read from srcBuffer will be provided within *srcSizePtr (necessarily <= original value).\n *  If number of bytes read is < number of bytes provided, then decompression operation is not complete.\n *  Remaining data will have to be presented again in a subsequent invocation.\n *\n *  The function result is an hint of the better srcSize to use for next call to LZ4F_decompress.\n *  Schematically, it's the size of the current (or remaining) compressed block + header of next block.\n *  Respecting the hint provides a small boost to performance, since it allows less buffer shuffling.\n *  Note that this is just a hint, and it's always possible to any srcSize value.\n *  When a frame is fully decoded, @return will be 0.\n *  If decompression failed, @return is an error code which can be tested using LZ4F_isError().\n */\nsize_t LZ4F_decompress(LZ4F_dctx* dctx,\n                       void* dstBuffer, size_t* dstSizePtr,\n                       const void* srcBuffer, size_t* srcSizePtr,\n                       const LZ4F_decompressOptions_t* decompressOptionsPtr)\n{\n    LZ4F_decompressOptions_t optionsNull;\n    const BYTE* const srcStart = (const BYTE*)srcBuffer;\n    const BYTE* const srcEnd = srcStart + *srcSizePtr;\n    const BYTE* srcPtr = srcStart;\n    BYTE* const dstStart = (BYTE*)dstBuffer;\n    BYTE* const dstEnd = dstStart ? dstStart + *dstSizePtr : NULL;\n    BYTE* dstPtr = dstStart;\n    const BYTE* selectedIn = NULL;\n    unsigned doAnotherStage = 1;\n    size_t nextSrcSizeHint = 1;\n\n\n    DEBUGLOG(5, \"LZ4F_decompress : %p,%u => %p,%u\",\n            srcBuffer, (unsigned)*srcSizePtr, dstBuffer, (unsigned)*dstSizePtr);\n    if (dstBuffer == NULL) assert(*dstSizePtr == 0);\n    MEM_INIT(&optionsNull, 0, sizeof(optionsNull));\n    if (decompressOptionsPtr==NULL) decompressOptionsPtr = &optionsNull;\n    *srcSizePtr = 0;\n    *dstSizePtr = 0;\n    assert(dctx != NULL);\n\n    /* behaves as a state machine */\n\n    while (doAnotherStage) {\n\n        switch(dctx->dStage)\n        {\n\n        case dstage_getFrameHeader:\n            DEBUGLOG(6, \"dstage_getFrameHeader\");\n            if ((size_t)(srcEnd-srcPtr) >= maxFHSize) {  /* enough to decode - shortcut */\n                size_t const hSize = LZ4F_decodeHeader(dctx, srcPtr, (size_t)(srcEnd-srcPtr));  /* will update dStage appropriately */\n                if (LZ4F_isError(hSize)) return hSize;\n                srcPtr += hSize;\n                break;\n            }\n            dctx->tmpInSize = 0;\n            if (srcEnd-srcPtr == 0) return minFHSize;   /* 0-size input */\n            dctx->tmpInTarget = minFHSize;   /* minimum size to decode header */\n            dctx->dStage = dstage_storeFrameHeader;\n            /* fall-through */\n\n        case dstage_storeFrameHeader:\n            DEBUGLOG(6, \"dstage_storeFrameHeader\");\n            {   size_t const sizeToCopy = MIN(dctx->tmpInTarget - dctx->tmpInSize, (size_t)(srcEnd - srcPtr));\n                memcpy(dctx->header + dctx->tmpInSize, srcPtr, sizeToCopy);\n                dctx->tmpInSize += sizeToCopy;\n                srcPtr += sizeToCopy;\n            }\n            if (dctx->tmpInSize < dctx->tmpInTarget) {\n                nextSrcSizeHint = (dctx->tmpInTarget - dctx->tmpInSize) + BHSize;   /* rest of header + nextBlockHeader */\n                doAnotherStage = 0;   /* not enough src data, ask for some more */\n                break;\n            }\n            {   size_t const hSize = LZ4F_decodeHeader(dctx, dctx->header, dctx->tmpInTarget);  /* will update dStage appropriately */\n                if (LZ4F_isError(hSize)) return hSize;\n            }\n            break;\n\n        case dstage_init:\n            DEBUGLOG(6, \"dstage_init\");\n            if (dctx->frameInfo.contentChecksumFlag) (void)XXH32_reset(&(dctx->xxh), 0);\n            /* internal buffers allocation */\n            {   size_t const bufferNeeded = dctx->maxBlockSize\n                    + ((dctx->frameInfo.blockMode==LZ4F_blockLinked) ? 128 KB : 0);\n                if (bufferNeeded > dctx->maxBufferSize) {   /* tmp buffers too small */\n                    dctx->maxBufferSize = 0;   /* ensure allocation will be re-attempted on next entry*/\n                    FREEMEM(dctx->tmpIn);\n                    dctx->tmpIn = (BYTE*)ALLOC(dctx->maxBlockSize + BFSize /* block checksum */);\n                    if (dctx->tmpIn == NULL)\n                        return err0r(LZ4F_ERROR_allocation_failed);\n                    FREEMEM(dctx->tmpOutBuffer);\n                    dctx->tmpOutBuffer= (BYTE*)ALLOC(bufferNeeded);\n                    if (dctx->tmpOutBuffer== NULL)\n                        return err0r(LZ4F_ERROR_allocation_failed);\n                    dctx->maxBufferSize = bufferNeeded;\n            }   }\n            dctx->tmpInSize = 0;\n            dctx->tmpInTarget = 0;\n            dctx->tmpOut = dctx->tmpOutBuffer;\n            dctx->tmpOutStart = 0;\n            dctx->tmpOutSize = 0;\n\n            dctx->dStage = dstage_getBlockHeader;\n            /* fall-through */\n\n        case dstage_getBlockHeader:\n            if ((size_t)(srcEnd - srcPtr) >= BHSize) {\n                selectedIn = srcPtr;\n                srcPtr += BHSize;\n            } else {\n                /* not enough input to read cBlockSize field */\n                dctx->tmpInSize = 0;\n                dctx->dStage = dstage_storeBlockHeader;\n            }\n\n            if (dctx->dStage == dstage_storeBlockHeader)   /* can be skipped */\n        case dstage_storeBlockHeader:\n            {   size_t const remainingInput = (size_t)(srcEnd - srcPtr);\n                size_t const wantedData = BHSize - dctx->tmpInSize;\n                size_t const sizeToCopy = MIN(wantedData, remainingInput);\n                memcpy(dctx->tmpIn + dctx->tmpInSize, srcPtr, sizeToCopy);\n                srcPtr += sizeToCopy;\n                dctx->tmpInSize += sizeToCopy;\n\n                if (dctx->tmpInSize < BHSize) {   /* not enough input for cBlockSize */\n                    nextSrcSizeHint = BHSize - dctx->tmpInSize;\n                    doAnotherStage  = 0;\n                    break;\n                }\n                selectedIn = dctx->tmpIn;\n            }   /* if (dctx->dStage == dstage_storeBlockHeader) */\n\n        /* decode block header */\n            {   U32 const blockHeader = LZ4F_readLE32(selectedIn);\n                size_t const nextCBlockSize = blockHeader & 0x7FFFFFFFU;\n                size_t const crcSize = dctx->frameInfo.blockChecksumFlag * BFSize;\n                if (blockHeader==0) {  /* frameEnd signal, no more block */\n                    DEBUGLOG(5, \"end of frame\");\n                    dctx->dStage = dstage_getSuffix;\n                    break;\n                }\n                if (nextCBlockSize > dctx->maxBlockSize) {\n                    return err0r(LZ4F_ERROR_maxBlockSize_invalid);\n                }\n                if (blockHeader & LZ4F_BLOCKUNCOMPRESSED_FLAG) {\n                    /* next block is uncompressed */\n                    dctx->tmpInTarget = nextCBlockSize;\n                    DEBUGLOG(5, \"next block is uncompressed (size %u)\", (U32)nextCBlockSize);\n                    if (dctx->frameInfo.blockChecksumFlag) {\n                        (void)XXH32_reset(&dctx->blockChecksum, 0);\n                    }\n                    dctx->dStage = dstage_copyDirect;\n                    break;\n                }\n                /* next block is a compressed block */\n                dctx->tmpInTarget = nextCBlockSize + crcSize;\n                dctx->dStage = dstage_getCBlock;\n                if (dstPtr==dstEnd || srcPtr==srcEnd) {\n                    nextSrcSizeHint = BHSize + nextCBlockSize + crcSize;\n                    doAnotherStage = 0;\n                }\n                break;\n            }\n\n        case dstage_copyDirect:   /* uncompressed block */\n            DEBUGLOG(6, \"dstage_copyDirect\");\n            {   size_t sizeToCopy;\n                if (dstPtr == NULL) {\n                    sizeToCopy = 0;\n                } else {\n                    size_t const minBuffSize = MIN((size_t)(srcEnd-srcPtr), (size_t)(dstEnd-dstPtr));\n                    sizeToCopy = MIN(dctx->tmpInTarget, minBuffSize);\n                    memcpy(dstPtr, srcPtr, sizeToCopy);\n                    if (dctx->frameInfo.blockChecksumFlag) {\n                        (void)XXH32_update(&dctx->blockChecksum, srcPtr, sizeToCopy);\n                    }\n                    if (dctx->frameInfo.contentChecksumFlag)\n                        (void)XXH32_update(&dctx->xxh, srcPtr, sizeToCopy);\n                    if (dctx->frameInfo.contentSize)\n                        dctx->frameRemainingSize -= sizeToCopy;\n\n                    /* history management (linked blocks only)*/\n                    if (dctx->frameInfo.blockMode == LZ4F_blockLinked) {\n                        LZ4F_updateDict(dctx, dstPtr, sizeToCopy, dstStart, 0);\n                }   }\n\n                srcPtr += sizeToCopy;\n                dstPtr += sizeToCopy;\n                if (sizeToCopy == dctx->tmpInTarget) {   /* all done */\n                    if (dctx->frameInfo.blockChecksumFlag) {\n                        dctx->tmpInSize = 0;\n                        dctx->dStage = dstage_getBlockChecksum;\n                    } else\n                        dctx->dStage = dstage_getBlockHeader;  /* new block */\n                    break;\n                }\n                dctx->tmpInTarget -= sizeToCopy;  /* need to copy more */\n            }\n            nextSrcSizeHint = dctx->tmpInTarget +\n                            +(dctx->frameInfo.blockChecksumFlag ? BFSize : 0)\n                            + BHSize /* next header size */;\n            doAnotherStage = 0;\n            break;\n\n        /* check block checksum for recently transferred uncompressed block */\n        case dstage_getBlockChecksum:\n            DEBUGLOG(6, \"dstage_getBlockChecksum\");\n            {   const void* crcSrc;\n                if ((srcEnd-srcPtr >= 4) && (dctx->tmpInSize==0)) {\n                    crcSrc = srcPtr;\n                    srcPtr += 4;\n                } else {\n                    size_t const stillToCopy = 4 - dctx->tmpInSize;\n                    size_t const sizeToCopy = MIN(stillToCopy, (size_t)(srcEnd-srcPtr));\n                    memcpy(dctx->header + dctx->tmpInSize, srcPtr, sizeToCopy);\n                    dctx->tmpInSize += sizeToCopy;\n                    srcPtr += sizeToCopy;\n                    if (dctx->tmpInSize < 4) {  /* all input consumed */\n                        doAnotherStage = 0;\n                        break;\n                    }\n                    crcSrc = dctx->header;\n                }\n                {   U32 const readCRC = LZ4F_readLE32(crcSrc);\n                    U32 const calcCRC = XXH32_digest(&dctx->blockChecksum);\n#ifndef FUZZING_BUILD_MODE_UNSAFE_FOR_PRODUCTION\n                    DEBUGLOG(6, \"compare block checksum\");\n                    if (readCRC != calcCRC) {\n                        DEBUGLOG(4, \"incorrect block checksum: %08X != %08X\",\n                                readCRC, calcCRC);\n                        return err0r(LZ4F_ERROR_blockChecksum_invalid);\n                    }\n#else\n                    (void)readCRC;\n                    (void)calcCRC;\n#endif\n            }   }\n            dctx->dStage = dstage_getBlockHeader;  /* new block */\n            break;\n\n        case dstage_getCBlock:\n            DEBUGLOG(6, \"dstage_getCBlock\");\n            if ((size_t)(srcEnd-srcPtr) < dctx->tmpInTarget) {\n                dctx->tmpInSize = 0;\n                dctx->dStage = dstage_storeCBlock;\n                break;\n            }\n            /* input large enough to read full block directly */\n            selectedIn = srcPtr;\n            srcPtr += dctx->tmpInTarget;\n\n            if (0)  /* always jump over next block */\n        case dstage_storeCBlock:\n            {   size_t const wantedData = dctx->tmpInTarget - dctx->tmpInSize;\n                size_t const inputLeft = (size_t)(srcEnd-srcPtr);\n                size_t const sizeToCopy = MIN(wantedData, inputLeft);\n                memcpy(dctx->tmpIn + dctx->tmpInSize, srcPtr, sizeToCopy);\n                dctx->tmpInSize += sizeToCopy;\n                srcPtr += sizeToCopy;\n                if (dctx->tmpInSize < dctx->tmpInTarget) { /* need more input */\n                    nextSrcSizeHint = (dctx->tmpInTarget - dctx->tmpInSize)\n                                    + (dctx->frameInfo.blockChecksumFlag ? BFSize : 0)\n                                    + BHSize /* next header size */;\n                    doAnotherStage = 0;\n                    break;\n                }\n                selectedIn = dctx->tmpIn;\n            }\n\n            /* At this stage, input is large enough to decode a block */\n            if (dctx->frameInfo.blockChecksumFlag) {\n                dctx->tmpInTarget -= 4;\n                assert(selectedIn != NULL);  /* selectedIn is defined at this stage (either srcPtr, or dctx->tmpIn) */\n                {   U32 const readBlockCrc = LZ4F_readLE32(selectedIn + dctx->tmpInTarget);\n                    U32 const calcBlockCrc = XXH32(selectedIn, dctx->tmpInTarget, 0);\n#ifndef FUZZING_BUILD_MODE_UNSAFE_FOR_PRODUCTION\n                    if (readBlockCrc != calcBlockCrc)\n                        return err0r(LZ4F_ERROR_blockChecksum_invalid);\n#else\n                    (void)readBlockCrc;\n                    (void)calcBlockCrc;\n#endif\n            }   }\n\n            if ((size_t)(dstEnd-dstPtr) >= dctx->maxBlockSize) {\n                const char* dict = (const char*)dctx->dict;\n                size_t dictSize = dctx->dictSize;\n                int decodedSize;\n                assert(dstPtr != NULL);\n                if (dict && dictSize > 1 GB) {\n                    /* the dictSize param is an int, avoid truncation / sign issues */\n                    dict += dictSize - 64 KB;\n                    dictSize = 64 KB;\n                }\n                /* enough capacity in `dst` to decompress directly there */\n                decodedSize = LZ4_decompress_safe_usingDict(\n                        (const char*)selectedIn, (char*)dstPtr,\n                        (int)dctx->tmpInTarget, (int)dctx->maxBlockSize,\n                        dict, (int)dictSize);\n                if (decodedSize < 0) return err0r(LZ4F_ERROR_GENERIC);   /* decompression failed */\n                if (dctx->frameInfo.contentChecksumFlag)\n                    XXH32_update(&(dctx->xxh), dstPtr, (size_t)decodedSize);\n                if (dctx->frameInfo.contentSize)\n                    dctx->frameRemainingSize -= (size_t)decodedSize;\n\n                /* dictionary management */\n                if (dctx->frameInfo.blockMode==LZ4F_blockLinked) {\n                    LZ4F_updateDict(dctx, dstPtr, (size_t)decodedSize, dstStart, 0);\n                }\n\n                dstPtr += decodedSize;\n                dctx->dStage = dstage_getBlockHeader;\n                break;\n            }\n\n            /* not enough place into dst : decode into tmpOut */\n            /* ensure enough place for tmpOut */\n            if (dctx->frameInfo.blockMode == LZ4F_blockLinked) {\n                if (dctx->dict == dctx->tmpOutBuffer) {\n                    if (dctx->dictSize > 128 KB) {\n                        memcpy(dctx->tmpOutBuffer, dctx->dict + dctx->dictSize - 64 KB, 64 KB);\n                        dctx->dictSize = 64 KB;\n                    }\n                    dctx->tmpOut = dctx->tmpOutBuffer + dctx->dictSize;\n                } else {  /* dict not within tmp */\n                    size_t const reservedDictSpace = MIN(dctx->dictSize, 64 KB);\n                    dctx->tmpOut = dctx->tmpOutBuffer + reservedDictSpace;\n            }   }\n\n            /* Decode block */\n            {   const char* dict = (const char*)dctx->dict;\n                size_t dictSize = dctx->dictSize;\n                int decodedSize;\n                if (dict && dictSize > 1 GB) {\n                    /* the dictSize param is an int, avoid truncation / sign issues */\n                    dict += dictSize - 64 KB;\n                    dictSize = 64 KB;\n                }\n                decodedSize = LZ4_decompress_safe_usingDict(\n                        (const char*)selectedIn, (char*)dctx->tmpOut,\n                        (int)dctx->tmpInTarget, (int)dctx->maxBlockSize,\n                        dict, (int)dictSize);\n                if (decodedSize < 0)  /* decompression failed */\n                    return err0r(LZ4F_ERROR_decompressionFailed);\n                if (dctx->frameInfo.contentChecksumFlag)\n                    XXH32_update(&(dctx->xxh), dctx->tmpOut, (size_t)decodedSize);\n                if (dctx->frameInfo.contentSize)\n                    dctx->frameRemainingSize -= (size_t)decodedSize;\n                dctx->tmpOutSize = (size_t)decodedSize;\n                dctx->tmpOutStart = 0;\n                dctx->dStage = dstage_flushOut;\n            }\n            /* fall-through */\n\n        case dstage_flushOut:  /* flush decoded data from tmpOut to dstBuffer */\n            DEBUGLOG(6, \"dstage_flushOut\");\n            if (dstPtr != NULL) {\n                size_t const sizeToCopy = MIN(dctx->tmpOutSize - dctx->tmpOutStart, (size_t)(dstEnd-dstPtr));\n                memcpy(dstPtr, dctx->tmpOut + dctx->tmpOutStart, sizeToCopy);\n\n                /* dictionary management */\n                if (dctx->frameInfo.blockMode == LZ4F_blockLinked)\n                    LZ4F_updateDict(dctx, dstPtr, sizeToCopy, dstStart, 1 /*withinTmp*/);\n\n                dctx->tmpOutStart += sizeToCopy;\n                dstPtr += sizeToCopy;\n            }\n            if (dctx->tmpOutStart == dctx->tmpOutSize) { /* all flushed */\n                dctx->dStage = dstage_getBlockHeader;  /* get next block */\n                break;\n            }\n            /* could not flush everything : stop there, just request a block header */\n            doAnotherStage = 0;\n            nextSrcSizeHint = BHSize;\n            break;\n\n        case dstage_getSuffix:\n            if (dctx->frameRemainingSize)\n                return err0r(LZ4F_ERROR_frameSize_wrong);   /* incorrect frame size decoded */\n            if (!dctx->frameInfo.contentChecksumFlag) {  /* no checksum, frame is completed */\n                nextSrcSizeHint = 0;\n                LZ4F_resetDecompressionContext(dctx);\n                doAnotherStage = 0;\n                break;\n            }\n            if ((srcEnd - srcPtr) < 4) {  /* not enough size for entire CRC */\n                dctx->tmpInSize = 0;\n                dctx->dStage = dstage_storeSuffix;\n            } else {\n                selectedIn = srcPtr;\n                srcPtr += 4;\n            }\n\n            if (dctx->dStage == dstage_storeSuffix)   /* can be skipped */\n        case dstage_storeSuffix:\n            {   size_t const remainingInput = (size_t)(srcEnd - srcPtr);\n                size_t const wantedData = 4 - dctx->tmpInSize;\n                size_t const sizeToCopy = MIN(wantedData, remainingInput);\n                memcpy(dctx->tmpIn + dctx->tmpInSize, srcPtr, sizeToCopy);\n                srcPtr += sizeToCopy;\n                dctx->tmpInSize += sizeToCopy;\n                if (dctx->tmpInSize < 4) { /* not enough input to read complete suffix */\n                    nextSrcSizeHint = 4 - dctx->tmpInSize;\n                    doAnotherStage=0;\n                    break;\n                }\n                selectedIn = dctx->tmpIn;\n            }   /* if (dctx->dStage == dstage_storeSuffix) */\n\n        /* case dstage_checkSuffix: */   /* no direct entry, avoid initialization risks */\n            {   U32 const readCRC = LZ4F_readLE32(selectedIn);\n                U32 const resultCRC = XXH32_digest(&(dctx->xxh));\n#ifndef FUZZING_BUILD_MODE_UNSAFE_FOR_PRODUCTION\n                if (readCRC != resultCRC)\n                    return err0r(LZ4F_ERROR_contentChecksum_invalid);\n#else\n                (void)readCRC;\n                (void)resultCRC;\n#endif\n                nextSrcSizeHint = 0;\n                LZ4F_resetDecompressionContext(dctx);\n                doAnotherStage = 0;\n                break;\n            }\n\n        case dstage_getSFrameSize:\n            if ((srcEnd - srcPtr) >= 4) {\n                selectedIn = srcPtr;\n                srcPtr += 4;\n            } else {\n                /* not enough input to read cBlockSize field */\n                dctx->tmpInSize = 4;\n                dctx->tmpInTarget = 8;\n                dctx->dStage = dstage_storeSFrameSize;\n            }\n\n            if (dctx->dStage == dstage_storeSFrameSize)\n        case dstage_storeSFrameSize:\n            {   size_t const sizeToCopy = MIN(dctx->tmpInTarget - dctx->tmpInSize,\n                                             (size_t)(srcEnd - srcPtr) );\n                memcpy(dctx->header + dctx->tmpInSize, srcPtr, sizeToCopy);\n                srcPtr += sizeToCopy;\n                dctx->tmpInSize += sizeToCopy;\n                if (dctx->tmpInSize < dctx->tmpInTarget) {\n                    /* not enough input to get full sBlockSize; wait for more */\n                    nextSrcSizeHint = dctx->tmpInTarget - dctx->tmpInSize;\n                    doAnotherStage = 0;\n                    break;\n                }\n                selectedIn = dctx->header + 4;\n            }   /* if (dctx->dStage == dstage_storeSFrameSize) */\n\n        /* case dstage_decodeSFrameSize: */   /* no direct entry */\n            {   size_t const SFrameSize = LZ4F_readLE32(selectedIn);\n                dctx->frameInfo.contentSize = SFrameSize;\n                dctx->tmpInTarget = SFrameSize;\n                dctx->dStage = dstage_skipSkippable;\n                break;\n            }\n\n        case dstage_skipSkippable:\n            {   size_t const skipSize = MIN(dctx->tmpInTarget, (size_t)(srcEnd-srcPtr));\n                srcPtr += skipSize;\n                dctx->tmpInTarget -= skipSize;\n                doAnotherStage = 0;\n                nextSrcSizeHint = dctx->tmpInTarget;\n                if (nextSrcSizeHint) break;  /* still more to skip */\n                /* frame fully skipped : prepare context for a new frame */\n                LZ4F_resetDecompressionContext(dctx);\n                break;\n            }\n        }   /* switch (dctx->dStage) */\n    }   /* while (doAnotherStage) */\n\n    /* preserve history within tmp whenever necessary */\n    LZ4F_STATIC_ASSERT((unsigned)dstage_init == 2);\n    if ( (dctx->frameInfo.blockMode==LZ4F_blockLinked)  /* next block will use up to 64KB from previous ones */\n      && (dctx->dict != dctx->tmpOutBuffer)             /* dictionary is not already within tmp */\n      && (dctx->dict != NULL)                           /* dictionary exists */\n      && (!decompressOptionsPtr->stableDst)             /* cannot rely on dst data to remain there for next call */\n      && ((unsigned)(dctx->dStage)-2 < (unsigned)(dstage_getSuffix)-2) )  /* valid stages : [init ... getSuffix[ */\n    {\n        if (dctx->dStage == dstage_flushOut) {\n            size_t const preserveSize = (size_t)(dctx->tmpOut - dctx->tmpOutBuffer);\n            size_t copySize = 64 KB - dctx->tmpOutSize;\n            const BYTE* oldDictEnd = dctx->dict + dctx->dictSize - dctx->tmpOutStart;\n            if (dctx->tmpOutSize > 64 KB) copySize = 0;\n            if (copySize > preserveSize) copySize = preserveSize;\n            assert(dctx->tmpOutBuffer != NULL);\n\n            memcpy(dctx->tmpOutBuffer + preserveSize - copySize, oldDictEnd - copySize, copySize);\n\n            dctx->dict = dctx->tmpOutBuffer;\n            dctx->dictSize = preserveSize + dctx->tmpOutStart;\n        } else {\n            const BYTE* const oldDictEnd = dctx->dict + dctx->dictSize;\n            size_t const newDictSize = MIN(dctx->dictSize, 64 KB);\n\n            memcpy(dctx->tmpOutBuffer, oldDictEnd - newDictSize, newDictSize);\n\n            dctx->dict = dctx->tmpOutBuffer;\n            dctx->dictSize = newDictSize;\n            dctx->tmpOut = dctx->tmpOutBuffer + newDictSize;\n        }\n    }\n\n    *srcSizePtr = (size_t)(srcPtr - srcStart);\n    *dstSizePtr = (size_t)(dstPtr - dstStart);\n    return nextSrcSizeHint;\n}\n\n/*! LZ4F_decompress_usingDict() :\n *  Same as LZ4F_decompress(), using a predefined dictionary.\n *  Dictionary is used \"in place\", without any preprocessing.\n *  It must remain accessible throughout the entire frame decoding.\n */\nsize_t LZ4F_decompress_usingDict(LZ4F_dctx* dctx,\n                       void* dstBuffer, size_t* dstSizePtr,\n                       const void* srcBuffer, size_t* srcSizePtr,\n                       const void* dict, size_t dictSize,\n                       const LZ4F_decompressOptions_t* decompressOptionsPtr)\n{\n    if (dctx->dStage <= dstage_init) {\n        dctx->dict = (const BYTE*)dict;\n        dctx->dictSize = dictSize;\n    }\n    return LZ4F_decompress(dctx, dstBuffer, dstSizePtr,\n                           srcBuffer, srcSizePtr,\n                           decompressOptionsPtr);\n}\n"
  },
  {
    "path": "external/lz4/lz4frame.h",
    "content": "/*\n   LZ4 auto-framing library\n   Header File\n   Copyright (C) 2011-2017, Yann Collet.\n   BSD 2-Clause License (http://www.opensource.org/licenses/bsd-license.php)\n\n   Redistribution and use in source and binary forms, with or without\n   modification, are permitted provided that the following conditions are\n   met:\n\n       * Redistributions of source code must retain the above copyright\n   notice, this list of conditions and the following disclaimer.\n       * Redistributions in binary form must reproduce the above\n   copyright notice, this list of conditions and the following disclaimer\n   in the documentation and/or other materials provided with the\n   distribution.\n\n   THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\n   \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\n   LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR\n   A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT\n   OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,\n   SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT\n   LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,\n   DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY\n   THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\n   (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE\n   OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n\n   You can contact the author at :\n   - LZ4 source repository : https://github.com/lz4/lz4\n   - LZ4 public forum : https://groups.google.com/forum/#!forum/lz4c\n*/\n\n/* LZ4F is a stand-alone API able to create and decode LZ4 frames\n * conformant with specification v1.6.1 in doc/lz4_Frame_format.md .\n * Generated frames are compatible with `lz4` CLI.\n *\n * LZ4F also offers streaming capabilities.\n *\n * lz4.h is not required when using lz4frame.h,\n * except to extract common constant such as LZ4_VERSION_NUMBER.\n * */\n\n#ifndef LZ4F_H_09782039843\n#define LZ4F_H_09782039843\n\n#if defined (__cplusplus)\nextern \"C\" {\n#endif\n\n/* ---   Dependency   --- */\n#include <stddef.h>   /* size_t */\n\n\n/**\n  Introduction\n\n  lz4frame.h implements LZ4 frame specification (doc/lz4_Frame_format.md).\n  lz4frame.h provides frame compression functions that take care\n  of encoding standard metadata alongside LZ4-compressed blocks.\n*/\n\n/*-***************************************************************\n *  Compiler specifics\n *****************************************************************/\n/*  LZ4_DLL_EXPORT :\n *  Enable exporting of functions when building a Windows DLL\n *  LZ4FLIB_VISIBILITY :\n *  Control library symbols visibility.\n */\n#ifndef LZ4FLIB_VISIBILITY\n#  if defined(__GNUC__) && (__GNUC__ >= 4)\n#    define LZ4FLIB_VISIBILITY __attribute__ ((visibility (\"default\")))\n#  else\n#    define LZ4FLIB_VISIBILITY\n#  endif\n#endif\n#if defined(LZ4_DLL_EXPORT) && (LZ4_DLL_EXPORT==1)\n#  define LZ4FLIB_API __declspec(dllexport) LZ4FLIB_VISIBILITY\n#elif defined(LZ4_DLL_IMPORT) && (LZ4_DLL_IMPORT==1)\n#  define LZ4FLIB_API __declspec(dllimport) LZ4FLIB_VISIBILITY\n#else\n#  define LZ4FLIB_API LZ4FLIB_VISIBILITY\n#endif\n\n#ifdef LZ4F_DISABLE_DEPRECATE_WARNINGS\n#  define LZ4F_DEPRECATE(x) x\n#else\n#  if defined(_MSC_VER)\n#    define LZ4F_DEPRECATE(x) x   /* __declspec(deprecated) x - only works with C++ */\n#  elif defined(__clang__) || (defined(__GNUC__) && (__GNUC__ >= 6))\n#    define LZ4F_DEPRECATE(x) x __attribute__((deprecated))\n#  else\n#    define LZ4F_DEPRECATE(x) x   /* no deprecation warning for this compiler */\n#  endif\n#endif\n\n\n/*-************************************\n *  Error management\n **************************************/\ntypedef size_t LZ4F_errorCode_t;\n\nLZ4FLIB_API unsigned    LZ4F_isError(LZ4F_errorCode_t code);   /**< tells when a function result is an error code */\nLZ4FLIB_API const char* LZ4F_getErrorName(LZ4F_errorCode_t code);   /**< return error code string; for debugging */\n\n\n/*-************************************\n *  Frame compression types\n ************************************* */\n/* #define LZ4F_ENABLE_OBSOLETE_ENUMS   // uncomment to enable obsolete enums */\n#ifdef LZ4F_ENABLE_OBSOLETE_ENUMS\n#  define LZ4F_OBSOLETE_ENUM(x) , LZ4F_DEPRECATE(x) = LZ4F_##x\n#else\n#  define LZ4F_OBSOLETE_ENUM(x)\n#endif\n\n/* The larger the block size, the (slightly) better the compression ratio,\n * though there are diminishing returns.\n * Larger blocks also increase memory usage on both compression and decompression sides.\n */\ntypedef enum {\n    LZ4F_default=0,\n    LZ4F_max64KB=4,\n    LZ4F_max256KB=5,\n    LZ4F_max1MB=6,\n    LZ4F_max4MB=7\n    LZ4F_OBSOLETE_ENUM(max64KB)\n    LZ4F_OBSOLETE_ENUM(max256KB)\n    LZ4F_OBSOLETE_ENUM(max1MB)\n    LZ4F_OBSOLETE_ENUM(max4MB)\n} LZ4F_blockSizeID_t;\n\n/* Linked blocks sharply reduce inefficiencies when using small blocks,\n * they compress better.\n * However, some LZ4 decoders are only compatible with independent blocks */\ntypedef enum {\n    LZ4F_blockLinked=0,\n    LZ4F_blockIndependent\n    LZ4F_OBSOLETE_ENUM(blockLinked)\n    LZ4F_OBSOLETE_ENUM(blockIndependent)\n} LZ4F_blockMode_t;\n\ntypedef enum {\n    LZ4F_noContentChecksum=0,\n    LZ4F_contentChecksumEnabled\n    LZ4F_OBSOLETE_ENUM(noContentChecksum)\n    LZ4F_OBSOLETE_ENUM(contentChecksumEnabled)\n} LZ4F_contentChecksum_t;\n\ntypedef enum {\n    LZ4F_noBlockChecksum=0,\n    LZ4F_blockChecksumEnabled\n} LZ4F_blockChecksum_t;\n\ntypedef enum {\n    LZ4F_frame=0,\n    LZ4F_skippableFrame\n    LZ4F_OBSOLETE_ENUM(skippableFrame)\n} LZ4F_frameType_t;\n\n#ifdef LZ4F_ENABLE_OBSOLETE_ENUMS\ntypedef LZ4F_blockSizeID_t blockSizeID_t;\ntypedef LZ4F_blockMode_t blockMode_t;\ntypedef LZ4F_frameType_t frameType_t;\ntypedef LZ4F_contentChecksum_t contentChecksum_t;\n#endif\n\n/*! LZ4F_frameInfo_t :\n *  makes it possible to set or read frame parameters.\n *  Structure must be first init to 0, using memset() or LZ4F_INIT_FRAMEINFO,\n *  setting all parameters to default.\n *  It's then possible to update selectively some parameters */\ntypedef struct {\n  LZ4F_blockSizeID_t     blockSizeID;         /* max64KB, max256KB, max1MB, max4MB; 0 == default */\n  LZ4F_blockMode_t       blockMode;           /* LZ4F_blockLinked, LZ4F_blockIndependent; 0 == default */\n  LZ4F_contentChecksum_t contentChecksumFlag; /* 1: frame terminated with 32-bit checksum of decompressed data; 0: disabled (default) */\n  LZ4F_frameType_t       frameType;           /* read-only field : LZ4F_frame or LZ4F_skippableFrame */\n  unsigned long long     contentSize;         /* Size of uncompressed content ; 0 == unknown */\n  unsigned               dictID;              /* Dictionary ID, sent by compressor to help decoder select correct dictionary; 0 == no dictID provided */\n  LZ4F_blockChecksum_t   blockChecksumFlag;   /* 1: each block followed by a checksum of block's compressed data; 0: disabled (default) */\n} LZ4F_frameInfo_t;\n\n#define LZ4F_INIT_FRAMEINFO   { LZ4F_default, LZ4F_blockLinked, LZ4F_noContentChecksum, LZ4F_frame, 0ULL, 0U, LZ4F_noBlockChecksum }    /* v1.8.3+ */\n\n/*! LZ4F_preferences_t :\n *  makes it possible to supply advanced compression instructions to streaming interface.\n *  Structure must be first init to 0, using memset() or LZ4F_INIT_PREFERENCES,\n *  setting all parameters to default.\n *  All reserved fields must be set to zero. */\ntypedef struct {\n  LZ4F_frameInfo_t frameInfo;\n  int      compressionLevel;    /* 0: default (fast mode); values > LZ4HC_CLEVEL_MAX count as LZ4HC_CLEVEL_MAX; values < 0 trigger \"fast acceleration\" */\n  unsigned autoFlush;           /* 1: always flush; reduces usage of internal buffers */\n  unsigned favorDecSpeed;       /* 1: parser favors decompression speed vs compression ratio. Only works for high compression modes (>= LZ4HC_CLEVEL_OPT_MIN) */  /* v1.8.2+ */\n  unsigned reserved[3];         /* must be zero for forward compatibility */\n} LZ4F_preferences_t;\n\n#define LZ4F_INIT_PREFERENCES   { LZ4F_INIT_FRAMEINFO, 0, 0u, 0u, { 0u, 0u, 0u } }    /* v1.8.3+ */\n\n\n/*-*********************************\n*  Simple compression function\n***********************************/\n\nLZ4FLIB_API int LZ4F_compressionLevel_max(void);   /* v1.8.0+ */\n\n/*! LZ4F_compressFrameBound() :\n *  Returns the maximum possible compressed size with LZ4F_compressFrame() given srcSize and preferences.\n * `preferencesPtr` is optional. It can be replaced by NULL, in which case, the function will assume default preferences.\n *  Note : this result is only usable with LZ4F_compressFrame().\n *         It may also be used with LZ4F_compressUpdate() _if no flush() operation_ is performed.\n */\nLZ4FLIB_API size_t LZ4F_compressFrameBound(size_t srcSize, const LZ4F_preferences_t* preferencesPtr);\n\n/*! LZ4F_compressFrame() :\n *  Compress an entire srcBuffer into a valid LZ4 frame.\n *  dstCapacity MUST be >= LZ4F_compressFrameBound(srcSize, preferencesPtr).\n *  The LZ4F_preferences_t structure is optional : you can provide NULL as argument. All preferences will be set to default.\n * @return : number of bytes written into dstBuffer.\n *           or an error code if it fails (can be tested using LZ4F_isError())\n */\nLZ4FLIB_API size_t LZ4F_compressFrame(void* dstBuffer, size_t dstCapacity,\n                                const void* srcBuffer, size_t srcSize,\n                                const LZ4F_preferences_t* preferencesPtr);\n\n\n/*-***********************************\n*  Advanced compression functions\n*************************************/\ntypedef struct LZ4F_cctx_s LZ4F_cctx;   /* incomplete type */\ntypedef LZ4F_cctx* LZ4F_compressionContext_t;   /* for compatibility with previous API version */\n\ntypedef struct {\n  unsigned stableSrc;    /* 1 == src content will remain present on future calls to LZ4F_compress(); skip copying src content within tmp buffer */\n  unsigned reserved[3];\n} LZ4F_compressOptions_t;\n\n/*---   Resource Management   ---*/\n\n#define LZ4F_VERSION 100    /* This number can be used to check for an incompatible API breaking change */\nLZ4FLIB_API unsigned LZ4F_getVersion(void);\n\n/*! LZ4F_createCompressionContext() :\n * The first thing to do is to create a compressionContext object, which will be used in all compression operations.\n * This is achieved using LZ4F_createCompressionContext(), which takes as argument a version.\n * The version provided MUST be LZ4F_VERSION. It is intended to track potential version mismatch, notably when using DLL.\n * The function will provide a pointer to a fully allocated LZ4F_cctx object.\n * If @return != zero, there was an error during context creation.\n * Object can release its memory using LZ4F_freeCompressionContext();\n */\nLZ4FLIB_API LZ4F_errorCode_t LZ4F_createCompressionContext(LZ4F_cctx** cctxPtr, unsigned version);\nLZ4FLIB_API LZ4F_errorCode_t LZ4F_freeCompressionContext(LZ4F_cctx* cctx);\n\n\n/*----    Compression    ----*/\n\n#define LZ4F_HEADER_SIZE_MIN  7   /* LZ4 Frame header size can vary, depending on selected paramaters */\n#define LZ4F_HEADER_SIZE_MAX 19\n\n/* Size in bytes of a block header in little-endian format. Highest bit indicates if block data is uncompressed */\n#define LZ4F_BLOCK_HEADER_SIZE 4\n\n/* Size in bytes of a block checksum footer in little-endian format. */\n#define LZ4F_BLOCK_CHECKSUM_SIZE 4\n\n/* Size in bytes of the content checksum. */\n#define LZ4F_CONTENT_CHECKSUM_SIZE 4\n\n/*! LZ4F_compressBegin() :\n *  will write the frame header into dstBuffer.\n *  dstCapacity must be >= LZ4F_HEADER_SIZE_MAX bytes.\n * `prefsPtr` is optional : you can provide NULL as argument, all preferences will then be set to default.\n * @return : number of bytes written into dstBuffer for the header\n *           or an error code (which can be tested using LZ4F_isError())\n */\nLZ4FLIB_API size_t LZ4F_compressBegin(LZ4F_cctx* cctx,\n                                      void* dstBuffer, size_t dstCapacity,\n                                      const LZ4F_preferences_t* prefsPtr);\n\n/*! LZ4F_compressBound() :\n *  Provides minimum dstCapacity required to guarantee success of\n *  LZ4F_compressUpdate(), given a srcSize and preferences, for a worst case scenario.\n *  When srcSize==0, LZ4F_compressBound() provides an upper bound for LZ4F_flush() and LZ4F_compressEnd() instead.\n *  Note that the result is only valid for a single invocation of LZ4F_compressUpdate().\n *  When invoking LZ4F_compressUpdate() multiple times,\n *  if the output buffer is gradually filled up instead of emptied and re-used from its start,\n *  one must check if there is enough remaining capacity before each invocation, using LZ4F_compressBound().\n * @return is always the same for a srcSize and prefsPtr.\n *  prefsPtr is optional : when NULL is provided, preferences will be set to cover worst case scenario.\n *  tech details :\n * @return if automatic flushing is not enabled, includes the possibility that internal buffer might already be filled by up to (blockSize-1) bytes.\n *  It also includes frame footer (ending + checksum), since it might be generated by LZ4F_compressEnd().\n * @return doesn't include frame header, as it was already generated by LZ4F_compressBegin().\n */\nLZ4FLIB_API size_t LZ4F_compressBound(size_t srcSize, const LZ4F_preferences_t* prefsPtr);\n\n/*! LZ4F_compressUpdate() :\n *  LZ4F_compressUpdate() can be called repetitively to compress as much data as necessary.\n *  Important rule: dstCapacity MUST be large enough to ensure operation success even in worst case situations.\n *  This value is provided by LZ4F_compressBound().\n *  If this condition is not respected, LZ4F_compress() will fail (result is an errorCode).\n *  LZ4F_compressUpdate() doesn't guarantee error recovery.\n *  When an error occurs, compression context must be freed or resized.\n * `cOptPtr` is optional : NULL can be provided, in which case all options are set to default.\n * @return : number of bytes written into `dstBuffer` (it can be zero, meaning input data was just buffered).\n *           or an error code if it fails (which can be tested using LZ4F_isError())\n */\nLZ4FLIB_API size_t LZ4F_compressUpdate(LZ4F_cctx* cctx,\n                                       void* dstBuffer, size_t dstCapacity,\n                                 const void* srcBuffer, size_t srcSize,\n                                 const LZ4F_compressOptions_t* cOptPtr);\n\n/*! LZ4F_flush() :\n *  When data must be generated and sent immediately, without waiting for a block to be completely filled,\n *  it's possible to call LZ4_flush(). It will immediately compress any data buffered within cctx.\n * `dstCapacity` must be large enough to ensure the operation will be successful.\n * `cOptPtr` is optional : it's possible to provide NULL, all options will be set to default.\n * @return : nb of bytes written into dstBuffer (can be zero, when there is no data stored within cctx)\n *           or an error code if it fails (which can be tested using LZ4F_isError())\n *  Note : LZ4F_flush() is guaranteed to be successful when dstCapacity >= LZ4F_compressBound(0, prefsPtr).\n */\nLZ4FLIB_API size_t LZ4F_flush(LZ4F_cctx* cctx,\n                              void* dstBuffer, size_t dstCapacity,\n                        const LZ4F_compressOptions_t* cOptPtr);\n\n/*! LZ4F_compressEnd() :\n *  To properly finish an LZ4 frame, invoke LZ4F_compressEnd().\n *  It will flush whatever data remained within `cctx` (like LZ4_flush())\n *  and properly finalize the frame, with an endMark and a checksum.\n * `cOptPtr` is optional : NULL can be provided, in which case all options will be set to default.\n * @return : nb of bytes written into dstBuffer, necessarily >= 4 (endMark),\n *           or an error code if it fails (which can be tested using LZ4F_isError())\n *  Note : LZ4F_compressEnd() is guaranteed to be successful when dstCapacity >= LZ4F_compressBound(0, prefsPtr).\n *  A successful call to LZ4F_compressEnd() makes `cctx` available again for another compression task.\n */\nLZ4FLIB_API size_t LZ4F_compressEnd(LZ4F_cctx* cctx,\n                                    void* dstBuffer, size_t dstCapacity,\n                              const LZ4F_compressOptions_t* cOptPtr);\n\n\n/*-*********************************\n*  Decompression functions\n***********************************/\ntypedef struct LZ4F_dctx_s LZ4F_dctx;   /* incomplete type */\ntypedef LZ4F_dctx* LZ4F_decompressionContext_t;   /* compatibility with previous API versions */\n\ntypedef struct {\n  unsigned stableDst;    /* pledges that last 64KB decompressed data will remain available unmodified. This optimization skips storage operations in tmp buffers. */\n  unsigned reserved[3];  /* must be set to zero for forward compatibility */\n} LZ4F_decompressOptions_t;\n\n\n/* Resource management */\n\n/*! LZ4F_createDecompressionContext() :\n *  Create an LZ4F_dctx object, to track all decompression operations.\n *  The version provided MUST be LZ4F_VERSION.\n *  The function provides a pointer to an allocated and initialized LZ4F_dctx object.\n *  The result is an errorCode, which can be tested using LZ4F_isError().\n *  dctx memory can be released using LZ4F_freeDecompressionContext();\n *  Result of LZ4F_freeDecompressionContext() indicates current state of decompressionContext when being released.\n *  That is, it should be == 0 if decompression has been completed fully and correctly.\n */\nLZ4FLIB_API LZ4F_errorCode_t LZ4F_createDecompressionContext(LZ4F_dctx** dctxPtr, unsigned version);\nLZ4FLIB_API LZ4F_errorCode_t LZ4F_freeDecompressionContext(LZ4F_dctx* dctx);\n\n\n/*-***********************************\n*  Streaming decompression functions\n*************************************/\n\n#define LZ4F_MIN_SIZE_TO_KNOW_HEADER_LENGTH 5\n\n/*! LZ4F_headerSize() : v1.9.0+\n *  Provide the header size of a frame starting at `src`.\n * `srcSize` must be >= LZ4F_MIN_SIZE_TO_KNOW_HEADER_LENGTH,\n *  which is enough to decode the header length.\n * @return : size of frame header\n *           or an error code, which can be tested using LZ4F_isError()\n *  note : Frame header size is variable, but is guaranteed to be\n *         >= LZ4F_HEADER_SIZE_MIN bytes, and <= LZ4F_HEADER_SIZE_MAX bytes.\n */\nLZ4FLIB_API size_t LZ4F_headerSize(const void* src, size_t srcSize);\n\n/*! LZ4F_getFrameInfo() :\n *  This function extracts frame parameters (max blockSize, dictID, etc.).\n *  Its usage is optional: user can call LZ4F_decompress() directly.\n *\n *  Extracted information will fill an existing LZ4F_frameInfo_t structure.\n *  This can be useful for allocation and dictionary identification purposes.\n *\n *  LZ4F_getFrameInfo() can work in the following situations :\n *\n *  1) At the beginning of a new frame, before any invocation of LZ4F_decompress().\n *     It will decode header from `srcBuffer`,\n *     consuming the header and starting the decoding process.\n *\n *     Input size must be large enough to contain the full frame header.\n *     Frame header size can be known beforehand by LZ4F_headerSize().\n *     Frame header size is variable, but is guaranteed to be >= LZ4F_HEADER_SIZE_MIN bytes,\n *     and not more than <= LZ4F_HEADER_SIZE_MAX bytes.\n *     Hence, blindly providing LZ4F_HEADER_SIZE_MAX bytes or more will always work.\n *     It's allowed to provide more input data than the header size,\n *     LZ4F_getFrameInfo() will only consume the header.\n *\n *     If input size is not large enough,\n *     aka if it's smaller than header size,\n *     function will fail and return an error code.\n *\n *  2) After decoding has been started,\n *     it's possible to invoke LZ4F_getFrameInfo() anytime\n *     to extract already decoded frame parameters stored within dctx.\n *\n *     Note that, if decoding has barely started,\n *     and not yet read enough information to decode the header,\n *     LZ4F_getFrameInfo() will fail.\n *\n *  The number of bytes consumed from srcBuffer will be updated in *srcSizePtr (necessarily <= original value).\n *  LZ4F_getFrameInfo() only consumes bytes when decoding has not yet started,\n *  and when decoding the header has been successful.\n *  Decompression must then resume from (srcBuffer + *srcSizePtr).\n *\n * @return : a hint about how many srcSize bytes LZ4F_decompress() expects for next call,\n *           or an error code which can be tested using LZ4F_isError().\n *  note 1 : in case of error, dctx is not modified. Decoding operation can resume from beginning safely.\n *  note 2 : frame parameters are *copied into* an already allocated LZ4F_frameInfo_t structure.\n */\nLZ4FLIB_API size_t LZ4F_getFrameInfo(LZ4F_dctx* dctx,\n                                     LZ4F_frameInfo_t* frameInfoPtr,\n                                     const void* srcBuffer, size_t* srcSizePtr);\n\n/*! LZ4F_decompress() :\n *  Call this function repetitively to regenerate data compressed in `srcBuffer`.\n *\n *  The function requires a valid dctx state.\n *  It will read up to *srcSizePtr bytes from srcBuffer,\n *  and decompress data into dstBuffer, of capacity *dstSizePtr.\n *\n *  The nb of bytes consumed from srcBuffer will be written into *srcSizePtr (necessarily <= original value).\n *  The nb of bytes decompressed into dstBuffer will be written into *dstSizePtr (necessarily <= original value).\n *\n *  The function does not necessarily read all input bytes, so always check value in *srcSizePtr.\n *  Unconsumed source data must be presented again in subsequent invocations.\n *\n * `dstBuffer` can freely change between each consecutive function invocation.\n * `dstBuffer` content will be overwritten.\n *\n * @return : an hint of how many `srcSize` bytes LZ4F_decompress() expects for next call.\n *  Schematically, it's the size of the current (or remaining) compressed block + header of next block.\n *  Respecting the hint provides some small speed benefit, because it skips intermediate buffers.\n *  This is just a hint though, it's always possible to provide any srcSize.\n *\n *  When a frame is fully decoded, @return will be 0 (no more data expected).\n *  When provided with more bytes than necessary to decode a frame,\n *  LZ4F_decompress() will stop reading exactly at end of current frame, and @return 0.\n *\n *  If decompression failed, @return is an error code, which can be tested using LZ4F_isError().\n *  After a decompression error, the `dctx` context is not resumable.\n *  Use LZ4F_resetDecompressionContext() to return to clean state.\n *\n *  After a frame is fully decoded, dctx can be used again to decompress another frame.\n */\nLZ4FLIB_API size_t LZ4F_decompress(LZ4F_dctx* dctx,\n                                   void* dstBuffer, size_t* dstSizePtr,\n                                   const void* srcBuffer, size_t* srcSizePtr,\n                                   const LZ4F_decompressOptions_t* dOptPtr);\n\n\n/*! LZ4F_resetDecompressionContext() : added in v1.8.0\n *  In case of an error, the context is left in \"undefined\" state.\n *  In which case, it's necessary to reset it, before re-using it.\n *  This method can also be used to abruptly stop any unfinished decompression,\n *  and start a new one using same context resources. */\nLZ4FLIB_API void LZ4F_resetDecompressionContext(LZ4F_dctx* dctx);   /* always successful */\n\n\n\n#if defined (__cplusplus)\n}\n#endif\n\n#endif  /* LZ4F_H_09782039843 */\n\n#if defined(LZ4F_STATIC_LINKING_ONLY) && !defined(LZ4F_H_STATIC_09782039843)\n#define LZ4F_H_STATIC_09782039843\n\n#if defined (__cplusplus)\nextern \"C\" {\n#endif\n\n/* These declarations are not stable and may change in the future.\n * They are therefore only safe to depend on\n * when the caller is statically linked against the library.\n * To access their declarations, define LZ4F_STATIC_LINKING_ONLY.\n *\n * By default, these symbols aren't published into shared/dynamic libraries.\n * You can override this behavior and force them to be published\n * by defining LZ4F_PUBLISH_STATIC_FUNCTIONS.\n * Use at your own risk.\n */\n#ifdef LZ4F_PUBLISH_STATIC_FUNCTIONS\n# define LZ4FLIB_STATIC_API LZ4FLIB_API\n#else\n# define LZ4FLIB_STATIC_API\n#endif\n\n\n/* ---   Error List   --- */\n#define LZ4F_LIST_ERRORS(ITEM) \\\n        ITEM(OK_NoError) \\\n        ITEM(ERROR_GENERIC) \\\n        ITEM(ERROR_maxBlockSize_invalid) \\\n        ITEM(ERROR_blockMode_invalid) \\\n        ITEM(ERROR_contentChecksumFlag_invalid) \\\n        ITEM(ERROR_compressionLevel_invalid) \\\n        ITEM(ERROR_headerVersion_wrong) \\\n        ITEM(ERROR_blockChecksum_invalid) \\\n        ITEM(ERROR_reservedFlag_set) \\\n        ITEM(ERROR_allocation_failed) \\\n        ITEM(ERROR_srcSize_tooLarge) \\\n        ITEM(ERROR_dstMaxSize_tooSmall) \\\n        ITEM(ERROR_frameHeader_incomplete) \\\n        ITEM(ERROR_frameType_unknown) \\\n        ITEM(ERROR_frameSize_wrong) \\\n        ITEM(ERROR_srcPtr_wrong) \\\n        ITEM(ERROR_decompressionFailed) \\\n        ITEM(ERROR_headerChecksum_invalid) \\\n        ITEM(ERROR_contentChecksum_invalid) \\\n        ITEM(ERROR_frameDecoding_alreadyStarted) \\\n        ITEM(ERROR_maxCode)\n\n#define LZ4F_GENERATE_ENUM(ENUM) LZ4F_##ENUM,\n\n/* enum list is exposed, to handle specific errors */\ntypedef enum { LZ4F_LIST_ERRORS(LZ4F_GENERATE_ENUM)\n              _LZ4F_dummy_error_enum_for_c89_never_used } LZ4F_errorCodes;\n\nLZ4FLIB_STATIC_API LZ4F_errorCodes LZ4F_getErrorCode(size_t functionResult);\n\nLZ4FLIB_STATIC_API size_t LZ4F_getBlockSize(unsigned);\n\n/**********************************\n *  Bulk processing dictionary API\n *********************************/\n\n/* A Dictionary is useful for the compression of small messages (KB range).\n * It dramatically improves compression efficiency.\n *\n * LZ4 can ingest any input as dictionary, though only the last 64 KB are useful.\n * Best results are generally achieved by using Zstandard's Dictionary Builder\n * to generate a high-quality dictionary from a set of samples.\n *\n * Loading a dictionary has a cost, since it involves construction of tables.\n * The Bulk processing dictionary API makes it possible to share this cost\n * over an arbitrary number of compression jobs, even concurrently,\n * markedly improving compression latency for these cases.\n *\n * The same dictionary will have to be used on the decompression side\n * for decoding to be successful.\n * To help identify the correct dictionary at decoding stage,\n * the frame header allows optional embedding of a dictID field.\n */\ntypedef struct LZ4F_CDict_s LZ4F_CDict;\n\n/*! LZ4_createCDict() :\n *  When compressing multiple messages / blocks using the same dictionary, it's recommended to load it just once.\n *  LZ4_createCDict() will create a digested dictionary, ready to start future compression operations without startup delay.\n *  LZ4_CDict can be created once and shared by multiple threads concurrently, since its usage is read-only.\n * `dictBuffer` can be released after LZ4_CDict creation, since its content is copied within CDict */\nLZ4FLIB_STATIC_API LZ4F_CDict* LZ4F_createCDict(const void* dictBuffer, size_t dictSize);\nLZ4FLIB_STATIC_API void        LZ4F_freeCDict(LZ4F_CDict* CDict);\n\n\n/*! LZ4_compressFrame_usingCDict() :\n *  Compress an entire srcBuffer into a valid LZ4 frame using a digested Dictionary.\n *  cctx must point to a context created by LZ4F_createCompressionContext().\n *  If cdict==NULL, compress without a dictionary.\n *  dstBuffer MUST be >= LZ4F_compressFrameBound(srcSize, preferencesPtr).\n *  If this condition is not respected, function will fail (@return an errorCode).\n *  The LZ4F_preferences_t structure is optional : you may provide NULL as argument,\n *  but it's not recommended, as it's the only way to provide dictID in the frame header.\n * @return : number of bytes written into dstBuffer.\n *           or an error code if it fails (can be tested using LZ4F_isError()) */\nLZ4FLIB_STATIC_API size_t LZ4F_compressFrame_usingCDict(\n    LZ4F_cctx* cctx,\n    void* dst, size_t dstCapacity,\n    const void* src, size_t srcSize,\n    const LZ4F_CDict* cdict,\n    const LZ4F_preferences_t* preferencesPtr);\n\n\n/*! LZ4F_compressBegin_usingCDict() :\n *  Inits streaming dictionary compression, and writes the frame header into dstBuffer.\n *  dstCapacity must be >= LZ4F_HEADER_SIZE_MAX bytes.\n * `prefsPtr` is optional : you may provide NULL as argument,\n *  however, it's the only way to provide dictID in the frame header.\n * @return : number of bytes written into dstBuffer for the header,\n *           or an error code (which can be tested using LZ4F_isError()) */\nLZ4FLIB_STATIC_API size_t LZ4F_compressBegin_usingCDict(\n    LZ4F_cctx* cctx,\n    void* dstBuffer, size_t dstCapacity,\n    const LZ4F_CDict* cdict,\n    const LZ4F_preferences_t* prefsPtr);\n\n\n/*! LZ4F_decompress_usingDict() :\n *  Same as LZ4F_decompress(), using a predefined dictionary.\n *  Dictionary is used \"in place\", without any preprocessing.\n *  It must remain accessible throughout the entire frame decoding. */\nLZ4FLIB_STATIC_API size_t LZ4F_decompress_usingDict(\n    LZ4F_dctx* dctxPtr,\n    void* dstBuffer, size_t* dstSizePtr,\n    const void* srcBuffer, size_t* srcSizePtr,\n    const void* dict, size_t dictSize,\n    const LZ4F_decompressOptions_t* decompressOptionsPtr);\n\n#if defined (__cplusplus)\n}\n#endif\n\n#endif  /* defined(LZ4F_STATIC_LINKING_ONLY) && !defined(LZ4F_H_STATIC_09782039843) */\n"
  },
  {
    "path": "external/lz4/lz4frame_static.h",
    "content": "/*\n   LZ4 auto-framing library\n   Header File for static linking only\n   Copyright (C) 2011-2016, Yann Collet.\n\n   BSD 2-Clause License (http://www.opensource.org/licenses/bsd-license.php)\n\n   Redistribution and use in source and binary forms, with or without\n   modification, are permitted provided that the following conditions are\n   met:\n\n       * Redistributions of source code must retain the above copyright\n   notice, this list of conditions and the following disclaimer.\n       * Redistributions in binary form must reproduce the above\n   copyright notice, this list of conditions and the following disclaimer\n   in the documentation and/or other materials provided with the\n   distribution.\n\n   THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\n   \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\n   LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR\n   A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT\n   OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,\n   SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT\n   LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,\n   DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY\n   THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\n   (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE\n   OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n\n   You can contact the author at :\n   - LZ4 source repository : https://github.com/lz4/lz4\n   - LZ4 public forum : https://groups.google.com/forum/#!forum/lz4c\n*/\n\n#ifndef LZ4FRAME_STATIC_H_0398209384\n#define LZ4FRAME_STATIC_H_0398209384\n\n/* The declarations that formerly were made here have been merged into\n * lz4frame.h, protected by the LZ4F_STATIC_LINKING_ONLY macro. Going forward,\n * it is recommended to simply include that header directly.\n */\n\n#define LZ4F_STATIC_LINKING_ONLY\n#include \"lz4frame.h\"\n\n#endif /* LZ4FRAME_STATIC_H_0398209384 */\n"
  },
  {
    "path": "external/lz4/lz4hc.c",
    "content": "/*\n    LZ4 HC - High Compression Mode of LZ4\n    Copyright (C) 2011-2017, Yann Collet.\n\n    BSD 2-Clause License (http://www.opensource.org/licenses/bsd-license.php)\n\n    Redistribution and use in source and binary forms, with or without\n    modification, are permitted provided that the following conditions are\n    met:\n\n    * Redistributions of source code must retain the above copyright\n    notice, this list of conditions and the following disclaimer.\n    * Redistributions in binary form must reproduce the above\n    copyright notice, this list of conditions and the following disclaimer\n    in the documentation and/or other materials provided with the\n    distribution.\n\n    THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\n    \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\n    LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR\n    A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT\n    OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,\n    SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT\n    LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,\n    DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY\n    THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\n    (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE\n    OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n\n    You can contact the author at :\n       - LZ4 source repository : https://github.com/lz4/lz4\n       - LZ4 public forum : https://groups.google.com/forum/#!forum/lz4c\n*/\n/* note : lz4hc is not an independent module, it requires lz4.h/lz4.c for proper compilation */\n\n\n/* *************************************\n*  Tuning Parameter\n***************************************/\n\n/*! HEAPMODE :\n *  Select how default compression function will allocate workplace memory,\n *  in stack (0:fastest), or in heap (1:requires malloc()).\n *  Since workplace is rather large, heap mode is recommended.\n */\n#ifndef LZ4HC_HEAPMODE\n#  define LZ4HC_HEAPMODE 1\n#endif\n\n\n/*===    Dependency    ===*/\n#define LZ4_HC_STATIC_LINKING_ONLY\n#include \"lz4hc.h\"\n\n\n/*===   Common definitions   ===*/\n#if defined(__GNUC__)\n#  pragma GCC diagnostic ignored \"-Wunused-function\"\n#endif\n#if defined (__clang__)\n#  pragma clang diagnostic ignored \"-Wunused-function\"\n#endif\n\n#define LZ4_COMMONDEFS_ONLY\n#ifndef LZ4_SRC_INCLUDED\n#include \"lz4.c\"   /* LZ4_count, constants, mem */\n#endif\n\n\n/*===   Enums   ===*/\ntypedef enum { noDictCtx, usingDictCtxHc } dictCtx_directive;\n\n\n/*===   Constants   ===*/\n#define OPTIMAL_ML (int)((ML_MASK-1)+MINMATCH)\n#define LZ4_OPT_NUM   (1<<12)\n\n\n/*===   Macros   ===*/\n#define MIN(a,b)   ( (a) < (b) ? (a) : (b) )\n#define MAX(a,b)   ( (a) > (b) ? (a) : (b) )\n#define HASH_FUNCTION(i)         (((i) * 2654435761U) >> ((MINMATCH*8)-LZ4HC_HASH_LOG))\n#define DELTANEXTMAXD(p)         chainTable[(p) & LZ4HC_MAXD_MASK]    /* flexible, LZ4HC_MAXD dependent */\n#define DELTANEXTU16(table, pos) table[(U16)(pos)]   /* faster */\n/* Make fields passed to, and updated by LZ4HC_encodeSequence explicit */\n#define UPDATABLE(ip, op, anchor) &ip, &op, &anchor\n\nstatic U32 LZ4HC_hashPtr(const void* ptr) { return HASH_FUNCTION(LZ4_read32(ptr)); }\n\n\n/**************************************\n*  HC Compression\n**************************************/\nstatic void LZ4HC_clearTables (LZ4HC_CCtx_internal* hc4)\n{\n    MEM_INIT(hc4->hashTable, 0, sizeof(hc4->hashTable));\n    MEM_INIT(hc4->chainTable, 0xFF, sizeof(hc4->chainTable));\n}\n\nstatic void LZ4HC_init_internal (LZ4HC_CCtx_internal* hc4, const BYTE* start)\n{\n    uptrval startingOffset = (uptrval)(hc4->end - hc4->base);\n    if (startingOffset > 1 GB) {\n        LZ4HC_clearTables(hc4);\n        startingOffset = 0;\n    }\n    startingOffset += 64 KB;\n    hc4->nextToUpdate = (U32) startingOffset;\n    hc4->base = start - startingOffset;\n    hc4->end = start;\n    hc4->dictBase = start - startingOffset;\n    hc4->dictLimit = (U32) startingOffset;\n    hc4->lowLimit = (U32) startingOffset;\n}\n\n\n/* Update chains up to ip (excluded) */\nLZ4_FORCE_INLINE void LZ4HC_Insert (LZ4HC_CCtx_internal* hc4, const BYTE* ip)\n{\n    U16* const chainTable = hc4->chainTable;\n    U32* const hashTable  = hc4->hashTable;\n    const BYTE* const base = hc4->base;\n    U32 const target = (U32)(ip - base);\n    U32 idx = hc4->nextToUpdate;\n\n    while (idx < target) {\n        U32 const h = LZ4HC_hashPtr(base+idx);\n        size_t delta = idx - hashTable[h];\n        if (delta>LZ4_DISTANCE_MAX) delta = LZ4_DISTANCE_MAX;\n        DELTANEXTU16(chainTable, idx) = (U16)delta;\n        hashTable[h] = idx;\n        idx++;\n    }\n\n    hc4->nextToUpdate = target;\n}\n\n/** LZ4HC_countBack() :\n * @return : negative value, nb of common bytes before ip/match */\nLZ4_FORCE_INLINE\nint LZ4HC_countBack(const BYTE* const ip, const BYTE* const match,\n                    const BYTE* const iMin, const BYTE* const mMin)\n{\n    int back = 0;\n    int const min = (int)MAX(iMin - ip, mMin - match);\n    assert(min <= 0);\n    assert(ip >= iMin); assert((size_t)(ip-iMin) < (1U<<31));\n    assert(match >= mMin); assert((size_t)(match - mMin) < (1U<<31));\n    while ( (back > min)\n         && (ip[back-1] == match[back-1]) )\n            back--;\n    return back;\n}\n\n#if defined(_MSC_VER)\n#  define LZ4HC_rotl32(x,r) _rotl(x,r)\n#else\n#  define LZ4HC_rotl32(x,r) ((x << r) | (x >> (32 - r)))\n#endif\n\n\nstatic U32 LZ4HC_rotatePattern(size_t const rotate, U32 const pattern)\n{\n    size_t const bitsToRotate = (rotate & (sizeof(pattern) - 1)) << 3;\n    if (bitsToRotate == 0) return pattern;\n    return LZ4HC_rotl32(pattern, (int)bitsToRotate);\n}\n\n/* LZ4HC_countPattern() :\n * pattern32 must be a sample of repetitive pattern of length 1, 2 or 4 (but not 3!) */\nstatic unsigned\nLZ4HC_countPattern(const BYTE* ip, const BYTE* const iEnd, U32 const pattern32)\n{\n    const BYTE* const iStart = ip;\n    reg_t const pattern = (sizeof(pattern)==8) ?\n        (reg_t)pattern32 + (((reg_t)pattern32) << (sizeof(pattern)*4)) : pattern32;\n\n    while (likely(ip < iEnd-(sizeof(pattern)-1))) {\n        reg_t const diff = LZ4_read_ARCH(ip) ^ pattern;\n        if (!diff) { ip+=sizeof(pattern); continue; }\n        ip += LZ4_NbCommonBytes(diff);\n        return (unsigned)(ip - iStart);\n    }\n\n    if (LZ4_isLittleEndian()) {\n        reg_t patternByte = pattern;\n        while ((ip<iEnd) && (*ip == (BYTE)patternByte)) {\n            ip++; patternByte >>= 8;\n        }\n    } else {  /* big endian */\n        U32 bitOffset = (sizeof(pattern)*8) - 8;\n        while (ip < iEnd) {\n            BYTE const byte = (BYTE)(pattern >> bitOffset);\n            if (*ip != byte) break;\n            ip ++; bitOffset -= 8;\n        }\n    }\n\n    return (unsigned)(ip - iStart);\n}\n\n/* LZ4HC_reverseCountPattern() :\n * pattern must be a sample of repetitive pattern of length 1, 2 or 4 (but not 3!)\n * read using natural platform endianess */\nstatic unsigned\nLZ4HC_reverseCountPattern(const BYTE* ip, const BYTE* const iLow, U32 pattern)\n{\n    const BYTE* const iStart = ip;\n\n    while (likely(ip >= iLow+4)) {\n        if (LZ4_read32(ip-4) != pattern) break;\n        ip -= 4;\n    }\n    {   const BYTE* bytePtr = (const BYTE*)(&pattern) + 3; /* works for any endianess */\n        while (likely(ip>iLow)) {\n            if (ip[-1] != *bytePtr) break;\n            ip--; bytePtr--;\n    }   }\n    return (unsigned)(iStart - ip);\n}\n\n/* LZ4HC_protectDictEnd() :\n * Checks if the match is in the last 3 bytes of the dictionary, so reading the\n * 4 byte MINMATCH would overflow.\n * @returns true if the match index is okay.\n */\nstatic int LZ4HC_protectDictEnd(U32 const dictLimit, U32 const matchIndex)\n{\n    return ((U32)((dictLimit - 1) - matchIndex) >= 3);\n}\n\ntypedef enum { rep_untested, rep_not, rep_confirmed } repeat_state_e;\ntypedef enum { favorCompressionRatio=0, favorDecompressionSpeed } HCfavor_e;\n\nLZ4_FORCE_INLINE int\nLZ4HC_InsertAndGetWiderMatch (\n    LZ4HC_CCtx_internal* hc4,\n    const BYTE* const ip,\n    const BYTE* const iLowLimit,\n    const BYTE* const iHighLimit,\n    int longest,\n    const BYTE** matchpos,\n    const BYTE** startpos,\n    const int maxNbAttempts,\n    const int patternAnalysis,\n    const int chainSwap,\n    const dictCtx_directive dict,\n    const HCfavor_e favorDecSpeed)\n{\n    U16* const chainTable = hc4->chainTable;\n    U32* const HashTable = hc4->hashTable;\n    const LZ4HC_CCtx_internal * const dictCtx = hc4->dictCtx;\n    const BYTE* const base = hc4->base;\n    const U32 dictLimit = hc4->dictLimit;\n    const BYTE* const lowPrefixPtr = base + dictLimit;\n    const U32 ipIndex = (U32)(ip - base);\n    const U32 lowestMatchIndex = (hc4->lowLimit + (LZ4_DISTANCE_MAX + 1) > ipIndex) ? hc4->lowLimit : ipIndex - LZ4_DISTANCE_MAX;\n    const BYTE* const dictBase = hc4->dictBase;\n    int const lookBackLength = (int)(ip-iLowLimit);\n    int nbAttempts = maxNbAttempts;\n    U32 matchChainPos = 0;\n    U32 const pattern = LZ4_read32(ip);\n    U32 matchIndex;\n    repeat_state_e repeat = rep_untested;\n    size_t srcPatternLength = 0;\n\n    DEBUGLOG(7, \"LZ4HC_InsertAndGetWiderMatch\");\n    /* First Match */\n    LZ4HC_Insert(hc4, ip);\n    matchIndex = HashTable[LZ4HC_hashPtr(ip)];\n    DEBUGLOG(7, \"First match at index %u / %u (lowestMatchIndex)\",\n                matchIndex, lowestMatchIndex);\n\n    while ((matchIndex>=lowestMatchIndex) && (nbAttempts>0)) {\n        int matchLength=0;\n        nbAttempts--;\n        assert(matchIndex < ipIndex);\n        if (favorDecSpeed && (ipIndex - matchIndex < 8)) {\n            /* do nothing */\n        } else if (matchIndex >= dictLimit) {   /* within current Prefix */\n            const BYTE* const matchPtr = base + matchIndex;\n            assert(matchPtr >= lowPrefixPtr);\n            assert(matchPtr < ip);\n            assert(longest >= 1);\n            if (LZ4_read16(iLowLimit + longest - 1) == LZ4_read16(matchPtr - lookBackLength + longest - 1)) {\n                if (LZ4_read32(matchPtr) == pattern) {\n                    int const back = lookBackLength ? LZ4HC_countBack(ip, matchPtr, iLowLimit, lowPrefixPtr) : 0;\n                    matchLength = MINMATCH + (int)LZ4_count(ip+MINMATCH, matchPtr+MINMATCH, iHighLimit);\n                    matchLength -= back;\n                    if (matchLength > longest) {\n                        longest = matchLength;\n                        *matchpos = matchPtr + back;\n                        *startpos = ip + back;\n            }   }   }\n        } else {   /* lowestMatchIndex <= matchIndex < dictLimit */\n            const BYTE* const matchPtr = dictBase + matchIndex;\n            if (LZ4_read32(matchPtr) == pattern) {\n                const BYTE* const dictStart = dictBase + hc4->lowLimit;\n                int back = 0;\n                const BYTE* vLimit = ip + (dictLimit - matchIndex);\n                if (vLimit > iHighLimit) vLimit = iHighLimit;\n                matchLength = (int)LZ4_count(ip+MINMATCH, matchPtr+MINMATCH, vLimit) + MINMATCH;\n                if ((ip+matchLength == vLimit) && (vLimit < iHighLimit))\n                    matchLength += LZ4_count(ip+matchLength, lowPrefixPtr, iHighLimit);\n                back = lookBackLength ? LZ4HC_countBack(ip, matchPtr, iLowLimit, dictStart) : 0;\n                matchLength -= back;\n                if (matchLength > longest) {\n                    longest = matchLength;\n                    *matchpos = base + matchIndex + back;   /* virtual pos, relative to ip, to retrieve offset */\n                    *startpos = ip + back;\n        }   }   }\n\n        if (chainSwap && matchLength==longest) {    /* better match => select a better chain */\n            assert(lookBackLength==0);   /* search forward only */\n            if (matchIndex + (U32)longest <= ipIndex) {\n                int const kTrigger = 4;\n                U32 distanceToNextMatch = 1;\n                int const end = longest - MINMATCH + 1;\n                int step = 1;\n                int accel = 1 << kTrigger;\n                int pos;\n                for (pos = 0; pos < end; pos += step) {\n                    U32 const candidateDist = DELTANEXTU16(chainTable, matchIndex + (U32)pos);\n                    step = (accel++ >> kTrigger);\n                    if (candidateDist > distanceToNextMatch) {\n                        distanceToNextMatch = candidateDist;\n                        matchChainPos = (U32)pos;\n                        accel = 1 << kTrigger;\n                    }\n                }\n                if (distanceToNextMatch > 1) {\n                    if (distanceToNextMatch > matchIndex) break;   /* avoid overflow */\n                    matchIndex -= distanceToNextMatch;\n                    continue;\n        }   }   }\n\n        {   U32 const distNextMatch = DELTANEXTU16(chainTable, matchIndex);\n            if (patternAnalysis && distNextMatch==1 && matchChainPos==0) {\n                U32 const matchCandidateIdx = matchIndex-1;\n                /* may be a repeated pattern */\n                if (repeat == rep_untested) {\n                    if ( ((pattern & 0xFFFF) == (pattern >> 16))\n                      &  ((pattern & 0xFF)   == (pattern >> 24)) ) {\n                        repeat = rep_confirmed;\n                        srcPatternLength = LZ4HC_countPattern(ip+sizeof(pattern), iHighLimit, pattern) + sizeof(pattern);\n                    } else {\n                        repeat = rep_not;\n                }   }\n                if ( (repeat == rep_confirmed) && (matchCandidateIdx >= lowestMatchIndex)\n                  && LZ4HC_protectDictEnd(dictLimit, matchCandidateIdx) ) {\n                    const int extDict = matchCandidateIdx < dictLimit;\n                    const BYTE* const matchPtr = (extDict ? dictBase : base) + matchCandidateIdx;\n                    if (LZ4_read32(matchPtr) == pattern) {  /* good candidate */\n                        const BYTE* const dictStart = dictBase + hc4->lowLimit;\n                        const BYTE* const iLimit = extDict ? dictBase + dictLimit : iHighLimit;\n                        size_t forwardPatternLength = LZ4HC_countPattern(matchPtr+sizeof(pattern), iLimit, pattern) + sizeof(pattern);\n                        if (extDict && matchPtr + forwardPatternLength == iLimit) {\n                            U32 const rotatedPattern = LZ4HC_rotatePattern(forwardPatternLength, pattern);\n                            forwardPatternLength += LZ4HC_countPattern(lowPrefixPtr, iHighLimit, rotatedPattern);\n                        }\n                        {   const BYTE* const lowestMatchPtr = extDict ? dictStart : lowPrefixPtr;\n                            size_t backLength = LZ4HC_reverseCountPattern(matchPtr, lowestMatchPtr, pattern);\n                            size_t currentSegmentLength;\n                            if (!extDict && matchPtr - backLength == lowPrefixPtr && hc4->lowLimit < dictLimit) {\n                                U32 const rotatedPattern = LZ4HC_rotatePattern((U32)(-(int)backLength), pattern);\n                                backLength += LZ4HC_reverseCountPattern(dictBase + dictLimit, dictStart, rotatedPattern);\n                            }\n                            /* Limit backLength not go further than lowestMatchIndex */\n                            backLength = matchCandidateIdx - MAX(matchCandidateIdx - (U32)backLength, lowestMatchIndex);\n                            assert(matchCandidateIdx - backLength >= lowestMatchIndex);\n                            currentSegmentLength = backLength + forwardPatternLength;\n                            /* Adjust to end of pattern if the source pattern fits, otherwise the beginning of the pattern */\n                            if ( (currentSegmentLength >= srcPatternLength)   /* current pattern segment large enough to contain full srcPatternLength */\n                              && (forwardPatternLength <= srcPatternLength) ) { /* haven't reached this position yet */\n                                U32 const newMatchIndex = matchCandidateIdx + (U32)forwardPatternLength - (U32)srcPatternLength;  /* best position, full pattern, might be followed by more match */\n                                if (LZ4HC_protectDictEnd(dictLimit, newMatchIndex))\n                                    matchIndex = newMatchIndex;\n                                else {\n                                    /* Can only happen if started in the prefix */\n                                    assert(newMatchIndex >= dictLimit - 3 && newMatchIndex < dictLimit && !extDict);\n                                    matchIndex = dictLimit;\n                                }\n                            } else {\n                                U32 const newMatchIndex = matchCandidateIdx - (U32)backLength;   /* farthest position in current segment, will find a match of length currentSegmentLength + maybe some back */\n                                if (!LZ4HC_protectDictEnd(dictLimit, newMatchIndex)) {\n                                    assert(newMatchIndex >= dictLimit - 3 && newMatchIndex < dictLimit && !extDict);\n                                    matchIndex = dictLimit;\n                                } else {\n                                    matchIndex = newMatchIndex;\n                                    if (lookBackLength==0) {  /* no back possible */\n                                        size_t const maxML = MIN(currentSegmentLength, srcPatternLength);\n                                        if ((size_t)longest < maxML) {\n                                            assert(base + matchIndex != ip);\n                                            if ((size_t)(ip - base) - matchIndex > LZ4_DISTANCE_MAX) break;\n                                            assert(maxML < 2 GB);\n                                            longest = (int)maxML;\n                                            *matchpos = base + matchIndex;   /* virtual pos, relative to ip, to retrieve offset */\n                                            *startpos = ip;\n                                        }\n                                        {   U32 const distToNextPattern = DELTANEXTU16(chainTable, matchIndex);\n                                            if (distToNextPattern > matchIndex) break;  /* avoid overflow */\n                                            matchIndex -= distToNextPattern;\n                        }   }   }   }   }\n                        continue;\n                }   }\n        }   }   /* PA optimization */\n\n        /* follow current chain */\n        matchIndex -= DELTANEXTU16(chainTable, matchIndex + matchChainPos);\n\n    }  /* while ((matchIndex>=lowestMatchIndex) && (nbAttempts)) */\n\n    if ( dict == usingDictCtxHc\n      && nbAttempts > 0\n      && ipIndex - lowestMatchIndex < LZ4_DISTANCE_MAX) {\n        size_t const dictEndOffset = (size_t)(dictCtx->end - dictCtx->base);\n        U32 dictMatchIndex = dictCtx->hashTable[LZ4HC_hashPtr(ip)];\n        assert(dictEndOffset <= 1 GB);\n        matchIndex = dictMatchIndex + lowestMatchIndex - (U32)dictEndOffset;\n        while (ipIndex - matchIndex <= LZ4_DISTANCE_MAX && nbAttempts--) {\n            const BYTE* const matchPtr = dictCtx->base + dictMatchIndex;\n\n            if (LZ4_read32(matchPtr) == pattern) {\n                int mlt;\n                int back = 0;\n                const BYTE* vLimit = ip + (dictEndOffset - dictMatchIndex);\n                if (vLimit > iHighLimit) vLimit = iHighLimit;\n                mlt = (int)LZ4_count(ip+MINMATCH, matchPtr+MINMATCH, vLimit) + MINMATCH;\n                back = lookBackLength ? LZ4HC_countBack(ip, matchPtr, iLowLimit, dictCtx->base + dictCtx->dictLimit) : 0;\n                mlt -= back;\n                if (mlt > longest) {\n                    longest = mlt;\n                    *matchpos = base + matchIndex + back;\n                    *startpos = ip + back;\n            }   }\n\n            {   U32 const nextOffset = DELTANEXTU16(dictCtx->chainTable, dictMatchIndex);\n                dictMatchIndex -= nextOffset;\n                matchIndex -= nextOffset;\n    }   }   }\n\n    return longest;\n}\n\nLZ4_FORCE_INLINE\nint LZ4HC_InsertAndFindBestMatch(LZ4HC_CCtx_internal* const hc4,   /* Index table will be updated */\n                                 const BYTE* const ip, const BYTE* const iLimit,\n                                 const BYTE** matchpos,\n                                 const int maxNbAttempts,\n                                 const int patternAnalysis,\n                                 const dictCtx_directive dict)\n{\n    const BYTE* uselessPtr = ip;\n    /* note : LZ4HC_InsertAndGetWiderMatch() is able to modify the starting position of a match (*startpos),\n     * but this won't be the case here, as we define iLowLimit==ip,\n     * so LZ4HC_InsertAndGetWiderMatch() won't be allowed to search past ip */\n    return LZ4HC_InsertAndGetWiderMatch(hc4, ip, ip, iLimit, MINMATCH-1, matchpos, &uselessPtr, maxNbAttempts, patternAnalysis, 0 /*chainSwap*/, dict, favorCompressionRatio);\n}\n\n/* LZ4HC_encodeSequence() :\n * @return : 0 if ok,\n *           1 if buffer issue detected */\nLZ4_FORCE_INLINE int LZ4HC_encodeSequence (\n    const BYTE** _ip,\n    BYTE** _op,\n    const BYTE** _anchor,\n    int matchLength,\n    const BYTE* const match,\n    limitedOutput_directive limit,\n    BYTE* oend)\n{\n#define ip      (*_ip)\n#define op      (*_op)\n#define anchor  (*_anchor)\n\n    size_t length;\n    BYTE* const token = op++;\n\n#if defined(LZ4_DEBUG) && (LZ4_DEBUG >= 6)\n    static const BYTE* start = NULL;\n    static U32 totalCost = 0;\n    U32 const pos = (start==NULL) ? 0 : (U32)(anchor - start);\n    U32 const ll = (U32)(ip - anchor);\n    U32 const llAdd = (ll>=15) ? ((ll-15) / 255) + 1 : 0;\n    U32 const mlAdd = (matchLength>=19) ? ((matchLength-19) / 255) + 1 : 0;\n    U32 const cost = 1 + llAdd + ll + 2 + mlAdd;\n    if (start==NULL) start = anchor;  /* only works for single segment */\n    /* g_debuglog_enable = (pos >= 2228) & (pos <= 2262); */\n    DEBUGLOG(6, \"pos:%7u -- literals:%4u, match:%4i, offset:%5u, cost:%4u + %5u\",\n                pos,\n                (U32)(ip - anchor), matchLength, (U32)(ip-match),\n                cost, totalCost);\n    totalCost += cost;\n#endif\n\n    /* Encode Literal length */\n    length = (size_t)(ip - anchor);\n    LZ4_STATIC_ASSERT(notLimited == 0);\n    /* Check output limit */\n    if (limit && ((op + (length / 255) + length + (2 + 1 + LASTLITERALS)) > oend)) {\n        DEBUGLOG(6, \"Not enough room to write %i literals (%i bytes remaining)\",\n                (int)length, (int)(oend - op));\n        return 1;\n    }\n    if (length >= RUN_MASK) {\n        size_t len = length - RUN_MASK;\n        *token = (RUN_MASK << ML_BITS);\n        for(; len >= 255 ; len -= 255) *op++ = 255;\n        *op++ = (BYTE)len;\n    } else {\n        *token = (BYTE)(length << ML_BITS);\n    }\n\n    /* Copy Literals */\n    LZ4_wildCopy8(op, anchor, op + length);\n    op += length;\n\n    /* Encode Offset */\n    assert( (ip - match) <= LZ4_DISTANCE_MAX );   /* note : consider providing offset as a value, rather than as a pointer difference */\n    LZ4_writeLE16(op, (U16)(ip - match)); op += 2;\n\n    /* Encode MatchLength */\n    assert(matchLength >= MINMATCH);\n    length = (size_t)matchLength - MINMATCH;\n    if (limit && (op + (length / 255) + (1 + LASTLITERALS) > oend)) {\n        DEBUGLOG(6, \"Not enough room to write match length\");\n        return 1;   /* Check output limit */\n    }\n    if (length >= ML_MASK) {\n        *token += ML_MASK;\n        length -= ML_MASK;\n        for(; length >= 510 ; length -= 510) { *op++ = 255; *op++ = 255; }\n        if (length >= 255) { length -= 255; *op++ = 255; }\n        *op++ = (BYTE)length;\n    } else {\n        *token += (BYTE)(length);\n    }\n\n    /* Prepare next loop */\n    ip += matchLength;\n    anchor = ip;\n\n    return 0;\n}\n#undef ip\n#undef op\n#undef anchor\n\nLZ4_FORCE_INLINE int LZ4HC_compress_hashChain (\n    LZ4HC_CCtx_internal* const ctx,\n    const char* const source,\n    char* const dest,\n    int* srcSizePtr,\n    int const maxOutputSize,\n    int maxNbAttempts,\n    const limitedOutput_directive limit,\n    const dictCtx_directive dict\n    )\n{\n    const int inputSize = *srcSizePtr;\n    const int patternAnalysis = (maxNbAttempts > 128);   /* levels 9+ */\n\n    const BYTE* ip = (const BYTE*) source;\n    const BYTE* anchor = ip;\n    const BYTE* const iend = ip + inputSize;\n    const BYTE* const mflimit = iend - MFLIMIT;\n    const BYTE* const matchlimit = (iend - LASTLITERALS);\n\n    BYTE* optr = (BYTE*) dest;\n    BYTE* op = (BYTE*) dest;\n    BYTE* oend = op + maxOutputSize;\n\n    int   ml0, ml, ml2, ml3;\n    const BYTE* start0;\n    const BYTE* ref0;\n    const BYTE* ref = NULL;\n    const BYTE* start2 = NULL;\n    const BYTE* ref2 = NULL;\n    const BYTE* start3 = NULL;\n    const BYTE* ref3 = NULL;\n\n    /* init */\n    *srcSizePtr = 0;\n    if (limit == fillOutput) oend -= LASTLITERALS;                  /* Hack for support LZ4 format restriction */\n    if (inputSize < LZ4_minLength) goto _last_literals;             /* Input too small, no compression (all literals) */\n\n    /* Main Loop */\n    while (ip <= mflimit) {\n        ml = LZ4HC_InsertAndFindBestMatch(ctx, ip, matchlimit, &ref, maxNbAttempts, patternAnalysis, dict);\n        if (ml<MINMATCH) { ip++; continue; }\n\n        /* saved, in case we would skip too much */\n        start0 = ip; ref0 = ref; ml0 = ml;\n\n_Search2:\n        if (ip+ml <= mflimit) {\n            ml2 = LZ4HC_InsertAndGetWiderMatch(ctx,\n                            ip + ml - 2, ip + 0, matchlimit, ml, &ref2, &start2,\n                            maxNbAttempts, patternAnalysis, 0, dict, favorCompressionRatio);\n        } else {\n            ml2 = ml;\n        }\n\n        if (ml2 == ml) { /* No better match => encode ML1 */\n            optr = op;\n            if (LZ4HC_encodeSequence(UPDATABLE(ip, op, anchor), ml, ref, limit, oend)) goto _dest_overflow;\n            continue;\n        }\n\n        if (start0 < ip) {   /* first match was skipped at least once */\n            if (start2 < ip + ml0) {  /* squeezing ML1 between ML0(original ML1) and ML2 */\n                ip = start0; ref = ref0; ml = ml0;  /* restore initial ML1 */\n        }   }\n\n        /* Here, start0==ip */\n        if ((start2 - ip) < 3) {  /* First Match too small : removed */\n            ml = ml2;\n            ip = start2;\n            ref =ref2;\n            goto _Search2;\n        }\n\n_Search3:\n        /* At this stage, we have :\n        *  ml2 > ml1, and\n        *  ip1+3 <= ip2 (usually < ip1+ml1) */\n        if ((start2 - ip) < OPTIMAL_ML) {\n            int correction;\n            int new_ml = ml;\n            if (new_ml > OPTIMAL_ML) new_ml = OPTIMAL_ML;\n            if (ip+new_ml > start2 + ml2 - MINMATCH) new_ml = (int)(start2 - ip) + ml2 - MINMATCH;\n            correction = new_ml - (int)(start2 - ip);\n            if (correction > 0) {\n                start2 += correction;\n                ref2 += correction;\n                ml2 -= correction;\n            }\n        }\n        /* Now, we have start2 = ip+new_ml, with new_ml = min(ml, OPTIMAL_ML=18) */\n\n        if (start2 + ml2 <= mflimit) {\n            ml3 = LZ4HC_InsertAndGetWiderMatch(ctx,\n                            start2 + ml2 - 3, start2, matchlimit, ml2, &ref3, &start3,\n                            maxNbAttempts, patternAnalysis, 0, dict, favorCompressionRatio);\n        } else {\n            ml3 = ml2;\n        }\n\n        if (ml3 == ml2) {  /* No better match => encode ML1 and ML2 */\n            /* ip & ref are known; Now for ml */\n            if (start2 < ip+ml)  ml = (int)(start2 - ip);\n            /* Now, encode 2 sequences */\n            optr = op;\n            if (LZ4HC_encodeSequence(UPDATABLE(ip, op, anchor), ml, ref, limit, oend)) goto _dest_overflow;\n            ip = start2;\n            optr = op;\n            if (LZ4HC_encodeSequence(UPDATABLE(ip, op, anchor), ml2, ref2, limit, oend)) {\n                ml  = ml2;\n                ref = ref2;\n                goto _dest_overflow;\n            }\n            continue;\n        }\n\n        if (start3 < ip+ml+3) {  /* Not enough space for match 2 : remove it */\n            if (start3 >= (ip+ml)) {  /* can write Seq1 immediately ==> Seq2 is removed, so Seq3 becomes Seq1 */\n                if (start2 < ip+ml) {\n                    int correction = (int)(ip+ml - start2);\n                    start2 += correction;\n                    ref2 += correction;\n                    ml2 -= correction;\n                    if (ml2 < MINMATCH) {\n                        start2 = start3;\n                        ref2 = ref3;\n                        ml2 = ml3;\n                    }\n                }\n\n                optr = op;\n                if (LZ4HC_encodeSequence(UPDATABLE(ip, op, anchor), ml, ref, limit, oend)) goto _dest_overflow;\n                ip  = start3;\n                ref = ref3;\n                ml  = ml3;\n\n                start0 = start2;\n                ref0 = ref2;\n                ml0 = ml2;\n                goto _Search2;\n            }\n\n            start2 = start3;\n            ref2 = ref3;\n            ml2 = ml3;\n            goto _Search3;\n        }\n\n        /*\n        * OK, now we have 3 ascending matches;\n        * let's write the first one ML1.\n        * ip & ref are known; Now decide ml.\n        */\n        if (start2 < ip+ml) {\n            if ((start2 - ip) < OPTIMAL_ML) {\n                int correction;\n                if (ml > OPTIMAL_ML) ml = OPTIMAL_ML;\n                if (ip + ml > start2 + ml2 - MINMATCH) ml = (int)(start2 - ip) + ml2 - MINMATCH;\n                correction = ml - (int)(start2 - ip);\n                if (correction > 0) {\n                    start2 += correction;\n                    ref2 += correction;\n                    ml2 -= correction;\n                }\n            } else {\n                ml = (int)(start2 - ip);\n            }\n        }\n        optr = op;\n        if (LZ4HC_encodeSequence(UPDATABLE(ip, op, anchor), ml, ref, limit, oend)) goto _dest_overflow;\n\n        /* ML2 becomes ML1 */\n        ip = start2; ref = ref2; ml = ml2;\n\n        /* ML3 becomes ML2 */\n        start2 = start3; ref2 = ref3; ml2 = ml3;\n\n        /* let's find a new ML3 */\n        goto _Search3;\n    }\n\n_last_literals:\n    /* Encode Last Literals */\n    {   size_t lastRunSize = (size_t)(iend - anchor);  /* literals */\n        size_t llAdd = (lastRunSize + 255 - RUN_MASK) / 255;\n        size_t const totalSize = 1 + llAdd + lastRunSize;\n        if (limit == fillOutput) oend += LASTLITERALS;  /* restore correct value */\n        if (limit && (op + totalSize > oend)) {\n            if (limit == limitedOutput) return 0;\n            /* adapt lastRunSize to fill 'dest' */\n            lastRunSize  = (size_t)(oend - op) - 1 /*token*/;\n            llAdd = (lastRunSize + 256 - RUN_MASK) / 256;\n            lastRunSize -= llAdd;\n        }\n        DEBUGLOG(6, \"Final literal run : %i literals\", (int)lastRunSize);\n        ip = anchor + lastRunSize;  /* can be != iend if limit==fillOutput */\n\n        if (lastRunSize >= RUN_MASK) {\n            size_t accumulator = lastRunSize - RUN_MASK;\n            *op++ = (RUN_MASK << ML_BITS);\n            for(; accumulator >= 255 ; accumulator -= 255) *op++ = 255;\n            *op++ = (BYTE) accumulator;\n        } else {\n            *op++ = (BYTE)(lastRunSize << ML_BITS);\n        }\n        memcpy(op, anchor, lastRunSize);\n        op += lastRunSize;\n    }\n\n    /* End */\n    *srcSizePtr = (int) (((const char*)ip) - source);\n    return (int) (((char*)op)-dest);\n\n_dest_overflow:\n    if (limit == fillOutput) {\n        /* Assumption : ip, anchor, ml and ref must be set correctly */\n        size_t const ll = (size_t)(ip - anchor);\n        size_t const ll_addbytes = (ll + 240) / 255;\n        size_t const ll_totalCost = 1 + ll_addbytes + ll;\n        BYTE* const maxLitPos = oend - 3; /* 2 for offset, 1 for token */\n        DEBUGLOG(6, \"Last sequence overflowing\");\n        op = optr;  /* restore correct out pointer */\n        if (op + ll_totalCost <= maxLitPos) {\n            /* ll validated; now adjust match length */\n            size_t const bytesLeftForMl = (size_t)(maxLitPos - (op+ll_totalCost));\n            size_t const maxMlSize = MINMATCH + (ML_MASK-1) + (bytesLeftForMl * 255);\n            assert(maxMlSize < INT_MAX); assert(ml >= 0);\n            if ((size_t)ml > maxMlSize) ml = (int)maxMlSize;\n            if ((oend + LASTLITERALS) - (op + ll_totalCost + 2) - 1 + ml >= MFLIMIT) {\n                LZ4HC_encodeSequence(UPDATABLE(ip, op, anchor), ml, ref, notLimited, oend);\n        }   }\n        goto _last_literals;\n    }\n    /* compression failed */\n    return 0;\n}\n\n\nstatic int LZ4HC_compress_optimal( LZ4HC_CCtx_internal* ctx,\n    const char* const source, char* dst,\n    int* srcSizePtr, int dstCapacity,\n    int const nbSearches, size_t sufficient_len,\n    const limitedOutput_directive limit, int const fullUpdate,\n    const dictCtx_directive dict,\n    const HCfavor_e favorDecSpeed);\n\n\nLZ4_FORCE_INLINE int LZ4HC_compress_generic_internal (\n    LZ4HC_CCtx_internal* const ctx,\n    const char* const src,\n    char* const dst,\n    int* const srcSizePtr,\n    int const dstCapacity,\n    int cLevel,\n    const limitedOutput_directive limit,\n    const dictCtx_directive dict\n    )\n{\n    typedef enum { lz4hc, lz4opt } lz4hc_strat_e;\n    typedef struct {\n        lz4hc_strat_e strat;\n        int nbSearches;\n        U32 targetLength;\n    } cParams_t;\n    static const cParams_t clTable[LZ4HC_CLEVEL_MAX+1] = {\n        { lz4hc,     2, 16 },  /* 0, unused */\n        { lz4hc,     2, 16 },  /* 1, unused */\n        { lz4hc,     2, 16 },  /* 2, unused */\n        { lz4hc,     4, 16 },  /* 3 */\n        { lz4hc,     8, 16 },  /* 4 */\n        { lz4hc,    16, 16 },  /* 5 */\n        { lz4hc,    32, 16 },  /* 6 */\n        { lz4hc,    64, 16 },  /* 7 */\n        { lz4hc,   128, 16 },  /* 8 */\n        { lz4hc,   256, 16 },  /* 9 */\n        { lz4opt,   96, 64 },  /*10==LZ4HC_CLEVEL_OPT_MIN*/\n        { lz4opt,  512,128 },  /*11 */\n        { lz4opt,16384,LZ4_OPT_NUM },  /* 12==LZ4HC_CLEVEL_MAX */\n    };\n\n    DEBUGLOG(4, \"LZ4HC_compress_generic(ctx=%p, src=%p, srcSize=%d, limit=%d)\",\n                ctx, src, *srcSizePtr, limit);\n\n    if (limit == fillOutput && dstCapacity < 1) return 0;   /* Impossible to store anything */\n    if ((U32)*srcSizePtr > (U32)LZ4_MAX_INPUT_SIZE) return 0;    /* Unsupported input size (too large or negative) */\n\n    ctx->end += *srcSizePtr;\n    if (cLevel < 1) cLevel = LZ4HC_CLEVEL_DEFAULT;   /* note : convention is different from lz4frame, maybe something to review */\n    cLevel = MIN(LZ4HC_CLEVEL_MAX, cLevel);\n    {   cParams_t const cParam = clTable[cLevel];\n        HCfavor_e const favor = ctx->favorDecSpeed ? favorDecompressionSpeed : favorCompressionRatio;\n        int result;\n\n        if (cParam.strat == lz4hc) {\n            result = LZ4HC_compress_hashChain(ctx,\n                                src, dst, srcSizePtr, dstCapacity,\n                                cParam.nbSearches, limit, dict);\n        } else {\n            assert(cParam.strat == lz4opt);\n            result = LZ4HC_compress_optimal(ctx,\n                                src, dst, srcSizePtr, dstCapacity,\n                                cParam.nbSearches, cParam.targetLength, limit,\n                                cLevel == LZ4HC_CLEVEL_MAX,   /* ultra mode */\n                                dict, favor);\n        }\n        if (result <= 0) ctx->dirty = 1;\n        return result;\n    }\n}\n\nstatic void LZ4HC_setExternalDict(LZ4HC_CCtx_internal* ctxPtr, const BYTE* newBlock);\n\nstatic int\nLZ4HC_compress_generic_noDictCtx (\n        LZ4HC_CCtx_internal* const ctx,\n        const char* const src,\n        char* const dst,\n        int* const srcSizePtr,\n        int const dstCapacity,\n        int cLevel,\n        limitedOutput_directive limit\n        )\n{\n    assert(ctx->dictCtx == NULL);\n    return LZ4HC_compress_generic_internal(ctx, src, dst, srcSizePtr, dstCapacity, cLevel, limit, noDictCtx);\n}\n\nstatic int\nLZ4HC_compress_generic_dictCtx (\n        LZ4HC_CCtx_internal* const ctx,\n        const char* const src,\n        char* const dst,\n        int* const srcSizePtr,\n        int const dstCapacity,\n        int cLevel,\n        limitedOutput_directive limit\n        )\n{\n    const size_t position = (size_t)(ctx->end - ctx->base) - ctx->lowLimit;\n    assert(ctx->dictCtx != NULL);\n    if (position >= 64 KB) {\n        ctx->dictCtx = NULL;\n        return LZ4HC_compress_generic_noDictCtx(ctx, src, dst, srcSizePtr, dstCapacity, cLevel, limit);\n    } else if (position == 0 && *srcSizePtr > 4 KB) {\n        memcpy(ctx, ctx->dictCtx, sizeof(LZ4HC_CCtx_internal));\n        LZ4HC_setExternalDict(ctx, (const BYTE *)src);\n        ctx->compressionLevel = (short)cLevel;\n        return LZ4HC_compress_generic_noDictCtx(ctx, src, dst, srcSizePtr, dstCapacity, cLevel, limit);\n    } else {\n        return LZ4HC_compress_generic_internal(ctx, src, dst, srcSizePtr, dstCapacity, cLevel, limit, usingDictCtxHc);\n    }\n}\n\nstatic int\nLZ4HC_compress_generic (\n        LZ4HC_CCtx_internal* const ctx,\n        const char* const src,\n        char* const dst,\n        int* const srcSizePtr,\n        int const dstCapacity,\n        int cLevel,\n        limitedOutput_directive limit\n        )\n{\n    if (ctx->dictCtx == NULL) {\n        return LZ4HC_compress_generic_noDictCtx(ctx, src, dst, srcSizePtr, dstCapacity, cLevel, limit);\n    } else {\n        return LZ4HC_compress_generic_dictCtx(ctx, src, dst, srcSizePtr, dstCapacity, cLevel, limit);\n    }\n}\n\n\nint LZ4_sizeofStateHC(void) { return (int)sizeof(LZ4_streamHC_t); }\n\nstatic size_t LZ4_streamHC_t_alignment(void)\n{\n#if LZ4_ALIGN_TEST\n    typedef struct { char c; LZ4_streamHC_t t; } t_a;\n    return sizeof(t_a) - sizeof(LZ4_streamHC_t);\n#else\n    return 1;  /* effectively disabled */\n#endif\n}\n\n/* state is presumed correctly initialized,\n * in which case its size and alignment have already been validate */\nint LZ4_compress_HC_extStateHC_fastReset (void* state, const char* src, char* dst, int srcSize, int dstCapacity, int compressionLevel)\n{\n    LZ4HC_CCtx_internal* const ctx = &((LZ4_streamHC_t*)state)->internal_donotuse;\n    if (!LZ4_isAligned(state, LZ4_streamHC_t_alignment())) return 0;\n    LZ4_resetStreamHC_fast((LZ4_streamHC_t*)state, compressionLevel);\n    LZ4HC_init_internal (ctx, (const BYTE*)src);\n    if (dstCapacity < LZ4_compressBound(srcSize))\n        return LZ4HC_compress_generic (ctx, src, dst, &srcSize, dstCapacity, compressionLevel, limitedOutput);\n    else\n        return LZ4HC_compress_generic (ctx, src, dst, &srcSize, dstCapacity, compressionLevel, notLimited);\n}\n\nint LZ4_compress_HC_extStateHC (void* state, const char* src, char* dst, int srcSize, int dstCapacity, int compressionLevel)\n{\n    LZ4_streamHC_t* const ctx = LZ4_initStreamHC(state, sizeof(*ctx));\n    if (ctx==NULL) return 0;   /* init failure */\n    return LZ4_compress_HC_extStateHC_fastReset(state, src, dst, srcSize, dstCapacity, compressionLevel);\n}\n\nint LZ4_compress_HC(const char* src, char* dst, int srcSize, int dstCapacity, int compressionLevel)\n{\n#if defined(LZ4HC_HEAPMODE) && LZ4HC_HEAPMODE==1\n    LZ4_streamHC_t* const statePtr = (LZ4_streamHC_t*)ALLOC(sizeof(LZ4_streamHC_t));\n#else\n    LZ4_streamHC_t state;\n    LZ4_streamHC_t* const statePtr = &state;\n#endif\n    int const cSize = LZ4_compress_HC_extStateHC(statePtr, src, dst, srcSize, dstCapacity, compressionLevel);\n#if defined(LZ4HC_HEAPMODE) && LZ4HC_HEAPMODE==1\n    FREEMEM(statePtr);\n#endif\n    return cSize;\n}\n\n/* state is presumed sized correctly (>= sizeof(LZ4_streamHC_t)) */\nint LZ4_compress_HC_destSize(void* state, const char* source, char* dest, int* sourceSizePtr, int targetDestSize, int cLevel)\n{\n    LZ4_streamHC_t* const ctx = LZ4_initStreamHC(state, sizeof(*ctx));\n    if (ctx==NULL) return 0;   /* init failure */\n    LZ4HC_init_internal(&ctx->internal_donotuse, (const BYTE*) source);\n    LZ4_setCompressionLevel(ctx, cLevel);\n    return LZ4HC_compress_generic(&ctx->internal_donotuse, source, dest, sourceSizePtr, targetDestSize, cLevel, fillOutput);\n}\n\n\n\n/**************************************\n*  Streaming Functions\n**************************************/\n/* allocation */\nLZ4_streamHC_t* LZ4_createStreamHC(void)\n{\n    LZ4_streamHC_t* const state =\n        (LZ4_streamHC_t*)ALLOC_AND_ZERO(sizeof(LZ4_streamHC_t));\n    if (state == NULL) return NULL;\n    LZ4_setCompressionLevel(state, LZ4HC_CLEVEL_DEFAULT);\n    return state;\n}\n\nint LZ4_freeStreamHC (LZ4_streamHC_t* LZ4_streamHCPtr)\n{\n    DEBUGLOG(4, \"LZ4_freeStreamHC(%p)\", LZ4_streamHCPtr);\n    if (!LZ4_streamHCPtr) return 0;  /* support free on NULL */\n    FREEMEM(LZ4_streamHCPtr);\n    return 0;\n}\n\n\nLZ4_streamHC_t* LZ4_initStreamHC (void* buffer, size_t size)\n{\n    LZ4_streamHC_t* const LZ4_streamHCPtr = (LZ4_streamHC_t*)buffer;\n    /* if compilation fails here, LZ4_STREAMHCSIZE must be increased */\n    LZ4_STATIC_ASSERT(sizeof(LZ4HC_CCtx_internal) <= LZ4_STREAMHCSIZE);\n    DEBUGLOG(4, \"LZ4_initStreamHC(%p, %u)\", buffer, (unsigned)size);\n    /* check conditions */\n    if (buffer == NULL) return NULL;\n    if (size < sizeof(LZ4_streamHC_t)) return NULL;\n    if (!LZ4_isAligned(buffer, LZ4_streamHC_t_alignment())) return NULL;\n    /* init */\n    { LZ4HC_CCtx_internal* const hcstate = &(LZ4_streamHCPtr->internal_donotuse);\n      MEM_INIT(hcstate, 0, sizeof(*hcstate)); }\n    LZ4_setCompressionLevel(LZ4_streamHCPtr, LZ4HC_CLEVEL_DEFAULT);\n    return LZ4_streamHCPtr;\n}\n\n/* just a stub */\nvoid LZ4_resetStreamHC (LZ4_streamHC_t* LZ4_streamHCPtr, int compressionLevel)\n{\n    LZ4_initStreamHC(LZ4_streamHCPtr, sizeof(*LZ4_streamHCPtr));\n    LZ4_setCompressionLevel(LZ4_streamHCPtr, compressionLevel);\n}\n\nvoid LZ4_resetStreamHC_fast (LZ4_streamHC_t* LZ4_streamHCPtr, int compressionLevel)\n{\n    DEBUGLOG(4, \"LZ4_resetStreamHC_fast(%p, %d)\", LZ4_streamHCPtr, compressionLevel);\n    if (LZ4_streamHCPtr->internal_donotuse.dirty) {\n        LZ4_initStreamHC(LZ4_streamHCPtr, sizeof(*LZ4_streamHCPtr));\n    } else {\n        /* preserve end - base : can trigger clearTable's threshold */\n        LZ4_streamHCPtr->internal_donotuse.end -= (uptrval)LZ4_streamHCPtr->internal_donotuse.base;\n        LZ4_streamHCPtr->internal_donotuse.base = NULL;\n        LZ4_streamHCPtr->internal_donotuse.dictCtx = NULL;\n    }\n    LZ4_setCompressionLevel(LZ4_streamHCPtr, compressionLevel);\n}\n\nvoid LZ4_setCompressionLevel(LZ4_streamHC_t* LZ4_streamHCPtr, int compressionLevel)\n{\n    DEBUGLOG(5, \"LZ4_setCompressionLevel(%p, %d)\", LZ4_streamHCPtr, compressionLevel);\n    if (compressionLevel < 1) compressionLevel = LZ4HC_CLEVEL_DEFAULT;\n    if (compressionLevel > LZ4HC_CLEVEL_MAX) compressionLevel = LZ4HC_CLEVEL_MAX;\n    LZ4_streamHCPtr->internal_donotuse.compressionLevel = (short)compressionLevel;\n}\n\nvoid LZ4_favorDecompressionSpeed(LZ4_streamHC_t* LZ4_streamHCPtr, int favor)\n{\n    LZ4_streamHCPtr->internal_donotuse.favorDecSpeed = (favor!=0);\n}\n\n/* LZ4_loadDictHC() :\n * LZ4_streamHCPtr is presumed properly initialized */\nint LZ4_loadDictHC (LZ4_streamHC_t* LZ4_streamHCPtr,\n              const char* dictionary, int dictSize)\n{\n    LZ4HC_CCtx_internal* const ctxPtr = &LZ4_streamHCPtr->internal_donotuse;\n    DEBUGLOG(4, \"LZ4_loadDictHC(ctx:%p, dict:%p, dictSize:%d)\", LZ4_streamHCPtr, dictionary, dictSize);\n    assert(LZ4_streamHCPtr != NULL);\n    if (dictSize > 64 KB) {\n        dictionary += (size_t)dictSize - 64 KB;\n        dictSize = 64 KB;\n    }\n    /* need a full initialization, there are bad side-effects when using resetFast() */\n    {   int const cLevel = ctxPtr->compressionLevel;\n        LZ4_initStreamHC(LZ4_streamHCPtr, sizeof(*LZ4_streamHCPtr));\n        LZ4_setCompressionLevel(LZ4_streamHCPtr, cLevel);\n    }\n    LZ4HC_init_internal (ctxPtr, (const BYTE*)dictionary);\n    ctxPtr->end = (const BYTE*)dictionary + dictSize;\n    if (dictSize >= 4) LZ4HC_Insert (ctxPtr, ctxPtr->end-3);\n    return dictSize;\n}\n\nvoid LZ4_attach_HC_dictionary(LZ4_streamHC_t *working_stream, const LZ4_streamHC_t *dictionary_stream) {\n    working_stream->internal_donotuse.dictCtx = dictionary_stream != NULL ? &(dictionary_stream->internal_donotuse) : NULL;\n}\n\n/* compression */\n\nstatic void LZ4HC_setExternalDict(LZ4HC_CCtx_internal* ctxPtr, const BYTE* newBlock)\n{\n    DEBUGLOG(4, \"LZ4HC_setExternalDict(%p, %p)\", ctxPtr, newBlock);\n    if (ctxPtr->end >= ctxPtr->base + ctxPtr->dictLimit + 4)\n        LZ4HC_Insert (ctxPtr, ctxPtr->end-3);   /* Referencing remaining dictionary content */\n\n    /* Only one memory segment for extDict, so any previous extDict is lost at this stage */\n    ctxPtr->lowLimit  = ctxPtr->dictLimit;\n    ctxPtr->dictLimit = (U32)(ctxPtr->end - ctxPtr->base);\n    ctxPtr->dictBase  = ctxPtr->base;\n    ctxPtr->base = newBlock - ctxPtr->dictLimit;\n    ctxPtr->end  = newBlock;\n    ctxPtr->nextToUpdate = ctxPtr->dictLimit;   /* match referencing will resume from there */\n\n    /* cannot reference an extDict and a dictCtx at the same time */\n    ctxPtr->dictCtx = NULL;\n}\n\nstatic int\nLZ4_compressHC_continue_generic (LZ4_streamHC_t* LZ4_streamHCPtr,\n                                 const char* src, char* dst,\n                                 int* srcSizePtr, int dstCapacity,\n                                 limitedOutput_directive limit)\n{\n    LZ4HC_CCtx_internal* const ctxPtr = &LZ4_streamHCPtr->internal_donotuse;\n    DEBUGLOG(5, \"LZ4_compressHC_continue_generic(ctx=%p, src=%p, srcSize=%d, limit=%d)\",\n                LZ4_streamHCPtr, src, *srcSizePtr, limit);\n    assert(ctxPtr != NULL);\n    /* auto-init if forgotten */\n    if (ctxPtr->base == NULL) LZ4HC_init_internal (ctxPtr, (const BYTE*) src);\n\n    /* Check overflow */\n    if ((size_t)(ctxPtr->end - ctxPtr->base) > 2 GB) {\n        size_t dictSize = (size_t)(ctxPtr->end - ctxPtr->base) - ctxPtr->dictLimit;\n        if (dictSize > 64 KB) dictSize = 64 KB;\n        LZ4_loadDictHC(LZ4_streamHCPtr, (const char*)(ctxPtr->end) - dictSize, (int)dictSize);\n    }\n\n    /* Check if blocks follow each other */\n    if ((const BYTE*)src != ctxPtr->end)\n        LZ4HC_setExternalDict(ctxPtr, (const BYTE*)src);\n\n    /* Check overlapping input/dictionary space */\n    {   const BYTE* sourceEnd = (const BYTE*) src + *srcSizePtr;\n        const BYTE* const dictBegin = ctxPtr->dictBase + ctxPtr->lowLimit;\n        const BYTE* const dictEnd   = ctxPtr->dictBase + ctxPtr->dictLimit;\n        if ((sourceEnd > dictBegin) && ((const BYTE*)src < dictEnd)) {\n            if (sourceEnd > dictEnd) sourceEnd = dictEnd;\n            ctxPtr->lowLimit = (U32)(sourceEnd - ctxPtr->dictBase);\n            if (ctxPtr->dictLimit - ctxPtr->lowLimit < 4) ctxPtr->lowLimit = ctxPtr->dictLimit;\n    }   }\n\n    return LZ4HC_compress_generic (ctxPtr, src, dst, srcSizePtr, dstCapacity, ctxPtr->compressionLevel, limit);\n}\n\nint LZ4_compress_HC_continue (LZ4_streamHC_t* LZ4_streamHCPtr, const char* src, char* dst, int srcSize, int dstCapacity)\n{\n    if (dstCapacity < LZ4_compressBound(srcSize))\n        return LZ4_compressHC_continue_generic (LZ4_streamHCPtr, src, dst, &srcSize, dstCapacity, limitedOutput);\n    else\n        return LZ4_compressHC_continue_generic (LZ4_streamHCPtr, src, dst, &srcSize, dstCapacity, notLimited);\n}\n\nint LZ4_compress_HC_continue_destSize (LZ4_streamHC_t* LZ4_streamHCPtr, const char* src, char* dst, int* srcSizePtr, int targetDestSize)\n{\n    return LZ4_compressHC_continue_generic(LZ4_streamHCPtr, src, dst, srcSizePtr, targetDestSize, fillOutput);\n}\n\n\n\n/* LZ4_saveDictHC :\n * save history content\n * into a user-provided buffer\n * which is then used to continue compression\n */\nint LZ4_saveDictHC (LZ4_streamHC_t* LZ4_streamHCPtr, char* safeBuffer, int dictSize)\n{\n    LZ4HC_CCtx_internal* const streamPtr = &LZ4_streamHCPtr->internal_donotuse;\n    int const prefixSize = (int)(streamPtr->end - (streamPtr->base + streamPtr->dictLimit));\n    DEBUGLOG(5, \"LZ4_saveDictHC(%p, %p, %d)\", LZ4_streamHCPtr, safeBuffer, dictSize);\n    assert(prefixSize >= 0);\n    if (dictSize > 64 KB) dictSize = 64 KB;\n    if (dictSize < 4) dictSize = 0;\n    if (dictSize > prefixSize) dictSize = prefixSize;\n    if (safeBuffer == NULL) assert(dictSize == 0);\n    if (dictSize > 0)\n        memmove(safeBuffer, streamPtr->end - dictSize, dictSize);\n    {   U32 const endIndex = (U32)(streamPtr->end - streamPtr->base);\n        streamPtr->end = (const BYTE*)safeBuffer + dictSize;\n        streamPtr->base = streamPtr->end - endIndex;\n        streamPtr->dictLimit = endIndex - (U32)dictSize;\n        streamPtr->lowLimit = endIndex - (U32)dictSize;\n        if (streamPtr->nextToUpdate < streamPtr->dictLimit)\n            streamPtr->nextToUpdate = streamPtr->dictLimit;\n    }\n    return dictSize;\n}\n\n\n/***************************************************\n*  Deprecated Functions\n***************************************************/\n\n/* These functions currently generate deprecation warnings */\n\n/* Wrappers for deprecated compression functions */\nint LZ4_compressHC(const char* src, char* dst, int srcSize) { return LZ4_compress_HC (src, dst, srcSize, LZ4_compressBound(srcSize), 0); }\nint LZ4_compressHC_limitedOutput(const char* src, char* dst, int srcSize, int maxDstSize) { return LZ4_compress_HC(src, dst, srcSize, maxDstSize, 0); }\nint LZ4_compressHC2(const char* src, char* dst, int srcSize, int cLevel) { return LZ4_compress_HC (src, dst, srcSize, LZ4_compressBound(srcSize), cLevel); }\nint LZ4_compressHC2_limitedOutput(const char* src, char* dst, int srcSize, int maxDstSize, int cLevel) { return LZ4_compress_HC(src, dst, srcSize, maxDstSize, cLevel); }\nint LZ4_compressHC_withStateHC (void* state, const char* src, char* dst, int srcSize) { return LZ4_compress_HC_extStateHC (state, src, dst, srcSize, LZ4_compressBound(srcSize), 0); }\nint LZ4_compressHC_limitedOutput_withStateHC (void* state, const char* src, char* dst, int srcSize, int maxDstSize) { return LZ4_compress_HC_extStateHC (state, src, dst, srcSize, maxDstSize, 0); }\nint LZ4_compressHC2_withStateHC (void* state, const char* src, char* dst, int srcSize, int cLevel) { return LZ4_compress_HC_extStateHC(state, src, dst, srcSize, LZ4_compressBound(srcSize), cLevel); }\nint LZ4_compressHC2_limitedOutput_withStateHC (void* state, const char* src, char* dst, int srcSize, int maxDstSize, int cLevel) { return LZ4_compress_HC_extStateHC(state, src, dst, srcSize, maxDstSize, cLevel); }\nint LZ4_compressHC_continue (LZ4_streamHC_t* ctx, const char* src, char* dst, int srcSize) { return LZ4_compress_HC_continue (ctx, src, dst, srcSize, LZ4_compressBound(srcSize)); }\nint LZ4_compressHC_limitedOutput_continue (LZ4_streamHC_t* ctx, const char* src, char* dst, int srcSize, int maxDstSize) { return LZ4_compress_HC_continue (ctx, src, dst, srcSize, maxDstSize); }\n\n\n/* Deprecated streaming functions */\nint LZ4_sizeofStreamStateHC(void) { return LZ4_STREAMHCSIZE; }\n\n/* state is presumed correctly sized, aka >= sizeof(LZ4_streamHC_t)\n * @return : 0 on success, !=0 if error */\nint LZ4_resetStreamStateHC(void* state, char* inputBuffer)\n{\n    LZ4_streamHC_t* const hc4 = LZ4_initStreamHC(state, sizeof(*hc4));\n    if (hc4 == NULL) return 1;   /* init failed */\n    LZ4HC_init_internal (&hc4->internal_donotuse, (const BYTE*)inputBuffer);\n    return 0;\n}\n\nvoid* LZ4_createHC (const char* inputBuffer)\n{\n    LZ4_streamHC_t* const hc4 = LZ4_createStreamHC();\n    if (hc4 == NULL) return NULL;   /* not enough memory */\n    LZ4HC_init_internal (&hc4->internal_donotuse, (const BYTE*)inputBuffer);\n    return hc4;\n}\n\nint LZ4_freeHC (void* LZ4HC_Data)\n{\n    if (!LZ4HC_Data) return 0;  /* support free on NULL */\n    FREEMEM(LZ4HC_Data);\n    return 0;\n}\n\nint LZ4_compressHC2_continue (void* LZ4HC_Data, const char* src, char* dst, int srcSize, int cLevel)\n{\n    return LZ4HC_compress_generic (&((LZ4_streamHC_t*)LZ4HC_Data)->internal_donotuse, src, dst, &srcSize, 0, cLevel, notLimited);\n}\n\nint LZ4_compressHC2_limitedOutput_continue (void* LZ4HC_Data, const char* src, char* dst, int srcSize, int dstCapacity, int cLevel)\n{\n    return LZ4HC_compress_generic (&((LZ4_streamHC_t*)LZ4HC_Data)->internal_donotuse, src, dst, &srcSize, dstCapacity, cLevel, limitedOutput);\n}\n\nchar* LZ4_slideInputBufferHC(void* LZ4HC_Data)\n{\n    LZ4_streamHC_t *ctx = (LZ4_streamHC_t*)LZ4HC_Data;\n    const BYTE *bufferStart = ctx->internal_donotuse.base + ctx->internal_donotuse.lowLimit;\n    LZ4_resetStreamHC_fast(ctx, ctx->internal_donotuse.compressionLevel);\n    /* avoid const char * -> char * conversion warning :( */\n    return (char *)(uptrval)bufferStart;\n}\n\n\n/* ================================================\n *  LZ4 Optimal parser (levels [LZ4HC_CLEVEL_OPT_MIN - LZ4HC_CLEVEL_MAX])\n * ===============================================*/\ntypedef struct {\n    int price;\n    int off;\n    int mlen;\n    int litlen;\n} LZ4HC_optimal_t;\n\n/* price in bytes */\nLZ4_FORCE_INLINE int LZ4HC_literalsPrice(int const litlen)\n{\n    int price = litlen;\n    assert(litlen >= 0);\n    if (litlen >= (int)RUN_MASK)\n        price += 1 + ((litlen-(int)RUN_MASK) / 255);\n    return price;\n}\n\n\n/* requires mlen >= MINMATCH */\nLZ4_FORCE_INLINE int LZ4HC_sequencePrice(int litlen, int mlen)\n{\n    int price = 1 + 2 ; /* token + 16-bit offset */\n    assert(litlen >= 0);\n    assert(mlen >= MINMATCH);\n\n    price += LZ4HC_literalsPrice(litlen);\n\n    if (mlen >= (int)(ML_MASK+MINMATCH))\n        price += 1 + ((mlen-(int)(ML_MASK+MINMATCH)) / 255);\n\n    return price;\n}\n\n\ntypedef struct {\n    int off;\n    int len;\n} LZ4HC_match_t;\n\nLZ4_FORCE_INLINE LZ4HC_match_t\nLZ4HC_FindLongerMatch(LZ4HC_CCtx_internal* const ctx,\n                      const BYTE* ip, const BYTE* const iHighLimit,\n                      int minLen, int nbSearches,\n                      const dictCtx_directive dict,\n                      const HCfavor_e favorDecSpeed)\n{\n    LZ4HC_match_t match = { 0 , 0 };\n    const BYTE* matchPtr = NULL;\n    /* note : LZ4HC_InsertAndGetWiderMatch() is able to modify the starting position of a match (*startpos),\n     * but this won't be the case here, as we define iLowLimit==ip,\n     * so LZ4HC_InsertAndGetWiderMatch() won't be allowed to search past ip */\n    int matchLength = LZ4HC_InsertAndGetWiderMatch(ctx, ip, ip, iHighLimit, minLen, &matchPtr, &ip, nbSearches, 1 /*patternAnalysis*/, 1 /*chainSwap*/, dict, favorDecSpeed);\n    if (matchLength <= minLen) return match;\n    if (favorDecSpeed) {\n        if ((matchLength>18) & (matchLength<=36)) matchLength=18;   /* favor shortcut */\n    }\n    match.len = matchLength;\n    match.off = (int)(ip-matchPtr);\n    return match;\n}\n\n\nstatic int LZ4HC_compress_optimal ( LZ4HC_CCtx_internal* ctx,\n                                    const char* const source,\n                                    char* dst,\n                                    int* srcSizePtr,\n                                    int dstCapacity,\n                                    int const nbSearches,\n                                    size_t sufficient_len,\n                                    const limitedOutput_directive limit,\n                                    int const fullUpdate,\n                                    const dictCtx_directive dict,\n                                    const HCfavor_e favorDecSpeed)\n{\n    int retval = 0;\n#define TRAILING_LITERALS 3\n#ifdef LZ4HC_HEAPMODE\n    LZ4HC_optimal_t* const opt = (LZ4HC_optimal_t*)ALLOC(sizeof(LZ4HC_optimal_t) * (LZ4_OPT_NUM + TRAILING_LITERALS));\n#else\n    LZ4HC_optimal_t opt[LZ4_OPT_NUM + TRAILING_LITERALS];   /* ~64 KB, which is a bit large for stack... */\n#endif\n\n    const BYTE* ip = (const BYTE*) source;\n    const BYTE* anchor = ip;\n    const BYTE* const iend = ip + *srcSizePtr;\n    const BYTE* const mflimit = iend - MFLIMIT;\n    const BYTE* const matchlimit = iend - LASTLITERALS;\n    BYTE* op = (BYTE*) dst;\n    BYTE* opSaved = (BYTE*) dst;\n    BYTE* oend = op + dstCapacity;\n    int ovml = MINMATCH;  /* overflow - last sequence */\n    const BYTE* ovref = NULL;\n\n    /* init */\n#ifdef LZ4HC_HEAPMODE\n    if (opt == NULL) goto _return_label;\n#endif\n    DEBUGLOG(5, \"LZ4HC_compress_optimal(dst=%p, dstCapa=%u)\", dst, (unsigned)dstCapacity);\n    *srcSizePtr = 0;\n    if (limit == fillOutput) oend -= LASTLITERALS;   /* Hack for support LZ4 format restriction */\n    if (sufficient_len >= LZ4_OPT_NUM) sufficient_len = LZ4_OPT_NUM-1;\n\n    /* Main Loop */\n    while (ip <= mflimit) {\n         int const llen = (int)(ip - anchor);\n         int best_mlen, best_off;\n         int cur, last_match_pos = 0;\n\n         LZ4HC_match_t const firstMatch = LZ4HC_FindLongerMatch(ctx, ip, matchlimit, MINMATCH-1, nbSearches, dict, favorDecSpeed);\n         if (firstMatch.len==0) { ip++; continue; }\n\n         if ((size_t)firstMatch.len > sufficient_len) {\n             /* good enough solution : immediate encoding */\n             int const firstML = firstMatch.len;\n             const BYTE* const matchPos = ip - firstMatch.off;\n             opSaved = op;\n             if ( LZ4HC_encodeSequence(UPDATABLE(ip, op, anchor), firstML, matchPos, limit, oend) ) {  /* updates ip, op and anchor */\n                 ovml = firstML;\n                 ovref = matchPos;\n                 goto _dest_overflow;\n             }\n             continue;\n         }\n\n         /* set prices for first positions (literals) */\n         {   int rPos;\n             for (rPos = 0 ; rPos < MINMATCH ; rPos++) {\n                 int const cost = LZ4HC_literalsPrice(llen + rPos);\n                 opt[rPos].mlen = 1;\n                 opt[rPos].off = 0;\n                 opt[rPos].litlen = llen + rPos;\n                 opt[rPos].price = cost;\n                 DEBUGLOG(7, \"rPos:%3i => price:%3i (litlen=%i) -- initial setup\",\n                             rPos, cost, opt[rPos].litlen);\n         }   }\n         /* set prices using initial match */\n         {   int mlen = MINMATCH;\n             int const matchML = firstMatch.len;   /* necessarily < sufficient_len < LZ4_OPT_NUM */\n             int const offset = firstMatch.off;\n             assert(matchML < LZ4_OPT_NUM);\n             for ( ; mlen <= matchML ; mlen++) {\n                 int const cost = LZ4HC_sequencePrice(llen, mlen);\n                 opt[mlen].mlen = mlen;\n                 opt[mlen].off = offset;\n                 opt[mlen].litlen = llen;\n                 opt[mlen].price = cost;\n                 DEBUGLOG(7, \"rPos:%3i => price:%3i (matchlen=%i) -- initial setup\",\n                             mlen, cost, mlen);\n         }   }\n         last_match_pos = firstMatch.len;\n         {   int addLit;\n             for (addLit = 1; addLit <= TRAILING_LITERALS; addLit ++) {\n                 opt[last_match_pos+addLit].mlen = 1; /* literal */\n                 opt[last_match_pos+addLit].off = 0;\n                 opt[last_match_pos+addLit].litlen = addLit;\n                 opt[last_match_pos+addLit].price = opt[last_match_pos].price + LZ4HC_literalsPrice(addLit);\n                 DEBUGLOG(7, \"rPos:%3i => price:%3i (litlen=%i) -- initial setup\",\n                             last_match_pos+addLit, opt[last_match_pos+addLit].price, addLit);\n         }   }\n\n         /* check further positions */\n         for (cur = 1; cur < last_match_pos; cur++) {\n             const BYTE* const curPtr = ip + cur;\n             LZ4HC_match_t newMatch;\n\n             if (curPtr > mflimit) break;\n             DEBUGLOG(7, \"rPos:%u[%u] vs [%u]%u\",\n                     cur, opt[cur].price, opt[cur+1].price, cur+1);\n             if (fullUpdate) {\n                 /* not useful to search here if next position has same (or lower) cost */\n                 if ( (opt[cur+1].price <= opt[cur].price)\n                   /* in some cases, next position has same cost, but cost rises sharply after, so a small match would still be beneficial */\n                   && (opt[cur+MINMATCH].price < opt[cur].price + 3/*min seq price*/) )\n                     continue;\n             } else {\n                 /* not useful to search here if next position has same (or lower) cost */\n                 if (opt[cur+1].price <= opt[cur].price) continue;\n             }\n\n             DEBUGLOG(7, \"search at rPos:%u\", cur);\n             if (fullUpdate)\n                 newMatch = LZ4HC_FindLongerMatch(ctx, curPtr, matchlimit, MINMATCH-1, nbSearches, dict, favorDecSpeed);\n             else\n                 /* only test matches of minimum length; slightly faster, but misses a few bytes */\n                 newMatch = LZ4HC_FindLongerMatch(ctx, curPtr, matchlimit, last_match_pos - cur, nbSearches, dict, favorDecSpeed);\n             if (!newMatch.len) continue;\n\n             if ( ((size_t)newMatch.len > sufficient_len)\n               || (newMatch.len + cur >= LZ4_OPT_NUM) ) {\n                 /* immediate encoding */\n                 best_mlen = newMatch.len;\n                 best_off = newMatch.off;\n                 last_match_pos = cur + 1;\n                 goto encode;\n             }\n\n             /* before match : set price with literals at beginning */\n             {   int const baseLitlen = opt[cur].litlen;\n                 int litlen;\n                 for (litlen = 1; litlen < MINMATCH; litlen++) {\n                     int const price = opt[cur].price - LZ4HC_literalsPrice(baseLitlen) + LZ4HC_literalsPrice(baseLitlen+litlen);\n                     int const pos = cur + litlen;\n                     if (price < opt[pos].price) {\n                         opt[pos].mlen = 1; /* literal */\n                         opt[pos].off = 0;\n                         opt[pos].litlen = baseLitlen+litlen;\n                         opt[pos].price = price;\n                         DEBUGLOG(7, \"rPos:%3i => price:%3i (litlen=%i)\",\n                                     pos, price, opt[pos].litlen);\n             }   }   }\n\n             /* set prices using match at position = cur */\n             {   int const matchML = newMatch.len;\n                 int ml = MINMATCH;\n\n                 assert(cur + newMatch.len < LZ4_OPT_NUM);\n                 for ( ; ml <= matchML ; ml++) {\n                     int const pos = cur + ml;\n                     int const offset = newMatch.off;\n                     int price;\n                     int ll;\n                     DEBUGLOG(7, \"testing price rPos %i (last_match_pos=%i)\",\n                                 pos, last_match_pos);\n                     if (opt[cur].mlen == 1) {\n                         ll = opt[cur].litlen;\n                         price = ((cur > ll) ? opt[cur - ll].price : 0)\n                               + LZ4HC_sequencePrice(ll, ml);\n                     } else {\n                         ll = 0;\n                         price = opt[cur].price + LZ4HC_sequencePrice(0, ml);\n                     }\n\n                    assert((U32)favorDecSpeed <= 1);\n                     if (pos > last_match_pos+TRAILING_LITERALS\n                      || price <= opt[pos].price - (int)favorDecSpeed) {\n                         DEBUGLOG(7, \"rPos:%3i => price:%3i (matchlen=%i)\",\n                                     pos, price, ml);\n                         assert(pos < LZ4_OPT_NUM);\n                         if ( (ml == matchML)  /* last pos of last match */\n                           && (last_match_pos < pos) )\n                             last_match_pos = pos;\n                         opt[pos].mlen = ml;\n                         opt[pos].off = offset;\n                         opt[pos].litlen = ll;\n                         opt[pos].price = price;\n             }   }   }\n             /* complete following positions with literals */\n             {   int addLit;\n                 for (addLit = 1; addLit <= TRAILING_LITERALS; addLit ++) {\n                     opt[last_match_pos+addLit].mlen = 1; /* literal */\n                     opt[last_match_pos+addLit].off = 0;\n                     opt[last_match_pos+addLit].litlen = addLit;\n                     opt[last_match_pos+addLit].price = opt[last_match_pos].price + LZ4HC_literalsPrice(addLit);\n                     DEBUGLOG(7, \"rPos:%3i => price:%3i (litlen=%i)\", last_match_pos+addLit, opt[last_match_pos+addLit].price, addLit);\n             }   }\n         }  /* for (cur = 1; cur <= last_match_pos; cur++) */\n\n         assert(last_match_pos < LZ4_OPT_NUM + TRAILING_LITERALS);\n         best_mlen = opt[last_match_pos].mlen;\n         best_off = opt[last_match_pos].off;\n         cur = last_match_pos - best_mlen;\n\nencode: /* cur, last_match_pos, best_mlen, best_off must be set */\n         assert(cur < LZ4_OPT_NUM);\n         assert(last_match_pos >= 1);  /* == 1 when only one candidate */\n         DEBUGLOG(6, \"reverse traversal, looking for shortest path (last_match_pos=%i)\", last_match_pos);\n         {   int candidate_pos = cur;\n             int selected_matchLength = best_mlen;\n             int selected_offset = best_off;\n             while (1) {  /* from end to beginning */\n                 int const next_matchLength = opt[candidate_pos].mlen;  /* can be 1, means literal */\n                 int const next_offset = opt[candidate_pos].off;\n                 DEBUGLOG(7, \"pos %i: sequence length %i\", candidate_pos, selected_matchLength);\n                 opt[candidate_pos].mlen = selected_matchLength;\n                 opt[candidate_pos].off = selected_offset;\n                 selected_matchLength = next_matchLength;\n                 selected_offset = next_offset;\n                 if (next_matchLength > candidate_pos) break; /* last match elected, first match to encode */\n                 assert(next_matchLength > 0);  /* can be 1, means literal */\n                 candidate_pos -= next_matchLength;\n         }   }\n\n         /* encode all recorded sequences in order */\n         {   int rPos = 0;  /* relative position (to ip) */\n             while (rPos < last_match_pos) {\n                 int const ml = opt[rPos].mlen;\n                 int const offset = opt[rPos].off;\n                 if (ml == 1) { ip++; rPos++; continue; }  /* literal; note: can end up with several literals, in which case, skip them */\n                 rPos += ml;\n                 assert(ml >= MINMATCH);\n                 assert((offset >= 1) && (offset <= LZ4_DISTANCE_MAX));\n                 opSaved = op;\n                 if ( LZ4HC_encodeSequence(UPDATABLE(ip, op, anchor), ml, ip - offset, limit, oend) ) {  /* updates ip, op and anchor */\n                     ovml = ml;\n                     ovref = ip - offset;\n                     goto _dest_overflow;\n         }   }   }\n     }  /* while (ip <= mflimit) */\n\n_last_literals:\n     /* Encode Last Literals */\n     {   size_t lastRunSize = (size_t)(iend - anchor);  /* literals */\n         size_t llAdd = (lastRunSize + 255 - RUN_MASK) / 255;\n         size_t const totalSize = 1 + llAdd + lastRunSize;\n         if (limit == fillOutput) oend += LASTLITERALS;  /* restore correct value */\n         if (limit && (op + totalSize > oend)) {\n             if (limit == limitedOutput) { /* Check output limit */\n                retval = 0;\n                goto _return_label;\n             }\n             /* adapt lastRunSize to fill 'dst' */\n             lastRunSize  = (size_t)(oend - op) - 1 /*token*/;\n             llAdd = (lastRunSize + 256 - RUN_MASK) / 256;\n             lastRunSize -= llAdd;\n         }\n         DEBUGLOG(6, \"Final literal run : %i literals\", (int)lastRunSize);\n         ip = anchor + lastRunSize; /* can be != iend if limit==fillOutput */\n\n         if (lastRunSize >= RUN_MASK) {\n             size_t accumulator = lastRunSize - RUN_MASK;\n             *op++ = (RUN_MASK << ML_BITS);\n             for(; accumulator >= 255 ; accumulator -= 255) *op++ = 255;\n             *op++ = (BYTE) accumulator;\n         } else {\n             *op++ = (BYTE)(lastRunSize << ML_BITS);\n         }\n         memcpy(op, anchor, lastRunSize);\n         op += lastRunSize;\n     }\n\n     /* End */\n     *srcSizePtr = (int) (((const char*)ip) - source);\n     retval = (int) ((char*)op-dst);\n     goto _return_label;\n\n_dest_overflow:\nif (limit == fillOutput) {\n     /* Assumption : ip, anchor, ovml and ovref must be set correctly */\n     size_t const ll = (size_t)(ip - anchor);\n     size_t const ll_addbytes = (ll + 240) / 255;\n     size_t const ll_totalCost = 1 + ll_addbytes + ll;\n     BYTE* const maxLitPos = oend - 3; /* 2 for offset, 1 for token */\n     DEBUGLOG(6, \"Last sequence overflowing (only %i bytes remaining)\", (int)(oend-1-opSaved));\n     op = opSaved;  /* restore correct out pointer */\n     if (op + ll_totalCost <= maxLitPos) {\n         /* ll validated; now adjust match length */\n         size_t const bytesLeftForMl = (size_t)(maxLitPos - (op+ll_totalCost));\n         size_t const maxMlSize = MINMATCH + (ML_MASK-1) + (bytesLeftForMl * 255);\n         assert(maxMlSize < INT_MAX); assert(ovml >= 0);\n         if ((size_t)ovml > maxMlSize) ovml = (int)maxMlSize;\n         if ((oend + LASTLITERALS) - (op + ll_totalCost + 2) - 1 + ovml >= MFLIMIT) {\n             DEBUGLOG(6, \"Space to end : %i + ml (%i)\", (int)((oend + LASTLITERALS) - (op + ll_totalCost + 2) - 1), ovml);\n             DEBUGLOG(6, \"Before : ip = %p, anchor = %p\", ip, anchor);\n             LZ4HC_encodeSequence(UPDATABLE(ip, op, anchor), ovml, ovref, notLimited, oend);\n             DEBUGLOG(6, \"After : ip = %p, anchor = %p\", ip, anchor);\n     }   }\n     goto _last_literals;\n}\n_return_label:\n#ifdef LZ4HC_HEAPMODE\n     FREEMEM(opt);\n#endif\n     return retval;\n}\n"
  },
  {
    "path": "external/lz4/lz4hc.h",
    "content": "/*\n   LZ4 HC - High Compression Mode of LZ4\n   Header File\n   Copyright (C) 2011-2017, Yann Collet.\n   BSD 2-Clause License (http://www.opensource.org/licenses/bsd-license.php)\n\n   Redistribution and use in source and binary forms, with or without\n   modification, are permitted provided that the following conditions are\n   met:\n\n       * Redistributions of source code must retain the above copyright\n   notice, this list of conditions and the following disclaimer.\n       * Redistributions in binary form must reproduce the above\n   copyright notice, this list of conditions and the following disclaimer\n   in the documentation and/or other materials provided with the\n   distribution.\n\n   THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\n   \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\n   LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR\n   A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT\n   OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,\n   SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT\n   LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,\n   DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY\n   THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\n   (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE\n   OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n\n   You can contact the author at :\n   - LZ4 source repository : https://github.com/lz4/lz4\n   - LZ4 public forum : https://groups.google.com/forum/#!forum/lz4c\n*/\n#ifndef LZ4_HC_H_19834876238432\n#define LZ4_HC_H_19834876238432\n\n#if defined (__cplusplus)\nextern \"C\" {\n#endif\n\n/* --- Dependency --- */\n/* note : lz4hc requires lz4.h/lz4.c for compilation */\n#include \"lz4.h\"   /* stddef, LZ4LIB_API, LZ4_DEPRECATED */\n\n\n/* --- Useful constants --- */\n#define LZ4HC_CLEVEL_MIN         3\n#define LZ4HC_CLEVEL_DEFAULT     9\n#define LZ4HC_CLEVEL_OPT_MIN    10\n#define LZ4HC_CLEVEL_MAX        12\n\n\n/*-************************************\n *  Block Compression\n **************************************/\n/*! LZ4_compress_HC() :\n *  Compress data from `src` into `dst`, using the powerful but slower \"HC\" algorithm.\n * `dst` must be already allocated.\n *  Compression is guaranteed to succeed if `dstCapacity >= LZ4_compressBound(srcSize)` (see \"lz4.h\")\n *  Max supported `srcSize` value is LZ4_MAX_INPUT_SIZE (see \"lz4.h\")\n * `compressionLevel` : any value between 1 and LZ4HC_CLEVEL_MAX will work.\n *                      Values > LZ4HC_CLEVEL_MAX behave the same as LZ4HC_CLEVEL_MAX.\n * @return : the number of bytes written into 'dst'\n *           or 0 if compression fails.\n */\nLZ4LIB_API int LZ4_compress_HC (const char* src, char* dst, int srcSize, int dstCapacity, int compressionLevel);\n\n\n/* Note :\n *   Decompression functions are provided within \"lz4.h\" (BSD license)\n */\n\n\n/*! LZ4_compress_HC_extStateHC() :\n *  Same as LZ4_compress_HC(), but using an externally allocated memory segment for `state`.\n * `state` size is provided by LZ4_sizeofStateHC().\n *  Memory segment must be aligned on 8-bytes boundaries (which a normal malloc() should do properly).\n */\nLZ4LIB_API int LZ4_sizeofStateHC(void);\nLZ4LIB_API int LZ4_compress_HC_extStateHC(void* stateHC, const char* src, char* dst, int srcSize, int maxDstSize, int compressionLevel);\n\n\n/*! LZ4_compress_HC_destSize() : v1.9.0+\n *  Will compress as much data as possible from `src`\n *  to fit into `targetDstSize` budget.\n *  Result is provided in 2 parts :\n * @return : the number of bytes written into 'dst' (necessarily <= targetDstSize)\n *           or 0 if compression fails.\n * `srcSizePtr` : on success, *srcSizePtr is updated to indicate how much bytes were read from `src`\n */\nLZ4LIB_API int LZ4_compress_HC_destSize(void* stateHC,\n                                  const char* src, char* dst,\n                                        int* srcSizePtr, int targetDstSize,\n                                        int compressionLevel);\n\n\n/*-************************************\n *  Streaming Compression\n *  Bufferless synchronous API\n **************************************/\n typedef union LZ4_streamHC_u LZ4_streamHC_t;   /* incomplete type (defined later) */\n\n/*! LZ4_createStreamHC() and LZ4_freeStreamHC() :\n *  These functions create and release memory for LZ4 HC streaming state.\n *  Newly created states are automatically initialized.\n *  A same state can be used multiple times consecutively,\n *  starting with LZ4_resetStreamHC_fast() to start a new stream of blocks.\n */\nLZ4LIB_API LZ4_streamHC_t* LZ4_createStreamHC(void);\nLZ4LIB_API int             LZ4_freeStreamHC (LZ4_streamHC_t* streamHCPtr);\n\n/*\n  These functions compress data in successive blocks of any size,\n  using previous blocks as dictionary, to improve compression ratio.\n  One key assumption is that previous blocks (up to 64 KB) remain read-accessible while compressing next blocks.\n  There is an exception for ring buffers, which can be smaller than 64 KB.\n  Ring-buffer scenario is automatically detected and handled within LZ4_compress_HC_continue().\n\n  Before starting compression, state must be allocated and properly initialized.\n  LZ4_createStreamHC() does both, though compression level is set to LZ4HC_CLEVEL_DEFAULT.\n\n  Selecting the compression level can be done with LZ4_resetStreamHC_fast() (starts a new stream)\n  or LZ4_setCompressionLevel() (anytime, between blocks in the same stream) (experimental).\n  LZ4_resetStreamHC_fast() only works on states which have been properly initialized at least once,\n  which is automatically the case when state is created using LZ4_createStreamHC().\n\n  After reset, a first \"fictional block\" can be designated as initial dictionary,\n  using LZ4_loadDictHC() (Optional).\n\n  Invoke LZ4_compress_HC_continue() to compress each successive block.\n  The number of blocks is unlimited.\n  Previous input blocks, including initial dictionary when present,\n  must remain accessible and unmodified during compression.\n\n  It's allowed to update compression level anytime between blocks,\n  using LZ4_setCompressionLevel() (experimental).\n\n  'dst' buffer should be sized to handle worst case scenarios\n  (see LZ4_compressBound(), it ensures compression success).\n  In case of failure, the API does not guarantee recovery,\n  so the state _must_ be reset.\n  To ensure compression success\n  whenever `dst` buffer size cannot be made >= LZ4_compressBound(),\n  consider using LZ4_compress_HC_continue_destSize().\n\n  Whenever previous input blocks can't be preserved unmodified in-place during compression of next blocks,\n  it's possible to copy the last blocks into a more stable memory space, using LZ4_saveDictHC().\n  Return value of LZ4_saveDictHC() is the size of dictionary effectively saved into 'safeBuffer' (<= 64 KB)\n\n  After completing a streaming compression,\n  it's possible to start a new stream of blocks, using the same LZ4_streamHC_t state,\n  just by resetting it, using LZ4_resetStreamHC_fast().\n*/\n\nLZ4LIB_API void LZ4_resetStreamHC_fast(LZ4_streamHC_t* streamHCPtr, int compressionLevel);   /* v1.9.0+ */\nLZ4LIB_API int  LZ4_loadDictHC (LZ4_streamHC_t* streamHCPtr, const char* dictionary, int dictSize);\n\nLZ4LIB_API int LZ4_compress_HC_continue (LZ4_streamHC_t* streamHCPtr,\n                                   const char* src, char* dst,\n                                         int srcSize, int maxDstSize);\n\n/*! LZ4_compress_HC_continue_destSize() : v1.9.0+\n *  Similar to LZ4_compress_HC_continue(),\n *  but will read as much data as possible from `src`\n *  to fit into `targetDstSize` budget.\n *  Result is provided into 2 parts :\n * @return : the number of bytes written into 'dst' (necessarily <= targetDstSize)\n *           or 0 if compression fails.\n * `srcSizePtr` : on success, *srcSizePtr will be updated to indicate how much bytes were read from `src`.\n *           Note that this function may not consume the entire input.\n */\nLZ4LIB_API int LZ4_compress_HC_continue_destSize(LZ4_streamHC_t* LZ4_streamHCPtr,\n                                           const char* src, char* dst,\n                                                 int* srcSizePtr, int targetDstSize);\n\nLZ4LIB_API int LZ4_saveDictHC (LZ4_streamHC_t* streamHCPtr, char* safeBuffer, int maxDictSize);\n\n\n\n/*^**********************************************\n * !!!!!!   STATIC LINKING ONLY   !!!!!!\n ***********************************************/\n\n/*-******************************************************************\n * PRIVATE DEFINITIONS :\n * Do not use these definitions directly.\n * They are merely exposed to allow static allocation of `LZ4_streamHC_t`.\n * Declare an `LZ4_streamHC_t` directly, rather than any type below.\n * Even then, only do so in the context of static linking, as definitions may change between versions.\n ********************************************************************/\n\n#define LZ4HC_DICTIONARY_LOGSIZE 16\n#define LZ4HC_MAXD (1<<LZ4HC_DICTIONARY_LOGSIZE)\n#define LZ4HC_MAXD_MASK (LZ4HC_MAXD - 1)\n\n#define LZ4HC_HASH_LOG 15\n#define LZ4HC_HASHTABLESIZE (1 << LZ4HC_HASH_LOG)\n#define LZ4HC_HASH_MASK (LZ4HC_HASHTABLESIZE - 1)\n\n\ntypedef struct LZ4HC_CCtx_internal LZ4HC_CCtx_internal;\nstruct LZ4HC_CCtx_internal\n{\n    LZ4_u32   hashTable[LZ4HC_HASHTABLESIZE];\n    LZ4_u16   chainTable[LZ4HC_MAXD];\n    const LZ4_byte* end;       /* next block here to continue on current prefix */\n    const LZ4_byte* base;      /* All index relative to this position */\n    const LZ4_byte* dictBase;  /* alternate base for extDict */\n    LZ4_u32   dictLimit;       /* below that point, need extDict */\n    LZ4_u32   lowLimit;        /* below that point, no more dict */\n    LZ4_u32   nextToUpdate;    /* index from which to continue dictionary update */\n    short     compressionLevel;\n    LZ4_i8    favorDecSpeed;   /* favor decompression speed if this flag set,\n                                  otherwise, favor compression ratio */\n    LZ4_i8    dirty;           /* stream has to be fully reset if this flag is set */\n    const LZ4HC_CCtx_internal* dictCtx;\n};\n\n\n/* Do not use these definitions directly !\n * Declare or allocate an LZ4_streamHC_t instead.\n */\n#define LZ4_STREAMHCSIZE       262200  /* static size, for inter-version compatibility */\n#define LZ4_STREAMHCSIZE_VOIDP (LZ4_STREAMHCSIZE / sizeof(void*))\nunion LZ4_streamHC_u {\n    void* table[LZ4_STREAMHCSIZE_VOIDP];\n    LZ4HC_CCtx_internal internal_donotuse;\n}; /* previously typedef'd to LZ4_streamHC_t */\n\n/* LZ4_streamHC_t :\n * This structure allows static allocation of LZ4 HC streaming state.\n * This can be used to allocate statically, on state, or as part of a larger structure.\n *\n * Such state **must** be initialized using LZ4_initStreamHC() before first use.\n *\n * Note that invoking LZ4_initStreamHC() is not required when\n * the state was created using LZ4_createStreamHC() (which is recommended).\n * Using the normal builder, a newly created state is automatically initialized.\n *\n * Static allocation shall only be used in combination with static linking.\n */\n\n/* LZ4_initStreamHC() : v1.9.0+\n * Required before first use of a statically allocated LZ4_streamHC_t.\n * Before v1.9.0 : use LZ4_resetStreamHC() instead\n */\nLZ4LIB_API LZ4_streamHC_t* LZ4_initStreamHC (void* buffer, size_t size);\n\n\n/*-************************************\n*  Deprecated Functions\n**************************************/\n/* see lz4.h LZ4_DISABLE_DEPRECATE_WARNINGS to turn off deprecation warnings */\n\n/* deprecated compression functions */\nLZ4_DEPRECATED(\"use LZ4_compress_HC() instead\") LZ4LIB_API int LZ4_compressHC               (const char* source, char* dest, int inputSize);\nLZ4_DEPRECATED(\"use LZ4_compress_HC() instead\") LZ4LIB_API int LZ4_compressHC_limitedOutput (const char* source, char* dest, int inputSize, int maxOutputSize);\nLZ4_DEPRECATED(\"use LZ4_compress_HC() instead\") LZ4LIB_API int LZ4_compressHC2              (const char* source, char* dest, int inputSize, int compressionLevel);\nLZ4_DEPRECATED(\"use LZ4_compress_HC() instead\") LZ4LIB_API int LZ4_compressHC2_limitedOutput(const char* source, char* dest, int inputSize, int maxOutputSize, int compressionLevel);\nLZ4_DEPRECATED(\"use LZ4_compress_HC_extStateHC() instead\") LZ4LIB_API int LZ4_compressHC_withStateHC               (void* state, const char* source, char* dest, int inputSize);\nLZ4_DEPRECATED(\"use LZ4_compress_HC_extStateHC() instead\") LZ4LIB_API int LZ4_compressHC_limitedOutput_withStateHC (void* state, const char* source, char* dest, int inputSize, int maxOutputSize);\nLZ4_DEPRECATED(\"use LZ4_compress_HC_extStateHC() instead\") LZ4LIB_API int LZ4_compressHC2_withStateHC              (void* state, const char* source, char* dest, int inputSize, int compressionLevel);\nLZ4_DEPRECATED(\"use LZ4_compress_HC_extStateHC() instead\") LZ4LIB_API int LZ4_compressHC2_limitedOutput_withStateHC(void* state, const char* source, char* dest, int inputSize, int maxOutputSize, int compressionLevel);\nLZ4_DEPRECATED(\"use LZ4_compress_HC_continue() instead\") LZ4LIB_API int LZ4_compressHC_continue               (LZ4_streamHC_t* LZ4_streamHCPtr, const char* source, char* dest, int inputSize);\nLZ4_DEPRECATED(\"use LZ4_compress_HC_continue() instead\") LZ4LIB_API int LZ4_compressHC_limitedOutput_continue (LZ4_streamHC_t* LZ4_streamHCPtr, const char* source, char* dest, int inputSize, int maxOutputSize);\n\n/* Obsolete streaming functions; degraded functionality; do not use!\n *\n * In order to perform streaming compression, these functions depended on data\n * that is no longer tracked in the state. They have been preserved as well as\n * possible: using them will still produce a correct output. However, use of\n * LZ4_slideInputBufferHC() will truncate the history of the stream, rather\n * than preserve a window-sized chunk of history.\n */\nLZ4_DEPRECATED(\"use LZ4_createStreamHC() instead\") LZ4LIB_API void* LZ4_createHC (const char* inputBuffer);\nLZ4_DEPRECATED(\"use LZ4_saveDictHC() instead\") LZ4LIB_API     char* LZ4_slideInputBufferHC (void* LZ4HC_Data);\nLZ4_DEPRECATED(\"use LZ4_freeStreamHC() instead\") LZ4LIB_API   int   LZ4_freeHC (void* LZ4HC_Data);\nLZ4_DEPRECATED(\"use LZ4_compress_HC_continue() instead\") LZ4LIB_API int LZ4_compressHC2_continue               (void* LZ4HC_Data, const char* source, char* dest, int inputSize, int compressionLevel);\nLZ4_DEPRECATED(\"use LZ4_compress_HC_continue() instead\") LZ4LIB_API int LZ4_compressHC2_limitedOutput_continue (void* LZ4HC_Data, const char* source, char* dest, int inputSize, int maxOutputSize, int compressionLevel);\nLZ4_DEPRECATED(\"use LZ4_createStreamHC() instead\") LZ4LIB_API int   LZ4_sizeofStreamStateHC(void);\nLZ4_DEPRECATED(\"use LZ4_initStreamHC() instead\") LZ4LIB_API  int   LZ4_resetStreamStateHC(void* state, char* inputBuffer);\n\n\n/* LZ4_resetStreamHC() is now replaced by LZ4_initStreamHC().\n * The intention is to emphasize the difference with LZ4_resetStreamHC_fast(),\n * which is now the recommended function to start a new stream of blocks,\n * but cannot be used to initialize a memory segment containing arbitrary garbage data.\n *\n * It is recommended to switch to LZ4_initStreamHC().\n * LZ4_resetStreamHC() will generate deprecation warnings in a future version.\n */\nLZ4LIB_API void LZ4_resetStreamHC (LZ4_streamHC_t* streamHCPtr, int compressionLevel);\n\n\n#if defined (__cplusplus)\n}\n#endif\n\n#endif /* LZ4_HC_H_19834876238432 */\n\n\n/*-**************************************************\n * !!!!!     STATIC LINKING ONLY     !!!!!\n * Following definitions are considered experimental.\n * They should not be linked from DLL,\n * as there is no guarantee of API stability yet.\n * Prototypes will be promoted to \"stable\" status\n * after successfull usage in real-life scenarios.\n ***************************************************/\n#ifdef LZ4_HC_STATIC_LINKING_ONLY   /* protection macro */\n#ifndef LZ4_HC_SLO_098092834\n#define LZ4_HC_SLO_098092834\n\n#define LZ4_STATIC_LINKING_ONLY   /* LZ4LIB_STATIC_API */\n#include \"lz4.h\"\n\n#if defined (__cplusplus)\nextern \"C\" {\n#endif\n\n/*! LZ4_setCompressionLevel() : v1.8.0+ (experimental)\n *  It's possible to change compression level\n *  between successive invocations of LZ4_compress_HC_continue*()\n *  for dynamic adaptation.\n */\nLZ4LIB_STATIC_API void LZ4_setCompressionLevel(\n    LZ4_streamHC_t* LZ4_streamHCPtr, int compressionLevel);\n\n/*! LZ4_favorDecompressionSpeed() : v1.8.2+ (experimental)\n *  Opt. Parser will favor decompression speed over compression ratio.\n *  Only applicable to levels >= LZ4HC_CLEVEL_OPT_MIN.\n */\nLZ4LIB_STATIC_API void LZ4_favorDecompressionSpeed(\n    LZ4_streamHC_t* LZ4_streamHCPtr, int favor);\n\n/*! LZ4_resetStreamHC_fast() : v1.9.0+\n *  When an LZ4_streamHC_t is known to be in a internally coherent state,\n *  it can often be prepared for a new compression with almost no work, only\n *  sometimes falling back to the full, expensive reset that is always required\n *  when the stream is in an indeterminate state (i.e., the reset performed by\n *  LZ4_resetStreamHC()).\n *\n *  LZ4_streamHCs are guaranteed to be in a valid state when:\n *  - returned from LZ4_createStreamHC()\n *  - reset by LZ4_resetStreamHC()\n *  - memset(stream, 0, sizeof(LZ4_streamHC_t))\n *  - the stream was in a valid state and was reset by LZ4_resetStreamHC_fast()\n *  - the stream was in a valid state and was then used in any compression call\n *    that returned success\n *  - the stream was in an indeterminate state and was used in a compression\n *    call that fully reset the state (LZ4_compress_HC_extStateHC()) and that\n *    returned success\n *\n *  Note:\n *  A stream that was last used in a compression call that returned an error\n *  may be passed to this function. However, it will be fully reset, which will\n *  clear any existing history and settings from the context.\n */\nLZ4LIB_STATIC_API void LZ4_resetStreamHC_fast(\n    LZ4_streamHC_t* LZ4_streamHCPtr, int compressionLevel);\n\n/*! LZ4_compress_HC_extStateHC_fastReset() :\n *  A variant of LZ4_compress_HC_extStateHC().\n *\n *  Using this variant avoids an expensive initialization step. It is only safe\n *  to call if the state buffer is known to be correctly initialized already\n *  (see above comment on LZ4_resetStreamHC_fast() for a definition of\n *  \"correctly initialized\"). From a high level, the difference is that this\n *  function initializes the provided state with a call to\n *  LZ4_resetStreamHC_fast() while LZ4_compress_HC_extStateHC() starts with a\n *  call to LZ4_resetStreamHC().\n */\nLZ4LIB_STATIC_API int LZ4_compress_HC_extStateHC_fastReset (\n    void* state,\n    const char* src, char* dst,\n    int srcSize, int dstCapacity,\n    int compressionLevel);\n\n/*! LZ4_attach_HC_dictionary() :\n *  This is an experimental API that allows for the efficient use of a\n *  static dictionary many times.\n *\n *  Rather than re-loading the dictionary buffer into a working context before\n *  each compression, or copying a pre-loaded dictionary's LZ4_streamHC_t into a\n *  working LZ4_streamHC_t, this function introduces a no-copy setup mechanism,\n *  in which the working stream references the dictionary stream in-place.\n *\n *  Several assumptions are made about the state of the dictionary stream.\n *  Currently, only streams which have been prepared by LZ4_loadDictHC() should\n *  be expected to work.\n *\n *  Alternatively, the provided dictionary stream pointer may be NULL, in which\n *  case any existing dictionary stream is unset.\n *\n *  A dictionary should only be attached to a stream without any history (i.e.,\n *  a stream that has just been reset).\n *\n *  The dictionary will remain attached to the working stream only for the\n *  current stream session. Calls to LZ4_resetStreamHC(_fast) will remove the\n *  dictionary context association from the working stream. The dictionary\n *  stream (and source buffer) must remain in-place / accessible / unchanged\n *  through the lifetime of the stream session.\n */\nLZ4LIB_STATIC_API void LZ4_attach_HC_dictionary(\n          LZ4_streamHC_t *working_stream,\n    const LZ4_streamHC_t *dictionary_stream);\n\n#if defined (__cplusplus)\n}\n#endif\n\n#endif   /* LZ4_HC_SLO_098092834 */\n#endif   /* LZ4_HC_STATIC_LINKING_ONLY */\n"
  },
  {
    "path": "external/lz4/xxhash.c",
    "content": "/*\n*  xxHash - Fast Hash algorithm\n*  Copyright (C) 2012-2016, Yann Collet\n*\n*  BSD 2-Clause License (http://www.opensource.org/licenses/bsd-license.php)\n*\n*  Redistribution and use in source and binary forms, with or without\n*  modification, are permitted provided that the following conditions are\n*  met:\n*\n*  * Redistributions of source code must retain the above copyright\n*  notice, this list of conditions and the following disclaimer.\n*  * Redistributions in binary form must reproduce the above\n*  copyright notice, this list of conditions and the following disclaimer\n*  in the documentation and/or other materials provided with the\n*  distribution.\n*\n*  THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\n*  \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\n*  LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR\n*  A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT\n*  OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,\n*  SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT\n*  LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,\n*  DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY\n*  THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\n*  (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE\n*  OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n*\n*  You can contact the author at :\n*  - xxHash homepage: http://www.xxhash.com\n*  - xxHash source repository : https://github.com/Cyan4973/xxHash\n*/\n\n\n/* *************************************\n*  Tuning parameters\n***************************************/\n/*!XXH_FORCE_MEMORY_ACCESS :\n * By default, access to unaligned memory is controlled by `memcpy()`, which is safe and portable.\n * Unfortunately, on some target/compiler combinations, the generated assembly is sub-optimal.\n * The below switch allow to select different access method for improved performance.\n * Method 0 (default) : use `memcpy()`. Safe and portable.\n * Method 1 : `__packed` statement. It depends on compiler extension (ie, not portable).\n *            This method is safe if your compiler supports it, and *generally* as fast or faster than `memcpy`.\n * Method 2 : direct access. This method doesn't depend on compiler but violate C standard.\n *            It can generate buggy code on targets which do not support unaligned memory accesses.\n *            But in some circumstances, it's the only known way to get the most performance (ie GCC + ARMv6)\n * See http://stackoverflow.com/a/32095106/646947 for details.\n * Prefer these methods in priority order (0 > 1 > 2)\n */\n#ifndef XXH_FORCE_MEMORY_ACCESS   /* can be defined externally, on command line for example */\n#  if defined(__GNUC__) && ( defined(__ARM_ARCH_6__) || defined(__ARM_ARCH_6J__) \\\n                        || defined(__ARM_ARCH_6K__) || defined(__ARM_ARCH_6Z__) \\\n                        || defined(__ARM_ARCH_6ZK__) || defined(__ARM_ARCH_6T2__) )\n#    define XXH_FORCE_MEMORY_ACCESS 2\n#  elif (defined(__INTEL_COMPILER) && !defined(_WIN32)) || \\\n  (defined(__GNUC__) && ( defined(__ARM_ARCH_7__) || defined(__ARM_ARCH_7A__) \\\n                    || defined(__ARM_ARCH_7R__) || defined(__ARM_ARCH_7M__) \\\n                    || defined(__ARM_ARCH_7S__) ))\n#    define XXH_FORCE_MEMORY_ACCESS 1\n#  endif\n#endif\n\n/*!XXH_ACCEPT_NULL_INPUT_POINTER :\n * If input pointer is NULL, xxHash default behavior is to dereference it, triggering a segfault.\n * When this macro is enabled, xxHash actively checks input for null pointer.\n * It it is, result for null input pointers is the same as a null-length input.\n */\n#ifndef XXH_ACCEPT_NULL_INPUT_POINTER   /* can be defined externally */\n#  define XXH_ACCEPT_NULL_INPUT_POINTER 0\n#endif\n\n/*!XXH_FORCE_NATIVE_FORMAT :\n * By default, xxHash library provides endian-independent Hash values, based on little-endian convention.\n * Results are therefore identical for little-endian and big-endian CPU.\n * This comes at a performance cost for big-endian CPU, since some swapping is required to emulate little-endian format.\n * Should endian-independence be of no importance for your application, you may set the #define below to 1,\n * to improve speed for Big-endian CPU.\n * This option has no impact on Little_Endian CPU.\n */\n#ifndef XXH_FORCE_NATIVE_FORMAT   /* can be defined externally */\n#  define XXH_FORCE_NATIVE_FORMAT 0\n#endif\n\n/*!XXH_FORCE_ALIGN_CHECK :\n * This is a minor performance trick, only useful with lots of very small keys.\n * It means : check for aligned/unaligned input.\n * The check costs one initial branch per hash;\n * set it to 0 when the input is guaranteed to be aligned,\n * or when alignment doesn't matter for performance.\n */\n#ifndef XXH_FORCE_ALIGN_CHECK /* can be defined externally */\n#  if defined(__i386) || defined(_M_IX86) || defined(__x86_64__) || defined(_M_X64)\n#    define XXH_FORCE_ALIGN_CHECK 0\n#  else\n#    define XXH_FORCE_ALIGN_CHECK 1\n#  endif\n#endif\n\n\n/* *************************************\n*  Includes & Memory related functions\n***************************************/\n/*! Modify the local functions below should you wish to use some other memory routines\n*   for malloc(), free() */\n#include <stdlib.h>\nstatic void* XXH_malloc(size_t s) { return malloc(s); }\nstatic void  XXH_free  (void* p)  { free(p); }\n/*! and for memcpy() */\n#include <string.h>\nstatic void* XXH_memcpy(void* dest, const void* src, size_t size) { return memcpy(dest,src,size); }\n\n#include <assert.h>   /* assert */\n\n#define XXH_STATIC_LINKING_ONLY\n#include \"xxhash.h\"\n\n\n/* *************************************\n*  Compiler Specific Options\n***************************************/\n#ifdef _MSC_VER    /* Visual Studio */\n#  pragma warning(disable : 4127)      /* disable: C4127: conditional expression is constant */\n#  define FORCE_INLINE static __forceinline\n#else\n#  if defined (__cplusplus) || defined (__STDC_VERSION__) && __STDC_VERSION__ >= 199901L   /* C99 */\n#    ifdef __GNUC__\n#      define FORCE_INLINE static inline __attribute__((always_inline))\n#    else\n#      define FORCE_INLINE static inline\n#    endif\n#  else\n#    define FORCE_INLINE static\n#  endif /* __STDC_VERSION__ */\n#endif\n\n\n/* *************************************\n*  Basic Types\n***************************************/\n#ifndef MEM_MODULE\n# if !defined (__VMS) \\\n  && (defined (__cplusplus) \\\n  || (defined (__STDC_VERSION__) && (__STDC_VERSION__ >= 199901L) /* C99 */) )\n#   include <stdint.h>\n    typedef uint8_t  BYTE;\n    typedef uint16_t U16;\n    typedef uint32_t U32;\n# else\n    typedef unsigned char      BYTE;\n    typedef unsigned short     U16;\n    typedef unsigned int       U32;\n# endif\n#endif\n\n#if (defined(XXH_FORCE_MEMORY_ACCESS) && (XXH_FORCE_MEMORY_ACCESS==2))\n\n/* Force direct memory access. Only works on CPU which support unaligned memory access in hardware */\nstatic U32 XXH_read32(const void* memPtr) { return *(const U32*) memPtr; }\n\n#elif (defined(XXH_FORCE_MEMORY_ACCESS) && (XXH_FORCE_MEMORY_ACCESS==1))\n\n/* __pack instructions are safer, but compiler specific, hence potentially problematic for some compilers */\n/* currently only defined for gcc and icc */\ntypedef union { U32 u32; } __attribute__((packed)) unalign;\nstatic U32 XXH_read32(const void* ptr) { return ((const unalign*)ptr)->u32; }\n\n#else\n\n/* portable and safe solution. Generally efficient.\n * see : http://stackoverflow.com/a/32095106/646947\n */\nstatic U32 XXH_read32(const void* memPtr)\n{\n    U32 val;\n    memcpy(&val, memPtr, sizeof(val));\n    return val;\n}\n\n#endif   /* XXH_FORCE_DIRECT_MEMORY_ACCESS */\n\n\n/* ****************************************\n*  Compiler-specific Functions and Macros\n******************************************/\n#define XXH_GCC_VERSION (__GNUC__ * 100 + __GNUC_MINOR__)\n\n/* Note : although _rotl exists for minGW (GCC under windows), performance seems poor */\n#if defined(_MSC_VER)\n#  define XXH_rotl32(x,r) _rotl(x,r)\n#  define XXH_rotl64(x,r) _rotl64(x,r)\n#else\n#  define XXH_rotl32(x,r) ((x << r) | (x >> (32 - r)))\n#  define XXH_rotl64(x,r) ((x << r) | (x >> (64 - r)))\n#endif\n\n#if defined(_MSC_VER)     /* Visual Studio */\n#  define XXH_swap32 _byteswap_ulong\n#elif XXH_GCC_VERSION >= 403\n#  define XXH_swap32 __builtin_bswap32\n#else\nstatic U32 XXH_swap32 (U32 x)\n{\n    return  ((x << 24) & 0xff000000 ) |\n            ((x <<  8) & 0x00ff0000 ) |\n            ((x >>  8) & 0x0000ff00 ) |\n            ((x >> 24) & 0x000000ff );\n}\n#endif\n\n\n/* *************************************\n*  Architecture Macros\n***************************************/\ntypedef enum { XXH_bigEndian=0, XXH_littleEndian=1 } XXH_endianess;\n\n/* XXH_CPU_LITTLE_ENDIAN can be defined externally, for example on the compiler command line */\n#ifndef XXH_CPU_LITTLE_ENDIAN\nstatic int XXH_isLittleEndian(void)\n{\n    const union { U32 u; BYTE c[4]; } one = { 1 };   /* don't use static : performance detrimental  */\n    return one.c[0];\n}\n#   define XXH_CPU_LITTLE_ENDIAN   XXH_isLittleEndian()\n#endif\n\n\n/* ***************************\n*  Memory reads\n*****************************/\ntypedef enum { XXH_aligned, XXH_unaligned } XXH_alignment;\n\nFORCE_INLINE U32 XXH_readLE32_align(const void* ptr, XXH_endianess endian, XXH_alignment align)\n{\n    if (align==XXH_unaligned)\n        return endian==XXH_littleEndian ? XXH_read32(ptr) : XXH_swap32(XXH_read32(ptr));\n    else\n        return endian==XXH_littleEndian ? *(const U32*)ptr : XXH_swap32(*(const U32*)ptr);\n}\n\nFORCE_INLINE U32 XXH_readLE32(const void* ptr, XXH_endianess endian)\n{\n    return XXH_readLE32_align(ptr, endian, XXH_unaligned);\n}\n\nstatic U32 XXH_readBE32(const void* ptr)\n{\n    return XXH_CPU_LITTLE_ENDIAN ? XXH_swap32(XXH_read32(ptr)) : XXH_read32(ptr);\n}\n\n\n/* *************************************\n*  Macros\n***************************************/\n#define XXH_STATIC_ASSERT(c)  { enum { XXH_sa = 1/(int)(!!(c)) }; }  /* use after variable declarations */\nXXH_PUBLIC_API unsigned XXH_versionNumber (void) { return XXH_VERSION_NUMBER; }\n\n\n/* *******************************************************************\n*  32-bit hash functions\n*********************************************************************/\nstatic const U32 PRIME32_1 = 2654435761U;\nstatic const U32 PRIME32_2 = 2246822519U;\nstatic const U32 PRIME32_3 = 3266489917U;\nstatic const U32 PRIME32_4 =  668265263U;\nstatic const U32 PRIME32_5 =  374761393U;\n\nstatic U32 XXH32_round(U32 seed, U32 input)\n{\n    seed += input * PRIME32_2;\n    seed  = XXH_rotl32(seed, 13);\n    seed *= PRIME32_1;\n    return seed;\n}\n\n/* mix all bits */\nstatic U32 XXH32_avalanche(U32 h32)\n{\n    h32 ^= h32 >> 15;\n    h32 *= PRIME32_2;\n    h32 ^= h32 >> 13;\n    h32 *= PRIME32_3;\n    h32 ^= h32 >> 16;\n    return(h32);\n}\n\n#define XXH_get32bits(p) XXH_readLE32_align(p, endian, align)\n\nstatic U32\nXXH32_finalize(U32 h32, const void* ptr, size_t len,\n                XXH_endianess endian, XXH_alignment align)\n\n{\n    const BYTE* p = (const BYTE*)ptr;\n\n#define PROCESS1               \\\n    h32 += (*p++) * PRIME32_5; \\\n    h32 = XXH_rotl32(h32, 11) * PRIME32_1 ;\n\n#define PROCESS4                         \\\n    h32 += XXH_get32bits(p) * PRIME32_3; \\\n    p+=4;                                \\\n    h32  = XXH_rotl32(h32, 17) * PRIME32_4 ;\n\n    switch(len&15)  /* or switch(bEnd - p) */\n    {\n      case 12:      PROCESS4;\n                    /* fallthrough */\n      case 8:       PROCESS4;\n                    /* fallthrough */\n      case 4:       PROCESS4;\n                    return XXH32_avalanche(h32);\n\n      case 13:      PROCESS4;\n                    /* fallthrough */\n      case 9:       PROCESS4;\n                    /* fallthrough */\n      case 5:       PROCESS4;\n                    PROCESS1;\n                    return XXH32_avalanche(h32);\n\n      case 14:      PROCESS4;\n                    /* fallthrough */\n      case 10:      PROCESS4;\n                    /* fallthrough */\n      case 6:       PROCESS4;\n                    PROCESS1;\n                    PROCESS1;\n                    return XXH32_avalanche(h32);\n\n      case 15:      PROCESS4;\n                    /* fallthrough */\n      case 11:      PROCESS4;\n                    /* fallthrough */\n      case 7:       PROCESS4;\n                    /* fallthrough */\n      case 3:       PROCESS1;\n                    /* fallthrough */\n      case 2:       PROCESS1;\n                    /* fallthrough */\n      case 1:       PROCESS1;\n                    /* fallthrough */\n      case 0:       return XXH32_avalanche(h32);\n    }\n    assert(0);\n    return h32;   /* reaching this point is deemed impossible */\n}\n\n\nFORCE_INLINE U32\nXXH32_endian_align(const void* input, size_t len, U32 seed,\n                    XXH_endianess endian, XXH_alignment align)\n{\n    const BYTE* p = (const BYTE*)input;\n    const BYTE* bEnd = p + len;\n    U32 h32;\n\n#if defined(XXH_ACCEPT_NULL_INPUT_POINTER) && (XXH_ACCEPT_NULL_INPUT_POINTER>=1)\n    if (p==NULL) {\n        len=0;\n        bEnd=p=(const BYTE*)(size_t)16;\n    }\n#endif\n\n    if (len>=16) {\n        const BYTE* const limit = bEnd - 15;\n        U32 v1 = seed + PRIME32_1 + PRIME32_2;\n        U32 v2 = seed + PRIME32_2;\n        U32 v3 = seed + 0;\n        U32 v4 = seed - PRIME32_1;\n\n        do {\n            v1 = XXH32_round(v1, XXH_get32bits(p)); p+=4;\n            v2 = XXH32_round(v2, XXH_get32bits(p)); p+=4;\n            v3 = XXH32_round(v3, XXH_get32bits(p)); p+=4;\n            v4 = XXH32_round(v4, XXH_get32bits(p)); p+=4;\n        } while (p < limit);\n\n        h32 = XXH_rotl32(v1, 1)  + XXH_rotl32(v2, 7)\n            + XXH_rotl32(v3, 12) + XXH_rotl32(v4, 18);\n    } else {\n        h32  = seed + PRIME32_5;\n    }\n\n    h32 += (U32)len;\n\n    return XXH32_finalize(h32, p, len&15, endian, align);\n}\n\n\nXXH_PUBLIC_API unsigned int XXH32 (const void* input, size_t len, unsigned int seed)\n{\n#if 0\n    /* Simple version, good for code maintenance, but unfortunately slow for small inputs */\n    XXH32_state_t state;\n    XXH32_reset(&state, seed);\n    XXH32_update(&state, input, len);\n    return XXH32_digest(&state);\n#else\n    XXH_endianess endian_detected = (XXH_endianess)XXH_CPU_LITTLE_ENDIAN;\n\n    if (XXH_FORCE_ALIGN_CHECK) {\n        if ((((size_t)input) & 3) == 0) {   /* Input is 4-bytes aligned, leverage the speed benefit */\n            if ((endian_detected==XXH_littleEndian) || XXH_FORCE_NATIVE_FORMAT)\n                return XXH32_endian_align(input, len, seed, XXH_littleEndian, XXH_aligned);\n            else\n                return XXH32_endian_align(input, len, seed, XXH_bigEndian, XXH_aligned);\n    }   }\n\n    if ((endian_detected==XXH_littleEndian) || XXH_FORCE_NATIVE_FORMAT)\n        return XXH32_endian_align(input, len, seed, XXH_littleEndian, XXH_unaligned);\n    else\n        return XXH32_endian_align(input, len, seed, XXH_bigEndian, XXH_unaligned);\n#endif\n}\n\n\n\n/*======   Hash streaming   ======*/\n\nXXH_PUBLIC_API XXH32_state_t* XXH32_createState(void)\n{\n    return (XXH32_state_t*)XXH_malloc(sizeof(XXH32_state_t));\n}\nXXH_PUBLIC_API XXH_errorcode XXH32_freeState(XXH32_state_t* statePtr)\n{\n    XXH_free(statePtr);\n    return XXH_OK;\n}\n\nXXH_PUBLIC_API void XXH32_copyState(XXH32_state_t* dstState, const XXH32_state_t* srcState)\n{\n    memcpy(dstState, srcState, sizeof(*dstState));\n}\n\nXXH_PUBLIC_API XXH_errorcode XXH32_reset(XXH32_state_t* statePtr, unsigned int seed)\n{\n    XXH32_state_t state;   /* using a local state to memcpy() in order to avoid strict-aliasing warnings */\n    memset(&state, 0, sizeof(state));\n    state.v1 = seed + PRIME32_1 + PRIME32_2;\n    state.v2 = seed + PRIME32_2;\n    state.v3 = seed + 0;\n    state.v4 = seed - PRIME32_1;\n    /* do not write into reserved, planned to be removed in a future version */\n    memcpy(statePtr, &state, sizeof(state) - sizeof(state.reserved));\n    return XXH_OK;\n}\n\n\nFORCE_INLINE XXH_errorcode\nXXH32_update_endian(XXH32_state_t* state, const void* input, size_t len, XXH_endianess endian)\n{\n    if (input==NULL)\n#if defined(XXH_ACCEPT_NULL_INPUT_POINTER) && (XXH_ACCEPT_NULL_INPUT_POINTER>=1)\n        return XXH_OK;\n#else\n        return XXH_ERROR;\n#endif\n\n    {   const BYTE* p = (const BYTE*)input;\n        const BYTE* const bEnd = p + len;\n\n        state->total_len_32 += (unsigned)len;\n        state->large_len |= (len>=16) | (state->total_len_32>=16);\n\n        if (state->memsize + len < 16)  {   /* fill in tmp buffer */\n            XXH_memcpy((BYTE*)(state->mem32) + state->memsize, input, len);\n            state->memsize += (unsigned)len;\n            return XXH_OK;\n        }\n\n        if (state->memsize) {   /* some data left from previous update */\n            XXH_memcpy((BYTE*)(state->mem32) + state->memsize, input, 16-state->memsize);\n            {   const U32* p32 = state->mem32;\n                state->v1 = XXH32_round(state->v1, XXH_readLE32(p32, endian)); p32++;\n                state->v2 = XXH32_round(state->v2, XXH_readLE32(p32, endian)); p32++;\n                state->v3 = XXH32_round(state->v3, XXH_readLE32(p32, endian)); p32++;\n                state->v4 = XXH32_round(state->v4, XXH_readLE32(p32, endian));\n            }\n            p += 16-state->memsize;\n            state->memsize = 0;\n        }\n\n        if (p <= bEnd-16) {\n            const BYTE* const limit = bEnd - 16;\n            U32 v1 = state->v1;\n            U32 v2 = state->v2;\n            U32 v3 = state->v3;\n            U32 v4 = state->v4;\n\n            do {\n                v1 = XXH32_round(v1, XXH_readLE32(p, endian)); p+=4;\n                v2 = XXH32_round(v2, XXH_readLE32(p, endian)); p+=4;\n                v3 = XXH32_round(v3, XXH_readLE32(p, endian)); p+=4;\n                v4 = XXH32_round(v4, XXH_readLE32(p, endian)); p+=4;\n            } while (p<=limit);\n\n            state->v1 = v1;\n            state->v2 = v2;\n            state->v3 = v3;\n            state->v4 = v4;\n        }\n\n        if (p < bEnd) {\n            XXH_memcpy(state->mem32, p, (size_t)(bEnd-p));\n            state->memsize = (unsigned)(bEnd-p);\n        }\n    }\n\n    return XXH_OK;\n}\n\n\nXXH_PUBLIC_API XXH_errorcode XXH32_update (XXH32_state_t* state_in, const void* input, size_t len)\n{\n    XXH_endianess endian_detected = (XXH_endianess)XXH_CPU_LITTLE_ENDIAN;\n\n    if ((endian_detected==XXH_littleEndian) || XXH_FORCE_NATIVE_FORMAT)\n        return XXH32_update_endian(state_in, input, len, XXH_littleEndian);\n    else\n        return XXH32_update_endian(state_in, input, len, XXH_bigEndian);\n}\n\n\nFORCE_INLINE U32\nXXH32_digest_endian (const XXH32_state_t* state, XXH_endianess endian)\n{\n    U32 h32;\n\n    if (state->large_len) {\n        h32 = XXH_rotl32(state->v1, 1)\n            + XXH_rotl32(state->v2, 7)\n            + XXH_rotl32(state->v3, 12)\n            + XXH_rotl32(state->v4, 18);\n    } else {\n        h32 = state->v3 /* == seed */ + PRIME32_5;\n    }\n\n    h32 += state->total_len_32;\n\n    return XXH32_finalize(h32, state->mem32, state->memsize, endian, XXH_aligned);\n}\n\n\nXXH_PUBLIC_API unsigned int XXH32_digest (const XXH32_state_t* state_in)\n{\n    XXH_endianess endian_detected = (XXH_endianess)XXH_CPU_LITTLE_ENDIAN;\n\n    if ((endian_detected==XXH_littleEndian) || XXH_FORCE_NATIVE_FORMAT)\n        return XXH32_digest_endian(state_in, XXH_littleEndian);\n    else\n        return XXH32_digest_endian(state_in, XXH_bigEndian);\n}\n\n\n/*======   Canonical representation   ======*/\n\n/*! Default XXH result types are basic unsigned 32 and 64 bits.\n*   The canonical representation follows human-readable write convention, aka big-endian (large digits first).\n*   These functions allow transformation of hash result into and from its canonical format.\n*   This way, hash values can be written into a file or buffer, remaining comparable across different systems.\n*/\n\nXXH_PUBLIC_API void XXH32_canonicalFromHash(XXH32_canonical_t* dst, XXH32_hash_t hash)\n{\n    XXH_STATIC_ASSERT(sizeof(XXH32_canonical_t) == sizeof(XXH32_hash_t));\n    if (XXH_CPU_LITTLE_ENDIAN) hash = XXH_swap32(hash);\n    memcpy(dst, &hash, sizeof(*dst));\n}\n\nXXH_PUBLIC_API XXH32_hash_t XXH32_hashFromCanonical(const XXH32_canonical_t* src)\n{\n    return XXH_readBE32(src);\n}\n\n\n#ifndef XXH_NO_LONG_LONG\n\n/* *******************************************************************\n*  64-bit hash functions\n*********************************************************************/\n\n/*======   Memory access   ======*/\n\n#ifndef MEM_MODULE\n# define MEM_MODULE\n# if !defined (__VMS) \\\n  && (defined (__cplusplus) \\\n  || (defined (__STDC_VERSION__) && (__STDC_VERSION__ >= 199901L) /* C99 */) )\n#   include <stdint.h>\n    typedef uint64_t U64;\n# else\n    /* if compiler doesn't support unsigned long long, replace by another 64-bit type */\n    typedef unsigned long long U64;\n# endif\n#endif\n\n\n#if (defined(XXH_FORCE_MEMORY_ACCESS) && (XXH_FORCE_MEMORY_ACCESS==2))\n\n/* Force direct memory access. Only works on CPU which support unaligned memory access in hardware */\nstatic U64 XXH_read64(const void* memPtr) { return *(const U64*) memPtr; }\n\n#elif (defined(XXH_FORCE_MEMORY_ACCESS) && (XXH_FORCE_MEMORY_ACCESS==1))\n\n/* __pack instructions are safer, but compiler specific, hence potentially problematic for some compilers */\n/* currently only defined for gcc and icc */\ntypedef union { U32 u32; U64 u64; } __attribute__((packed)) unalign64;\nstatic U64 XXH_read64(const void* ptr) { return ((const unalign64*)ptr)->u64; }\n\n#else\n\n/* portable and safe solution. Generally efficient.\n * see : http://stackoverflow.com/a/32095106/646947\n */\n\nstatic U64 XXH_read64(const void* memPtr)\n{\n    U64 val;\n    memcpy(&val, memPtr, sizeof(val));\n    return val;\n}\n\n#endif   /* XXH_FORCE_DIRECT_MEMORY_ACCESS */\n\n#if defined(_MSC_VER)     /* Visual Studio */\n#  define XXH_swap64 _byteswap_uint64\n#elif XXH_GCC_VERSION >= 403\n#  define XXH_swap64 __builtin_bswap64\n#else\nstatic U64 XXH_swap64 (U64 x)\n{\n    return  ((x << 56) & 0xff00000000000000ULL) |\n            ((x << 40) & 0x00ff000000000000ULL) |\n            ((x << 24) & 0x0000ff0000000000ULL) |\n            ((x << 8)  & 0x000000ff00000000ULL) |\n            ((x >> 8)  & 0x00000000ff000000ULL) |\n            ((x >> 24) & 0x0000000000ff0000ULL) |\n            ((x >> 40) & 0x000000000000ff00ULL) |\n            ((x >> 56) & 0x00000000000000ffULL);\n}\n#endif\n\nFORCE_INLINE U64 XXH_readLE64_align(const void* ptr, XXH_endianess endian, XXH_alignment align)\n{\n    if (align==XXH_unaligned)\n        return endian==XXH_littleEndian ? XXH_read64(ptr) : XXH_swap64(XXH_read64(ptr));\n    else\n        return endian==XXH_littleEndian ? *(const U64*)ptr : XXH_swap64(*(const U64*)ptr);\n}\n\nFORCE_INLINE U64 XXH_readLE64(const void* ptr, XXH_endianess endian)\n{\n    return XXH_readLE64_align(ptr, endian, XXH_unaligned);\n}\n\nstatic U64 XXH_readBE64(const void* ptr)\n{\n    return XXH_CPU_LITTLE_ENDIAN ? XXH_swap64(XXH_read64(ptr)) : XXH_read64(ptr);\n}\n\n\n/*======   xxh64   ======*/\n\nstatic const U64 PRIME64_1 = 11400714785074694791ULL;\nstatic const U64 PRIME64_2 = 14029467366897019727ULL;\nstatic const U64 PRIME64_3 =  1609587929392839161ULL;\nstatic const U64 PRIME64_4 =  9650029242287828579ULL;\nstatic const U64 PRIME64_5 =  2870177450012600261ULL;\n\nstatic U64 XXH64_round(U64 acc, U64 input)\n{\n    acc += input * PRIME64_2;\n    acc  = XXH_rotl64(acc, 31);\n    acc *= PRIME64_1;\n    return acc;\n}\n\nstatic U64 XXH64_mergeRound(U64 acc, U64 val)\n{\n    val  = XXH64_round(0, val);\n    acc ^= val;\n    acc  = acc * PRIME64_1 + PRIME64_4;\n    return acc;\n}\n\nstatic U64 XXH64_avalanche(U64 h64)\n{\n    h64 ^= h64 >> 33;\n    h64 *= PRIME64_2;\n    h64 ^= h64 >> 29;\n    h64 *= PRIME64_3;\n    h64 ^= h64 >> 32;\n    return h64;\n}\n\n\n#define XXH_get64bits(p) XXH_readLE64_align(p, endian, align)\n\nstatic U64\nXXH64_finalize(U64 h64, const void* ptr, size_t len,\n               XXH_endianess endian, XXH_alignment align)\n{\n    const BYTE* p = (const BYTE*)ptr;\n\n#define PROCESS1_64            \\\n    h64 ^= (*p++) * PRIME64_5; \\\n    h64 = XXH_rotl64(h64, 11) * PRIME64_1;\n\n#define PROCESS4_64          \\\n    h64 ^= (U64)(XXH_get32bits(p)) * PRIME64_1; \\\n    p+=4;                    \\\n    h64 = XXH_rotl64(h64, 23) * PRIME64_2 + PRIME64_3;\n\n#define PROCESS8_64 {        \\\n    U64 const k1 = XXH64_round(0, XXH_get64bits(p)); \\\n    p+=8;                    \\\n    h64 ^= k1;               \\\n    h64  = XXH_rotl64(h64,27) * PRIME64_1 + PRIME64_4; \\\n}\n\n    switch(len&31) {\n      case 24: PROCESS8_64;\n                    /* fallthrough */\n      case 16: PROCESS8_64;\n                    /* fallthrough */\n      case  8: PROCESS8_64;\n               return XXH64_avalanche(h64);\n\n      case 28: PROCESS8_64;\n                    /* fallthrough */\n      case 20: PROCESS8_64;\n                    /* fallthrough */\n      case 12: PROCESS8_64;\n                    /* fallthrough */\n      case  4: PROCESS4_64;\n               return XXH64_avalanche(h64);\n\n      case 25: PROCESS8_64;\n                    /* fallthrough */\n      case 17: PROCESS8_64;\n                    /* fallthrough */\n      case  9: PROCESS8_64;\n               PROCESS1_64;\n               return XXH64_avalanche(h64);\n\n      case 29: PROCESS8_64;\n                    /* fallthrough */\n      case 21: PROCESS8_64;\n                    /* fallthrough */\n      case 13: PROCESS8_64;\n                    /* fallthrough */\n      case  5: PROCESS4_64;\n               PROCESS1_64;\n               return XXH64_avalanche(h64);\n\n      case 26: PROCESS8_64;\n                    /* fallthrough */\n      case 18: PROCESS8_64;\n                    /* fallthrough */\n      case 10: PROCESS8_64;\n               PROCESS1_64;\n               PROCESS1_64;\n               return XXH64_avalanche(h64);\n\n      case 30: PROCESS8_64;\n                    /* fallthrough */\n      case 22: PROCESS8_64;\n                    /* fallthrough */\n      case 14: PROCESS8_64;\n                    /* fallthrough */\n      case  6: PROCESS4_64;\n               PROCESS1_64;\n               PROCESS1_64;\n               return XXH64_avalanche(h64);\n\n      case 27: PROCESS8_64;\n                    /* fallthrough */\n      case 19: PROCESS8_64;\n                    /* fallthrough */\n      case 11: PROCESS8_64;\n               PROCESS1_64;\n               PROCESS1_64;\n               PROCESS1_64;\n               return XXH64_avalanche(h64);\n\n      case 31: PROCESS8_64;\n                    /* fallthrough */\n      case 23: PROCESS8_64;\n                    /* fallthrough */\n      case 15: PROCESS8_64;\n                    /* fallthrough */\n      case  7: PROCESS4_64;\n                    /* fallthrough */\n      case  3: PROCESS1_64;\n                    /* fallthrough */\n      case  2: PROCESS1_64;\n                    /* fallthrough */\n      case  1: PROCESS1_64;\n                    /* fallthrough */\n      case  0: return XXH64_avalanche(h64);\n    }\n\n    /* impossible to reach */\n    assert(0);\n    return 0;  /* unreachable, but some compilers complain without it */\n}\n\nFORCE_INLINE U64\nXXH64_endian_align(const void* input, size_t len, U64 seed,\n                XXH_endianess endian, XXH_alignment align)\n{\n    const BYTE* p = (const BYTE*)input;\n    const BYTE* bEnd = p + len;\n    U64 h64;\n\n#if defined(XXH_ACCEPT_NULL_INPUT_POINTER) && (XXH_ACCEPT_NULL_INPUT_POINTER>=1)\n    if (p==NULL) {\n        len=0;\n        bEnd=p=(const BYTE*)(size_t)32;\n    }\n#endif\n\n    if (len>=32) {\n        const BYTE* const limit = bEnd - 32;\n        U64 v1 = seed + PRIME64_1 + PRIME64_2;\n        U64 v2 = seed + PRIME64_2;\n        U64 v3 = seed + 0;\n        U64 v4 = seed - PRIME64_1;\n\n        do {\n            v1 = XXH64_round(v1, XXH_get64bits(p)); p+=8;\n            v2 = XXH64_round(v2, XXH_get64bits(p)); p+=8;\n            v3 = XXH64_round(v3, XXH_get64bits(p)); p+=8;\n            v4 = XXH64_round(v4, XXH_get64bits(p)); p+=8;\n        } while (p<=limit);\n\n        h64 = XXH_rotl64(v1, 1) + XXH_rotl64(v2, 7) + XXH_rotl64(v3, 12) + XXH_rotl64(v4, 18);\n        h64 = XXH64_mergeRound(h64, v1);\n        h64 = XXH64_mergeRound(h64, v2);\n        h64 = XXH64_mergeRound(h64, v3);\n        h64 = XXH64_mergeRound(h64, v4);\n\n    } else {\n        h64  = seed + PRIME64_5;\n    }\n\n    h64 += (U64) len;\n\n    return XXH64_finalize(h64, p, len, endian, align);\n}\n\n\nXXH_PUBLIC_API unsigned long long XXH64 (const void* input, size_t len, unsigned long long seed)\n{\n#if 0\n    /* Simple version, good for code maintenance, but unfortunately slow for small inputs */\n    XXH64_state_t state;\n    XXH64_reset(&state, seed);\n    XXH64_update(&state, input, len);\n    return XXH64_digest(&state);\n#else\n    XXH_endianess endian_detected = (XXH_endianess)XXH_CPU_LITTLE_ENDIAN;\n\n    if (XXH_FORCE_ALIGN_CHECK) {\n        if ((((size_t)input) & 7)==0) {  /* Input is aligned, let's leverage the speed advantage */\n            if ((endian_detected==XXH_littleEndian) || XXH_FORCE_NATIVE_FORMAT)\n                return XXH64_endian_align(input, len, seed, XXH_littleEndian, XXH_aligned);\n            else\n                return XXH64_endian_align(input, len, seed, XXH_bigEndian, XXH_aligned);\n    }   }\n\n    if ((endian_detected==XXH_littleEndian) || XXH_FORCE_NATIVE_FORMAT)\n        return XXH64_endian_align(input, len, seed, XXH_littleEndian, XXH_unaligned);\n    else\n        return XXH64_endian_align(input, len, seed, XXH_bigEndian, XXH_unaligned);\n#endif\n}\n\n/*======   Hash Streaming   ======*/\n\nXXH_PUBLIC_API XXH64_state_t* XXH64_createState(void)\n{\n    return (XXH64_state_t*)XXH_malloc(sizeof(XXH64_state_t));\n}\nXXH_PUBLIC_API XXH_errorcode XXH64_freeState(XXH64_state_t* statePtr)\n{\n    XXH_free(statePtr);\n    return XXH_OK;\n}\n\nXXH_PUBLIC_API void XXH64_copyState(XXH64_state_t* dstState, const XXH64_state_t* srcState)\n{\n    memcpy(dstState, srcState, sizeof(*dstState));\n}\n\nXXH_PUBLIC_API XXH_errorcode XXH64_reset(XXH64_state_t* statePtr, unsigned long long seed)\n{\n    XXH64_state_t state;   /* using a local state to memcpy() in order to avoid strict-aliasing warnings */\n    memset(&state, 0, sizeof(state));\n    state.v1 = seed + PRIME64_1 + PRIME64_2;\n    state.v2 = seed + PRIME64_2;\n    state.v3 = seed + 0;\n    state.v4 = seed - PRIME64_1;\n     /* do not write into reserved, planned to be removed in a future version */\n    memcpy(statePtr, &state, sizeof(state) - sizeof(state.reserved));\n    return XXH_OK;\n}\n\nFORCE_INLINE XXH_errorcode\nXXH64_update_endian (XXH64_state_t* state, const void* input, size_t len, XXH_endianess endian)\n{\n    if (input==NULL)\n#if defined(XXH_ACCEPT_NULL_INPUT_POINTER) && (XXH_ACCEPT_NULL_INPUT_POINTER>=1)\n        return XXH_OK;\n#else\n        return XXH_ERROR;\n#endif\n\n    {   const BYTE* p = (const BYTE*)input;\n        const BYTE* const bEnd = p + len;\n\n        state->total_len += len;\n\n        if (state->memsize + len < 32) {  /* fill in tmp buffer */\n            XXH_memcpy(((BYTE*)state->mem64) + state->memsize, input, len);\n            state->memsize += (U32)len;\n            return XXH_OK;\n        }\n\n        if (state->memsize) {   /* tmp buffer is full */\n            XXH_memcpy(((BYTE*)state->mem64) + state->memsize, input, 32-state->memsize);\n            state->v1 = XXH64_round(state->v1, XXH_readLE64(state->mem64+0, endian));\n            state->v2 = XXH64_round(state->v2, XXH_readLE64(state->mem64+1, endian));\n            state->v3 = XXH64_round(state->v3, XXH_readLE64(state->mem64+2, endian));\n            state->v4 = XXH64_round(state->v4, XXH_readLE64(state->mem64+3, endian));\n            p += 32-state->memsize;\n            state->memsize = 0;\n        }\n\n        if (p+32 <= bEnd) {\n            const BYTE* const limit = bEnd - 32;\n            U64 v1 = state->v1;\n            U64 v2 = state->v2;\n            U64 v3 = state->v3;\n            U64 v4 = state->v4;\n\n            do {\n                v1 = XXH64_round(v1, XXH_readLE64(p, endian)); p+=8;\n                v2 = XXH64_round(v2, XXH_readLE64(p, endian)); p+=8;\n                v3 = XXH64_round(v3, XXH_readLE64(p, endian)); p+=8;\n                v4 = XXH64_round(v4, XXH_readLE64(p, endian)); p+=8;\n            } while (p<=limit);\n\n            state->v1 = v1;\n            state->v2 = v2;\n            state->v3 = v3;\n            state->v4 = v4;\n        }\n\n        if (p < bEnd) {\n            XXH_memcpy(state->mem64, p, (size_t)(bEnd-p));\n            state->memsize = (unsigned)(bEnd-p);\n        }\n    }\n\n    return XXH_OK;\n}\n\nXXH_PUBLIC_API XXH_errorcode XXH64_update (XXH64_state_t* state_in, const void* input, size_t len)\n{\n    XXH_endianess endian_detected = (XXH_endianess)XXH_CPU_LITTLE_ENDIAN;\n\n    if ((endian_detected==XXH_littleEndian) || XXH_FORCE_NATIVE_FORMAT)\n        return XXH64_update_endian(state_in, input, len, XXH_littleEndian);\n    else\n        return XXH64_update_endian(state_in, input, len, XXH_bigEndian);\n}\n\nFORCE_INLINE U64 XXH64_digest_endian (const XXH64_state_t* state, XXH_endianess endian)\n{\n    U64 h64;\n\n    if (state->total_len >= 32) {\n        U64 const v1 = state->v1;\n        U64 const v2 = state->v2;\n        U64 const v3 = state->v3;\n        U64 const v4 = state->v4;\n\n        h64 = XXH_rotl64(v1, 1) + XXH_rotl64(v2, 7) + XXH_rotl64(v3, 12) + XXH_rotl64(v4, 18);\n        h64 = XXH64_mergeRound(h64, v1);\n        h64 = XXH64_mergeRound(h64, v2);\n        h64 = XXH64_mergeRound(h64, v3);\n        h64 = XXH64_mergeRound(h64, v4);\n    } else {\n        h64  = state->v3 /*seed*/ + PRIME64_5;\n    }\n\n    h64 += (U64) state->total_len;\n\n    return XXH64_finalize(h64, state->mem64, (size_t)state->total_len, endian, XXH_aligned);\n}\n\nXXH_PUBLIC_API unsigned long long XXH64_digest (const XXH64_state_t* state_in)\n{\n    XXH_endianess endian_detected = (XXH_endianess)XXH_CPU_LITTLE_ENDIAN;\n\n    if ((endian_detected==XXH_littleEndian) || XXH_FORCE_NATIVE_FORMAT)\n        return XXH64_digest_endian(state_in, XXH_littleEndian);\n    else\n        return XXH64_digest_endian(state_in, XXH_bigEndian);\n}\n\n\n/*====== Canonical representation   ======*/\n\nXXH_PUBLIC_API void XXH64_canonicalFromHash(XXH64_canonical_t* dst, XXH64_hash_t hash)\n{\n    XXH_STATIC_ASSERT(sizeof(XXH64_canonical_t) == sizeof(XXH64_hash_t));\n    if (XXH_CPU_LITTLE_ENDIAN) hash = XXH_swap64(hash);\n    memcpy(dst, &hash, sizeof(*dst));\n}\n\nXXH_PUBLIC_API XXH64_hash_t XXH64_hashFromCanonical(const XXH64_canonical_t* src)\n{\n    return XXH_readBE64(src);\n}\n\n#endif  /* XXH_NO_LONG_LONG */\n"
  },
  {
    "path": "external/lz4/xxhash.h",
    "content": "/*\n   xxHash - Extremely Fast Hash algorithm\n   Header File\n   Copyright (C) 2012-2016, Yann Collet.\n\n   BSD 2-Clause License (http://www.opensource.org/licenses/bsd-license.php)\n\n   Redistribution and use in source and binary forms, with or without\n   modification, are permitted provided that the following conditions are\n   met:\n\n       * Redistributions of source code must retain the above copyright\n   notice, this list of conditions and the following disclaimer.\n       * Redistributions in binary form must reproduce the above\n   copyright notice, this list of conditions and the following disclaimer\n   in the documentation and/or other materials provided with the\n   distribution.\n\n   THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\n   \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\n   LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR\n   A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT\n   OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,\n   SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT\n   LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,\n   DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY\n   THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\n   (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE\n   OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n\n   You can contact the author at :\n   - xxHash source repository : https://github.com/Cyan4973/xxHash\n*/\n\n/* Notice extracted from xxHash homepage :\n\nxxHash is an extremely fast Hash algorithm, running at RAM speed limits.\nIt also successfully passes all tests from the SMHasher suite.\n\nComparison (single thread, Windows Seven 32 bits, using SMHasher on a Core 2 Duo @3GHz)\n\nName            Speed       Q.Score   Author\nxxHash          5.4 GB/s     10\nCrapWow         3.2 GB/s      2       Andrew\nMumurHash 3a    2.7 GB/s     10       Austin Appleby\nSpookyHash      2.0 GB/s     10       Bob Jenkins\nSBox            1.4 GB/s      9       Bret Mulvey\nLookup3         1.2 GB/s      9       Bob Jenkins\nSuperFastHash   1.2 GB/s      1       Paul Hsieh\nCityHash64      1.05 GB/s    10       Pike & Alakuijala\nFNV             0.55 GB/s     5       Fowler, Noll, Vo\nCRC32           0.43 GB/s     9\nMD5-32          0.33 GB/s    10       Ronald L. Rivest\nSHA1-32         0.28 GB/s    10\n\nQ.Score is a measure of quality of the hash function.\nIt depends on successfully passing SMHasher test set.\n10 is a perfect score.\n\nA 64-bit version, named XXH64, is available since r35.\nIt offers much better speed, but for 64-bit applications only.\nName     Speed on 64 bits    Speed on 32 bits\nXXH64       13.8 GB/s            1.9 GB/s\nXXH32        6.8 GB/s            6.0 GB/s\n*/\n\n#ifndef XXHASH_H_5627135585666179\n#define XXHASH_H_5627135585666179 1\n\n#if defined (__cplusplus)\nextern \"C\" {\n#endif\n\n\n/* ****************************\n*  Definitions\n******************************/\n#include <stddef.h>   /* size_t */\ntypedef enum { XXH_OK=0, XXH_ERROR } XXH_errorcode;\n\n\n/* ****************************\n *  API modifier\n ******************************/\n/** XXH_INLINE_ALL (and XXH_PRIVATE_API)\n *  This is useful to include xxhash functions in `static` mode\n *  in order to inline them, and remove their symbol from the public list.\n *  Inlining can offer dramatic performance improvement on small keys.\n *  Methodology :\n *     #define XXH_INLINE_ALL\n *     #include \"xxhash.h\"\n * `xxhash.c` is automatically included.\n *  It's not useful to compile and link it as a separate module.\n */\n#if defined(XXH_INLINE_ALL) || defined(XXH_PRIVATE_API)\n#  ifndef XXH_STATIC_LINKING_ONLY\n#    define XXH_STATIC_LINKING_ONLY\n#  endif\n#  if defined(__GNUC__)\n#    define XXH_PUBLIC_API static __inline __attribute__((unused))\n#  elif defined (__cplusplus) || (defined (__STDC_VERSION__) && (__STDC_VERSION__ >= 199901L) /* C99 */)\n#    define XXH_PUBLIC_API static inline\n#  elif defined(_MSC_VER)\n#    define XXH_PUBLIC_API static __inline\n#  else\n     /* this version may generate warnings for unused static functions */\n#    define XXH_PUBLIC_API static\n#  endif\n#else\n#  define XXH_PUBLIC_API   /* do nothing */\n#endif /* XXH_INLINE_ALL || XXH_PRIVATE_API */\n\n/*! XXH_NAMESPACE, aka Namespace Emulation :\n *\n * If you want to include _and expose_ xxHash functions from within your own library,\n * but also want to avoid symbol collisions with other libraries which may also include xxHash,\n *\n * you can use XXH_NAMESPACE, to automatically prefix any public symbol from xxhash library\n * with the value of XXH_NAMESPACE (therefore, avoid NULL and numeric values).\n *\n * Note that no change is required within the calling program as long as it includes `xxhash.h` :\n * regular symbol name will be automatically translated by this header.\n */\n#ifdef XXH_NAMESPACE\n#  define XXH_CAT(A,B) A##B\n#  define XXH_NAME2(A,B) XXH_CAT(A,B)\n#  define XXH_versionNumber XXH_NAME2(XXH_NAMESPACE, XXH_versionNumber)\n#  define XXH32 XXH_NAME2(XXH_NAMESPACE, XXH32)\n#  define XXH32_createState XXH_NAME2(XXH_NAMESPACE, XXH32_createState)\n#  define XXH32_freeState XXH_NAME2(XXH_NAMESPACE, XXH32_freeState)\n#  define XXH32_reset XXH_NAME2(XXH_NAMESPACE, XXH32_reset)\n#  define XXH32_update XXH_NAME2(XXH_NAMESPACE, XXH32_update)\n#  define XXH32_digest XXH_NAME2(XXH_NAMESPACE, XXH32_digest)\n#  define XXH32_copyState XXH_NAME2(XXH_NAMESPACE, XXH32_copyState)\n#  define XXH32_canonicalFromHash XXH_NAME2(XXH_NAMESPACE, XXH32_canonicalFromHash)\n#  define XXH32_hashFromCanonical XXH_NAME2(XXH_NAMESPACE, XXH32_hashFromCanonical)\n#  define XXH64 XXH_NAME2(XXH_NAMESPACE, XXH64)\n#  define XXH64_createState XXH_NAME2(XXH_NAMESPACE, XXH64_createState)\n#  define XXH64_freeState XXH_NAME2(XXH_NAMESPACE, XXH64_freeState)\n#  define XXH64_reset XXH_NAME2(XXH_NAMESPACE, XXH64_reset)\n#  define XXH64_update XXH_NAME2(XXH_NAMESPACE, XXH64_update)\n#  define XXH64_digest XXH_NAME2(XXH_NAMESPACE, XXH64_digest)\n#  define XXH64_copyState XXH_NAME2(XXH_NAMESPACE, XXH64_copyState)\n#  define XXH64_canonicalFromHash XXH_NAME2(XXH_NAMESPACE, XXH64_canonicalFromHash)\n#  define XXH64_hashFromCanonical XXH_NAME2(XXH_NAMESPACE, XXH64_hashFromCanonical)\n#endif\n\n\n/* *************************************\n*  Version\n***************************************/\n#define XXH_VERSION_MAJOR    0\n#define XXH_VERSION_MINOR    6\n#define XXH_VERSION_RELEASE  5\n#define XXH_VERSION_NUMBER  (XXH_VERSION_MAJOR *100*100 + XXH_VERSION_MINOR *100 + XXH_VERSION_RELEASE)\nXXH_PUBLIC_API unsigned XXH_versionNumber (void);\n\n\n/*-**********************************************************************\n*  32-bit hash\n************************************************************************/\ntypedef unsigned int XXH32_hash_t;\n\n/*! XXH32() :\n    Calculate the 32-bit hash of sequence \"length\" bytes stored at memory address \"input\".\n    The memory between input & input+length must be valid (allocated and read-accessible).\n    \"seed\" can be used to alter the result predictably.\n    Speed on Core 2 Duo @ 3 GHz (single thread, SMHasher benchmark) : 5.4 GB/s */\nXXH_PUBLIC_API XXH32_hash_t XXH32 (const void* input, size_t length, unsigned int seed);\n\n/*======   Streaming   ======*/\ntypedef struct XXH32_state_s XXH32_state_t;   /* incomplete type */\nXXH_PUBLIC_API XXH32_state_t* XXH32_createState(void);\nXXH_PUBLIC_API XXH_errorcode  XXH32_freeState(XXH32_state_t* statePtr);\nXXH_PUBLIC_API void XXH32_copyState(XXH32_state_t* dst_state, const XXH32_state_t* src_state);\n\nXXH_PUBLIC_API XXH_errorcode XXH32_reset  (XXH32_state_t* statePtr, unsigned int seed);\nXXH_PUBLIC_API XXH_errorcode XXH32_update (XXH32_state_t* statePtr, const void* input, size_t length);\nXXH_PUBLIC_API XXH32_hash_t  XXH32_digest (const XXH32_state_t* statePtr);\n\n/*\n * Streaming functions generate the xxHash of an input provided in multiple segments.\n * Note that, for small input, they are slower than single-call functions, due to state management.\n * For small inputs, prefer `XXH32()` and `XXH64()`, which are better optimized.\n *\n * XXH state must first be allocated, using XXH*_createState() .\n *\n * Start a new hash by initializing state with a seed, using XXH*_reset().\n *\n * Then, feed the hash state by calling XXH*_update() as many times as necessary.\n * The function returns an error code, with 0 meaning OK, and any other value meaning there is an error.\n *\n * Finally, a hash value can be produced anytime, by using XXH*_digest().\n * This function returns the nn-bits hash as an int or long long.\n *\n * It's still possible to continue inserting input into the hash state after a digest,\n * and generate some new hashes later on, by calling again XXH*_digest().\n *\n * When done, free XXH state space if it was allocated dynamically.\n */\n\n/*======   Canonical representation   ======*/\n\ntypedef struct { unsigned char digest[4]; } XXH32_canonical_t;\nXXH_PUBLIC_API void XXH32_canonicalFromHash(XXH32_canonical_t* dst, XXH32_hash_t hash);\nXXH_PUBLIC_API XXH32_hash_t XXH32_hashFromCanonical(const XXH32_canonical_t* src);\n\n/* Default result type for XXH functions are primitive unsigned 32 and 64 bits.\n * The canonical representation uses human-readable write convention, aka big-endian (large digits first).\n * These functions allow transformation of hash result into and from its canonical format.\n * This way, hash values can be written into a file / memory, and remain comparable on different systems and programs.\n */\n\n\n#ifndef XXH_NO_LONG_LONG\n/*-**********************************************************************\n*  64-bit hash\n************************************************************************/\ntypedef unsigned long long XXH64_hash_t;\n\n/*! XXH64() :\n    Calculate the 64-bit hash of sequence of length \"len\" stored at memory address \"input\".\n    \"seed\" can be used to alter the result predictably.\n    This function runs faster on 64-bit systems, but slower on 32-bit systems (see benchmark).\n*/\nXXH_PUBLIC_API XXH64_hash_t XXH64 (const void* input, size_t length, unsigned long long seed);\n\n/*======   Streaming   ======*/\ntypedef struct XXH64_state_s XXH64_state_t;   /* incomplete type */\nXXH_PUBLIC_API XXH64_state_t* XXH64_createState(void);\nXXH_PUBLIC_API XXH_errorcode  XXH64_freeState(XXH64_state_t* statePtr);\nXXH_PUBLIC_API void XXH64_copyState(XXH64_state_t* dst_state, const XXH64_state_t* src_state);\n\nXXH_PUBLIC_API XXH_errorcode XXH64_reset  (XXH64_state_t* statePtr, unsigned long long seed);\nXXH_PUBLIC_API XXH_errorcode XXH64_update (XXH64_state_t* statePtr, const void* input, size_t length);\nXXH_PUBLIC_API XXH64_hash_t  XXH64_digest (const XXH64_state_t* statePtr);\n\n/*======   Canonical representation   ======*/\ntypedef struct { unsigned char digest[8]; } XXH64_canonical_t;\nXXH_PUBLIC_API void XXH64_canonicalFromHash(XXH64_canonical_t* dst, XXH64_hash_t hash);\nXXH_PUBLIC_API XXH64_hash_t XXH64_hashFromCanonical(const XXH64_canonical_t* src);\n#endif  /* XXH_NO_LONG_LONG */\n\n\n\n#ifdef XXH_STATIC_LINKING_ONLY\n\n/* ================================================================================================\n   This section contains declarations which are not guaranteed to remain stable.\n   They may change in future versions, becoming incompatible with a different version of the library.\n   These declarations should only be used with static linking.\n   Never use them in association with dynamic linking !\n=================================================================================================== */\n\n/* These definitions are only present to allow\n * static allocation of XXH state, on stack or in a struct for example.\n * Never **ever** use members directly. */\n\n#if !defined (__VMS) \\\n  && (defined (__cplusplus) \\\n  || (defined (__STDC_VERSION__) && (__STDC_VERSION__ >= 199901L) /* C99 */) )\n#   include <stdint.h>\n\nstruct XXH32_state_s {\n   uint32_t total_len_32;\n   uint32_t large_len;\n   uint32_t v1;\n   uint32_t v2;\n   uint32_t v3;\n   uint32_t v4;\n   uint32_t mem32[4];\n   uint32_t memsize;\n   uint32_t reserved;   /* never read nor write, might be removed in a future version */\n};   /* typedef'd to XXH32_state_t */\n\nstruct XXH64_state_s {\n   uint64_t total_len;\n   uint64_t v1;\n   uint64_t v2;\n   uint64_t v3;\n   uint64_t v4;\n   uint64_t mem64[4];\n   uint32_t memsize;\n   uint32_t reserved[2];          /* never read nor write, might be removed in a future version */\n};   /* typedef'd to XXH64_state_t */\n\n# else\n\nstruct XXH32_state_s {\n   unsigned total_len_32;\n   unsigned large_len;\n   unsigned v1;\n   unsigned v2;\n   unsigned v3;\n   unsigned v4;\n   unsigned mem32[4];\n   unsigned memsize;\n   unsigned reserved;   /* never read nor write, might be removed in a future version */\n};   /* typedef'd to XXH32_state_t */\n\n#   ifndef XXH_NO_LONG_LONG  /* remove 64-bit support */\nstruct XXH64_state_s {\n   unsigned long long total_len;\n   unsigned long long v1;\n   unsigned long long v2;\n   unsigned long long v3;\n   unsigned long long v4;\n   unsigned long long mem64[4];\n   unsigned memsize;\n   unsigned reserved[2];     /* never read nor write, might be removed in a future version */\n};   /* typedef'd to XXH64_state_t */\n#    endif\n\n# endif\n\n\n#if defined(XXH_INLINE_ALL) || defined(XXH_PRIVATE_API)\n#  include \"xxhash.c\"   /* include xxhash function bodies as `static`, for inlining */\n#endif\n\n#endif /* XXH_STATIC_LINKING_ONLY */\n\n\n#if defined (__cplusplus)\n}\n#endif\n\n#endif /* XXHASH_H_5627135585666179 */\n"
  },
  {
    "path": "external/mincrypt/dsa_sig.c",
    "content": "/*\n * Copyright 2013 The Android Open Source Project\n *\n * Redistribution and use in source and binary forms, with or without\n * modification, are permitted provided that the following conditions are met:\n *     * Redistributions of source code must retain the above copyright\n *       notice, this list of conditions and the following disclaimer.\n *     * Redistributions in binary form must reproduce the above copyright\n *       notice, this list of conditions and the following disclaimer in the\n *       documentation and/or other materials provided with the distribution.\n *     * Neither the name of Google Inc. nor the names of its contributors may\n *       be used to endorse or promote products derived from this software\n *       without specific prior written permission.\n *\n * THIS SOFTWARE IS PROVIDED BY Google Inc. ``AS IS'' AND ANY EXPRESS OR\n * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF\n * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO\n * EVENT SHALL Google Inc. BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,\n * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,\n * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS;\n * OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,\n * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR\n * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF\n * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n */\n\n#include <string.h>\n\n#include \"mincrypt/dsa_sig.h\"\n#include \"mincrypt/p256.h\"\n\n/**\n * Trims off the leading zero bytes and copy it to a buffer aligning it to the end.\n */\nstatic inline int trim_to_p256_bytes(unsigned char dst[P256_NBYTES], unsigned char *src,\n        int src_len) {\n    int dst_offset;\n    while (*src == '\\0' && src_len > 0) {\n        src++;\n        src_len--;\n    }\n    if (src_len > P256_NBYTES || src_len < 1) {\n        return 0;\n    }\n    dst_offset = P256_NBYTES - src_len;\n    memset(dst, 0, dst_offset);\n    memcpy(dst + dst_offset, src, src_len);\n    return 1;\n}\n\n/**\n * Unpacks the ASN.1 DSA signature sequence.\n */\nint dsa_sig_unpack(unsigned char* sig, int sig_len, p256_int* r_int, p256_int* s_int) {\n    /*\n     * Structure is:\n     *   0x30 0xNN  SEQUENCE + s_length\n     *     0x02 0xNN  INTEGER + r_length\n     *       0xAA 0xBB ..   r_length bytes of \"r\" (offset 4)\n     *     0x02 0xNN  INTEGER + s_length\n     *       0xMM 0xNN ..   s_length bytes of \"s\" (offset 6 + r_len)\n     */\n    int seq_len;\n    unsigned char r_bytes[P256_NBYTES];\n    unsigned char s_bytes[P256_NBYTES];\n    int r_len;\n    int s_len;\n\n    memset(r_bytes, 0, sizeof(r_bytes));\n    memset(s_bytes, 0, sizeof(s_bytes));\n\n    /*\n     * Must have at least:\n     * 2 bytes sequence header and length\n     * 2 bytes R integer header and length\n     * 1 byte of R\n     * 2 bytes S integer header and length\n     * 1 byte of S\n     *\n     * 8 bytes total\n     */\n    if (sig_len < 8 || sig[0] != 0x30 || sig[2] != 0x02) {\n        return 0;\n    }\n\n    seq_len = sig[1];\n    if ((seq_len <= 0) || (seq_len + 2 != sig_len)) {\n        return 0;\n    }\n\n    r_len = sig[3];\n    /*\n     * Must have at least:\n     * 2 bytes for R header and length\n     * 2 bytes S integer header and length\n     * 1 byte of S\n     */\n    if ((r_len < 1) || (r_len > seq_len - 5) || (sig[4 + r_len] != 0x02)) {\n        return 0;\n    }\n    s_len = sig[5 + r_len];\n\n    /**\n     * Must have:\n     * 2 bytes for R header and length\n     * r_len bytes for R\n     * 2 bytes S integer header and length\n     */\n    if ((s_len < 1) || (s_len != seq_len - 4 - r_len)) {\n        return 0;\n    }\n\n    /*\n     * ASN.1 encoded integers are zero-padded for positive integers. Make sure we have\n     * a correctly-sized buffer and that the resulting integer isn't too large.\n     */\n    if (!trim_to_p256_bytes(r_bytes, &sig[4], r_len)\n            || !trim_to_p256_bytes(s_bytes, &sig[6 + r_len], s_len)) {\n        return 0;\n    }\n\n    p256_from_bin(r_bytes, r_int);\n    p256_from_bin(s_bytes, s_int);\n\n    return 1;\n}\n"
  },
  {
    "path": "external/mincrypt/include/mincrypt/dsa_sig.h",
    "content": "/*\n * Copyright 2013 The Android Open Source Project\n *\n * Redistribution and use in source and binary forms, with or without\n * modification, are permitted provided that the following conditions are met:\n *     * Redistributions of source code must retain the above copyright\n *       notice, this list of conditions and the following disclaimer.\n *     * Redistributions in binary form must reproduce the above copyright\n *       notice, this list of conditions and the following disclaimer in the\n *       documentation and/or other materials provided with the distribution.\n *     * Neither the name of Google Inc. nor the names of its contributors may\n *       be used to endorse or promote products derived from this software\n *       without specific prior written permission.\n *\n * THIS SOFTWARE IS PROVIDED BY Google Inc. ``AS IS'' AND ANY EXPRESS OR\n * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF\n * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO\n * EVENT SHALL Google Inc. BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,\n * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,\n * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS;\n * OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,\n * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR\n * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF\n * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n */\n\n#ifndef SYSTEM_CORE_INCLUDE_MINCRYPT_DSA_SIG_H_\n#define SYSTEM_CORE_INCLUDE_MINCRYPT_DSA_SIG_H_\n\n#include \"mincrypt/p256.h\"\n\n#ifdef __cplusplus\nextern \"C\" {\n#endif\n\n// Returns 0 if input sig is not a valid ASN.1 sequence\nint dsa_sig_unpack(unsigned char* sig, int sig_len, p256_int* r_int, p256_int* s_int);\n\n#ifdef __cplusplus\n}\n#endif\n\n#endif /* SYSTEM_CORE_INCLUDE_MINCRYPT_DSA_SIG_H_ */\n"
  },
  {
    "path": "external/mincrypt/include/mincrypt/hash-internal.h",
    "content": "/*\n * Copyright 2007 The Android Open Source Project\n *\n * Redistribution and use in source and binary forms, with or without\n * modification, are permitted provided that the following conditions are met:\n *     * Redistributions of source code must retain the above copyright\n *       notice, this list of conditions and the following disclaimer.\n *     * Redistributions in binary form must reproduce the above copyright\n *       notice, this list of conditions and the following disclaimer in the\n *       documentation and/or other materials provided with the distribution.\n *     * Neither the name of Google Inc. nor the names of its contributors may\n *       be used to endorse or promote products derived from this software\n *       without specific prior written permission.\n *\n * THIS SOFTWARE IS PROVIDED BY Google Inc. ``AS IS'' AND ANY EXPRESS OR\n * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF\n * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO\n * EVENT SHALL Google Inc. BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,\n * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,\n * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS;\n * OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,\n * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR\n * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF\n * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n */\n\n#ifndef SYSTEM_CORE_INCLUDE_MINCRYPT_HASH_INTERNAL_H_\n#define SYSTEM_CORE_INCLUDE_MINCRYPT_HASH_INTERNAL_H_\n\n#include <stdint.h>\n\n#ifdef __cplusplus\nextern \"C\" {\n#endif  // __cplusplus\n\nstruct HASH_CTX;  // forward decl\n\ntypedef struct HASH_VTAB {\n  void (* const init)(struct HASH_CTX*);\n  void (* const update)(struct HASH_CTX*, const void*, int);\n  const uint8_t* (* const final)(struct HASH_CTX*);\n  const uint8_t* (* const hash)(const void*, int, uint8_t*);\n  int size;\n} HASH_VTAB;\n\ntypedef struct HASH_CTX {\n  const HASH_VTAB * f;\n  uint64_t count;\n  uint8_t buf[64];\n  uint32_t state[8];  // upto SHA2\n} HASH_CTX;\n\n#define HASH_init(ctx) (ctx)->f->init(ctx)\n#define HASH_update(ctx, data, len) (ctx)->f->update(ctx, data, len)\n#define HASH_final(ctx) (ctx)->f->final(ctx)\n#define HASH_hash(data, len, digest) (ctx)->f->hash(data, len, digest)\n#define HASH_size(ctx) (ctx)->f->size\n\n#ifdef __cplusplus\n}\n#endif  // __cplusplus\n\n#endif  // SYSTEM_CORE_INCLUDE_MINCRYPT_HASH_INTERNAL_H_\n"
  },
  {
    "path": "external/mincrypt/include/mincrypt/p256.h",
    "content": "/*\n * Copyright 2013 The Android Open Source Project\n *\n * Redistribution and use in source and binary forms, with or without\n * modification, are permitted provided that the following conditions are met:\n *     * Redistributions of source code must retain the above copyright\n *       notice, this list of conditions and the following disclaimer.\n *     * Redistributions in binary form must reproduce the above copyright\n *       notice, this list of conditions and the following disclaimer in the\n *       documentation and/or other materials provided with the distribution.\n *     * Neither the name of Google Inc. nor the names of its contributors may\n *       be used to endorse or promote products derived from this software\n *       without specific prior written permission.\n *\n * THIS SOFTWARE IS PROVIDED BY Google Inc. ``AS IS'' AND ANY EXPRESS OR\n * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF\n * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO\n * EVENT SHALL Google Inc. BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,\n * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,\n * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS;\n * OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,\n * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR\n * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF\n * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n */\n\n#ifndef SYSTEM_CORE_INCLUDE_MINCRYPT_LITE_P256_H_\n#define SYSTEM_CORE_INCLUDE_MINCRYPT_LITE_P256_H_\n\n// Collection of routines manipulating 256 bit unsigned integers.\n// Just enough to implement ecdsa-p256 and related algorithms.\n\n#include <stdint.h>\n\n#ifdef __cplusplus\nextern \"C\" {\n#endif\n\n#define P256_BITSPERDIGIT 32\n#define P256_NDIGITS 8\n#define P256_NBYTES 32\n\ntypedef int p256_err;\ntypedef uint32_t p256_digit;\ntypedef int32_t p256_sdigit;\ntypedef uint64_t p256_ddigit;\ntypedef int64_t p256_sddigit;\n\n// Defining p256_int as struct to leverage struct assigment.\ntypedef struct {\n  p256_digit a[P256_NDIGITS];\n} p256_int;\n\nextern const p256_int SECP256r1_n;  // Curve order\nextern const p256_int SECP256r1_p;  // Curve prime\nextern const p256_int SECP256r1_b;  // Curve param\n\n// Initialize a p256_int to zero.\nvoid p256_init(p256_int* a);\n\n// Clear a p256_int to zero.\nvoid p256_clear(p256_int* a);\n\n// Return bit. Index 0 is least significant.\nint p256_get_bit(const p256_int* a, int index);\n\n// b := a % MOD\nvoid p256_mod(\n    const p256_int* MOD,\n    const p256_int* a,\n    p256_int* b);\n\n// c := a * (top_b | b) % MOD\nvoid p256_modmul(\n    const p256_int* MOD,\n    const p256_int* a,\n    const p256_digit top_b,\n    const p256_int* b,\n    p256_int* c);\n\n// b := 1 / a % MOD\n// MOD best be SECP256r1_n\nvoid p256_modinv(\n    const p256_int* MOD,\n    const p256_int* a,\n    p256_int* b);\n\n// b := 1 / a % MOD\n// MOD best be SECP256r1_n\n// Faster than p256_modinv()\nvoid p256_modinv_vartime(\n    const p256_int* MOD,\n    const p256_int* a,\n    p256_int* b);\n\n// b := a << (n % P256_BITSPERDIGIT)\n// Returns the bits shifted out of most significant digit.\np256_digit p256_shl(const p256_int* a, int n, p256_int* b);\n\n// b := a >> (n % P256_BITSPERDIGIT)\nvoid p256_shr(const p256_int* a, int n, p256_int* b);\n\nint p256_is_zero(const p256_int* a);\nint p256_is_odd(const p256_int* a);\nint p256_is_even(const p256_int* a);\n\n// Returns -1, 0 or 1.\nint p256_cmp(const p256_int* a, const p256_int *b);\n\n// c: = a - b\n// Returns -1 on borrow.\nint p256_sub(const p256_int* a, const p256_int* b, p256_int* c);\n\n// c := a + b\n// Returns 1 on carry.\nint p256_add(const p256_int* a, const p256_int* b, p256_int* c);\n\n// c := a + (single digit)b\n// Returns carry 1 on carry.\nint p256_add_d(const p256_int* a, p256_digit b, p256_int* c);\n\n// ec routines.\n\n// {out_x,out_y} := nG\nvoid p256_base_point_mul(const p256_int *n,\n                         p256_int *out_x,\n                         p256_int *out_y);\n\n// {out_x,out_y} := n{in_x,in_y}\nvoid p256_point_mul(const p256_int *n,\n                    const p256_int *in_x,\n                    const p256_int *in_y,\n                    p256_int *out_x,\n                    p256_int *out_y);\n\n// {out_x,out_y} := n1G + n2{in_x,in_y}\nvoid p256_points_mul_vartime(\n    const p256_int *n1, const p256_int *n2,\n    const p256_int *in_x, const p256_int *in_y,\n    p256_int *out_x, p256_int *out_y);\n\n// Return whether point {x,y} is on curve.\nint p256_is_valid_point(const p256_int* x, const p256_int* y);\n\n// Outputs big-endian binary form. No leading zero skips.\nvoid p256_to_bin(const p256_int* src, uint8_t dst[P256_NBYTES]);\n\n// Reads from big-endian binary form,\n// thus pre-pad with leading zeros if short.\nvoid p256_from_bin(const uint8_t src[P256_NBYTES], p256_int* dst);\n\n#define P256_DIGITS(x) ((x)->a)\n#define P256_DIGIT(x,y) ((x)->a[y])\n\n#define P256_ZERO {{0}}\n#define P256_ONE {{1}}\n\n#ifdef __cplusplus\n}\n#endif\n\n#endif  // SYSTEM_CORE_INCLUDE_MINCRYPT_LITE_P256_H_\n"
  },
  {
    "path": "external/mincrypt/include/mincrypt/p256_ecdsa.h",
    "content": "/*\n * Copyright 2013 The Android Open Source Project\n *\n * Redistribution and use in source and binary forms, with or without\n * modification, are permitted provided that the following conditions are met:\n *     * Redistributions of source code must retain the above copyright\n *       notice, this list of conditions and the following disclaimer.\n *     * Redistributions in binary form must reproduce the above copyright\n *       notice, this list of conditions and the following disclaimer in the\n *       documentation and/or other materials provided with the distribution.\n *     * Neither the name of Google Inc. nor the names of its contributors may\n *       be used to endorse or promote products derived from this software\n *       without specific prior written permission.\n *\n * THIS SOFTWARE IS PROVIDED BY Google Inc. ``AS IS'' AND ANY EXPRESS OR\n * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF\n * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO\n * EVENT SHALL Google Inc. BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,\n * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,\n * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS;\n * OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,\n * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR\n * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF\n * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n */\n\n#ifndef SYSTEM_CORE_INCLUDE_MINCRYPT_P256_ECDSA_H_\n#define SYSTEM_CORE_INCLUDE_MINCRYPT_P256_ECDSA_H_\n\n// Using current directory as relative include path here since\n// this code typically gets lifted into a variety of build systems\n// and directory structures.\n#include \"p256.h\"\n\n#ifdef __cplusplus\nextern \"C\" {\n#endif\n\n// Returns 0 if {r,s} is not a signature on message for\n// public key {key_x,key_y}.\n//\n// Note: message is a p256_int.\n// Convert from a binary string using p256_from_bin().\nint p256_ecdsa_verify(const p256_int* key_x,\n                      const p256_int* key_y,\n                      const p256_int* message,\n                      const p256_int* r, const p256_int* s);\n\n#ifdef __cplusplus\n}\n#endif\n\n#endif  // SYSTEM_CORE_INCLUDE_MINCRYPT_P256_ECDSA_H_\n"
  },
  {
    "path": "external/mincrypt/include/mincrypt/rsa.h",
    "content": "/* rsa.h\n**\n** Copyright 2008, The Android Open Source Project\n**\n** Redistribution and use in source and binary forms, with or without\n** modification, are permitted provided that the following conditions are met:\n**     * Redistributions of source code must retain the above copyright\n**       notice, this list of conditions and the following disclaimer.\n**     * Redistributions in binary form must reproduce the above copyright\n**       notice, this list of conditions and the following disclaimer in the\n**       documentation and/or other materials provided with the distribution.\n**     * Neither the name of Google Inc. nor the names of its contributors may\n**       be used to endorse or promote products derived from this software\n**       without specific prior written permission.\n**\n** THIS SOFTWARE IS PROVIDED BY Google Inc. ``AS IS'' AND ANY EXPRESS OR\n** IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF\n** MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO\n** EVENT SHALL Google Inc. BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,\n** SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,\n** PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS;\n** OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,\n** WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR\n** OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF\n** ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n*/\n\n#ifndef SYSTEM_CORE_INCLUDE_MINCRYPT_RSA_H_\n#define SYSTEM_CORE_INCLUDE_MINCRYPT_RSA_H_\n\n#include <inttypes.h>\n\n#ifdef __cplusplus\nextern \"C\" {\n#endif\n\n#define RSANUMBYTES 256           /* 2048 bit key length */\n#define RSANUMWORDS (RSANUMBYTES / sizeof(uint32_t))\n\ntypedef struct RSAPublicKey {\n    int len;                  /* Length of n[] in number of uint32_t */\n    uint32_t n0inv;           /* -1 / n[0] mod 2^32 */\n    uint32_t n[RSANUMWORDS];  /* modulus as little endian array */\n    uint32_t rr[RSANUMWORDS]; /* R^2 as little endian array */\n    int exponent;             /* 3 or 65537 */\n} RSAPublicKey;\n\nint RSA_verify(const RSAPublicKey *key,\n               const uint8_t* signature,\n               const int len,\n               const uint8_t* hash,\n               const int hash_len);\n\n#ifdef __cplusplus\n}\n#endif\n\n#endif // SYSTEM_CORE_INCLUDE_MINCRYPT_RSA_H_\n"
  },
  {
    "path": "external/mincrypt/include/mincrypt/sha.h",
    "content": "/*\n * Copyright 2005 The Android Open Source Project\n *\n * Redistribution and use in source and binary forms, with or without\n * modification, are permitted provided that the following conditions are met:\n *     * Redistributions of source code must retain the above copyright\n *       notice, this list of conditions and the following disclaimer.\n *     * Redistributions in binary form must reproduce the above copyright\n *       notice, this list of conditions and the following disclaimer in the\n *       documentation and/or other materials provided with the distribution.\n *     * Neither the name of Google Inc. nor the names of its contributors may\n *       be used to endorse or promote products derived from this software\n *       without specific prior written permission.\n *\n * THIS SOFTWARE IS PROVIDED BY Google Inc. ``AS IS'' AND ANY EXPRESS OR\n * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF\n * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO\n * EVENT SHALL Google Inc. BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,\n * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,\n * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS;\n * OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,\n * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR\n * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF\n * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n */\n#ifndef SYSTEM_CORE_INCLUDE_MINCRYPT_SHA1_H_\n#define SYSTEM_CORE_INCLUDE_MINCRYPT_SHA1_H_\n\n#include <stdint.h>\n#include \"hash-internal.h\"\n\n#ifdef __cplusplus\nextern \"C\" {\n#endif // __cplusplus\n\ntypedef HASH_CTX SHA_CTX;\n\nvoid SHA_init(SHA_CTX* ctx);\nvoid SHA_update(SHA_CTX* ctx, const void* data, int len);\nconst uint8_t* SHA_final(SHA_CTX* ctx);\n\n// Convenience method. Returns digest address.\n// NOTE: *digest needs to hold SHA_DIGEST_SIZE bytes.\nconst uint8_t* SHA_hash(const void* data, int len, uint8_t* digest);\n\n#define SHA_DIGEST_SIZE 20\n\n#ifdef __cplusplus\n}\n#endif // __cplusplus\n\n#endif  // SYSTEM_CORE_INCLUDE_MINCRYPT_SHA1_H_\n"
  },
  {
    "path": "external/mincrypt/include/mincrypt/sha256.h",
    "content": "/*\n * Copyright 2011 The Android Open Source Project\n *\n * Redistribution and use in source and binary forms, with or without\n * modification, are permitted provided that the following conditions are met:\n *     * Redistributions of source code must retain the above copyright\n *       notice, this list of conditions and the following disclaimer.\n *     * Redistributions in binary form must reproduce the above copyright\n *       notice, this list of conditions and the following disclaimer in the\n *       documentation and/or other materials provided with the distribution.\n *     * Neither the name of Google Inc. nor the names of its contributors may\n *       be used to endorse or promote products derived from this software\n *       without specific prior written permission.\n *\n * THIS SOFTWARE IS PROVIDED BY Google Inc. ``AS IS'' AND ANY EXPRESS OR\n * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF\n * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO\n * EVENT SHALL Google Inc. BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,\n * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,\n * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS;\n * OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,\n * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR\n * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF\n * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n */\n\n#ifndef SYSTEM_CORE_INCLUDE_MINCRYPT_SHA256_H_\n#define SYSTEM_CORE_INCLUDE_MINCRYPT_SHA256_H_\n\n#include <stdint.h>\n#include \"hash-internal.h\"\n\n#ifdef __cplusplus\nextern \"C\" {\n#endif // __cplusplus\n\ntypedef HASH_CTX SHA256_CTX;\n\nvoid SHA256_init(SHA256_CTX* ctx);\nvoid SHA256_update(SHA256_CTX* ctx, const void* data, int len);\nconst uint8_t* SHA256_final(SHA256_CTX* ctx);\n\n// Convenience method. Returns digest address.\nconst uint8_t* SHA256_hash(const void* data, int len, uint8_t* digest);\n\n#define SHA256_DIGEST_SIZE 32\n\n#ifdef __cplusplus\n}\n#endif // __cplusplus\n\n#endif  // SYSTEM_CORE_INCLUDE_MINCRYPT_SHA256_H_\n"
  },
  {
    "path": "external/mincrypt/p256.c",
    "content": "/*\n * Copyright 2013 The Android Open Source Project\n *\n * Redistribution and use in source and binary forms, with or without\n * modification, are permitted provided that the following conditions are met:\n *     * Redistributions of source code must retain the above copyright\n *       notice, this list of conditions and the following disclaimer.\n *     * Redistributions in binary form must reproduce the above copyright\n *       notice, this list of conditions and the following disclaimer in the\n *       documentation and/or other materials provided with the distribution.\n *     * Neither the name of Google Inc. nor the names of its contributors may\n *       be used to endorse or promote products derived from this software\n *       without specific prior written permission.\n *\n * THIS SOFTWARE IS PROVIDED BY Google Inc. ``AS IS'' AND ANY EXPRESS OR\n * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF\n * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO\n * EVENT SHALL Google Inc. BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,\n * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,\n * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS;\n * OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,\n * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR\n * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF\n * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n */\n\n// This is an implementation of the P256 elliptic curve group. It's written to\n// be portable 32-bit, although it's still constant-time.\n//\n// WARNING: Implementing these functions in a constant-time manner is far from\n//          obvious. Be careful when touching this code.\n//\n// See http://www.imperialviolet.org/2010/12/04/ecc.html ([1]) for background.\n\n#include <assert.h>\n#include <stdint.h>\n#include <string.h>\n#include <stdio.h>\n\n#include \"mincrypt/p256.h\"\n\nconst p256_int SECP256r1_n =  // curve order\n  {{0xfc632551, 0xf3b9cac2, 0xa7179e84, 0xbce6faad, -1, -1, 0, -1}};\n\nconst p256_int SECP256r1_p =  // curve field size\n  {{-1, -1, -1, 0, 0, 0, 1, -1 }};\n\nconst p256_int SECP256r1_b =  // curve b\n  {{0x27d2604b, 0x3bce3c3e, 0xcc53b0f6, 0x651d06b0,\n    0x769886bc, 0xb3ebbd55, 0xaa3a93e7, 0x5ac635d8}};\n\nvoid p256_init(p256_int* a) {\n  memset(a, 0, sizeof(*a));\n}\n\nvoid p256_clear(p256_int* a) { p256_init(a); }\n\nint p256_get_bit(const p256_int* scalar, int bit) {\n  return (P256_DIGIT(scalar, bit / P256_BITSPERDIGIT)\n              >> (bit & (P256_BITSPERDIGIT - 1))) & 1;\n}\n\nint p256_is_zero(const p256_int* a) {\n  int i, result = 0;\n  for (i = 0; i < P256_NDIGITS; ++i) result |= P256_DIGIT(a, i);\n  return !result;\n}\n\n// top, c[] += a[] * b\n// Returns new top\nstatic p256_digit mulAdd(const p256_int* a,\n                         p256_digit b,\n                         p256_digit top,\n                         p256_digit* c) {\n  int i;\n  p256_ddigit carry = 0;\n\n  for (i = 0; i < P256_NDIGITS; ++i) {\n    carry += *c;\n    carry += (p256_ddigit)P256_DIGIT(a, i) * b;\n    *c++ = (p256_digit)carry;\n    carry >>= P256_BITSPERDIGIT;\n  }\n  return top + (p256_digit)carry;\n}\n\n// top, c[] -= top_a, a[]\nstatic p256_digit subTop(p256_digit top_a,\n                         const p256_digit* a,\n                         p256_digit top_c,\n                         p256_digit* c) {\n  int i;\n  p256_sddigit borrow = 0;\n\n  for (i = 0; i < P256_NDIGITS; ++i) {\n    borrow += *c;\n    borrow -= *a++;\n    *c++ = (p256_digit)borrow;\n    borrow >>= P256_BITSPERDIGIT;\n  }\n  borrow += top_c;\n  borrow -= top_a;\n  top_c = (p256_digit)borrow;\n  assert((borrow >> P256_BITSPERDIGIT) == 0);\n  return top_c;\n}\n\n// top, c[] -= MOD[] & mask (0 or -1)\n// returns new top.\nstatic p256_digit subM(const p256_int* MOD,\n                       p256_digit top,\n                       p256_digit* c,\n                       p256_digit mask) {\n  int i;\n  p256_sddigit borrow = 0;\n  for (i = 0; i < P256_NDIGITS; ++i) {\n    borrow += *c;\n    borrow -= P256_DIGIT(MOD, i) & mask;\n    *c++ = (p256_digit)borrow;\n    borrow >>= P256_BITSPERDIGIT;\n  }\n  return top + (p256_digit)borrow;\n}\n\n// top, c[] += MOD[] & mask (0 or -1)\n// returns new top.\nstatic p256_digit addM(const p256_int* MOD,\n                       p256_digit top,\n                       p256_digit* c,\n                       p256_digit mask) {\n  int i;\n  p256_ddigit carry = 0;\n  for (i = 0; i < P256_NDIGITS; ++i) {\n    carry += *c;\n    carry += P256_DIGIT(MOD, i) & mask;\n    *c++ = (p256_digit)carry;\n    carry >>= P256_BITSPERDIGIT;\n  }\n  return top + (p256_digit)carry;\n}\n\n// c = a * b mod MOD. c can be a and/or b.\nvoid p256_modmul(const p256_int* MOD,\n                 const p256_int* a,\n                 const p256_digit top_b,\n                 const p256_int* b,\n                 p256_int* c) {\n  p256_digit tmp[P256_NDIGITS * 2 + 1] = { 0 };\n  p256_digit top = 0;\n  int i;\n\n  // Multiply/add into tmp.\n  for (i = 0; i < P256_NDIGITS; ++i) {\n    if (i) tmp[i + P256_NDIGITS - 1] = top;\n    top = mulAdd(a, P256_DIGIT(b, i), 0, tmp + i);\n  }\n\n  // Multiply/add top digit\n  tmp[i + P256_NDIGITS - 1] = top;\n  top = mulAdd(a, top_b, 0, tmp + i);\n\n  // Reduce tmp, digit by digit.\n  for (; i >= 0; --i) {\n    p256_digit reducer[P256_NDIGITS] = { 0 };\n    p256_digit top_reducer;\n\n    // top can be any value at this point.\n    // Guestimate reducer as top * MOD, since msw of MOD is -1.\n    top_reducer = mulAdd(MOD, top, 0, reducer);\n\n    // Subtract reducer from top | tmp.\n    top = subTop(top_reducer, reducer, top, tmp + i);\n\n    // top is now either 0 or 1. Make it 0, fixed-timing.\n    assert(top <= 1);\n\n    top = subM(MOD, top, tmp + i, ~(top - 1));\n\n    assert(top == 0);\n\n    // We have now reduced the top digit off tmp. Fetch new top digit.\n    top = tmp[i + P256_NDIGITS - 1];\n  }\n\n  // tmp might still be larger than MOD, yet same bit length.\n  // Make sure it is less, fixed-timing.\n  addM(MOD, 0, tmp, subM(MOD, 0, tmp, -1));\n\n  memcpy(c, tmp, P256_NBYTES);\n}\nint p256_is_odd(const p256_int* a) { return P256_DIGIT(a, 0) & 1; }\nint p256_is_even(const p256_int* a) { return !(P256_DIGIT(a, 0) & 1); }\n\np256_digit p256_shl(const p256_int* a, int n, p256_int* b) {\n  int i;\n  p256_digit top = P256_DIGIT(a, P256_NDIGITS - 1);\n\n  n %= P256_BITSPERDIGIT;\n  for (i = P256_NDIGITS - 1; i > 0; --i) {\n    p256_digit accu = (P256_DIGIT(a, i) << n);\n    accu |= (P256_DIGIT(a, i - 1) >> (P256_BITSPERDIGIT - n));\n    P256_DIGIT(b, i) = accu;\n  }\n  P256_DIGIT(b, i) = (P256_DIGIT(a, i) << n);\n\n  top = (p256_digit)((((p256_ddigit)top) << n) >> P256_BITSPERDIGIT);\n\n  return top;\n}\n\nvoid p256_shr(const p256_int* a, int n, p256_int* b) {\n  int i;\n\n  n %= P256_BITSPERDIGIT;\n  for (i = 0; i < P256_NDIGITS - 1; ++i) {\n    p256_digit accu = (P256_DIGIT(a, i) >> n);\n    accu |= (P256_DIGIT(a, i + 1) << (P256_BITSPERDIGIT - n));\n    P256_DIGIT(b, i) = accu;\n  }\n  P256_DIGIT(b, i) = (P256_DIGIT(a, i) >> n);\n}\n\nstatic void p256_shr1(const p256_int* a, int highbit, p256_int* b) {\n  int i;\n\n  for (i = 0; i < P256_NDIGITS - 1; ++i) {\n    p256_digit accu = (P256_DIGIT(a, i) >> 1);\n    accu |= (P256_DIGIT(a, i + 1) << (P256_BITSPERDIGIT - 1));\n    P256_DIGIT(b, i) = accu;\n  }\n  P256_DIGIT(b, i) = (P256_DIGIT(a, i) >> 1) |\n      (highbit << (P256_BITSPERDIGIT - 1));\n}\n\n// Return -1, 0, 1 for a < b, a == b or a > b respectively.\nint p256_cmp(const p256_int* a, const p256_int* b) {\n  int i;\n  p256_sddigit borrow = 0;\n  p256_digit notzero = 0;\n\n  for (i = 0; i < P256_NDIGITS; ++i) {\n    borrow += (p256_sddigit)P256_DIGIT(a, i) - P256_DIGIT(b, i);\n    // Track whether any result digit is ever not zero.\n    // Relies on !!(non-zero) evaluating to 1, e.g., !!(-1) evaluating to 1.\n    notzero |= !!((p256_digit)borrow);\n    borrow >>= P256_BITSPERDIGIT;\n  }\n  return (int)borrow | notzero;\n}\n\n// c = a - b. Returns borrow: 0 or -1.\nint p256_sub(const p256_int* a, const p256_int* b, p256_int* c) {\n  int i;\n  p256_sddigit borrow = 0;\n\n  for (i = 0; i < P256_NDIGITS; ++i) {\n    borrow += (p256_sddigit)P256_DIGIT(a, i) - P256_DIGIT(b, i);\n    if (c) P256_DIGIT(c, i) = (p256_digit)borrow;\n    borrow >>= P256_BITSPERDIGIT;\n  }\n  return (int)borrow;\n}\n\n// c = a + b. Returns carry: 0 or 1.\nint p256_add(const p256_int* a, const p256_int* b, p256_int* c) {\n  int i;\n  p256_ddigit carry = 0;\n\n  for (i = 0; i < P256_NDIGITS; ++i) {\n    carry += (p256_ddigit)P256_DIGIT(a, i) + P256_DIGIT(b, i);\n    if (c) P256_DIGIT(c, i) = (p256_digit)carry;\n    carry >>= P256_BITSPERDIGIT;\n  }\n  return (int)carry;\n}\n\n// b = a + d. Returns carry, 0 or 1.\nint p256_add_d(const p256_int* a, p256_digit d, p256_int* b) {\n  int i;\n  p256_ddigit carry = d;\n\n  for (i = 0; i < P256_NDIGITS; ++i) {\n    carry += (p256_ddigit)P256_DIGIT(a, i);\n    if (b) P256_DIGIT(b, i) = (p256_digit)carry;\n    carry >>= P256_BITSPERDIGIT;\n  }\n  return (int)carry;\n}\n\n// b = 1/a mod MOD, binary euclid.\nvoid p256_modinv_vartime(const p256_int* MOD,\n                         const p256_int* a,\n                         p256_int* b) {\n  p256_int R = P256_ZERO;\n  p256_int S = P256_ONE;\n  p256_int U = *MOD;\n  p256_int V = *a;\n\n  for (;;) {\n    if (p256_is_even(&U)) {\n      p256_shr1(&U, 0, &U);\n      if (p256_is_even(&R)) {\n        p256_shr1(&R, 0, &R);\n      } else {\n        // R = (R+MOD)/2\n        p256_shr1(&R, p256_add(&R, MOD, &R), &R);\n      }\n    } else if (p256_is_even(&V)) {\n      p256_shr1(&V, 0, &V);\n      if (p256_is_even(&S)) {\n        p256_shr1(&S, 0, &S);\n      } else {\n        // S = (S+MOD)/2\n        p256_shr1(&S, p256_add(&S, MOD, &S) , &S);\n      }\n    } else {  // U,V both odd.\n      if (!p256_sub(&V, &U, NULL)) {\n        p256_sub(&V, &U, &V);\n        if (p256_sub(&S, &R, &S)) p256_add(&S, MOD, &S);\n        if (p256_is_zero(&V)) break;  // done.\n      } else {\n        p256_sub(&U, &V, &U);\n        if (p256_sub(&R, &S, &R)) p256_add(&R, MOD, &R);\n      }\n    }\n  }\n\n  p256_mod(MOD, &R, b);\n}\n\nvoid p256_mod(const p256_int* MOD,\n              const p256_int* in,\n              p256_int* out) {\n  if (out != in) *out = *in;\n  addM(MOD, 0, P256_DIGITS(out), subM(MOD, 0, P256_DIGITS(out), -1));\n}\n\n// Verify y^2 == x^3 - 3x + b mod p\n// and 0 < x < p and 0 < y < p\nint p256_is_valid_point(const p256_int* x, const p256_int* y) {\n  p256_int y2, x3;\n\n  if (p256_cmp(&SECP256r1_p, x) <= 0 ||\n      p256_cmp(&SECP256r1_p, y) <= 0 ||\n      p256_is_zero(x) ||\n      p256_is_zero(y)) return 0;\n\n  p256_modmul(&SECP256r1_p, y, 0, y, &y2);  // y^2\n\n  p256_modmul(&SECP256r1_p, x, 0, x, &x3);  // x^2\n  p256_modmul(&SECP256r1_p, x, 0, &x3, &x3);  // x^3\n  if (p256_sub(&x3, x, &x3)) p256_add(&x3, &SECP256r1_p, &x3);  // x^3 - x\n  if (p256_sub(&x3, x, &x3)) p256_add(&x3, &SECP256r1_p, &x3);  // x^3 - 2x\n  if (p256_sub(&x3, x, &x3)) p256_add(&x3, &SECP256r1_p, &x3);  // x^3 - 3x\n  if (p256_add(&x3, &SECP256r1_b, &x3))  // x^3 - 3x + b\n    p256_sub(&x3, &SECP256r1_p, &x3);\n\n  return p256_cmp(&y2, &x3) == 0;\n}\n\nvoid p256_from_bin(const uint8_t src[P256_NBYTES], p256_int* dst) {\n  int i;\n  const uint8_t* p = &src[0];\n\n  for (i = P256_NDIGITS - 1; i >= 0; --i) {\n    P256_DIGIT(dst, i) =\n        (p[0] << 24) |\n        (p[1] << 16) |\n        (p[2] << 8) |\n        p[3];\n    p += 4;\n  }\n}\n"
  },
  {
    "path": "external/mincrypt/p256_ec.c",
    "content": "/*\n * Copyright 2013 The Android Open Source Project\n *\n * Redistribution and use in source and binary forms, with or without\n * modification, are permitted provided that the following conditions are met:\n *     * Redistributions of source code must retain the above copyright\n *       notice, this list of conditions and the following disclaimer.\n *     * Redistributions in binary form must reproduce the above copyright\n *       notice, this list of conditions and the following disclaimer in the\n *       documentation and/or other materials provided with the distribution.\n *     * Neither the name of Google Inc. nor the names of its contributors may\n *       be used to endorse or promote products derived from this software\n *       without specific prior written permission.\n *\n * THIS SOFTWARE IS PROVIDED BY Google Inc. ``AS IS'' AND ANY EXPRESS OR\n * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF\n * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO\n * EVENT SHALL Google Inc. BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,\n * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,\n * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS;\n * OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,\n * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR\n * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF\n * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n */\n\n// This is an implementation of the P256 elliptic curve group. It's written to\n// be portable 32-bit, although it's still constant-time.\n//\n// WARNING: Implementing these functions in a constant-time manner is far from\n//          obvious. Be careful when touching this code.\n//\n// See http://www.imperialviolet.org/2010/12/04/ecc.html ([1]) for background.\n\n#include <stdint.h>\n#include <stdio.h>\n\n#include <string.h>\n#include <stdlib.h>\n\n#include \"mincrypt/p256.h\"\n\ntypedef uint8_t u8;\ntypedef uint32_t u32;\ntypedef int32_t s32;\ntypedef uint64_t u64;\n\n/* Our field elements are represented as nine 32-bit limbs.\n *\n * The value of an felem (field element) is:\n *   x[0] + (x[1] * 2**29) + (x[2] * 2**57) + ... + (x[8] * 2**228)\n *\n * That is, each limb is alternately 29 or 28-bits wide in little-endian\n * order.\n *\n * This means that an felem hits 2**257, rather than 2**256 as we would like. A\n * 28, 29, ... pattern would cause us to hit 2**256, but that causes problems\n * when multiplying as terms end up one bit short of a limb which would require\n * much bit-shifting to correct.\n *\n * Finally, the values stored in an felem are in Montgomery form. So the value\n * |y| is stored as (y*R) mod p, where p is the P-256 prime and R is 2**257.\n */\ntypedef u32 limb;\n#define NLIMBS 9\ntypedef limb felem[NLIMBS];\n\nstatic const limb kBottom28Bits = 0xfffffff;\nstatic const limb kBottom29Bits = 0x1fffffff;\n\n/* kOne is the number 1 as an felem. It's 2**257 mod p split up into 29 and\n * 28-bit words. */\nstatic const felem kOne = {\n    2, 0, 0, 0xffff800,\n    0x1fffffff, 0xfffffff, 0x1fbfffff, 0x1ffffff,\n    0\n};\nstatic const felem kZero = {0};\nstatic const felem kP = {\n    0x1fffffff, 0xfffffff, 0x1fffffff, 0x3ff,\n    0, 0, 0x200000, 0xf000000,\n    0xfffffff\n};\nstatic const felem k2P = {\n    0x1ffffffe, 0xfffffff, 0x1fffffff, 0x7ff,\n    0, 0, 0x400000, 0xe000000,\n    0x1fffffff\n};\n/* kPrecomputed contains precomputed values to aid the calculation of scalar\n * multiples of the base point, G. It's actually two, equal length, tables\n * concatenated.\n *\n * The first table contains (x,y) felem pairs for 16 multiples of the base\n * point, G.\n *\n *   Index  |  Index (binary) | Value\n *       0  |           0000  | 0G (all zeros, omitted)\n *       1  |           0001  | G\n *       2  |           0010  | 2**64G\n *       3  |           0011  | 2**64G + G\n *       4  |           0100  | 2**128G\n *       5  |           0101  | 2**128G + G\n *       6  |           0110  | 2**128G + 2**64G\n *       7  |           0111  | 2**128G + 2**64G + G\n *       8  |           1000  | 2**192G\n *       9  |           1001  | 2**192G + G\n *      10  |           1010  | 2**192G + 2**64G\n *      11  |           1011  | 2**192G + 2**64G + G\n *      12  |           1100  | 2**192G + 2**128G\n *      13  |           1101  | 2**192G + 2**128G + G\n *      14  |           1110  | 2**192G + 2**128G + 2**64G\n *      15  |           1111  | 2**192G + 2**128G + 2**64G + G\n *\n * The second table follows the same style, but the terms are 2**32G,\n * 2**96G, 2**160G, 2**224G.\n *\n * This is ~2KB of data. */\nstatic const limb kPrecomputed[NLIMBS * 2 * 15 * 2] = {\n    0x11522878, 0xe730d41, 0xdb60179, 0x4afe2ff, 0x12883add, 0xcaddd88, 0x119e7edc, 0xd4a6eab, 0x3120bee,\n    0x1d2aac15, 0xf25357c, 0x19e45cdd, 0x5c721d0, 0x1992c5a5, 0xa237487, 0x154ba21, 0x14b10bb, 0xae3fe3,\n    0xd41a576, 0x922fc51, 0x234994f, 0x60b60d3, 0x164586ae, 0xce95f18, 0x1fe49073, 0x3fa36cc, 0x5ebcd2c,\n    0xb402f2f, 0x15c70bf, 0x1561925c, 0x5a26704, 0xda91e90, 0xcdc1c7f, 0x1ea12446, 0xe1ade1e, 0xec91f22,\n    0x26f7778, 0x566847e, 0xa0bec9e, 0x234f453, 0x1a31f21a, 0xd85e75c, 0x56c7109, 0xa267a00, 0xb57c050,\n    0x98fb57, 0xaa837cc, 0x60c0792, 0xcfa5e19, 0x61bab9e, 0x589e39b, 0xa324c5, 0x7d6dee7, 0x2976e4b,\n    0x1fc4124a, 0xa8c244b, 0x1ce86762, 0xcd61c7e, 0x1831c8e0, 0x75774e1, 0x1d96a5a9, 0x843a649, 0xc3ab0fa,\n    0x6e2e7d5, 0x7673a2a, 0x178b65e8, 0x4003e9b, 0x1a1f11c2, 0x7816ea, 0xf643e11, 0x58c43df, 0xf423fc2,\n    0x19633ffa, 0x891f2b2, 0x123c231c, 0x46add8c, 0x54700dd, 0x59e2b17, 0x172db40f, 0x83e277d, 0xb0dd609,\n    0xfd1da12, 0x35c6e52, 0x19ede20c, 0xd19e0c0, 0x97d0f40, 0xb015b19, 0x449e3f5, 0xe10c9e, 0x33ab581,\n    0x56a67ab, 0x577734d, 0x1dddc062, 0xc57b10d, 0x149b39d, 0x26a9e7b, 0xc35df9f, 0x48764cd, 0x76dbcca,\n    0xca4b366, 0xe9303ab, 0x1a7480e7, 0x57e9e81, 0x1e13eb50, 0xf466cf3, 0x6f16b20, 0x4ba3173, 0xc168c33,\n    0x15cb5439, 0x6a38e11, 0x73658bd, 0xb29564f, 0x3f6dc5b, 0x53b97e, 0x1322c4c0, 0x65dd7ff, 0x3a1e4f6,\n    0x14e614aa, 0x9246317, 0x1bc83aca, 0xad97eed, 0xd38ce4a, 0xf82b006, 0x341f077, 0xa6add89, 0x4894acd,\n    0x9f162d5, 0xf8410ef, 0x1b266a56, 0xd7f223, 0x3e0cb92, 0xe39b672, 0x6a2901a, 0x69a8556, 0x7e7c0,\n    0x9b7d8d3, 0x309a80, 0x1ad05f7f, 0xc2fb5dd, 0xcbfd41d, 0x9ceb638, 0x1051825c, 0xda0cf5b, 0x812e881,\n    0x6f35669, 0x6a56f2c, 0x1df8d184, 0x345820, 0x1477d477, 0x1645db1, 0xbe80c51, 0xc22be3e, 0xe35e65a,\n    0x1aeb7aa0, 0xc375315, 0xf67bc99, 0x7fdd7b9, 0x191fc1be, 0x61235d, 0x2c184e9, 0x1c5a839, 0x47a1e26,\n    0xb7cb456, 0x93e225d, 0x14f3c6ed, 0xccc1ac9, 0x17fe37f3, 0x4988989, 0x1a90c502, 0x2f32042, 0xa17769b,\n    0xafd8c7c, 0x8191c6e, 0x1dcdb237, 0x16200c0, 0x107b32a1, 0x66c08db, 0x10d06a02, 0x3fc93, 0x5620023,\n    0x16722b27, 0x68b5c59, 0x270fcfc, 0xfad0ecc, 0xe5de1c2, 0xeab466b, 0x2fc513c, 0x407f75c, 0xbaab133,\n    0x9705fe9, 0xb88b8e7, 0x734c993, 0x1e1ff8f, 0x19156970, 0xabd0f00, 0x10469ea7, 0x3293ac0, 0xcdc98aa,\n    0x1d843fd, 0xe14bfe8, 0x15be825f, 0x8b5212, 0xeb3fb67, 0x81cbd29, 0xbc62f16, 0x2b6fcc7, 0xf5a4e29,\n    0x13560b66, 0xc0b6ac2, 0x51ae690, 0xd41e271, 0xf3e9bd4, 0x1d70aab, 0x1029f72, 0x73e1c35, 0xee70fbc,\n    0xad81baf, 0x9ecc49a, 0x86c741e, 0xfe6be30, 0x176752e7, 0x23d416, 0x1f83de85, 0x27de188, 0x66f70b8,\n    0x181cd51f, 0x96b6e4c, 0x188f2335, 0xa5df759, 0x17a77eb6, 0xfeb0e73, 0x154ae914, 0x2f3ec51, 0x3826b59,\n    0xb91f17d, 0x1c72949, 0x1362bf0a, 0xe23fddf, 0xa5614b0, 0xf7d8f, 0x79061, 0x823d9d2, 0x8213f39,\n    0x1128ae0b, 0xd095d05, 0xb85c0c2, 0x1ecb2ef, 0x24ddc84, 0xe35e901, 0x18411a4a, 0xf5ddc3d, 0x3786689,\n    0x52260e8, 0x5ae3564, 0x542b10d, 0x8d93a45, 0x19952aa4, 0x996cc41, 0x1051a729, 0x4be3499, 0x52b23aa,\n    0x109f307e, 0x6f5b6bb, 0x1f84e1e7, 0x77a0cfa, 0x10c4df3f, 0x25a02ea, 0xb048035, 0xe31de66, 0xc6ecaa3,\n    0x28ea335, 0x2886024, 0x1372f020, 0xf55d35, 0x15e4684c, 0xf2a9e17, 0x1a4a7529, 0xcb7beb1, 0xb2a78a1,\n    0x1ab21f1f, 0x6361ccf, 0x6c9179d, 0xb135627, 0x1267b974, 0x4408bad, 0x1cbff658, 0xe3d6511, 0xc7d76f,\n    0x1cc7a69, 0xe7ee31b, 0x54fab4f, 0x2b914f, 0x1ad27a30, 0xcd3579e, 0xc50124c, 0x50daa90, 0xb13f72,\n    0xb06aa75, 0x70f5cc6, 0x1649e5aa, 0x84a5312, 0x329043c, 0x41c4011, 0x13d32411, 0xb04a838, 0xd760d2d,\n    0x1713b532, 0xbaa0c03, 0x84022ab, 0x6bcf5c1, 0x2f45379, 0x18ae070, 0x18c9e11e, 0x20bca9a, 0x66f496b,\n    0x3eef294, 0x67500d2, 0xd7f613c, 0x2dbbeb, 0xb741038, 0xe04133f, 0x1582968d, 0xbe985f7, 0x1acbc1a,\n    0x1a6a939f, 0x33e50f6, 0xd665ed4, 0xb4b7bd6, 0x1e5a3799, 0x6b33847, 0x17fa56ff, 0x65ef930, 0x21dc4a,\n    0x2b37659, 0x450fe17, 0xb357b65, 0xdf5efac, 0x15397bef, 0x9d35a7f, 0x112ac15f, 0x624e62e, 0xa90ae2f,\n    0x107eecd2, 0x1f69bbe, 0x77d6bce, 0x5741394, 0x13c684fc, 0x950c910, 0x725522b, 0xdc78583, 0x40eeabb,\n    0x1fde328a, 0xbd61d96, 0xd28c387, 0x9e77d89, 0x12550c40, 0x759cb7d, 0x367ef34, 0xae2a960, 0x91b8bdc,\n    0x93462a9, 0xf469ef, 0xb2e9aef, 0xd2ca771, 0x54e1f42, 0x7aaa49, 0x6316abb, 0x2413c8e, 0x5425bf9,\n    0x1bed3e3a, 0xf272274, 0x1f5e7326, 0x6416517, 0xea27072, 0x9cedea7, 0x6e7633, 0x7c91952, 0xd806dce,\n    0x8e2a7e1, 0xe421e1a, 0x418c9e1, 0x1dbc890, 0x1b395c36, 0xa1dc175, 0x1dc4ef73, 0x8956f34, 0xe4b5cf2,\n    0x1b0d3a18, 0x3194a36, 0x6c2641f, 0xe44124c, 0xa2f4eaa, 0xa8c25ba, 0xf927ed7, 0x627b614, 0x7371cca,\n    0xba16694, 0x417bc03, 0x7c0a7e3, 0x9c35c19, 0x1168a205, 0x8b6b00d, 0x10e3edc9, 0x9c19bf2, 0x5882229,\n    0x1b2b4162, 0xa5cef1a, 0x1543622b, 0x9bd433e, 0x364e04d, 0x7480792, 0x5c9b5b3, 0xe85ff25, 0x408ef57,\n    0x1814cfa4, 0x121b41b, 0xd248a0f, 0x3b05222, 0x39bb16a, 0xc75966d, 0xa038113, 0xa4a1769, 0x11fbc6c,\n    0x917e50e, 0xeec3da8, 0x169d6eac, 0x10c1699, 0xa416153, 0xf724912, 0x15cd60b7, 0x4acbad9, 0x5efc5fa,\n    0xf150ed7, 0x122b51, 0x1104b40a, 0xcb7f442, 0xfbb28ff, 0x6ac53ca, 0x196142cc, 0x7bf0fa9, 0x957651,\n    0x4e0f215, 0xed439f8, 0x3f46bd5, 0x5ace82f, 0x110916b6, 0x6db078, 0xffd7d57, 0xf2ecaac, 0xca86dec,\n    0x15d6b2da, 0x965ecc9, 0x1c92b4c2, 0x1f3811, 0x1cb080f5, 0x2d8b804, 0x19d1c12d, 0xf20bd46, 0x1951fa7,\n    0xa3656c3, 0x523a425, 0xfcd0692, 0xd44ddc8, 0x131f0f5b, 0xaf80e4a, 0xcd9fc74, 0x99bb618, 0x2db944c,\n    0xa673090, 0x1c210e1, 0x178c8d23, 0x1474383, 0x10b8743d, 0x985a55b, 0x2e74779, 0x576138, 0x9587927,\n    0x133130fa, 0xbe05516, 0x9f4d619, 0xbb62570, 0x99ec591, 0xd9468fe, 0x1d07782d, 0xfc72e0b, 0x701b298,\n    0x1863863b, 0x85954b8, 0x121a0c36, 0x9e7fedf, 0xf64b429, 0x9b9d71e, 0x14e2f5d8, 0xf858d3a, 0x942eea8,\n    0xda5b765, 0x6edafff, 0xa9d18cc, 0xc65e4ba, 0x1c747e86, 0xe4ea915, 0x1981d7a1, 0x8395659, 0x52ed4e2,\n    0x87d43b7, 0x37ab11b, 0x19d292ce, 0xf8d4692, 0x18c3053f, 0x8863e13, 0x4c146c0, 0x6bdf55a, 0x4e4457d,\n    0x16152289, 0xac78ec2, 0x1a59c5a2, 0x2028b97, 0x71c2d01, 0x295851f, 0x404747b, 0x878558d, 0x7d29aa4,\n    0x13d8341f, 0x8daefd7, 0x139c972d, 0x6b7ea75, 0xd4a9dde, 0xff163d8, 0x81d55d7, 0xa5bef68, 0xb7b30d8,\n    0xbe73d6f, 0xaa88141, 0xd976c81, 0x7e7a9cc, 0x18beb771, 0xd773cbd, 0x13f51951, 0x9d0c177, 0x1c49a78,\n};\n\n\n/* Field element operations: */\n\n/* NON_ZERO_TO_ALL_ONES returns:\n *   0xffffffff for 0 < x <= 2**31\n *   0 for x == 0 or x > 2**31.\n *\n * x must be a u32 or an equivalent type such as limb. */\n#define NON_ZERO_TO_ALL_ONES(x) ((((u32)(x) - 1) >> 31) - 1)\n\n/* felem_reduce_carry adds a multiple of p in order to cancel |carry|,\n * which is a term at 2**257.\n *\n * On entry: carry < 2**3, inout[0,2,...] < 2**29, inout[1,3,...] < 2**28.\n * On exit: inout[0,2,..] < 2**30, inout[1,3,...] < 2**29. */\nstatic void felem_reduce_carry(felem inout, limb carry) {\n  const u32 carry_mask = NON_ZERO_TO_ALL_ONES(carry);\n\n  inout[0] += carry << 1;\n  inout[3] += 0x10000000 & carry_mask;\n  /* carry < 2**3 thus (carry << 11) < 2**14 and we added 2**28 in the\n   * previous line therefore this doesn't underflow. */\n  inout[3] -= carry << 11;\n  inout[4] += (0x20000000 - 1) & carry_mask;\n  inout[5] += (0x10000000 - 1) & carry_mask;\n  inout[6] += (0x20000000 - 1) & carry_mask;\n  inout[6] -= carry << 22;\n  /* This may underflow if carry is non-zero but, if so, we'll fix it in the\n   * next line. */\n  inout[7] -= 1 & carry_mask;\n  inout[7] += carry << 25;\n}\n\n/* felem_sum sets out = in+in2.\n *\n * On entry, in[i]+in2[i] must not overflow a 32-bit word.\n * On exit: out[0,2,...] < 2**30, out[1,3,...] < 2**29 */\nstatic void felem_sum(felem out, const felem in, const felem in2) {\n  limb carry = 0;\n  unsigned i;\n\n  for (i = 0;; i++) {\n    out[i] = in[i] + in2[i];\n    out[i] += carry;\n    carry = out[i] >> 29;\n    out[i] &= kBottom29Bits;\n\n    i++;\n    if (i == NLIMBS)\n      break;\n\n    out[i] = in[i] + in2[i];\n    out[i] += carry;\n    carry = out[i] >> 28;\n    out[i] &= kBottom28Bits;\n  }\n\n  felem_reduce_carry(out, carry);\n}\n\n#define two31m3 (((limb)1) << 31) - (((limb)1) << 3)\n#define two30m2 (((limb)1) << 30) - (((limb)1) << 2)\n#define two30p13m2 (((limb)1) << 30) + (((limb)1) << 13) - (((limb)1) << 2)\n#define two31m2 (((limb)1) << 31) - (((limb)1) << 2)\n#define two31p24m2 (((limb)1) << 31) + (((limb)1) << 24) - (((limb)1) << 2)\n#define two30m27m2 (((limb)1) << 30) - (((limb)1) << 27) - (((limb)1) << 2)\n\n/* zero31 is 0 mod p. */\nstatic const felem zero31 = { two31m3, two30m2, two31m2, two30p13m2, two31m2, two30m2, two31p24m2, two30m27m2, two31m2 };\n\n/* felem_diff sets out = in-in2.\n *\n * On entry: in[0,2,...] < 2**30, in[1,3,...] < 2**29 and\n *           in2[0,2,...] < 2**30, in2[1,3,...] < 2**29.\n * On exit: out[0,2,...] < 2**30, out[1,3,...] < 2**29. */\nstatic void felem_diff(felem out, const felem in, const felem in2) {\n  limb carry = 0;\n  unsigned i;\n\n   for (i = 0;; i++) {\n    out[i] = in[i] - in2[i];\n    out[i] += zero31[i];\n    out[i] += carry;\n    carry = out[i] >> 29;\n    out[i] &= kBottom29Bits;\n\n    i++;\n    if (i == NLIMBS)\n      break;\n\n    out[i] = in[i] - in2[i];\n    out[i] += zero31[i];\n    out[i] += carry;\n    carry = out[i] >> 28;\n    out[i] &= kBottom28Bits;\n  }\n\n  felem_reduce_carry(out, carry);\n}\n\n/* felem_reduce_degree sets out = tmp/R mod p where tmp contains 64-bit words\n * with the same 29,28,... bit positions as an felem.\n *\n * The values in felems are in Montgomery form: x*R mod p where R = 2**257.\n * Since we just multiplied two Montgomery values together, the result is\n * x*y*R*R mod p. We wish to divide by R in order for the result also to be\n * in Montgomery form.\n *\n * On entry: tmp[i] < 2**64\n * On exit: out[0,2,...] < 2**30, out[1,3,...] < 2**29 */\nstatic void felem_reduce_degree(felem out, u64 tmp[17]) {\n   /* The following table may be helpful when reading this code:\n    *\n    * Limb number:   0 | 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10...\n    * Width (bits):  29| 28| 29| 28| 29| 28| 29| 28| 29| 28| 29\n    * Start bit:     0 | 29| 57| 86|114|143|171|200|228|257|285\n    *   (odd phase): 0 | 28| 57| 85|114|142|171|199|228|256|285 */\n  limb tmp2[18], carry, x, xMask;\n  unsigned i;\n\n  /* tmp contains 64-bit words with the same 29,28,29-bit positions as an\n   * felem. So the top of an element of tmp might overlap with another\n   * element two positions down. The following loop eliminates this\n   * overlap. */\n  tmp2[0] = (limb)(tmp[0] & kBottom29Bits);\n\n  /* In the following we use \"(limb) tmp[x]\" and \"(limb) (tmp[x]>>32)\" to try\n   * and hint to the compiler that it can do a single-word shift by selecting\n   * the right register rather than doing a double-word shift and truncating\n   * afterwards. */\n  tmp2[1] = ((limb) tmp[0]) >> 29;\n  tmp2[1] |= (((limb)(tmp[0] >> 32)) << 3) & kBottom28Bits;\n  tmp2[1] += ((limb) tmp[1]) & kBottom28Bits;\n  carry = tmp2[1] >> 28;\n  tmp2[1] &= kBottom28Bits;\n\n  for (i = 2; i < 17; i++) {\n    tmp2[i] = ((limb)(tmp[i - 2] >> 32)) >> 25;\n    tmp2[i] += ((limb)(tmp[i - 1])) >> 28;\n    tmp2[i] += (((limb)(tmp[i - 1] >> 32)) << 4) & kBottom29Bits;\n    tmp2[i] += ((limb) tmp[i]) & kBottom29Bits;\n    tmp2[i] += carry;\n    carry = tmp2[i] >> 29;\n    tmp2[i] &= kBottom29Bits;\n\n    i++;\n    if (i == 17)\n      break;\n    tmp2[i] = ((limb)(tmp[i - 2] >> 32)) >> 25;\n    tmp2[i] += ((limb)(tmp[i - 1])) >> 29;\n    tmp2[i] += (((limb)(tmp[i - 1] >> 32)) << 3) & kBottom28Bits;\n    tmp2[i] += ((limb) tmp[i]) & kBottom28Bits;\n    tmp2[i] += carry;\n    carry = tmp2[i] >> 28;\n    tmp2[i] &= kBottom28Bits;\n  }\n\n  tmp2[17] = ((limb)(tmp[15] >> 32)) >> 25;\n  tmp2[17] += ((limb)(tmp[16])) >> 29;\n  tmp2[17] += (((limb)(tmp[16] >> 32)) << 3);\n  tmp2[17] += carry;\n\n  /* Montgomery elimination of terms.\n   *\n   * Since R is 2**257, we can divide by R with a bitwise shift if we can\n   * ensure that the right-most 257 bits are all zero. We can make that true by\n   * adding multiplies of p without affecting the value.\n   *\n   * So we eliminate limbs from right to left. Since the bottom 29 bits of p\n   * are all ones, then by adding tmp2[0]*p to tmp2 we'll make tmp2[0] == 0.\n   * We can do that for 8 further limbs and then right shift to eliminate the\n   * extra factor of R. */\n  for (i = 0;; i += 2) {\n    tmp2[i + 1] += tmp2[i] >> 29;\n    x = tmp2[i] & kBottom29Bits;\n    xMask = NON_ZERO_TO_ALL_ONES(x);\n    tmp2[i] = 0;\n\n    /* The bounds calculations for this loop are tricky. Each iteration of\n     * the loop eliminates two words by adding values to words to their\n     * right.\n     *\n     * The following table contains the amounts added to each word (as an\n     * offset from the value of i at the top of the loop). The amounts are\n     * accounted for from the first and second half of the loop separately\n     * and are written as, for example, 28 to mean a value <2**28.\n     *\n     * Word:                   3   4   5   6   7   8   9   10\n     * Added in top half:     28  11      29  21  29  28\n     *                                        28  29\n     *                                            29\n     * Added in bottom half:      29  10      28  21  28   28\n     *                                            29\n     *\n     * The value that is currently offset 7 will be offset 5 for the next\n     * iteration and then offset 3 for the iteration after that. Therefore\n     * the total value added will be the values added at 7, 5 and 3.\n     *\n     * The following table accumulates these values. The sums at the bottom\n     * are written as, for example, 29+28, to mean a value < 2**29+2**28.\n     *\n     * Word:                   3   4   5   6   7   8   9  10  11  12  13\n     *                        28  11  10  29  21  29  28  28  28  28  28\n     *                            29  28  11  28  29  28  29  28  29  28\n     *                                    29  28  21  21  29  21  29  21\n     *                                        10  29  28  21  28  21  28\n     *                                        28  29  28  29  28  29  28\n     *                                            11  10  29  10  29  10\n     *                                            29  28  11  28  11\n     *                                                    29      29\n     *                        --------------------------------------------\n     *                                                30+ 31+ 30+ 31+ 30+\n     *                                                28+ 29+ 28+ 29+ 21+\n     *                                                21+ 28+ 21+ 28+ 10\n     *                                                10  21+ 10  21+\n     *                                                    11      11\n     *\n     * So the greatest amount is added to tmp2[10] and tmp2[12]. If\n     * tmp2[10/12] has an initial value of <2**29, then the maximum value\n     * will be < 2**31 + 2**30 + 2**28 + 2**21 + 2**11, which is < 2**32,\n     * as required. */\n    tmp2[i + 3] += (x << 10) & kBottom28Bits;\n    tmp2[i + 4] += (x >> 18);\n\n    tmp2[i + 6] += (x << 21) & kBottom29Bits;\n    tmp2[i + 7] += x >> 8;\n\n    /* At position 200, which is the starting bit position for word 7, we\n     * have a factor of 0xf000000 = 2**28 - 2**24. */\n    tmp2[i + 7] += 0x10000000 & xMask;\n    /* Word 7 is 28 bits wide, so the 2**28 term exactly hits word 8. */\n    tmp2[i + 8] += (x - 1) & xMask;\n    tmp2[i + 7] -= (x << 24) & kBottom28Bits;\n    tmp2[i + 8] -= x >> 4;\n\n    tmp2[i + 8] += 0x20000000 & xMask;\n    tmp2[i + 8] -= x;\n    tmp2[i + 8] += (x << 28) & kBottom29Bits;\n    tmp2[i + 9] += ((x >> 1) - 1) & xMask;\n\n    if (i+1 == NLIMBS)\n      break;\n    tmp2[i + 2] += tmp2[i + 1] >> 28;\n    x = tmp2[i + 1] & kBottom28Bits;\n    xMask = NON_ZERO_TO_ALL_ONES(x);\n    tmp2[i + 1] = 0;\n\n    tmp2[i + 4] += (x << 11) & kBottom29Bits;\n    tmp2[i + 5] += (x >> 18);\n\n    tmp2[i + 7] += (x << 21) & kBottom28Bits;\n    tmp2[i + 8] += x >> 7;\n\n    /* At position 199, which is the starting bit of the 8th word when\n     * dealing with a context starting on an odd word, we have a factor of\n     * 0x1e000000 = 2**29 - 2**25. Since we have not updated i, the 8th\n     * word from i+1 is i+8. */\n    tmp2[i + 8] += 0x20000000 & xMask;\n    tmp2[i + 9] += (x - 1) & xMask;\n    tmp2[i + 8] -= (x << 25) & kBottom29Bits;\n    tmp2[i + 9] -= x >> 4;\n\n    tmp2[i + 9] += 0x10000000 & xMask;\n    tmp2[i + 9] -= x;\n    tmp2[i + 10] += (x - 1) & xMask;\n  }\n\n  /* We merge the right shift with a carry chain. The words above 2**257 have\n   * widths of 28,29,... which we need to correct when copying them down.  */\n  carry = 0;\n  for (i = 0; i < 8; i++) {\n    /* The maximum value of tmp2[i + 9] occurs on the first iteration and\n     * is < 2**30+2**29+2**28. Adding 2**29 (from tmp2[i + 10]) is\n     * therefore safe. */\n    out[i] = tmp2[i + 9];\n    out[i] += carry;\n    out[i] += (tmp2[i + 10] << 28) & kBottom29Bits;\n    carry = out[i] >> 29;\n    out[i] &= kBottom29Bits;\n\n    i++;\n    out[i] = tmp2[i + 9] >> 1;\n    out[i] += carry;\n    carry = out[i] >> 28;\n    out[i] &= kBottom28Bits;\n  }\n\n  out[8] = tmp2[17];\n  out[8] += carry;\n  carry = out[8] >> 29;\n  out[8] &= kBottom29Bits;\n\n  felem_reduce_carry(out, carry);\n}\n\n/* felem_square sets out=in*in.\n *\n * On entry: in[0,2,...] < 2**30, in[1,3,...] < 2**29.\n * On exit: out[0,2,...] < 2**30, out[1,3,...] < 2**29. */\nstatic void felem_square(felem out, const felem in) {\n  u64 tmp[17];\n\n  tmp[0] = ((u64) in[0]) * in[0];\n  tmp[1] = ((u64) in[0]) * (in[1] << 1);\n  tmp[2] = ((u64) in[0]) * (in[2] << 1) +\n           ((u64) in[1]) * (in[1] << 1);\n  tmp[3] = ((u64) in[0]) * (in[3] << 1) +\n           ((u64) in[1]) * (in[2] << 1);\n  tmp[4] = ((u64) in[0]) * (in[4] << 1) +\n           ((u64) in[1]) * (in[3] << 2) + ((u64) in[2]) * in[2];\n  tmp[5] = ((u64) in[0]) * (in[5] << 1) + ((u64) in[1]) *\n           (in[4] << 1) + ((u64) in[2]) * (in[3] << 1);\n  tmp[6] = ((u64) in[0]) * (in[6] << 1) + ((u64) in[1]) *\n           (in[5] << 2) + ((u64) in[2]) * (in[4] << 1) +\n           ((u64) in[3]) * (in[3] << 1);\n  tmp[7] = ((u64) in[0]) * (in[7] << 1) + ((u64) in[1]) *\n           (in[6] << 1) + ((u64) in[2]) * (in[5] << 1) +\n           ((u64) in[3]) * (in[4] << 1);\n  /* tmp[8] has the greatest value of 2**61 + 2**60 + 2**61 + 2**60 + 2**60,\n   * which is < 2**64 as required. */\n  tmp[8] = ((u64) in[0]) * (in[8] << 1) + ((u64) in[1]) *\n           (in[7] << 2) + ((u64) in[2]) * (in[6] << 1) +\n           ((u64) in[3]) * (in[5] << 2) + ((u64) in[4]) * in[4];\n  tmp[9] = ((u64) in[1]) * (in[8] << 1) + ((u64) in[2]) *\n           (in[7] << 1) + ((u64) in[3]) * (in[6] << 1) +\n           ((u64) in[4]) * (in[5] << 1);\n  tmp[10] = ((u64) in[2]) * (in[8] << 1) + ((u64) in[3]) *\n            (in[7] << 2) + ((u64) in[4]) * (in[6] << 1) +\n            ((u64) in[5]) * (in[5] << 1);\n  tmp[11] = ((u64) in[3]) * (in[8] << 1) + ((u64) in[4]) *\n            (in[7] << 1) + ((u64) in[5]) * (in[6] << 1);\n  tmp[12] = ((u64) in[4]) * (in[8] << 1) +\n            ((u64) in[5]) * (in[7] << 2) + ((u64) in[6]) * in[6];\n  tmp[13] = ((u64) in[5]) * (in[8] << 1) +\n            ((u64) in[6]) * (in[7] << 1);\n  tmp[14] = ((u64) in[6]) * (in[8] << 1) +\n            ((u64) in[7]) * (in[7] << 1);\n  tmp[15] = ((u64) in[7]) * (in[8] << 1);\n  tmp[16] = ((u64) in[8]) * in[8];\n\n  felem_reduce_degree(out, tmp);\n}\n\n/* felem_mul sets out=in*in2.\n *\n * On entry: in[0,2,...] < 2**30, in[1,3,...] < 2**29 and\n *           in2[0,2,...] < 2**30, in2[1,3,...] < 2**29.\n * On exit: out[0,2,...] < 2**30, out[1,3,...] < 2**29. */\nstatic void felem_mul(felem out, const felem in, const felem in2) {\n  u64 tmp[17];\n\n  tmp[0] = ((u64) in[0]) * in2[0];\n  tmp[1] = ((u64) in[0]) * (in2[1] << 0) +\n           ((u64) in[1]) * (in2[0] << 0);\n  tmp[2] = ((u64) in[0]) * (in2[2] << 0) + ((u64) in[1]) *\n           (in2[1] << 1) + ((u64) in[2]) * (in2[0] << 0);\n  tmp[3] = ((u64) in[0]) * (in2[3] << 0) + ((u64) in[1]) *\n           (in2[2] << 0) + ((u64) in[2]) * (in2[1] << 0) +\n           ((u64) in[3]) * (in2[0] << 0);\n  tmp[4] = ((u64) in[0]) * (in2[4] << 0) + ((u64) in[1]) *\n           (in2[3] << 1) + ((u64) in[2]) * (in2[2] << 0) +\n           ((u64) in[3]) * (in2[1] << 1) +\n           ((u64) in[4]) * (in2[0] << 0);\n  tmp[5] = ((u64) in[0]) * (in2[5] << 0) + ((u64) in[1]) *\n           (in2[4] << 0) + ((u64) in[2]) * (in2[3] << 0) +\n           ((u64) in[3]) * (in2[2] << 0) + ((u64) in[4]) *\n           (in2[1] << 0) + ((u64) in[5]) * (in2[0] << 0);\n  tmp[6] = ((u64) in[0]) * (in2[6] << 0) + ((u64) in[1]) *\n           (in2[5] << 1) + ((u64) in[2]) * (in2[4] << 0) +\n           ((u64) in[3]) * (in2[3] << 1) + ((u64) in[4]) *\n           (in2[2] << 0) + ((u64) in[5]) * (in2[1] << 1) +\n           ((u64) in[6]) * (in2[0] << 0);\n  tmp[7] = ((u64) in[0]) * (in2[7] << 0) + ((u64) in[1]) *\n           (in2[6] << 0) + ((u64) in[2]) * (in2[5] << 0) +\n           ((u64) in[3]) * (in2[4] << 0) + ((u64) in[4]) *\n           (in2[3] << 0) + ((u64) in[5]) * (in2[2] << 0) +\n           ((u64) in[6]) * (in2[1] << 0) +\n           ((u64) in[7]) * (in2[0] << 0);\n  /* tmp[8] has the greatest value but doesn't overflow. See logic in\n   * felem_square. */\n  tmp[8] = ((u64) in[0]) * (in2[8] << 0) + ((u64) in[1]) *\n           (in2[7] << 1) + ((u64) in[2]) * (in2[6] << 0) +\n           ((u64) in[3]) * (in2[5] << 1) + ((u64) in[4]) *\n           (in2[4] << 0) + ((u64) in[5]) * (in2[3] << 1) +\n           ((u64) in[6]) * (in2[2] << 0) + ((u64) in[7]) *\n           (in2[1] << 1) + ((u64) in[8]) * (in2[0] << 0);\n  tmp[9] = ((u64) in[1]) * (in2[8] << 0) + ((u64) in[2]) *\n           (in2[7] << 0) + ((u64) in[3]) * (in2[6] << 0) +\n           ((u64) in[4]) * (in2[5] << 0) + ((u64) in[5]) *\n           (in2[4] << 0) + ((u64) in[6]) * (in2[3] << 0) +\n           ((u64) in[7]) * (in2[2] << 0) +\n           ((u64) in[8]) * (in2[1] << 0);\n  tmp[10] = ((u64) in[2]) * (in2[8] << 0) + ((u64) in[3]) *\n            (in2[7] << 1) + ((u64) in[4]) * (in2[6] << 0) +\n            ((u64) in[5]) * (in2[5] << 1) + ((u64) in[6]) *\n            (in2[4] << 0) + ((u64) in[7]) * (in2[3] << 1) +\n            ((u64) in[8]) * (in2[2] << 0);\n  tmp[11] = ((u64) in[3]) * (in2[8] << 0) + ((u64) in[4]) *\n            (in2[7] << 0) + ((u64) in[5]) * (in2[6] << 0) +\n            ((u64) in[6]) * (in2[5] << 0) + ((u64) in[7]) *\n            (in2[4] << 0) + ((u64) in[8]) * (in2[3] << 0);\n  tmp[12] = ((u64) in[4]) * (in2[8] << 0) + ((u64) in[5]) *\n            (in2[7] << 1) + ((u64) in[6]) * (in2[6] << 0) +\n            ((u64) in[7]) * (in2[5] << 1) +\n            ((u64) in[8]) * (in2[4] << 0);\n  tmp[13] = ((u64) in[5]) * (in2[8] << 0) + ((u64) in[6]) *\n            (in2[7] << 0) + ((u64) in[7]) * (in2[6] << 0) +\n            ((u64) in[8]) * (in2[5] << 0);\n  tmp[14] = ((u64) in[6]) * (in2[8] << 0) + ((u64) in[7]) *\n            (in2[7] << 1) + ((u64) in[8]) * (in2[6] << 0);\n  tmp[15] = ((u64) in[7]) * (in2[8] << 0) +\n            ((u64) in[8]) * (in2[7] << 0);\n  tmp[16] = ((u64) in[8]) * (in2[8] << 0);\n\n  felem_reduce_degree(out, tmp);\n}\n\nstatic void felem_assign(felem out, const felem in) {\n  memcpy(out, in, sizeof(felem));\n}\n\n/* felem_inv calculates |out| = |in|^{-1}\n *\n * Based on Fermat's Little Theorem:\n *   a^p = a (mod p)\n *   a^{p-1} = 1 (mod p)\n *   a^{p-2} = a^{-1} (mod p)\n */\nstatic void felem_inv(felem out, const felem in) {\n  felem ftmp, ftmp2;\n  /* each e_I will hold |in|^{2^I - 1} */\n  felem e2, e4, e8, e16, e32, e64;\n  unsigned i;\n\n  felem_square(ftmp, in); /* 2^1 */\n  felem_mul(ftmp, in, ftmp); /* 2^2 - 2^0 */\n  felem_assign(e2, ftmp);\n  felem_square(ftmp, ftmp); /* 2^3 - 2^1 */\n  felem_square(ftmp, ftmp); /* 2^4 - 2^2 */\n  felem_mul(ftmp, ftmp, e2); /* 2^4 - 2^0 */\n  felem_assign(e4, ftmp);\n  felem_square(ftmp, ftmp); /* 2^5 - 2^1 */\n  felem_square(ftmp, ftmp); /* 2^6 - 2^2 */\n  felem_square(ftmp, ftmp); /* 2^7 - 2^3 */\n  felem_square(ftmp, ftmp); /* 2^8 - 2^4 */\n  felem_mul(ftmp, ftmp, e4); /* 2^8 - 2^0 */\n  felem_assign(e8, ftmp);\n  for (i = 0; i < 8; i++) {\n    felem_square(ftmp, ftmp);\n  } /* 2^16 - 2^8 */\n  felem_mul(ftmp, ftmp, e8); /* 2^16 - 2^0 */\n  felem_assign(e16, ftmp);\n  for (i = 0; i < 16; i++) {\n    felem_square(ftmp, ftmp);\n  } /* 2^32 - 2^16 */\n  felem_mul(ftmp, ftmp, e16); /* 2^32 - 2^0 */\n  felem_assign(e32, ftmp);\n  for (i = 0; i < 32; i++) {\n    felem_square(ftmp, ftmp);\n  } /* 2^64 - 2^32 */\n  felem_assign(e64, ftmp);\n  felem_mul(ftmp, ftmp, in); /* 2^64 - 2^32 + 2^0 */\n  for (i = 0; i < 192; i++) {\n    felem_square(ftmp, ftmp);\n  } /* 2^256 - 2^224 + 2^192 */\n\n  felem_mul(ftmp2, e64, e32); /* 2^64 - 2^0 */\n  for (i = 0; i < 16; i++) {\n    felem_square(ftmp2, ftmp2);\n  } /* 2^80 - 2^16 */\n  felem_mul(ftmp2, ftmp2, e16); /* 2^80 - 2^0 */\n  for (i = 0; i < 8; i++) {\n    felem_square(ftmp2, ftmp2);\n  } /* 2^88 - 2^8 */\n  felem_mul(ftmp2, ftmp2, e8); /* 2^88 - 2^0 */\n  for (i = 0; i < 4; i++) {\n    felem_square(ftmp2, ftmp2);\n  } /* 2^92 - 2^4 */\n  felem_mul(ftmp2, ftmp2, e4); /* 2^92 - 2^0 */\n  felem_square(ftmp2, ftmp2); /* 2^93 - 2^1 */\n  felem_square(ftmp2, ftmp2); /* 2^94 - 2^2 */\n  felem_mul(ftmp2, ftmp2, e2); /* 2^94 - 2^0 */\n  felem_square(ftmp2, ftmp2); /* 2^95 - 2^1 */\n  felem_square(ftmp2, ftmp2); /* 2^96 - 2^2 */\n  felem_mul(ftmp2, ftmp2, in); /* 2^96 - 3 */\n\n  felem_mul(out, ftmp2, ftmp); /* 2^256 - 2^224 + 2^192 + 2^96 - 3 */\n}\n\n/* felem_scalar_3 sets out=3*out.\n *\n * On entry: out[0,2,...] < 2**30, out[1,3,...] < 2**29.\n * On exit: out[0,2,...] < 2**30, out[1,3,...] < 2**29. */\nstatic void felem_scalar_3(felem out) {\n  limb carry = 0;\n  unsigned i;\n\n  for (i = 0;; i++) {\n    out[i] *= 3;\n    out[i] += carry;\n    carry = out[i] >> 29;\n    out[i] &= kBottom29Bits;\n\n    i++;\n    if (i == NLIMBS)\n      break;\n\n    out[i] *= 3;\n    out[i] += carry;\n    carry = out[i] >> 28;\n    out[i] &= kBottom28Bits;\n  }\n\n  felem_reduce_carry(out, carry);\n}\n\n/* felem_scalar_4 sets out=4*out.\n *\n * On entry: out[0,2,...] < 2**30, out[1,3,...] < 2**29.\n * On exit: out[0,2,...] < 2**30, out[1,3,...] < 2**29. */\nstatic void felem_scalar_4(felem out) {\n  limb carry = 0, next_carry;\n  unsigned i;\n\n  for (i = 0;; i++) {\n    next_carry = out[i] >> 27;\n    out[i] <<= 2;\n    out[i] &= kBottom29Bits;\n    out[i] += carry;\n    carry = next_carry + (out[i] >> 29);\n    out[i] &= kBottom29Bits;\n\n    i++;\n    if (i == NLIMBS)\n      break;\n\n    next_carry = out[i] >> 26;\n    out[i] <<= 2;\n    out[i] &= kBottom28Bits;\n    out[i] += carry;\n    carry = next_carry + (out[i] >> 28);\n    out[i] &= kBottom28Bits;\n  }\n\n  felem_reduce_carry(out, carry);\n}\n\n/* felem_scalar_8 sets out=8*out.\n *\n * On entry: out[0,2,...] < 2**30, out[1,3,...] < 2**29.\n * On exit: out[0,2,...] < 2**30, out[1,3,...] < 2**29. */\nstatic void felem_scalar_8(felem out) {\n  limb carry = 0, next_carry;\n  unsigned i;\n\n  for (i = 0;; i++) {\n    next_carry = out[i] >> 26;\n    out[i] <<= 3;\n    out[i] &= kBottom29Bits;\n    out[i] += carry;\n    carry = next_carry + (out[i] >> 29);\n    out[i] &= kBottom29Bits;\n\n    i++;\n    if (i == NLIMBS)\n      break;\n\n    next_carry = out[i] >> 25;\n    out[i] <<= 3;\n    out[i] &= kBottom28Bits;\n    out[i] += carry;\n    carry = next_carry + (out[i] >> 28);\n    out[i] &= kBottom28Bits;\n  }\n\n  felem_reduce_carry(out, carry);\n}\n\n/* felem_is_zero_vartime returns 1 iff |in| == 0. It takes a variable amount of\n * time depending on the value of |in|. */\nstatic char felem_is_zero_vartime(const felem in) {\n  limb carry;\n  int i;\n  limb tmp[NLIMBS];\n\n  felem_assign(tmp, in);\n\n  /* First, reduce tmp to a minimal form. */\n  do {\n    carry = 0;\n    for (i = 0;; i++) {\n      tmp[i] += carry;\n      carry = tmp[i] >> 29;\n      tmp[i] &= kBottom29Bits;\n\n      i++;\n      if (i == NLIMBS)\n        break;\n\n      tmp[i] += carry;\n      carry = tmp[i] >> 28;\n      tmp[i] &= kBottom28Bits;\n    }\n\n    felem_reduce_carry(tmp, carry);\n  } while (carry);\n\n  /* tmp < 2**257, so the only possible zero values are 0, p and 2p. */\n  return memcmp(tmp, kZero, sizeof(tmp)) == 0 ||\n         memcmp(tmp, kP, sizeof(tmp)) == 0 ||\n         memcmp(tmp, k2P, sizeof(tmp)) == 0;\n}\n\n\n/* Group operations:\n *\n * Elements of the elliptic curve group are represented in Jacobian\n * coordinates: (x, y, z). An affine point (x', y') is x'=x/z**2, y'=y/z**3 in\n * Jacobian form. */\n\n/* point_double sets {x_out,y_out,z_out} = 2*{x,y,z}.\n *\n * See http://www.hyperelliptic.org/EFD/g1p/auto-shortw-jacobian-0.html#doubling-dbl-2009-l */\nstatic void point_double(felem x_out, felem y_out, felem z_out, const felem x,\n                         const felem y, const felem z) {\n  felem delta, gamma, alpha, beta, tmp, tmp2;\n\n  felem_square(delta, z);\n  felem_square(gamma, y);\n  felem_mul(beta, x, gamma);\n\n  felem_sum(tmp, x, delta);\n  felem_diff(tmp2, x, delta);\n  felem_mul(alpha, tmp, tmp2);\n  felem_scalar_3(alpha);\n\n  felem_sum(tmp, y, z);\n  felem_square(tmp, tmp);\n  felem_diff(tmp, tmp, gamma);\n  felem_diff(z_out, tmp, delta);\n\n  felem_scalar_4(beta);\n  felem_square(x_out, alpha);\n  felem_diff(x_out, x_out, beta);\n  felem_diff(x_out, x_out, beta);\n\n  felem_diff(tmp, beta, x_out);\n  felem_mul(tmp, alpha, tmp);\n  felem_square(tmp2, gamma);\n  felem_scalar_8(tmp2);\n  felem_diff(y_out, tmp, tmp2);\n}\n\n/* point_add_mixed sets {x_out,y_out,z_out} = {x1,y1,z1} + {x2,y2,1}.\n * (i.e. the second point is affine.)\n *\n * See http://www.hyperelliptic.org/EFD/g1p/auto-shortw-jacobian-0.html#addition-add-2007-bl\n *\n * Note that this function does not handle P+P, infinity+P nor P+infinity\n * correctly. */\nstatic void point_add_mixed(felem x_out, felem y_out, felem z_out,\n                            const felem x1, const felem y1, const felem z1,\n                            const felem x2, const felem y2) {\n  felem z1z1, z1z1z1, s2, u2, h, i, j, r, rr, v, tmp;\n\n  felem_square(z1z1, z1);\n  felem_sum(tmp, z1, z1);\n\n  felem_mul(u2, x2, z1z1);\n  felem_mul(z1z1z1, z1, z1z1);\n  felem_mul(s2, y2, z1z1z1);\n  felem_diff(h, u2, x1);\n  felem_sum(i, h, h);\n  felem_square(i, i);\n  felem_mul(j, h, i);\n  felem_diff(r, s2, y1);\n  felem_sum(r, r, r);\n  felem_mul(v, x1, i);\n\n  felem_mul(z_out, tmp, h);\n  felem_square(rr, r);\n  felem_diff(x_out, rr, j);\n  felem_diff(x_out, x_out, v);\n  felem_diff(x_out, x_out, v);\n\n  felem_diff(tmp, v, x_out);\n  felem_mul(y_out, tmp, r);\n  felem_mul(tmp, y1, j);\n  felem_diff(y_out, y_out, tmp);\n  felem_diff(y_out, y_out, tmp);\n}\n\n/* point_add sets {x_out,y_out,z_out} = {x1,y1,z1} + {x2,y2,z2}.\n *\n * See http://www.hyperelliptic.org/EFD/g1p/auto-shortw-jacobian-0.html#addition-add-2007-bl\n *\n * Note that this function does not handle P+P, infinity+P nor P+infinity\n * correctly. */\nstatic void point_add(felem x_out, felem y_out, felem z_out, const felem x1,\n                      const felem y1, const felem z1, const felem x2,\n                      const felem y2, const felem z2) {\n  felem z1z1, z1z1z1, z2z2, z2z2z2, s1, s2, u1, u2, h, i, j, r, rr, v, tmp;\n\n  felem_square(z1z1, z1);\n  felem_square(z2z2, z2);\n  felem_mul(u1, x1, z2z2);\n\n  felem_sum(tmp, z1, z2);\n  felem_square(tmp, tmp);\n  felem_diff(tmp, tmp, z1z1);\n  felem_diff(tmp, tmp, z2z2);\n\n  felem_mul(z2z2z2, z2, z2z2);\n  felem_mul(s1, y1, z2z2z2);\n\n  felem_mul(u2, x2, z1z1);\n  felem_mul(z1z1z1, z1, z1z1);\n  felem_mul(s2, y2, z1z1z1);\n  felem_diff(h, u2, u1);\n  felem_sum(i, h, h);\n  felem_square(i, i);\n  felem_mul(j, h, i);\n  felem_diff(r, s2, s1);\n  felem_sum(r, r, r);\n  felem_mul(v, u1, i);\n\n  felem_mul(z_out, tmp, h);\n  felem_square(rr, r);\n  felem_diff(x_out, rr, j);\n  felem_diff(x_out, x_out, v);\n  felem_diff(x_out, x_out, v);\n\n  felem_diff(tmp, v, x_out);\n  felem_mul(y_out, tmp, r);\n  felem_mul(tmp, s1, j);\n  felem_diff(y_out, y_out, tmp);\n  felem_diff(y_out, y_out, tmp);\n}\n\n/* point_add_or_double_vartime sets {x_out,y_out,z_out} = {x1,y1,z1} +\n *                                                        {x2,y2,z2}.\n *\n * See http://www.hyperelliptic.org/EFD/g1p/auto-shortw-jacobian-0.html#addition-add-2007-bl\n *\n * This function handles the case where {x1,y1,z1}={x2,y2,z2}. */\nstatic void point_add_or_double_vartime(\n    felem x_out, felem y_out, felem z_out, const felem x1, const felem y1,\n    const felem z1, const felem x2, const felem y2, const felem z2) {\n  felem z1z1, z1z1z1, z2z2, z2z2z2, s1, s2, u1, u2, h, i, j, r, rr, v, tmp;\n  char x_equal, y_equal;\n\n  felem_square(z1z1, z1);\n  felem_square(z2z2, z2);\n  felem_mul(u1, x1, z2z2);\n\n  felem_sum(tmp, z1, z2);\n  felem_square(tmp, tmp);\n  felem_diff(tmp, tmp, z1z1);\n  felem_diff(tmp, tmp, z2z2);\n\n  felem_mul(z2z2z2, z2, z2z2);\n  felem_mul(s1, y1, z2z2z2);\n\n  felem_mul(u2, x2, z1z1);\n  felem_mul(z1z1z1, z1, z1z1);\n  felem_mul(s2, y2, z1z1z1);\n  felem_diff(h, u2, u1);\n  x_equal = felem_is_zero_vartime(h);\n  felem_sum(i, h, h);\n  felem_square(i, i);\n  felem_mul(j, h, i);\n  felem_diff(r, s2, s1);\n  y_equal = felem_is_zero_vartime(r);\n  if (x_equal && y_equal) {\n    point_double(x_out, y_out, z_out, x1, y1, z1);\n    return;\n  }\n  felem_sum(r, r, r);\n  felem_mul(v, u1, i);\n\n  felem_mul(z_out, tmp, h);\n  felem_square(rr, r);\n  felem_diff(x_out, rr, j);\n  felem_diff(x_out, x_out, v);\n  felem_diff(x_out, x_out, v);\n\n  felem_diff(tmp, v, x_out);\n  felem_mul(y_out, tmp, r);\n  felem_mul(tmp, s1, j);\n  felem_diff(y_out, y_out, tmp);\n  felem_diff(y_out, y_out, tmp);\n}\n\n/* copy_conditional sets out=in if mask = 0xffffffff in constant time.\n *\n * On entry: mask is either 0 or 0xffffffff. */\nstatic void copy_conditional(felem out, const felem in, limb mask) {\n  int i;\n\n  for (i = 0; i < NLIMBS; i++) {\n    const limb tmp = mask & (in[i] ^ out[i]);\n    out[i] ^= tmp;\n  }\n}\n\n/* select_affine_point sets {out_x,out_y} to the index'th entry of table.\n * On entry: index < 16, table[0] must be zero. */\nstatic void select_affine_point(felem out_x, felem out_y, const limb* table,\n                                limb index) {\n  limb i, j;\n\n  memset(out_x, 0, sizeof(felem));\n  memset(out_y, 0, sizeof(felem));\n\n  for (i = 1; i < 16; i++) {\n    limb mask = i ^ index;\n    mask |= mask >> 2;\n    mask |= mask >> 1;\n    mask &= 1;\n    mask--;\n    for (j = 0; j < NLIMBS; j++, table++) {\n      out_x[j] |= *table & mask;\n    }\n    for (j = 0; j < NLIMBS; j++, table++) {\n      out_y[j] |= *table & mask;\n    }\n  }\n}\n\n/* select_jacobian_point sets {out_x,out_y,out_z} to the index'th entry of\n * table. On entry: index < 16, table[0] must be zero. */\nstatic void select_jacobian_point(felem out_x, felem out_y, felem out_z,\n                                  const limb* table, limb index) {\n  limb i, j;\n\n  memset(out_x, 0, sizeof(felem));\n  memset(out_y, 0, sizeof(felem));\n  memset(out_z, 0, sizeof(felem));\n\n  /* The implicit value at index 0 is all zero. We don't need to perform that\n   * iteration of the loop because we already set out_* to zero. */\n  table += 3 * NLIMBS;\n\n  // Hit all entries to obscure cache profiling.\n  for (i = 1; i < 16; i++) {\n    limb mask = i ^ index;\n    mask |= mask >> 2;\n    mask |= mask >> 1;\n    mask &= 1;\n    mask--;\n    for (j = 0; j < NLIMBS; j++, table++) {\n      out_x[j] |= *table & mask;\n    }\n    for (j = 0; j < NLIMBS; j++, table++) {\n      out_y[j] |= *table & mask;\n    }\n    for (j = 0; j < NLIMBS; j++, table++) {\n      out_z[j] |= *table & mask;\n    }\n  }\n}\n\n/* scalar_base_mult sets {nx,ny,nz} = scalar*G where scalar is a little-endian\n * number. Note that the value of scalar must be less than the order of the\n * group. */\nstatic void scalar_base_mult(felem nx, felem ny, felem nz,\n                             const p256_int* scalar) {\n  int i, j;\n  limb n_is_infinity_mask = -1, p_is_noninfinite_mask, mask;\n  u32 table_offset;\n\n  felem px, py;\n  felem tx, ty, tz;\n\n  memset(nx, 0, sizeof(felem));\n  memset(ny, 0, sizeof(felem));\n  memset(nz, 0, sizeof(felem));\n\n  /* The loop adds bits at positions 0, 64, 128 and 192, followed by\n   * positions 32,96,160 and 224 and does this 32 times. */\n  for (i = 0; i < 32; i++) {\n    if (i) {\n      point_double(nx, ny, nz, nx, ny, nz);\n    }\n    table_offset = 0;\n    for (j = 0; j <= 32; j += 32) {\n      char bit0 = p256_get_bit(scalar, 31 - i + j);\n      char bit1 = p256_get_bit(scalar, 95 - i + j);\n      char bit2 = p256_get_bit(scalar, 159 - i + j);\n      char bit3 = p256_get_bit(scalar, 223 - i + j);\n      limb index = bit0 | (bit1 << 1) | (bit2 << 2) | (bit3 << 3);\n\n      select_affine_point(px, py, kPrecomputed + table_offset, index);\n      table_offset += 30 * NLIMBS;\n\n      /* Since scalar is less than the order of the group, we know that\n       * {nx,ny,nz} != {px,py,1}, unless both are zero, which we handle\n       * below. */\n      point_add_mixed(tx, ty, tz, nx, ny, nz, px, py);\n      /* The result of point_add_mixed is incorrect if {nx,ny,nz} is zero\n       * (a.k.a.  the point at infinity). We handle that situation by\n       * copying the point from the table. */\n      copy_conditional(nx, px, n_is_infinity_mask);\n      copy_conditional(ny, py, n_is_infinity_mask);\n      copy_conditional(nz, kOne, n_is_infinity_mask);\n\n      /* Equally, the result is also wrong if the point from the table is\n       * zero, which happens when the index is zero. We handle that by\n       * only copying from {tx,ty,tz} to {nx,ny,nz} if index != 0. */\n      p_is_noninfinite_mask = NON_ZERO_TO_ALL_ONES(index);\n      mask = p_is_noninfinite_mask & ~n_is_infinity_mask;\n      copy_conditional(nx, tx, mask);\n      copy_conditional(ny, ty, mask);\n      copy_conditional(nz, tz, mask);\n      /* If p was not zero, then n is now non-zero. */\n      n_is_infinity_mask &= ~p_is_noninfinite_mask;\n    }\n  }\n}\n\n/* point_to_affine converts a Jacobian point to an affine point. If the input\n * is the point at infinity then it returns (0, 0) in constant time. */\nstatic void point_to_affine(felem x_out, felem y_out, const felem nx,\n                            const felem ny, const felem nz) {\n  felem z_inv, z_inv_sq;\n  felem_inv(z_inv, nz);\n  felem_square(z_inv_sq, z_inv);\n  felem_mul(x_out, nx, z_inv_sq);\n  felem_mul(z_inv, z_inv, z_inv_sq);\n  felem_mul(y_out, ny, z_inv);\n}\n\n/* scalar_base_mult sets {nx,ny,nz} = scalar*{x,y}. */\nstatic void scalar_mult(felem nx, felem ny, felem nz, const felem x,\n                        const felem y, const p256_int* scalar) {\n  int i;\n  felem px, py, pz, tx, ty, tz;\n  felem precomp[16][3];\n  limb n_is_infinity_mask, index, p_is_noninfinite_mask, mask;\n\n  /* We precompute 0,1,2,... times {x,y}. */\n  memset(precomp, 0, sizeof(felem) * 3);\n  memcpy(&precomp[1][0], x, sizeof(felem));\n  memcpy(&precomp[1][1], y, sizeof(felem));\n  memcpy(&precomp[1][2], kOne, sizeof(felem));\n\n  for (i = 2; i < 16; i += 2) {\n    point_double(precomp[i][0], precomp[i][1], precomp[i][2],\n                 precomp[i / 2][0], precomp[i / 2][1], precomp[i / 2][2]);\n\n    point_add_mixed(precomp[i + 1][0], precomp[i + 1][1], precomp[i + 1][2],\n                    precomp[i][0], precomp[i][1], precomp[i][2], x, y);\n  }\n\n  memset(nx, 0, sizeof(felem));\n  memset(ny, 0, sizeof(felem));\n  memset(nz, 0, sizeof(felem));\n  n_is_infinity_mask = -1;\n\n  /* We add in a window of four bits each iteration and do this 64 times. */\n  for (i = 0; i < 256; i += 4) {\n    if (i) {\n      point_double(nx, ny, nz, nx, ny, nz);\n      point_double(nx, ny, nz, nx, ny, nz);\n      point_double(nx, ny, nz, nx, ny, nz);\n      point_double(nx, ny, nz, nx, ny, nz);\n    }\n\n    index = (p256_get_bit(scalar, 255 - i - 0) << 3) |\n            (p256_get_bit(scalar, 255 - i - 1) << 2) |\n            (p256_get_bit(scalar, 255 - i - 2) << 1) |\n            p256_get_bit(scalar, 255 - i - 3);\n\n    /* See the comments in scalar_base_mult about handling infinities. */\n    select_jacobian_point(px, py, pz, precomp[0][0], index);\n    point_add(tx, ty, tz, nx, ny, nz, px, py, pz);\n    copy_conditional(nx, px, n_is_infinity_mask);\n    copy_conditional(ny, py, n_is_infinity_mask);\n    copy_conditional(nz, pz, n_is_infinity_mask);\n\n    p_is_noninfinite_mask = NON_ZERO_TO_ALL_ONES(index);\n    mask = p_is_noninfinite_mask & ~n_is_infinity_mask;\n\n    copy_conditional(nx, tx, mask);\n    copy_conditional(ny, ty, mask);\n    copy_conditional(nz, tz, mask);\n    n_is_infinity_mask &= ~p_is_noninfinite_mask;\n  }\n}\n\n#define kRDigits {2, 0, 0, 0xfffffffe, 0xffffffff, 0xffffffff, 0xfffffffd, 1} // 2^257 mod p256.p\n\n#define kRInvDigits {0x80000000, 1, 0xffffffff, 0, 0x80000001, 0xfffffffe, 1, 0x7fffffff}  // 1 / 2^257 mod p256.p\n\nstatic const p256_int kR = { kRDigits };\nstatic const p256_int kRInv = { kRInvDigits };\n\n/* to_montgomery sets out = R*in. */\nstatic void to_montgomery(felem out, const p256_int* in) {\n  p256_int in_shifted;\n  int i;\n\n  p256_init(&in_shifted);\n  p256_modmul(&SECP256r1_p, in, 0, &kR, &in_shifted);\n\n  for (i = 0; i < NLIMBS; i++) {\n    if ((i & 1) == 0) {\n      out[i] = P256_DIGIT(&in_shifted, 0) & kBottom29Bits;\n      p256_shr(&in_shifted, 29, &in_shifted);\n    } else {\n      out[i] = P256_DIGIT(&in_shifted, 0) & kBottom28Bits;\n      p256_shr(&in_shifted, 28, &in_shifted);\n    }\n  }\n\n  p256_clear(&in_shifted);\n}\n\n/* from_montgomery sets out=in/R. */\nstatic void from_montgomery(p256_int* out, const felem in) {\n  p256_int result, tmp;\n  int i, top;\n\n  p256_init(&result);\n  p256_init(&tmp);\n\n  p256_add_d(&tmp, in[NLIMBS - 1], &result);\n  for (i = NLIMBS - 2; i >= 0; i--) {\n    if ((i & 1) == 0) {\n      top = p256_shl(&result, 29, &tmp);\n    } else {\n      top = p256_shl(&result, 28, &tmp);\n    }\n    top |= p256_add_d(&tmp, in[i], &result);\n  }\n\n  p256_modmul(&SECP256r1_p, &kRInv, top, &result, out);\n\n  p256_clear(&result);\n  p256_clear(&tmp);\n}\n\n/* p256_base_point_mul sets {out_x,out_y} = nG, where n is < the\n * order of the group. */\nvoid p256_base_point_mul(const p256_int* n, p256_int* out_x, p256_int* out_y) {\n  felem x, y, z;\n\n  scalar_base_mult(x, y, z, n);\n\n  {\n    felem x_affine, y_affine;\n\n    point_to_affine(x_affine, y_affine, x, y, z);\n    from_montgomery(out_x, x_affine);\n    from_montgomery(out_y, y_affine);\n  }\n}\n\n/* p256_points_mul_vartime sets {out_x,out_y} = n1*G + n2*{in_x,in_y}, where\n * n1 and n2 are < the order of the group.\n *\n * As indicated by the name, this function operates in variable time. This\n * is safe because it's used for signature validation which doesn't deal\n * with secrets. */\nvoid p256_points_mul_vartime(\n    const p256_int* n1, const p256_int* n2, const p256_int* in_x,\n    const p256_int* in_y, p256_int* out_x, p256_int* out_y) {\n  felem x1, y1, z1, x2, y2, z2, px, py;\n\n  /* If both scalars are zero, then the result is the point at infinity. */\n  if (p256_is_zero(n1) != 0 && p256_is_zero(n2) != 0) {\n    p256_clear(out_x);\n    p256_clear(out_y);\n    return;\n  }\n\n  to_montgomery(px, in_x);\n  to_montgomery(py, in_y);\n  scalar_base_mult(x1, y1, z1, n1);\n  scalar_mult(x2, y2, z2, px, py, n2);\n\n  if (p256_is_zero(n2) != 0) {\n    /* If n2 == 0, then {x2,y2,z2} is zero and the result is just\n         * {x1,y1,z1}. */\n  } else if (p256_is_zero(n1) != 0) {\n    /* If n1 == 0, then {x1,y1,z1} is zero and the result is just\n         * {x2,y2,z2}. */\n    memcpy(x1, x2, sizeof(x2));\n    memcpy(y1, y2, sizeof(y2));\n    memcpy(z1, z2, sizeof(z2));\n  } else {\n    /* This function handles the case where {x1,y1,z1} == {x2,y2,z2}. */\n    point_add_or_double_vartime(x1, y1, z1, x1, y1, z1, x2, y2, z2);\n  }\n\n  point_to_affine(px, py, x1, y1, z1);\n  from_montgomery(out_x, px);\n  from_montgomery(out_y, py);\n}\n"
  },
  {
    "path": "external/mincrypt/p256_ecdsa.c",
    "content": "/*\n * Copyright 2013 The Android Open Source Project\n *\n * Redistribution and use in source and binary forms, with or without\n * modification, are permitted provided that the following conditions are met:\n *     * Redistributions of source code must retain the above copyright\n *       notice, this list of conditions and the following disclaimer.\n *     * Redistributions in binary form must reproduce the above copyright\n *       notice, this list of conditions and the following disclaimer in the\n *       documentation and/or other materials provided with the distribution.\n *     * Neither the name of Google Inc. nor the names of its contributors may\n *       be used to endorse or promote products derived from this software\n *       without specific prior written permission.\n *\n * THIS SOFTWARE IS PROVIDED BY Google Inc. ``AS IS'' AND ANY EXPRESS OR\n * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF\n * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO\n * EVENT SHALL Google Inc. BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,\n * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,\n * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS;\n * OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,\n * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR\n * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF\n * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n */\n\n#include <string.h>\n\n#include \"mincrypt/p256_ecdsa.h\"\n#include \"mincrypt/p256.h\"\n\nint p256_ecdsa_verify(const p256_int* key_x, const p256_int* key_y,\n                      const p256_int* message,\n                      const p256_int* r, const p256_int* s) {\n  p256_int u, v;\n\n  // Check public key.\n  if (!p256_is_valid_point(key_x, key_y)) return 0;\n\n  // Check r and s are != 0 % n.\n  p256_mod(&SECP256r1_n, r, &u);\n  p256_mod(&SECP256r1_n, s, &v);\n  if (p256_is_zero(&u) || p256_is_zero(&v)) return 0;\n\n  p256_modinv_vartime(&SECP256r1_n, s, &v);\n  p256_modmul(&SECP256r1_n, message, 0, &v, &u);  // message / s % n\n  p256_modmul(&SECP256r1_n, r, 0, &v, &v);  // r / s % n\n\n  p256_points_mul_vartime(&u, &v,\n                          key_x, key_y,\n                          &u, &v);\n\n  p256_mod(&SECP256r1_n, &u, &u);  // (x coord % p) % n\n  return p256_cmp(r, &u) == 0;\n}\n\n"
  },
  {
    "path": "external/mincrypt/rsa.c",
    "content": "/* rsa.c\n**\n** Copyright 2012, The Android Open Source Project\n**\n** Redistribution and use in source and binary forms, with or without\n** modification, are permitted provided that the following conditions are met:\n**     * Redistributions of source code must retain the above copyright\n**       notice, this list of conditions and the following disclaimer.\n**     * Redistributions in binary form must reproduce the above copyright\n**       notice, this list of conditions and the following disclaimer in the\n**       documentation and/or other materials provided with the distribution.\n**     * Neither the name of Google Inc. nor the names of its contributors may\n**       be used to endorse or promote products derived from this software\n**       without specific prior written permission.\n**\n** THIS SOFTWARE IS PROVIDED BY Google Inc. ``AS IS'' AND ANY EXPRESS OR\n** IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF\n** MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO\n** EVENT SHALL Google Inc. BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,\n** SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,\n** PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS;\n** OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,\n** WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR\n** OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF\n** ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n*/\n\n#include \"mincrypt/rsa.h\"\n#include \"mincrypt/sha.h\"\n#include \"mincrypt/sha256.h\"\n\n// a[] -= mod\nstatic void subM(const RSAPublicKey* key,\n                 uint32_t* a) {\n    int64_t A = 0;\n    int i;\n    for (i = 0; i < key->len; ++i) {\n        A += (uint64_t)a[i] - key->n[i];\n        a[i] = (uint32_t)A;\n        A >>= 32;\n    }\n}\n\n// return a[] >= mod\nstatic int geM(const RSAPublicKey* key,\n               const uint32_t* a) {\n    int i;\n    for (i = key->len; i;) {\n        --i;\n        if (a[i] < key->n[i]) return 0;\n        if (a[i] > key->n[i]) return 1;\n    }\n    return 1;  // equal\n}\n\n// montgomery c[] += a * b[] / R % mod\nstatic void montMulAdd(const RSAPublicKey* key,\n                       uint32_t* c,\n                       const uint32_t a,\n                       const uint32_t* b) {\n    uint64_t A = (uint64_t)a * b[0] + c[0];\n    uint32_t d0 = (uint32_t)A * key->n0inv;\n    uint64_t B = (uint64_t)d0 * key->n[0] + (uint32_t)A;\n    int i;\n\n    for (i = 1; i < key->len; ++i) {\n        A = (A >> 32) + (uint64_t)a * b[i] + c[i];\n        B = (B >> 32) + (uint64_t)d0 * key->n[i] + (uint32_t)A;\n        c[i - 1] = (uint32_t)B;\n    }\n\n    A = (A >> 32) + (B >> 32);\n\n    c[i - 1] = (uint32_t)A;\n\n    if (A >> 32) {\n        subM(key, c);\n    }\n}\n\n// montgomery c[] = a[] * b[] / R % mod\nstatic void montMul(const RSAPublicKey* key,\n                    uint32_t* c,\n                    const uint32_t* a,\n                    const uint32_t* b) {\n    int i;\n    for (i = 0; i < key->len; ++i) {\n        c[i] = 0;\n    }\n    for (i = 0; i < key->len; ++i) {\n        montMulAdd(key, c, a[i], b);\n    }\n}\n\n// In-place public exponentiation.\n// Input and output big-endian byte array in inout.\nstatic void modpow(const RSAPublicKey* key,\n                   uint8_t* inout) {\n    uint32_t a[RSANUMWORDS];\n    uint32_t aR[RSANUMWORDS];\n    uint32_t aaR[RSANUMWORDS];\n    uint32_t* aaa = 0;\n    int i;\n\n    // Convert from big endian byte array to little endian word array.\n    for (i = 0; i < key->len; ++i) {\n        uint32_t tmp =\n            (inout[((key->len - 1 - i) * 4) + 0] << 24) |\n            (inout[((key->len - 1 - i) * 4) + 1] << 16) |\n            (inout[((key->len - 1 - i) * 4) + 2] << 8) |\n            (inout[((key->len - 1 - i) * 4) + 3] << 0);\n        a[i] = tmp;\n    }\n\n    if (key->exponent == 65537) {\n        aaa = aaR;  // Re-use location.\n        montMul(key, aR, a, key->rr);  // aR = a * RR / R mod M\n        for (i = 0; i < 16; i += 2) {\n            montMul(key, aaR, aR, aR);  // aaR = aR * aR / R mod M\n            montMul(key, aR, aaR, aaR);  // aR = aaR * aaR / R mod M\n        }\n        montMul(key, aaa, aR, a);  // aaa = aR * a / R mod M\n    } else if (key->exponent == 3) {\n        aaa = aR;  // Re-use location.\n        montMul(key, aR, a, key->rr);  /* aR = a * RR / R mod M   */\n        montMul(key, aaR, aR, aR);     /* aaR = aR * aR / R mod M */\n        montMul(key, aaa, aaR, a);     /* aaa = aaR * a / R mod M */\n    }\n\n    // Make sure aaa < mod; aaa is at most 1x mod too large.\n    if (geM(key, aaa)) {\n        subM(key, aaa);\n    }\n\n    // Convert to bigendian byte array\n    for (i = key->len - 1; i >= 0; --i) {\n        uint32_t tmp = aaa[i];\n        *inout++ = tmp >> 24;\n        *inout++ = tmp >> 16;\n        *inout++ = tmp >> 8;\n        *inout++ = tmp >> 0;\n    }\n}\n\n// Expected PKCS1.5 signature padding bytes, for a keytool RSA signature.\n// Has the 0-length optional parameter encoded in the ASN1 (as opposed to the\n// other flavor which omits the optional parameter entirely). This code does not\n// accept signatures without the optional parameter.\n\n/*\nstatic const uint8_t sha_padding[RSANUMBYTES] = {\n    0x00, 0x01, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,\n    0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,\n    0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,\n    0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,\n    0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,\n    0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,\n    0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,\n    0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,\n    0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,\n    0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,\n    0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,\n    0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,\n    0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,\n    0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,\n    0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,\n    0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,\n    0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,\n    0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,\n    0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,\n    0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,\n    0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,\n    0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,\n    0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,\n    0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,\n    0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,\n    0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,\n    0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,\n    0xff, 0xff, 0xff, 0xff, 0x00, 0x30, 0x21, 0x30,\n    0x09, 0x06, 0x05, 0x2b, 0x0e, 0x03, 0x02, 0x1a,\n    0x05, 0x00, 0x04, 0x14,\n\n    // 20 bytes of hash go here.\n    0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0\n};\n*/\n\n// SHA-1 of PKCS1.5 signature sha_padding for 2048 bit, as above.\n// At the location of the bytes of the hash all 00 are hashed.\nstatic const uint8_t kExpectedPadShaRsa2048[SHA_DIGEST_SIZE] = {\n    0xdc, 0xbd, 0xbe, 0x42, 0xd5, 0xf5, 0xa7, 0x2e,\n    0x6e, 0xfc, 0xf5, 0x5d, 0xaf, 0x9d, 0xea, 0x68,\n    0x7c, 0xfb, 0xf1, 0x67\n};\n\n/*\nstatic const uint8_t sha256_padding[RSANUMBYTES] = {\n    0x00, 0x01, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,\n    0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,\n    0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,\n    0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,\n    0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,\n    0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,\n    0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,\n    0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,\n    0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,\n    0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,\n    0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,\n    0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,\n    0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,\n    0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,\n    0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,\n    0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,\n    0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,\n    0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,\n    0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,\n    0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,\n    0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,\n    0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,\n    0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,\n    0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,\n    0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,\n    0xff, 0xff, 0xff, 0xff, 0x00, 0x30, 0x31, 0x30,\n    0x0d, 0x06, 0x09, 0x60, 0x86, 0x48, 0x01, 0x65,\n    0x03, 0x04, 0x02, 0x01, 0x05, 0x00, 0x04, 0x20,\n\n    // 32 bytes of hash go here.\n    0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,\n    0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,\n};\n*/\n\n// SHA-256 of PKCS1.5 signature sha256_padding for 2048 bit, as above.\n// At the location of the bytes of the hash all 00 are hashed.\nstatic const uint8_t kExpectedPadSha256Rsa2048[SHA256_DIGEST_SIZE] = {\n    0xab, 0x28, 0x8d, 0x8a, 0xd7, 0xd9, 0x59, 0x92,\n    0xba, 0xcc, 0xf8, 0x67, 0x20, 0xe1, 0x15, 0x2e,\n    0x39, 0x8d, 0x80, 0x36, 0xd6, 0x6f, 0xf0, 0xfd,\n    0x90, 0xe8, 0x7d, 0x8b, 0xe1, 0x7c, 0x87, 0x59,\n};\n\n// Verify a 2048-bit RSA PKCS1.5 signature against an expected hash.\n// Both e=3 and e=65537 are supported.  hash_len may be\n// SHA_DIGEST_SIZE (== 20) to indicate a SHA-1 hash, or\n// SHA256_DIGEST_SIZE (== 32) to indicate a SHA-256 hash.  No other\n// values are supported.\n//\n// Returns 1 on successful verification, 0 on failure.\nint RSA_verify(const RSAPublicKey *key,\n               const uint8_t *signature,\n               const int len,\n               const uint8_t *hash,\n               const int hash_len) {\n    uint8_t buf[RSANUMBYTES];\n    int i;\n    const uint8_t* padding_hash;\n\n    if (key->len != RSANUMWORDS) {\n        return 0;  // Wrong key passed in.\n    }\n\n    if (len != sizeof(buf)) {\n        return 0;  // Wrong input length.\n    }\n\n    if (hash_len != SHA_DIGEST_SIZE &&\n        hash_len != SHA256_DIGEST_SIZE) {\n        return 0;  // Unsupported hash.\n    }\n\n    if (key->exponent != 3 && key->exponent != 65537) {\n        return 0;  // Unsupported exponent.\n    }\n\n    for (i = 0; i < len; ++i) {  // Copy input to local workspace.\n        buf[i] = signature[i];\n    }\n\n    modpow(key, buf);  // In-place exponentiation.\n\n    // Xor sha portion, so it all becomes 00 iff equal.\n    for (i = len - hash_len; i < len; ++i) {\n        buf[i] ^= *hash++;\n    }\n\n    // Hash resulting buf, in-place.\n    switch (hash_len) {\n        case SHA_DIGEST_SIZE:\n            padding_hash = kExpectedPadShaRsa2048;\n            SHA_hash(buf, len, buf);\n            break;\n        case SHA256_DIGEST_SIZE:\n            padding_hash = kExpectedPadSha256Rsa2048;\n            SHA256_hash(buf, len, buf);\n            break;\n        default:\n            return 0;\n    }\n\n    // Compare against expected hash value.\n    for (i = 0; i < hash_len; ++i) {\n        if (buf[i] != padding_hash[i]) {\n            return 0;\n        }\n    }\n\n    return 1;  // All checked out OK.\n}\n"
  },
  {
    "path": "external/mincrypt/sha.c",
    "content": "/* sha.c\n**\n** Copyright 2013, The Android Open Source Project\n**\n** Redistribution and use in source and binary forms, with or without\n** modification, are permitted provided that the following conditions are met:\n**     * Redistributions of source code must retain the above copyright\n**       notice, this list of conditions and the following disclaimer.\n**     * Redistributions in binary form must reproduce the above copyright\n**       notice, this list of conditions and the following disclaimer in the\n**       documentation and/or other materials provided with the distribution.\n**     * Neither the name of Google Inc. nor the names of its contributors may\n**       be used to endorse or promote products derived from this software\n**       without specific prior written permission.\n**\n** THIS SOFTWARE IS PROVIDED BY Google Inc. ``AS IS'' AND ANY EXPRESS OR\n** IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF\n** MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO\n** EVENT SHALL Google Inc. BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,\n** SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,\n** PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS;\n** OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,\n** WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR\n** OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF\n** ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n*/\n\n// Optimized for minimal code size.\n\n#include \"mincrypt/sha.h\"\n\n#include <stdio.h>\n#include <string.h>\n#include <stdint.h>\n\n#define rol(bits, value) (((value) << (bits)) | ((value) >> (32 - (bits))))\n\nstatic void SHA1_Transform(SHA_CTX* ctx) {\n    uint32_t W[80];\n    uint32_t A, B, C, D, E;\n    uint8_t* p = ctx->buf;\n    int t;\n\n    for(t = 0; t < 16; ++t) {\n        uint32_t tmp =  *p++ << 24;\n        tmp |= *p++ << 16;\n        tmp |= *p++ << 8;\n        tmp |= *p++;\n        W[t] = tmp;\n    }\n\n    for(; t < 80; t++) {\n        W[t] = rol(1,W[t-3] ^ W[t-8] ^ W[t-14] ^ W[t-16]);\n    }\n\n    A = ctx->state[0];\n    B = ctx->state[1];\n    C = ctx->state[2];\n    D = ctx->state[3];\n    E = ctx->state[4];\n\n    for(t = 0; t < 80; t++) {\n        uint32_t tmp = rol(5,A) + E + W[t];\n\n        if (t < 20)\n            tmp += (D^(B&(C^D))) + 0x5A827999;\n        else if ( t < 40)\n            tmp += (B^C^D) + 0x6ED9EBA1;\n        else if ( t < 60)\n            tmp += ((B&C)|(D&(B|C))) + 0x8F1BBCDC;\n        else\n            tmp += (B^C^D) + 0xCA62C1D6;\n\n        E = D;\n        D = C;\n        C = rol(30,B);\n        B = A;\n        A = tmp;\n    }\n\n    ctx->state[0] += A;\n    ctx->state[1] += B;\n    ctx->state[2] += C;\n    ctx->state[3] += D;\n    ctx->state[4] += E;\n}\n\nstatic const HASH_VTAB SHA_VTAB = {\n    SHA_init,\n    SHA_update,\n    SHA_final,\n    SHA_hash,\n    SHA_DIGEST_SIZE\n};\n\nvoid SHA_init(SHA_CTX* ctx) {\n    ctx->f = &SHA_VTAB;\n    ctx->state[0] = 0x67452301;\n    ctx->state[1] = 0xEFCDAB89;\n    ctx->state[2] = 0x98BADCFE;\n    ctx->state[3] = 0x10325476;\n    ctx->state[4] = 0xC3D2E1F0;\n    ctx->count = 0;\n}\n\n\nvoid SHA_update(SHA_CTX* ctx, const void* data, int len) {\n    int i = (int) (ctx->count & 63);\n    const uint8_t* p = (const uint8_t*)data;\n\n    ctx->count += len;\n\n    while (len--) {\n        ctx->buf[i++] = *p++;\n        if (i == 64) {\n            SHA1_Transform(ctx);\n            i = 0;\n        }\n    }\n}\n\n\nconst uint8_t* SHA_final(SHA_CTX* ctx) {\n    uint8_t *p = ctx->buf;\n    uint64_t cnt = ctx->count * 8;\n    int i;\n\n    SHA_update(ctx, (uint8_t*)\"\\x80\", 1);\n    while ((ctx->count & 63) != 56) {\n        SHA_update(ctx, (uint8_t*)\"\\0\", 1);\n    }\n    for (i = 0; i < 8; ++i) {\n        uint8_t tmp = (uint8_t) (cnt >> ((7 - i) * 8));\n        SHA_update(ctx, &tmp, 1);\n    }\n\n    for (i = 0; i < 5; i++) {\n        uint32_t tmp = ctx->state[i];\n        *p++ = tmp >> 24;\n        *p++ = tmp >> 16;\n        *p++ = tmp >> 8;\n        *p++ = tmp >> 0;\n    }\n\n    return ctx->buf;\n}\n\n/* Convenience function */\nconst uint8_t* SHA_hash(const void* data, int len, uint8_t* digest) {\n    SHA_CTX ctx;\n    SHA_init(&ctx);\n    SHA_update(&ctx, data, len);\n    memcpy(digest, SHA_final(&ctx), SHA_DIGEST_SIZE);\n    return digest;\n}\n"
  },
  {
    "path": "external/mincrypt/sha256.c",
    "content": "/* sha256.c\n**\n** Copyright 2013, The Android Open Source Project\n**\n** Redistribution and use in source and binary forms, with or without\n** modification, are permitted provided that the following conditions are met:\n**     * Redistributions of source code must retain the above copyright\n**       notice, this list of conditions and the following disclaimer.\n**     * Redistributions in binary form must reproduce the above copyright\n**       notice, this list of conditions and the following disclaimer in the\n**       documentation and/or other materials provided with the distribution.\n**     * Neither the name of Google Inc. nor the names of its contributors may\n**       be used to endorse or promote products derived from this software\n**       without specific prior written permission.\n**\n** THIS SOFTWARE IS PROVIDED BY Google Inc. ``AS IS'' AND ANY EXPRESS OR\n** IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF\n** MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO\n** EVENT SHALL Google Inc. BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,\n** SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,\n** PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS;\n** OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,\n** WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR\n** OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF\n** ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n*/\n\n// Optimized for minimal code size.\n\n#include \"mincrypt/sha256.h\"\n\n#include <stdio.h>\n#include <string.h>\n#include <stdint.h>\n\n#define ror(value, bits) (((value) >> (bits)) | ((value) << (32 - (bits))))\n#define shr(value, bits) ((value) >> (bits))\n\nstatic const uint32_t K[64] = {\n    0x428a2f98, 0x71374491, 0xb5c0fbcf, 0xe9b5dba5,\n    0x3956c25b, 0x59f111f1, 0x923f82a4, 0xab1c5ed5,\n    0xd807aa98, 0x12835b01, 0x243185be, 0x550c7dc3,\n    0x72be5d74, 0x80deb1fe, 0x9bdc06a7, 0xc19bf174,\n    0xe49b69c1, 0xefbe4786, 0x0fc19dc6, 0x240ca1cc,\n    0x2de92c6f, 0x4a7484aa, 0x5cb0a9dc, 0x76f988da,\n    0x983e5152, 0xa831c66d, 0xb00327c8, 0xbf597fc7,\n    0xc6e00bf3, 0xd5a79147, 0x06ca6351, 0x14292967,\n    0x27b70a85, 0x2e1b2138, 0x4d2c6dfc, 0x53380d13,\n    0x650a7354, 0x766a0abb, 0x81c2c92e, 0x92722c85,\n    0xa2bfe8a1, 0xa81a664b, 0xc24b8b70, 0xc76c51a3,\n    0xd192e819, 0xd6990624, 0xf40e3585, 0x106aa070,\n    0x19a4c116, 0x1e376c08, 0x2748774c, 0x34b0bcb5,\n    0x391c0cb3, 0x4ed8aa4a, 0x5b9cca4f, 0x682e6ff3,\n    0x748f82ee, 0x78a5636f, 0x84c87814, 0x8cc70208,\n    0x90befffa, 0xa4506ceb, 0xbef9a3f7, 0xc67178f2 };\n\nstatic void SHA256_Transform(SHA256_CTX* ctx) {\n    uint32_t W[64];\n    uint32_t A, B, C, D, E, F, G, H;\n    uint8_t* p = ctx->buf;\n    int t;\n\n    for(t = 0; t < 16; ++t) {\n        uint32_t tmp =  *p++ << 24;\n        tmp |= *p++ << 16;\n        tmp |= *p++ << 8;\n        tmp |= *p++;\n        W[t] = tmp;\n    }\n\n    for(; t < 64; t++) {\n        uint32_t s0 = ror(W[t-15], 7) ^ ror(W[t-15], 18) ^ shr(W[t-15], 3);\n        uint32_t s1 = ror(W[t-2], 17) ^ ror(W[t-2], 19) ^ shr(W[t-2], 10);\n        W[t] = W[t-16] + s0 + W[t-7] + s1;\n    }\n\n    A = ctx->state[0];\n    B = ctx->state[1];\n    C = ctx->state[2];\n    D = ctx->state[3];\n    E = ctx->state[4];\n    F = ctx->state[5];\n    G = ctx->state[6];\n    H = ctx->state[7];\n\n    for(t = 0; t < 64; t++) {\n        uint32_t s0 = ror(A, 2) ^ ror(A, 13) ^ ror(A, 22);\n        uint32_t maj = (A & B) ^ (A & C) ^ (B & C);\n        uint32_t t2 = s0 + maj;\n        uint32_t s1 = ror(E, 6) ^ ror(E, 11) ^ ror(E, 25);\n        uint32_t ch = (E & F) ^ ((~E) & G);\n        uint32_t t1 = H + s1 + ch + K[t] + W[t];\n\n        H = G;\n        G = F;\n        F = E;\n        E = D + t1;\n        D = C;\n        C = B;\n        B = A;\n        A = t1 + t2;\n    }\n\n    ctx->state[0] += A;\n    ctx->state[1] += B;\n    ctx->state[2] += C;\n    ctx->state[3] += D;\n    ctx->state[4] += E;\n    ctx->state[5] += F;\n    ctx->state[6] += G;\n    ctx->state[7] += H;\n}\n\nstatic const HASH_VTAB SHA256_VTAB = {\n    SHA256_init,\n    SHA256_update,\n    SHA256_final,\n    SHA256_hash,\n    SHA256_DIGEST_SIZE\n};\n\nvoid SHA256_init(SHA256_CTX* ctx) {\n    ctx->f = &SHA256_VTAB;\n    ctx->state[0] = 0x6a09e667;\n    ctx->state[1] = 0xbb67ae85;\n    ctx->state[2] = 0x3c6ef372;\n    ctx->state[3] = 0xa54ff53a;\n    ctx->state[4] = 0x510e527f;\n    ctx->state[5] = 0x9b05688c;\n    ctx->state[6] = 0x1f83d9ab;\n    ctx->state[7] = 0x5be0cd19;\n    ctx->count = 0;\n}\n\n\nvoid SHA256_update(SHA256_CTX* ctx, const void* data, int len) {\n    int i = (int) (ctx->count & 63);\n    const uint8_t* p = (const uint8_t*)data;\n\n    ctx->count += len;\n\n    while (len--) {\n        ctx->buf[i++] = *p++;\n        if (i == 64) {\n            SHA256_Transform(ctx);\n            i = 0;\n        }\n    }\n}\n\n\nconst uint8_t* SHA256_final(SHA256_CTX* ctx) {\n    uint8_t *p = ctx->buf;\n    uint64_t cnt = ctx->count * 8;\n    int i;\n\n    SHA256_update(ctx, (uint8_t*)\"\\x80\", 1);\n    while ((ctx->count & 63) != 56) {\n        SHA256_update(ctx, (uint8_t*)\"\\0\", 1);\n    }\n    for (i = 0; i < 8; ++i) {\n        uint8_t tmp = (uint8_t) (cnt >> ((7 - i) * 8));\n        SHA256_update(ctx, &tmp, 1);\n    }\n\n    for (i = 0; i < 8; i++) {\n        uint32_t tmp = ctx->state[i];\n        *p++ = tmp >> 24;\n        *p++ = tmp >> 16;\n        *p++ = tmp >> 8;\n        *p++ = tmp >> 0;\n    }\n\n    return ctx->buf;\n}\n\n/* Convenience function */\nconst uint8_t* SHA256_hash(const void* data, int len, uint8_t* digest) {\n    SHA256_CTX ctx;\n    SHA256_init(&ctx);\n    SHA256_update(&ctx, data, len);\n    memcpy(digest, SHA256_final(&ctx), SHA256_DIGEST_SIZE);\n    return digest;\n}\n"
  },
  {
    "path": "external/xz/common/mythread.h",
    "content": "///////////////////////////////////////////////////////////////////////////////\n//\n/// \\file       mythread.h\n/// \\brief      Some threading related helper macros and functions\n//\n//  Author:     Lasse Collin\n//\n//  This file has been put into the public domain.\n//  You can do whatever you want with this file.\n//\n///////////////////////////////////////////////////////////////////////////////\n\n#ifndef MYTHREAD_H\n#define MYTHREAD_H\n\n#include \"sysdefs.h\"\n\n// If any type of threading is enabled, #define MYTHREAD_ENABLED.\n#if defined(MYTHREAD_POSIX) || defined(MYTHREAD_WIN95) \\\n\t\t|| defined(MYTHREAD_VISTA)\n#\tdefine MYTHREAD_ENABLED 1\n#endif\n\n\n#ifdef MYTHREAD_ENABLED\n\n////////////////////////////////////////\n// Shared between all threading types //\n////////////////////////////////////////\n\n// Locks a mutex for a duration of a block.\n//\n// Perform mythread_mutex_lock(&mutex) in the beginning of a block\n// and mythread_mutex_unlock(&mutex) at the end of the block. \"break\"\n// may be used to unlock the mutex and jump out of the block.\n// mythread_sync blocks may be nested.\n//\n// Example:\n//\n//     mythread_sync(mutex) {\n//         foo();\n//         if (some_error)\n//             break; // Skips bar()\n//         bar();\n//     }\n//\n// At least GCC optimizes the loops completely away so it doesn't slow\n// things down at all compared to plain mythread_mutex_lock(&mutex)\n// and mythread_mutex_unlock(&mutex) calls.\n//\n#define mythread_sync(mutex) mythread_sync_helper1(mutex, __LINE__)\n#define mythread_sync_helper1(mutex, line) mythread_sync_helper2(mutex, line)\n#define mythread_sync_helper2(mutex, line) \\\n\tfor (unsigned int mythread_i_ ## line = 0; \\\n\t\t\tmythread_i_ ## line \\\n\t\t\t\t? (mythread_mutex_unlock(&(mutex)), 0) \\\n\t\t\t\t: (mythread_mutex_lock(&(mutex)), 1); \\\n\t\t\tmythread_i_ ## line = 1) \\\n\t\tfor (unsigned int mythread_j_ ## line = 0; \\\n\t\t\t\t!mythread_j_ ## line; \\\n\t\t\t\tmythread_j_ ## line = 1)\n#endif\n\n\n#if !defined(MYTHREAD_ENABLED)\n\n//////////////////\n// No threading //\n//////////////////\n\n// Calls the given function once. This isn't thread safe.\n#define mythread_once(func) \\\ndo { \\\n\tstatic bool once_ = false; \\\n\tif (!once_) { \\\n\t\tfunc(); \\\n\t\tonce_ = true; \\\n\t} \\\n} while (0)\n\n\n#if !(defined(_WIN32) && !defined(__CYGWIN__))\n// Use sigprocmask() to set the signal mask in single-threaded programs.\n#include <signal.h>\n\nstatic inline void\nmythread_sigmask(int how, const sigset_t *restrict set,\n\t\tsigset_t *restrict oset)\n{\n\tint ret = sigprocmask(how, set, oset);\n\tassert(ret == 0);\n\t(void)ret;\n}\n#endif\n\n\n#elif defined(MYTHREAD_POSIX)\n\n////////////////////\n// Using pthreads //\n////////////////////\n\n#include <sys/time.h>\n#include <pthread.h>\n#include <signal.h>\n#include <time.h>\n#include <errno.h>\n\n#define MYTHREAD_RET_TYPE void *\n#define MYTHREAD_RET_VALUE NULL\n\ntypedef pthread_t mythread;\ntypedef pthread_mutex_t mythread_mutex;\n\ntypedef struct {\n\tpthread_cond_t cond;\n#ifdef HAVE_CLOCK_GETTIME\n\t// Clock ID (CLOCK_REALTIME or CLOCK_MONOTONIC) associated with\n\t// the condition variable.\n\tclockid_t clk_id;\n#endif\n} mythread_cond;\n\ntypedef struct timespec mythread_condtime;\n\n\n// Calls the given function once in a thread-safe way.\n#define mythread_once(func) \\\n\tdo { \\\n\t\tstatic pthread_once_t once_ = PTHREAD_ONCE_INIT; \\\n\t\tpthread_once(&once_, &func); \\\n\t} while (0)\n\n\n// Use pthread_sigmask() to set the signal mask in multi-threaded programs.\n// Do nothing on OpenVMS since it lacks pthread_sigmask().\nstatic inline void\nmythread_sigmask(int how, const sigset_t *restrict set,\n\t\tsigset_t *restrict oset)\n{\n#ifdef __VMS\n\t(void)how;\n\t(void)set;\n\t(void)oset;\n#else\n\tint ret = pthread_sigmask(how, set, oset);\n\tassert(ret == 0);\n\t(void)ret;\n#endif\n}\n\n\n// Creates a new thread with all signals blocked. Returns zero on success\n// and non-zero on error.\nstatic inline int\nmythread_create(mythread *thread, void *(*func)(void *arg), void *arg)\n{\n\tsigset_t old;\n\tsigset_t all;\n#ifndef SVB_MINGW  \n\tsigfillset(&all);\n#else\n\tall = 255;\n#endif\n\tmythread_sigmask(SIG_SETMASK, &all, &old);\n\tconst int ret = pthread_create(thread, NULL, func, arg);\n\tmythread_sigmask(SIG_SETMASK, &old, NULL);\n\n\treturn ret;\n}\n\n// Joins a thread. Returns zero on success and non-zero on error.\nstatic inline int\nmythread_join(mythread thread)\n{\n\treturn pthread_join(thread, NULL);\n}\n\n\n// Initiatlizes a mutex. Returns zero on success and non-zero on error.\nstatic inline int\nmythread_mutex_init(mythread_mutex *mutex)\n{\n\treturn pthread_mutex_init(mutex, NULL);\n}\n\nstatic inline void\nmythread_mutex_destroy(mythread_mutex *mutex)\n{\n\tint ret = pthread_mutex_destroy(mutex);\n\tassert(ret == 0);\n\t(void)ret;\n}\n\nstatic inline void\nmythread_mutex_lock(mythread_mutex *mutex)\n{\n\tint ret = pthread_mutex_lock(mutex);\n\tassert(ret == 0);\n\t(void)ret;\n}\n\nstatic inline void\nmythread_mutex_unlock(mythread_mutex *mutex)\n{\n\tint ret = pthread_mutex_unlock(mutex);\n\tassert(ret == 0);\n\t(void)ret;\n}\n\n\n// Initializes a condition variable.\n//\n// Using CLOCK_MONOTONIC instead of the default CLOCK_REALTIME makes the\n// timeout in pthread_cond_timedwait() work correctly also if system time\n// is suddenly changed. Unfortunately CLOCK_MONOTONIC isn't available\n// everywhere while the default CLOCK_REALTIME is, so the default is\n// used if CLOCK_MONOTONIC isn't available.\n//\n// If clock_gettime() isn't available at all, gettimeofday() will be used.\nstatic inline int\nmythread_cond_init(mythread_cond *mycond)\n{\n#ifdef HAVE_CLOCK_GETTIME\n\t// NOTE: HAVE_DECL_CLOCK_MONOTONIC is always defined to 0 or 1.\n#\tif defined(HAVE_PTHREAD_CONDATTR_SETCLOCK) && HAVE_DECL_CLOCK_MONOTONIC\n\tstruct timespec ts;\n\tpthread_condattr_t condattr;\n\n\t// POSIX doesn't seem to *require* that pthread_condattr_setclock()\n\t// will fail if given an unsupported clock ID. Test that\n\t// CLOCK_MONOTONIC really is supported using clock_gettime().\n\tif (clock_gettime(CLOCK_MONOTONIC, &ts) == 0\n\t\t\t&& pthread_condattr_init(&condattr) == 0) {\n\t\tint ret = pthread_condattr_setclock(\n\t\t\t\t&condattr, CLOCK_MONOTONIC);\n\t\tif (ret == 0)\n\t\t\tret = pthread_cond_init(&mycond->cond, &condattr);\n\n\t\tpthread_condattr_destroy(&condattr);\n\n\t\tif (ret == 0) {\n\t\t\tmycond->clk_id = CLOCK_MONOTONIC;\n\t\t\treturn 0;\n\t\t}\n\t}\n\n\t// If anything above fails, fall back to the default CLOCK_REALTIME.\n\t// POSIX requires that all implementations of clock_gettime() must\n\t// support at least CLOCK_REALTIME.\n#\tendif\n\n\tmycond->clk_id = CLOCK_REALTIME;\n#endif\n\n\treturn pthread_cond_init(&mycond->cond, NULL);\n}\n\nstatic inline void\nmythread_cond_destroy(mythread_cond *cond)\n{\n\tint ret = pthread_cond_destroy(&cond->cond);\n\tassert(ret == 0);\n\t(void)ret;\n}\n\nstatic inline void\nmythread_cond_signal(mythread_cond *cond)\n{\n\tint ret = pthread_cond_signal(&cond->cond);\n\tassert(ret == 0);\n\t(void)ret;\n}\n\nstatic inline void\nmythread_cond_wait(mythread_cond *cond, mythread_mutex *mutex)\n{\n\tint ret = pthread_cond_wait(&cond->cond, mutex);\n\tassert(ret == 0);\n\t(void)ret;\n}\n\n// Waits on a condition or until a timeout expires. If the timeout expires,\n// non-zero is returned, otherwise zero is returned.\nstatic inline int\nmythread_cond_timedwait(mythread_cond *cond, mythread_mutex *mutex,\n\t\tconst mythread_condtime *condtime)\n{\n\tint ret = pthread_cond_timedwait(&cond->cond, mutex, condtime);\n\tassert(ret == 0 || ret == ETIMEDOUT);\n\treturn ret;\n}\n\n// Sets condtime to the absolute time that is timeout_ms milliseconds\n// in the future. The type of the clock to use is taken from cond.\nstatic inline void\nmythread_condtime_set(mythread_condtime *condtime, const mythread_cond *cond,\n\t\tuint32_t timeout_ms)\n{\n\tcondtime->tv_sec = timeout_ms / 1000;\n\tcondtime->tv_nsec = (timeout_ms % 1000) * 1000000;\n\n#ifdef HAVE_CLOCK_GETTIME\n\tstruct timespec now;\n\tint ret = clock_gettime(cond->clk_id, &now);\n\tassert(ret == 0);\n\t(void)ret;\n\n\tcondtime->tv_sec += now.tv_sec;\n\tcondtime->tv_nsec += now.tv_nsec;\n#else\n\t(void)cond;\n\n\tstruct timeval now;\n\tgettimeofday(&now, NULL);\n\n\tcondtime->tv_sec += now.tv_sec;\n\tcondtime->tv_nsec += now.tv_usec * 1000L;\n#endif\n\n\t// tv_nsec must stay in the range [0, 999_999_999].\n\tif (condtime->tv_nsec >= 1000000000L) {\n\t\tcondtime->tv_nsec -= 1000000000L;\n\t\t++condtime->tv_sec;\n\t}\n}\n\n\n#elif defined(MYTHREAD_WIN95) || defined(MYTHREAD_VISTA)\n\n/////////////////////\n// Windows threads //\n/////////////////////\n\n#define WIN32_LEAN_AND_MEAN\n#ifdef MYTHREAD_VISTA\n#\tundef _WIN32_WINNT\n#\tdefine _WIN32_WINNT 0x0600\n#endif\n#include <windows.h>\n#include <process.h>\n\n#define MYTHREAD_RET_TYPE unsigned int __stdcall\n#define MYTHREAD_RET_VALUE 0\n\ntypedef HANDLE mythread;\ntypedef CRITICAL_SECTION mythread_mutex;\n\n#ifdef MYTHREAD_WIN95\ntypedef HANDLE mythread_cond;\n#else\ntypedef CONDITION_VARIABLE mythread_cond;\n#endif\n\ntypedef struct {\n\t// Tick count (milliseconds) in the beginning of the timeout.\n\t// NOTE: This is 32 bits so it wraps around after 49.7 days.\n\t// Multi-day timeouts may not work as expected.\n\tDWORD start;\n\n\t// Length of the timeout in milliseconds. The timeout expires\n\t// when the current tick count minus \"start\" is equal or greater\n\t// than \"timeout\".\n\tDWORD timeout;\n} mythread_condtime;\n\n\n// mythread_once() is only available with Vista threads.\n#ifdef MYTHREAD_VISTA\n#define mythread_once(func) \\\n\tdo { \\\n\t\tstatic INIT_ONCE once_ = INIT_ONCE_STATIC_INIT; \\\n\t\tBOOL pending_; \\\n\t\tif (!InitOnceBeginInitialize(&once_, 0, &pending_, NULL)) \\\n\t\t\tabort(); \\\n\t\tif (pending_) \\\n\t\t\tfunc(); \\\n\t\tif (!InitOnceComplete(&once, 0, NULL)) \\\n\t\t\tabort(); \\\n\t} while (0)\n#endif\n\n\n// mythread_sigmask() isn't available on Windows. Even a dummy version would\n// make no sense because the other POSIX signal functions are missing anyway.\n\n\nstatic inline int\nmythread_create(mythread *thread,\n\t\tunsigned int (__stdcall *func)(void *arg), void *arg)\n{\n\tuintptr_t ret = _beginthreadex(NULL, 0, func, arg, 0, NULL);\n\tif (ret == 0)\n\t\treturn -1;\n\n\t*thread = (HANDLE)ret;\n\treturn 0;\n}\n\nstatic inline int\nmythread_join(mythread thread)\n{\n\tint ret = 0;\n\n\tif (WaitForSingleObject(thread, INFINITE) != WAIT_OBJECT_0)\n\t\tret = -1;\n\n\tif (!CloseHandle(thread))\n\t\tret = -1;\n\n\treturn ret;\n}\n\n\nstatic inline int\nmythread_mutex_init(mythread_mutex *mutex)\n{\n\tInitializeCriticalSection(mutex);\n\treturn 0;\n}\n\nstatic inline void\nmythread_mutex_destroy(mythread_mutex *mutex)\n{\n\tDeleteCriticalSection(mutex);\n}\n\nstatic inline void\nmythread_mutex_lock(mythread_mutex *mutex)\n{\n\tEnterCriticalSection(mutex);\n}\n\nstatic inline void\nmythread_mutex_unlock(mythread_mutex *mutex)\n{\n\tLeaveCriticalSection(mutex);\n}\n\n\nstatic inline int\nmythread_cond_init(mythread_cond *cond)\n{\n#ifdef MYTHREAD_WIN95\n\t*cond = CreateEvent(NULL, FALSE, FALSE, NULL);\n\treturn *cond == NULL ? -1 : 0;\n#else\n\tInitializeConditionVariable(cond);\n\treturn 0;\n#endif\n}\n\nstatic inline void\nmythread_cond_destroy(mythread_cond *cond)\n{\n#ifdef MYTHREAD_WIN95\n\tCloseHandle(*cond);\n#else\n\t(void)cond;\n#endif\n}\n\nstatic inline void\nmythread_cond_signal(mythread_cond *cond)\n{\n#ifdef MYTHREAD_WIN95\n\tSetEvent(*cond);\n#else\n\tWakeConditionVariable(cond);\n#endif\n}\n\nstatic inline void\nmythread_cond_wait(mythread_cond *cond, mythread_mutex *mutex)\n{\n#ifdef MYTHREAD_WIN95\n\tLeaveCriticalSection(mutex);\n\tWaitForSingleObject(*cond, INFINITE);\n\tEnterCriticalSection(mutex);\n#else\n\tBOOL ret = SleepConditionVariableCS(cond, mutex, INFINITE);\n\tassert(ret);\n\t(void)ret;\n#endif\n}\n\nstatic inline int\nmythread_cond_timedwait(mythread_cond *cond, mythread_mutex *mutex,\n\t\tconst mythread_condtime *condtime)\n{\n#ifdef MYTHREAD_WIN95\n\tLeaveCriticalSection(mutex);\n#endif\n\n\tDWORD elapsed = GetTickCount() - condtime->start;\n\tDWORD timeout = elapsed >= condtime->timeout\n\t\t\t? 0 : condtime->timeout - elapsed;\n\n#ifdef MYTHREAD_WIN95\n\tDWORD ret = WaitForSingleObject(*cond, timeout);\n\tassert(ret == WAIT_OBJECT_0 || ret == WAIT_TIMEOUT);\n\n\tEnterCriticalSection(mutex);\n\n\treturn ret == WAIT_TIMEOUT;\n#else\n\tBOOL ret = SleepConditionVariableCS(cond, mutex, timeout);\n\tassert(ret || GetLastError() == ERROR_TIMEOUT);\n\treturn !ret;\n#endif\n}\n\nstatic inline void\nmythread_condtime_set(mythread_condtime *condtime, const mythread_cond *cond,\n\t\tuint32_t timeout)\n{\n\t(void)cond;\n\tcondtime->start = GetTickCount();\n\tcondtime->timeout = timeout;\n}\n\n#endif\n\n#endif\n"
  },
  {
    "path": "external/xz/common/sysdefs.h",
    "content": "///////////////////////////////////////////////////////////////////////////////\n//\n/// \\file       sysdefs.h\n/// \\brief      Common includes, definitions, system-specific things etc.\n///\n/// This file is used also by the lzma command line tool, that's why this\n/// file is separate from common.h.\n//\n//  Author:     Lasse Collin\n//\n//  This file has been put into the public domain.\n//  You can do whatever you want with this file.\n//\n///////////////////////////////////////////////////////////////////////////////\n\n#ifndef LZMA_SYSDEFS_H\n#define LZMA_SYSDEFS_H\n\n//////////////\n// Includes //\n//////////////\n\n#ifdef HAVE_CONFIG_H\n#\tinclude <config.h>\n#endif\n\n// Get standard-compliant stdio functions under MinGW and MinGW-w64.\n#ifdef __MINGW32__\n#\tdefine __USE_MINGW_ANSI_STDIO 1\n#endif\n\n// size_t and NULL\n#include <stddef.h>\n\n#ifdef HAVE_INTTYPES_H\n#\tinclude <inttypes.h>\n#endif\n\n// C99 says that inttypes.h always includes stdint.h, but some systems\n// don't do that, and require including stdint.h separately.\n#ifdef HAVE_STDINT_H\n#\tinclude <stdint.h>\n#endif\n\n// Some pre-C99 systems have SIZE_MAX in limits.h instead of stdint.h. The\n// limits are also used to figure out some macros missing from pre-C99 systems.\n#include <limits.h>\n\n// Be more compatible with systems that have non-conforming inttypes.h.\n// We assume that int is 32-bit and that long is either 32-bit or 64-bit.\n// Full Autoconf test could be more correct, but this should work well enough.\n// Note that this duplicates some code from lzma.h, but this is better since\n// we can work without inttypes.h thanks to Autoconf tests.\n#ifndef UINT32_C\n#\tif UINT_MAX != 4294967295U\n#\t\terror UINT32_C is not defined and unsigned int is not 32-bit.\n#\tendif\n#\tdefine UINT32_C(n) n ## U\n#endif\n#ifndef UINT32_MAX\n#\tdefine UINT32_MAX UINT32_C(4294967295)\n#endif\n#ifndef PRIu32\n#\tdefine PRIu32 \"u\"\n#endif\n#ifndef PRIx32\n#\tdefine PRIx32 \"x\"\n#endif\n#ifndef PRIX32\n#\tdefine PRIX32 \"X\"\n#endif\n\n#if ULONG_MAX == 4294967295UL\n#\tifndef UINT64_C\n#\t\tdefine UINT64_C(n) n ## ULL\n#\tendif\n#\tifndef PRIu64\n#\t\tdefine PRIu64 \"llu\"\n#\tendif\n#\tifndef PRIx64\n#\t\tdefine PRIx64 \"llx\"\n#\tendif\n#\tifndef PRIX64\n#\t\tdefine PRIX64 \"llX\"\n#\tendif\n#else\n#\tifndef UINT64_C\n#\t\tdefine UINT64_C(n) n ## UL\n#\tendif\n#\tifndef PRIu64\n#\t\tdefine PRIu64 \"lu\"\n#\tendif\n#\tifndef PRIx64\n#\t\tdefine PRIx64 \"lx\"\n#\tendif\n#\tifndef PRIX64\n#\t\tdefine PRIX64 \"lX\"\n#\tendif\n#endif\n#ifndef UINT64_MAX\n#\tdefine UINT64_MAX UINT64_C(18446744073709551615)\n#endif\n\n// Incorrect(?) SIZE_MAX:\n//   - Interix headers typedef size_t to unsigned long,\n//     but a few lines later define SIZE_MAX to INT32_MAX.\n//   - SCO OpenServer (x86) headers typedef size_t to unsigned int\n//     but define SIZE_MAX to INT32_MAX.\n#if defined(__INTERIX) || defined(_SCO_DS)\n#\tundef SIZE_MAX\n#endif\n\n// The code currently assumes that size_t is either 32-bit or 64-bit.\n#ifndef SIZE_MAX\n#\tif SIZEOF_SIZE_T == 4\n#\t\tdefine SIZE_MAX UINT32_MAX\n#\telif SIZEOF_SIZE_T == 8\n#\t\tdefine SIZE_MAX UINT64_MAX\n#\telse\n#\t\terror size_t is not 32-bit or 64-bit\n#\tendif\n#endif\n#if SIZE_MAX != UINT32_MAX && SIZE_MAX != UINT64_MAX\n#\terror size_t is not 32-bit or 64-bit\n#endif\n\n#include <stdlib.h>\n#include <assert.h>\n\n// Pre-C99 systems lack stdbool.h. All the code in LZMA Utils must be written\n// so that it works with fake bool type, for example:\n//\n//    bool foo = (flags & 0x100) != 0;\n//    bool bar = !!(flags & 0x100);\n//\n// This works with the real C99 bool but breaks with fake bool:\n//\n//    bool baz = (flags & 0x100);\n//\n#ifdef HAVE_STDBOOL_H\n#\tinclude <stdbool.h>\n#else\n#\tif ! HAVE__BOOL\ntypedef unsigned char _Bool;\n#\tendif\n#\tdefine bool _Bool\n#\tdefine false 0\n#\tdefine true 1\n#\tdefine __bool_true_false_are_defined 1\n#endif\n\n// string.h should be enough but let's include strings.h and memory.h too if\n// they exists, since that shouldn't do any harm, but may improve portability.\n#include <string.h>\n\n#ifdef HAVE_STRINGS_H\n#\tinclude <strings.h>\n#endif\n\n#ifdef HAVE_MEMORY_H\n#\tinclude <memory.h>\n#endif\n\n// As of MSVC 2013, inline and restrict are supported with\n// non-standard keywords.\n#if defined(_WIN32) && defined(_MSC_VER)\n#\tifndef inline\n#\t\tdefine inline __inline\n#\tendif\n#\tifndef restrict\n#\t\tdefine restrict __restrict\n#\tendif\n#endif\n\n////////////\n// Macros //\n////////////\n\n#undef memzero\n#define memzero(s, n) memset(s, 0, n)\n\n// NOTE: Avoid using MIN() and MAX(), because even conditionally defining\n// those macros can cause some portability trouble, since on some systems\n// the system headers insist defining their own versions.\n#define my_min(x, y) ((x) < (y) ? (x) : (y))\n#define my_max(x, y) ((x) > (y) ? (x) : (y))\n\n#ifndef ARRAY_SIZE\n#\tdefine ARRAY_SIZE(array) (sizeof(array) / sizeof((array)[0]))\n#endif\n\n#if defined(__GNUC__) \\\n\t\t&& ((__GNUC__ == 4 && __GNUC_MINOR__ >= 3) || __GNUC__ > 4)\n#\tdefine lzma_attr_alloc_size(x) __attribute__((__alloc_size__(x)))\n#else\n#\tdefine lzma_attr_alloc_size(x)\n#endif\n\n#endif\n"
  },
  {
    "path": "external/xz/common/tuklib_common.h",
    "content": "///////////////////////////////////////////////////////////////////////////////\n//\n/// \\file       tuklib_common.h\n/// \\brief      Common definitions for tuklib modules\n//\n//  Author:     Lasse Collin\n//\n//  This file has been put into the public domain.\n//  You can do whatever you want with this file.\n//\n///////////////////////////////////////////////////////////////////////////////\n\n#ifndef TUKLIB_COMMON_H\n#define TUKLIB_COMMON_H\n\n// The config file may be replaced by a package-specific file.\n// It should include at least stddef.h, inttypes.h, and limits.h.\n#include \"tuklib_config.h\"\n\n// TUKLIB_SYMBOL_PREFIX is prefixed to all symbols exported by\n// the tuklib modules. If you use a tuklib module in a library,\n// you should use TUKLIB_SYMBOL_PREFIX to make sure that there\n// are no symbol conflicts in case someone links your library\n// into application that also uses the same tuklib module.\n#ifndef TUKLIB_SYMBOL_PREFIX\n#\tdefine TUKLIB_SYMBOL_PREFIX\n#endif\n\n#define TUKLIB_CAT_X(a, b) a ## b\n#define TUKLIB_CAT(a, b) TUKLIB_CAT_X(a, b)\n\n#ifndef TUKLIB_SYMBOL\n#\tdefine TUKLIB_SYMBOL(sym) TUKLIB_CAT(TUKLIB_SYMBOL_PREFIX, sym)\n#endif\n\n#ifndef TUKLIB_DECLS_BEGIN\n#\tifdef __cplusplus\n#\t\tdefine TUKLIB_DECLS_BEGIN extern \"C\" {\n#\telse\n#\t\tdefine TUKLIB_DECLS_BEGIN\n#\tendif\n#endif\n\n#ifndef TUKLIB_DECLS_END\n#\tifdef __cplusplus\n#\t\tdefine TUKLIB_DECLS_END }\n#\telse\n#\t\tdefine TUKLIB_DECLS_END\n#\tendif\n#endif\n\n#if defined(__GNUC__) && defined(__GNUC_MINOR__)\n#\tdefine TUKLIB_GNUC_REQ(major, minor) \\\n\t\t((__GNUC__ == (major) && __GNUC_MINOR__ >= (minor)) \\\n\t\t\t|| __GNUC__ > (major))\n#else\n#\tdefine TUKLIB_GNUC_REQ(major, minor) 0\n#endif\n\n#if TUKLIB_GNUC_REQ(2, 5)\n#\tdefine tuklib_attr_noreturn __attribute__((__noreturn__))\n#else\n#\tdefine tuklib_attr_noreturn\n#endif\n\n#if (defined(_WIN32) && !defined(__CYGWIN__)) \\\n\t\t|| defined(__OS2__) || defined(__MSDOS__)\n#\tdefine TUKLIB_DOSLIKE 1\n#endif\n\n#endif\n"
  },
  {
    "path": "external/xz/common/tuklib_config.h",
    "content": "#ifdef HAVE_CONFIG_H\n#\tinclude \"sysdefs.h\"\n#else\n#\tinclude <stddef.h>\n#\tinclude <inttypes.h>\n#\tinclude <limits.h>\n#endif\n"
  },
  {
    "path": "external/xz/common/tuklib_cpucores.c",
    "content": "///////////////////////////////////////////////////////////////////////////////\n//\n/// \\file       tuklib_cpucores.c\n/// \\brief      Get the number of CPU cores online\n//\n//  Author:     Lasse Collin\n//\n//  This file has been put into the public domain.\n//  You can do whatever you want with this file.\n//\n///////////////////////////////////////////////////////////////////////////////\n\n#include \"tuklib_cpucores.h\"\n\n#if defined(_WIN32) || defined(__CYGWIN__)\n#\tifndef _WIN32_WINNT\n#\t\tdefine _WIN32_WINNT 0x0500\n#\tendif\n#\tinclude <windows.h>\n\n// glibc >= 2.9\n#elif defined(TUKLIB_CPUCORES_SCHED_GETAFFINITY)\n#\tinclude <sched.h>\n\n// FreeBSD\n#elif defined(TUKLIB_CPUCORES_CPUSET)\n#\tinclude <sys/param.h>\n#\tinclude <sys/cpuset.h>\n\n#elif defined(TUKLIB_CPUCORES_SYSCTL)\n#\tifdef HAVE_SYS_PARAM_H\n#\t\tinclude <sys/param.h>\n#\tendif\n#\tinclude <sys/sysctl.h>\n\n#elif defined(TUKLIB_CPUCORES_SYSCONF)\n#\tinclude <unistd.h>\n\n// HP-UX\n#elif defined(TUKLIB_CPUCORES_PSTAT_GETDYNAMIC)\n#\tinclude <sys/param.h>\n#\tinclude <sys/pstat.h>\n#endif\n\n\nextern uint32_t\ntuklib_cpucores(void)\n{\n\tuint32_t ret = 0;\n\n#if defined(_WIN32) || defined(__CYGWIN__)\n\tSYSTEM_INFO sysinfo;\n\tGetSystemInfo(&sysinfo);\n\tret = sysinfo.dwNumberOfProcessors;\n\n#elif defined(TUKLIB_CPUCORES_SCHED_GETAFFINITY)\n\tcpu_set_t cpu_mask;\n\tif (sched_getaffinity(0, sizeof(cpu_mask), &cpu_mask) == 0)\n\t\tret = (uint32_t)CPU_COUNT(&cpu_mask);\n\n#elif defined(TUKLIB_CPUCORES_CPUSET)\n\tcpuset_t set;\n\tif (cpuset_getaffinity(CPU_LEVEL_WHICH, CPU_WHICH_PID, -1,\n\t\t\tsizeof(set), &set) == 0) {\n#\tifdef CPU_COUNT\n\t\tret = (uint32_t)CPU_COUNT(&set);\n#\telse\n\t\tfor (unsigned i = 0; i < CPU_SETSIZE; ++i)\n\t\t\tif (CPU_ISSET(i, &set))\n\t\t\t\t++ret;\n#\tendif\n\t}\n\n#elif defined(TUKLIB_CPUCORES_SYSCTL)\n\tint name[2] = { CTL_HW, HW_NCPU };\n\tint cpus;\n\tsize_t cpus_size = sizeof(cpus);\n\tif (sysctl(name, 2, &cpus, &cpus_size, NULL, 0) != -1\n\t\t\t&& cpus_size == sizeof(cpus) && cpus > 0)\n\t\tret = (uint32_t)cpus;\n\n#elif defined(TUKLIB_CPUCORES_SYSCONF)\n#\tifdef _SC_NPROCESSORS_ONLN\n\t// Most systems\n\tconst long cpus = sysconf(_SC_NPROCESSORS_ONLN);\n#\telse\n\t// IRIX\n\tconst long cpus = sysconf(_SC_NPROC_ONLN);\n#\tendif\n\tif (cpus > 0)\n\t\tret = (uint32_t)cpus;\n\n#elif defined(TUKLIB_CPUCORES_PSTAT_GETDYNAMIC)\n\tstruct pst_dynamic pst;\n\tif (pstat_getdynamic(&pst, sizeof(pst), 1, 0) != -1)\n\t\tret = (uint32_t)pst.psd_proc_cnt;\n#endif\n\n\treturn ret;\n}\n"
  },
  {
    "path": "external/xz/common/tuklib_cpucores.h",
    "content": "///////////////////////////////////////////////////////////////////////////////\n//\n/// \\file       tuklib_cpucores.h\n/// \\brief      Get the number of CPU cores online\n//\n//  Author:     Lasse Collin\n//\n//  This file has been put into the public domain.\n//  You can do whatever you want with this file.\n//\n///////////////////////////////////////////////////////////////////////////////\n\n#ifndef TUKLIB_CPUCORES_H\n#define TUKLIB_CPUCORES_H\n\n#include \"tuklib_common.h\"\nTUKLIB_DECLS_BEGIN\n\n#define tuklib_cpucores TUKLIB_SYMBOL(tuklib_cpucores)\nextern uint32_t tuklib_cpucores(void);\n\nTUKLIB_DECLS_END\n#endif\n"
  },
  {
    "path": "external/xz/common/tuklib_exit.c",
    "content": "///////////////////////////////////////////////////////////////////////////////\n//\n/// \\file       tuklib_exit.c\n/// \\brief      Close stdout and stderr, and exit\n//\n//  Author:     Lasse Collin\n//\n//  This file has been put into the public domain.\n//  You can do whatever you want with this file.\n//\n///////////////////////////////////////////////////////////////////////////////\n\n#include \"tuklib_common.h\"\n\n#include <stdlib.h>\n#include <stdio.h>\n#include <string.h>\n\n#include \"tuklib_gettext.h\"\n#include \"tuklib_progname.h\"\n#include \"tuklib_exit.h\"\n\n\nextern void\ntuklib_exit(int status, int err_status, int show_error)\n{\n\tif (status != err_status) {\n\t\t// Close stdout. If something goes wrong,\n\t\t// print an error message to stderr.\n\t\tconst int ferror_err = ferror(stdout);\n\t\tconst int fclose_err = fclose(stdout);\n\t\tif (ferror_err || fclose_err) {\n\t\t\tstatus = err_status;\n\n\t\t\t// If it was fclose() that failed, we have the reason\n\t\t\t// in errno. If only ferror() indicated an error,\n\t\t\t// we have no idea what the reason was.\n\t\t\tif (show_error)\n\t\t\t\tfprintf(stderr, \"%s: %s: %s\\n\", progname,\n\t\t\t\t\t\t_(\"Writing to standard \"\n\t\t\t\t\t\t\t\"output failed\"),\n\t\t\t\t\t\tfclose_err ? strerror(errno)\n\t\t\t\t\t\t\t: _(\"Unknown error\"));\n\t\t}\n\t}\n\n\tif (status != err_status) {\n\t\t// Close stderr. If something goes wrong, there's\n\t\t// nothing where we could print an error message.\n\t\t// Just set the exit status.\n\t\tconst int ferror_err = ferror(stderr);\n\t\tconst int fclose_err = fclose(stderr);\n\t\tif (fclose_err || ferror_err)\n\t\t\tstatus = err_status;\n\t}\n\n\texit(status);\n}\n"
  },
  {
    "path": "external/xz/common/tuklib_exit.h",
    "content": "///////////////////////////////////////////////////////////////////////////////\n//\n/// \\file       tuklib_exit.h\n/// \\brief      Close stdout and stderr, and exit\n/// \\note       Requires tuklib_progname and tuklib_gettext modules\n//\n//  Author:     Lasse Collin\n//\n//  This file has been put into the public domain.\n//  You can do whatever you want with this file.\n//\n///////////////////////////////////////////////////////////////////////////////\n\n#ifndef TUKLIB_EXIT_H\n#define TUKLIB_EXIT_H\n\n#include \"tuklib_common.h\"\nTUKLIB_DECLS_BEGIN\n\n#define tuklib_exit TUKLIB_SYMBOL(tuklib_exit)\nextern void tuklib_exit(int status, int err_status, int show_error)\n\t\ttuklib_attr_noreturn;\n\nTUKLIB_DECLS_END\n#endif\n"
  },
  {
    "path": "external/xz/common/tuklib_gettext.h",
    "content": "///////////////////////////////////////////////////////////////////////////////\n//\n/// \\file       tuklib_gettext.h\n/// \\brief      Wrapper for gettext and friends\n//\n//  Author:     Lasse Collin\n//\n//  This file has been put into the public domain.\n//  You can do whatever you want with this file.\n//\n///////////////////////////////////////////////////////////////////////////////\n\n#ifndef TUKLIB_GETTEXT_H\n#define TUKLIB_GETTEXT_H\n\n#include \"tuklib_common.h\"\n#include <locale.h>\n\n#ifndef TUKLIB_GETTEXT\n#\tifdef ENABLE_NLS\n#\t\tdefine TUKLIB_GETTEXT 1\n#\telse\n#\t\tdefine TUKLIB_GETTEXT 0\n#\tendif\n#endif\n\n#if TUKLIB_GETTEXT\n#\tinclude <libintl.h>\n#\tdefine tuklib_gettext_init(package, localedir) \\\n\t\tdo { \\\n\t\t\tsetlocale(LC_ALL, \"\"); \\\n\t\t\tbindtextdomain(package, localedir); \\\n\t\t\ttextdomain(package); \\\n\t\t} while (0)\n#\tdefine _(msgid) gettext(msgid)\n#else\n#\tdefine tuklib_gettext_init(package, localedir) \\\n\t\tsetlocale(LC_ALL, \"\")\n#\tdefine _(msgid) (msgid)\n#\tdefine ngettext(msgid1, msgid2, n) ((n) == 1 ? (msgid1) : (msgid2))\n#endif\n#define N_(msgid) msgid\n\n#endif\n"
  },
  {
    "path": "external/xz/common/tuklib_integer.h",
    "content": "///////////////////////////////////////////////////////////////////////////////\n//\n/// \\file       tuklib_integer.h\n/// \\brief      Various integer and bit operations\n///\n/// This file provides macros or functions to do some basic integer and bit\n/// operations.\n///\n/// Native endian inline functions (XX = 16, 32, or 64):\n///   - Unaligned native endian reads: readXXne(ptr)\n///   - Unaligned native endian writes: writeXXne(ptr, num)\n///   - Aligned native endian reads: aligned_readXXne(ptr)\n///   - Aligned native endian writes: aligned_writeXXne(ptr, num)\n///\n/// Endianness-converting integer operations (these can be macros!)\n/// (XX = 16, 32, or 64; Y = b or l):\n///   - Byte swapping: bswapXX(num)\n///   - Byte order conversions to/from native (byteswaps if Y isn't\n///     the native endianness): convXXYe(num)\n///   - Unaligned reads (16/32-bit only): readXXYe(ptr)\n///   - Unaligned writes (16/32-bit only): writeXXYe(ptr, num)\n///   - Aligned reads: aligned_readXXYe(ptr)\n///   - Aligned writes: aligned_writeXXYe(ptr, num)\n///\n/// Since the above can macros, the arguments should have no side effects\n/// because they may be evaluated more than once.\n///\n/// Bit scan operations for non-zero 32-bit integers (inline functions):\n///   - Bit scan reverse (find highest non-zero bit): bsr32(num)\n///   - Count leading zeros: clz32(num)\n///   - Count trailing zeros: ctz32(num)\n///   - Bit scan forward (simply an alias for ctz32()): bsf32(num)\n///\n/// The above bit scan operations return 0-31. If num is zero,\n/// the result is undefined.\n//\n//  Authors:    Lasse Collin\n//              Joachim Henke\n//\n//  This file has been put into the public domain.\n//  You can do whatever you want with this file.\n//\n///////////////////////////////////////////////////////////////////////////////\n\n#ifndef TUKLIB_INTEGER_H\n#define TUKLIB_INTEGER_H\n\n#include \"tuklib_common.h\"\n#include <string.h>\n\n// Newer Intel C compilers require immintrin.h for _bit_scan_reverse()\n// and such functions.\n#if defined(__INTEL_COMPILER) && (__INTEL_COMPILER >= 1500)\n#\tinclude <immintrin.h>\n#endif\n\n\n///////////////////\n// Byte swapping //\n///////////////////\n\n#if defined(HAVE___BUILTIN_BSWAPXX)\n\t// GCC >= 4.8 and Clang\n#\tdefine bswap16(n) __builtin_bswap16(n)\n#\tdefine bswap32(n) __builtin_bswap32(n)\n#\tdefine bswap64(n) __builtin_bswap64(n)\n\n#elif defined(HAVE_BYTESWAP_H)\n\t// glibc, uClibc, dietlibc\n#\tinclude <byteswap.h>\n#\tifdef HAVE_BSWAP_16\n#\t\tdefine bswap16(num) bswap_16(num)\n#\tendif\n#\tifdef HAVE_BSWAP_32\n#\t\tdefine bswap32(num) bswap_32(num)\n#\tendif\n#\tifdef HAVE_BSWAP_64\n#\t\tdefine bswap64(num) bswap_64(num)\n#\tendif\n\n#elif defined(HAVE_SYS_ENDIAN_H)\n\t// *BSDs and Darwin\n#\tinclude <sys/endian.h>\n\n#elif defined(HAVE_SYS_BYTEORDER_H)\n\t// Solaris\n#\tinclude <sys/byteorder.h>\n#\tifdef BSWAP_16\n#\t\tdefine bswap16(num) BSWAP_16(num)\n#\tendif\n#\tifdef BSWAP_32\n#\t\tdefine bswap32(num) BSWAP_32(num)\n#\tendif\n#\tifdef BSWAP_64\n#\t\tdefine bswap64(num) BSWAP_64(num)\n#\tendif\n#\tifdef BE_16\n#\t\tdefine conv16be(num) BE_16(num)\n#\tendif\n#\tifdef BE_32\n#\t\tdefine conv32be(num) BE_32(num)\n#\tendif\n#\tifdef BE_64\n#\t\tdefine conv64be(num) BE_64(num)\n#\tendif\n#\tifdef LE_16\n#\t\tdefine conv16le(num) LE_16(num)\n#\tendif\n#\tifdef LE_32\n#\t\tdefine conv32le(num) LE_32(num)\n#\tendif\n#\tifdef LE_64\n#\t\tdefine conv64le(num) LE_64(num)\n#\tendif\n#endif\n\n#ifndef bswap16\n#\tdefine bswap16(n) (uint16_t)( \\\n\t\t  (((n) & 0x00FFU) << 8) \\\n\t\t| (((n) & 0xFF00U) >> 8) \\\n\t)\n#endif\n\n#ifndef bswap32\n#\tdefine bswap32(n) (uint32_t)( \\\n\t\t  (((n) & UINT32_C(0x000000FF)) << 24) \\\n\t\t| (((n) & UINT32_C(0x0000FF00)) << 8) \\\n\t\t| (((n) & UINT32_C(0x00FF0000)) >> 8) \\\n\t\t| (((n) & UINT32_C(0xFF000000)) >> 24) \\\n\t)\n#endif\n\n#ifndef bswap64\n#\tdefine bswap64(n) (uint64_t)( \\\n\t\t  (((n) & UINT64_C(0x00000000000000FF)) << 56) \\\n\t\t| (((n) & UINT64_C(0x000000000000FF00)) << 40) \\\n\t\t| (((n) & UINT64_C(0x0000000000FF0000)) << 24) \\\n\t\t| (((n) & UINT64_C(0x00000000FF000000)) << 8) \\\n\t\t| (((n) & UINT64_C(0x000000FF00000000)) >> 8) \\\n\t\t| (((n) & UINT64_C(0x0000FF0000000000)) >> 24) \\\n\t\t| (((n) & UINT64_C(0x00FF000000000000)) >> 40) \\\n\t\t| (((n) & UINT64_C(0xFF00000000000000)) >> 56) \\\n\t)\n#endif\n\n// Define conversion macros using the basic byte swapping macros.\n#ifdef WORDS_BIGENDIAN\n#\tifndef conv16be\n#\t\tdefine conv16be(num) ((uint16_t)(num))\n#\tendif\n#\tifndef conv32be\n#\t\tdefine conv32be(num) ((uint32_t)(num))\n#\tendif\n#\tifndef conv64be\n#\t\tdefine conv64be(num) ((uint64_t)(num))\n#\tendif\n#\tifndef conv16le\n#\t\tdefine conv16le(num) bswap16(num)\n#\tendif\n#\tifndef conv32le\n#\t\tdefine conv32le(num) bswap32(num)\n#\tendif\n#\tifndef conv64le\n#\t\tdefine conv64le(num) bswap64(num)\n#\tendif\n#else\n#\tifndef conv16be\n#\t\tdefine conv16be(num) bswap16(num)\n#\tendif\n#\tifndef conv32be\n#\t\tdefine conv32be(num) bswap32(num)\n#\tendif\n#\tifndef conv64be\n#\t\tdefine conv64be(num) bswap64(num)\n#\tendif\n#\tifndef conv16le\n#\t\tdefine conv16le(num) ((uint16_t)(num))\n#\tendif\n#\tifndef conv32le\n#\t\tdefine conv32le(num) ((uint32_t)(num))\n#\tendif\n#\tifndef conv64le\n#\t\tdefine conv64le(num) ((uint64_t)(num))\n#\tendif\n#endif\n\n\n////////////////////////////////\n// Unaligned reads and writes //\n////////////////////////////////\n\n// The traditional way of casting e.g. *(const uint16_t *)uint8_pointer\n// is bad even if the uint8_pointer is properly aligned because this kind\n// of casts break strict aliasing rules and result in undefined behavior.\n// With unaligned pointers it's even worse: compilers may emit vector\n// instructions that require aligned pointers even if non-vector\n// instructions work with unaligned pointers.\n//\n// Using memcpy() is the standard compliant way to do unaligned access.\n// Many modern compilers inline it so there is no function call overhead.\n// For those compilers that don't handle the memcpy() method well, the\n// old casting method (that violates strict aliasing) can be requested at\n// build time. A third method, casting to a packed struct, would also be\n// an option but isn't provided to keep things simpler (it's already a mess).\n// Hopefully this is flexible enough in practice.\n\nstatic inline uint16_t\nread16ne(const uint8_t *buf)\n{\n#if defined(TUKLIB_FAST_UNALIGNED_ACCESS) \\\n\t\t&& defined(TUKLIB_USE_UNSAFE_TYPE_PUNNING)\n\treturn *(const uint16_t *)buf;\n#else\n\tuint16_t num;\n\tmemcpy(&num, buf, sizeof(num));\n\treturn num;\n#endif\n}\n\n\nstatic inline uint32_t\nread32ne(const uint8_t *buf)\n{\n#if defined(TUKLIB_FAST_UNALIGNED_ACCESS) \\\n\t\t&& defined(TUKLIB_USE_UNSAFE_TYPE_PUNNING)\n\treturn *(const uint32_t *)buf;\n#else\n\tuint32_t num;\n\tmemcpy(&num, buf, sizeof(num));\n\treturn num;\n#endif\n}\n\n\nstatic inline uint64_t\nread64ne(const uint8_t *buf)\n{\n#if defined(TUKLIB_FAST_UNALIGNED_ACCESS) \\\n\t\t&& defined(TUKLIB_USE_UNSAFE_TYPE_PUNNING)\n\treturn *(const uint64_t *)buf;\n#else\n\tuint64_t num;\n\tmemcpy(&num, buf, sizeof(num));\n\treturn num;\n#endif\n}\n\n\nstatic inline void\nwrite16ne(uint8_t *buf, uint16_t num)\n{\n#if defined(TUKLIB_FAST_UNALIGNED_ACCESS) \\\n\t\t&& defined(TUKLIB_USE_UNSAFE_TYPE_PUNNING)\n\t*(uint16_t *)buf = num;\n#else\n\tmemcpy(buf, &num, sizeof(num));\n#endif\n\treturn;\n}\n\n\nstatic inline void\nwrite32ne(uint8_t *buf, uint32_t num)\n{\n#if defined(TUKLIB_FAST_UNALIGNED_ACCESS) \\\n\t\t&& defined(TUKLIB_USE_UNSAFE_TYPE_PUNNING)\n\t*(uint32_t *)buf = num;\n#else\n\tmemcpy(buf, &num, sizeof(num));\n#endif\n\treturn;\n}\n\n\nstatic inline void\nwrite64ne(uint8_t *buf, uint64_t num)\n{\n#if defined(TUKLIB_FAST_UNALIGNED_ACCESS) \\\n\t\t&& defined(TUKLIB_USE_UNSAFE_TYPE_PUNNING)\n\t*(uint64_t *)buf = num;\n#else\n\tmemcpy(buf, &num, sizeof(num));\n#endif\n\treturn;\n}\n\n\nstatic inline uint16_t\nread16be(const uint8_t *buf)\n{\n#if defined(WORDS_BIGENDIAN) || defined(TUKLIB_FAST_UNALIGNED_ACCESS)\n\tuint16_t num = read16ne(buf);\n\treturn conv16be(num);\n#else\n\tuint16_t num = ((uint16_t)buf[0] << 8) | (uint16_t)buf[1];\n\treturn num;\n#endif\n}\n\n\nstatic inline uint16_t\nread16le(const uint8_t *buf)\n{\n#if !defined(WORDS_BIGENDIAN) || defined(TUKLIB_FAST_UNALIGNED_ACCESS)\n\tuint16_t num = read16ne(buf);\n\treturn conv16le(num);\n#else\n\tuint16_t num = ((uint16_t)buf[0]) | ((uint16_t)buf[1] << 8);\n\treturn num;\n#endif\n}\n\n\nstatic inline uint32_t\nread32be(const uint8_t *buf)\n{\n#if defined(WORDS_BIGENDIAN) || defined(TUKLIB_FAST_UNALIGNED_ACCESS)\n\tuint32_t num = read32ne(buf);\n\treturn conv32be(num);\n#else\n\tuint32_t num = (uint32_t)buf[0] << 24;\n\tnum |= (uint32_t)buf[1] << 16;\n\tnum |= (uint32_t)buf[2] << 8;\n\tnum |= (uint32_t)buf[3];\n\treturn num;\n#endif\n}\n\n\nstatic inline uint32_t\nread32le(const uint8_t *buf)\n{\n#if !defined(WORDS_BIGENDIAN) || defined(TUKLIB_FAST_UNALIGNED_ACCESS)\n\tuint32_t num = read32ne(buf);\n\treturn conv32le(num);\n#else\n\tuint32_t num = (uint32_t)buf[0];\n\tnum |= (uint32_t)buf[1] << 8;\n\tnum |= (uint32_t)buf[2] << 16;\n\tnum |= (uint32_t)buf[3] << 24;\n\treturn num;\n#endif\n}\n\n\n// NOTE: Possible byte swapping must be done in a macro to allow the compiler\n// to optimize byte swapping of constants when using glibc's or *BSD's\n// byte swapping macros. The actual write is done in an inline function\n// to make type checking of the buf pointer possible.\n#if defined(WORDS_BIGENDIAN) || defined(TUKLIB_FAST_UNALIGNED_ACCESS)\n#\tdefine write16be(buf, num) write16ne(buf, conv16be(num))\n#\tdefine write32be(buf, num) write32ne(buf, conv32be(num))\n#endif\n\n#if !defined(WORDS_BIGENDIAN) || defined(TUKLIB_FAST_UNALIGNED_ACCESS)\n#\tdefine write16le(buf, num) write16ne(buf, conv16le(num))\n#\tdefine write32le(buf, num) write32ne(buf, conv32le(num))\n#endif\n\n\n#ifndef write16be\nstatic inline void\nwrite16be(uint8_t *buf, uint16_t num)\n{\n\tbuf[0] = (uint8_t)(num >> 8);\n\tbuf[1] = (uint8_t)num;\n\treturn;\n}\n#endif\n\n\n#ifndef write16le\nstatic inline void\nwrite16le(uint8_t *buf, uint16_t num)\n{\n\tbuf[0] = (uint8_t)num;\n\tbuf[1] = (uint8_t)(num >> 8);\n\treturn;\n}\n#endif\n\n\n#ifndef write32be\nstatic inline void\nwrite32be(uint8_t *buf, uint32_t num)\n{\n\tbuf[0] = (uint8_t)(num >> 24);\n\tbuf[1] = (uint8_t)(num >> 16);\n\tbuf[2] = (uint8_t)(num >> 8);\n\tbuf[3] = (uint8_t)num;\n\treturn;\n}\n#endif\n\n\n#ifndef write32le\nstatic inline void\nwrite32le(uint8_t *buf, uint32_t num)\n{\n\tbuf[0] = (uint8_t)num;\n\tbuf[1] = (uint8_t)(num >> 8);\n\tbuf[2] = (uint8_t)(num >> 16);\n\tbuf[3] = (uint8_t)(num >> 24);\n\treturn;\n}\n#endif\n\n\n//////////////////////////////\n// Aligned reads and writes //\n//////////////////////////////\n\n// Separate functions for aligned reads and writes are provided since on\n// strict-align archs aligned access is much faster than unaligned access.\n//\n// Just like in the unaligned case, memcpy() is needed to avoid\n// strict aliasing violations. However, on archs that don't support\n// unaligned access the compiler cannot know that the pointers given\n// to memcpy() are aligned which results in slow code. As of C11 there is\n// no standard way to tell the compiler that we know that the address is\n// aligned but some compilers have language extensions to do that. With\n// such language extensions the memcpy() method gives excellent results.\n//\n// What to do on a strict-align system when no known language extentensions\n// are available? Falling back to byte-by-byte access would be safe but ruin\n// optimizations that have been made specifically with aligned access in mind.\n// As a compromise, aligned reads will fall back to non-compliant type punning\n// but aligned writes will be byte-by-byte, that is, fast reads are preferred\n// over fast writes. This obviously isn't great but hopefully it's a working\n// compromise for now.\n//\n// __builtin_assume_aligned is support by GCC >= 4.7 and clang >= 3.6.\n#ifdef HAVE___BUILTIN_ASSUME_ALIGNED\n#\tdefine tuklib_memcpy_aligned(dest, src, size) \\\n\t\tmemcpy(dest, __builtin_assume_aligned(src, size), size)\n#else\n#\tdefine tuklib_memcpy_aligned(dest, src, size) \\\n\t\tmemcpy(dest, src, size)\n#\tifndef TUKLIB_FAST_UNALIGNED_ACCESS\n#\t\tdefine TUKLIB_USE_UNSAFE_ALIGNED_READS 1\n#\tendif\n#endif\n\n\nstatic inline uint16_t\naligned_read16ne(const uint8_t *buf)\n{\n#if defined(TUKLIB_USE_UNSAFE_TYPE_PUNNING) \\\n\t\t|| defined(TUKLIB_USE_UNSAFE_ALIGNED_READS)\n\treturn *(const uint16_t *)buf;\n#else\n\tuint16_t num;\n\ttuklib_memcpy_aligned(&num, buf, sizeof(num));\n\treturn num;\n#endif\n}\n\n\nstatic inline uint32_t\naligned_read32ne(const uint8_t *buf)\n{\n#if defined(TUKLIB_USE_UNSAFE_TYPE_PUNNING) \\\n\t\t|| defined(TUKLIB_USE_UNSAFE_ALIGNED_READS)\n\treturn *(const uint32_t *)buf;\n#else\n\tuint32_t num;\n\ttuklib_memcpy_aligned(&num, buf, sizeof(num));\n\treturn num;\n#endif\n}\n\n\nstatic inline uint64_t\naligned_read64ne(const uint8_t *buf)\n{\n#if defined(TUKLIB_USE_UNSAFE_TYPE_PUNNING) \\\n\t\t|| defined(TUKLIB_USE_UNSAFE_ALIGNED_READS)\n\treturn *(const uint64_t *)buf;\n#else\n\tuint64_t num;\n\ttuklib_memcpy_aligned(&num, buf, sizeof(num));\n\treturn num;\n#endif\n}\n\n\nstatic inline void\naligned_write16ne(uint8_t *buf, uint16_t num)\n{\n#ifdef TUKLIB_USE_UNSAFE_TYPE_PUNNING\n\t*(uint16_t *)buf = num;\n#else\n\ttuklib_memcpy_aligned(buf, &num, sizeof(num));\n#endif\n\treturn;\n}\n\n\nstatic inline void\naligned_write32ne(uint8_t *buf, uint32_t num)\n{\n#ifdef TUKLIB_USE_UNSAFE_TYPE_PUNNING\n\t*(uint32_t *)buf = num;\n#else\n\ttuklib_memcpy_aligned(buf, &num, sizeof(num));\n#endif\n\treturn;\n}\n\n\nstatic inline void\naligned_write64ne(uint8_t *buf, uint64_t num)\n{\n#ifdef TUKLIB_USE_UNSAFE_TYPE_PUNNING\n\t*(uint64_t *)buf = num;\n#else\n\ttuklib_memcpy_aligned(buf, &num, sizeof(num));\n#endif\n\treturn;\n}\n\n\nstatic inline uint16_t\naligned_read16be(const uint8_t *buf)\n{\n\tuint16_t num = aligned_read16ne(buf);\n\treturn conv16be(num);\n}\n\n\nstatic inline uint16_t\naligned_read16le(const uint8_t *buf)\n{\n\tuint16_t num = aligned_read16ne(buf);\n\treturn conv16le(num);\n}\n\n\nstatic inline uint32_t\naligned_read32be(const uint8_t *buf)\n{\n\tuint32_t num = aligned_read32ne(buf);\n\treturn conv32be(num);\n}\n\n\nstatic inline uint32_t\naligned_read32le(const uint8_t *buf)\n{\n\tuint32_t num = aligned_read32ne(buf);\n\treturn conv32le(num);\n}\n\n\nstatic inline uint64_t\naligned_read64be(const uint8_t *buf)\n{\n\tuint64_t num = aligned_read64ne(buf);\n\treturn conv64be(num);\n}\n\n\nstatic inline uint64_t\naligned_read64le(const uint8_t *buf)\n{\n\tuint64_t num = aligned_read64ne(buf);\n\treturn conv64le(num);\n}\n\n\n// These need to be macros like in the unaligned case.\n#define aligned_write16be(buf, num) aligned_write16ne((buf), conv16be(num))\n#define aligned_write16le(buf, num) aligned_write16ne((buf), conv16le(num))\n#define aligned_write32be(buf, num) aligned_write32ne((buf), conv32be(num))\n#define aligned_write32le(buf, num) aligned_write32ne((buf), conv32le(num))\n#define aligned_write64be(buf, num) aligned_write64ne((buf), conv64be(num))\n#define aligned_write64le(buf, num) aligned_write64ne((buf), conv64le(num))\n\n\n////////////////////\n// Bit operations //\n////////////////////\n\nstatic inline uint32_t\nbsr32(uint32_t n)\n{\n\t// Check for ICC first, since it tends to define __GNUC__ too.\n#if defined(__INTEL_COMPILER)\n\treturn _bit_scan_reverse(n);\n\n#elif TUKLIB_GNUC_REQ(3, 4) && UINT_MAX == UINT32_MAX\n\t// GCC >= 3.4 has __builtin_clz(), which gives good results on\n\t// multiple architectures. On x86, __builtin_clz() ^ 31U becomes\n\t// either plain BSR (so the XOR gets optimized away) or LZCNT and\n\t// XOR (if -march indicates that SSE4a instructions are supported).\n\treturn (uint32_t)__builtin_clz(n) ^ 31U;\n\n#elif defined(__GNUC__) && (defined(__i386__) || defined(__x86_64__))\n\tuint32_t i;\n\t__asm__(\"bsrl %1, %0\" : \"=r\" (i) : \"rm\" (n));\n\treturn i;\n\n#elif defined(_MSC_VER)\n\tunsigned long i;\n\t_BitScanReverse(&i, n);\n\treturn i;\n\n#else\n\tuint32_t i = 31;\n\n\tif ((n & 0xFFFF0000) == 0) {\n\t\tn <<= 16;\n\t\ti = 15;\n\t}\n\n\tif ((n & 0xFF000000) == 0) {\n\t\tn <<= 8;\n\t\ti -= 8;\n\t}\n\n\tif ((n & 0xF0000000) == 0) {\n\t\tn <<= 4;\n\t\ti -= 4;\n\t}\n\n\tif ((n & 0xC0000000) == 0) {\n\t\tn <<= 2;\n\t\ti -= 2;\n\t}\n\n\tif ((n & 0x80000000) == 0)\n\t\t--i;\n\n\treturn i;\n#endif\n}\n\n\nstatic inline uint32_t\nclz32(uint32_t n)\n{\n#if defined(__INTEL_COMPILER)\n\treturn _bit_scan_reverse(n) ^ 31U;\n\n#elif TUKLIB_GNUC_REQ(3, 4) && UINT_MAX == UINT32_MAX\n\treturn (uint32_t)__builtin_clz(n);\n\n#elif defined(__GNUC__) && (defined(__i386__) || defined(__x86_64__))\n\tuint32_t i;\n\t__asm__(\"bsrl %1, %0\\n\\t\"\n\t\t\"xorl $31, %0\"\n\t\t: \"=r\" (i) : \"rm\" (n));\n\treturn i;\n\n#elif defined(_MSC_VER)\n\tunsigned long i;\n\t_BitScanReverse(&i, n);\n\treturn i ^ 31U;\n\n#else\n\tuint32_t i = 0;\n\n\tif ((n & 0xFFFF0000) == 0) {\n\t\tn <<= 16;\n\t\ti = 16;\n\t}\n\n\tif ((n & 0xFF000000) == 0) {\n\t\tn <<= 8;\n\t\ti += 8;\n\t}\n\n\tif ((n & 0xF0000000) == 0) {\n\t\tn <<= 4;\n\t\ti += 4;\n\t}\n\n\tif ((n & 0xC0000000) == 0) {\n\t\tn <<= 2;\n\t\ti += 2;\n\t}\n\n\tif ((n & 0x80000000) == 0)\n\t\t++i;\n\n\treturn i;\n#endif\n}\n\n\nstatic inline uint32_t\nctz32(uint32_t n)\n{\n#if defined(__INTEL_COMPILER)\n\treturn _bit_scan_forward(n);\n\n#elif TUKLIB_GNUC_REQ(3, 4) && UINT_MAX >= UINT32_MAX\n\treturn (uint32_t)__builtin_ctz(n);\n\n#elif defined(__GNUC__) && (defined(__i386__) || defined(__x86_64__))\n\tuint32_t i;\n\t__asm__(\"bsfl %1, %0\" : \"=r\" (i) : \"rm\" (n));\n\treturn i;\n\n#elif defined(_MSC_VER)\n\tunsigned long i;\n\t_BitScanForward(&i, n);\n\treturn i;\n\n#else\n\tuint32_t i = 0;\n\n\tif ((n & 0x0000FFFF) == 0) {\n\t\tn >>= 16;\n\t\ti = 16;\n\t}\n\n\tif ((n & 0x000000FF) == 0) {\n\t\tn >>= 8;\n\t\ti += 8;\n\t}\n\n\tif ((n & 0x0000000F) == 0) {\n\t\tn >>= 4;\n\t\ti += 4;\n\t}\n\n\tif ((n & 0x00000003) == 0) {\n\t\tn >>= 2;\n\t\ti += 2;\n\t}\n\n\tif ((n & 0x00000001) == 0)\n\t\t++i;\n\n\treturn i;\n#endif\n}\n\n#define bsf32 ctz32\n\n#endif\n"
  },
  {
    "path": "external/xz/common/tuklib_mbstr.h",
    "content": "///////////////////////////////////////////////////////////////////////////////\n//\n/// \\file       tuklib_mbstr.h\n/// \\brief      Utility functions for handling multibyte strings\n///\n/// If not enough multibyte string support is available in the C library,\n/// these functions keep working with the assumption that all strings\n/// are in a single-byte character set without combining characters, e.g.\n/// US-ASCII or ISO-8859-*.\n//\n//  Author:     Lasse Collin\n//\n//  This file has been put into the public domain.\n//  You can do whatever you want with this file.\n//\n///////////////////////////////////////////////////////////////////////////////\n\n#ifndef TUKLIB_MBSTR_H\n#define TUKLIB_MBSTR_H\n\n#include \"tuklib_common.h\"\nTUKLIB_DECLS_BEGIN\n\n#define tuklib_mbstr_width TUKLIB_SYMBOL(tuklib_mbstr_width)\nextern size_t tuklib_mbstr_width(const char *str, size_t *bytes);\n///<\n/// \\brief      Get the number of columns needed for the multibyte string\n///\n/// This is somewhat similar to wcswidth() but works on multibyte strings.\n///\n/// \\param      str         String whose width is to be calculated. If the\n///                         current locale uses a multibyte character set\n///                         that has shift states, the string must begin\n///                         and end in the initial shift state.\n/// \\param      bytes       If this is not NULL, *bytes is set to the\n///                         value returned by strlen(str) (even if an\n///                         error occurs when calculating the width).\n///\n/// \\return     On success, the number of columns needed to display the\n///             string e.g. in a terminal emulator is returned. On error,\n///             (size_t)-1 is returned. Possible errors include invalid,\n///             partial, or non-printable multibyte character in str, or\n///             that str doesn't end in the initial shift state.\n\n#define tuklib_mbstr_fw TUKLIB_SYMBOL(tuklib_mbstr_fw)\nextern int tuklib_mbstr_fw(const char *str, int columns_min);\n///<\n/// \\brief      Get the field width for printf() e.g. to align table columns\n///\n/// Printing simple tables to a terminal can be done using the field field\n/// feature in the printf() format string, but it works only with single-byte\n/// character sets. To do the same with multibyte strings, tuklib_mbstr_fw()\n/// can be used to calculate appropriate field width.\n///\n/// The behavior of this function is undefined, if\n///   - str is NULL or not terminated with '\\0';\n///   - columns_min <= 0; or\n///   - the calculated field width exceeds INT_MAX.\n///\n/// \\return     If tuklib_mbstr_width(str, NULL) fails, -1 is returned.\n///             If str needs more columns than columns_min, zero is returned.\n///             Otherwise a positive integer is returned, which can be\n///             used as the field width, e.g. printf(\"%*s\", fw, str).\n\nTUKLIB_DECLS_END\n#endif\n"
  },
  {
    "path": "external/xz/common/tuklib_mbstr_fw.c",
    "content": "///////////////////////////////////////////////////////////////////////////////\n//\n/// \\file       tuklib_mbstr_fw.c\n/// \\brief      Get the field width for printf() e.g. to align table columns\n//\n//  Author:     Lasse Collin\n//\n//  This file has been put into the public domain.\n//  You can do whatever you want with this file.\n//\n///////////////////////////////////////////////////////////////////////////////\n\n#include \"tuklib_mbstr.h\"\n\n\nextern int\ntuklib_mbstr_fw(const char *str, int columns_min)\n{\n\tsize_t len;\n\tconst size_t width = tuklib_mbstr_width(str, &len);\n\tif (width == (size_t)-1)\n\t\treturn -1;\n\n\tif (width > (size_t)columns_min)\n\t\treturn 0;\n\n\tif (width < (size_t)columns_min)\n\t\tlen += (size_t)columns_min - width;\n\n\treturn len;\n}\n"
  },
  {
    "path": "external/xz/common/tuklib_mbstr_width.c",
    "content": "///////////////////////////////////////////////////////////////////////////////\n//\n/// \\file       tuklib_mbstr_width.c\n/// \\brief      Calculate width of a multibyte string\n//\n//  Author:     Lasse Collin\n//\n//  This file has been put into the public domain.\n//  You can do whatever you want with this file.\n//\n///////////////////////////////////////////////////////////////////////////////\n\n#include \"tuklib_mbstr.h\"\n#include <string.h>\n\n#if defined(HAVE_MBRTOWC) && defined(HAVE_WCWIDTH)\n#\tinclude <wchar.h>\n#endif\n\n\nextern size_t\ntuklib_mbstr_width(const char *str, size_t *bytes)\n{\n\tconst size_t len = strlen(str);\n\tif (bytes != NULL)\n\t\t*bytes = len;\n\n#if !(defined(HAVE_MBRTOWC) && defined(HAVE_WCWIDTH))\n\t// In single-byte mode, the width of the string is the same\n\t// as its length.\n\treturn len;\n\n#else\n\tmbstate_t state;\n\tmemset(&state, 0, sizeof(state));\n\n\tsize_t width = 0;\n\tsize_t i = 0;\n\n\t// Convert one multibyte character at a time to wchar_t\n\t// and get its width using wcwidth().\n\twhile (i < len) {\n\t\twchar_t wc;\n\t\tconst size_t ret = mbrtowc(&wc, str + i, len - i, &state);\n\t\tif (ret < 1 || ret > len)\n\t\t\treturn (size_t)-1;\n\n\t\ti += ret;\n\n\t\tconst int wc_width = wcwidth(wc);\n\t\tif (wc_width < 0)\n\t\t\treturn (size_t)-1;\n\n\t\twidth += (size_t)wc_width;\n\t}\n\n\t// Require that the string ends in the initial shift state.\n\t// This way the caller can be combine the string with other\n\t// strings without needing to worry about the shift states.\n\tif (!mbsinit(&state))\n\t\treturn (size_t)-1;\n\n\treturn width;\n#endif\n}\n"
  },
  {
    "path": "external/xz/common/tuklib_open_stdxxx.c",
    "content": "///////////////////////////////////////////////////////////////////////////////\n//\n/// \\file       tuklib_open_stdxxx.c\n/// \\brief      Make sure that file descriptors 0, 1, and 2 are open\n//\n//  Author:     Lasse Collin\n//\n//  This file has been put into the public domain.\n//  You can do whatever you want with this file.\n//\n///////////////////////////////////////////////////////////////////////////////\n\n#include \"tuklib_open_stdxxx.h\"\n\n#ifndef TUKLIB_DOSLIKE\n#\tinclude <stdlib.h>\n#\tinclude <errno.h>\n#\tinclude <fcntl.h>\n#\tinclude <unistd.h>\n#endif\n\n\nextern void\ntuklib_open_stdxxx(int err_status)\n{\n#ifdef TUKLIB_DOSLIKE\n\t// Do nothing, just silence warnings.\n\t(void)err_status;\n\n#else\n\tfor (int i = 0; i <= 2; ++i) {\n\t\t// We use fcntl() to check if the file descriptor is open.\n\t\tif (fcntl(i, F_GETFD) == -1 && errno == EBADF) {\n\t\t\t// With stdin, we could use /dev/full so that\n\t\t\t// writing to stdin would fail. However, /dev/full\n\t\t\t// is Linux specific, and if the program tries to\n\t\t\t// write to stdin, there's already a problem anyway.\n\t\t\tconst int fd = open(\"/dev/null\", O_NOCTTY\n\t\t\t\t\t| (i == 0 ? O_WRONLY : O_RDONLY));\n\n\t\t\tif (fd != i) {\n\t\t\t\tif (fd != -1)\n\t\t\t\t\t(void)close(fd);\n\n\t\t\t\t// Something went wrong. Exit with the\n\t\t\t\t// exit status we were given. Don't try\n\t\t\t\t// to print an error message, since stderr\n\t\t\t\t// may very well be non-existent. This\n\t\t\t\t// error should be extremely rare.\n\t\t\t\texit(err_status);\n\t\t\t}\n\t\t}\n\t}\n#endif\n\n\treturn;\n}\n"
  },
  {
    "path": "external/xz/common/tuklib_open_stdxxx.h",
    "content": "///////////////////////////////////////////////////////////////////////////////\n//\n/// \\file       tuklib_open_stdxxx.h\n/// \\brief      Make sure that file descriptors 0, 1, and 2 are open\n//\n//  Author:     Lasse Collin\n//\n//  This file has been put into the public domain.\n//  You can do whatever you want with this file.\n//\n///////////////////////////////////////////////////////////////////////////////\n\n#ifndef TUKLIB_OPEN_STDXXX_H\n#define TUKLIB_OPEN_STDXXX_H\n\n#include \"tuklib_common.h\"\nTUKLIB_DECLS_BEGIN\n\n#define tuklib_open_stdxx TUKLIB_SYMBOL(tuklib_open_stdxxx)\nextern void tuklib_open_stdxxx(int err_status);\n\nTUKLIB_DECLS_END\n#endif\n"
  },
  {
    "path": "external/xz/common/tuklib_physmem.c",
    "content": "///////////////////////////////////////////////////////////////////////////////\n//\n/// \\file       tuklib_physmem.c\n/// \\brief      Get the amount of physical memory\n//\n//  Author:     Lasse Collin\n//\n//  This file has been put into the public domain.\n//  You can do whatever you want with this file.\n//\n///////////////////////////////////////////////////////////////////////////////\n\n#include \"tuklib_physmem.h\"\n\n// We want to use Windows-specific code on Cygwin, which also has memory\n// information available via sysconf(), but on Cygwin 1.5 and older it\n// gives wrong results (from our point of view).\n#if defined(_WIN32) || defined(__CYGWIN__)\n#\tifndef _WIN32_WINNT\n#\t\tdefine _WIN32_WINNT 0x0500\n#\tendif\n#\tinclude <windows.h>\n\n#elif defined(__OS2__)\n#\tdefine INCL_DOSMISC\n#\tinclude <os2.h>\n\n#elif defined(__DJGPP__)\n#\tinclude <dpmi.h>\n\n#elif defined(__VMS)\n#\tinclude <lib$routines.h>\n#\tinclude <syidef.h>\n#\tinclude <ssdef.h>\n\n#elif defined(AMIGA) || defined(__AROS__)\n#\tdefine __USE_INLINE__\n#\tinclude <proto/exec.h>\n\n#elif defined(__QNX__)\n#\tinclude <sys/syspage.h>\n#\tinclude <string.h>\n\n#elif defined(TUKLIB_PHYSMEM_AIX)\n#\tinclude <sys/systemcfg.h>\n\n#elif defined(TUKLIB_PHYSMEM_SYSCONF)\n#\tinclude <unistd.h>\n\n#elif defined(TUKLIB_PHYSMEM_SYSCTL)\n#\tifdef HAVE_SYS_PARAM_H\n#\t\tinclude <sys/param.h>\n#\tendif\n#\tinclude <sys/sysctl.h>\n\n// Tru64\n#elif defined(TUKLIB_PHYSMEM_GETSYSINFO)\n#\tinclude <sys/sysinfo.h>\n#\tinclude <machine/hal_sysinfo.h>\n\n// HP-UX\n#elif defined(TUKLIB_PHYSMEM_PSTAT_GETSTATIC)\n#\tinclude <sys/param.h>\n#\tinclude <sys/pstat.h>\n\n// IRIX\n#elif defined(TUKLIB_PHYSMEM_GETINVENT_R)\n#\tinclude <invent.h>\n\n// This sysinfo() is Linux-specific.\n#elif defined(TUKLIB_PHYSMEM_SYSINFO)\n#\tinclude <sys/sysinfo.h>\n#endif\n\n\nextern uint64_t\ntuklib_physmem(void)\n{\n\tuint64_t ret = 0;\n\n#if defined(_WIN32) || defined(__CYGWIN__)\n\tif ((GetVersion() & 0xFF) >= 5) {\n\t\t// Windows 2000 and later have GlobalMemoryStatusEx() which\n\t\t// supports reporting values greater than 4 GiB. To keep the\n\t\t// code working also on older Windows versions, use\n\t\t// GlobalMemoryStatusEx() conditionally.\n\t\tHMODULE kernel32 = GetModuleHandle(\"kernel32.dll\");\n\t\tif (kernel32 != NULL) {\n\t\t\ttypedef BOOL (WINAPI *gmse_type)(LPMEMORYSTATUSEX);\n\t\t\tgmse_type gmse = (gmse_type)GetProcAddress(\n\t\t\t\t\tkernel32, \"GlobalMemoryStatusEx\");\n\t\t\tif (gmse != NULL) {\n\t\t\t\tMEMORYSTATUSEX meminfo;\n\t\t\t\tmeminfo.dwLength = sizeof(meminfo);\n\t\t\t\tif (gmse(&meminfo))\n\t\t\t\t\tret = meminfo.ullTotalPhys;\n\t\t\t}\n\t\t}\n\t}\n\n\tif (ret == 0) {\n\t\t// GlobalMemoryStatus() is supported by Windows 95 and later,\n\t\t// so it is fine to link against it unconditionally. Note that\n\t\t// GlobalMemoryStatus() has no return value.\n\t\tMEMORYSTATUS meminfo;\n\t\tmeminfo.dwLength = sizeof(meminfo);\n\t\tGlobalMemoryStatus(&meminfo);\n\t\tret = meminfo.dwTotalPhys;\n\t}\n\n#elif defined(__OS2__)\n\tunsigned long mem;\n\tif (DosQuerySysInfo(QSV_TOTPHYSMEM, QSV_TOTPHYSMEM,\n\t\t\t&mem, sizeof(mem)) == 0)\n\t\tret = mem;\n\n#elif defined(__DJGPP__)\n\t__dpmi_free_mem_info meminfo;\n\tif (__dpmi_get_free_memory_information(&meminfo) == 0\n\t\t\t&& meminfo.total_number_of_physical_pages\n\t\t\t\t!= (unsigned long)-1)\n\t\tret = (uint64_t)meminfo.total_number_of_physical_pages * 4096;\n\n#elif defined(__VMS)\n\tint vms_mem;\n\tint val = SYI$_MEMSIZE;\n\tif (LIB$GETSYI(&val, &vms_mem, 0, 0, 0, 0) == SS$_NORMAL)\n\t\tret = (uint64_t)vms_mem * 8192;\n\n#elif defined(AMIGA) || defined(__AROS__)\n\tret = AvailMem(MEMF_TOTAL);\n\n#elif defined(__QNX__)\n\tconst struct asinfo_entry *entries = SYSPAGE_ENTRY(asinfo);\n\tsize_t count = SYSPAGE_ENTRY_SIZE(asinfo) / sizeof(struct asinfo_entry);\n\tconst char *strings = SYSPAGE_ENTRY(strings)->data;\n\n\tfor (size_t i = 0; i < count; ++i)\n\t\tif (strcmp(strings + entries[i].name, \"ram\") == 0)\n\t\t\tret += entries[i].end - entries[i].start + 1;\n\n#elif defined(TUKLIB_PHYSMEM_AIX)\n\tret = _system_configuration.physmem;\n\n#elif defined(TUKLIB_PHYSMEM_SYSCONF)\n\tconst long pagesize = sysconf(_SC_PAGESIZE);\n\tconst long pages = sysconf(_SC_PHYS_PAGES);\n\tif (pagesize != -1 && pages != -1)\n\t\t// According to docs, pagesize * pages can overflow.\n\t\t// Simple case is 32-bit box with 4 GiB or more RAM,\n\t\t// which may report exactly 4 GiB of RAM, and \"long\"\n\t\t// being 32-bit will overflow. Casting to uint64_t\n\t\t// hopefully avoids overflows in the near future.\n\t\tret = (uint64_t)pagesize * (uint64_t)pages;\n\n#elif defined(TUKLIB_PHYSMEM_SYSCTL)\n\tint name[2] = {\n\t\tCTL_HW,\n#ifdef HW_PHYSMEM64\n\t\tHW_PHYSMEM64\n#else\n\t\tHW_PHYSMEM\n#endif\n\t};\n\tunion {\n\t\tuint32_t u32;\n\t\tuint64_t u64;\n\t} mem;\n\tsize_t mem_ptr_size = sizeof(mem.u64);\n\tif (sysctl(name, 2, &mem.u64, &mem_ptr_size, NULL, 0) != -1) {\n\t\t// IIRC, 64-bit \"return value\" is possible on some 64-bit\n\t\t// BSD systems even with HW_PHYSMEM (instead of HW_PHYSMEM64),\n\t\t// so support both.\n\t\tif (mem_ptr_size == sizeof(mem.u64))\n\t\t\tret = mem.u64;\n\t\telse if (mem_ptr_size == sizeof(mem.u32))\n\t\t\tret = mem.u32;\n\t}\n\n#elif defined(TUKLIB_PHYSMEM_GETSYSINFO)\n\t// Docs are unclear if \"start\" is needed, but it doesn't hurt\n\t// much to have it.\n\tint memkb;\n\tint start = 0;\n\tif (getsysinfo(GSI_PHYSMEM, (caddr_t)&memkb, sizeof(memkb), &start)\n\t\t\t!= -1)\n\t\tret = (uint64_t)memkb * 1024;\n\n#elif defined(TUKLIB_PHYSMEM_PSTAT_GETSTATIC)\n\tstruct pst_static pst;\n\tif (pstat_getstatic(&pst, sizeof(pst), 1, 0) != -1)\n\t\tret = (uint64_t)pst.physical_memory * (uint64_t)pst.page_size;\n\n#elif defined(TUKLIB_PHYSMEM_GETINVENT_R)\n\tinv_state_t *st = NULL;\n\tif (setinvent_r(&st) != -1) {\n\t\tinventory_t *i;\n\t\twhile ((i = getinvent_r(st)) != NULL) {\n\t\t\tif (i->inv_class == INV_MEMORY\n\t\t\t\t\t&& i->inv_type == INV_MAIN_MB) {\n\t\t\t\tret = (uint64_t)i->inv_state << 20;\n\t\t\t\tbreak;\n\t\t\t}\n\t\t}\n\n\t\tendinvent_r(st);\n\t}\n\n#elif defined(TUKLIB_PHYSMEM_SYSINFO)\n\tstruct sysinfo si;\n\tif (sysinfo(&si) == 0)\n\t\tret = (uint64_t)si.totalram * si.mem_unit;\n#endif\n\n\treturn ret;\n}\n"
  },
  {
    "path": "external/xz/common/tuklib_physmem.h",
    "content": "///////////////////////////////////////////////////////////////////////////////\n//\n/// \\file       tuklib_physmem.h\n/// \\brief      Get the amount of physical memory\n//\n//  Author:     Lasse Collin\n//\n//  This file has been put into the public domain.\n//  You can do whatever you want with this file.\n//\n///////////////////////////////////////////////////////////////////////////////\n\n#ifndef TUKLIB_PHYSMEM_H\n#define TUKLIB_PHYSMEM_H\n\n#include \"tuklib_common.h\"\nTUKLIB_DECLS_BEGIN\n\n#define tuklib_physmem TUKLIB_SYMBOL(tuklib_physmem)\nextern uint64_t tuklib_physmem(void);\n///<\n/// \\brief      Get the amount of physical memory in bytes\n///\n/// \\return     Amount of physical memory in bytes. On error, zero is\n///             returned.\n\nTUKLIB_DECLS_END\n#endif\n"
  },
  {
    "path": "external/xz/common/tuklib_progname.c",
    "content": "///////////////////////////////////////////////////////////////////////////////\n//\n/// \\file       tuklib_progname.c\n/// \\brief      Program name to be displayed in messages\n//\n//  Author:     Lasse Collin\n//\n//  This file has been put into the public domain.\n//  You can do whatever you want with this file.\n//\n///////////////////////////////////////////////////////////////////////////////\n\n#include \"tuklib_progname.h\"\n#include <string.h>\n\n\n#if !HAVE_DECL_PROGRAM_INVOCATION_NAME\nchar *progname = NULL;\n#endif\n\n\nextern void\ntuklib_progname_init(char **argv)\n{\n#ifdef TUKLIB_DOSLIKE\n\t// On these systems, argv[0] always has the full path and .exe\n\t// suffix even if the user just types the plain program name.\n\t// We modify argv[0] to make it nicer to read.\n\n\t// Strip the leading path.\n\tchar *p = argv[0] + strlen(argv[0]);\n\twhile (argv[0] < p && p[-1] != '/' && p[-1] != '\\\\')\n\t\t--p;\n\n\targv[0] = p;\n\n\t// Strip the .exe suffix.\n\tp = strrchr(p, '.');\n\tif (p != NULL)\n\t\t*p = '\\0';\n\n\t// Make it lowercase.\n\tfor (p = argv[0]; *p != '\\0'; ++p)\n\t\tif (*p >= 'A' && *p <= 'Z')\n\t\t\t*p = *p - 'A' + 'a';\n#endif\n\n\tprogname = argv[0];\n\treturn;\n}\n"
  },
  {
    "path": "external/xz/common/tuklib_progname.h",
    "content": "///////////////////////////////////////////////////////////////////////////////\n//\n/// \\file       tuklib_progname.h\n/// \\brief      Program name to be displayed in messages\n//\n//  Author:     Lasse Collin\n//\n//  This file has been put into the public domain.\n//  You can do whatever you want with this file.\n//\n///////////////////////////////////////////////////////////////////////////////\n\n#ifndef TUKLIB_PROGNAME_H\n#define TUKLIB_PROGNAME_H\n\n#include \"tuklib_common.h\"\n#include <errno.h>\n\nTUKLIB_DECLS_BEGIN\n\n#if HAVE_DECL_PROGRAM_INVOCATION_NAME\n#\tdefine progname program_invocation_name\n#else\n#\tdefine progname TUKLIB_SYMBOL(tuklib_progname)\n\textern char *progname;\n#endif\n\n#define tuklib_progname_init TUKLIB_SYMBOL(tuklib_progname_init)\nextern void tuklib_progname_init(char **argv);\n\nTUKLIB_DECLS_END\n#endif\n"
  },
  {
    "path": "external/xz/liblzma/api/lzma/base.h",
    "content": "/**\n * \\file        lzma/base.h\n * \\brief       Data types and functions used in many places in liblzma API\n */\n\n/*\n * Author: Lasse Collin\n *\n * This file has been put into the public domain.\n * You can do whatever you want with this file.\n *\n * See ../lzma.h for information about liblzma as a whole.\n */\n\n#ifndef LZMA_H_INTERNAL\n#\terror Never include this file directly. Use <lzma.h> instead.\n#endif\n\n\n/**\n * \\brief       Boolean\n *\n * This is here because C89 doesn't have stdbool.h. To set a value for\n * variables having type lzma_bool, you can use\n *   - C99's `true' and `false' from stdbool.h;\n *   - C++'s internal `true' and `false'; or\n *   - integers one (true) and zero (false).\n */\ntypedef unsigned char lzma_bool;\n\n\n/**\n * \\brief       Type of reserved enumeration variable in structures\n *\n * To avoid breaking library ABI when new features are added, several\n * structures contain extra variables that may be used in future. Since\n * sizeof(enum) can be different than sizeof(int), and sizeof(enum) may\n * even vary depending on the range of enumeration constants, we specify\n * a separate type to be used for reserved enumeration variables. All\n * enumeration constants in liblzma API will be non-negative and less\n * than 128, which should guarantee that the ABI won't break even when\n * new constants are added to existing enumerations.\n */\ntypedef enum {\n\tLZMA_RESERVED_ENUM      = 0\n} lzma_reserved_enum;\n\n\n/**\n * \\brief       Return values used by several functions in liblzma\n *\n * Check the descriptions of specific functions to find out which return\n * values they can return. With some functions the return values may have\n * more specific meanings than described here; those differences are\n * described per-function basis.\n */\ntypedef enum {\n\tLZMA_OK                 = 0,\n\t\t/**<\n\t\t * \\brief       Operation completed successfully\n\t\t */\n\n\tLZMA_STREAM_END         = 1,\n\t\t/**<\n\t\t * \\brief       End of stream was reached\n\t\t *\n\t\t * In encoder, LZMA_SYNC_FLUSH, LZMA_FULL_FLUSH, or\n\t\t * LZMA_FINISH was finished. In decoder, this indicates\n\t\t * that all the data was successfully decoded.\n\t\t *\n\t\t * In all cases, when LZMA_STREAM_END is returned, the last\n\t\t * output bytes should be picked from strm->next_out.\n\t\t */\n\n\tLZMA_NO_CHECK           = 2,\n\t\t/**<\n\t\t * \\brief       Input stream has no integrity check\n\t\t *\n\t\t * This return value can be returned only if the\n\t\t * LZMA_TELL_NO_CHECK flag was used when initializing\n\t\t * the decoder. LZMA_NO_CHECK is just a warning, and\n\t\t * the decoding can be continued normally.\n\t\t *\n\t\t * It is possible to call lzma_get_check() immediately after\n\t\t * lzma_code has returned LZMA_NO_CHECK. The result will\n\t\t * naturally be LZMA_CHECK_NONE, but the possibility to call\n\t\t * lzma_get_check() may be convenient in some applications.\n\t\t */\n\n\tLZMA_UNSUPPORTED_CHECK  = 3,\n\t\t/**<\n\t\t * \\brief       Cannot calculate the integrity check\n\t\t *\n\t\t * The usage of this return value is different in encoders\n\t\t * and decoders.\n\t\t *\n\t\t * Encoders can return this value only from the initialization\n\t\t * function. If initialization fails with this value, the\n\t\t * encoding cannot be done, because there's no way to produce\n\t\t * output with the correct integrity check.\n\t\t *\n\t\t * Decoders can return this value only from lzma_code() and\n\t\t * only if the LZMA_TELL_UNSUPPORTED_CHECK flag was used when\n\t\t * initializing the decoder. The decoding can still be\n\t\t * continued normally even if the check type is unsupported,\n\t\t * but naturally the check will not be validated, and possible\n\t\t * errors may go undetected.\n\t\t *\n\t\t * With decoder, it is possible to call lzma_get_check()\n\t\t * immediately after lzma_code() has returned\n\t\t * LZMA_UNSUPPORTED_CHECK. This way it is possible to find\n\t\t * out what the unsupported Check ID was.\n\t\t */\n\n\tLZMA_GET_CHECK          = 4,\n\t\t/**<\n\t\t * \\brief       Integrity check type is now available\n\t\t *\n\t\t * This value can be returned only by the lzma_code() function\n\t\t * and only if the decoder was initialized with the\n\t\t * LZMA_TELL_ANY_CHECK flag. LZMA_GET_CHECK tells the\n\t\t * application that it may now call lzma_get_check() to find\n\t\t * out the Check ID. This can be used, for example, to\n\t\t * implement a decoder that accepts only files that have\n\t\t * strong enough integrity check.\n\t\t */\n\n\tLZMA_MEM_ERROR          = 5,\n\t\t/**<\n\t\t * \\brief       Cannot allocate memory\n\t\t *\n\t\t * Memory allocation failed, or the size of the allocation\n\t\t * would be greater than SIZE_MAX.\n\t\t *\n\t\t * Due to internal implementation reasons, the coding cannot\n\t\t * be continued even if more memory were made available after\n\t\t * LZMA_MEM_ERROR.\n\t\t */\n\n\tLZMA_MEMLIMIT_ERROR     = 6,\n\t\t/**\n\t\t * \\brief       Memory usage limit was reached\n\t\t *\n\t\t * Decoder would need more memory than allowed by the\n\t\t * specified memory usage limit. To continue decoding,\n\t\t * the memory usage limit has to be increased with\n\t\t * lzma_memlimit_set().\n\t\t */\n\n\tLZMA_FORMAT_ERROR       = 7,\n\t\t/**<\n\t\t * \\brief       File format not recognized\n\t\t *\n\t\t * The decoder did not recognize the input as supported file\n\t\t * format. This error can occur, for example, when trying to\n\t\t * decode .lzma format file with lzma_stream_decoder,\n\t\t * because lzma_stream_decoder accepts only the .xz format.\n\t\t */\n\n\tLZMA_OPTIONS_ERROR      = 8,\n\t\t/**<\n\t\t * \\brief       Invalid or unsupported options\n\t\t *\n\t\t * Invalid or unsupported options, for example\n\t\t *  - unsupported filter(s) or filter options; or\n\t\t *  - reserved bits set in headers (decoder only).\n\t\t *\n\t\t * Rebuilding liblzma with more features enabled, or\n\t\t * upgrading to a newer version of liblzma may help.\n\t\t */\n\n\tLZMA_DATA_ERROR         = 9,\n\t\t/**<\n\t\t * \\brief       Data is corrupt\n\t\t *\n\t\t * The usage of this return value is different in encoders\n\t\t * and decoders. In both encoder and decoder, the coding\n\t\t * cannot continue after this error.\n\t\t *\n\t\t * Encoders return this if size limits of the target file\n\t\t * format would be exceeded. These limits are huge, thus\n\t\t * getting this error from an encoder is mostly theoretical.\n\t\t * For example, the maximum compressed and uncompressed\n\t\t * size of a .xz Stream is roughly 8 EiB (2^63 bytes).\n\t\t *\n\t\t * Decoders return this error if the input data is corrupt.\n\t\t * This can mean, for example, invalid CRC32 in headers\n\t\t * or invalid check of uncompressed data.\n\t\t */\n\n\tLZMA_BUF_ERROR          = 10,\n\t\t/**<\n\t\t * \\brief       No progress is possible\n\t\t *\n\t\t * This error code is returned when the coder cannot consume\n\t\t * any new input and produce any new output. The most common\n\t\t * reason for this error is that the input stream being\n\t\t * decoded is truncated or corrupt.\n\t\t *\n\t\t * This error is not fatal. Coding can be continued normally\n\t\t * by providing more input and/or more output space, if\n\t\t * possible.\n\t\t *\n\t\t * Typically the first call to lzma_code() that can do no\n\t\t * progress returns LZMA_OK instead of LZMA_BUF_ERROR. Only\n\t\t * the second consecutive call doing no progress will return\n\t\t * LZMA_BUF_ERROR. This is intentional.\n\t\t *\n\t\t * With zlib, Z_BUF_ERROR may be returned even if the\n\t\t * application is doing nothing wrong, so apps will need\n\t\t * to handle Z_BUF_ERROR specially. The above hack\n\t\t * guarantees that liblzma never returns LZMA_BUF_ERROR\n\t\t * to properly written applications unless the input file\n\t\t * is truncated or corrupt. This should simplify the\n\t\t * applications a little.\n\t\t */\n\n\tLZMA_PROG_ERROR         = 11,\n\t\t/**<\n\t\t * \\brief       Programming error\n\t\t *\n\t\t * This indicates that the arguments given to the function are\n\t\t * invalid or the internal state of the decoder is corrupt.\n\t\t *   - Function arguments are invalid or the structures\n\t\t *     pointed by the argument pointers are invalid\n\t\t *     e.g. if strm->next_out has been set to NULL and\n\t\t *     strm->avail_out > 0 when calling lzma_code().\n\t\t *   - lzma_* functions have been called in wrong order\n\t\t *     e.g. lzma_code() was called right after lzma_end().\n\t\t *   - If errors occur randomly, the reason might be flaky\n\t\t *     hardware.\n\t\t *\n\t\t * If you think that your code is correct, this error code\n\t\t * can be a sign of a bug in liblzma. See the documentation\n\t\t * how to report bugs.\n\t\t */\n} lzma_ret;\n\n\n/**\n * \\brief       The `action' argument for lzma_code()\n *\n * After the first use of LZMA_SYNC_FLUSH, LZMA_FULL_FLUSH, LZMA_FULL_BARRIER,\n * or LZMA_FINISH, the same `action' must is used until lzma_code() returns\n * LZMA_STREAM_END. Also, the amount of input (that is, strm->avail_in) must\n * not be modified by the application until lzma_code() returns\n * LZMA_STREAM_END. Changing the `action' or modifying the amount of input\n * will make lzma_code() return LZMA_PROG_ERROR.\n */\ntypedef enum {\n\tLZMA_RUN = 0,\n\t\t/**<\n\t\t * \\brief       Continue coding\n\t\t *\n\t\t * Encoder: Encode as much input as possible. Some internal\n\t\t * buffering will probably be done (depends on the filter\n\t\t * chain in use), which causes latency: the input used won't\n\t\t * usually be decodeable from the output of the same\n\t\t * lzma_code() call.\n\t\t *\n\t\t * Decoder: Decode as much input as possible and produce as\n\t\t * much output as possible.\n\t\t */\n\n\tLZMA_SYNC_FLUSH = 1,\n\t\t/**<\n\t\t * \\brief       Make all the input available at output\n\t\t *\n\t\t * Normally the encoder introduces some latency.\n\t\t * LZMA_SYNC_FLUSH forces all the buffered data to be\n\t\t * available at output without resetting the internal\n\t\t * state of the encoder. This way it is possible to use\n\t\t * compressed stream for example for communication over\n\t\t * network.\n\t\t *\n\t\t * Only some filters support LZMA_SYNC_FLUSH. Trying to use\n\t\t * LZMA_SYNC_FLUSH with filters that don't support it will\n\t\t * make lzma_code() return LZMA_OPTIONS_ERROR. For example,\n\t\t * LZMA1 doesn't support LZMA_SYNC_FLUSH but LZMA2 does.\n\t\t *\n\t\t * Using LZMA_SYNC_FLUSH very often can dramatically reduce\n\t\t * the compression ratio. With some filters (for example,\n\t\t * LZMA2), fine-tuning the compression options may help\n\t\t * mitigate this problem significantly (for example,\n\t\t * match finder with LZMA2).\n\t\t *\n\t\t * Decoders don't support LZMA_SYNC_FLUSH.\n\t\t */\n\n\tLZMA_FULL_FLUSH = 2,\n\t\t/**<\n\t\t * \\brief       Finish encoding of the current Block\n\t\t *\n\t\t * All the input data going to the current Block must have\n\t\t * been given to the encoder (the last bytes can still be\n\t\t * pending in *next_in). Call lzma_code() with LZMA_FULL_FLUSH\n\t\t * until it returns LZMA_STREAM_END. Then continue normally\n\t\t * with LZMA_RUN or finish the Stream with LZMA_FINISH.\n\t\t *\n\t\t * This action is currently supported only by Stream encoder\n\t\t * and easy encoder (which uses Stream encoder). If there is\n\t\t * no unfinished Block, no empty Block is created.\n\t\t */\n\n\tLZMA_FULL_BARRIER = 4,\n\t\t/**<\n\t\t * \\brief       Finish encoding of the current Block\n\t\t *\n\t\t * This is like LZMA_FULL_FLUSH except that this doesn't\n\t\t * necessarily wait until all the input has been made\n\t\t * available via the output buffer. That is, lzma_code()\n\t\t * might return LZMA_STREAM_END as soon as all the input\n\t\t * has been consumed (avail_in == 0).\n\t\t *\n\t\t * LZMA_FULL_BARRIER is useful with a threaded encoder if\n\t\t * one wants to split the .xz Stream into Blocks at specific\n\t\t * offsets but doesn't care if the output isn't flushed\n\t\t * immediately. Using LZMA_FULL_BARRIER allows keeping\n\t\t * the threads busy while LZMA_FULL_FLUSH would make\n\t\t * lzma_code() wait until all the threads have finished\n\t\t * until more data could be passed to the encoder.\n\t\t *\n\t\t * With a lzma_stream initialized with the single-threaded\n\t\t * lzma_stream_encoder() or lzma_easy_encoder(),\n\t\t * LZMA_FULL_BARRIER is an alias for LZMA_FULL_FLUSH.\n\t\t */\n\n\tLZMA_FINISH = 3\n\t\t/**<\n\t\t * \\brief       Finish the coding operation\n\t\t *\n\t\t * All the input data must have been given to the encoder\n\t\t * (the last bytes can still be pending in next_in).\n\t\t * Call lzma_code() with LZMA_FINISH until it returns\n\t\t * LZMA_STREAM_END. Once LZMA_FINISH has been used,\n\t\t * the amount of input must no longer be changed by\n\t\t * the application.\n\t\t *\n\t\t * When decoding, using LZMA_FINISH is optional unless the\n\t\t * LZMA_CONCATENATED flag was used when the decoder was\n\t\t * initialized. When LZMA_CONCATENATED was not used, the only\n\t\t * effect of LZMA_FINISH is that the amount of input must not\n\t\t * be changed just like in the encoder.\n\t\t */\n} lzma_action;\n\n\n/**\n * \\brief       Custom functions for memory handling\n *\n * A pointer to lzma_allocator may be passed via lzma_stream structure\n * to liblzma, and some advanced functions take a pointer to lzma_allocator\n * as a separate function argument. The library will use the functions\n * specified in lzma_allocator for memory handling instead of the default\n * malloc() and free(). C++ users should note that the custom memory\n * handling functions must not throw exceptions.\n *\n * Single-threaded mode only: liblzma doesn't make an internal copy of\n * lzma_allocator. Thus, it is OK to change these function pointers in\n * the middle of the coding process, but obviously it must be done\n * carefully to make sure that the replacement `free' can deallocate\n * memory allocated by the earlier `alloc' function(s).\n *\n * Multithreaded mode: liblzma might internally store pointers to the\n * lzma_allocator given via the lzma_stream structure. The application\n * must not change the allocator pointer in lzma_stream or the contents\n * of the pointed lzma_allocator structure until lzma_end() has been used\n * to free the memory associated with that lzma_stream. The allocation\n * functions might be called simultaneously from multiple threads, and\n * thus they must be thread safe.\n */\ntypedef struct {\n\t/**\n\t * \\brief       Pointer to a custom memory allocation function\n\t *\n\t * If you don't want a custom allocator, but still want\n\t * custom free(), set this to NULL and liblzma will use\n\t * the standard malloc().\n\t *\n\t * \\param       opaque  lzma_allocator.opaque (see below)\n\t * \\param       nmemb   Number of elements like in calloc(). liblzma\n\t *                      will always set nmemb to 1, so it is safe to\n\t *                      ignore nmemb in a custom allocator if you like.\n\t *                      The nmemb argument exists only for\n\t *                      compatibility with zlib and libbzip2.\n\t * \\param       size    Size of an element in bytes.\n\t *                      liblzma never sets this to zero.\n\t *\n\t * \\return      Pointer to the beginning of a memory block of\n\t *              `size' bytes, or NULL if allocation fails\n\t *              for some reason. When allocation fails, functions\n\t *              of liblzma return LZMA_MEM_ERROR.\n\t *\n\t * The allocator should not waste time zeroing the allocated buffers.\n\t * This is not only about speed, but also memory usage, since the\n\t * operating system kernel doesn't necessarily allocate the requested\n\t * memory in physical memory until it is actually used. With small\n\t * input files, liblzma may actually need only a fraction of the\n\t * memory that it requested for allocation.\n\t *\n\t * \\note        LZMA_MEM_ERROR is also used when the size of the\n\t *              allocation would be greater than SIZE_MAX. Thus,\n\t *              don't assume that the custom allocator must have\n\t *              returned NULL if some function from liblzma\n\t *              returns LZMA_MEM_ERROR.\n\t */\n\tvoid *(LZMA_API_CALL *alloc)(void *opaque, size_t nmemb, size_t size);\n\n\t/**\n\t * \\brief       Pointer to a custom memory freeing function\n\t *\n\t * If you don't want a custom freeing function, but still\n\t * want a custom allocator, set this to NULL and liblzma\n\t * will use the standard free().\n\t *\n\t * \\param       opaque  lzma_allocator.opaque (see below)\n\t * \\param       ptr     Pointer returned by lzma_allocator.alloc(),\n\t *                      or when it is set to NULL, a pointer returned\n\t *                      by the standard malloc().\n\t */\n\tvoid (LZMA_API_CALL *free)(void *opaque, void *ptr);\n\n\t/**\n\t * \\brief       Pointer passed to .alloc() and .free()\n\t *\n\t * opaque is passed as the first argument to lzma_allocator.alloc()\n\t * and lzma_allocator.free(). This intended to ease implementing\n\t * custom memory allocation functions for use with liblzma.\n\t *\n\t * If you don't need this, you should set this to NULL.\n\t */\n\tvoid *opaque;\n\n} lzma_allocator;\n\n\n/**\n * \\brief       Internal data structure\n *\n * The contents of this structure is not visible outside the library.\n */\ntypedef struct lzma_internal_s lzma_internal;\n\n\n/**\n * \\brief       Passing data to and from liblzma\n *\n * The lzma_stream structure is used for\n *  - passing pointers to input and output buffers to liblzma;\n *  - defining custom memory hander functions; and\n *  - holding a pointer to coder-specific internal data structures.\n *\n * Typical usage:\n *\n *  - After allocating lzma_stream (on stack or with malloc()), it must be\n *    initialized to LZMA_STREAM_INIT (see LZMA_STREAM_INIT for details).\n *\n *  - Initialize a coder to the lzma_stream, for example by using\n *    lzma_easy_encoder() or lzma_auto_decoder(). Some notes:\n *      - In contrast to zlib, strm->next_in and strm->next_out are\n *        ignored by all initialization functions, thus it is safe\n *        to not initialize them yet.\n *      - The initialization functions always set strm->total_in and\n *        strm->total_out to zero.\n *      - If the initialization function fails, no memory is left allocated\n *        that would require freeing with lzma_end() even if some memory was\n *        associated with the lzma_stream structure when the initialization\n *        function was called.\n *\n *  - Use lzma_code() to do the actual work.\n *\n *  - Once the coding has been finished, the existing lzma_stream can be\n *    reused. It is OK to reuse lzma_stream with different initialization\n *    function without calling lzma_end() first. Old allocations are\n *    automatically freed.\n *\n *  - Finally, use lzma_end() to free the allocated memory. lzma_end() never\n *    frees the lzma_stream structure itself.\n *\n * Application may modify the values of total_in and total_out as it wants.\n * They are updated by liblzma to match the amount of data read and\n * written but aren't used for anything else except as a possible return\n * values from lzma_get_progress().\n */\ntypedef struct {\n\tconst uint8_t *next_in; /**< Pointer to the next input byte. */\n\tsize_t avail_in;    /**< Number of available input bytes in next_in. */\n\tuint64_t total_in;  /**< Total number of bytes read by liblzma. */\n\n\tuint8_t *next_out;  /**< Pointer to the next output position. */\n\tsize_t avail_out;   /**< Amount of free space in next_out. */\n\tuint64_t total_out; /**< Total number of bytes written by liblzma. */\n\n\t/**\n\t * \\brief       Custom memory allocation functions\n\t *\n\t * In most cases this is NULL which makes liblzma use\n\t * the standard malloc() and free().\n\t *\n\t * \\note        In 5.0.x this is not a const pointer.\n\t */\n\tconst lzma_allocator *allocator;\n\n\t/** Internal state is not visible to applications. */\n\tlzma_internal *internal;\n\n\t/*\n\t * Reserved space to allow possible future extensions without\n\t * breaking the ABI. Excluding the initialization of this structure,\n\t * you should not touch these, because the names of these variables\n\t * may change.\n\t */\n\tvoid *reserved_ptr1;\n\tvoid *reserved_ptr2;\n\tvoid *reserved_ptr3;\n\tvoid *reserved_ptr4;\n\tuint64_t reserved_int1;\n\tuint64_t reserved_int2;\n\tsize_t reserved_int3;\n\tsize_t reserved_int4;\n\tlzma_reserved_enum reserved_enum1;\n\tlzma_reserved_enum reserved_enum2;\n\n} lzma_stream;\n\n\n/**\n * \\brief       Initialization for lzma_stream\n *\n * When you declare an instance of lzma_stream, you can immediately\n * initialize it so that initialization functions know that no memory\n * has been allocated yet:\n *\n *     lzma_stream strm = LZMA_STREAM_INIT;\n *\n * If you need to initialize a dynamically allocated lzma_stream, you can use\n * memset(strm_pointer, 0, sizeof(lzma_stream)). Strictly speaking, this\n * violates the C standard since NULL may have different internal\n * representation than zero, but it should be portable enough in practice.\n * Anyway, for maximum portability, you can use something like this:\n *\n *     lzma_stream tmp = LZMA_STREAM_INIT;\n *     *strm = tmp;\n */\n#define LZMA_STREAM_INIT \\\n\t{ NULL, 0, 0, NULL, 0, 0, NULL, NULL, \\\n\tNULL, NULL, NULL, NULL, 0, 0, 0, 0, \\\n\tLZMA_RESERVED_ENUM, LZMA_RESERVED_ENUM }\n\n\n/**\n * \\brief       Encode or decode data\n *\n * Once the lzma_stream has been successfully initialized (e.g. with\n * lzma_stream_encoder()), the actual encoding or decoding is done\n * using this function. The application has to update strm->next_in,\n * strm->avail_in, strm->next_out, and strm->avail_out to pass input\n * to and get output from liblzma.\n *\n * See the description of the coder-specific initialization function to find\n * out what `action' values are supported by the coder.\n */\nextern LZMA_API(lzma_ret) lzma_code(lzma_stream *strm, lzma_action action)\n\t\tlzma_nothrow lzma_attr_warn_unused_result;\n\n\n/**\n * \\brief       Free memory allocated for the coder data structures\n *\n * \\param       strm    Pointer to lzma_stream that is at least initialized\n *                      with LZMA_STREAM_INIT.\n *\n * After lzma_end(strm), strm->internal is guaranteed to be NULL. No other\n * members of the lzma_stream structure are touched.\n *\n * \\note        zlib indicates an error if application end()s unfinished\n *              stream structure. liblzma doesn't do this, and assumes that\n *              application knows what it is doing.\n */\nextern LZMA_API(void) lzma_end(lzma_stream *strm) lzma_nothrow;\n\n\n/**\n * \\brief       Get progress information\n *\n * In single-threaded mode, applications can get progress information from\n * strm->total_in and strm->total_out. In multi-threaded mode this is less\n * useful because a significant amount of both input and output data gets\n * buffered internally by liblzma. This makes total_in and total_out give\n * misleading information and also makes the progress indicator updates\n * non-smooth.\n *\n * This function gives realistic progress information also in multi-threaded\n * mode by taking into account the progress made by each thread. In\n * single-threaded mode *progress_in and *progress_out are set to\n * strm->total_in and strm->total_out, respectively.\n */\nextern LZMA_API(void) lzma_get_progress(lzma_stream *strm,\n\t\tuint64_t *progress_in, uint64_t *progress_out) lzma_nothrow;\n\n\n/**\n * \\brief       Get the memory usage of decoder filter chain\n *\n * This function is currently supported only when *strm has been initialized\n * with a function that takes a memlimit argument. With other functions, you\n * should use e.g. lzma_raw_encoder_memusage() or lzma_raw_decoder_memusage()\n * to estimate the memory requirements.\n *\n * This function is useful e.g. after LZMA_MEMLIMIT_ERROR to find out how big\n * the memory usage limit should have been to decode the input. Note that\n * this may give misleading information if decoding .xz Streams that have\n * multiple Blocks, because each Block can have different memory requirements.\n *\n * \\return      How much memory is currently allocated for the filter\n *              decoders. If no filter chain is currently allocated,\n *              some non-zero value is still returned, which is less than\n *              or equal to what any filter chain would indicate as its\n *              memory requirement.\n *\n *              If this function isn't supported by *strm or some other error\n *              occurs, zero is returned.\n */\nextern LZMA_API(uint64_t) lzma_memusage(const lzma_stream *strm)\n\t\tlzma_nothrow lzma_attr_pure;\n\n\n/**\n * \\brief       Get the current memory usage limit\n *\n * This function is supported only when *strm has been initialized with\n * a function that takes a memlimit argument.\n *\n * \\return      On success, the current memory usage limit is returned\n *              (always non-zero). On error, zero is returned.\n */\nextern LZMA_API(uint64_t) lzma_memlimit_get(const lzma_stream *strm)\n\t\tlzma_nothrow lzma_attr_pure;\n\n\n/**\n * \\brief       Set the memory usage limit\n *\n * This function is supported only when *strm has been initialized with\n * a function that takes a memlimit argument.\n *\n * liblzma 5.2.3 and earlier has a bug where memlimit value of 0 causes\n * this function to do nothing (leaving the limit unchanged) and still\n * return LZMA_OK. Later versions treat 0 as if 1 had been specified (so\n * lzma_memlimit_get() will return 1 even if you specify 0 here).\n *\n * \\return      - LZMA_OK: New memory usage limit successfully set.\n *              - LZMA_MEMLIMIT_ERROR: The new limit is too small.\n *                The limit was not changed.\n *              - LZMA_PROG_ERROR: Invalid arguments, e.g. *strm doesn't\n *                support memory usage limit.\n */\nextern LZMA_API(lzma_ret) lzma_memlimit_set(\n\t\tlzma_stream *strm, uint64_t memlimit) lzma_nothrow;\n"
  },
  {
    "path": "external/xz/liblzma/api/lzma/bcj.h",
    "content": "/**\n * \\file        lzma/bcj.h\n * \\brief       Branch/Call/Jump conversion filters\n */\n\n/*\n * Author: Lasse Collin\n *\n * This file has been put into the public domain.\n * You can do whatever you want with this file.\n *\n * See ../lzma.h for information about liblzma as a whole.\n */\n\n#ifndef LZMA_H_INTERNAL\n#\terror Never include this file directly. Use <lzma.h> instead.\n#endif\n\n\n/* Filter IDs for lzma_filter.id */\n\n#define LZMA_FILTER_X86         LZMA_VLI_C(0x04)\n\t/**<\n\t * Filter for x86 binaries\n\t */\n\n#define LZMA_FILTER_POWERPC     LZMA_VLI_C(0x05)\n\t/**<\n\t * Filter for Big endian PowerPC binaries\n\t */\n\n#define LZMA_FILTER_IA64        LZMA_VLI_C(0x06)\n\t/**<\n\t * Filter for IA-64 (Itanium) binaries.\n\t */\n\n#define LZMA_FILTER_ARM         LZMA_VLI_C(0x07)\n\t/**<\n\t * Filter for ARM binaries.\n\t */\n\n#define LZMA_FILTER_ARMTHUMB    LZMA_VLI_C(0x08)\n\t/**<\n\t * Filter for ARM-Thumb binaries.\n\t */\n\n#define LZMA_FILTER_SPARC       LZMA_VLI_C(0x09)\n\t/**<\n\t * Filter for SPARC binaries.\n\t */\n\n\n/**\n * \\brief       Options for BCJ filters\n *\n * The BCJ filters never change the size of the data. Specifying options\n * for them is optional: if pointer to options is NULL, default value is\n * used. You probably never need to specify options to BCJ filters, so just\n * set the options pointer to NULL and be happy.\n *\n * If options with non-default values have been specified when encoding,\n * the same options must also be specified when decoding.\n *\n * \\note        At the moment, none of the BCJ filters support\n *              LZMA_SYNC_FLUSH. If LZMA_SYNC_FLUSH is specified,\n *              LZMA_OPTIONS_ERROR will be returned. If there is need,\n *              partial support for LZMA_SYNC_FLUSH can be added in future.\n *              Partial means that flushing would be possible only at\n *              offsets that are multiple of 2, 4, or 16 depending on\n *              the filter, except x86 which cannot be made to support\n *              LZMA_SYNC_FLUSH predictably.\n */\ntypedef struct {\n\t/**\n\t * \\brief       Start offset for conversions\n\t *\n\t * This setting is useful only when the same filter is used\n\t * _separately_ for multiple sections of the same executable file,\n\t * and the sections contain cross-section branch/call/jump\n\t * instructions. In that case it is beneficial to set the start\n\t * offset of the non-first sections so that the relative addresses\n\t * of the cross-section branch/call/jump instructions will use the\n\t * same absolute addresses as in the first section.\n\t *\n\t * When the pointer to options is NULL, the default value (zero)\n\t * is used.\n\t */\n\tuint32_t start_offset;\n\n} lzma_options_bcj;\n"
  },
  {
    "path": "external/xz/liblzma/api/lzma/block.h",
    "content": "/**\n * \\file        lzma/block.h\n * \\brief       .xz Block handling\n */\n\n/*\n * Author: Lasse Collin\n *\n * This file has been put into the public domain.\n * You can do whatever you want with this file.\n *\n * See ../lzma.h for information about liblzma as a whole.\n */\n\n#ifndef LZMA_H_INTERNAL\n#\terror Never include this file directly. Use <lzma.h> instead.\n#endif\n\n\n/**\n * \\brief       Options for the Block and Block Header encoders and decoders\n *\n * Different Block handling functions use different parts of this structure.\n * Some read some members, other functions write, and some do both. Only the\n * members listed for reading need to be initialized when the specified\n * functions are called. The members marked for writing will be assigned\n * new values at some point either by calling the given function or by\n * later calls to lzma_code().\n */\ntypedef struct {\n\t/**\n\t * \\brief       Block format version\n\t *\n\t * To prevent API and ABI breakages when new features are needed,\n\t * a version number is used to indicate which fields in this\n\t * structure are in use:\n\t *   - liblzma >= 5.0.0: version = 0 is supported.\n\t *   - liblzma >= 5.1.4beta: Support for version = 1 was added,\n\t *     which adds the ignore_check field.\n\t *\n\t * If version is greater than one, most Block related functions\n\t * will return LZMA_OPTIONS_ERROR (lzma_block_header_decode() works\n\t * with any version value).\n\t *\n\t * Read by:\n\t *  - All functions that take pointer to lzma_block as argument,\n\t *    including lzma_block_header_decode().\n\t *\n\t * Written by:\n\t *  - lzma_block_header_decode()\n\t */\n\tuint32_t version;\n\n\t/**\n\t * \\brief       Size of the Block Header field\n\t *\n\t * This is always a multiple of four.\n\t *\n\t * Read by:\n\t *  - lzma_block_header_encode()\n\t *  - lzma_block_header_decode()\n\t *  - lzma_block_compressed_size()\n\t *  - lzma_block_unpadded_size()\n\t *  - lzma_block_total_size()\n\t *  - lzma_block_decoder()\n\t *  - lzma_block_buffer_decode()\n\t *\n\t * Written by:\n\t *  - lzma_block_header_size()\n\t *  - lzma_block_buffer_encode()\n\t */\n\tuint32_t header_size;\n#\tdefine LZMA_BLOCK_HEADER_SIZE_MIN 8\n#\tdefine LZMA_BLOCK_HEADER_SIZE_MAX 1024\n\n\t/**\n\t * \\brief       Type of integrity Check\n\t *\n\t * The Check ID is not stored into the Block Header, thus its value\n\t * must be provided also when decoding.\n\t *\n\t * Read by:\n\t *  - lzma_block_header_encode()\n\t *  - lzma_block_header_decode()\n\t *  - lzma_block_compressed_size()\n\t *  - lzma_block_unpadded_size()\n\t *  - lzma_block_total_size()\n\t *  - lzma_block_encoder()\n\t *  - lzma_block_decoder()\n\t *  - lzma_block_buffer_encode()\n\t *  - lzma_block_buffer_decode()\n\t */\n\tlzma_check check;\n\n\t/**\n\t * \\brief       Size of the Compressed Data in bytes\n\t *\n\t * Encoding: If this is not LZMA_VLI_UNKNOWN, Block Header encoder\n\t * will store this value to the Block Header. Block encoder doesn't\n\t * care about this value, but will set it once the encoding has been\n\t * finished.\n\t *\n\t * Decoding: If this is not LZMA_VLI_UNKNOWN, Block decoder will\n\t * verify that the size of the Compressed Data field matches\n\t * compressed_size.\n\t *\n\t * Usually you don't know this value when encoding in streamed mode,\n\t * and thus cannot write this field into the Block Header.\n\t *\n\t * In non-streamed mode you can reserve space for this field before\n\t * encoding the actual Block. After encoding the data, finish the\n\t * Block by encoding the Block Header. Steps in detail:\n\t *\n\t *  - Set compressed_size to some big enough value. If you don't know\n\t *    better, use LZMA_VLI_MAX, but remember that bigger values take\n\t *    more space in Block Header.\n\t *\n\t *  - Call lzma_block_header_size() to see how much space you need to\n\t *    reserve for the Block Header.\n\t *\n\t *  - Encode the Block using lzma_block_encoder() and lzma_code().\n\t *    It sets compressed_size to the correct value.\n\t *\n\t *  - Use lzma_block_header_encode() to encode the Block Header.\n\t *    Because space was reserved in the first step, you don't need\n\t *    to call lzma_block_header_size() anymore, because due to\n\t *    reserving, header_size has to be big enough. If it is \"too big\",\n\t *    lzma_block_header_encode() will add enough Header Padding to\n\t *    make Block Header to match the size specified by header_size.\n\t *\n\t * Read by:\n\t *  - lzma_block_header_size()\n\t *  - lzma_block_header_encode()\n\t *  - lzma_block_compressed_size()\n\t *  - lzma_block_unpadded_size()\n\t *  - lzma_block_total_size()\n\t *  - lzma_block_decoder()\n\t *  - lzma_block_buffer_decode()\n\t *\n\t * Written by:\n\t *  - lzma_block_header_decode()\n\t *  - lzma_block_compressed_size()\n\t *  - lzma_block_encoder()\n\t *  - lzma_block_decoder()\n\t *  - lzma_block_buffer_encode()\n\t *  - lzma_block_buffer_decode()\n\t */\n\tlzma_vli compressed_size;\n\n\t/**\n\t * \\brief       Uncompressed Size in bytes\n\t *\n\t * This is handled very similarly to compressed_size above.\n\t *\n\t * uncompressed_size is needed by fewer functions than\n\t * compressed_size. This is because uncompressed_size isn't\n\t * needed to validate that Block stays within proper limits.\n\t *\n\t * Read by:\n\t *  - lzma_block_header_size()\n\t *  - lzma_block_header_encode()\n\t *  - lzma_block_decoder()\n\t *  - lzma_block_buffer_decode()\n\t *\n\t * Written by:\n\t *  - lzma_block_header_decode()\n\t *  - lzma_block_encoder()\n\t *  - lzma_block_decoder()\n\t *  - lzma_block_buffer_encode()\n\t *  - lzma_block_buffer_decode()\n\t */\n\tlzma_vli uncompressed_size;\n\n\t/**\n\t * \\brief       Array of filters\n\t *\n\t * There can be 1-4 filters. The end of the array is marked with\n\t * .id = LZMA_VLI_UNKNOWN.\n\t *\n\t * Read by:\n\t *  - lzma_block_header_size()\n\t *  - lzma_block_header_encode()\n\t *  - lzma_block_encoder()\n\t *  - lzma_block_decoder()\n\t *  - lzma_block_buffer_encode()\n\t *  - lzma_block_buffer_decode()\n\t *\n\t * Written by:\n\t *  - lzma_block_header_decode(): Note that this does NOT free()\n\t *    the old filter options structures. All unused filters[] will\n\t *    have .id == LZMA_VLI_UNKNOWN and .options == NULL. If\n\t *    decoding fails, all filters[] are guaranteed to be\n\t *    LZMA_VLI_UNKNOWN and NULL.\n\t *\n\t * \\note        Because of the array is terminated with\n\t *              .id = LZMA_VLI_UNKNOWN, the actual array must\n\t *              have LZMA_FILTERS_MAX + 1 members or the Block\n\t *              Header decoder will overflow the buffer.\n\t */\n\tlzma_filter *filters;\n\n\t/**\n\t * \\brief       Raw value stored in the Check field\n\t *\n\t * After successful coding, the first lzma_check_size(check) bytes\n\t * of this array contain the raw value stored in the Check field.\n\t *\n\t * Note that CRC32 and CRC64 are stored in little endian byte order.\n\t * Take it into account if you display the Check values to the user.\n\t *\n\t * Written by:\n\t *  - lzma_block_encoder()\n\t *  - lzma_block_decoder()\n\t *  - lzma_block_buffer_encode()\n\t *  - lzma_block_buffer_decode()\n\t */\n\tuint8_t raw_check[LZMA_CHECK_SIZE_MAX];\n\n\t/*\n\t * Reserved space to allow possible future extensions without\n\t * breaking the ABI. You should not touch these, because the names\n\t * of these variables may change. These are and will never be used\n\t * with the currently supported options, so it is safe to leave these\n\t * uninitialized.\n\t */\n\tvoid *reserved_ptr1;\n\tvoid *reserved_ptr2;\n\tvoid *reserved_ptr3;\n\tuint32_t reserved_int1;\n\tuint32_t reserved_int2;\n\tlzma_vli reserved_int3;\n\tlzma_vli reserved_int4;\n\tlzma_vli reserved_int5;\n\tlzma_vli reserved_int6;\n\tlzma_vli reserved_int7;\n\tlzma_vli reserved_int8;\n\tlzma_reserved_enum reserved_enum1;\n\tlzma_reserved_enum reserved_enum2;\n\tlzma_reserved_enum reserved_enum3;\n\tlzma_reserved_enum reserved_enum4;\n\n\t/**\n\t * \\brief       A flag to Block decoder to not verify the Check field\n\t *\n\t * This field is supported by liblzma >= 5.1.4beta if .version >= 1.\n\t *\n\t * If this is set to true, the integrity check won't be calculated\n\t * and verified. Unless you know what you are doing, you should\n\t * leave this to false. (A reason to set this to true is when the\n\t * file integrity is verified externally anyway and you want to\n\t * speed up the decompression, which matters mostly when using\n\t * SHA-256 as the integrity check.)\n\t *\n\t * If .version >= 1, read by:\n\t *   - lzma_block_decoder()\n\t *   - lzma_block_buffer_decode()\n\t *\n\t * Written by (.version is ignored):\n\t *   - lzma_block_header_decode() always sets this to false\n\t */\n\tlzma_bool ignore_check;\n\n\tlzma_bool reserved_bool2;\n\tlzma_bool reserved_bool3;\n\tlzma_bool reserved_bool4;\n\tlzma_bool reserved_bool5;\n\tlzma_bool reserved_bool6;\n\tlzma_bool reserved_bool7;\n\tlzma_bool reserved_bool8;\n\n} lzma_block;\n\n\n/**\n * \\brief       Decode the Block Header Size field\n *\n * To decode Block Header using lzma_block_header_decode(), the size of the\n * Block Header has to be known and stored into lzma_block.header_size.\n * The size can be calculated from the first byte of a Block using this macro.\n * Note that if the first byte is 0x00, it indicates beginning of Index; use\n * this macro only when the byte is not 0x00.\n *\n * There is no encoding macro, because Block Header encoder is enough for that.\n */\n#define lzma_block_header_size_decode(b) (((uint32_t)(b) + 1) * 4)\n\n\n/**\n * \\brief       Calculate Block Header Size\n *\n * Calculate the minimum size needed for the Block Header field using the\n * settings specified in the lzma_block structure. Note that it is OK to\n * increase the calculated header_size value as long as it is a multiple of\n * four and doesn't exceed LZMA_BLOCK_HEADER_SIZE_MAX. Increasing header_size\n * just means that lzma_block_header_encode() will add Header Padding.\n *\n * \\return      - LZMA_OK: Size calculated successfully and stored to\n *                block->header_size.\n *              - LZMA_OPTIONS_ERROR: Unsupported version, filters or\n *                filter options.\n *              - LZMA_PROG_ERROR: Invalid values like compressed_size == 0.\n *\n * \\note        This doesn't check that all the options are valid i.e. this\n *              may return LZMA_OK even if lzma_block_header_encode() or\n *              lzma_block_encoder() would fail. If you want to validate the\n *              filter chain, consider using lzma_memlimit_encoder() which as\n *              a side-effect validates the filter chain.\n */\nextern LZMA_API(lzma_ret) lzma_block_header_size(lzma_block *block)\n\t\tlzma_nothrow lzma_attr_warn_unused_result;\n\n\n/**\n * \\brief       Encode Block Header\n *\n * The caller must have calculated the size of the Block Header already with\n * lzma_block_header_size(). If a value larger than the one calculated by\n * lzma_block_header_size() is used, the Block Header will be padded to the\n * specified size.\n *\n * \\param       out         Beginning of the output buffer. This must be\n *                          at least block->header_size bytes.\n * \\param       block       Block options to be encoded.\n *\n * \\return      - LZMA_OK: Encoding was successful. block->header_size\n *                bytes were written to output buffer.\n *              - LZMA_OPTIONS_ERROR: Invalid or unsupported options.\n *              - LZMA_PROG_ERROR: Invalid arguments, for example\n *                block->header_size is invalid or block->filters is NULL.\n */\nextern LZMA_API(lzma_ret) lzma_block_header_encode(\n\t\tconst lzma_block *block, uint8_t *out)\n\t\tlzma_nothrow lzma_attr_warn_unused_result;\n\n\n/**\n * \\brief       Decode Block Header\n *\n * block->version should (usually) be set to the highest value supported\n * by the application. If the application sets block->version to a value\n * higher than supported by the current liblzma version, this function will\n * downgrade block->version to the highest value supported by it. Thus one\n * should check the value of block->version after calling this function if\n * block->version was set to a non-zero value and the application doesn't\n * otherwise know that the liblzma version being used is new enough to\n * support the specified block->version.\n *\n * The size of the Block Header must have already been decoded with\n * lzma_block_header_size_decode() macro and stored to block->header_size.\n *\n * The integrity check type from Stream Header must have been stored\n * to block->check.\n *\n * block->filters must have been allocated, but they don't need to be\n * initialized (possible existing filter options are not freed).\n *\n * \\param       block       Destination for Block options.\n * \\param       allocator   lzma_allocator for custom allocator functions.\n *                          Set to NULL to use malloc() (and also free()\n *                          if an error occurs).\n * \\param       in          Beginning of the input buffer. This must be\n *                          at least block->header_size bytes.\n *\n * \\return      - LZMA_OK: Decoding was successful. block->header_size\n *                bytes were read from the input buffer.\n *              - LZMA_OPTIONS_ERROR: The Block Header specifies some\n *                unsupported options such as unsupported filters. This can\n *                happen also if block->version was set to a too low value\n *                compared to what would be required to properly represent\n *                the information stored in the Block Header.\n *              - LZMA_DATA_ERROR: Block Header is corrupt, for example,\n *                the CRC32 doesn't match.\n *              - LZMA_PROG_ERROR: Invalid arguments, for example\n *                block->header_size is invalid or block->filters is NULL.\n */\nextern LZMA_API(lzma_ret) lzma_block_header_decode(lzma_block *block,\n\t\tconst lzma_allocator *allocator, const uint8_t *in)\n\t\tlzma_nothrow lzma_attr_warn_unused_result;\n\n\n/**\n * \\brief       Validate and set Compressed Size according to Unpadded Size\n *\n * Block Header stores Compressed Size, but Index has Unpadded Size. If the\n * application has already parsed the Index and is now decoding Blocks,\n * it can calculate Compressed Size from Unpadded Size. This function does\n * exactly that with error checking:\n *\n *  - Compressed Size calculated from Unpadded Size must be positive integer,\n *    that is, Unpadded Size must be big enough that after Block Header and\n *    Check fields there's still at least one byte for Compressed Size.\n *\n *  - If Compressed Size was present in Block Header, the new value\n *    calculated from Unpadded Size is compared against the value\n *    from Block Header.\n *\n * \\note        This function must be called _after_ decoding the Block Header\n *              field so that it can properly validate Compressed Size if it\n *              was present in Block Header.\n *\n * \\return      - LZMA_OK: block->compressed_size was set successfully.\n *              - LZMA_DATA_ERROR: unpadded_size is too small compared to\n *                block->header_size and lzma_check_size(block->check).\n *              - LZMA_PROG_ERROR: Some values are invalid. For example,\n *                block->header_size must be a multiple of four and\n *                between 8 and 1024 inclusive.\n */\nextern LZMA_API(lzma_ret) lzma_block_compressed_size(\n\t\tlzma_block *block, lzma_vli unpadded_size)\n\t\tlzma_nothrow lzma_attr_warn_unused_result;\n\n\n/**\n * \\brief       Calculate Unpadded Size\n *\n * The Index field stores Unpadded Size and Uncompressed Size. The latter\n * can be taken directly from the lzma_block structure after coding a Block,\n * but Unpadded Size needs to be calculated from Block Header Size,\n * Compressed Size, and size of the Check field. This is where this function\n * is needed.\n *\n * \\return      Unpadded Size on success, or zero on error.\n */\nextern LZMA_API(lzma_vli) lzma_block_unpadded_size(const lzma_block *block)\n\t\tlzma_nothrow lzma_attr_pure;\n\n\n/**\n * \\brief       Calculate the total encoded size of a Block\n *\n * This is equivalent to lzma_block_unpadded_size() except that the returned\n * value includes the size of the Block Padding field.\n *\n * \\return      On success, total encoded size of the Block. On error,\n *              zero is returned.\n */\nextern LZMA_API(lzma_vli) lzma_block_total_size(const lzma_block *block)\n\t\tlzma_nothrow lzma_attr_pure;\n\n\n/**\n * \\brief       Initialize .xz Block encoder\n *\n * Valid actions for lzma_code() are LZMA_RUN, LZMA_SYNC_FLUSH (only if the\n * filter chain supports it), and LZMA_FINISH.\n *\n * \\return      - LZMA_OK: All good, continue with lzma_code().\n *              - LZMA_MEM_ERROR\n *              - LZMA_OPTIONS_ERROR\n *              - LZMA_UNSUPPORTED_CHECK: block->check specifies a Check ID\n *                that is not supported by this build of liblzma. Initializing\n *                the encoder failed.\n *              - LZMA_PROG_ERROR\n */\nextern LZMA_API(lzma_ret) lzma_block_encoder(\n\t\tlzma_stream *strm, lzma_block *block)\n\t\tlzma_nothrow lzma_attr_warn_unused_result;\n\n\n/**\n * \\brief       Initialize .xz Block decoder\n *\n * Valid actions for lzma_code() are LZMA_RUN and LZMA_FINISH. Using\n * LZMA_FINISH is not required. It is supported only for convenience.\n *\n * \\return      - LZMA_OK: All good, continue with lzma_code().\n *              - LZMA_UNSUPPORTED_CHECK: Initialization was successful, but\n *                the given Check ID is not supported, thus Check will be\n *                ignored.\n *              - LZMA_PROG_ERROR\n *              - LZMA_MEM_ERROR\n */\nextern LZMA_API(lzma_ret) lzma_block_decoder(\n\t\tlzma_stream *strm, lzma_block *block)\n\t\tlzma_nothrow lzma_attr_warn_unused_result;\n\n\n/**\n * \\brief       Calculate maximum output size for single-call Block encoding\n *\n * This is equivalent to lzma_stream_buffer_bound() but for .xz Blocks.\n * See the documentation of lzma_stream_buffer_bound().\n */\nextern LZMA_API(size_t) lzma_block_buffer_bound(size_t uncompressed_size)\n\t\tlzma_nothrow;\n\n\n/**\n * \\brief       Single-call .xz Block encoder\n *\n * In contrast to the multi-call encoder initialized with\n * lzma_block_encoder(), this function encodes also the Block Header. This\n * is required to make it possible to write appropriate Block Header also\n * in case the data isn't compressible, and different filter chain has to be\n * used to encode the data in uncompressed form using uncompressed chunks\n * of the LZMA2 filter.\n *\n * When the data isn't compressible, header_size, compressed_size, and\n * uncompressed_size are set just like when the data was compressible, but\n * it is possible that header_size is too small to hold the filter chain\n * specified in block->filters, because that isn't necessarily the filter\n * chain that was actually used to encode the data. lzma_block_unpadded_size()\n * still works normally, because it doesn't read the filters array.\n *\n * \\param       block       Block options: block->version, block->check,\n *                          and block->filters must have been initialized.\n * \\param       allocator   lzma_allocator for custom allocator functions.\n *                          Set to NULL to use malloc() and free().\n * \\param       in          Beginning of the input buffer\n * \\param       in_size     Size of the input buffer\n * \\param       out         Beginning of the output buffer\n * \\param       out_pos     The next byte will be written to out[*out_pos].\n *                          *out_pos is updated only if encoding succeeds.\n * \\param       out_size    Size of the out buffer; the first byte into\n *                          which no data is written to is out[out_size].\n *\n * \\return      - LZMA_OK: Encoding was successful.\n *              - LZMA_BUF_ERROR: Not enough output buffer space.\n *              - LZMA_UNSUPPORTED_CHECK\n *              - LZMA_OPTIONS_ERROR\n *              - LZMA_MEM_ERROR\n *              - LZMA_DATA_ERROR\n *              - LZMA_PROG_ERROR\n */\nextern LZMA_API(lzma_ret) lzma_block_buffer_encode(\n\t\tlzma_block *block, const lzma_allocator *allocator,\n\t\tconst uint8_t *in, size_t in_size,\n\t\tuint8_t *out, size_t *out_pos, size_t out_size)\n\t\tlzma_nothrow lzma_attr_warn_unused_result;\n\n\n/**\n * \\brief       Single-call uncompressed .xz Block encoder\n *\n * This is like lzma_block_buffer_encode() except this doesn't try to\n * compress the data and instead encodes the data using LZMA2 uncompressed\n * chunks. The required output buffer size can be determined with\n * lzma_block_buffer_bound().\n *\n * Since the data won't be compressed, this function ignores block->filters.\n * This function doesn't take lzma_allocator because this function doesn't\n * allocate any memory from the heap.\n */\nextern LZMA_API(lzma_ret) lzma_block_uncomp_encode(lzma_block *block,\n\t\tconst uint8_t *in, size_t in_size,\n\t\tuint8_t *out, size_t *out_pos, size_t out_size)\n\t\tlzma_nothrow lzma_attr_warn_unused_result;\n\n\n/**\n * \\brief       Single-call .xz Block decoder\n *\n * This is single-call equivalent of lzma_block_decoder(), and requires that\n * the caller has already decoded Block Header and checked its memory usage.\n *\n * \\param       block       Block options just like with lzma_block_decoder().\n * \\param       allocator   lzma_allocator for custom allocator functions.\n *                          Set to NULL to use malloc() and free().\n * \\param       in          Beginning of the input buffer\n * \\param       in_pos      The next byte will be read from in[*in_pos].\n *                          *in_pos is updated only if decoding succeeds.\n * \\param       in_size     Size of the input buffer; the first byte that\n *                          won't be read is in[in_size].\n * \\param       out         Beginning of the output buffer\n * \\param       out_pos     The next byte will be written to out[*out_pos].\n *                          *out_pos is updated only if encoding succeeds.\n * \\param       out_size    Size of the out buffer; the first byte into\n *                          which no data is written to is out[out_size].\n *\n * \\return      - LZMA_OK: Decoding was successful.\n *              - LZMA_OPTIONS_ERROR\n *              - LZMA_DATA_ERROR\n *              - LZMA_MEM_ERROR\n *              - LZMA_BUF_ERROR: Output buffer was too small.\n *              - LZMA_PROG_ERROR\n */\nextern LZMA_API(lzma_ret) lzma_block_buffer_decode(\n\t\tlzma_block *block, const lzma_allocator *allocator,\n\t\tconst uint8_t *in, size_t *in_pos, size_t in_size,\n\t\tuint8_t *out, size_t *out_pos, size_t out_size)\n\t\tlzma_nothrow;\n"
  },
  {
    "path": "external/xz/liblzma/api/lzma/check.h",
    "content": "/**\n * \\file        lzma/check.h\n * \\brief       Integrity checks\n */\n\n/*\n * Author: Lasse Collin\n *\n * This file has been put into the public domain.\n * You can do whatever you want with this file.\n *\n * See ../lzma.h for information about liblzma as a whole.\n */\n\n#ifndef LZMA_H_INTERNAL\n#\terror Never include this file directly. Use <lzma.h> instead.\n#endif\n\n\n/**\n * \\brief       Type of the integrity check (Check ID)\n *\n * The .xz format supports multiple types of checks that are calculated\n * from the uncompressed data. They vary in both speed and ability to\n * detect errors.\n */\ntypedef enum {\n\tLZMA_CHECK_NONE     = 0,\n\t\t/**<\n\t\t * No Check is calculated.\n\t\t *\n\t\t * Size of the Check field: 0 bytes\n\t\t */\n\n\tLZMA_CHECK_CRC32    = 1,\n\t\t/**<\n\t\t * CRC32 using the polynomial from the IEEE 802.3 standard\n\t\t *\n\t\t * Size of the Check field: 4 bytes\n\t\t */\n\n\tLZMA_CHECK_CRC64    = 4,\n\t\t/**<\n\t\t * CRC64 using the polynomial from the ECMA-182 standard\n\t\t *\n\t\t * Size of the Check field: 8 bytes\n\t\t */\n\n\tLZMA_CHECK_SHA256   = 10\n\t\t/**<\n\t\t * SHA-256\n\t\t *\n\t\t * Size of the Check field: 32 bytes\n\t\t */\n} lzma_check;\n\n\n/**\n * \\brief       Maximum valid Check ID\n *\n * The .xz file format specification specifies 16 Check IDs (0-15). Some\n * of them are only reserved, that is, no actual Check algorithm has been\n * assigned. When decoding, liblzma still accepts unknown Check IDs for\n * future compatibility. If a valid but unsupported Check ID is detected,\n * liblzma can indicate a warning; see the flags LZMA_TELL_NO_CHECK,\n * LZMA_TELL_UNSUPPORTED_CHECK, and LZMA_TELL_ANY_CHECK in container.h.\n */\n#define LZMA_CHECK_ID_MAX 15\n\n\n/**\n * \\brief       Test if the given Check ID is supported\n *\n * Return true if the given Check ID is supported by this liblzma build.\n * Otherwise false is returned. It is safe to call this with a value that\n * is not in the range [0, 15]; in that case the return value is always false.\n *\n * You can assume that LZMA_CHECK_NONE and LZMA_CHECK_CRC32 are always\n * supported (even if liblzma is built with limited features).\n */\nextern LZMA_API(lzma_bool) lzma_check_is_supported(lzma_check check)\n\t\tlzma_nothrow lzma_attr_const;\n\n\n/**\n * \\brief       Get the size of the Check field with the given Check ID\n *\n * Although not all Check IDs have a check algorithm associated, the size of\n * every Check is already frozen. This function returns the size (in bytes) of\n * the Check field with the specified Check ID. The values are:\n * { 0, 4, 4, 4, 8, 8, 8, 16, 16, 16, 32, 32, 32, 64, 64, 64 }\n *\n * If the argument is not in the range [0, 15], UINT32_MAX is returned.\n */\nextern LZMA_API(uint32_t) lzma_check_size(lzma_check check)\n\t\tlzma_nothrow lzma_attr_const;\n\n\n/**\n * \\brief       Maximum size of a Check field\n */\n#define LZMA_CHECK_SIZE_MAX 64\n\n\n/**\n * \\brief       Calculate CRC32\n *\n * Calculate CRC32 using the polynomial from the IEEE 802.3 standard.\n *\n * \\param       buf     Pointer to the input buffer\n * \\param       size    Size of the input buffer\n * \\param       crc     Previously returned CRC value. This is used to\n *                      calculate the CRC of a big buffer in smaller chunks.\n *                      Set to zero when starting a new calculation.\n *\n * \\return      Updated CRC value, which can be passed to this function\n *              again to continue CRC calculation.\n */\nextern LZMA_API(uint32_t) lzma_crc32(\n\t\tconst uint8_t *buf, size_t size, uint32_t crc)\n\t\tlzma_nothrow lzma_attr_pure;\n\n\n/**\n * \\brief       Calculate CRC64\n *\n * Calculate CRC64 using the polynomial from the ECMA-182 standard.\n *\n * This function is used similarly to lzma_crc32(). See its documentation.\n */\nextern LZMA_API(uint64_t) lzma_crc64(\n\t\tconst uint8_t *buf, size_t size, uint64_t crc)\n\t\tlzma_nothrow lzma_attr_pure;\n\n\n/*\n * SHA-256 functions are currently not exported to public API.\n * Contact Lasse Collin if you think it should be.\n */\n\n\n/**\n * \\brief       Get the type of the integrity check\n *\n * This function can be called only immediately after lzma_code() has\n * returned LZMA_NO_CHECK, LZMA_UNSUPPORTED_CHECK, or LZMA_GET_CHECK.\n * Calling this function in any other situation has undefined behavior.\n */\nextern LZMA_API(lzma_check) lzma_get_check(const lzma_stream *strm)\n\t\tlzma_nothrow;\n"
  },
  {
    "path": "external/xz/liblzma/api/lzma/container.h",
    "content": "/**\n * \\file        lzma/container.h\n * \\brief       File formats\n */\n\n/*\n * Author: Lasse Collin\n *\n * This file has been put into the public domain.\n * You can do whatever you want with this file.\n *\n * See ../lzma.h for information about liblzma as a whole.\n */\n\n#ifndef LZMA_H_INTERNAL\n#\terror Never include this file directly. Use <lzma.h> instead.\n#endif\n\n\n/************\n * Encoding *\n ************/\n\n/**\n * \\brief       Default compression preset\n *\n * It's not straightforward to recommend a default preset, because in some\n * cases keeping the resource usage relatively low is more important that\n * getting the maximum compression ratio.\n */\n#define LZMA_PRESET_DEFAULT     UINT32_C(6)\n\n\n/**\n * \\brief       Mask for preset level\n *\n * This is useful only if you need to extract the level from the preset\n * variable. That should be rare.\n */\n#define LZMA_PRESET_LEVEL_MASK  UINT32_C(0x1F)\n\n\n/*\n * Preset flags\n *\n * Currently only one flag is defined.\n */\n\n/**\n * \\brief       Extreme compression preset\n *\n * This flag modifies the preset to make the encoding significantly slower\n * while improving the compression ratio only marginally. This is useful\n * when you don't mind wasting time to get as small result as possible.\n *\n * This flag doesn't affect the memory usage requirements of the decoder (at\n * least not significantly). The memory usage of the encoder may be increased\n * a little but only at the lowest preset levels (0-3).\n */\n#define LZMA_PRESET_EXTREME       (UINT32_C(1) << 31)\n\n\n/**\n * \\brief       Multithreading options\n */\ntypedef struct {\n\t/**\n\t * \\brief       Flags\n\t *\n\t * Set this to zero if no flags are wanted.\n\t *\n\t * No flags are currently supported.\n\t */\n\tuint32_t flags;\n\n\t/**\n\t * \\brief       Number of worker threads to use\n\t */\n\tuint32_t threads;\n\n\t/**\n\t * \\brief       Maximum uncompressed size of a Block\n\t *\n\t * The encoder will start a new .xz Block every block_size bytes.\n\t * Using LZMA_FULL_FLUSH or LZMA_FULL_BARRIER with lzma_code()\n\t * the caller may tell liblzma to start a new Block earlier.\n\t *\n\t * With LZMA2, a recommended block size is 2-4 times the LZMA2\n\t * dictionary size. With very small dictionaries, it is recommended\n\t * to use at least 1 MiB block size for good compression ratio, even\n\t * if this is more than four times the dictionary size. Note that\n\t * these are only recommendations for typical use cases; feel free\n\t * to use other values. Just keep in mind that using a block size\n\t * less than the LZMA2 dictionary size is waste of RAM.\n\t *\n\t * Set this to 0 to let liblzma choose the block size depending\n\t * on the compression options. For LZMA2 it will be 3*dict_size\n\t * or 1 MiB, whichever is more.\n\t *\n\t * For each thread, about 3 * block_size bytes of memory will be\n\t * allocated. This may change in later liblzma versions. If so,\n\t * the memory usage will probably be reduced, not increased.\n\t */\n\tuint64_t block_size;\n\n\t/**\n\t * \\brief       Timeout to allow lzma_code() to return early\n\t *\n\t * Multithreading can make liblzma to consume input and produce\n\t * output in a very bursty way: it may first read a lot of input\n\t * to fill internal buffers, then no input or output occurs for\n\t * a while.\n\t *\n\t * In single-threaded mode, lzma_code() won't return until it has\n\t * either consumed all the input or filled the output buffer. If\n\t * this is done in multithreaded mode, it may cause a call\n\t * lzma_code() to take even tens of seconds, which isn't acceptable\n\t * in all applications.\n\t *\n\t * To avoid very long blocking times in lzma_code(), a timeout\n\t * (in milliseconds) may be set here. If lzma_code() would block\n\t * longer than this number of milliseconds, it will return with\n\t * LZMA_OK. Reasonable values are 100 ms or more. The xz command\n\t * line tool uses 300 ms.\n\t *\n\t * If long blocking times are fine for you, set timeout to a special\n\t * value of 0, which will disable the timeout mechanism and will make\n\t * lzma_code() block until all the input is consumed or the output\n\t * buffer has been filled.\n\t *\n\t * \\note        Even with a timeout, lzma_code() might sometimes take\n\t *              somewhat long time to return. No timing guarantees\n\t *              are made.\n\t */\n\tuint32_t timeout;\n\n\t/**\n\t * \\brief       Compression preset (level and possible flags)\n\t *\n\t * The preset is set just like with lzma_easy_encoder().\n\t * The preset is ignored if filters below is non-NULL.\n\t */\n\tuint32_t preset;\n\n\t/**\n\t * \\brief       Filter chain (alternative to a preset)\n\t *\n\t * If this is NULL, the preset above is used. Otherwise the preset\n\t * is ignored and the filter chain specified here is used.\n\t */\n\tconst lzma_filter *filters;\n\n\t/**\n\t * \\brief       Integrity check type\n\t *\n\t * See check.h for available checks. The xz command line tool\n\t * defaults to LZMA_CHECK_CRC64, which is a good choice if you\n\t * are unsure.\n\t */\n\tlzma_check check;\n\n\t/*\n\t * Reserved space to allow possible future extensions without\n\t * breaking the ABI. You should not touch these, because the names\n\t * of these variables may change. These are and will never be used\n\t * with the currently supported options, so it is safe to leave these\n\t * uninitialized.\n\t */\n\tlzma_reserved_enum reserved_enum1;\n\tlzma_reserved_enum reserved_enum2;\n\tlzma_reserved_enum reserved_enum3;\n\tuint32_t reserved_int1;\n\tuint32_t reserved_int2;\n\tuint32_t reserved_int3;\n\tuint32_t reserved_int4;\n\tuint64_t reserved_int5;\n\tuint64_t reserved_int6;\n\tuint64_t reserved_int7;\n\tuint64_t reserved_int8;\n\tvoid *reserved_ptr1;\n\tvoid *reserved_ptr2;\n\tvoid *reserved_ptr3;\n\tvoid *reserved_ptr4;\n\n} lzma_mt;\n\n\n/**\n * \\brief       Calculate approximate memory usage of easy encoder\n *\n * This function is a wrapper for lzma_raw_encoder_memusage().\n *\n * \\param       preset  Compression preset (level and possible flags)\n *\n * \\return      Number of bytes of memory required for the given\n *              preset when encoding. If an error occurs, for example\n *              due to unsupported preset, UINT64_MAX is returned.\n */\nextern LZMA_API(uint64_t) lzma_easy_encoder_memusage(uint32_t preset)\n\t\tlzma_nothrow lzma_attr_pure;\n\n\n/**\n * \\brief       Calculate approximate decoder memory usage of a preset\n *\n * This function is a wrapper for lzma_raw_decoder_memusage().\n *\n * \\param       preset  Compression preset (level and possible flags)\n *\n * \\return      Number of bytes of memory required to decompress a file\n *              that was compressed using the given preset. If an error\n *              occurs, for example due to unsupported preset, UINT64_MAX\n *              is returned.\n */\nextern LZMA_API(uint64_t) lzma_easy_decoder_memusage(uint32_t preset)\n\t\tlzma_nothrow lzma_attr_pure;\n\n\n/**\n * \\brief       Initialize .xz Stream encoder using a preset number\n *\n * This function is intended for those who just want to use the basic features\n * if liblzma (that is, most developers out there).\n *\n * \\param       strm    Pointer to lzma_stream that is at least initialized\n *                      with LZMA_STREAM_INIT.\n * \\param       preset  Compression preset to use. A preset consist of level\n *                      number and zero or more flags. Usually flags aren't\n *                      used, so preset is simply a number [0, 9] which match\n *                      the options -0 ... -9 of the xz command line tool.\n *                      Additional flags can be be set using bitwise-or with\n *                      the preset level number, e.g. 6 | LZMA_PRESET_EXTREME.\n * \\param       check   Integrity check type to use. See check.h for available\n *                      checks. The xz command line tool defaults to\n *                      LZMA_CHECK_CRC64, which is a good choice if you are\n *                      unsure. LZMA_CHECK_CRC32 is good too as long as the\n *                      uncompressed file is not many gigabytes.\n *\n * \\return      - LZMA_OK: Initialization succeeded. Use lzma_code() to\n *                encode your data.\n *              - LZMA_MEM_ERROR: Memory allocation failed.\n *              - LZMA_OPTIONS_ERROR: The given compression preset is not\n *                supported by this build of liblzma.\n *              - LZMA_UNSUPPORTED_CHECK: The given check type is not\n *                supported by this liblzma build.\n *              - LZMA_PROG_ERROR: One or more of the parameters have values\n *                that will never be valid. For example, strm == NULL.\n *\n * If initialization fails (return value is not LZMA_OK), all the memory\n * allocated for *strm by liblzma is always freed. Thus, there is no need\n * to call lzma_end() after failed initialization.\n *\n * If initialization succeeds, use lzma_code() to do the actual encoding.\n * Valid values for `action' (the second argument of lzma_code()) are\n * LZMA_RUN, LZMA_SYNC_FLUSH, LZMA_FULL_FLUSH, and LZMA_FINISH. In future,\n * there may be compression levels or flags that don't support LZMA_SYNC_FLUSH.\n */\nextern LZMA_API(lzma_ret) lzma_easy_encoder(\n\t\tlzma_stream *strm, uint32_t preset, lzma_check check)\n\t\tlzma_nothrow lzma_attr_warn_unused_result;\n\n\n/**\n * \\brief       Single-call .xz Stream encoding using a preset number\n *\n * The maximum required output buffer size can be calculated with\n * lzma_stream_buffer_bound().\n *\n * \\param       preset      Compression preset to use. See the description\n *                          in lzma_easy_encoder().\n * \\param       check       Type of the integrity check to calculate from\n *                          uncompressed data.\n * \\param       allocator   lzma_allocator for custom allocator functions.\n *                          Set to NULL to use malloc() and free().\n * \\param       in          Beginning of the input buffer\n * \\param       in_size     Size of the input buffer\n * \\param       out         Beginning of the output buffer\n * \\param       out_pos     The next byte will be written to out[*out_pos].\n *                          *out_pos is updated only if encoding succeeds.\n * \\param       out_size    Size of the out buffer; the first byte into\n *                          which no data is written to is out[out_size].\n *\n * \\return      - LZMA_OK: Encoding was successful.\n *              - LZMA_BUF_ERROR: Not enough output buffer space.\n *              - LZMA_UNSUPPORTED_CHECK\n *              - LZMA_OPTIONS_ERROR\n *              - LZMA_MEM_ERROR\n *              - LZMA_DATA_ERROR\n *              - LZMA_PROG_ERROR\n */\nextern LZMA_API(lzma_ret) lzma_easy_buffer_encode(\n\t\tuint32_t preset, lzma_check check,\n\t\tconst lzma_allocator *allocator,\n\t\tconst uint8_t *in, size_t in_size,\n\t\tuint8_t *out, size_t *out_pos, size_t out_size) lzma_nothrow;\n\n\n/**\n * \\brief       Initialize .xz Stream encoder using a custom filter chain\n *\n * \\param       strm    Pointer to properly prepared lzma_stream\n * \\param       filters Array of filters. This must be terminated with\n *                      filters[n].id = LZMA_VLI_UNKNOWN. See filter.h for\n *                      more information.\n * \\param       check   Type of the integrity check to calculate from\n *                      uncompressed data.\n *\n * \\return      - LZMA_OK: Initialization was successful.\n *              - LZMA_MEM_ERROR\n *              - LZMA_UNSUPPORTED_CHECK\n *              - LZMA_OPTIONS_ERROR\n *              - LZMA_PROG_ERROR\n */\nextern LZMA_API(lzma_ret) lzma_stream_encoder(lzma_stream *strm,\n\t\tconst lzma_filter *filters, lzma_check check)\n\t\tlzma_nothrow lzma_attr_warn_unused_result;\n\n\n/**\n * \\brief       Calculate approximate memory usage of multithreaded .xz encoder\n *\n * Since doing the encoding in threaded mode doesn't affect the memory\n * requirements of single-threaded decompressor, you can use\n * lzma_easy_decoder_memusage(options->preset) or\n * lzma_raw_decoder_memusage(options->filters) to calculate\n * the decompressor memory requirements.\n *\n * \\param       options Compression options\n *\n * \\return      Number of bytes of memory required for encoding with the\n *              given options. If an error occurs, for example due to\n *              unsupported preset or filter chain, UINT64_MAX is returned.\n */\nextern LZMA_API(uint64_t) lzma_stream_encoder_mt_memusage(\n\t\tconst lzma_mt *options) lzma_nothrow lzma_attr_pure;\n\n\n/**\n * \\brief       Initialize multithreaded .xz Stream encoder\n *\n * This provides the functionality of lzma_easy_encoder() and\n * lzma_stream_encoder() as a single function for multithreaded use.\n *\n * The supported actions for lzma_code() are LZMA_RUN, LZMA_FULL_FLUSH,\n * LZMA_FULL_BARRIER, and LZMA_FINISH. Support for LZMA_SYNC_FLUSH might be\n * added in the future.\n *\n * \\param       strm    Pointer to properly prepared lzma_stream\n * \\param       options Pointer to multithreaded compression options\n *\n * \\return      - LZMA_OK\n *              - LZMA_MEM_ERROR\n *              - LZMA_UNSUPPORTED_CHECK\n *              - LZMA_OPTIONS_ERROR\n *              - LZMA_PROG_ERROR\n */\nextern LZMA_API(lzma_ret) lzma_stream_encoder_mt(\n\t\tlzma_stream *strm, const lzma_mt *options)\n\t\tlzma_nothrow lzma_attr_warn_unused_result;\n\n\n/**\n * \\brief       Initialize .lzma encoder (legacy file format)\n *\n * The .lzma format is sometimes called the LZMA_Alone format, which is the\n * reason for the name of this function. The .lzma format supports only the\n * LZMA1 filter. There is no support for integrity checks like CRC32.\n *\n * Use this function if and only if you need to create files readable by\n * legacy LZMA tools such as LZMA Utils 4.32.x. Moving to the .xz format\n * is strongly recommended.\n *\n * The valid action values for lzma_code() are LZMA_RUN and LZMA_FINISH.\n * No kind of flushing is supported, because the file format doesn't make\n * it possible.\n *\n * \\return      - LZMA_OK\n *              - LZMA_MEM_ERROR\n *              - LZMA_OPTIONS_ERROR\n *              - LZMA_PROG_ERROR\n */\nextern LZMA_API(lzma_ret) lzma_alone_encoder(\n\t\tlzma_stream *strm, const lzma_options_lzma *options)\n\t\tlzma_nothrow lzma_attr_warn_unused_result;\n\n\n/**\n * \\brief       Calculate output buffer size for single-call Stream encoder\n *\n * When trying to compress uncompressible data, the encoded size will be\n * slightly bigger than the input data. This function calculates how much\n * output buffer space is required to be sure that lzma_stream_buffer_encode()\n * doesn't return LZMA_BUF_ERROR.\n *\n * The calculated value is not exact, but it is guaranteed to be big enough.\n * The actual maximum output space required may be slightly smaller (up to\n * about 100 bytes). This should not be a problem in practice.\n *\n * If the calculated maximum size doesn't fit into size_t or would make the\n * Stream grow past LZMA_VLI_MAX (which should never happen in practice),\n * zero is returned to indicate the error.\n *\n * \\note        The limit calculated by this function applies only to\n *              single-call encoding. Multi-call encoding may (and probably\n *              will) have larger maximum expansion when encoding\n *              uncompressible data. Currently there is no function to\n *              calculate the maximum expansion of multi-call encoding.\n */\nextern LZMA_API(size_t) lzma_stream_buffer_bound(size_t uncompressed_size)\n\t\tlzma_nothrow;\n\n\n/**\n * \\brief       Single-call .xz Stream encoder\n *\n * \\param       filters     Array of filters. This must be terminated with\n *                          filters[n].id = LZMA_VLI_UNKNOWN. See filter.h\n *                          for more information.\n * \\param       check       Type of the integrity check to calculate from\n *                          uncompressed data.\n * \\param       allocator   lzma_allocator for custom allocator functions.\n *                          Set to NULL to use malloc() and free().\n * \\param       in          Beginning of the input buffer\n * \\param       in_size     Size of the input buffer\n * \\param       out         Beginning of the output buffer\n * \\param       out_pos     The next byte will be written to out[*out_pos].\n *                          *out_pos is updated only if encoding succeeds.\n * \\param       out_size    Size of the out buffer; the first byte into\n *                          which no data is written to is out[out_size].\n *\n * \\return      - LZMA_OK: Encoding was successful.\n *              - LZMA_BUF_ERROR: Not enough output buffer space.\n *              - LZMA_UNSUPPORTED_CHECK\n *              - LZMA_OPTIONS_ERROR\n *              - LZMA_MEM_ERROR\n *              - LZMA_DATA_ERROR\n *              - LZMA_PROG_ERROR\n */\nextern LZMA_API(lzma_ret) lzma_stream_buffer_encode(\n\t\tlzma_filter *filters, lzma_check check,\n\t\tconst lzma_allocator *allocator,\n\t\tconst uint8_t *in, size_t in_size,\n\t\tuint8_t *out, size_t *out_pos, size_t out_size)\n\t\tlzma_nothrow lzma_attr_warn_unused_result;\n\n\n/************\n * Decoding *\n ************/\n\n/**\n * This flag makes lzma_code() return LZMA_NO_CHECK if the input stream\n * being decoded has no integrity check. Note that when used with\n * lzma_auto_decoder(), all .lzma files will trigger LZMA_NO_CHECK\n * if LZMA_TELL_NO_CHECK is used.\n */\n#define LZMA_TELL_NO_CHECK              UINT32_C(0x01)\n\n\n/**\n * This flag makes lzma_code() return LZMA_UNSUPPORTED_CHECK if the input\n * stream has an integrity check, but the type of the integrity check is not\n * supported by this liblzma version or build. Such files can still be\n * decoded, but the integrity check cannot be verified.\n */\n#define LZMA_TELL_UNSUPPORTED_CHECK     UINT32_C(0x02)\n\n\n/**\n * This flag makes lzma_code() return LZMA_GET_CHECK as soon as the type\n * of the integrity check is known. The type can then be got with\n * lzma_get_check().\n */\n#define LZMA_TELL_ANY_CHECK             UINT32_C(0x04)\n\n\n/**\n * This flag makes lzma_code() not calculate and verify the integrity check\n * of the compressed data in .xz files. This means that invalid integrity\n * check values won't be detected and LZMA_DATA_ERROR won't be returned in\n * such cases.\n *\n * This flag only affects the checks of the compressed data itself; the CRC32\n * values in the .xz headers will still be verified normally.\n *\n * Don't use this flag unless you know what you are doing. Possible reasons\n * to use this flag:\n *\n *   - Trying to recover data from a corrupt .xz file.\n *\n *   - Speeding up decompression, which matters mostly with SHA-256\n *     or with files that have compressed extremely well. It's recommended\n *     to not use this flag for this purpose unless the file integrity is\n *     verified externally in some other way.\n *\n * Support for this flag was added in liblzma 5.1.4beta.\n */\n#define LZMA_IGNORE_CHECK               UINT32_C(0x10)\n\n\n/**\n * This flag enables decoding of concatenated files with file formats that\n * allow concatenating compressed files as is. From the formats currently\n * supported by liblzma, only the .xz format allows concatenated files.\n * Concatenated files are not allowed with the legacy .lzma format.\n *\n * This flag also affects the usage of the `action' argument for lzma_code().\n * When LZMA_CONCATENATED is used, lzma_code() won't return LZMA_STREAM_END\n * unless LZMA_FINISH is used as `action'. Thus, the application has to set\n * LZMA_FINISH in the same way as it does when encoding.\n *\n * If LZMA_CONCATENATED is not used, the decoders still accept LZMA_FINISH\n * as `action' for lzma_code(), but the usage of LZMA_FINISH isn't required.\n */\n#define LZMA_CONCATENATED               UINT32_C(0x08)\n\n\n/**\n * \\brief       Initialize .xz Stream decoder\n *\n * \\param       strm        Pointer to properly prepared lzma_stream\n * \\param       memlimit    Memory usage limit as bytes. Use UINT64_MAX\n *                          to effectively disable the limiter. liblzma\n *                          5.2.3 and earlier don't allow 0 here and return\n *                          LZMA_PROG_ERROR; later versions treat 0 as if 1\n *                          had been specified.\n * \\param       flags       Bitwise-or of zero or more of the decoder flags:\n *                          LZMA_TELL_NO_CHECK, LZMA_TELL_UNSUPPORTED_CHECK,\n *                          LZMA_TELL_ANY_CHECK, LZMA_CONCATENATED\n *\n * \\return      - LZMA_OK: Initialization was successful.\n *              - LZMA_MEM_ERROR: Cannot allocate memory.\n *              - LZMA_OPTIONS_ERROR: Unsupported flags\n *              - LZMA_PROG_ERROR\n */\nextern LZMA_API(lzma_ret) lzma_stream_decoder(\n\t\tlzma_stream *strm, uint64_t memlimit, uint32_t flags)\n\t\tlzma_nothrow lzma_attr_warn_unused_result;\n\n\n/**\n * \\brief       Decode .xz Streams and .lzma files with autodetection\n *\n * This decoder autodetects between the .xz and .lzma file formats, and\n * calls lzma_stream_decoder() or lzma_alone_decoder() once the type\n * of the input file has been detected.\n *\n * \\param       strm        Pointer to properly prepared lzma_stream\n * \\param       memlimit    Memory usage limit as bytes. Use UINT64_MAX\n *                          to effectively disable the limiter. liblzma\n *                          5.2.3 and earlier don't allow 0 here and return\n *                          LZMA_PROG_ERROR; later versions treat 0 as if 1\n *                          had been specified.\n * \\param       flags       Bitwise-or of flags, or zero for no flags.\n *\n * \\return      - LZMA_OK: Initialization was successful.\n *              - LZMA_MEM_ERROR: Cannot allocate memory.\n *              - LZMA_OPTIONS_ERROR: Unsupported flags\n *              - LZMA_PROG_ERROR\n */\nextern LZMA_API(lzma_ret) lzma_auto_decoder(\n\t\tlzma_stream *strm, uint64_t memlimit, uint32_t flags)\n\t\tlzma_nothrow lzma_attr_warn_unused_result;\n\n\n/**\n * \\brief       Initialize .lzma decoder (legacy file format)\n *\n * \\param       strm        Pointer to properly prepared lzma_stream\n * \\param       memlimit    Memory usage limit as bytes. Use UINT64_MAX\n *                          to effectively disable the limiter. liblzma\n *                          5.2.3 and earlier don't allow 0 here and return\n *                          LZMA_PROG_ERROR; later versions treat 0 as if 1\n *                          had been specified.\n *\n * Valid `action' arguments to lzma_code() are LZMA_RUN and LZMA_FINISH.\n * There is no need to use LZMA_FINISH, but it's allowed because it may\n * simplify certain types of applications.\n *\n * \\return      - LZMA_OK\n *              - LZMA_MEM_ERROR\n *              - LZMA_PROG_ERROR\n */\nextern LZMA_API(lzma_ret) lzma_alone_decoder(\n\t\tlzma_stream *strm, uint64_t memlimit)\n\t\tlzma_nothrow lzma_attr_warn_unused_result;\n\n\n/**\n * \\brief       Single-call .xz Stream decoder\n *\n * \\param       memlimit    Pointer to how much memory the decoder is allowed\n *                          to allocate. The value pointed by this pointer is\n *                          modified if and only if LZMA_MEMLIMIT_ERROR is\n *                          returned.\n * \\param       flags       Bitwise-or of zero or more of the decoder flags:\n *                          LZMA_TELL_NO_CHECK, LZMA_TELL_UNSUPPORTED_CHECK,\n *                          LZMA_CONCATENATED. Note that LZMA_TELL_ANY_CHECK\n *                          is not allowed and will return LZMA_PROG_ERROR.\n * \\param       allocator   lzma_allocator for custom allocator functions.\n *                          Set to NULL to use malloc() and free().\n * \\param       in          Beginning of the input buffer\n * \\param       in_pos      The next byte will be read from in[*in_pos].\n *                          *in_pos is updated only if decoding succeeds.\n * \\param       in_size     Size of the input buffer; the first byte that\n *                          won't be read is in[in_size].\n * \\param       out         Beginning of the output buffer\n * \\param       out_pos     The next byte will be written to out[*out_pos].\n *                          *out_pos is updated only if decoding succeeds.\n * \\param       out_size    Size of the out buffer; the first byte into\n *                          which no data is written to is out[out_size].\n *\n * \\return      - LZMA_OK: Decoding was successful.\n *              - LZMA_FORMAT_ERROR\n *              - LZMA_OPTIONS_ERROR\n *              - LZMA_DATA_ERROR\n *              - LZMA_NO_CHECK: This can be returned only if using\n *                the LZMA_TELL_NO_CHECK flag.\n *              - LZMA_UNSUPPORTED_CHECK: This can be returned only if using\n *                the LZMA_TELL_UNSUPPORTED_CHECK flag.\n *              - LZMA_MEM_ERROR\n *              - LZMA_MEMLIMIT_ERROR: Memory usage limit was reached.\n *                The minimum required memlimit value was stored to *memlimit.\n *              - LZMA_BUF_ERROR: Output buffer was too small.\n *              - LZMA_PROG_ERROR\n */\nextern LZMA_API(lzma_ret) lzma_stream_buffer_decode(\n\t\tuint64_t *memlimit, uint32_t flags,\n\t\tconst lzma_allocator *allocator,\n\t\tconst uint8_t *in, size_t *in_pos, size_t in_size,\n\t\tuint8_t *out, size_t *out_pos, size_t out_size)\n\t\tlzma_nothrow lzma_attr_warn_unused_result;\n"
  },
  {
    "path": "external/xz/liblzma/api/lzma/delta.h",
    "content": "/**\n * \\file        lzma/delta.h\n * \\brief       Delta filter\n */\n\n/*\n * Author: Lasse Collin\n *\n * This file has been put into the public domain.\n * You can do whatever you want with this file.\n *\n * See ../lzma.h for information about liblzma as a whole.\n */\n\n#ifndef LZMA_H_INTERNAL\n#\terror Never include this file directly. Use <lzma.h> instead.\n#endif\n\n\n/**\n * \\brief       Filter ID\n *\n * Filter ID of the Delta filter. This is used as lzma_filter.id.\n */\n#define LZMA_FILTER_DELTA       LZMA_VLI_C(0x03)\n\n\n/**\n * \\brief       Type of the delta calculation\n *\n * Currently only byte-wise delta is supported. Other possible types could\n * be, for example, delta of 16/32/64-bit little/big endian integers, but\n * these are not currently planned since byte-wise delta is almost as good.\n */\ntypedef enum {\n\tLZMA_DELTA_TYPE_BYTE\n} lzma_delta_type;\n\n\n/**\n * \\brief       Options for the Delta filter\n *\n * These options are needed by both encoder and decoder.\n */\ntypedef struct {\n\t/** For now, this must always be LZMA_DELTA_TYPE_BYTE. */\n\tlzma_delta_type type;\n\n\t/**\n\t * \\brief       Delta distance\n\t *\n\t * With the only currently supported type, LZMA_DELTA_TYPE_BYTE,\n\t * the distance is as bytes.\n\t *\n\t * Examples:\n\t *  - 16-bit stereo audio: distance = 4 bytes\n\t *  - 24-bit RGB image data: distance = 3 bytes\n\t */\n\tuint32_t dist;\n#\tdefine LZMA_DELTA_DIST_MIN 1\n#\tdefine LZMA_DELTA_DIST_MAX 256\n\n\t/*\n\t * Reserved space to allow possible future extensions without\n\t * breaking the ABI. You should not touch these, because the names\n\t * of these variables may change. These are and will never be used\n\t * when type is LZMA_DELTA_TYPE_BYTE, so it is safe to leave these\n\t * uninitialized.\n\t */\n\tuint32_t reserved_int1;\n\tuint32_t reserved_int2;\n\tuint32_t reserved_int3;\n\tuint32_t reserved_int4;\n\tvoid *reserved_ptr1;\n\tvoid *reserved_ptr2;\n\n} lzma_options_delta;\n"
  },
  {
    "path": "external/xz/liblzma/api/lzma/filter.h",
    "content": "/**\n * \\file        lzma/filter.h\n * \\brief       Common filter related types and functions\n */\n\n/*\n * Author: Lasse Collin\n *\n * This file has been put into the public domain.\n * You can do whatever you want with this file.\n *\n * See ../lzma.h for information about liblzma as a whole.\n */\n\n#ifndef LZMA_H_INTERNAL\n#\terror Never include this file directly. Use <lzma.h> instead.\n#endif\n\n\n/**\n * \\brief       Maximum number of filters in a chain\n *\n * A filter chain can have 1-4 filters, of which three are allowed to change\n * the size of the data. Usually only one or two filters are needed.\n */\n#define LZMA_FILTERS_MAX 4\n\n\n/**\n * \\brief       Filter options\n *\n * This structure is used to pass Filter ID and a pointer filter's\n * options to liblzma. A few functions work with a single lzma_filter\n * structure, while most functions expect a filter chain.\n *\n * A filter chain is indicated with an array of lzma_filter structures.\n * The array is terminated with .id = LZMA_VLI_UNKNOWN. Thus, the filter\n * array must have LZMA_FILTERS_MAX + 1 elements (that is, five) to\n * be able to hold any arbitrary filter chain. This is important when\n * using lzma_block_header_decode() from block.h, because too small\n * array would make liblzma write past the end of the filters array.\n */\ntypedef struct {\n\t/**\n\t * \\brief       Filter ID\n\t *\n\t * Use constants whose name begin with `LZMA_FILTER_' to specify\n\t * different filters. In an array of lzma_filter structures, use\n\t * LZMA_VLI_UNKNOWN to indicate end of filters.\n\t *\n\t * \\note        This is not an enum, because on some systems enums\n\t *              cannot be 64-bit.\n\t */\n\tlzma_vli id;\n\n\t/**\n\t * \\brief       Pointer to filter-specific options structure\n\t *\n\t * If the filter doesn't need options, set this to NULL. If id is\n\t * set to LZMA_VLI_UNKNOWN, options is ignored, and thus\n\t * doesn't need be initialized.\n\t */\n\tvoid *options;\n\n} lzma_filter;\n\n\n/**\n * \\brief       Test if the given Filter ID is supported for encoding\n *\n * Return true if the give Filter ID is supported for encoding by this\n * liblzma build. Otherwise false is returned.\n *\n * There is no way to list which filters are available in this particular\n * liblzma version and build. It would be useless, because the application\n * couldn't know what kind of options the filter would need.\n */\nextern LZMA_API(lzma_bool) lzma_filter_encoder_is_supported(lzma_vli id)\n\t\tlzma_nothrow lzma_attr_const;\n\n\n/**\n * \\brief       Test if the given Filter ID is supported for decoding\n *\n * Return true if the give Filter ID is supported for decoding by this\n * liblzma build. Otherwise false is returned.\n */\nextern LZMA_API(lzma_bool) lzma_filter_decoder_is_supported(lzma_vli id)\n\t\tlzma_nothrow lzma_attr_const;\n\n\n/**\n * \\brief       Copy the filters array\n *\n * Copy the Filter IDs and filter-specific options from src to dest.\n * Up to LZMA_FILTERS_MAX filters are copied, plus the terminating\n * .id == LZMA_VLI_UNKNOWN. Thus, dest should have at least\n * LZMA_FILTERS_MAX + 1 elements space unless the caller knows that\n * src is smaller than that.\n *\n * Unless the filter-specific options is NULL, the Filter ID has to be\n * supported by liblzma, because liblzma needs to know the size of every\n * filter-specific options structure. The filter-specific options are not\n * validated. If options is NULL, any unsupported Filter IDs are copied\n * without returning an error.\n *\n * Old filter-specific options in dest are not freed, so dest doesn't\n * need to be initialized by the caller in any way.\n *\n * If an error occurs, memory possibly already allocated by this function\n * is always freed.\n *\n * \\return      - LZMA_OK\n *              - LZMA_MEM_ERROR\n *              - LZMA_OPTIONS_ERROR: Unsupported Filter ID and its options\n *                is not NULL.\n *              - LZMA_PROG_ERROR: src or dest is NULL.\n */\nextern LZMA_API(lzma_ret) lzma_filters_copy(\n\t\tconst lzma_filter *src, lzma_filter *dest,\n\t\tconst lzma_allocator *allocator) lzma_nothrow;\n\n\n/**\n * \\brief       Calculate approximate memory requirements for raw encoder\n *\n * This function can be used to calculate the memory requirements for\n * Block and Stream encoders too because Block and Stream encoders don't\n * need significantly more memory than raw encoder.\n *\n * \\param       filters     Array of filters terminated with\n *                          .id == LZMA_VLI_UNKNOWN.\n *\n * \\return      Number of bytes of memory required for the given\n *              filter chain when encoding. If an error occurs,\n *              for example due to unsupported filter chain,\n *              UINT64_MAX is returned.\n */\nextern LZMA_API(uint64_t) lzma_raw_encoder_memusage(const lzma_filter *filters)\n\t\tlzma_nothrow lzma_attr_pure;\n\n\n/**\n * \\brief       Calculate approximate memory requirements for raw decoder\n *\n * This function can be used to calculate the memory requirements for\n * Block and Stream decoders too because Block and Stream decoders don't\n * need significantly more memory than raw decoder.\n *\n * \\param       filters     Array of filters terminated with\n *                          .id == LZMA_VLI_UNKNOWN.\n *\n * \\return      Number of bytes of memory required for the given\n *              filter chain when decoding. If an error occurs,\n *              for example due to unsupported filter chain,\n *              UINT64_MAX is returned.\n */\nextern LZMA_API(uint64_t) lzma_raw_decoder_memusage(const lzma_filter *filters)\n\t\tlzma_nothrow lzma_attr_pure;\n\n\n/**\n * \\brief       Initialize raw encoder\n *\n * This function may be useful when implementing custom file formats.\n *\n * \\param       strm    Pointer to properly prepared lzma_stream\n * \\param       filters Array of lzma_filter structures. The end of the\n *                      array must be marked with .id = LZMA_VLI_UNKNOWN.\n *\n * The `action' with lzma_code() can be LZMA_RUN, LZMA_SYNC_FLUSH (if the\n * filter chain supports it), or LZMA_FINISH.\n *\n * \\return      - LZMA_OK\n *              - LZMA_MEM_ERROR\n *              - LZMA_OPTIONS_ERROR\n *              - LZMA_PROG_ERROR\n */\nextern LZMA_API(lzma_ret) lzma_raw_encoder(\n\t\tlzma_stream *strm, const lzma_filter *filters)\n\t\tlzma_nothrow lzma_attr_warn_unused_result;\n\n\n/**\n * \\brief       Initialize raw decoder\n *\n * The initialization of raw decoder goes similarly to raw encoder.\n *\n * The `action' with lzma_code() can be LZMA_RUN or LZMA_FINISH. Using\n * LZMA_FINISH is not required, it is supported just for convenience.\n *\n * \\return      - LZMA_OK\n *              - LZMA_MEM_ERROR\n *              - LZMA_OPTIONS_ERROR\n *              - LZMA_PROG_ERROR\n */\nextern LZMA_API(lzma_ret) lzma_raw_decoder(\n\t\tlzma_stream *strm, const lzma_filter *filters)\n\t\tlzma_nothrow lzma_attr_warn_unused_result;\n\n\n/**\n * \\brief       Update the filter chain in the encoder\n *\n * This function is for advanced users only. This function has two slightly\n * different purposes:\n *\n *  - After LZMA_FULL_FLUSH when using Stream encoder: Set a new filter\n *    chain, which will be used starting from the next Block.\n *\n *  - After LZMA_SYNC_FLUSH using Raw, Block, or Stream encoder: Change\n *    the filter-specific options in the middle of encoding. The actual\n *    filters in the chain (Filter IDs) cannot be changed. In the future,\n *    it might become possible to change the filter options without\n *    using LZMA_SYNC_FLUSH.\n *\n * While rarely useful, this function may be called also when no data has\n * been compressed yet. In that case, this function will behave as if\n * LZMA_FULL_FLUSH (Stream encoder) or LZMA_SYNC_FLUSH (Raw or Block\n * encoder) had been used right before calling this function.\n *\n * \\return      - LZMA_OK\n *              - LZMA_MEM_ERROR\n *              - LZMA_MEMLIMIT_ERROR\n *              - LZMA_OPTIONS_ERROR\n *              - LZMA_PROG_ERROR\n */\nextern LZMA_API(lzma_ret) lzma_filters_update(\n\t\tlzma_stream *strm, const lzma_filter *filters) lzma_nothrow;\n\n\n/**\n * \\brief       Single-call raw encoder\n *\n * \\param       filters     Array of lzma_filter structures. The end of the\n *                          array must be marked with .id = LZMA_VLI_UNKNOWN.\n * \\param       allocator   lzma_allocator for custom allocator functions.\n *                          Set to NULL to use malloc() and free().\n * \\param       in          Beginning of the input buffer\n * \\param       in_size     Size of the input buffer\n * \\param       out         Beginning of the output buffer\n * \\param       out_pos     The next byte will be written to out[*out_pos].\n *                          *out_pos is updated only if encoding succeeds.\n * \\param       out_size    Size of the out buffer; the first byte into\n *                          which no data is written to is out[out_size].\n *\n * \\return      - LZMA_OK: Encoding was successful.\n *              - LZMA_BUF_ERROR: Not enough output buffer space.\n *              - LZMA_OPTIONS_ERROR\n *              - LZMA_MEM_ERROR\n *              - LZMA_DATA_ERROR\n *              - LZMA_PROG_ERROR\n *\n * \\note        There is no function to calculate how big output buffer\n *              would surely be big enough. (lzma_stream_buffer_bound()\n *              works only for lzma_stream_buffer_encode(); raw encoder\n *              won't necessarily meet that bound.)\n */\nextern LZMA_API(lzma_ret) lzma_raw_buffer_encode(\n\t\tconst lzma_filter *filters, const lzma_allocator *allocator,\n\t\tconst uint8_t *in, size_t in_size, uint8_t *out,\n\t\tsize_t *out_pos, size_t out_size) lzma_nothrow;\n\n\n/**\n * \\brief       Single-call raw decoder\n *\n * \\param       filters     Array of lzma_filter structures. The end of the\n *                          array must be marked with .id = LZMA_VLI_UNKNOWN.\n * \\param       allocator   lzma_allocator for custom allocator functions.\n *                          Set to NULL to use malloc() and free().\n * \\param       in          Beginning of the input buffer\n * \\param       in_pos      The next byte will be read from in[*in_pos].\n *                          *in_pos is updated only if decoding succeeds.\n * \\param       in_size     Size of the input buffer; the first byte that\n *                          won't be read is in[in_size].\n * \\param       out         Beginning of the output buffer\n * \\param       out_pos     The next byte will be written to out[*out_pos].\n *                          *out_pos is updated only if encoding succeeds.\n * \\param       out_size    Size of the out buffer; the first byte into\n *                          which no data is written to is out[out_size].\n */\nextern LZMA_API(lzma_ret) lzma_raw_buffer_decode(\n\t\tconst lzma_filter *filters, const lzma_allocator *allocator,\n\t\tconst uint8_t *in, size_t *in_pos, size_t in_size,\n\t\tuint8_t *out, size_t *out_pos, size_t out_size) lzma_nothrow;\n\n\n/**\n * \\brief       Get the size of the Filter Properties field\n *\n * This function may be useful when implementing custom file formats\n * using the raw encoder and decoder.\n *\n * \\param       size    Pointer to uint32_t to hold the size of the properties\n * \\param       filter  Filter ID and options (the size of the properties may\n *                      vary depending on the options)\n *\n * \\return      - LZMA_OK\n *              - LZMA_OPTIONS_ERROR\n *              - LZMA_PROG_ERROR\n *\n * \\note        This function validates the Filter ID, but does not\n *              necessarily validate the options. Thus, it is possible\n *              that this returns LZMA_OK while the following call to\n *              lzma_properties_encode() returns LZMA_OPTIONS_ERROR.\n */\nextern LZMA_API(lzma_ret) lzma_properties_size(\n\t\tuint32_t *size, const lzma_filter *filter) lzma_nothrow;\n\n\n/**\n * \\brief       Encode the Filter Properties field\n *\n * \\param       filter  Filter ID and options\n * \\param       props   Buffer to hold the encoded options. The size of\n *                      buffer must have been already determined with\n *                      lzma_properties_size().\n *\n * \\return      - LZMA_OK\n *              - LZMA_OPTIONS_ERROR\n *              - LZMA_PROG_ERROR\n *\n * \\note        Even this function won't validate more options than actually\n *              necessary. Thus, it is possible that encoding the properties\n *              succeeds but using the same options to initialize the encoder\n *              will fail.\n *\n * \\note        If lzma_properties_size() indicated that the size\n *              of the Filter Properties field is zero, calling\n *              lzma_properties_encode() is not required, but it\n *              won't do any harm either.\n */\nextern LZMA_API(lzma_ret) lzma_properties_encode(\n\t\tconst lzma_filter *filter, uint8_t *props) lzma_nothrow;\n\n\n/**\n * \\brief       Decode the Filter Properties field\n *\n * \\param       filter      filter->id must have been set to the correct\n *                          Filter ID. filter->options doesn't need to be\n *                          initialized (it's not freed by this function). The\n *                          decoded options will be stored in filter->options;\n *                          it's application's responsibility to free it when\n *                          appropriate. filter->options is set to NULL if\n *                          there are no properties or if an error occurs.\n * \\param       allocator   Custom memory allocator used to allocate the\n *                          options. Set to NULL to use the default malloc(),\n *                          and in case of an error, also free().\n * \\param       props       Input buffer containing the properties.\n * \\param       props_size  Size of the properties. This must be the exact\n *                          size; giving too much or too little input will\n *                          return LZMA_OPTIONS_ERROR.\n *\n * \\return      - LZMA_OK\n *              - LZMA_OPTIONS_ERROR\n *              - LZMA_MEM_ERROR\n */\nextern LZMA_API(lzma_ret) lzma_properties_decode(\n\t\tlzma_filter *filter, const lzma_allocator *allocator,\n\t\tconst uint8_t *props, size_t props_size) lzma_nothrow;\n\n\n/**\n * \\brief       Calculate encoded size of a Filter Flags field\n *\n * Knowing the size of Filter Flags is useful to know when allocating\n * memory to hold the encoded Filter Flags.\n *\n * \\param       size    Pointer to integer to hold the calculated size\n * \\param       filter  Filter ID and associated options whose encoded\n *                      size is to be calculated\n *\n * \\return      - LZMA_OK: *size set successfully. Note that this doesn't\n *                guarantee that filter->options is valid, thus\n *                lzma_filter_flags_encode() may still fail.\n *              - LZMA_OPTIONS_ERROR: Unknown Filter ID or unsupported options.\n *              - LZMA_PROG_ERROR: Invalid options\n *\n * \\note        If you need to calculate size of List of Filter Flags,\n *              you need to loop over every lzma_filter entry.\n */\nextern LZMA_API(lzma_ret) lzma_filter_flags_size(\n\t\tuint32_t *size, const lzma_filter *filter)\n\t\tlzma_nothrow lzma_attr_warn_unused_result;\n\n\n/**\n * \\brief       Encode Filter Flags into given buffer\n *\n * In contrast to some functions, this doesn't allocate the needed buffer.\n * This is due to how this function is used internally by liblzma.\n *\n * \\param       filter      Filter ID and options to be encoded\n * \\param       out         Beginning of the output buffer\n * \\param       out_pos     out[*out_pos] is the next write position. This\n *                          is updated by the encoder.\n * \\param       out_size    out[out_size] is the first byte to not write.\n *\n * \\return      - LZMA_OK: Encoding was successful.\n *              - LZMA_OPTIONS_ERROR: Invalid or unsupported options.\n *              - LZMA_PROG_ERROR: Invalid options or not enough output\n *                buffer space (you should have checked it with\n *                lzma_filter_flags_size()).\n */\nextern LZMA_API(lzma_ret) lzma_filter_flags_encode(const lzma_filter *filter,\n\t\tuint8_t *out, size_t *out_pos, size_t out_size)\n\t\tlzma_nothrow lzma_attr_warn_unused_result;\n\n\n/**\n * \\brief       Decode Filter Flags from given buffer\n *\n * The decoded result is stored into *filter. The old value of\n * filter->options is not free()d.\n *\n * \\return      - LZMA_OK\n *              - LZMA_OPTIONS_ERROR\n *              - LZMA_MEM_ERROR\n *              - LZMA_PROG_ERROR\n */\nextern LZMA_API(lzma_ret) lzma_filter_flags_decode(\n\t\tlzma_filter *filter, const lzma_allocator *allocator,\n\t\tconst uint8_t *in, size_t *in_pos, size_t in_size)\n\t\tlzma_nothrow lzma_attr_warn_unused_result;\n"
  },
  {
    "path": "external/xz/liblzma/api/lzma/hardware.h",
    "content": "/**\n * \\file        lzma/hardware.h\n * \\brief       Hardware information\n *\n * Since liblzma can consume a lot of system resources, it also provides\n * ways to limit the resource usage. Applications linking against liblzma\n * need to do the actual decisions how much resources to let liblzma to use.\n * To ease making these decisions, liblzma provides functions to find out\n * the relevant capabilities of the underlying hardware. Currently there\n * is only a function to find out the amount of RAM, but in the future there\n * will be also a function to detect how many concurrent threads the system\n * can run.\n *\n * \\note        On some operating systems, these function may temporarily\n *              load a shared library or open file descriptor(s) to find out\n *              the requested hardware information. Unless the application\n *              assumes that specific file descriptors are not touched by\n *              other threads, this should have no effect on thread safety.\n *              Possible operations involving file descriptors will restart\n *              the syscalls if they return EINTR.\n */\n\n/*\n * Author: Lasse Collin\n *\n * This file has been put into the public domain.\n * You can do whatever you want with this file.\n *\n * See ../lzma.h for information about liblzma as a whole.\n */\n\n#ifndef LZMA_H_INTERNAL\n#\terror Never include this file directly. Use <lzma.h> instead.\n#endif\n\n\n/**\n * \\brief       Get the total amount of physical memory (RAM) in bytes\n *\n * This function may be useful when determining a reasonable memory\n * usage limit for decompressing or how much memory it is OK to use\n * for compressing.\n *\n * \\return      On success, the total amount of physical memory in bytes\n *              is returned. If the amount of RAM cannot be determined,\n *              zero is returned. This can happen if an error occurs\n *              or if there is no code in liblzma to detect the amount\n *              of RAM on the specific operating system.\n */\nextern LZMA_API(uint64_t) lzma_physmem(void) lzma_nothrow;\n\n\n/**\n * \\brief       Get the number of processor cores or threads\n *\n * This function may be useful when determining how many threads to use.\n * If the hardware supports more than one thread per CPU core, the number\n * of hardware threads is returned if that information is available.\n *\n * \\brief       On success, the number of available CPU threads or cores is\n *              returned. If this information isn't available or an error\n *              occurs, zero is returned.\n */\nextern LZMA_API(uint32_t) lzma_cputhreads(void) lzma_nothrow;\n"
  },
  {
    "path": "external/xz/liblzma/api/lzma/index.h",
    "content": "/**\n * \\file        lzma/index.h\n * \\brief       Handling of .xz Index and related information\n */\n\n/*\n * Author: Lasse Collin\n *\n * This file has been put into the public domain.\n * You can do whatever you want with this file.\n *\n * See ../lzma.h for information about liblzma as a whole.\n */\n\n#ifndef LZMA_H_INTERNAL\n#\terror Never include this file directly. Use <lzma.h> instead.\n#endif\n\n\n/**\n * \\brief       Opaque data type to hold the Index(es) and other information\n *\n * lzma_index often holds just one .xz Index and possibly the Stream Flags\n * of the same Stream and size of the Stream Padding field. However,\n * multiple lzma_indexes can be concatenated with lzma_index_cat() and then\n * there may be information about multiple Streams in the same lzma_index.\n *\n * Notes about thread safety: Only one thread may modify lzma_index at\n * a time. All functions that take non-const pointer to lzma_index\n * modify it. As long as no thread is modifying the lzma_index, getting\n * information from the same lzma_index can be done from multiple threads\n * at the same time with functions that take a const pointer to\n * lzma_index or use lzma_index_iter. The same iterator must be used\n * only by one thread at a time, of course, but there can be as many\n * iterators for the same lzma_index as needed.\n */\ntypedef struct lzma_index_s lzma_index;\n\n\n/**\n * \\brief       Iterator to get information about Blocks and Streams\n */\ntypedef struct {\n\tstruct {\n\t\t/**\n\t\t * \\brief       Pointer to Stream Flags\n\t\t *\n\t\t * This is NULL if Stream Flags have not been set for\n\t\t * this Stream with lzma_index_stream_flags().\n\t\t */\n\t\tconst lzma_stream_flags *flags;\n\n\t\tconst void *reserved_ptr1;\n\t\tconst void *reserved_ptr2;\n\t\tconst void *reserved_ptr3;\n\n\t\t/**\n\t\t * \\brief       Stream number in the lzma_index\n\t\t *\n\t\t * The first Stream is 1.\n\t\t */\n\t\tlzma_vli number;\n\n\t\t/**\n\t\t * \\brief       Number of Blocks in the Stream\n\t\t *\n\t\t * If this is zero, the block structure below has\n\t\t * undefined values.\n\t\t */\n\t\tlzma_vli block_count;\n\n\t\t/**\n\t\t * \\brief       Compressed start offset of this Stream\n\t\t *\n\t\t * The offset is relative to the beginning of the lzma_index\n\t\t * (i.e. usually the beginning of the .xz file).\n\t\t */\n\t\tlzma_vli compressed_offset;\n\n\t\t/**\n\t\t * \\brief       Uncompressed start offset of this Stream\n\t\t *\n\t\t * The offset is relative to the beginning of the lzma_index\n\t\t * (i.e. usually the beginning of the .xz file).\n\t\t */\n\t\tlzma_vli uncompressed_offset;\n\n\t\t/**\n\t\t * \\brief       Compressed size of this Stream\n\t\t *\n\t\t * This includes all headers except the possible\n\t\t * Stream Padding after this Stream.\n\t\t */\n\t\tlzma_vli compressed_size;\n\n\t\t/**\n\t\t * \\brief       Uncompressed size of this Stream\n\t\t */\n\t\tlzma_vli uncompressed_size;\n\n\t\t/**\n\t\t * \\brief       Size of Stream Padding after this Stream\n\t\t *\n\t\t * If it hasn't been set with lzma_index_stream_padding(),\n\t\t * this defaults to zero. Stream Padding is always\n\t\t * a multiple of four bytes.\n\t\t */\n\t\tlzma_vli padding;\n\n\t\tlzma_vli reserved_vli1;\n\t\tlzma_vli reserved_vli2;\n\t\tlzma_vli reserved_vli3;\n\t\tlzma_vli reserved_vli4;\n\t} stream;\n\n\tstruct {\n\t\t/**\n\t\t * \\brief       Block number in the file\n\t\t *\n\t\t * The first Block is 1.\n\t\t */\n\t\tlzma_vli number_in_file;\n\n\t\t/**\n\t\t * \\brief       Compressed start offset of this Block\n\t\t *\n\t\t * This offset is relative to the beginning of the\n\t\t * lzma_index (i.e. usually the beginning of the .xz file).\n\t\t * Normally this is where you should seek in the .xz file\n\t\t * to start decompressing this Block.\n\t\t */\n\t\tlzma_vli compressed_file_offset;\n\n\t\t/**\n\t\t * \\brief       Uncompressed start offset of this Block\n\t\t *\n\t\t * This offset is relative to the beginning of the lzma_index\n\t\t * (i.e. usually the beginning of the .xz file).\n\t\t *\n\t\t * When doing random-access reading, it is possible that\n\t\t * the target offset is not exactly at Block boundary. One\n\t\t * will need to compare the target offset against\n\t\t * uncompressed_file_offset or uncompressed_stream_offset,\n\t\t * and possibly decode and throw away some amount of data\n\t\t * before reaching the target offset.\n\t\t */\n\t\tlzma_vli uncompressed_file_offset;\n\n\t\t/**\n\t\t * \\brief       Block number in this Stream\n\t\t *\n\t\t * The first Block is 1.\n\t\t */\n\t\tlzma_vli number_in_stream;\n\n\t\t/**\n\t\t * \\brief       Compressed start offset of this Block\n\t\t *\n\t\t * This offset is relative to the beginning of the Stream\n\t\t * containing this Block.\n\t\t */\n\t\tlzma_vli compressed_stream_offset;\n\n\t\t/**\n\t\t * \\brief       Uncompressed start offset of this Block\n\t\t *\n\t\t * This offset is relative to the beginning of the Stream\n\t\t * containing this Block.\n\t\t */\n\t\tlzma_vli uncompressed_stream_offset;\n\n\t\t/**\n\t\t * \\brief       Uncompressed size of this Block\n\t\t *\n\t\t * You should pass this to the Block decoder if you will\n\t\t * decode this Block. It will allow the Block decoder to\n\t\t * validate the uncompressed size.\n\t\t */\n\t\tlzma_vli uncompressed_size;\n\n\t\t/**\n\t\t * \\brief       Unpadded size of this Block\n\t\t *\n\t\t * You should pass this to the Block decoder if you will\n\t\t * decode this Block. It will allow the Block decoder to\n\t\t * validate the unpadded size.\n\t\t */\n\t\tlzma_vli unpadded_size;\n\n\t\t/**\n\t\t * \\brief       Total compressed size\n\t\t *\n\t\t * This includes all headers and padding in this Block.\n\t\t * This is useful if you need to know how many bytes\n\t\t * the Block decoder will actually read.\n\t\t */\n\t\tlzma_vli total_size;\n\n\t\tlzma_vli reserved_vli1;\n\t\tlzma_vli reserved_vli2;\n\t\tlzma_vli reserved_vli3;\n\t\tlzma_vli reserved_vli4;\n\n\t\tconst void *reserved_ptr1;\n\t\tconst void *reserved_ptr2;\n\t\tconst void *reserved_ptr3;\n\t\tconst void *reserved_ptr4;\n\t} block;\n\n\t/*\n\t * Internal data which is used to store the state of the iterator.\n\t * The exact format may vary between liblzma versions, so don't\n\t * touch these in any way.\n\t */\n\tunion {\n\t\tconst void *p;\n\t\tsize_t s;\n\t\tlzma_vli v;\n\t} internal[6];\n} lzma_index_iter;\n\n\n/**\n * \\brief       Operation mode for lzma_index_iter_next()\n */\ntypedef enum {\n\tLZMA_INDEX_ITER_ANY             = 0,\n\t\t/**<\n\t\t * \\brief       Get the next Block or Stream\n\t\t *\n\t\t * Go to the next Block if the current Stream has at least\n\t\t * one Block left. Otherwise go to the next Stream even if\n\t\t * it has no Blocks. If the Stream has no Blocks\n\t\t * (lzma_index_iter.stream.block_count == 0),\n\t\t * lzma_index_iter.block will have undefined values.\n\t\t */\n\n\tLZMA_INDEX_ITER_STREAM          = 1,\n\t\t/**<\n\t\t * \\brief       Get the next Stream\n\t\t *\n\t\t * Go to the next Stream even if the current Stream has\n\t\t * unread Blocks left. If the next Stream has at least one\n\t\t * Block, the iterator will point to the first Block.\n\t\t * If there are no Blocks, lzma_index_iter.block will have\n\t\t * undefined values.\n\t\t */\n\n\tLZMA_INDEX_ITER_BLOCK           = 2,\n\t\t/**<\n\t\t * \\brief       Get the next Block\n\t\t *\n\t\t * Go to the next Block if the current Stream has at least\n\t\t * one Block left. If the current Stream has no Blocks left,\n\t\t * the next Stream with at least one Block is located and\n\t\t * the iterator will be made to point to the first Block of\n\t\t * that Stream.\n\t\t */\n\n\tLZMA_INDEX_ITER_NONEMPTY_BLOCK  = 3\n\t\t/**<\n\t\t * \\brief       Get the next non-empty Block\n\t\t *\n\t\t * This is like LZMA_INDEX_ITER_BLOCK except that it will\n\t\t * skip Blocks whose Uncompressed Size is zero.\n\t\t */\n\n} lzma_index_iter_mode;\n\n\n/**\n * \\brief       Calculate memory usage of lzma_index\n *\n * On disk, the size of the Index field depends on both the number of Records\n * stored and how big values the Records store (due to variable-length integer\n * encoding). When the Index is kept in lzma_index structure, the memory usage\n * depends only on the number of Records/Blocks stored in the Index(es), and\n * in case of concatenated lzma_indexes, the number of Streams. The size in\n * RAM is almost always significantly bigger than in the encoded form on disk.\n *\n * This function calculates an approximate amount of memory needed hold\n * the given number of Streams and Blocks in lzma_index structure. This\n * value may vary between CPU architectures and also between liblzma versions\n * if the internal implementation is modified.\n */\nextern LZMA_API(uint64_t) lzma_index_memusage(\n\t\tlzma_vli streams, lzma_vli blocks) lzma_nothrow;\n\n\n/**\n * \\brief       Calculate the memory usage of an existing lzma_index\n *\n * This is a shorthand for lzma_index_memusage(lzma_index_stream_count(i),\n * lzma_index_block_count(i)).\n */\nextern LZMA_API(uint64_t) lzma_index_memused(const lzma_index *i)\n\t\tlzma_nothrow;\n\n\n/**\n * \\brief       Allocate and initialize a new lzma_index structure\n *\n * \\return      On success, a pointer to an empty initialized lzma_index is\n *              returned. If allocation fails, NULL is returned.\n */\nextern LZMA_API(lzma_index *) lzma_index_init(const lzma_allocator *allocator)\n\t\tlzma_nothrow;\n\n\n/**\n * \\brief       Deallocate lzma_index\n *\n * If i is NULL, this does nothing.\n */\nextern LZMA_API(void) lzma_index_end(\n\t\tlzma_index *i, const lzma_allocator *allocator) lzma_nothrow;\n\n\n/**\n * \\brief       Add a new Block to lzma_index\n *\n * \\param       i                 Pointer to a lzma_index structure\n * \\param       allocator         Pointer to lzma_allocator, or NULL to\n *                                use malloc()\n * \\param       unpadded_size     Unpadded Size of a Block. This can be\n *                                calculated with lzma_block_unpadded_size()\n *                                after encoding or decoding the Block.\n * \\param       uncompressed_size Uncompressed Size of a Block. This can be\n *                                taken directly from lzma_block structure\n *                                after encoding or decoding the Block.\n *\n * Appending a new Block does not invalidate iterators. For example,\n * if an iterator was pointing to the end of the lzma_index, after\n * lzma_index_append() it is possible to read the next Block with\n * an existing iterator.\n *\n * \\return      - LZMA_OK\n *              - LZMA_MEM_ERROR\n *              - LZMA_DATA_ERROR: Compressed or uncompressed size of the\n *                Stream or size of the Index field would grow too big.\n *              - LZMA_PROG_ERROR\n */\nextern LZMA_API(lzma_ret) lzma_index_append(\n\t\tlzma_index *i, const lzma_allocator *allocator,\n\t\tlzma_vli unpadded_size, lzma_vli uncompressed_size)\n\t\tlzma_nothrow lzma_attr_warn_unused_result;\n\n\n/**\n * \\brief       Set the Stream Flags\n *\n * Set the Stream Flags of the last (and typically the only) Stream\n * in lzma_index. This can be useful when reading information from the\n * lzma_index, because to decode Blocks, knowing the integrity check type\n * is needed.\n *\n * The given Stream Flags are copied into internal preallocated structure\n * in the lzma_index, thus the caller doesn't need to keep the *stream_flags\n * available after calling this function.\n *\n * \\return      - LZMA_OK\n *              - LZMA_OPTIONS_ERROR: Unsupported stream_flags->version.\n *              - LZMA_PROG_ERROR\n */\nextern LZMA_API(lzma_ret) lzma_index_stream_flags(\n\t\tlzma_index *i, const lzma_stream_flags *stream_flags)\n\t\tlzma_nothrow lzma_attr_warn_unused_result;\n\n\n/**\n * \\brief       Get the types of integrity Checks\n *\n * If lzma_index_stream_flags() is used to set the Stream Flags for\n * every Stream, lzma_index_checks() can be used to get a bitmask to\n * indicate which Check types have been used. It can be useful e.g. if\n * showing the Check types to the user.\n *\n * The bitmask is 1 << check_id, e.g. CRC32 is 1 << 1 and SHA-256 is 1 << 10.\n */\nextern LZMA_API(uint32_t) lzma_index_checks(const lzma_index *i)\n\t\tlzma_nothrow lzma_attr_pure;\n\n\n/**\n * \\brief       Set the amount of Stream Padding\n *\n * Set the amount of Stream Padding of the last (and typically the only)\n * Stream in the lzma_index. This is needed when planning to do random-access\n * reading within multiple concatenated Streams.\n *\n * By default, the amount of Stream Padding is assumed to be zero bytes.\n *\n * \\return      - LZMA_OK\n *              - LZMA_DATA_ERROR: The file size would grow too big.\n *              - LZMA_PROG_ERROR\n */\nextern LZMA_API(lzma_ret) lzma_index_stream_padding(\n\t\tlzma_index *i, lzma_vli stream_padding)\n\t\tlzma_nothrow lzma_attr_warn_unused_result;\n\n\n/**\n * \\brief       Get the number of Streams\n */\nextern LZMA_API(lzma_vli) lzma_index_stream_count(const lzma_index *i)\n\t\tlzma_nothrow lzma_attr_pure;\n\n\n/**\n * \\brief       Get the number of Blocks\n *\n * This returns the total number of Blocks in lzma_index. To get number\n * of Blocks in individual Streams, use lzma_index_iter.\n */\nextern LZMA_API(lzma_vli) lzma_index_block_count(const lzma_index *i)\n\t\tlzma_nothrow lzma_attr_pure;\n\n\n/**\n * \\brief       Get the size of the Index field as bytes\n *\n * This is needed to verify the Backward Size field in the Stream Footer.\n */\nextern LZMA_API(lzma_vli) lzma_index_size(const lzma_index *i)\n\t\tlzma_nothrow lzma_attr_pure;\n\n\n/**\n * \\brief       Get the total size of the Stream\n *\n * If multiple lzma_indexes have been combined, this works as if the Blocks\n * were in a single Stream. This is useful if you are going to combine\n * Blocks from multiple Streams into a single new Stream.\n */\nextern LZMA_API(lzma_vli) lzma_index_stream_size(const lzma_index *i)\n\t\tlzma_nothrow lzma_attr_pure;\n\n\n/**\n * \\brief       Get the total size of the Blocks\n *\n * This doesn't include the Stream Header, Stream Footer, Stream Padding,\n * or Index fields.\n */\nextern LZMA_API(lzma_vli) lzma_index_total_size(const lzma_index *i)\n\t\tlzma_nothrow lzma_attr_pure;\n\n\n/**\n * \\brief       Get the total size of the file\n *\n * When no lzma_indexes have been combined with lzma_index_cat() and there is\n * no Stream Padding, this function is identical to lzma_index_stream_size().\n * If multiple lzma_indexes have been combined, this includes also the headers\n * of each separate Stream and the possible Stream Padding fields.\n */\nextern LZMA_API(lzma_vli) lzma_index_file_size(const lzma_index *i)\n\t\tlzma_nothrow lzma_attr_pure;\n\n\n/**\n * \\brief       Get the uncompressed size of the file\n */\nextern LZMA_API(lzma_vli) lzma_index_uncompressed_size(const lzma_index *i)\n\t\tlzma_nothrow lzma_attr_pure;\n\n\n/**\n * \\brief       Initialize an iterator\n *\n * \\param       iter    Pointer to a lzma_index_iter structure\n * \\param       i       lzma_index to which the iterator will be associated\n *\n * This function associates the iterator with the given lzma_index, and calls\n * lzma_index_iter_rewind() on the iterator.\n *\n * This function doesn't allocate any memory, thus there is no\n * lzma_index_iter_end(). The iterator is valid as long as the\n * associated lzma_index is valid, that is, until lzma_index_end() or\n * using it as source in lzma_index_cat(). Specifically, lzma_index doesn't\n * become invalid if new Blocks are added to it with lzma_index_append() or\n * if it is used as the destination in lzma_index_cat().\n *\n * It is safe to make copies of an initialized lzma_index_iter, for example,\n * to easily restart reading at some particular position.\n */\nextern LZMA_API(void) lzma_index_iter_init(\n\t\tlzma_index_iter *iter, const lzma_index *i) lzma_nothrow;\n\n\n/**\n * \\brief       Rewind the iterator\n *\n * Rewind the iterator so that next call to lzma_index_iter_next() will\n * return the first Block or Stream.\n */\nextern LZMA_API(void) lzma_index_iter_rewind(lzma_index_iter *iter)\n\t\tlzma_nothrow;\n\n\n/**\n * \\brief       Get the next Block or Stream\n *\n * \\param       iter    Iterator initialized with lzma_index_iter_init()\n * \\param       mode    Specify what kind of information the caller wants\n *                      to get. See lzma_index_iter_mode for details.\n *\n * \\return      If next Block or Stream matching the mode was found, *iter\n *              is updated and this function returns false. If no Block or\n *              Stream matching the mode is found, *iter is not modified\n *              and this function returns true. If mode is set to an unknown\n *              value, *iter is not modified and this function returns true.\n */\nextern LZMA_API(lzma_bool) lzma_index_iter_next(\n\t\tlzma_index_iter *iter, lzma_index_iter_mode mode)\n\t\tlzma_nothrow lzma_attr_warn_unused_result;\n\n\n/**\n * \\brief       Locate a Block\n *\n * If it is possible to seek in the .xz file, it is possible to parse\n * the Index field(s) and use lzma_index_iter_locate() to do random-access\n * reading with granularity of Block size.\n *\n * \\param       iter    Iterator that was earlier initialized with\n *                      lzma_index_iter_init().\n * \\param       target  Uncompressed target offset which the caller would\n *                      like to locate from the Stream\n *\n * If the target is smaller than the uncompressed size of the Stream (can be\n * checked with lzma_index_uncompressed_size()):\n *  - Information about the Stream and Block containing the requested\n *    uncompressed offset is stored into *iter.\n *  - Internal state of the iterator is adjusted so that\n *    lzma_index_iter_next() can be used to read subsequent Blocks or Streams.\n *  - This function returns false.\n *\n * If target is greater than the uncompressed size of the Stream, *iter\n * is not modified, and this function returns true.\n */\nextern LZMA_API(lzma_bool) lzma_index_iter_locate(\n\t\tlzma_index_iter *iter, lzma_vli target) lzma_nothrow;\n\n\n/**\n * \\brief       Concatenate lzma_indexes\n *\n * Concatenating lzma_indexes is useful when doing random-access reading in\n * multi-Stream .xz file, or when combining multiple Streams into single\n * Stream.\n *\n * \\param       dest      lzma_index after which src is appended\n * \\param       src       lzma_index to be appended after dest. If this\n *                        function succeeds, the memory allocated for src\n *                        is freed or moved to be part of dest, and all\n *                        iterators pointing to src will become invalid.\n * \\param       allocator Custom memory allocator; can be NULL to use\n *                        malloc() and free().\n *\n * \\return      - LZMA_OK: lzma_indexes were concatenated successfully.\n *                src is now a dangling pointer.\n *              - LZMA_DATA_ERROR: *dest would grow too big.\n *              - LZMA_MEM_ERROR\n *              - LZMA_PROG_ERROR\n */\nextern LZMA_API(lzma_ret) lzma_index_cat(lzma_index *dest, lzma_index *src,\n\t\tconst lzma_allocator *allocator)\n\t\tlzma_nothrow lzma_attr_warn_unused_result;\n\n\n/**\n * \\brief       Duplicate lzma_index\n *\n * \\return      A copy of the lzma_index, or NULL if memory allocation failed.\n */\nextern LZMA_API(lzma_index *) lzma_index_dup(\n\t\tconst lzma_index *i, const lzma_allocator *allocator)\n\t\tlzma_nothrow lzma_attr_warn_unused_result;\n\n\n/**\n * \\brief       Initialize .xz Index encoder\n *\n * \\param       strm        Pointer to properly prepared lzma_stream\n * \\param       i           Pointer to lzma_index which should be encoded.\n *\n * The valid `action' values for lzma_code() are LZMA_RUN and LZMA_FINISH.\n * It is enough to use only one of them (you can choose freely).\n *\n * \\return      - LZMA_OK: Initialization succeeded, continue with lzma_code().\n *              - LZMA_MEM_ERROR\n *              - LZMA_PROG_ERROR\n */\nextern LZMA_API(lzma_ret) lzma_index_encoder(\n\t\tlzma_stream *strm, const lzma_index *i)\n\t\tlzma_nothrow lzma_attr_warn_unused_result;\n\n\n/**\n * \\brief       Initialize .xz Index decoder\n *\n * \\param       strm        Pointer to properly prepared lzma_stream\n * \\param       i           The decoded Index will be made available via\n *                          this pointer. Initially this function will\n *                          set *i to NULL (the old value is ignored). If\n *                          decoding succeeds (lzma_code() returns\n *                          LZMA_STREAM_END), *i will be set to point\n *                          to a new lzma_index, which the application\n *                          has to later free with lzma_index_end().\n * \\param       memlimit    How much memory the resulting lzma_index is\n *                          allowed to require. liblzma 5.2.3 and earlier\n *                          don't allow 0 here and return LZMA_PROG_ERROR;\n *                          later versions treat 0 as if 1 had been specified.\n *\n * Valid `action' arguments to lzma_code() are LZMA_RUN and LZMA_FINISH.\n * There is no need to use LZMA_FINISH, but it's allowed because it may\n * simplify certain types of applications.\n *\n * \\return      - LZMA_OK: Initialization succeeded, continue with lzma_code().\n *              - LZMA_MEM_ERROR\n *              - LZMA_PROG_ERROR\n *\n *              liblzma 5.2.3 and older list also LZMA_MEMLIMIT_ERROR here\n *              but that error code has never been possible from this\n *              initialization function.\n */\nextern LZMA_API(lzma_ret) lzma_index_decoder(\n\t\tlzma_stream *strm, lzma_index **i, uint64_t memlimit)\n\t\tlzma_nothrow lzma_attr_warn_unused_result;\n\n\n/**\n * \\brief       Single-call .xz Index encoder\n *\n * \\param       i         lzma_index to be encoded\n * \\param       out       Beginning of the output buffer\n * \\param       out_pos   The next byte will be written to out[*out_pos].\n *                        *out_pos is updated only if encoding succeeds.\n * \\param       out_size  Size of the out buffer; the first byte into\n *                        which no data is written to is out[out_size].\n *\n * \\return      - LZMA_OK: Encoding was successful.\n *              - LZMA_BUF_ERROR: Output buffer is too small. Use\n *                lzma_index_size() to find out how much output\n *                space is needed.\n *              - LZMA_PROG_ERROR\n *\n * \\note        This function doesn't take allocator argument since all\n *              the internal data is allocated on stack.\n */\nextern LZMA_API(lzma_ret) lzma_index_buffer_encode(const lzma_index *i,\n\t\tuint8_t *out, size_t *out_pos, size_t out_size) lzma_nothrow;\n\n\n/**\n * \\brief       Single-call .xz Index decoder\n *\n * \\param       i           If decoding succeeds, *i will point to a new\n *                          lzma_index, which the application has to\n *                          later free with lzma_index_end(). If an error\n *                          occurs, *i will be NULL. The old value of *i\n *                          is always ignored and thus doesn't need to be\n *                          initialized by the caller.\n * \\param       memlimit    Pointer to how much memory the resulting\n *                          lzma_index is allowed to require. The value\n *                          pointed by this pointer is modified if and only\n *                          if LZMA_MEMLIMIT_ERROR is returned.\n * \\param       allocator   Pointer to lzma_allocator, or NULL to use malloc()\n * \\param       in          Beginning of the input buffer\n * \\param       in_pos      The next byte will be read from in[*in_pos].\n *                          *in_pos is updated only if decoding succeeds.\n * \\param       in_size     Size of the input buffer; the first byte that\n *                          won't be read is in[in_size].\n *\n * \\return      - LZMA_OK: Decoding was successful.\n *              - LZMA_MEM_ERROR\n *              - LZMA_MEMLIMIT_ERROR: Memory usage limit was reached.\n *                The minimum required memlimit value was stored to *memlimit.\n *              - LZMA_DATA_ERROR\n *              - LZMA_PROG_ERROR\n */\nextern LZMA_API(lzma_ret) lzma_index_buffer_decode(lzma_index **i,\n\t\tuint64_t *memlimit, const lzma_allocator *allocator,\n\t\tconst uint8_t *in, size_t *in_pos, size_t in_size)\n\t\tlzma_nothrow;\n"
  },
  {
    "path": "external/xz/liblzma/api/lzma/index_hash.h",
    "content": "/**\n * \\file        lzma/index_hash.h\n * \\brief       Validate Index by using a hash function\n *\n * Hashing makes it possible to use constant amount of memory to validate\n * Index of arbitrary size.\n */\n\n/*\n * Author: Lasse Collin\n *\n * This file has been put into the public domain.\n * You can do whatever you want with this file.\n *\n * See ../lzma.h for information about liblzma as a whole.\n */\n\n#ifndef LZMA_H_INTERNAL\n#\terror Never include this file directly. Use <lzma.h> instead.\n#endif\n\n/**\n * \\brief       Opaque data type to hold the Index hash\n */\ntypedef struct lzma_index_hash_s lzma_index_hash;\n\n\n/**\n * \\brief       Allocate and initialize a new lzma_index_hash structure\n *\n * If index_hash is NULL, a new lzma_index_hash structure is allocated,\n * initialized, and a pointer to it returned. If allocation fails, NULL\n * is returned.\n *\n * If index_hash is non-NULL, it is reinitialized and the same pointer\n * returned. In this case, return value cannot be NULL or a different\n * pointer than the index_hash that was given as an argument.\n */\nextern LZMA_API(lzma_index_hash *) lzma_index_hash_init(\n\t\tlzma_index_hash *index_hash, const lzma_allocator *allocator)\n\t\tlzma_nothrow lzma_attr_warn_unused_result;\n\n\n/**\n * \\brief       Deallocate lzma_index_hash structure\n */\nextern LZMA_API(void) lzma_index_hash_end(\n\t\tlzma_index_hash *index_hash, const lzma_allocator *allocator)\n\t\tlzma_nothrow;\n\n\n/**\n * \\brief       Add a new Record to an Index hash\n *\n * \\param       index             Pointer to a lzma_index_hash structure\n * \\param       unpadded_size     Unpadded Size of a Block\n * \\param       uncompressed_size Uncompressed Size of a Block\n *\n * \\return      - LZMA_OK\n *              - LZMA_DATA_ERROR: Compressed or uncompressed size of the\n *                Stream or size of the Index field would grow too big.\n *              - LZMA_PROG_ERROR: Invalid arguments or this function is being\n *                used when lzma_index_hash_decode() has already been used.\n */\nextern LZMA_API(lzma_ret) lzma_index_hash_append(lzma_index_hash *index_hash,\n\t\tlzma_vli unpadded_size, lzma_vli uncompressed_size)\n\t\tlzma_nothrow lzma_attr_warn_unused_result;\n\n\n/**\n * \\brief       Decode and validate the Index field\n *\n * After telling the sizes of all Blocks with lzma_index_hash_append(),\n * the actual Index field is decoded with this function. Specifically,\n * once decoding of the Index field has been started, no more Records\n * can be added using lzma_index_hash_append().\n *\n * This function doesn't use lzma_stream structure to pass the input data.\n * Instead, the input buffer is specified using three arguments. This is\n * because it matches better the internal APIs of liblzma.\n *\n * \\param       index_hash      Pointer to a lzma_index_hash structure\n * \\param       in              Pointer to the beginning of the input buffer\n * \\param       in_pos          in[*in_pos] is the next byte to process\n * \\param       in_size         in[in_size] is the first byte not to process\n *\n * \\return      - LZMA_OK: So far good, but more input is needed.\n *              - LZMA_STREAM_END: Index decoded successfully and it matches\n *                the Records given with lzma_index_hash_append().\n *              - LZMA_DATA_ERROR: Index is corrupt or doesn't match the\n *                information given with lzma_index_hash_append().\n *              - LZMA_BUF_ERROR: Cannot progress because *in_pos >= in_size.\n *              - LZMA_PROG_ERROR\n */\nextern LZMA_API(lzma_ret) lzma_index_hash_decode(lzma_index_hash *index_hash,\n\t\tconst uint8_t *in, size_t *in_pos, size_t in_size)\n\t\tlzma_nothrow lzma_attr_warn_unused_result;\n\n\n/**\n * \\brief       Get the size of the Index field as bytes\n *\n * This is needed to verify the Backward Size field in the Stream Footer.\n */\nextern LZMA_API(lzma_vli) lzma_index_hash_size(\n\t\tconst lzma_index_hash *index_hash)\n\t\tlzma_nothrow lzma_attr_pure;\n"
  },
  {
    "path": "external/xz/liblzma/api/lzma/lzma12.h",
    "content": "/**\n * \\file        lzma/lzma12.h\n * \\brief       LZMA1 and LZMA2 filters\n */\n\n/*\n * Author: Lasse Collin\n *\n * This file has been put into the public domain.\n * You can do whatever you want with this file.\n *\n * See ../lzma.h for information about liblzma as a whole.\n */\n\n#ifndef LZMA_H_INTERNAL\n#\terror Never include this file directly. Use <lzma.h> instead.\n#endif\n\n\n/**\n * \\brief       LZMA1 Filter ID\n *\n * LZMA1 is the very same thing as what was called just LZMA in LZMA Utils,\n * 7-Zip, and LZMA SDK. It's called LZMA1 here to prevent developers from\n * accidentally using LZMA when they actually want LZMA2.\n *\n * LZMA1 shouldn't be used for new applications unless you _really_ know\n * what you are doing. LZMA2 is almost always a better choice.\n */\n#define LZMA_FILTER_LZMA1       LZMA_VLI_C(0x4000000000000001)\n\n/**\n * \\brief       LZMA2 Filter ID\n *\n * Usually you want this instead of LZMA1. Compared to LZMA1, LZMA2 adds\n * support for LZMA_SYNC_FLUSH, uncompressed chunks (smaller expansion\n * when trying to compress uncompressible data), possibility to change\n * lc/lp/pb in the middle of encoding, and some other internal improvements.\n */\n#define LZMA_FILTER_LZMA2       LZMA_VLI_C(0x21)\n\n\n/**\n * \\brief       Match finders\n *\n * Match finder has major effect on both speed and compression ratio.\n * Usually hash chains are faster than binary trees.\n *\n * If you will use LZMA_SYNC_FLUSH often, the hash chains may be a better\n * choice, because binary trees get much higher compression ratio penalty\n * with LZMA_SYNC_FLUSH.\n *\n * The memory usage formulas are only rough estimates, which are closest to\n * reality when dict_size is a power of two. The formulas are  more complex\n * in reality, and can also change a little between liblzma versions. Use\n * lzma_raw_encoder_memusage() to get more accurate estimate of memory usage.\n */\ntypedef enum {\n\tLZMA_MF_HC3     = 0x03,\n\t\t/**<\n\t\t * \\brief       Hash Chain with 2- and 3-byte hashing\n\t\t *\n\t\t * Minimum nice_len: 3\n\t\t *\n\t\t * Memory usage:\n\t\t *  - dict_size <= 16 MiB: dict_size * 7.5\n\t\t *  - dict_size > 16 MiB: dict_size * 5.5 + 64 MiB\n\t\t */\n\n\tLZMA_MF_HC4     = 0x04,\n\t\t/**<\n\t\t * \\brief       Hash Chain with 2-, 3-, and 4-byte hashing\n\t\t *\n\t\t * Minimum nice_len: 4\n\t\t *\n\t\t * Memory usage:\n\t\t *  - dict_size <= 32 MiB: dict_size * 7.5\n\t\t *  - dict_size > 32 MiB: dict_size * 6.5\n\t\t */\n\n\tLZMA_MF_BT2     = 0x12,\n\t\t/**<\n\t\t * \\brief       Binary Tree with 2-byte hashing\n\t\t *\n\t\t * Minimum nice_len: 2\n\t\t *\n\t\t * Memory usage: dict_size * 9.5\n\t\t */\n\n\tLZMA_MF_BT3     = 0x13,\n\t\t/**<\n\t\t * \\brief       Binary Tree with 2- and 3-byte hashing\n\t\t *\n\t\t * Minimum nice_len: 3\n\t\t *\n\t\t * Memory usage:\n\t\t *  - dict_size <= 16 MiB: dict_size * 11.5\n\t\t *  - dict_size > 16 MiB: dict_size * 9.5 + 64 MiB\n\t\t */\n\n\tLZMA_MF_BT4     = 0x14\n\t\t/**<\n\t\t * \\brief       Binary Tree with 2-, 3-, and 4-byte hashing\n\t\t *\n\t\t * Minimum nice_len: 4\n\t\t *\n\t\t * Memory usage:\n\t\t *  - dict_size <= 32 MiB: dict_size * 11.5\n\t\t *  - dict_size > 32 MiB: dict_size * 10.5\n\t\t */\n} lzma_match_finder;\n\n\n/**\n * \\brief       Test if given match finder is supported\n *\n * Return true if the given match finder is supported by this liblzma build.\n * Otherwise false is returned. It is safe to call this with a value that\n * isn't listed in lzma_match_finder enumeration; the return value will be\n * false.\n *\n * There is no way to list which match finders are available in this\n * particular liblzma version and build. It would be useless, because\n * a new match finder, which the application developer wasn't aware,\n * could require giving additional options to the encoder that the older\n * match finders don't need.\n */\nextern LZMA_API(lzma_bool) lzma_mf_is_supported(lzma_match_finder match_finder)\n\t\tlzma_nothrow lzma_attr_const;\n\n\n/**\n * \\brief       Compression modes\n *\n * This selects the function used to analyze the data produced by the match\n * finder.\n */\ntypedef enum {\n\tLZMA_MODE_FAST = 1,\n\t\t/**<\n\t\t * \\brief       Fast compression\n\t\t *\n\t\t * Fast mode is usually at its best when combined with\n\t\t * a hash chain match finder.\n\t\t */\n\n\tLZMA_MODE_NORMAL = 2\n\t\t/**<\n\t\t * \\brief       Normal compression\n\t\t *\n\t\t * This is usually notably slower than fast mode. Use this\n\t\t * together with binary tree match finders to expose the\n\t\t * full potential of the LZMA1 or LZMA2 encoder.\n\t\t */\n} lzma_mode;\n\n\n/**\n * \\brief       Test if given compression mode is supported\n *\n * Return true if the given compression mode is supported by this liblzma\n * build. Otherwise false is returned. It is safe to call this with a value\n * that isn't listed in lzma_mode enumeration; the return value will be false.\n *\n * There is no way to list which modes are available in this particular\n * liblzma version and build. It would be useless, because a new compression\n * mode, which the application developer wasn't aware, could require giving\n * additional options to the encoder that the older modes don't need.\n */\nextern LZMA_API(lzma_bool) lzma_mode_is_supported(lzma_mode mode)\n\t\tlzma_nothrow lzma_attr_const;\n\n\n/**\n * \\brief       Options specific to the LZMA1 and LZMA2 filters\n *\n * Since LZMA1 and LZMA2 share most of the code, it's simplest to share\n * the options structure too. For encoding, all but the reserved variables\n * need to be initialized unless specifically mentioned otherwise.\n * lzma_lzma_preset() can be used to get a good starting point.\n *\n * For raw decoding, both LZMA1 and LZMA2 need dict_size, preset_dict, and\n * preset_dict_size (if preset_dict != NULL). LZMA1 needs also lc, lp, and pb.\n */\ntypedef struct {\n\t/**\n\t * \\brief       Dictionary size in bytes\n\t *\n\t * Dictionary size indicates how many bytes of the recently processed\n\t * uncompressed data is kept in memory. One method to reduce size of\n\t * the uncompressed data is to store distance-length pairs, which\n\t * indicate what data to repeat from the dictionary buffer. Thus,\n\t * the bigger the dictionary, the better the compression ratio\n\t * usually is.\n\t *\n\t * Maximum size of the dictionary depends on multiple things:\n\t *  - Memory usage limit\n\t *  - Available address space (not a problem on 64-bit systems)\n\t *  - Selected match finder (encoder only)\n\t *\n\t * Currently the maximum dictionary size for encoding is 1.5 GiB\n\t * (i.e. (UINT32_C(1) << 30) + (UINT32_C(1) << 29)) even on 64-bit\n\t * systems for certain match finder implementation reasons. In the\n\t * future, there may be match finders that support bigger\n\t * dictionaries.\n\t *\n\t * Decoder already supports dictionaries up to 4 GiB - 1 B (i.e.\n\t * UINT32_MAX), so increasing the maximum dictionary size of the\n\t * encoder won't cause problems for old decoders.\n\t *\n\t * Because extremely small dictionaries sizes would have unneeded\n\t * overhead in the decoder, the minimum dictionary size is 4096 bytes.\n\t *\n\t * \\note        When decoding, too big dictionary does no other harm\n\t *              than wasting memory.\n\t */\n\tuint32_t dict_size;\n#\tdefine LZMA_DICT_SIZE_MIN       UINT32_C(4096)\n#\tdefine LZMA_DICT_SIZE_DEFAULT   (UINT32_C(1) << 23)\n\n\t/**\n\t * \\brief       Pointer to an initial dictionary\n\t *\n\t * It is possible to initialize the LZ77 history window using\n\t * a preset dictionary. It is useful when compressing many\n\t * similar, relatively small chunks of data independently from\n\t * each other. The preset dictionary should contain typical\n\t * strings that occur in the files being compressed. The most\n\t * probable strings should be near the end of the preset dictionary.\n\t *\n\t * This feature should be used only in special situations. For\n\t * now, it works correctly only with raw encoding and decoding.\n\t * Currently none of the container formats supported by\n\t * liblzma allow preset dictionary when decoding, thus if\n\t * you create a .xz or .lzma file with preset dictionary, it\n\t * cannot be decoded with the regular decoder functions. In the\n\t * future, the .xz format will likely get support for preset\n\t * dictionary though.\n\t */\n\tconst uint8_t *preset_dict;\n\n\t/**\n\t * \\brief       Size of the preset dictionary\n\t *\n\t * Specifies the size of the preset dictionary. If the size is\n\t * bigger than dict_size, only the last dict_size bytes are\n\t * processed.\n\t *\n\t * This variable is read only when preset_dict is not NULL.\n\t * If preset_dict is not NULL but preset_dict_size is zero,\n\t * no preset dictionary is used (identical to only setting\n\t * preset_dict to NULL).\n\t */\n\tuint32_t preset_dict_size;\n\n\t/**\n\t * \\brief       Number of literal context bits\n\t *\n\t * How many of the highest bits of the previous uncompressed\n\t * eight-bit byte (also known as `literal') are taken into\n\t * account when predicting the bits of the next literal.\n\t *\n\t * E.g. in typical English text, an upper-case letter is\n\t * often followed by a lower-case letter, and a lower-case\n\t * letter is usually followed by another lower-case letter.\n\t * In the US-ASCII character set, the highest three bits are 010\n\t * for upper-case letters and 011 for lower-case letters.\n\t * When lc is at least 3, the literal coding can take advantage of\n\t * this property in the uncompressed data.\n\t *\n\t * There is a limit that applies to literal context bits and literal\n\t * position bits together: lc + lp <= 4. Without this limit the\n\t * decoding could become very slow, which could have security related\n\t * results in some cases like email servers doing virus scanning.\n\t * This limit also simplifies the internal implementation in liblzma.\n\t *\n\t * There may be LZMA1 streams that have lc + lp > 4 (maximum possible\n\t * lc would be 8). It is not possible to decode such streams with\n\t * liblzma.\n\t */\n\tuint32_t lc;\n#\tdefine LZMA_LCLP_MIN    0\n#\tdefine LZMA_LCLP_MAX    4\n#\tdefine LZMA_LC_DEFAULT  3\n\n\t/**\n\t * \\brief       Number of literal position bits\n\t *\n\t * lp affects what kind of alignment in the uncompressed data is\n\t * assumed when encoding literals. A literal is a single 8-bit byte.\n\t * See pb below for more information about alignment.\n\t */\n\tuint32_t lp;\n#\tdefine LZMA_LP_DEFAULT  0\n\n\t/**\n\t * \\brief       Number of position bits\n\t *\n\t * pb affects what kind of alignment in the uncompressed data is\n\t * assumed in general. The default means four-byte alignment\n\t * (2^ pb =2^2=4), which is often a good choice when there's\n\t * no better guess.\n\t *\n\t * When the alignment is known, setting pb accordingly may reduce\n\t * the file size a little. E.g. with text files having one-byte\n\t * alignment (US-ASCII, ISO-8859-*, UTF-8), setting pb=0 can\n\t * improve compression slightly. For UTF-16 text, pb=1 is a good\n\t * choice. If the alignment is an odd number like 3 bytes, pb=0\n\t * might be the best choice.\n\t *\n\t * Even though the assumed alignment can be adjusted with pb and\n\t * lp, LZMA1 and LZMA2 still slightly favor 16-byte alignment.\n\t * It might be worth taking into account when designing file formats\n\t * that are likely to be often compressed with LZMA1 or LZMA2.\n\t */\n\tuint32_t pb;\n#\tdefine LZMA_PB_MIN      0\n#\tdefine LZMA_PB_MAX      4\n#\tdefine LZMA_PB_DEFAULT  2\n\n\t/** Compression mode */\n\tlzma_mode mode;\n\n\t/**\n\t * \\brief       Nice length of a match\n\t *\n\t * This determines how many bytes the encoder compares from the match\n\t * candidates when looking for the best match. Once a match of at\n\t * least nice_len bytes long is found, the encoder stops looking for\n\t * better candidates and encodes the match. (Naturally, if the found\n\t * match is actually longer than nice_len, the actual length is\n\t * encoded; it's not truncated to nice_len.)\n\t *\n\t * Bigger values usually increase the compression ratio and\n\t * compression time. For most files, 32 to 128 is a good value,\n\t * which gives very good compression ratio at good speed.\n\t *\n\t * The exact minimum value depends on the match finder. The maximum\n\t * is 273, which is the maximum length of a match that LZMA1 and\n\t * LZMA2 can encode.\n\t */\n\tuint32_t nice_len;\n\n\t/** Match finder ID */\n\tlzma_match_finder mf;\n\n\t/**\n\t * \\brief       Maximum search depth in the match finder\n\t *\n\t * For every input byte, match finder searches through the hash chain\n\t * or binary tree in a loop, each iteration going one step deeper in\n\t * the chain or tree. The searching stops if\n\t *  - a match of at least nice_len bytes long is found;\n\t *  - all match candidates from the hash chain or binary tree have\n\t *    been checked; or\n\t *  - maximum search depth is reached.\n\t *\n\t * Maximum search depth is needed to prevent the match finder from\n\t * wasting too much time in case there are lots of short match\n\t * candidates. On the other hand, stopping the search before all\n\t * candidates have been checked can reduce compression ratio.\n\t *\n\t * Setting depth to zero tells liblzma to use an automatic default\n\t * value, that depends on the selected match finder and nice_len.\n\t * The default is in the range [4, 200] or so (it may vary between\n\t * liblzma versions).\n\t *\n\t * Using a bigger depth value than the default can increase\n\t * compression ratio in some cases. There is no strict maximum value,\n\t * but high values (thousands or millions) should be used with care:\n\t * the encoder could remain fast enough with typical input, but\n\t * malicious input could cause the match finder to slow down\n\t * dramatically, possibly creating a denial of service attack.\n\t */\n\tuint32_t depth;\n\n\t/*\n\t * Reserved space to allow possible future extensions without\n\t * breaking the ABI. You should not touch these, because the names\n\t * of these variables may change. These are and will never be used\n\t * with the currently supported options, so it is safe to leave these\n\t * uninitialized.\n\t */\n\tuint32_t reserved_int1;\n\tuint32_t reserved_int2;\n\tuint32_t reserved_int3;\n\tuint32_t reserved_int4;\n\tuint32_t reserved_int5;\n\tuint32_t reserved_int6;\n\tuint32_t reserved_int7;\n\tuint32_t reserved_int8;\n\tlzma_reserved_enum reserved_enum1;\n\tlzma_reserved_enum reserved_enum2;\n\tlzma_reserved_enum reserved_enum3;\n\tlzma_reserved_enum reserved_enum4;\n\tvoid *reserved_ptr1;\n\tvoid *reserved_ptr2;\n\n} lzma_options_lzma;\n\n\n/**\n * \\brief       Set a compression preset to lzma_options_lzma structure\n *\n * 0 is the fastest and 9 is the slowest. These match the switches -0 .. -9\n * of the xz command line tool. In addition, it is possible to bitwise-or\n * flags to the preset. Currently only LZMA_PRESET_EXTREME is supported.\n * The flags are defined in container.h, because the flags are used also\n * with lzma_easy_encoder().\n *\n * The preset values are subject to changes between liblzma versions.\n *\n * This function is available only if LZMA1 or LZMA2 encoder has been enabled\n * when building liblzma.\n *\n * \\return      On success, false is returned. If the preset is not\n *              supported, true is returned.\n */\nextern LZMA_API(lzma_bool) lzma_lzma_preset(\n\t\tlzma_options_lzma *options, uint32_t preset) lzma_nothrow;\n"
  },
  {
    "path": "external/xz/liblzma/api/lzma/stream_flags.h",
    "content": "/**\n * \\file        lzma/stream_flags.h\n * \\brief       .xz Stream Header and Stream Footer encoder and decoder\n */\n\n/*\n * Author: Lasse Collin\n *\n * This file has been put into the public domain.\n * You can do whatever you want with this file.\n *\n * See ../lzma.h for information about liblzma as a whole.\n */\n\n#ifndef LZMA_H_INTERNAL\n#\terror Never include this file directly. Use <lzma.h> instead.\n#endif\n\n\n/**\n * \\brief       Size of Stream Header and Stream Footer\n *\n * Stream Header and Stream Footer have the same size and they are not\n * going to change even if a newer version of the .xz file format is\n * developed in future.\n */\n#define LZMA_STREAM_HEADER_SIZE 12\n\n\n/**\n * \\brief       Options for encoding/decoding Stream Header and Stream Footer\n */\ntypedef struct {\n\t/**\n\t * \\brief       Stream Flags format version\n\t *\n\t * To prevent API and ABI breakages if new features are needed in\n\t * Stream Header or Stream Footer, a version number is used to\n\t * indicate which fields in this structure are in use. For now,\n\t * version must always be zero. With non-zero version, the\n\t * lzma_stream_header_encode() and lzma_stream_footer_encode()\n\t * will return LZMA_OPTIONS_ERROR.\n\t *\n\t * lzma_stream_header_decode() and lzma_stream_footer_decode()\n\t * will always set this to the lowest value that supports all the\n\t * features indicated by the Stream Flags field. The application\n\t * must check that the version number set by the decoding functions\n\t * is supported by the application. Otherwise it is possible that\n\t * the application will decode the Stream incorrectly.\n\t */\n\tuint32_t version;\n\n\t/**\n\t * \\brief       Backward Size\n\t *\n\t * Backward Size must be a multiple of four bytes. In this Stream\n\t * format version, Backward Size is the size of the Index field.\n\t *\n\t * Backward Size isn't actually part of the Stream Flags field, but\n\t * it is convenient to include in this structure anyway. Backward\n\t * Size is present only in the Stream Footer. There is no need to\n\t * initialize backward_size when encoding Stream Header.\n\t *\n\t * lzma_stream_header_decode() always sets backward_size to\n\t * LZMA_VLI_UNKNOWN so that it is convenient to use\n\t * lzma_stream_flags_compare() when both Stream Header and Stream\n\t * Footer have been decoded.\n\t */\n\tlzma_vli backward_size;\n#\tdefine LZMA_BACKWARD_SIZE_MIN 4\n#\tdefine LZMA_BACKWARD_SIZE_MAX (LZMA_VLI_C(1) << 34)\n\n\t/**\n\t * \\brief       Check ID\n\t *\n\t * This indicates the type of the integrity check calculated from\n\t * uncompressed data.\n\t */\n\tlzma_check check;\n\n\t/*\n\t * Reserved space to allow possible future extensions without\n\t * breaking the ABI. You should not touch these, because the\n\t * names of these variables may change.\n\t *\n\t * (We will never be able to use all of these since Stream Flags\n\t * is just two bytes plus Backward Size of four bytes. But it's\n\t * nice to have the proper types when they are needed.)\n\t */\n\tlzma_reserved_enum reserved_enum1;\n\tlzma_reserved_enum reserved_enum2;\n\tlzma_reserved_enum reserved_enum3;\n\tlzma_reserved_enum reserved_enum4;\n\tlzma_bool reserved_bool1;\n\tlzma_bool reserved_bool2;\n\tlzma_bool reserved_bool3;\n\tlzma_bool reserved_bool4;\n\tlzma_bool reserved_bool5;\n\tlzma_bool reserved_bool6;\n\tlzma_bool reserved_bool7;\n\tlzma_bool reserved_bool8;\n\tuint32_t reserved_int1;\n\tuint32_t reserved_int2;\n\n} lzma_stream_flags;\n\n\n/**\n * \\brief       Encode Stream Header\n *\n * \\param       options     Stream Header options to be encoded.\n *                          options->backward_size is ignored and doesn't\n *                          need to be initialized.\n * \\param       out         Beginning of the output buffer of\n *                          LZMA_STREAM_HEADER_SIZE bytes.\n *\n * \\return      - LZMA_OK: Encoding was successful.\n *              - LZMA_OPTIONS_ERROR: options->version is not supported by\n *                this liblzma version.\n *              - LZMA_PROG_ERROR: Invalid options.\n */\nextern LZMA_API(lzma_ret) lzma_stream_header_encode(\n\t\tconst lzma_stream_flags *options, uint8_t *out)\n\t\tlzma_nothrow lzma_attr_warn_unused_result;\n\n\n/**\n * \\brief       Encode Stream Footer\n *\n * \\param       options     Stream Footer options to be encoded.\n * \\param       out         Beginning of the output buffer of\n *                          LZMA_STREAM_HEADER_SIZE bytes.\n *\n * \\return      - LZMA_OK: Encoding was successful.\n *              - LZMA_OPTIONS_ERROR: options->version is not supported by\n *                this liblzma version.\n *              - LZMA_PROG_ERROR: Invalid options.\n */\nextern LZMA_API(lzma_ret) lzma_stream_footer_encode(\n\t\tconst lzma_stream_flags *options, uint8_t *out)\n\t\tlzma_nothrow lzma_attr_warn_unused_result;\n\n\n/**\n * \\brief       Decode Stream Header\n *\n * \\param       options     Target for the decoded Stream Header options.\n * \\param       in          Beginning of the input buffer of\n *                          LZMA_STREAM_HEADER_SIZE bytes.\n *\n * options->backward_size is always set to LZMA_VLI_UNKNOWN. This is to\n * help comparing Stream Flags from Stream Header and Stream Footer with\n * lzma_stream_flags_compare().\n *\n * \\return      - LZMA_OK: Decoding was successful.\n *              - LZMA_FORMAT_ERROR: Magic bytes don't match, thus the given\n *                buffer cannot be Stream Header.\n *              - LZMA_DATA_ERROR: CRC32 doesn't match, thus the header\n *                is corrupt.\n *              - LZMA_OPTIONS_ERROR: Unsupported options are present\n *                in the header.\n *\n * \\note        When decoding .xz files that contain multiple Streams, it may\n *              make sense to print \"file format not recognized\" only if\n *              decoding of the Stream Header of the _first_ Stream gives\n *              LZMA_FORMAT_ERROR. If non-first Stream Header gives\n *              LZMA_FORMAT_ERROR, the message used for LZMA_DATA_ERROR is\n *              probably more appropriate.\n *\n *              For example, Stream decoder in liblzma uses LZMA_DATA_ERROR if\n *              LZMA_FORMAT_ERROR is returned by lzma_stream_header_decode()\n *              when decoding non-first Stream.\n */\nextern LZMA_API(lzma_ret) lzma_stream_header_decode(\n\t\tlzma_stream_flags *options, const uint8_t *in)\n\t\tlzma_nothrow lzma_attr_warn_unused_result;\n\n\n/**\n * \\brief       Decode Stream Footer\n *\n * \\param       options     Target for the decoded Stream Header options.\n * \\param       in          Beginning of the input buffer of\n *                          LZMA_STREAM_HEADER_SIZE bytes.\n *\n * \\return      - LZMA_OK: Decoding was successful.\n *              - LZMA_FORMAT_ERROR: Magic bytes don't match, thus the given\n *                buffer cannot be Stream Footer.\n *              - LZMA_DATA_ERROR: CRC32 doesn't match, thus the Stream Footer\n *                is corrupt.\n *              - LZMA_OPTIONS_ERROR: Unsupported options are present\n *                in Stream Footer.\n *\n * \\note        If Stream Header was already decoded successfully, but\n *              decoding Stream Footer returns LZMA_FORMAT_ERROR, the\n *              application should probably report some other error message\n *              than \"file format not recognized\", since the file more likely\n *              is corrupt (possibly truncated). Stream decoder in liblzma\n *              uses LZMA_DATA_ERROR in this situation.\n */\nextern LZMA_API(lzma_ret) lzma_stream_footer_decode(\n\t\tlzma_stream_flags *options, const uint8_t *in)\n\t\tlzma_nothrow lzma_attr_warn_unused_result;\n\n\n/**\n * \\brief       Compare two lzma_stream_flags structures\n *\n * backward_size values are compared only if both are not\n * LZMA_VLI_UNKNOWN.\n *\n * \\return      - LZMA_OK: Both are equal. If either had backward_size set\n *                to LZMA_VLI_UNKNOWN, backward_size values were not\n *                compared or validated.\n *              - LZMA_DATA_ERROR: The structures differ.\n *              - LZMA_OPTIONS_ERROR: version in either structure is greater\n *                than the maximum supported version (currently zero).\n *              - LZMA_PROG_ERROR: Invalid value, e.g. invalid check or\n *                backward_size.\n */\nextern LZMA_API(lzma_ret) lzma_stream_flags_compare(\n\t\tconst lzma_stream_flags *a, const lzma_stream_flags *b)\n\t\tlzma_nothrow lzma_attr_pure;\n"
  },
  {
    "path": "external/xz/liblzma/api/lzma/version.h",
    "content": "/**\n * \\file        lzma/version.h\n * \\brief       Version number\n */\n\n/*\n * Author: Lasse Collin\n *\n * This file has been put into the public domain.\n * You can do whatever you want with this file.\n *\n * See ../lzma.h for information about liblzma as a whole.\n */\n\n#ifndef LZMA_H_INTERNAL\n#\terror Never include this file directly. Use <lzma.h> instead.\n#endif\n\n\n/*\n * Version number split into components\n */\n#define LZMA_VERSION_MAJOR 5\n#define LZMA_VERSION_MINOR 2\n#define LZMA_VERSION_PATCH 5\n#define LZMA_VERSION_STABILITY LZMA_VERSION_STABILITY_STABLE\n\n#ifndef LZMA_VERSION_COMMIT\n#\tdefine LZMA_VERSION_COMMIT \"\"\n#endif\n\n\n/*\n * Map symbolic stability levels to integers.\n */\n#define LZMA_VERSION_STABILITY_ALPHA 0\n#define LZMA_VERSION_STABILITY_BETA 1\n#define LZMA_VERSION_STABILITY_STABLE 2\n\n\n/**\n * \\brief       Compile-time version number\n *\n * The version number is of format xyyyzzzs where\n *  - x = major\n *  - yyy = minor\n *  - zzz = revision\n *  - s indicates stability: 0 = alpha, 1 = beta, 2 = stable\n *\n * The same xyyyzzz triplet is never reused with different stability levels.\n * For example, if 5.1.0alpha has been released, there will never be 5.1.0beta\n * or 5.1.0 stable.\n *\n * \\note        The version number of liblzma has nothing to with\n *              the version number of Igor Pavlov's LZMA SDK.\n */\n#define LZMA_VERSION (LZMA_VERSION_MAJOR * UINT32_C(10000000) \\\n\t\t+ LZMA_VERSION_MINOR * UINT32_C(10000) \\\n\t\t+ LZMA_VERSION_PATCH * UINT32_C(10) \\\n\t\t+ LZMA_VERSION_STABILITY)\n\n\n/*\n * Macros to construct the compile-time version string\n */\n#if LZMA_VERSION_STABILITY == LZMA_VERSION_STABILITY_ALPHA\n#\tdefine LZMA_VERSION_STABILITY_STRING \"alpha\"\n#elif LZMA_VERSION_STABILITY == LZMA_VERSION_STABILITY_BETA\n#\tdefine LZMA_VERSION_STABILITY_STRING \"beta\"\n#elif LZMA_VERSION_STABILITY == LZMA_VERSION_STABILITY_STABLE\n#\tdefine LZMA_VERSION_STABILITY_STRING \"\"\n#else\n#\terror Incorrect LZMA_VERSION_STABILITY\n#endif\n\n#define LZMA_VERSION_STRING_C_(major, minor, patch, stability, commit) \\\n\t\t#major \".\" #minor \".\" #patch stability commit\n\n#define LZMA_VERSION_STRING_C(major, minor, patch, stability, commit) \\\n\t\tLZMA_VERSION_STRING_C_(major, minor, patch, stability, commit)\n\n\n/**\n * \\brief       Compile-time version as a string\n *\n * This can be for example \"4.999.5alpha\", \"4.999.8beta\", or \"5.0.0\" (stable\n * versions don't have any \"stable\" suffix). In future, a snapshot built\n * from source code repository may include an additional suffix, for example\n * \"4.999.8beta-21-g1d92\". The commit ID won't be available in numeric form\n * in LZMA_VERSION macro.\n */\n#define LZMA_VERSION_STRING LZMA_VERSION_STRING_C( \\\n\t\tLZMA_VERSION_MAJOR, LZMA_VERSION_MINOR, \\\n\t\tLZMA_VERSION_PATCH, LZMA_VERSION_STABILITY_STRING, \\\n\t\tLZMA_VERSION_COMMIT)\n\n\n/* #ifndef is needed for use with windres (MinGW or Cygwin). */\n#ifndef LZMA_H_INTERNAL_RC\n\n/**\n * \\brief       Run-time version number as an integer\n *\n * Return the value of LZMA_VERSION macro at the compile time of liblzma.\n * This allows the application to compare if it was built against the same,\n * older, or newer version of liblzma that is currently running.\n */\nextern LZMA_API(uint32_t) lzma_version_number(void)\n\t\tlzma_nothrow lzma_attr_const;\n\n\n/**\n * \\brief       Run-time version as a string\n *\n * This function may be useful if you want to display which version of\n * liblzma your application is currently using.\n */\nextern LZMA_API(const char *) lzma_version_string(void)\n\t\tlzma_nothrow lzma_attr_const;\n\n#endif\n"
  },
  {
    "path": "external/xz/liblzma/api/lzma/vli.h",
    "content": "/**\n * \\file        lzma/vli.h\n * \\brief       Variable-length integer handling\n *\n * In the .xz format, most integers are encoded in a variable-length\n * representation, which is sometimes called little endian base-128 encoding.\n * This saves space when smaller values are more likely than bigger values.\n *\n * The encoding scheme encodes seven bits to every byte, using minimum\n * number of bytes required to represent the given value. Encodings that use\n * non-minimum number of bytes are invalid, thus every integer has exactly\n * one encoded representation. The maximum number of bits in a VLI is 63,\n * thus the vli argument must be less than or equal to UINT64_MAX / 2. You\n * should use LZMA_VLI_MAX for clarity.\n */\n\n/*\n * Author: Lasse Collin\n *\n * This file has been put into the public domain.\n * You can do whatever you want with this file.\n *\n * See ../lzma.h for information about liblzma as a whole.\n */\n\n#ifndef LZMA_H_INTERNAL\n#\terror Never include this file directly. Use <lzma.h> instead.\n#endif\n\n\n/**\n * \\brief       Maximum supported value of a variable-length integer\n */\n#define LZMA_VLI_MAX (UINT64_MAX / 2)\n\n/**\n * \\brief       VLI value to denote that the value is unknown\n */\n#define LZMA_VLI_UNKNOWN UINT64_MAX\n\n/**\n * \\brief       Maximum supported encoded length of variable length integers\n */\n#define LZMA_VLI_BYTES_MAX 9\n\n/**\n * \\brief       VLI constant suffix\n */\n#define LZMA_VLI_C(n) UINT64_C(n)\n\n\n/**\n * \\brief       Variable-length integer type\n *\n * Valid VLI values are in the range [0, LZMA_VLI_MAX]. Unknown value is\n * indicated with LZMA_VLI_UNKNOWN, which is the maximum value of the\n * underlying integer type.\n *\n * lzma_vli will be uint64_t for the foreseeable future. If a bigger size\n * is needed in the future, it is guaranteed that 2 * LZMA_VLI_MAX will\n * not overflow lzma_vli. This simplifies integer overflow detection.\n */\ntypedef uint64_t lzma_vli;\n\n\n/**\n * \\brief       Validate a variable-length integer\n *\n * This is useful to test that application has given acceptable values\n * for example in the uncompressed_size and compressed_size variables.\n *\n * \\return      True if the integer is representable as VLI or if it\n *              indicates unknown value.\n */\n#define lzma_vli_is_valid(vli) \\\n\t((vli) <= LZMA_VLI_MAX || (vli) == LZMA_VLI_UNKNOWN)\n\n\n/**\n * \\brief       Encode a variable-length integer\n *\n * This function has two modes: single-call and multi-call. Single-call mode\n * encodes the whole integer at once; it is an error if the output buffer is\n * too small. Multi-call mode saves the position in *vli_pos, and thus it is\n * possible to continue encoding if the buffer becomes full before the whole\n * integer has been encoded.\n *\n * \\param       vli       Integer to be encoded\n * \\param       vli_pos   How many VLI-encoded bytes have already been written\n *                        out. When starting to encode a new integer in\n *                        multi-call mode, *vli_pos must be set to zero.\n *                        To use single-call encoding, set vli_pos to NULL.\n * \\param       out       Beginning of the output buffer\n * \\param       out_pos   The next byte will be written to out[*out_pos].\n * \\param       out_size  Size of the out buffer; the first byte into\n *                        which no data is written to is out[out_size].\n *\n * \\return      Slightly different return values are used in multi-call and\n *              single-call modes.\n *\n *              Single-call (vli_pos == NULL):\n *              - LZMA_OK: Integer successfully encoded.\n *              - LZMA_PROG_ERROR: Arguments are not sane. This can be due\n *                to too little output space; single-call mode doesn't use\n *                LZMA_BUF_ERROR, since the application should have checked\n *                the encoded size with lzma_vli_size().\n *\n *              Multi-call (vli_pos != NULL):\n *              - LZMA_OK: So far all OK, but the integer is not\n *                completely written out yet.\n *              - LZMA_STREAM_END: Integer successfully encoded.\n *              - LZMA_BUF_ERROR: No output space was provided.\n *              - LZMA_PROG_ERROR: Arguments are not sane.\n */\nextern LZMA_API(lzma_ret) lzma_vli_encode(lzma_vli vli, size_t *vli_pos,\n\t\tuint8_t *out, size_t *out_pos, size_t out_size) lzma_nothrow;\n\n\n/**\n * \\brief       Decode a variable-length integer\n *\n * Like lzma_vli_encode(), this function has single-call and multi-call modes.\n *\n * \\param       vli       Pointer to decoded integer. The decoder will\n *                        initialize it to zero when *vli_pos == 0, so\n *                        application isn't required to initialize *vli.\n * \\param       vli_pos   How many bytes have already been decoded. When\n *                        starting to decode a new integer in multi-call\n *                        mode, *vli_pos must be initialized to zero. To\n *                        use single-call decoding, set vli_pos to NULL.\n * \\param       in        Beginning of the input buffer\n * \\param       in_pos    The next byte will be read from in[*in_pos].\n * \\param       in_size   Size of the input buffer; the first byte that\n *                        won't be read is in[in_size].\n *\n * \\return      Slightly different return values are used in multi-call and\n *              single-call modes.\n *\n *              Single-call (vli_pos == NULL):\n *              - LZMA_OK: Integer successfully decoded.\n *              - LZMA_DATA_ERROR: Integer is corrupt. This includes hitting\n *                the end of the input buffer before the whole integer was\n *                decoded; providing no input at all will use LZMA_DATA_ERROR.\n *              - LZMA_PROG_ERROR: Arguments are not sane.\n *\n *              Multi-call (vli_pos != NULL):\n *              - LZMA_OK: So far all OK, but the integer is not\n *                completely decoded yet.\n *              - LZMA_STREAM_END: Integer successfully decoded.\n *              - LZMA_DATA_ERROR: Integer is corrupt.\n *              - LZMA_BUF_ERROR: No input was provided.\n *              - LZMA_PROG_ERROR: Arguments are not sane.\n */\nextern LZMA_API(lzma_ret) lzma_vli_decode(lzma_vli *vli, size_t *vli_pos,\n\t\tconst uint8_t *in, size_t *in_pos, size_t in_size)\n\t\tlzma_nothrow;\n\n\n/**\n * \\brief       Get the number of bytes required to encode a VLI\n *\n * \\return      Number of bytes on success (1-9). If vli isn't valid,\n *              zero is returned.\n */\nextern LZMA_API(uint32_t) lzma_vli_size(lzma_vli vli)\n\t\tlzma_nothrow lzma_attr_pure;\n"
  },
  {
    "path": "external/xz/liblzma/api/lzma.h",
    "content": "/**\n * \\file        api/lzma.h\n * \\brief       The public API of liblzma data compression library\n *\n * liblzma is a public domain general-purpose data compression library with\n * a zlib-like API. The native file format is .xz, but also the old .lzma\n * format and raw (no headers) streams are supported. Multiple compression\n * algorithms (filters) are supported. Currently LZMA2 is the primary filter.\n *\n * liblzma is part of XZ Utils <http://tukaani.org/xz/>. XZ Utils includes\n * a gzip-like command line tool named xz and some other tools. XZ Utils\n * is developed and maintained by Lasse Collin.\n *\n * Major parts of liblzma are based on Igor Pavlov's public domain LZMA SDK\n * <http://7-zip.org/sdk.html>.\n *\n * The SHA-256 implementation is based on the public domain code found from\n * 7-Zip <http://7-zip.org/>, which has a modified version of the public\n * domain SHA-256 code found from Crypto++ <http://www.cryptopp.com/>.\n * The SHA-256 code in Crypto++ was written by Kevin Springle and Wei Dai.\n */\n\n/*\n * Author: Lasse Collin\n *\n * This file has been put into the public domain.\n * You can do whatever you want with this file.\n */\n\n#ifndef LZMA_H\n#define LZMA_H\n\n/*****************************\n * Required standard headers *\n *****************************/\n\n/*\n * liblzma API headers need some standard types and macros. To allow\n * including lzma.h without requiring the application to include other\n * headers first, lzma.h includes the required standard headers unless\n * they already seem to be included already or if LZMA_MANUAL_HEADERS\n * has been defined.\n *\n * Here's what types and macros are needed and from which headers:\n *  - stddef.h: size_t, NULL\n *  - stdint.h: uint8_t, uint32_t, uint64_t, UINT32_C(n), uint64_C(n),\n *    UINT32_MAX, UINT64_MAX\n *\n * However, inttypes.h is a little more portable than stdint.h, although\n * inttypes.h declares some unneeded things compared to plain stdint.h.\n *\n * The hacks below aren't perfect, specifically they assume that inttypes.h\n * exists and that it typedefs at least uint8_t, uint32_t, and uint64_t,\n * and that, in case of incomplete inttypes.h, unsigned int is 32-bit.\n * If the application already takes care of setting up all the types and\n * macros properly (for example by using gnulib's stdint.h or inttypes.h),\n * we try to detect that the macros are already defined and don't include\n * inttypes.h here again. However, you may define LZMA_MANUAL_HEADERS to\n * force this file to never include any system headers.\n *\n * Some could argue that liblzma API should provide all the required types,\n * for example lzma_uint64, LZMA_UINT64_C(n), and LZMA_UINT64_MAX. This was\n * seen as an unnecessary mess, since most systems already provide all the\n * necessary types and macros in the standard headers.\n *\n * Note that liblzma API still has lzma_bool, because using stdbool.h would\n * break C89 and C++ programs on many systems. sizeof(bool) in C99 isn't\n * necessarily the same as sizeof(bool) in C++.\n */\n\n#ifndef LZMA_MANUAL_HEADERS\n\t/*\n\t * I suppose this works portably also in C++. Note that in C++,\n\t * we need to get size_t into the global namespace.\n\t */\n#\tinclude <stddef.h>\n\n\t/*\n\t * Skip inttypes.h if we already have all the required macros. If we\n\t * have the macros, we assume that we have the matching typedefs too.\n\t */\n#\tif !defined(UINT32_C) || !defined(UINT64_C) \\\n\t\t\t|| !defined(UINT32_MAX) || !defined(UINT64_MAX)\n\t\t/*\n\t\t * MSVC versions older than 2013 have no C99 support, and\n\t\t * thus they cannot be used to compile liblzma. Using an\n\t\t * existing liblzma.dll with old MSVC can work though(*),\n\t\t * but we need to define the required standard integer\n\t\t * types here in a MSVC-specific way.\n\t\t *\n\t\t * (*) If you do this, the existing liblzma.dll probably uses\n\t\t *     a different runtime library than your MSVC-built\n\t\t *     application. Mixing runtimes is generally bad, but\n\t\t *     in this case it should work as long as you avoid\n\t\t *     the few rarely-needed liblzma functions that allocate\n\t\t *     memory and expect the caller to free it using free().\n\t\t */\n#\t\tif defined(_WIN32) && defined(_MSC_VER) && _MSC_VER < 1800\n\t\t\ttypedef unsigned __int8 uint8_t;\n\t\t\ttypedef unsigned __int32 uint32_t;\n\t\t\ttypedef unsigned __int64 uint64_t;\n#\t\telse\n\t\t\t/* Use the standard inttypes.h. */\n#\t\t\tifdef __cplusplus\n\t\t\t\t/*\n\t\t\t\t * C99 sections 7.18.2 and 7.18.4 specify\n\t\t\t\t * that C++ implementations define the limit\n\t\t\t\t * and constant macros only if specifically\n\t\t\t\t * requested. Note that if you want the\n\t\t\t\t * format macros (PRIu64 etc.) too, you need\n\t\t\t\t * to define __STDC_FORMAT_MACROS before\n\t\t\t\t * including lzma.h, since re-including\n\t\t\t\t * inttypes.h with __STDC_FORMAT_MACROS\n\t\t\t\t * defined doesn't necessarily work.\n\t\t\t\t */\n#\t\t\t\tifndef __STDC_LIMIT_MACROS\n#\t\t\t\t\tdefine __STDC_LIMIT_MACROS 1\n#\t\t\t\tendif\n#\t\t\t\tifndef __STDC_CONSTANT_MACROS\n#\t\t\t\t\tdefine __STDC_CONSTANT_MACROS 1\n#\t\t\t\tendif\n#\t\t\tendif\n\n#\t\t\tinclude <inttypes.h>\n#\t\tendif\n\n\t\t/*\n\t\t * Some old systems have only the typedefs in inttypes.h, and\n\t\t * lack all the macros. For those systems, we need a few more\n\t\t * hacks. We assume that unsigned int is 32-bit and unsigned\n\t\t * long is either 32-bit or 64-bit. If these hacks aren't\n\t\t * enough, the application has to setup the types manually\n\t\t * before including lzma.h.\n\t\t */\n#\t\tifndef UINT32_C\n#\t\t\tif defined(_WIN32) && defined(_MSC_VER)\n#\t\t\t\tdefine UINT32_C(n) n ## UI32\n#\t\t\telse\n#\t\t\t\tdefine UINT32_C(n) n ## U\n#\t\t\tendif\n#\t\tendif\n\n#\t\tifndef UINT64_C\n#\t\t\tif defined(_WIN32) && defined(_MSC_VER)\n#\t\t\t\tdefine UINT64_C(n) n ## UI64\n#\t\t\telse\n\t\t\t\t/* Get ULONG_MAX. */\n#\t\t\t\tinclude <limits.h>\n#\t\t\t\tif ULONG_MAX == 4294967295UL\n#\t\t\t\t\tdefine UINT64_C(n) n ## ULL\n#\t\t\t\telse\n#\t\t\t\t\tdefine UINT64_C(n) n ## UL\n#\t\t\t\tendif\n#\t\t\tendif\n#\t\tendif\n\n#\t\tifndef UINT32_MAX\n#\t\t\tdefine UINT32_MAX (UINT32_C(4294967295))\n#\t\tendif\n\n#\t\tifndef UINT64_MAX\n#\t\t\tdefine UINT64_MAX (UINT64_C(18446744073709551615))\n#\t\tendif\n#\tendif\n#endif /* ifdef LZMA_MANUAL_HEADERS */\n\n\n/******************\n * LZMA_API macro *\n ******************/\n\n/*\n * Some systems require that the functions and function pointers are\n * declared specially in the headers. LZMA_API_IMPORT is for importing\n * symbols and LZMA_API_CALL is to specify the calling convention.\n *\n * By default it is assumed that the application will link dynamically\n * against liblzma. #define LZMA_API_STATIC in your application if you\n * want to link against static liblzma. If you don't care about portability\n * to operating systems like Windows, or at least don't care about linking\n * against static liblzma on them, don't worry about LZMA_API_STATIC. That\n * is, most developers will never need to use LZMA_API_STATIC.\n *\n * The GCC variants are a special case on Windows (Cygwin and MinGW).\n * We rely on GCC doing the right thing with its auto-import feature,\n * and thus don't use __declspec(dllimport). This way developers don't\n * need to worry about LZMA_API_STATIC. Also the calling convention is\n * omitted on Cygwin but not on MinGW.\n */\n#ifndef LZMA_API_IMPORT\n#\tif !defined(LZMA_API_STATIC) && defined(_WIN32) && !defined(__GNUC__)\n#\t\tdefine LZMA_API_IMPORT __declspec(dllimport)\n#\telse\n#\t\tdefine LZMA_API_IMPORT\n#\tendif\n#endif\n\n#ifndef LZMA_API_CALL\n#\tif defined(_WIN32) && !defined(__CYGWIN__)\n#\t\tdefine LZMA_API_CALL __cdecl\n#\telse\n#\t\tdefine LZMA_API_CALL\n#\tendif\n#endif\n\n#ifndef LZMA_API\n#\tdefine LZMA_API(type) LZMA_API_IMPORT type LZMA_API_CALL\n#endif\n\n\n/***********\n * nothrow *\n ***********/\n\n/*\n * None of the functions in liblzma may throw an exception. Even\n * the functions that use callback functions won't throw exceptions,\n * because liblzma would break if a callback function threw an exception.\n */\n#ifndef lzma_nothrow\n#\tif defined(__cplusplus)\n#\t\tif __cplusplus >= 201103L\n#\t\t\tdefine lzma_nothrow noexcept\n#\t\telse\n#\t\t\tdefine lzma_nothrow throw()\n#\t\tendif\n#\telif defined(__GNUC__) && (__GNUC__ > 3 \\\n\t\t\t|| (__GNUC__ == 3 && __GNUC_MINOR__ >= 3))\n#\t\tdefine lzma_nothrow __attribute__((__nothrow__))\n#\telse\n#\t\tdefine lzma_nothrow\n#\tendif\n#endif\n\n\n/********************\n * GNU C extensions *\n ********************/\n\n/*\n * GNU C extensions are used conditionally in the public API. It doesn't\n * break anything if these are sometimes enabled and sometimes not, only\n * affects warnings and optimizations.\n */\n#if defined(__GNUC__) && __GNUC__ >= 3\n#\tifndef lzma_attribute\n#\t\tdefine lzma_attribute(attr) __attribute__(attr)\n#\tendif\n\n\t/* warn_unused_result was added in GCC 3.4. */\n#\tifndef lzma_attr_warn_unused_result\n#\t\tif __GNUC__ == 3 && __GNUC_MINOR__ < 4\n#\t\t\tdefine lzma_attr_warn_unused_result\n#\t\tendif\n#\tendif\n\n#else\n#\tifndef lzma_attribute\n#\t\tdefine lzma_attribute(attr)\n#\tendif\n#endif\n\n\n#ifndef lzma_attr_pure\n#\tdefine lzma_attr_pure lzma_attribute((__pure__))\n#endif\n\n#ifndef lzma_attr_const\n#\tdefine lzma_attr_const lzma_attribute((__const__))\n#endif\n\n#ifndef lzma_attr_warn_unused_result\n#\tdefine lzma_attr_warn_unused_result \\\n\t\tlzma_attribute((__warn_unused_result__))\n#endif\n\n\n/**************\n * Subheaders *\n **************/\n\n#ifdef __cplusplus\nextern \"C\" {\n#endif\n\n/*\n * Subheaders check that this is defined. It is to prevent including\n * them directly from applications.\n */\n#define LZMA_H_INTERNAL 1\n\n/* Basic features */\n#include \"lzma/version.h\"\n#include \"lzma/base.h\"\n#include \"lzma/vli.h\"\n#include \"lzma/check.h\"\n\n/* Filters */\n#include \"lzma/filter.h\"\n#include \"lzma/bcj.h\"\n#include \"lzma/delta.h\"\n#include \"lzma/lzma12.h\"\n\n/* Container formats */\n#include \"lzma/container.h\"\n\n/* Advanced features */\n#include \"lzma/stream_flags.h\"\n#include \"lzma/block.h\"\n#include \"lzma/index.h\"\n#include \"lzma/index_hash.h\"\n\n/* Hardware information */\n#include \"lzma/hardware.h\"\n\n/*\n * All subheaders included. Undefine LZMA_H_INTERNAL to prevent applications\n * re-including the subheaders.\n */\n#undef LZMA_H_INTERNAL\n\n#ifdef __cplusplus\n}\n#endif\n\n#endif /* ifndef LZMA_H */\n"
  },
  {
    "path": "external/xz/liblzma/check/check.c",
    "content": "///////////////////////////////////////////////////////////////////////////////\n//\n/// \\file       check.c\n/// \\brief      Single API to access different integrity checks\n//\n//  Author:     Lasse Collin\n//\n//  This file has been put into the public domain.\n//  You can do whatever you want with this file.\n//\n///////////////////////////////////////////////////////////////////////////////\n\n#include \"check.h\"\n\n\nextern LZMA_API(lzma_bool)\nlzma_check_is_supported(lzma_check type)\n{\n\tif ((unsigned int)(type) > LZMA_CHECK_ID_MAX)\n\t\treturn false;\n\n\tstatic const lzma_bool available_checks[LZMA_CHECK_ID_MAX + 1] = {\n\t\ttrue,   // LZMA_CHECK_NONE\n\n#ifdef HAVE_CHECK_CRC32\n\t\ttrue,\n#else\n\t\tfalse,\n#endif\n\n\t\tfalse,  // Reserved\n\t\tfalse,  // Reserved\n\n#ifdef HAVE_CHECK_CRC64\n\t\ttrue,\n#else\n\t\tfalse,\n#endif\n\n\t\tfalse,  // Reserved\n\t\tfalse,  // Reserved\n\t\tfalse,  // Reserved\n\t\tfalse,  // Reserved\n\t\tfalse,  // Reserved\n\n#ifdef HAVE_CHECK_SHA256\n\t\ttrue,\n#else\n\t\tfalse,\n#endif\n\n\t\tfalse,  // Reserved\n\t\tfalse,  // Reserved\n\t\tfalse,  // Reserved\n\t\tfalse,  // Reserved\n\t\tfalse,  // Reserved\n\t};\n\n\treturn available_checks[(unsigned int)(type)];\n}\n\n\nextern LZMA_API(uint32_t)\nlzma_check_size(lzma_check type)\n{\n\tif ((unsigned int)(type) > LZMA_CHECK_ID_MAX)\n\t\treturn UINT32_MAX;\n\n\t// See file-format.txt section 2.1.1.2.\n\tstatic const uint8_t check_sizes[LZMA_CHECK_ID_MAX + 1] = {\n\t\t0,\n\t\t4, 4, 4,\n\t\t8, 8, 8,\n\t\t16, 16, 16,\n\t\t32, 32, 32,\n\t\t64, 64, 64\n\t};\n\n\treturn check_sizes[(unsigned int)(type)];\n}\n\n\nextern void\nlzma_check_init(lzma_check_state *check, lzma_check type)\n{\n\tswitch (type) {\n\tcase LZMA_CHECK_NONE:\n\t\tbreak;\n\n#ifdef HAVE_CHECK_CRC32\n\tcase LZMA_CHECK_CRC32:\n\t\tcheck->state.crc32 = 0;\n\t\tbreak;\n#endif\n\n#ifdef HAVE_CHECK_CRC64\n\tcase LZMA_CHECK_CRC64:\n\t\tcheck->state.crc64 = 0;\n\t\tbreak;\n#endif\n\n#ifdef HAVE_CHECK_SHA256\n\tcase LZMA_CHECK_SHA256:\n\t\tlzma_sha256_init(check);\n\t\tbreak;\n#endif\n\n\tdefault:\n\t\tbreak;\n\t}\n\n\treturn;\n}\n\n\nextern void\nlzma_check_update(lzma_check_state *check, lzma_check type,\n\t\tconst uint8_t *buf, size_t size)\n{\n\tswitch (type) {\n#ifdef HAVE_CHECK_CRC32\n\tcase LZMA_CHECK_CRC32:\n\t\tcheck->state.crc32 = lzma_crc32(buf, size, check->state.crc32);\n\t\tbreak;\n#endif\n\n#ifdef HAVE_CHECK_CRC64\n\tcase LZMA_CHECK_CRC64:\n\t\tcheck->state.crc64 = lzma_crc64(buf, size, check->state.crc64);\n\t\tbreak;\n#endif\n\n#ifdef HAVE_CHECK_SHA256\n\tcase LZMA_CHECK_SHA256:\n\t\tlzma_sha256_update(buf, size, check);\n\t\tbreak;\n#endif\n\n\tdefault:\n\t\tbreak;\n\t}\n\n\treturn;\n}\n\n\nextern void\nlzma_check_finish(lzma_check_state *check, lzma_check type)\n{\n\tswitch (type) {\n#ifdef HAVE_CHECK_CRC32\n\tcase LZMA_CHECK_CRC32:\n\t\tcheck->buffer.u32[0] = conv32le(check->state.crc32);\n\t\tbreak;\n#endif\n\n#ifdef HAVE_CHECK_CRC64\n\tcase LZMA_CHECK_CRC64:\n\t\tcheck->buffer.u64[0] = conv64le(check->state.crc64);\n\t\tbreak;\n#endif\n\n#ifdef HAVE_CHECK_SHA256\n\tcase LZMA_CHECK_SHA256:\n\t\tlzma_sha256_finish(check);\n\t\tbreak;\n#endif\n\n\tdefault:\n\t\tbreak;\n\t}\n\n\treturn;\n}\n"
  },
  {
    "path": "external/xz/liblzma/check/check.h",
    "content": "///////////////////////////////////////////////////////////////////////////////\n//\n/// \\file       check.h\n/// \\brief      Internal API to different integrity check functions\n//\n//  Author:     Lasse Collin\n//\n//  This file has been put into the public domain.\n//  You can do whatever you want with this file.\n//\n///////////////////////////////////////////////////////////////////////////////\n\n#ifndef LZMA_CHECK_H\n#define LZMA_CHECK_H\n\n#include \"common.h\"\n\n// If the function for external SHA-256 is missing, use the internal SHA-256\n// code. Due to how configure works, these defines can only get defined when\n// both a usable header and a type have already been found.\n#if !(defined(HAVE_CC_SHA256_INIT) \\\n\t\t|| defined(HAVE_SHA256_INIT) \\\n\t\t|| defined(HAVE_SHA256INIT))\n#\tdefine HAVE_INTERNAL_SHA256 1\n#endif\n\n#if defined(HAVE_INTERNAL_SHA256)\n// Nothing\n#elif defined(HAVE_COMMONCRYPTO_COMMONDIGEST_H)\n#\tinclude <CommonCrypto/CommonDigest.h>\n#elif defined(HAVE_SHA256_H)\n#\tinclude <sys/types.h>\n#\tinclude <sha256.h>\n#elif defined(HAVE_SHA2_H)\n#\tinclude <sys/types.h>\n#\tinclude <sha2.h>\n#endif\n\n#if defined(HAVE_INTERNAL_SHA256)\n/// State for the internal SHA-256 implementation\ntypedef struct {\n\t/// Internal state\n\tuint32_t state[8];\n\n\t/// Size of the message excluding padding\n\tuint64_t size;\n} lzma_sha256_state;\n#elif defined(HAVE_CC_SHA256_CTX)\ntypedef CC_SHA256_CTX lzma_sha256_state;\n#elif defined(HAVE_SHA256_CTX)\ntypedef SHA256_CTX lzma_sha256_state;\n#elif defined(HAVE_SHA2_CTX)\ntypedef SHA2_CTX lzma_sha256_state;\n#endif\n\n#if defined(HAVE_INTERNAL_SHA256)\n// Nothing\n#elif defined(HAVE_CC_SHA256_INIT)\n#\tdefine LZMA_SHA256FUNC(x) CC_SHA256_ ## x\n#elif defined(HAVE_SHA256_INIT)\n#\tdefine LZMA_SHA256FUNC(x) SHA256_ ## x\n#elif defined(HAVE_SHA256INIT)\n#\tdefine LZMA_SHA256FUNC(x) SHA256 ## x\n#endif\n\n// Index hashing needs the best possible hash function (preferably\n// a cryptographic hash) for maximum reliability.\n#if defined(HAVE_CHECK_SHA256)\n#\tdefine LZMA_CHECK_BEST LZMA_CHECK_SHA256\n#elif defined(HAVE_CHECK_CRC64)\n#\tdefine LZMA_CHECK_BEST LZMA_CHECK_CRC64\n#else\n#\tdefine LZMA_CHECK_BEST LZMA_CHECK_CRC32\n#endif\n\n\n/// \\brief      Structure to hold internal state of the check being calculated\n///\n/// \\note       This is not in the public API because this structure may\n///             change in future if new integrity check algorithms are added.\ntypedef struct {\n\t/// Buffer to hold the final result and a temporary buffer for SHA256.\n\tunion {\n\t\tuint8_t u8[64];\n\t\tuint32_t u32[16];\n\t\tuint64_t u64[8];\n\t} buffer;\n\n\t/// Check-specific data\n\tunion {\n\t\tuint32_t crc32;\n\t\tuint64_t crc64;\n\t\tlzma_sha256_state sha256;\n\t} state;\n\n} lzma_check_state;\n\n\n/// lzma_crc32_table[0] is needed by LZ encoder so we need to keep\n/// the array two-dimensional.\n#ifdef HAVE_SMALL\nextern uint32_t lzma_crc32_table[1][256];\nextern void lzma_crc32_init(void);\n#else\nextern const uint32_t lzma_crc32_table[8][256];\nextern const uint64_t lzma_crc64_table[4][256];\n#endif\n\n\n/// \\brief      Initialize *check depending on type\n///\n/// \\return     LZMA_OK on success. LZMA_UNSUPPORTED_CHECK if the type is not\n///             supported by the current version or build of liblzma.\n///             LZMA_PROG_ERROR if type > LZMA_CHECK_ID_MAX.\nextern void lzma_check_init(lzma_check_state *check, lzma_check type);\n\n/// Update the check state\nextern void lzma_check_update(lzma_check_state *check, lzma_check type,\n\t\tconst uint8_t *buf, size_t size);\n\n/// Finish the check calculation and store the result to check->buffer.u8.\nextern void lzma_check_finish(lzma_check_state *check, lzma_check type);\n\n\n#ifndef LZMA_SHA256FUNC\n\n/// Prepare SHA-256 state for new input.\nextern void lzma_sha256_init(lzma_check_state *check);\n\n/// Update the SHA-256 hash state\nextern void lzma_sha256_update(\n\t\tconst uint8_t *buf, size_t size, lzma_check_state *check);\n\n/// Finish the SHA-256 calculation and store the result to check->buffer.u8.\nextern void lzma_sha256_finish(lzma_check_state *check);\n\n\n#else\n\nstatic inline void\nlzma_sha256_init(lzma_check_state *check)\n{\n\tLZMA_SHA256FUNC(Init)(&check->state.sha256);\n}\n\n\nstatic inline void\nlzma_sha256_update(const uint8_t *buf, size_t size, lzma_check_state *check)\n{\n#if defined(HAVE_CC_SHA256_INIT) && SIZE_MAX > UINT32_MAX\n\t// Darwin's CC_SHA256_Update takes uint32_t as the buffer size,\n\t// so use a loop to support size_t.\n\twhile (size > UINT32_MAX) {\n\t\tLZMA_SHA256FUNC(Update)(&check->state.sha256, buf, UINT32_MAX);\n\t\tbuf += UINT32_MAX;\n\t\tsize -= UINT32_MAX;\n\t}\n#endif\n\n\tLZMA_SHA256FUNC(Update)(&check->state.sha256, buf, size);\n}\n\n\nstatic inline void\nlzma_sha256_finish(lzma_check_state *check)\n{\n\tLZMA_SHA256FUNC(Final)(check->buffer.u8, &check->state.sha256);\n}\n\n#endif\n\n#endif\n"
  },
  {
    "path": "external/xz/liblzma/check/crc32_fast.c",
    "content": "///////////////////////////////////////////////////////////////////////////////\n//\n/// \\file       crc32.c\n/// \\brief      CRC32 calculation\n///\n/// Calculate the CRC32 using the slice-by-eight algorithm.\n/// It is explained in this document:\n/// http://www.intel.com/technology/comms/perfnet/download/CRC_generators.pdf\n/// The code in this file is not the same as in Intel's paper, but\n/// the basic principle is identical.\n//\n//  Author:     Lasse Collin\n//\n//  This file has been put into the public domain.\n//  You can do whatever you want with this file.\n//\n///////////////////////////////////////////////////////////////////////////////\n\n#include \"check.h\"\n#include \"crc_macros.h\"\n\n\n// If you make any changes, do some benchmarking! Seemingly unrelated\n// changes can very easily ruin the performance (and very probably is\n// very compiler dependent).\nextern LZMA_API(uint32_t)\nlzma_crc32(const uint8_t *buf, size_t size, uint32_t crc)\n{\n\tcrc = ~crc;\n\n#ifdef WORDS_BIGENDIAN\n\tcrc = bswap32(crc);\n#endif\n\n\tif (size > 8) {\n\t\t// Fix the alignment, if needed. The if statement above\n\t\t// ensures that this won't read past the end of buf[].\n\t\twhile ((uintptr_t)(buf) & 7) {\n\t\t\tcrc = lzma_crc32_table[0][*buf++ ^ A(crc)] ^ S8(crc);\n\t\t\t--size;\n\t\t}\n\n\t\t// Calculate the position where to stop.\n\t\tconst uint8_t *const limit = buf + (size & ~(size_t)(7));\n\n\t\t// Calculate how many bytes must be calculated separately\n\t\t// before returning the result.\n\t\tsize &= (size_t)(7);\n\n\t\t// Calculate the CRC32 using the slice-by-eight algorithm.\n\t\twhile (buf < limit) {\n\t\t\tcrc ^= aligned_read32ne(buf);\n\t\t\tbuf += 4;\n\n\t\t\tcrc = lzma_crc32_table[7][A(crc)]\n\t\t\t    ^ lzma_crc32_table[6][B(crc)]\n\t\t\t    ^ lzma_crc32_table[5][C(crc)]\n\t\t\t    ^ lzma_crc32_table[4][D(crc)];\n\n\t\t\tconst uint32_t tmp = aligned_read32ne(buf);\n\t\t\tbuf += 4;\n\n\t\t\t// At least with some compilers, it is critical for\n\t\t\t// performance, that the crc variable is XORed\n\t\t\t// between the two table-lookup pairs.\n\t\t\tcrc = lzma_crc32_table[3][A(tmp)]\n\t\t\t    ^ lzma_crc32_table[2][B(tmp)]\n\t\t\t    ^ crc\n\t\t\t    ^ lzma_crc32_table[1][C(tmp)]\n\t\t\t    ^ lzma_crc32_table[0][D(tmp)];\n\t\t}\n\t}\n\n\twhile (size-- != 0)\n\t\tcrc = lzma_crc32_table[0][*buf++ ^ A(crc)] ^ S8(crc);\n\n#ifdef WORDS_BIGENDIAN\n\tcrc = bswap32(crc);\n#endif\n\n\treturn ~crc;\n}\n"
  },
  {
    "path": "external/xz/liblzma/check/crc32_small.c",
    "content": "///////////////////////////////////////////////////////////////////////////////\n//\n/// \\file       crc32_small.c\n/// \\brief      CRC32 calculation (size-optimized)\n//\n//  Author:     Lasse Collin\n//\n//  This file has been put into the public domain.\n//  You can do whatever you want with this file.\n//\n///////////////////////////////////////////////////////////////////////////////\n\n#include \"check.h\"\n\n\nuint32_t lzma_crc32_table[1][256];\n\n\nstatic void\ncrc32_init(void)\n{\n\tstatic const uint32_t poly32 = UINT32_C(0xEDB88320);\n\n\tfor (size_t b = 0; b < 256; ++b) {\n\t\tuint32_t r = b;\n\t\tfor (size_t i = 0; i < 8; ++i) {\n\t\t\tif (r & 1)\n\t\t\t\tr = (r >> 1) ^ poly32;\n\t\t\telse\n\t\t\t\tr >>= 1;\n\t\t}\n\n\t\tlzma_crc32_table[0][b] = r;\n\t}\n\n\treturn;\n}\n\n\nextern void\nlzma_crc32_init(void)\n{\n\tmythread_once(crc32_init);\n\treturn;\n}\n\n\nextern LZMA_API(uint32_t)\nlzma_crc32(const uint8_t *buf, size_t size, uint32_t crc)\n{\n\tlzma_crc32_init();\n\n\tcrc = ~crc;\n\n\twhile (size != 0) {\n\t\tcrc = lzma_crc32_table[0][*buf++ ^ (crc & 0xFF)] ^ (crc >> 8);\n\t\t--size;\n\t}\n\n\treturn ~crc;\n}\n"
  },
  {
    "path": "external/xz/liblzma/check/crc32_table.c",
    "content": "///////////////////////////////////////////////////////////////////////////////\n//\n/// \\file       crc32_table.c\n/// \\brief      Precalculated CRC32 table with correct endianness\n//\n//  Author:     Lasse Collin\n//\n//  This file has been put into the public domain.\n//  You can do whatever you want with this file.\n//\n///////////////////////////////////////////////////////////////////////////////\n\n#include \"common.h\"\n\n// Having the declaration here silences clang -Wmissing-variable-declarations.\nextern const uint32_t lzma_crc32_table[8][256];\n\n#ifdef WORDS_BIGENDIAN\n#\tinclude \"crc32_table_be.h\"\n#else\n#\tinclude \"crc32_table_le.h\"\n#endif\n"
  },
  {
    "path": "external/xz/liblzma/check/crc32_table_be.h",
    "content": "/* This file has been automatically generated by crc32_tablegen.c. */\n\nconst uint32_t lzma_crc32_table[8][256] = {\n\t{\n\t\t0x00000000, 0x96300777, 0x2C610EEE, 0xBA510999,\n\t\t0x19C46D07, 0x8FF46A70, 0x35A563E9, 0xA395649E,\n\t\t0x3288DB0E, 0xA4B8DC79, 0x1EE9D5E0, 0x88D9D297,\n\t\t0x2B4CB609, 0xBD7CB17E, 0x072DB8E7, 0x911DBF90,\n\t\t0x6410B71D, 0xF220B06A, 0x4871B9F3, 0xDE41BE84,\n\t\t0x7DD4DA1A, 0xEBE4DD6D, 0x51B5D4F4, 0xC785D383,\n\t\t0x56986C13, 0xC0A86B64, 0x7AF962FD, 0xECC9658A,\n\t\t0x4F5C0114, 0xD96C0663, 0x633D0FFA, 0xF50D088D,\n\t\t0xC8206E3B, 0x5E10694C, 0xE44160D5, 0x727167A2,\n\t\t0xD1E4033C, 0x47D4044B, 0xFD850DD2, 0x6BB50AA5,\n\t\t0xFAA8B535, 0x6C98B242, 0xD6C9BBDB, 0x40F9BCAC,\n\t\t0xE36CD832, 0x755CDF45, 0xCF0DD6DC, 0x593DD1AB,\n\t\t0xAC30D926, 0x3A00DE51, 0x8051D7C8, 0x1661D0BF,\n\t\t0xB5F4B421, 0x23C4B356, 0x9995BACF, 0x0FA5BDB8,\n\t\t0x9EB80228, 0x0888055F, 0xB2D90CC6, 0x24E90BB1,\n\t\t0x877C6F2F, 0x114C6858, 0xAB1D61C1, 0x3D2D66B6,\n\t\t0x9041DC76, 0x0671DB01, 0xBC20D298, 0x2A10D5EF,\n\t\t0x8985B171, 0x1FB5B606, 0xA5E4BF9F, 0x33D4B8E8,\n\t\t0xA2C90778, 0x34F9000F, 0x8EA80996, 0x18980EE1,\n\t\t0xBB0D6A7F, 0x2D3D6D08, 0x976C6491, 0x015C63E6,\n\t\t0xF4516B6B, 0x62616C1C, 0xD8306585, 0x4E0062F2,\n\t\t0xED95066C, 0x7BA5011B, 0xC1F40882, 0x57C40FF5,\n\t\t0xC6D9B065, 0x50E9B712, 0xEAB8BE8B, 0x7C88B9FC,\n\t\t0xDF1DDD62, 0x492DDA15, 0xF37CD38C, 0x654CD4FB,\n\t\t0x5861B24D, 0xCE51B53A, 0x7400BCA3, 0xE230BBD4,\n\t\t0x41A5DF4A, 0xD795D83D, 0x6DC4D1A4, 0xFBF4D6D3,\n\t\t0x6AE96943, 0xFCD96E34, 0x468867AD, 0xD0B860DA,\n\t\t0x732D0444, 0xE51D0333, 0x5F4C0AAA, 0xC97C0DDD,\n\t\t0x3C710550, 0xAA410227, 0x10100BBE, 0x86200CC9,\n\t\t0x25B56857, 0xB3856F20, 0x09D466B9, 0x9FE461CE,\n\t\t0x0EF9DE5E, 0x98C9D929, 0x2298D0B0, 0xB4A8D7C7,\n\t\t0x173DB359, 0x810DB42E, 0x3B5CBDB7, 0xAD6CBAC0,\n\t\t0x2083B8ED, 0xB6B3BF9A, 0x0CE2B603, 0x9AD2B174,\n\t\t0x3947D5EA, 0xAF77D29D, 0x1526DB04, 0x8316DC73,\n\t\t0x120B63E3, 0x843B6494, 0x3E6A6D0D, 0xA85A6A7A,\n\t\t0x0BCF0EE4, 0x9DFF0993, 0x27AE000A, 0xB19E077D,\n\t\t0x44930FF0, 0xD2A30887, 0x68F2011E, 0xFEC20669,\n\t\t0x5D5762F7, 0xCB676580, 0x71366C19, 0xE7066B6E,\n\t\t0x761BD4FE, 0xE02BD389, 0x5A7ADA10, 0xCC4ADD67,\n\t\t0x6FDFB9F9, 0xF9EFBE8E, 0x43BEB717, 0xD58EB060,\n\t\t0xE8A3D6D6, 0x7E93D1A1, 0xC4C2D838, 0x52F2DF4F,\n\t\t0xF167BBD1, 0x6757BCA6, 0xDD06B53F, 0x4B36B248,\n\t\t0xDA2B0DD8, 0x4C1B0AAF, 0xF64A0336, 0x607A0441,\n\t\t0xC3EF60DF, 0x55DF67A8, 0xEF8E6E31, 0x79BE6946,\n\t\t0x8CB361CB, 0x1A8366BC, 0xA0D26F25, 0x36E26852,\n\t\t0x95770CCC, 0x03470BBB, 0xB9160222, 0x2F260555,\n\t\t0xBE3BBAC5, 0x280BBDB2, 0x925AB42B, 0x046AB35C,\n\t\t0xA7FFD7C2, 0x31CFD0B5, 0x8B9ED92C, 0x1DAEDE5B,\n\t\t0xB0C2649B, 0x26F263EC, 0x9CA36A75, 0x0A936D02,\n\t\t0xA906099C, 0x3F360EEB, 0x85670772, 0x13570005,\n\t\t0x824ABF95, 0x147AB8E2, 0xAE2BB17B, 0x381BB60C,\n\t\t0x9B8ED292, 0x0DBED5E5, 0xB7EFDC7C, 0x21DFDB0B,\n\t\t0xD4D2D386, 0x42E2D4F1, 0xF8B3DD68, 0x6E83DA1F,\n\t\t0xCD16BE81, 0x5B26B9F6, 0xE177B06F, 0x7747B718,\n\t\t0xE65A0888, 0x706A0FFF, 0xCA3B0666, 0x5C0B0111,\n\t\t0xFF9E658F, 0x69AE62F8, 0xD3FF6B61, 0x45CF6C16,\n\t\t0x78E20AA0, 0xEED20DD7, 0x5483044E, 0xC2B30339,\n\t\t0x612667A7, 0xF71660D0, 0x4D476949, 0xDB776E3E,\n\t\t0x4A6AD1AE, 0xDC5AD6D9, 0x660BDF40, 0xF03BD837,\n\t\t0x53AEBCA9, 0xC59EBBDE, 0x7FCFB247, 0xE9FFB530,\n\t\t0x1CF2BDBD, 0x8AC2BACA, 0x3093B353, 0xA6A3B424,\n\t\t0x0536D0BA, 0x9306D7CD, 0x2957DE54, 0xBF67D923,\n\t\t0x2E7A66B3, 0xB84A61C4, 0x021B685D, 0x942B6F2A,\n\t\t0x37BE0BB4, 0xA18E0CC3, 0x1BDF055A, 0x8DEF022D\n\t}, {\n\t\t0x00000000, 0x41311B19, 0x82623632, 0xC3532D2B,\n\t\t0x04C56C64, 0x45F4777D, 0x86A75A56, 0xC796414F,\n\t\t0x088AD9C8, 0x49BBC2D1, 0x8AE8EFFA, 0xCBD9F4E3,\n\t\t0x0C4FB5AC, 0x4D7EAEB5, 0x8E2D839E, 0xCF1C9887,\n\t\t0x5112C24A, 0x1023D953, 0xD370F478, 0x9241EF61,\n\t\t0x55D7AE2E, 0x14E6B537, 0xD7B5981C, 0x96848305,\n\t\t0x59981B82, 0x18A9009B, 0xDBFA2DB0, 0x9ACB36A9,\n\t\t0x5D5D77E6, 0x1C6C6CFF, 0xDF3F41D4, 0x9E0E5ACD,\n\t\t0xA2248495, 0xE3159F8C, 0x2046B2A7, 0x6177A9BE,\n\t\t0xA6E1E8F1, 0xE7D0F3E8, 0x2483DEC3, 0x65B2C5DA,\n\t\t0xAAAE5D5D, 0xEB9F4644, 0x28CC6B6F, 0x69FD7076,\n\t\t0xAE6B3139, 0xEF5A2A20, 0x2C09070B, 0x6D381C12,\n\t\t0xF33646DF, 0xB2075DC6, 0x715470ED, 0x30656BF4,\n\t\t0xF7F32ABB, 0xB6C231A2, 0x75911C89, 0x34A00790,\n\t\t0xFBBC9F17, 0xBA8D840E, 0x79DEA925, 0x38EFB23C,\n\t\t0xFF79F373, 0xBE48E86A, 0x7D1BC541, 0x3C2ADE58,\n\t\t0x054F79F0, 0x447E62E9, 0x872D4FC2, 0xC61C54DB,\n\t\t0x018A1594, 0x40BB0E8D, 0x83E823A6, 0xC2D938BF,\n\t\t0x0DC5A038, 0x4CF4BB21, 0x8FA7960A, 0xCE968D13,\n\t\t0x0900CC5C, 0x4831D745, 0x8B62FA6E, 0xCA53E177,\n\t\t0x545DBBBA, 0x156CA0A3, 0xD63F8D88, 0x970E9691,\n\t\t0x5098D7DE, 0x11A9CCC7, 0xD2FAE1EC, 0x93CBFAF5,\n\t\t0x5CD76272, 0x1DE6796B, 0xDEB55440, 0x9F844F59,\n\t\t0x58120E16, 0x1923150F, 0xDA703824, 0x9B41233D,\n\t\t0xA76BFD65, 0xE65AE67C, 0x2509CB57, 0x6438D04E,\n\t\t0xA3AE9101, 0xE29F8A18, 0x21CCA733, 0x60FDBC2A,\n\t\t0xAFE124AD, 0xEED03FB4, 0x2D83129F, 0x6CB20986,\n\t\t0xAB2448C9, 0xEA1553D0, 0x29467EFB, 0x687765E2,\n\t\t0xF6793F2F, 0xB7482436, 0x741B091D, 0x352A1204,\n\t\t0xF2BC534B, 0xB38D4852, 0x70DE6579, 0x31EF7E60,\n\t\t0xFEF3E6E7, 0xBFC2FDFE, 0x7C91D0D5, 0x3DA0CBCC,\n\t\t0xFA368A83, 0xBB07919A, 0x7854BCB1, 0x3965A7A8,\n\t\t0x4B98833B, 0x0AA99822, 0xC9FAB509, 0x88CBAE10,\n\t\t0x4F5DEF5F, 0x0E6CF446, 0xCD3FD96D, 0x8C0EC274,\n\t\t0x43125AF3, 0x022341EA, 0xC1706CC1, 0x804177D8,\n\t\t0x47D73697, 0x06E62D8E, 0xC5B500A5, 0x84841BBC,\n\t\t0x1A8A4171, 0x5BBB5A68, 0x98E87743, 0xD9D96C5A,\n\t\t0x1E4F2D15, 0x5F7E360C, 0x9C2D1B27, 0xDD1C003E,\n\t\t0x120098B9, 0x533183A0, 0x9062AE8B, 0xD153B592,\n\t\t0x16C5F4DD, 0x57F4EFC4, 0x94A7C2EF, 0xD596D9F6,\n\t\t0xE9BC07AE, 0xA88D1CB7, 0x6BDE319C, 0x2AEF2A85,\n\t\t0xED796BCA, 0xAC4870D3, 0x6F1B5DF8, 0x2E2A46E1,\n\t\t0xE136DE66, 0xA007C57F, 0x6354E854, 0x2265F34D,\n\t\t0xE5F3B202, 0xA4C2A91B, 0x67918430, 0x26A09F29,\n\t\t0xB8AEC5E4, 0xF99FDEFD, 0x3ACCF3D6, 0x7BFDE8CF,\n\t\t0xBC6BA980, 0xFD5AB299, 0x3E099FB2, 0x7F3884AB,\n\t\t0xB0241C2C, 0xF1150735, 0x32462A1E, 0x73773107,\n\t\t0xB4E17048, 0xF5D06B51, 0x3683467A, 0x77B25D63,\n\t\t0x4ED7FACB, 0x0FE6E1D2, 0xCCB5CCF9, 0x8D84D7E0,\n\t\t0x4A1296AF, 0x0B238DB6, 0xC870A09D, 0x8941BB84,\n\t\t0x465D2303, 0x076C381A, 0xC43F1531, 0x850E0E28,\n\t\t0x42984F67, 0x03A9547E, 0xC0FA7955, 0x81CB624C,\n\t\t0x1FC53881, 0x5EF42398, 0x9DA70EB3, 0xDC9615AA,\n\t\t0x1B0054E5, 0x5A314FFC, 0x996262D7, 0xD85379CE,\n\t\t0x174FE149, 0x567EFA50, 0x952DD77B, 0xD41CCC62,\n\t\t0x138A8D2D, 0x52BB9634, 0x91E8BB1F, 0xD0D9A006,\n\t\t0xECF37E5E, 0xADC26547, 0x6E91486C, 0x2FA05375,\n\t\t0xE836123A, 0xA9070923, 0x6A542408, 0x2B653F11,\n\t\t0xE479A796, 0xA548BC8F, 0x661B91A4, 0x272A8ABD,\n\t\t0xE0BCCBF2, 0xA18DD0EB, 0x62DEFDC0, 0x23EFE6D9,\n\t\t0xBDE1BC14, 0xFCD0A70D, 0x3F838A26, 0x7EB2913F,\n\t\t0xB924D070, 0xF815CB69, 0x3B46E642, 0x7A77FD5B,\n\t\t0xB56B65DC, 0xF45A7EC5, 0x370953EE, 0x763848F7,\n\t\t0xB1AE09B8, 0xF09F12A1, 0x33CC3F8A, 0x72FD2493\n\t}, {\n\t\t0x00000000, 0x376AC201, 0x6ED48403, 0x59BE4602,\n\t\t0xDCA80907, 0xEBC2CB06, 0xB27C8D04, 0x85164F05,\n\t\t0xB851130E, 0x8F3BD10F, 0xD685970D, 0xE1EF550C,\n\t\t0x64F91A09, 0x5393D808, 0x0A2D9E0A, 0x3D475C0B,\n\t\t0x70A3261C, 0x47C9E41D, 0x1E77A21F, 0x291D601E,\n\t\t0xAC0B2F1B, 0x9B61ED1A, 0xC2DFAB18, 0xF5B56919,\n\t\t0xC8F23512, 0xFF98F713, 0xA626B111, 0x914C7310,\n\t\t0x145A3C15, 0x2330FE14, 0x7A8EB816, 0x4DE47A17,\n\t\t0xE0464D38, 0xD72C8F39, 0x8E92C93B, 0xB9F80B3A,\n\t\t0x3CEE443F, 0x0B84863E, 0x523AC03C, 0x6550023D,\n\t\t0x58175E36, 0x6F7D9C37, 0x36C3DA35, 0x01A91834,\n\t\t0x84BF5731, 0xB3D59530, 0xEA6BD332, 0xDD011133,\n\t\t0x90E56B24, 0xA78FA925, 0xFE31EF27, 0xC95B2D26,\n\t\t0x4C4D6223, 0x7B27A022, 0x2299E620, 0x15F32421,\n\t\t0x28B4782A, 0x1FDEBA2B, 0x4660FC29, 0x710A3E28,\n\t\t0xF41C712D, 0xC376B32C, 0x9AC8F52E, 0xADA2372F,\n\t\t0xC08D9A70, 0xF7E75871, 0xAE591E73, 0x9933DC72,\n\t\t0x1C259377, 0x2B4F5176, 0x72F11774, 0x459BD575,\n\t\t0x78DC897E, 0x4FB64B7F, 0x16080D7D, 0x2162CF7C,\n\t\t0xA4748079, 0x931E4278, 0xCAA0047A, 0xFDCAC67B,\n\t\t0xB02EBC6C, 0x87447E6D, 0xDEFA386F, 0xE990FA6E,\n\t\t0x6C86B56B, 0x5BEC776A, 0x02523168, 0x3538F369,\n\t\t0x087FAF62, 0x3F156D63, 0x66AB2B61, 0x51C1E960,\n\t\t0xD4D7A665, 0xE3BD6464, 0xBA032266, 0x8D69E067,\n\t\t0x20CBD748, 0x17A11549, 0x4E1F534B, 0x7975914A,\n\t\t0xFC63DE4F, 0xCB091C4E, 0x92B75A4C, 0xA5DD984D,\n\t\t0x989AC446, 0xAFF00647, 0xF64E4045, 0xC1248244,\n\t\t0x4432CD41, 0x73580F40, 0x2AE64942, 0x1D8C8B43,\n\t\t0x5068F154, 0x67023355, 0x3EBC7557, 0x09D6B756,\n\t\t0x8CC0F853, 0xBBAA3A52, 0xE2147C50, 0xD57EBE51,\n\t\t0xE839E25A, 0xDF53205B, 0x86ED6659, 0xB187A458,\n\t\t0x3491EB5D, 0x03FB295C, 0x5A456F5E, 0x6D2FAD5F,\n\t\t0x801B35E1, 0xB771F7E0, 0xEECFB1E2, 0xD9A573E3,\n\t\t0x5CB33CE6, 0x6BD9FEE7, 0x3267B8E5, 0x050D7AE4,\n\t\t0x384A26EF, 0x0F20E4EE, 0x569EA2EC, 0x61F460ED,\n\t\t0xE4E22FE8, 0xD388EDE9, 0x8A36ABEB, 0xBD5C69EA,\n\t\t0xF0B813FD, 0xC7D2D1FC, 0x9E6C97FE, 0xA90655FF,\n\t\t0x2C101AFA, 0x1B7AD8FB, 0x42C49EF9, 0x75AE5CF8,\n\t\t0x48E900F3, 0x7F83C2F2, 0x263D84F0, 0x115746F1,\n\t\t0x944109F4, 0xA32BCBF5, 0xFA958DF7, 0xCDFF4FF6,\n\t\t0x605D78D9, 0x5737BAD8, 0x0E89FCDA, 0x39E33EDB,\n\t\t0xBCF571DE, 0x8B9FB3DF, 0xD221F5DD, 0xE54B37DC,\n\t\t0xD80C6BD7, 0xEF66A9D6, 0xB6D8EFD4, 0x81B22DD5,\n\t\t0x04A462D0, 0x33CEA0D1, 0x6A70E6D3, 0x5D1A24D2,\n\t\t0x10FE5EC5, 0x27949CC4, 0x7E2ADAC6, 0x494018C7,\n\t\t0xCC5657C2, 0xFB3C95C3, 0xA282D3C1, 0x95E811C0,\n\t\t0xA8AF4DCB, 0x9FC58FCA, 0xC67BC9C8, 0xF1110BC9,\n\t\t0x740744CC, 0x436D86CD, 0x1AD3C0CF, 0x2DB902CE,\n\t\t0x4096AF91, 0x77FC6D90, 0x2E422B92, 0x1928E993,\n\t\t0x9C3EA696, 0xAB546497, 0xF2EA2295, 0xC580E094,\n\t\t0xF8C7BC9F, 0xCFAD7E9E, 0x9613389C, 0xA179FA9D,\n\t\t0x246FB598, 0x13057799, 0x4ABB319B, 0x7DD1F39A,\n\t\t0x3035898D, 0x075F4B8C, 0x5EE10D8E, 0x698BCF8F,\n\t\t0xEC9D808A, 0xDBF7428B, 0x82490489, 0xB523C688,\n\t\t0x88649A83, 0xBF0E5882, 0xE6B01E80, 0xD1DADC81,\n\t\t0x54CC9384, 0x63A65185, 0x3A181787, 0x0D72D586,\n\t\t0xA0D0E2A9, 0x97BA20A8, 0xCE0466AA, 0xF96EA4AB,\n\t\t0x7C78EBAE, 0x4B1229AF, 0x12AC6FAD, 0x25C6ADAC,\n\t\t0x1881F1A7, 0x2FEB33A6, 0x765575A4, 0x413FB7A5,\n\t\t0xC429F8A0, 0xF3433AA1, 0xAAFD7CA3, 0x9D97BEA2,\n\t\t0xD073C4B5, 0xE71906B4, 0xBEA740B6, 0x89CD82B7,\n\t\t0x0CDBCDB2, 0x3BB10FB3, 0x620F49B1, 0x55658BB0,\n\t\t0x6822D7BB, 0x5F4815BA, 0x06F653B8, 0x319C91B9,\n\t\t0xB48ADEBC, 0x83E01CBD, 0xDA5E5ABF, 0xED3498BE\n\t}, {\n\t\t0x00000000, 0x6567BCB8, 0x8BC809AA, 0xEEAFB512,\n\t\t0x5797628F, 0x32F0DE37, 0xDC5F6B25, 0xB938D79D,\n\t\t0xEF28B4C5, 0x8A4F087D, 0x64E0BD6F, 0x018701D7,\n\t\t0xB8BFD64A, 0xDDD86AF2, 0x3377DFE0, 0x56106358,\n\t\t0x9F571950, 0xFA30A5E8, 0x149F10FA, 0x71F8AC42,\n\t\t0xC8C07BDF, 0xADA7C767, 0x43087275, 0x266FCECD,\n\t\t0x707FAD95, 0x1518112D, 0xFBB7A43F, 0x9ED01887,\n\t\t0x27E8CF1A, 0x428F73A2, 0xAC20C6B0, 0xC9477A08,\n\t\t0x3EAF32A0, 0x5BC88E18, 0xB5673B0A, 0xD00087B2,\n\t\t0x6938502F, 0x0C5FEC97, 0xE2F05985, 0x8797E53D,\n\t\t0xD1878665, 0xB4E03ADD, 0x5A4F8FCF, 0x3F283377,\n\t\t0x8610E4EA, 0xE3775852, 0x0DD8ED40, 0x68BF51F8,\n\t\t0xA1F82BF0, 0xC49F9748, 0x2A30225A, 0x4F579EE2,\n\t\t0xF66F497F, 0x9308F5C7, 0x7DA740D5, 0x18C0FC6D,\n\t\t0x4ED09F35, 0x2BB7238D, 0xC518969F, 0xA07F2A27,\n\t\t0x1947FDBA, 0x7C204102, 0x928FF410, 0xF7E848A8,\n\t\t0x3D58149B, 0x583FA823, 0xB6901D31, 0xD3F7A189,\n\t\t0x6ACF7614, 0x0FA8CAAC, 0xE1077FBE, 0x8460C306,\n\t\t0xD270A05E, 0xB7171CE6, 0x59B8A9F4, 0x3CDF154C,\n\t\t0x85E7C2D1, 0xE0807E69, 0x0E2FCB7B, 0x6B4877C3,\n\t\t0xA20F0DCB, 0xC768B173, 0x29C70461, 0x4CA0B8D9,\n\t\t0xF5986F44, 0x90FFD3FC, 0x7E5066EE, 0x1B37DA56,\n\t\t0x4D27B90E, 0x284005B6, 0xC6EFB0A4, 0xA3880C1C,\n\t\t0x1AB0DB81, 0x7FD76739, 0x9178D22B, 0xF41F6E93,\n\t\t0x03F7263B, 0x66909A83, 0x883F2F91, 0xED589329,\n\t\t0x546044B4, 0x3107F80C, 0xDFA84D1E, 0xBACFF1A6,\n\t\t0xECDF92FE, 0x89B82E46, 0x67179B54, 0x027027EC,\n\t\t0xBB48F071, 0xDE2F4CC9, 0x3080F9DB, 0x55E74563,\n\t\t0x9CA03F6B, 0xF9C783D3, 0x176836C1, 0x720F8A79,\n\t\t0xCB375DE4, 0xAE50E15C, 0x40FF544E, 0x2598E8F6,\n\t\t0x73888BAE, 0x16EF3716, 0xF8408204, 0x9D273EBC,\n\t\t0x241FE921, 0x41785599, 0xAFD7E08B, 0xCAB05C33,\n\t\t0x3BB659ED, 0x5ED1E555, 0xB07E5047, 0xD519ECFF,\n\t\t0x6C213B62, 0x094687DA, 0xE7E932C8, 0x828E8E70,\n\t\t0xD49EED28, 0xB1F95190, 0x5F56E482, 0x3A31583A,\n\t\t0x83098FA7, 0xE66E331F, 0x08C1860D, 0x6DA63AB5,\n\t\t0xA4E140BD, 0xC186FC05, 0x2F294917, 0x4A4EF5AF,\n\t\t0xF3762232, 0x96119E8A, 0x78BE2B98, 0x1DD99720,\n\t\t0x4BC9F478, 0x2EAE48C0, 0xC001FDD2, 0xA566416A,\n\t\t0x1C5E96F7, 0x79392A4F, 0x97969F5D, 0xF2F123E5,\n\t\t0x05196B4D, 0x607ED7F5, 0x8ED162E7, 0xEBB6DE5F,\n\t\t0x528E09C2, 0x37E9B57A, 0xD9460068, 0xBC21BCD0,\n\t\t0xEA31DF88, 0x8F566330, 0x61F9D622, 0x049E6A9A,\n\t\t0xBDA6BD07, 0xD8C101BF, 0x366EB4AD, 0x53090815,\n\t\t0x9A4E721D, 0xFF29CEA5, 0x11867BB7, 0x74E1C70F,\n\t\t0xCDD91092, 0xA8BEAC2A, 0x46111938, 0x2376A580,\n\t\t0x7566C6D8, 0x10017A60, 0xFEAECF72, 0x9BC973CA,\n\t\t0x22F1A457, 0x479618EF, 0xA939ADFD, 0xCC5E1145,\n\t\t0x06EE4D76, 0x6389F1CE, 0x8D2644DC, 0xE841F864,\n\t\t0x51792FF9, 0x341E9341, 0xDAB12653, 0xBFD69AEB,\n\t\t0xE9C6F9B3, 0x8CA1450B, 0x620EF019, 0x07694CA1,\n\t\t0xBE519B3C, 0xDB362784, 0x35999296, 0x50FE2E2E,\n\t\t0x99B95426, 0xFCDEE89E, 0x12715D8C, 0x7716E134,\n\t\t0xCE2E36A9, 0xAB498A11, 0x45E63F03, 0x208183BB,\n\t\t0x7691E0E3, 0x13F65C5B, 0xFD59E949, 0x983E55F1,\n\t\t0x2106826C, 0x44613ED4, 0xAACE8BC6, 0xCFA9377E,\n\t\t0x38417FD6, 0x5D26C36E, 0xB389767C, 0xD6EECAC4,\n\t\t0x6FD61D59, 0x0AB1A1E1, 0xE41E14F3, 0x8179A84B,\n\t\t0xD769CB13, 0xB20E77AB, 0x5CA1C2B9, 0x39C67E01,\n\t\t0x80FEA99C, 0xE5991524, 0x0B36A036, 0x6E511C8E,\n\t\t0xA7166686, 0xC271DA3E, 0x2CDE6F2C, 0x49B9D394,\n\t\t0xF0810409, 0x95E6B8B1, 0x7B490DA3, 0x1E2EB11B,\n\t\t0x483ED243, 0x2D596EFB, 0xC3F6DBE9, 0xA6916751,\n\t\t0x1FA9B0CC, 0x7ACE0C74, 0x9461B966, 0xF10605DE\n\t}, {\n\t\t0x00000000, 0xB029603D, 0x6053C07A, 0xD07AA047,\n\t\t0xC0A680F5, 0x708FE0C8, 0xA0F5408F, 0x10DC20B2,\n\t\t0xC14B7030, 0x7162100D, 0xA118B04A, 0x1131D077,\n\t\t0x01EDF0C5, 0xB1C490F8, 0x61BE30BF, 0xD1975082,\n\t\t0x8297E060, 0x32BE805D, 0xE2C4201A, 0x52ED4027,\n\t\t0x42316095, 0xF21800A8, 0x2262A0EF, 0x924BC0D2,\n\t\t0x43DC9050, 0xF3F5F06D, 0x238F502A, 0x93A63017,\n\t\t0x837A10A5, 0x33537098, 0xE329D0DF, 0x5300B0E2,\n\t\t0x042FC1C1, 0xB406A1FC, 0x647C01BB, 0xD4556186,\n\t\t0xC4894134, 0x74A02109, 0xA4DA814E, 0x14F3E173,\n\t\t0xC564B1F1, 0x754DD1CC, 0xA537718B, 0x151E11B6,\n\t\t0x05C23104, 0xB5EB5139, 0x6591F17E, 0xD5B89143,\n\t\t0x86B821A1, 0x3691419C, 0xE6EBE1DB, 0x56C281E6,\n\t\t0x461EA154, 0xF637C169, 0x264D612E, 0x96640113,\n\t\t0x47F35191, 0xF7DA31AC, 0x27A091EB, 0x9789F1D6,\n\t\t0x8755D164, 0x377CB159, 0xE706111E, 0x572F7123,\n\t\t0x4958F358, 0xF9719365, 0x290B3322, 0x9922531F,\n\t\t0x89FE73AD, 0x39D71390, 0xE9ADB3D7, 0x5984D3EA,\n\t\t0x88138368, 0x383AE355, 0xE8404312, 0x5869232F,\n\t\t0x48B5039D, 0xF89C63A0, 0x28E6C3E7, 0x98CFA3DA,\n\t\t0xCBCF1338, 0x7BE67305, 0xAB9CD342, 0x1BB5B37F,\n\t\t0x0B6993CD, 0xBB40F3F0, 0x6B3A53B7, 0xDB13338A,\n\t\t0x0A846308, 0xBAAD0335, 0x6AD7A372, 0xDAFEC34F,\n\t\t0xCA22E3FD, 0x7A0B83C0, 0xAA712387, 0x1A5843BA,\n\t\t0x4D773299, 0xFD5E52A4, 0x2D24F2E3, 0x9D0D92DE,\n\t\t0x8DD1B26C, 0x3DF8D251, 0xED827216, 0x5DAB122B,\n\t\t0x8C3C42A9, 0x3C152294, 0xEC6F82D3, 0x5C46E2EE,\n\t\t0x4C9AC25C, 0xFCB3A261, 0x2CC90226, 0x9CE0621B,\n\t\t0xCFE0D2F9, 0x7FC9B2C4, 0xAFB31283, 0x1F9A72BE,\n\t\t0x0F46520C, 0xBF6F3231, 0x6F159276, 0xDF3CF24B,\n\t\t0x0EABA2C9, 0xBE82C2F4, 0x6EF862B3, 0xDED1028E,\n\t\t0xCE0D223C, 0x7E244201, 0xAE5EE246, 0x1E77827B,\n\t\t0x92B0E6B1, 0x2299868C, 0xF2E326CB, 0x42CA46F6,\n\t\t0x52166644, 0xE23F0679, 0x3245A63E, 0x826CC603,\n\t\t0x53FB9681, 0xE3D2F6BC, 0x33A856FB, 0x838136C6,\n\t\t0x935D1674, 0x23747649, 0xF30ED60E, 0x4327B633,\n\t\t0x102706D1, 0xA00E66EC, 0x7074C6AB, 0xC05DA696,\n\t\t0xD0818624, 0x60A8E619, 0xB0D2465E, 0x00FB2663,\n\t\t0xD16C76E1, 0x614516DC, 0xB13FB69B, 0x0116D6A6,\n\t\t0x11CAF614, 0xA1E39629, 0x7199366E, 0xC1B05653,\n\t\t0x969F2770, 0x26B6474D, 0xF6CCE70A, 0x46E58737,\n\t\t0x5639A785, 0xE610C7B8, 0x366A67FF, 0x864307C2,\n\t\t0x57D45740, 0xE7FD377D, 0x3787973A, 0x87AEF707,\n\t\t0x9772D7B5, 0x275BB788, 0xF72117CF, 0x470877F2,\n\t\t0x1408C710, 0xA421A72D, 0x745B076A, 0xC4726757,\n\t\t0xD4AE47E5, 0x648727D8, 0xB4FD879F, 0x04D4E7A2,\n\t\t0xD543B720, 0x656AD71D, 0xB510775A, 0x05391767,\n\t\t0x15E537D5, 0xA5CC57E8, 0x75B6F7AF, 0xC59F9792,\n\t\t0xDBE815E9, 0x6BC175D4, 0xBBBBD593, 0x0B92B5AE,\n\t\t0x1B4E951C, 0xAB67F521, 0x7B1D5566, 0xCB34355B,\n\t\t0x1AA365D9, 0xAA8A05E4, 0x7AF0A5A3, 0xCAD9C59E,\n\t\t0xDA05E52C, 0x6A2C8511, 0xBA562556, 0x0A7F456B,\n\t\t0x597FF589, 0xE95695B4, 0x392C35F3, 0x890555CE,\n\t\t0x99D9757C, 0x29F01541, 0xF98AB506, 0x49A3D53B,\n\t\t0x983485B9, 0x281DE584, 0xF86745C3, 0x484E25FE,\n\t\t0x5892054C, 0xE8BB6571, 0x38C1C536, 0x88E8A50B,\n\t\t0xDFC7D428, 0x6FEEB415, 0xBF941452, 0x0FBD746F,\n\t\t0x1F6154DD, 0xAF4834E0, 0x7F3294A7, 0xCF1BF49A,\n\t\t0x1E8CA418, 0xAEA5C425, 0x7EDF6462, 0xCEF6045F,\n\t\t0xDE2A24ED, 0x6E0344D0, 0xBE79E497, 0x0E5084AA,\n\t\t0x5D503448, 0xED795475, 0x3D03F432, 0x8D2A940F,\n\t\t0x9DF6B4BD, 0x2DDFD480, 0xFDA574C7, 0x4D8C14FA,\n\t\t0x9C1B4478, 0x2C322445, 0xFC488402, 0x4C61E43F,\n\t\t0x5CBDC48D, 0xEC94A4B0, 0x3CEE04F7, 0x8CC764CA\n\t}, {\n\t\t0x00000000, 0xA5D35CCB, 0x0BA1C84D, 0xAE729486,\n\t\t0x1642919B, 0xB391CD50, 0x1DE359D6, 0xB830051D,\n\t\t0x6D8253EC, 0xC8510F27, 0x66239BA1, 0xC3F0C76A,\n\t\t0x7BC0C277, 0xDE139EBC, 0x70610A3A, 0xD5B256F1,\n\t\t0x9B02D603, 0x3ED18AC8, 0x90A31E4E, 0x35704285,\n\t\t0x8D404798, 0x28931B53, 0x86E18FD5, 0x2332D31E,\n\t\t0xF68085EF, 0x5353D924, 0xFD214DA2, 0x58F21169,\n\t\t0xE0C21474, 0x451148BF, 0xEB63DC39, 0x4EB080F2,\n\t\t0x3605AC07, 0x93D6F0CC, 0x3DA4644A, 0x98773881,\n\t\t0x20473D9C, 0x85946157, 0x2BE6F5D1, 0x8E35A91A,\n\t\t0x5B87FFEB, 0xFE54A320, 0x502637A6, 0xF5F56B6D,\n\t\t0x4DC56E70, 0xE81632BB, 0x4664A63D, 0xE3B7FAF6,\n\t\t0xAD077A04, 0x08D426CF, 0xA6A6B249, 0x0375EE82,\n\t\t0xBB45EB9F, 0x1E96B754, 0xB0E423D2, 0x15377F19,\n\t\t0xC08529E8, 0x65567523, 0xCB24E1A5, 0x6EF7BD6E,\n\t\t0xD6C7B873, 0x7314E4B8, 0xDD66703E, 0x78B52CF5,\n\t\t0x6C0A580F, 0xC9D904C4, 0x67AB9042, 0xC278CC89,\n\t\t0x7A48C994, 0xDF9B955F, 0x71E901D9, 0xD43A5D12,\n\t\t0x01880BE3, 0xA45B5728, 0x0A29C3AE, 0xAFFA9F65,\n\t\t0x17CA9A78, 0xB219C6B3, 0x1C6B5235, 0xB9B80EFE,\n\t\t0xF7088E0C, 0x52DBD2C7, 0xFCA94641, 0x597A1A8A,\n\t\t0xE14A1F97, 0x4499435C, 0xEAEBD7DA, 0x4F388B11,\n\t\t0x9A8ADDE0, 0x3F59812B, 0x912B15AD, 0x34F84966,\n\t\t0x8CC84C7B, 0x291B10B0, 0x87698436, 0x22BAD8FD,\n\t\t0x5A0FF408, 0xFFDCA8C3, 0x51AE3C45, 0xF47D608E,\n\t\t0x4C4D6593, 0xE99E3958, 0x47ECADDE, 0xE23FF115,\n\t\t0x378DA7E4, 0x925EFB2F, 0x3C2C6FA9, 0x99FF3362,\n\t\t0x21CF367F, 0x841C6AB4, 0x2A6EFE32, 0x8FBDA2F9,\n\t\t0xC10D220B, 0x64DE7EC0, 0xCAACEA46, 0x6F7FB68D,\n\t\t0xD74FB390, 0x729CEF5B, 0xDCEE7BDD, 0x793D2716,\n\t\t0xAC8F71E7, 0x095C2D2C, 0xA72EB9AA, 0x02FDE561,\n\t\t0xBACDE07C, 0x1F1EBCB7, 0xB16C2831, 0x14BF74FA,\n\t\t0xD814B01E, 0x7DC7ECD5, 0xD3B57853, 0x76662498,\n\t\t0xCE562185, 0x6B857D4E, 0xC5F7E9C8, 0x6024B503,\n\t\t0xB596E3F2, 0x1045BF39, 0xBE372BBF, 0x1BE47774,\n\t\t0xA3D47269, 0x06072EA2, 0xA875BA24, 0x0DA6E6EF,\n\t\t0x4316661D, 0xE6C53AD6, 0x48B7AE50, 0xED64F29B,\n\t\t0x5554F786, 0xF087AB4D, 0x5EF53FCB, 0xFB266300,\n\t\t0x2E9435F1, 0x8B47693A, 0x2535FDBC, 0x80E6A177,\n\t\t0x38D6A46A, 0x9D05F8A1, 0x33776C27, 0x96A430EC,\n\t\t0xEE111C19, 0x4BC240D2, 0xE5B0D454, 0x4063889F,\n\t\t0xF8538D82, 0x5D80D149, 0xF3F245CF, 0x56211904,\n\t\t0x83934FF5, 0x2640133E, 0x883287B8, 0x2DE1DB73,\n\t\t0x95D1DE6E, 0x300282A5, 0x9E701623, 0x3BA34AE8,\n\t\t0x7513CA1A, 0xD0C096D1, 0x7EB20257, 0xDB615E9C,\n\t\t0x63515B81, 0xC682074A, 0x68F093CC, 0xCD23CF07,\n\t\t0x189199F6, 0xBD42C53D, 0x133051BB, 0xB6E30D70,\n\t\t0x0ED3086D, 0xAB0054A6, 0x0572C020, 0xA0A19CEB,\n\t\t0xB41EE811, 0x11CDB4DA, 0xBFBF205C, 0x1A6C7C97,\n\t\t0xA25C798A, 0x078F2541, 0xA9FDB1C7, 0x0C2EED0C,\n\t\t0xD99CBBFD, 0x7C4FE736, 0xD23D73B0, 0x77EE2F7B,\n\t\t0xCFDE2A66, 0x6A0D76AD, 0xC47FE22B, 0x61ACBEE0,\n\t\t0x2F1C3E12, 0x8ACF62D9, 0x24BDF65F, 0x816EAA94,\n\t\t0x395EAF89, 0x9C8DF342, 0x32FF67C4, 0x972C3B0F,\n\t\t0x429E6DFE, 0xE74D3135, 0x493FA5B3, 0xECECF978,\n\t\t0x54DCFC65, 0xF10FA0AE, 0x5F7D3428, 0xFAAE68E3,\n\t\t0x821B4416, 0x27C818DD, 0x89BA8C5B, 0x2C69D090,\n\t\t0x9459D58D, 0x318A8946, 0x9FF81DC0, 0x3A2B410B,\n\t\t0xEF9917FA, 0x4A4A4B31, 0xE438DFB7, 0x41EB837C,\n\t\t0xF9DB8661, 0x5C08DAAA, 0xF27A4E2C, 0x57A912E7,\n\t\t0x19199215, 0xBCCACEDE, 0x12B85A58, 0xB76B0693,\n\t\t0x0F5B038E, 0xAA885F45, 0x04FACBC3, 0xA1299708,\n\t\t0x749BC1F9, 0xD1489D32, 0x7F3A09B4, 0xDAE9557F,\n\t\t0x62D95062, 0xC70A0CA9, 0x6978982F, 0xCCABC4E4\n\t}, {\n\t\t0x00000000, 0xB40B77A6, 0x29119F97, 0x9D1AE831,\n\t\t0x13244FF4, 0xA72F3852, 0x3A35D063, 0x8E3EA7C5,\n\t\t0x674EEF33, 0xD3459895, 0x4E5F70A4, 0xFA540702,\n\t\t0x746AA0C7, 0xC061D761, 0x5D7B3F50, 0xE97048F6,\n\t\t0xCE9CDE67, 0x7A97A9C1, 0xE78D41F0, 0x53863656,\n\t\t0xDDB89193, 0x69B3E635, 0xF4A90E04, 0x40A279A2,\n\t\t0xA9D23154, 0x1DD946F2, 0x80C3AEC3, 0x34C8D965,\n\t\t0xBAF67EA0, 0x0EFD0906, 0x93E7E137, 0x27EC9691,\n\t\t0x9C39BDCF, 0x2832CA69, 0xB5282258, 0x012355FE,\n\t\t0x8F1DF23B, 0x3B16859D, 0xA60C6DAC, 0x12071A0A,\n\t\t0xFB7752FC, 0x4F7C255A, 0xD266CD6B, 0x666DBACD,\n\t\t0xE8531D08, 0x5C586AAE, 0xC142829F, 0x7549F539,\n\t\t0x52A563A8, 0xE6AE140E, 0x7BB4FC3F, 0xCFBF8B99,\n\t\t0x41812C5C, 0xF58A5BFA, 0x6890B3CB, 0xDC9BC46D,\n\t\t0x35EB8C9B, 0x81E0FB3D, 0x1CFA130C, 0xA8F164AA,\n\t\t0x26CFC36F, 0x92C4B4C9, 0x0FDE5CF8, 0xBBD52B5E,\n\t\t0x79750B44, 0xCD7E7CE2, 0x506494D3, 0xE46FE375,\n\t\t0x6A5144B0, 0xDE5A3316, 0x4340DB27, 0xF74BAC81,\n\t\t0x1E3BE477, 0xAA3093D1, 0x372A7BE0, 0x83210C46,\n\t\t0x0D1FAB83, 0xB914DC25, 0x240E3414, 0x900543B2,\n\t\t0xB7E9D523, 0x03E2A285, 0x9EF84AB4, 0x2AF33D12,\n\t\t0xA4CD9AD7, 0x10C6ED71, 0x8DDC0540, 0x39D772E6,\n\t\t0xD0A73A10, 0x64AC4DB6, 0xF9B6A587, 0x4DBDD221,\n\t\t0xC38375E4, 0x77880242, 0xEA92EA73, 0x5E999DD5,\n\t\t0xE54CB68B, 0x5147C12D, 0xCC5D291C, 0x78565EBA,\n\t\t0xF668F97F, 0x42638ED9, 0xDF7966E8, 0x6B72114E,\n\t\t0x820259B8, 0x36092E1E, 0xAB13C62F, 0x1F18B189,\n\t\t0x9126164C, 0x252D61EA, 0xB83789DB, 0x0C3CFE7D,\n\t\t0x2BD068EC, 0x9FDB1F4A, 0x02C1F77B, 0xB6CA80DD,\n\t\t0x38F42718, 0x8CFF50BE, 0x11E5B88F, 0xA5EECF29,\n\t\t0x4C9E87DF, 0xF895F079, 0x658F1848, 0xD1846FEE,\n\t\t0x5FBAC82B, 0xEBB1BF8D, 0x76AB57BC, 0xC2A0201A,\n\t\t0xF2EA1688, 0x46E1612E, 0xDBFB891F, 0x6FF0FEB9,\n\t\t0xE1CE597C, 0x55C52EDA, 0xC8DFC6EB, 0x7CD4B14D,\n\t\t0x95A4F9BB, 0x21AF8E1D, 0xBCB5662C, 0x08BE118A,\n\t\t0x8680B64F, 0x328BC1E9, 0xAF9129D8, 0x1B9A5E7E,\n\t\t0x3C76C8EF, 0x887DBF49, 0x15675778, 0xA16C20DE,\n\t\t0x2F52871B, 0x9B59F0BD, 0x0643188C, 0xB2486F2A,\n\t\t0x5B3827DC, 0xEF33507A, 0x7229B84B, 0xC622CFED,\n\t\t0x481C6828, 0xFC171F8E, 0x610DF7BF, 0xD5068019,\n\t\t0x6ED3AB47, 0xDAD8DCE1, 0x47C234D0, 0xF3C94376,\n\t\t0x7DF7E4B3, 0xC9FC9315, 0x54E67B24, 0xE0ED0C82,\n\t\t0x099D4474, 0xBD9633D2, 0x208CDBE3, 0x9487AC45,\n\t\t0x1AB90B80, 0xAEB27C26, 0x33A89417, 0x87A3E3B1,\n\t\t0xA04F7520, 0x14440286, 0x895EEAB7, 0x3D559D11,\n\t\t0xB36B3AD4, 0x07604D72, 0x9A7AA543, 0x2E71D2E5,\n\t\t0xC7019A13, 0x730AEDB5, 0xEE100584, 0x5A1B7222,\n\t\t0xD425D5E7, 0x602EA241, 0xFD344A70, 0x493F3DD6,\n\t\t0x8B9F1DCC, 0x3F946A6A, 0xA28E825B, 0x1685F5FD,\n\t\t0x98BB5238, 0x2CB0259E, 0xB1AACDAF, 0x05A1BA09,\n\t\t0xECD1F2FF, 0x58DA8559, 0xC5C06D68, 0x71CB1ACE,\n\t\t0xFFF5BD0B, 0x4BFECAAD, 0xD6E4229C, 0x62EF553A,\n\t\t0x4503C3AB, 0xF108B40D, 0x6C125C3C, 0xD8192B9A,\n\t\t0x56278C5F, 0xE22CFBF9, 0x7F3613C8, 0xCB3D646E,\n\t\t0x224D2C98, 0x96465B3E, 0x0B5CB30F, 0xBF57C4A9,\n\t\t0x3169636C, 0x856214CA, 0x1878FCFB, 0xAC738B5D,\n\t\t0x17A6A003, 0xA3ADD7A5, 0x3EB73F94, 0x8ABC4832,\n\t\t0x0482EFF7, 0xB0899851, 0x2D937060, 0x999807C6,\n\t\t0x70E84F30, 0xC4E33896, 0x59F9D0A7, 0xEDF2A701,\n\t\t0x63CC00C4, 0xD7C77762, 0x4ADD9F53, 0xFED6E8F5,\n\t\t0xD93A7E64, 0x6D3109C2, 0xF02BE1F3, 0x44209655,\n\t\t0xCA1E3190, 0x7E154636, 0xE30FAE07, 0x5704D9A1,\n\t\t0xBE749157, 0x0A7FE6F1, 0x97650EC0, 0x236E7966,\n\t\t0xAD50DEA3, 0x195BA905, 0x84414134, 0x304A3692\n\t}, {\n\t\t0x00000000, 0x9E00AACC, 0x7D072542, 0xE3078F8E,\n\t\t0xFA0E4A84, 0x640EE048, 0x87096FC6, 0x1909C50A,\n\t\t0xB51BE5D3, 0x2B1B4F1F, 0xC81CC091, 0x561C6A5D,\n\t\t0x4F15AF57, 0xD115059B, 0x32128A15, 0xAC1220D9,\n\t\t0x2B31BB7C, 0xB53111B0, 0x56369E3E, 0xC83634F2,\n\t\t0xD13FF1F8, 0x4F3F5B34, 0xAC38D4BA, 0x32387E76,\n\t\t0x9E2A5EAF, 0x002AF463, 0xE32D7BED, 0x7D2DD121,\n\t\t0x6424142B, 0xFA24BEE7, 0x19233169, 0x87239BA5,\n\t\t0x566276F9, 0xC862DC35, 0x2B6553BB, 0xB565F977,\n\t\t0xAC6C3C7D, 0x326C96B1, 0xD16B193F, 0x4F6BB3F3,\n\t\t0xE379932A, 0x7D7939E6, 0x9E7EB668, 0x007E1CA4,\n\t\t0x1977D9AE, 0x87777362, 0x6470FCEC, 0xFA705620,\n\t\t0x7D53CD85, 0xE3536749, 0x0054E8C7, 0x9E54420B,\n\t\t0x875D8701, 0x195D2DCD, 0xFA5AA243, 0x645A088F,\n\t\t0xC8482856, 0x5648829A, 0xB54F0D14, 0x2B4FA7D8,\n\t\t0x324662D2, 0xAC46C81E, 0x4F414790, 0xD141ED5C,\n\t\t0xEDC29D29, 0x73C237E5, 0x90C5B86B, 0x0EC512A7,\n\t\t0x17CCD7AD, 0x89CC7D61, 0x6ACBF2EF, 0xF4CB5823,\n\t\t0x58D978FA, 0xC6D9D236, 0x25DE5DB8, 0xBBDEF774,\n\t\t0xA2D7327E, 0x3CD798B2, 0xDFD0173C, 0x41D0BDF0,\n\t\t0xC6F32655, 0x58F38C99, 0xBBF40317, 0x25F4A9DB,\n\t\t0x3CFD6CD1, 0xA2FDC61D, 0x41FA4993, 0xDFFAE35F,\n\t\t0x73E8C386, 0xEDE8694A, 0x0EEFE6C4, 0x90EF4C08,\n\t\t0x89E68902, 0x17E623CE, 0xF4E1AC40, 0x6AE1068C,\n\t\t0xBBA0EBD0, 0x25A0411C, 0xC6A7CE92, 0x58A7645E,\n\t\t0x41AEA154, 0xDFAE0B98, 0x3CA98416, 0xA2A92EDA,\n\t\t0x0EBB0E03, 0x90BBA4CF, 0x73BC2B41, 0xEDBC818D,\n\t\t0xF4B54487, 0x6AB5EE4B, 0x89B261C5, 0x17B2CB09,\n\t\t0x909150AC, 0x0E91FA60, 0xED9675EE, 0x7396DF22,\n\t\t0x6A9F1A28, 0xF49FB0E4, 0x17983F6A, 0x899895A6,\n\t\t0x258AB57F, 0xBB8A1FB3, 0x588D903D, 0xC68D3AF1,\n\t\t0xDF84FFFB, 0x41845537, 0xA283DAB9, 0x3C837075,\n\t\t0xDA853B53, 0x4485919F, 0xA7821E11, 0x3982B4DD,\n\t\t0x208B71D7, 0xBE8BDB1B, 0x5D8C5495, 0xC38CFE59,\n\t\t0x6F9EDE80, 0xF19E744C, 0x1299FBC2, 0x8C99510E,\n\t\t0x95909404, 0x0B903EC8, 0xE897B146, 0x76971B8A,\n\t\t0xF1B4802F, 0x6FB42AE3, 0x8CB3A56D, 0x12B30FA1,\n\t\t0x0BBACAAB, 0x95BA6067, 0x76BDEFE9, 0xE8BD4525,\n\t\t0x44AF65FC, 0xDAAFCF30, 0x39A840BE, 0xA7A8EA72,\n\t\t0xBEA12F78, 0x20A185B4, 0xC3A60A3A, 0x5DA6A0F6,\n\t\t0x8CE74DAA, 0x12E7E766, 0xF1E068E8, 0x6FE0C224,\n\t\t0x76E9072E, 0xE8E9ADE2, 0x0BEE226C, 0x95EE88A0,\n\t\t0x39FCA879, 0xA7FC02B5, 0x44FB8D3B, 0xDAFB27F7,\n\t\t0xC3F2E2FD, 0x5DF24831, 0xBEF5C7BF, 0x20F56D73,\n\t\t0xA7D6F6D6, 0x39D65C1A, 0xDAD1D394, 0x44D17958,\n\t\t0x5DD8BC52, 0xC3D8169E, 0x20DF9910, 0xBEDF33DC,\n\t\t0x12CD1305, 0x8CCDB9C9, 0x6FCA3647, 0xF1CA9C8B,\n\t\t0xE8C35981, 0x76C3F34D, 0x95C47CC3, 0x0BC4D60F,\n\t\t0x3747A67A, 0xA9470CB6, 0x4A408338, 0xD44029F4,\n\t\t0xCD49ECFE, 0x53494632, 0xB04EC9BC, 0x2E4E6370,\n\t\t0x825C43A9, 0x1C5CE965, 0xFF5B66EB, 0x615BCC27,\n\t\t0x7852092D, 0xE652A3E1, 0x05552C6F, 0x9B5586A3,\n\t\t0x1C761D06, 0x8276B7CA, 0x61713844, 0xFF719288,\n\t\t0xE6785782, 0x7878FD4E, 0x9B7F72C0, 0x057FD80C,\n\t\t0xA96DF8D5, 0x376D5219, 0xD46ADD97, 0x4A6A775B,\n\t\t0x5363B251, 0xCD63189D, 0x2E649713, 0xB0643DDF,\n\t\t0x6125D083, 0xFF257A4F, 0x1C22F5C1, 0x82225F0D,\n\t\t0x9B2B9A07, 0x052B30CB, 0xE62CBF45, 0x782C1589,\n\t\t0xD43E3550, 0x4A3E9F9C, 0xA9391012, 0x3739BADE,\n\t\t0x2E307FD4, 0xB030D518, 0x53375A96, 0xCD37F05A,\n\t\t0x4A146BFF, 0xD414C133, 0x37134EBD, 0xA913E471,\n\t\t0xB01A217B, 0x2E1A8BB7, 0xCD1D0439, 0x531DAEF5,\n\t\t0xFF0F8E2C, 0x610F24E0, 0x8208AB6E, 0x1C0801A2,\n\t\t0x0501C4A8, 0x9B016E64, 0x7806E1EA, 0xE6064B26\n\t}\n};\n"
  },
  {
    "path": "external/xz/liblzma/check/crc32_table_le.h",
    "content": "/* This file has been automatically generated by crc32_tablegen.c. */\n\nconst uint32_t lzma_crc32_table[8][256] = {\n\t{\n\t\t0x00000000, 0x77073096, 0xEE0E612C, 0x990951BA,\n\t\t0x076DC419, 0x706AF48F, 0xE963A535, 0x9E6495A3,\n\t\t0x0EDB8832, 0x79DCB8A4, 0xE0D5E91E, 0x97D2D988,\n\t\t0x09B64C2B, 0x7EB17CBD, 0xE7B82D07, 0x90BF1D91,\n\t\t0x1DB71064, 0x6AB020F2, 0xF3B97148, 0x84BE41DE,\n\t\t0x1ADAD47D, 0x6DDDE4EB, 0xF4D4B551, 0x83D385C7,\n\t\t0x136C9856, 0x646BA8C0, 0xFD62F97A, 0x8A65C9EC,\n\t\t0x14015C4F, 0x63066CD9, 0xFA0F3D63, 0x8D080DF5,\n\t\t0x3B6E20C8, 0x4C69105E, 0xD56041E4, 0xA2677172,\n\t\t0x3C03E4D1, 0x4B04D447, 0xD20D85FD, 0xA50AB56B,\n\t\t0x35B5A8FA, 0x42B2986C, 0xDBBBC9D6, 0xACBCF940,\n\t\t0x32D86CE3, 0x45DF5C75, 0xDCD60DCF, 0xABD13D59,\n\t\t0x26D930AC, 0x51DE003A, 0xC8D75180, 0xBFD06116,\n\t\t0x21B4F4B5, 0x56B3C423, 0xCFBA9599, 0xB8BDA50F,\n\t\t0x2802B89E, 0x5F058808, 0xC60CD9B2, 0xB10BE924,\n\t\t0x2F6F7C87, 0x58684C11, 0xC1611DAB, 0xB6662D3D,\n\t\t0x76DC4190, 0x01DB7106, 0x98D220BC, 0xEFD5102A,\n\t\t0x71B18589, 0x06B6B51F, 0x9FBFE4A5, 0xE8B8D433,\n\t\t0x7807C9A2, 0x0F00F934, 0x9609A88E, 0xE10E9818,\n\t\t0x7F6A0DBB, 0x086D3D2D, 0x91646C97, 0xE6635C01,\n\t\t0x6B6B51F4, 0x1C6C6162, 0x856530D8, 0xF262004E,\n\t\t0x6C0695ED, 0x1B01A57B, 0x8208F4C1, 0xF50FC457,\n\t\t0x65B0D9C6, 0x12B7E950, 0x8BBEB8EA, 0xFCB9887C,\n\t\t0x62DD1DDF, 0x15DA2D49, 0x8CD37CF3, 0xFBD44C65,\n\t\t0x4DB26158, 0x3AB551CE, 0xA3BC0074, 0xD4BB30E2,\n\t\t0x4ADFA541, 0x3DD895D7, 0xA4D1C46D, 0xD3D6F4FB,\n\t\t0x4369E96A, 0x346ED9FC, 0xAD678846, 0xDA60B8D0,\n\t\t0x44042D73, 0x33031DE5, 0xAA0A4C5F, 0xDD0D7CC9,\n\t\t0x5005713C, 0x270241AA, 0xBE0B1010, 0xC90C2086,\n\t\t0x5768B525, 0x206F85B3, 0xB966D409, 0xCE61E49F,\n\t\t0x5EDEF90E, 0x29D9C998, 0xB0D09822, 0xC7D7A8B4,\n\t\t0x59B33D17, 0x2EB40D81, 0xB7BD5C3B, 0xC0BA6CAD,\n\t\t0xEDB88320, 0x9ABFB3B6, 0x03B6E20C, 0x74B1D29A,\n\t\t0xEAD54739, 0x9DD277AF, 0x04DB2615, 0x73DC1683,\n\t\t0xE3630B12, 0x94643B84, 0x0D6D6A3E, 0x7A6A5AA8,\n\t\t0xE40ECF0B, 0x9309FF9D, 0x0A00AE27, 0x7D079EB1,\n\t\t0xF00F9344, 0x8708A3D2, 0x1E01F268, 0x6906C2FE,\n\t\t0xF762575D, 0x806567CB, 0x196C3671, 0x6E6B06E7,\n\t\t0xFED41B76, 0x89D32BE0, 0x10DA7A5A, 0x67DD4ACC,\n\t\t0xF9B9DF6F, 0x8EBEEFF9, 0x17B7BE43, 0x60B08ED5,\n\t\t0xD6D6A3E8, 0xA1D1937E, 0x38D8C2C4, 0x4FDFF252,\n\t\t0xD1BB67F1, 0xA6BC5767, 0x3FB506DD, 0x48B2364B,\n\t\t0xD80D2BDA, 0xAF0A1B4C, 0x36034AF6, 0x41047A60,\n\t\t0xDF60EFC3, 0xA867DF55, 0x316E8EEF, 0x4669BE79,\n\t\t0xCB61B38C, 0xBC66831A, 0x256FD2A0, 0x5268E236,\n\t\t0xCC0C7795, 0xBB0B4703, 0x220216B9, 0x5505262F,\n\t\t0xC5BA3BBE, 0xB2BD0B28, 0x2BB45A92, 0x5CB36A04,\n\t\t0xC2D7FFA7, 0xB5D0CF31, 0x2CD99E8B, 0x5BDEAE1D,\n\t\t0x9B64C2B0, 0xEC63F226, 0x756AA39C, 0x026D930A,\n\t\t0x9C0906A9, 0xEB0E363F, 0x72076785, 0x05005713,\n\t\t0x95BF4A82, 0xE2B87A14, 0x7BB12BAE, 0x0CB61B38,\n\t\t0x92D28E9B, 0xE5D5BE0D, 0x7CDCEFB7, 0x0BDBDF21,\n\t\t0x86D3D2D4, 0xF1D4E242, 0x68DDB3F8, 0x1FDA836E,\n\t\t0x81BE16CD, 0xF6B9265B, 0x6FB077E1, 0x18B74777,\n\t\t0x88085AE6, 0xFF0F6A70, 0x66063BCA, 0x11010B5C,\n\t\t0x8F659EFF, 0xF862AE69, 0x616BFFD3, 0x166CCF45,\n\t\t0xA00AE278, 0xD70DD2EE, 0x4E048354, 0x3903B3C2,\n\t\t0xA7672661, 0xD06016F7, 0x4969474D, 0x3E6E77DB,\n\t\t0xAED16A4A, 0xD9D65ADC, 0x40DF0B66, 0x37D83BF0,\n\t\t0xA9BCAE53, 0xDEBB9EC5, 0x47B2CF7F, 0x30B5FFE9,\n\t\t0xBDBDF21C, 0xCABAC28A, 0x53B39330, 0x24B4A3A6,\n\t\t0xBAD03605, 0xCDD70693, 0x54DE5729, 0x23D967BF,\n\t\t0xB3667A2E, 0xC4614AB8, 0x5D681B02, 0x2A6F2B94,\n\t\t0xB40BBE37, 0xC30C8EA1, 0x5A05DF1B, 0x2D02EF8D\n\t}, {\n\t\t0x00000000, 0x191B3141, 0x32366282, 0x2B2D53C3,\n\t\t0x646CC504, 0x7D77F445, 0x565AA786, 0x4F4196C7,\n\t\t0xC8D98A08, 0xD1C2BB49, 0xFAEFE88A, 0xE3F4D9CB,\n\t\t0xACB54F0C, 0xB5AE7E4D, 0x9E832D8E, 0x87981CCF,\n\t\t0x4AC21251, 0x53D92310, 0x78F470D3, 0x61EF4192,\n\t\t0x2EAED755, 0x37B5E614, 0x1C98B5D7, 0x05838496,\n\t\t0x821B9859, 0x9B00A918, 0xB02DFADB, 0xA936CB9A,\n\t\t0xE6775D5D, 0xFF6C6C1C, 0xD4413FDF, 0xCD5A0E9E,\n\t\t0x958424A2, 0x8C9F15E3, 0xA7B24620, 0xBEA97761,\n\t\t0xF1E8E1A6, 0xE8F3D0E7, 0xC3DE8324, 0xDAC5B265,\n\t\t0x5D5DAEAA, 0x44469FEB, 0x6F6BCC28, 0x7670FD69,\n\t\t0x39316BAE, 0x202A5AEF, 0x0B07092C, 0x121C386D,\n\t\t0xDF4636F3, 0xC65D07B2, 0xED705471, 0xF46B6530,\n\t\t0xBB2AF3F7, 0xA231C2B6, 0x891C9175, 0x9007A034,\n\t\t0x179FBCFB, 0x0E848DBA, 0x25A9DE79, 0x3CB2EF38,\n\t\t0x73F379FF, 0x6AE848BE, 0x41C51B7D, 0x58DE2A3C,\n\t\t0xF0794F05, 0xE9627E44, 0xC24F2D87, 0xDB541CC6,\n\t\t0x94158A01, 0x8D0EBB40, 0xA623E883, 0xBF38D9C2,\n\t\t0x38A0C50D, 0x21BBF44C, 0x0A96A78F, 0x138D96CE,\n\t\t0x5CCC0009, 0x45D73148, 0x6EFA628B, 0x77E153CA,\n\t\t0xBABB5D54, 0xA3A06C15, 0x888D3FD6, 0x91960E97,\n\t\t0xDED79850, 0xC7CCA911, 0xECE1FAD2, 0xF5FACB93,\n\t\t0x7262D75C, 0x6B79E61D, 0x4054B5DE, 0x594F849F,\n\t\t0x160E1258, 0x0F152319, 0x243870DA, 0x3D23419B,\n\t\t0x65FD6BA7, 0x7CE65AE6, 0x57CB0925, 0x4ED03864,\n\t\t0x0191AEA3, 0x188A9FE2, 0x33A7CC21, 0x2ABCFD60,\n\t\t0xAD24E1AF, 0xB43FD0EE, 0x9F12832D, 0x8609B26C,\n\t\t0xC94824AB, 0xD05315EA, 0xFB7E4629, 0xE2657768,\n\t\t0x2F3F79F6, 0x362448B7, 0x1D091B74, 0x04122A35,\n\t\t0x4B53BCF2, 0x52488DB3, 0x7965DE70, 0x607EEF31,\n\t\t0xE7E6F3FE, 0xFEFDC2BF, 0xD5D0917C, 0xCCCBA03D,\n\t\t0x838A36FA, 0x9A9107BB, 0xB1BC5478, 0xA8A76539,\n\t\t0x3B83984B, 0x2298A90A, 0x09B5FAC9, 0x10AECB88,\n\t\t0x5FEF5D4F, 0x46F46C0E, 0x6DD93FCD, 0x74C20E8C,\n\t\t0xF35A1243, 0xEA412302, 0xC16C70C1, 0xD8774180,\n\t\t0x9736D747, 0x8E2DE606, 0xA500B5C5, 0xBC1B8484,\n\t\t0x71418A1A, 0x685ABB5B, 0x4377E898, 0x5A6CD9D9,\n\t\t0x152D4F1E, 0x0C367E5F, 0x271B2D9C, 0x3E001CDD,\n\t\t0xB9980012, 0xA0833153, 0x8BAE6290, 0x92B553D1,\n\t\t0xDDF4C516, 0xC4EFF457, 0xEFC2A794, 0xF6D996D5,\n\t\t0xAE07BCE9, 0xB71C8DA8, 0x9C31DE6B, 0x852AEF2A,\n\t\t0xCA6B79ED, 0xD37048AC, 0xF85D1B6F, 0xE1462A2E,\n\t\t0x66DE36E1, 0x7FC507A0, 0x54E85463, 0x4DF36522,\n\t\t0x02B2F3E5, 0x1BA9C2A4, 0x30849167, 0x299FA026,\n\t\t0xE4C5AEB8, 0xFDDE9FF9, 0xD6F3CC3A, 0xCFE8FD7B,\n\t\t0x80A96BBC, 0x99B25AFD, 0xB29F093E, 0xAB84387F,\n\t\t0x2C1C24B0, 0x350715F1, 0x1E2A4632, 0x07317773,\n\t\t0x4870E1B4, 0x516BD0F5, 0x7A468336, 0x635DB277,\n\t\t0xCBFAD74E, 0xD2E1E60F, 0xF9CCB5CC, 0xE0D7848D,\n\t\t0xAF96124A, 0xB68D230B, 0x9DA070C8, 0x84BB4189,\n\t\t0x03235D46, 0x1A386C07, 0x31153FC4, 0x280E0E85,\n\t\t0x674F9842, 0x7E54A903, 0x5579FAC0, 0x4C62CB81,\n\t\t0x8138C51F, 0x9823F45E, 0xB30EA79D, 0xAA1596DC,\n\t\t0xE554001B, 0xFC4F315A, 0xD7626299, 0xCE7953D8,\n\t\t0x49E14F17, 0x50FA7E56, 0x7BD72D95, 0x62CC1CD4,\n\t\t0x2D8D8A13, 0x3496BB52, 0x1FBBE891, 0x06A0D9D0,\n\t\t0x5E7EF3EC, 0x4765C2AD, 0x6C48916E, 0x7553A02F,\n\t\t0x3A1236E8, 0x230907A9, 0x0824546A, 0x113F652B,\n\t\t0x96A779E4, 0x8FBC48A5, 0xA4911B66, 0xBD8A2A27,\n\t\t0xF2CBBCE0, 0xEBD08DA1, 0xC0FDDE62, 0xD9E6EF23,\n\t\t0x14BCE1BD, 0x0DA7D0FC, 0x268A833F, 0x3F91B27E,\n\t\t0x70D024B9, 0x69CB15F8, 0x42E6463B, 0x5BFD777A,\n\t\t0xDC656BB5, 0xC57E5AF4, 0xEE530937, 0xF7483876,\n\t\t0xB809AEB1, 0xA1129FF0, 0x8A3FCC33, 0x9324FD72\n\t}, {\n\t\t0x00000000, 0x01C26A37, 0x0384D46E, 0x0246BE59,\n\t\t0x0709A8DC, 0x06CBC2EB, 0x048D7CB2, 0x054F1685,\n\t\t0x0E1351B8, 0x0FD13B8F, 0x0D9785D6, 0x0C55EFE1,\n\t\t0x091AF964, 0x08D89353, 0x0A9E2D0A, 0x0B5C473D,\n\t\t0x1C26A370, 0x1DE4C947, 0x1FA2771E, 0x1E601D29,\n\t\t0x1B2F0BAC, 0x1AED619B, 0x18ABDFC2, 0x1969B5F5,\n\t\t0x1235F2C8, 0x13F798FF, 0x11B126A6, 0x10734C91,\n\t\t0x153C5A14, 0x14FE3023, 0x16B88E7A, 0x177AE44D,\n\t\t0x384D46E0, 0x398F2CD7, 0x3BC9928E, 0x3A0BF8B9,\n\t\t0x3F44EE3C, 0x3E86840B, 0x3CC03A52, 0x3D025065,\n\t\t0x365E1758, 0x379C7D6F, 0x35DAC336, 0x3418A901,\n\t\t0x3157BF84, 0x3095D5B3, 0x32D36BEA, 0x331101DD,\n\t\t0x246BE590, 0x25A98FA7, 0x27EF31FE, 0x262D5BC9,\n\t\t0x23624D4C, 0x22A0277B, 0x20E69922, 0x2124F315,\n\t\t0x2A78B428, 0x2BBADE1F, 0x29FC6046, 0x283E0A71,\n\t\t0x2D711CF4, 0x2CB376C3, 0x2EF5C89A, 0x2F37A2AD,\n\t\t0x709A8DC0, 0x7158E7F7, 0x731E59AE, 0x72DC3399,\n\t\t0x7793251C, 0x76514F2B, 0x7417F172, 0x75D59B45,\n\t\t0x7E89DC78, 0x7F4BB64F, 0x7D0D0816, 0x7CCF6221,\n\t\t0x798074A4, 0x78421E93, 0x7A04A0CA, 0x7BC6CAFD,\n\t\t0x6CBC2EB0, 0x6D7E4487, 0x6F38FADE, 0x6EFA90E9,\n\t\t0x6BB5866C, 0x6A77EC5B, 0x68315202, 0x69F33835,\n\t\t0x62AF7F08, 0x636D153F, 0x612BAB66, 0x60E9C151,\n\t\t0x65A6D7D4, 0x6464BDE3, 0x662203BA, 0x67E0698D,\n\t\t0x48D7CB20, 0x4915A117, 0x4B531F4E, 0x4A917579,\n\t\t0x4FDE63FC, 0x4E1C09CB, 0x4C5AB792, 0x4D98DDA5,\n\t\t0x46C49A98, 0x4706F0AF, 0x45404EF6, 0x448224C1,\n\t\t0x41CD3244, 0x400F5873, 0x4249E62A, 0x438B8C1D,\n\t\t0x54F16850, 0x55330267, 0x5775BC3E, 0x56B7D609,\n\t\t0x53F8C08C, 0x523AAABB, 0x507C14E2, 0x51BE7ED5,\n\t\t0x5AE239E8, 0x5B2053DF, 0x5966ED86, 0x58A487B1,\n\t\t0x5DEB9134, 0x5C29FB03, 0x5E6F455A, 0x5FAD2F6D,\n\t\t0xE1351B80, 0xE0F771B7, 0xE2B1CFEE, 0xE373A5D9,\n\t\t0xE63CB35C, 0xE7FED96B, 0xE5B86732, 0xE47A0D05,\n\t\t0xEF264A38, 0xEEE4200F, 0xECA29E56, 0xED60F461,\n\t\t0xE82FE2E4, 0xE9ED88D3, 0xEBAB368A, 0xEA695CBD,\n\t\t0xFD13B8F0, 0xFCD1D2C7, 0xFE976C9E, 0xFF5506A9,\n\t\t0xFA1A102C, 0xFBD87A1B, 0xF99EC442, 0xF85CAE75,\n\t\t0xF300E948, 0xF2C2837F, 0xF0843D26, 0xF1465711,\n\t\t0xF4094194, 0xF5CB2BA3, 0xF78D95FA, 0xF64FFFCD,\n\t\t0xD9785D60, 0xD8BA3757, 0xDAFC890E, 0xDB3EE339,\n\t\t0xDE71F5BC, 0xDFB39F8B, 0xDDF521D2, 0xDC374BE5,\n\t\t0xD76B0CD8, 0xD6A966EF, 0xD4EFD8B6, 0xD52DB281,\n\t\t0xD062A404, 0xD1A0CE33, 0xD3E6706A, 0xD2241A5D,\n\t\t0xC55EFE10, 0xC49C9427, 0xC6DA2A7E, 0xC7184049,\n\t\t0xC25756CC, 0xC3953CFB, 0xC1D382A2, 0xC011E895,\n\t\t0xCB4DAFA8, 0xCA8FC59F, 0xC8C97BC6, 0xC90B11F1,\n\t\t0xCC440774, 0xCD866D43, 0xCFC0D31A, 0xCE02B92D,\n\t\t0x91AF9640, 0x906DFC77, 0x922B422E, 0x93E92819,\n\t\t0x96A63E9C, 0x976454AB, 0x9522EAF2, 0x94E080C5,\n\t\t0x9FBCC7F8, 0x9E7EADCF, 0x9C381396, 0x9DFA79A1,\n\t\t0x98B56F24, 0x99770513, 0x9B31BB4A, 0x9AF3D17D,\n\t\t0x8D893530, 0x8C4B5F07, 0x8E0DE15E, 0x8FCF8B69,\n\t\t0x8A809DEC, 0x8B42F7DB, 0x89044982, 0x88C623B5,\n\t\t0x839A6488, 0x82580EBF, 0x801EB0E6, 0x81DCDAD1,\n\t\t0x8493CC54, 0x8551A663, 0x8717183A, 0x86D5720D,\n\t\t0xA9E2D0A0, 0xA820BA97, 0xAA6604CE, 0xABA46EF9,\n\t\t0xAEEB787C, 0xAF29124B, 0xAD6FAC12, 0xACADC625,\n\t\t0xA7F18118, 0xA633EB2F, 0xA4755576, 0xA5B73F41,\n\t\t0xA0F829C4, 0xA13A43F3, 0xA37CFDAA, 0xA2BE979D,\n\t\t0xB5C473D0, 0xB40619E7, 0xB640A7BE, 0xB782CD89,\n\t\t0xB2CDDB0C, 0xB30FB13B, 0xB1490F62, 0xB08B6555,\n\t\t0xBBD72268, 0xBA15485F, 0xB853F606, 0xB9919C31,\n\t\t0xBCDE8AB4, 0xBD1CE083, 0xBF5A5EDA, 0xBE9834ED\n\t}, {\n\t\t0x00000000, 0xB8BC6765, 0xAA09C88B, 0x12B5AFEE,\n\t\t0x8F629757, 0x37DEF032, 0x256B5FDC, 0x9DD738B9,\n\t\t0xC5B428EF, 0x7D084F8A, 0x6FBDE064, 0xD7018701,\n\t\t0x4AD6BFB8, 0xF26AD8DD, 0xE0DF7733, 0x58631056,\n\t\t0x5019579F, 0xE8A530FA, 0xFA109F14, 0x42ACF871,\n\t\t0xDF7BC0C8, 0x67C7A7AD, 0x75720843, 0xCDCE6F26,\n\t\t0x95AD7F70, 0x2D111815, 0x3FA4B7FB, 0x8718D09E,\n\t\t0x1ACFE827, 0xA2738F42, 0xB0C620AC, 0x087A47C9,\n\t\t0xA032AF3E, 0x188EC85B, 0x0A3B67B5, 0xB28700D0,\n\t\t0x2F503869, 0x97EC5F0C, 0x8559F0E2, 0x3DE59787,\n\t\t0x658687D1, 0xDD3AE0B4, 0xCF8F4F5A, 0x7733283F,\n\t\t0xEAE41086, 0x525877E3, 0x40EDD80D, 0xF851BF68,\n\t\t0xF02BF8A1, 0x48979FC4, 0x5A22302A, 0xE29E574F,\n\t\t0x7F496FF6, 0xC7F50893, 0xD540A77D, 0x6DFCC018,\n\t\t0x359FD04E, 0x8D23B72B, 0x9F9618C5, 0x272A7FA0,\n\t\t0xBAFD4719, 0x0241207C, 0x10F48F92, 0xA848E8F7,\n\t\t0x9B14583D, 0x23A83F58, 0x311D90B6, 0x89A1F7D3,\n\t\t0x1476CF6A, 0xACCAA80F, 0xBE7F07E1, 0x06C36084,\n\t\t0x5EA070D2, 0xE61C17B7, 0xF4A9B859, 0x4C15DF3C,\n\t\t0xD1C2E785, 0x697E80E0, 0x7BCB2F0E, 0xC377486B,\n\t\t0xCB0D0FA2, 0x73B168C7, 0x6104C729, 0xD9B8A04C,\n\t\t0x446F98F5, 0xFCD3FF90, 0xEE66507E, 0x56DA371B,\n\t\t0x0EB9274D, 0xB6054028, 0xA4B0EFC6, 0x1C0C88A3,\n\t\t0x81DBB01A, 0x3967D77F, 0x2BD27891, 0x936E1FF4,\n\t\t0x3B26F703, 0x839A9066, 0x912F3F88, 0x299358ED,\n\t\t0xB4446054, 0x0CF80731, 0x1E4DA8DF, 0xA6F1CFBA,\n\t\t0xFE92DFEC, 0x462EB889, 0x549B1767, 0xEC277002,\n\t\t0x71F048BB, 0xC94C2FDE, 0xDBF98030, 0x6345E755,\n\t\t0x6B3FA09C, 0xD383C7F9, 0xC1366817, 0x798A0F72,\n\t\t0xE45D37CB, 0x5CE150AE, 0x4E54FF40, 0xF6E89825,\n\t\t0xAE8B8873, 0x1637EF16, 0x048240F8, 0xBC3E279D,\n\t\t0x21E91F24, 0x99557841, 0x8BE0D7AF, 0x335CB0CA,\n\t\t0xED59B63B, 0x55E5D15E, 0x47507EB0, 0xFFEC19D5,\n\t\t0x623B216C, 0xDA874609, 0xC832E9E7, 0x708E8E82,\n\t\t0x28ED9ED4, 0x9051F9B1, 0x82E4565F, 0x3A58313A,\n\t\t0xA78F0983, 0x1F336EE6, 0x0D86C108, 0xB53AA66D,\n\t\t0xBD40E1A4, 0x05FC86C1, 0x1749292F, 0xAFF54E4A,\n\t\t0x322276F3, 0x8A9E1196, 0x982BBE78, 0x2097D91D,\n\t\t0x78F4C94B, 0xC048AE2E, 0xD2FD01C0, 0x6A4166A5,\n\t\t0xF7965E1C, 0x4F2A3979, 0x5D9F9697, 0xE523F1F2,\n\t\t0x4D6B1905, 0xF5D77E60, 0xE762D18E, 0x5FDEB6EB,\n\t\t0xC2098E52, 0x7AB5E937, 0x680046D9, 0xD0BC21BC,\n\t\t0x88DF31EA, 0x3063568F, 0x22D6F961, 0x9A6A9E04,\n\t\t0x07BDA6BD, 0xBF01C1D8, 0xADB46E36, 0x15080953,\n\t\t0x1D724E9A, 0xA5CE29FF, 0xB77B8611, 0x0FC7E174,\n\t\t0x9210D9CD, 0x2AACBEA8, 0x38191146, 0x80A57623,\n\t\t0xD8C66675, 0x607A0110, 0x72CFAEFE, 0xCA73C99B,\n\t\t0x57A4F122, 0xEF189647, 0xFDAD39A9, 0x45115ECC,\n\t\t0x764DEE06, 0xCEF18963, 0xDC44268D, 0x64F841E8,\n\t\t0xF92F7951, 0x41931E34, 0x5326B1DA, 0xEB9AD6BF,\n\t\t0xB3F9C6E9, 0x0B45A18C, 0x19F00E62, 0xA14C6907,\n\t\t0x3C9B51BE, 0x842736DB, 0x96929935, 0x2E2EFE50,\n\t\t0x2654B999, 0x9EE8DEFC, 0x8C5D7112, 0x34E11677,\n\t\t0xA9362ECE, 0x118A49AB, 0x033FE645, 0xBB838120,\n\t\t0xE3E09176, 0x5B5CF613, 0x49E959FD, 0xF1553E98,\n\t\t0x6C820621, 0xD43E6144, 0xC68BCEAA, 0x7E37A9CF,\n\t\t0xD67F4138, 0x6EC3265D, 0x7C7689B3, 0xC4CAEED6,\n\t\t0x591DD66F, 0xE1A1B10A, 0xF3141EE4, 0x4BA87981,\n\t\t0x13CB69D7, 0xAB770EB2, 0xB9C2A15C, 0x017EC639,\n\t\t0x9CA9FE80, 0x241599E5, 0x36A0360B, 0x8E1C516E,\n\t\t0x866616A7, 0x3EDA71C2, 0x2C6FDE2C, 0x94D3B949,\n\t\t0x090481F0, 0xB1B8E695, 0xA30D497B, 0x1BB12E1E,\n\t\t0x43D23E48, 0xFB6E592D, 0xE9DBF6C3, 0x516791A6,\n\t\t0xCCB0A91F, 0x740CCE7A, 0x66B96194, 0xDE0506F1\n\t}, {\n\t\t0x00000000, 0x3D6029B0, 0x7AC05360, 0x47A07AD0,\n\t\t0xF580A6C0, 0xC8E08F70, 0x8F40F5A0, 0xB220DC10,\n\t\t0x30704BC1, 0x0D106271, 0x4AB018A1, 0x77D03111,\n\t\t0xC5F0ED01, 0xF890C4B1, 0xBF30BE61, 0x825097D1,\n\t\t0x60E09782, 0x5D80BE32, 0x1A20C4E2, 0x2740ED52,\n\t\t0x95603142, 0xA80018F2, 0xEFA06222, 0xD2C04B92,\n\t\t0x5090DC43, 0x6DF0F5F3, 0x2A508F23, 0x1730A693,\n\t\t0xA5107A83, 0x98705333, 0xDFD029E3, 0xE2B00053,\n\t\t0xC1C12F04, 0xFCA106B4, 0xBB017C64, 0x866155D4,\n\t\t0x344189C4, 0x0921A074, 0x4E81DAA4, 0x73E1F314,\n\t\t0xF1B164C5, 0xCCD14D75, 0x8B7137A5, 0xB6111E15,\n\t\t0x0431C205, 0x3951EBB5, 0x7EF19165, 0x4391B8D5,\n\t\t0xA121B886, 0x9C419136, 0xDBE1EBE6, 0xE681C256,\n\t\t0x54A11E46, 0x69C137F6, 0x2E614D26, 0x13016496,\n\t\t0x9151F347, 0xAC31DAF7, 0xEB91A027, 0xD6F18997,\n\t\t0x64D15587, 0x59B17C37, 0x1E1106E7, 0x23712F57,\n\t\t0x58F35849, 0x659371F9, 0x22330B29, 0x1F532299,\n\t\t0xAD73FE89, 0x9013D739, 0xD7B3ADE9, 0xEAD38459,\n\t\t0x68831388, 0x55E33A38, 0x124340E8, 0x2F236958,\n\t\t0x9D03B548, 0xA0639CF8, 0xE7C3E628, 0xDAA3CF98,\n\t\t0x3813CFCB, 0x0573E67B, 0x42D39CAB, 0x7FB3B51B,\n\t\t0xCD93690B, 0xF0F340BB, 0xB7533A6B, 0x8A3313DB,\n\t\t0x0863840A, 0x3503ADBA, 0x72A3D76A, 0x4FC3FEDA,\n\t\t0xFDE322CA, 0xC0830B7A, 0x872371AA, 0xBA43581A,\n\t\t0x9932774D, 0xA4525EFD, 0xE3F2242D, 0xDE920D9D,\n\t\t0x6CB2D18D, 0x51D2F83D, 0x167282ED, 0x2B12AB5D,\n\t\t0xA9423C8C, 0x9422153C, 0xD3826FEC, 0xEEE2465C,\n\t\t0x5CC29A4C, 0x61A2B3FC, 0x2602C92C, 0x1B62E09C,\n\t\t0xF9D2E0CF, 0xC4B2C97F, 0x8312B3AF, 0xBE729A1F,\n\t\t0x0C52460F, 0x31326FBF, 0x7692156F, 0x4BF23CDF,\n\t\t0xC9A2AB0E, 0xF4C282BE, 0xB362F86E, 0x8E02D1DE,\n\t\t0x3C220DCE, 0x0142247E, 0x46E25EAE, 0x7B82771E,\n\t\t0xB1E6B092, 0x8C869922, 0xCB26E3F2, 0xF646CA42,\n\t\t0x44661652, 0x79063FE2, 0x3EA64532, 0x03C66C82,\n\t\t0x8196FB53, 0xBCF6D2E3, 0xFB56A833, 0xC6368183,\n\t\t0x74165D93, 0x49767423, 0x0ED60EF3, 0x33B62743,\n\t\t0xD1062710, 0xEC660EA0, 0xABC67470, 0x96A65DC0,\n\t\t0x248681D0, 0x19E6A860, 0x5E46D2B0, 0x6326FB00,\n\t\t0xE1766CD1, 0xDC164561, 0x9BB63FB1, 0xA6D61601,\n\t\t0x14F6CA11, 0x2996E3A1, 0x6E369971, 0x5356B0C1,\n\t\t0x70279F96, 0x4D47B626, 0x0AE7CCF6, 0x3787E546,\n\t\t0x85A73956, 0xB8C710E6, 0xFF676A36, 0xC2074386,\n\t\t0x4057D457, 0x7D37FDE7, 0x3A978737, 0x07F7AE87,\n\t\t0xB5D77297, 0x88B75B27, 0xCF1721F7, 0xF2770847,\n\t\t0x10C70814, 0x2DA721A4, 0x6A075B74, 0x576772C4,\n\t\t0xE547AED4, 0xD8278764, 0x9F87FDB4, 0xA2E7D404,\n\t\t0x20B743D5, 0x1DD76A65, 0x5A7710B5, 0x67173905,\n\t\t0xD537E515, 0xE857CCA5, 0xAFF7B675, 0x92979FC5,\n\t\t0xE915E8DB, 0xD475C16B, 0x93D5BBBB, 0xAEB5920B,\n\t\t0x1C954E1B, 0x21F567AB, 0x66551D7B, 0x5B3534CB,\n\t\t0xD965A31A, 0xE4058AAA, 0xA3A5F07A, 0x9EC5D9CA,\n\t\t0x2CE505DA, 0x11852C6A, 0x562556BA, 0x6B457F0A,\n\t\t0x89F57F59, 0xB49556E9, 0xF3352C39, 0xCE550589,\n\t\t0x7C75D999, 0x4115F029, 0x06B58AF9, 0x3BD5A349,\n\t\t0xB9853498, 0x84E51D28, 0xC34567F8, 0xFE254E48,\n\t\t0x4C059258, 0x7165BBE8, 0x36C5C138, 0x0BA5E888,\n\t\t0x28D4C7DF, 0x15B4EE6F, 0x521494BF, 0x6F74BD0F,\n\t\t0xDD54611F, 0xE03448AF, 0xA794327F, 0x9AF41BCF,\n\t\t0x18A48C1E, 0x25C4A5AE, 0x6264DF7E, 0x5F04F6CE,\n\t\t0xED242ADE, 0xD044036E, 0x97E479BE, 0xAA84500E,\n\t\t0x4834505D, 0x755479ED, 0x32F4033D, 0x0F942A8D,\n\t\t0xBDB4F69D, 0x80D4DF2D, 0xC774A5FD, 0xFA148C4D,\n\t\t0x78441B9C, 0x4524322C, 0x028448FC, 0x3FE4614C,\n\t\t0x8DC4BD5C, 0xB0A494EC, 0xF704EE3C, 0xCA64C78C\n\t}, {\n\t\t0x00000000, 0xCB5CD3A5, 0x4DC8A10B, 0x869472AE,\n\t\t0x9B914216, 0x50CD91B3, 0xD659E31D, 0x1D0530B8,\n\t\t0xEC53826D, 0x270F51C8, 0xA19B2366, 0x6AC7F0C3,\n\t\t0x77C2C07B, 0xBC9E13DE, 0x3A0A6170, 0xF156B2D5,\n\t\t0x03D6029B, 0xC88AD13E, 0x4E1EA390, 0x85427035,\n\t\t0x9847408D, 0x531B9328, 0xD58FE186, 0x1ED33223,\n\t\t0xEF8580F6, 0x24D95353, 0xA24D21FD, 0x6911F258,\n\t\t0x7414C2E0, 0xBF481145, 0x39DC63EB, 0xF280B04E,\n\t\t0x07AC0536, 0xCCF0D693, 0x4A64A43D, 0x81387798,\n\t\t0x9C3D4720, 0x57619485, 0xD1F5E62B, 0x1AA9358E,\n\t\t0xEBFF875B, 0x20A354FE, 0xA6372650, 0x6D6BF5F5,\n\t\t0x706EC54D, 0xBB3216E8, 0x3DA66446, 0xF6FAB7E3,\n\t\t0x047A07AD, 0xCF26D408, 0x49B2A6A6, 0x82EE7503,\n\t\t0x9FEB45BB, 0x54B7961E, 0xD223E4B0, 0x197F3715,\n\t\t0xE82985C0, 0x23755665, 0xA5E124CB, 0x6EBDF76E,\n\t\t0x73B8C7D6, 0xB8E41473, 0x3E7066DD, 0xF52CB578,\n\t\t0x0F580A6C, 0xC404D9C9, 0x4290AB67, 0x89CC78C2,\n\t\t0x94C9487A, 0x5F959BDF, 0xD901E971, 0x125D3AD4,\n\t\t0xE30B8801, 0x28575BA4, 0xAEC3290A, 0x659FFAAF,\n\t\t0x789ACA17, 0xB3C619B2, 0x35526B1C, 0xFE0EB8B9,\n\t\t0x0C8E08F7, 0xC7D2DB52, 0x4146A9FC, 0x8A1A7A59,\n\t\t0x971F4AE1, 0x5C439944, 0xDAD7EBEA, 0x118B384F,\n\t\t0xE0DD8A9A, 0x2B81593F, 0xAD152B91, 0x6649F834,\n\t\t0x7B4CC88C, 0xB0101B29, 0x36846987, 0xFDD8BA22,\n\t\t0x08F40F5A, 0xC3A8DCFF, 0x453CAE51, 0x8E607DF4,\n\t\t0x93654D4C, 0x58399EE9, 0xDEADEC47, 0x15F13FE2,\n\t\t0xE4A78D37, 0x2FFB5E92, 0xA96F2C3C, 0x6233FF99,\n\t\t0x7F36CF21, 0xB46A1C84, 0x32FE6E2A, 0xF9A2BD8F,\n\t\t0x0B220DC1, 0xC07EDE64, 0x46EAACCA, 0x8DB67F6F,\n\t\t0x90B34FD7, 0x5BEF9C72, 0xDD7BEEDC, 0x16273D79,\n\t\t0xE7718FAC, 0x2C2D5C09, 0xAAB92EA7, 0x61E5FD02,\n\t\t0x7CE0CDBA, 0xB7BC1E1F, 0x31286CB1, 0xFA74BF14,\n\t\t0x1EB014D8, 0xD5ECC77D, 0x5378B5D3, 0x98246676,\n\t\t0x852156CE, 0x4E7D856B, 0xC8E9F7C5, 0x03B52460,\n\t\t0xF2E396B5, 0x39BF4510, 0xBF2B37BE, 0x7477E41B,\n\t\t0x6972D4A3, 0xA22E0706, 0x24BA75A8, 0xEFE6A60D,\n\t\t0x1D661643, 0xD63AC5E6, 0x50AEB748, 0x9BF264ED,\n\t\t0x86F75455, 0x4DAB87F0, 0xCB3FF55E, 0x006326FB,\n\t\t0xF135942E, 0x3A69478B, 0xBCFD3525, 0x77A1E680,\n\t\t0x6AA4D638, 0xA1F8059D, 0x276C7733, 0xEC30A496,\n\t\t0x191C11EE, 0xD240C24B, 0x54D4B0E5, 0x9F886340,\n\t\t0x828D53F8, 0x49D1805D, 0xCF45F2F3, 0x04192156,\n\t\t0xF54F9383, 0x3E134026, 0xB8873288, 0x73DBE12D,\n\t\t0x6EDED195, 0xA5820230, 0x2316709E, 0xE84AA33B,\n\t\t0x1ACA1375, 0xD196C0D0, 0x5702B27E, 0x9C5E61DB,\n\t\t0x815B5163, 0x4A0782C6, 0xCC93F068, 0x07CF23CD,\n\t\t0xF6999118, 0x3DC542BD, 0xBB513013, 0x700DE3B6,\n\t\t0x6D08D30E, 0xA65400AB, 0x20C07205, 0xEB9CA1A0,\n\t\t0x11E81EB4, 0xDAB4CD11, 0x5C20BFBF, 0x977C6C1A,\n\t\t0x8A795CA2, 0x41258F07, 0xC7B1FDA9, 0x0CED2E0C,\n\t\t0xFDBB9CD9, 0x36E74F7C, 0xB0733DD2, 0x7B2FEE77,\n\t\t0x662ADECF, 0xAD760D6A, 0x2BE27FC4, 0xE0BEAC61,\n\t\t0x123E1C2F, 0xD962CF8A, 0x5FF6BD24, 0x94AA6E81,\n\t\t0x89AF5E39, 0x42F38D9C, 0xC467FF32, 0x0F3B2C97,\n\t\t0xFE6D9E42, 0x35314DE7, 0xB3A53F49, 0x78F9ECEC,\n\t\t0x65FCDC54, 0xAEA00FF1, 0x28347D5F, 0xE368AEFA,\n\t\t0x16441B82, 0xDD18C827, 0x5B8CBA89, 0x90D0692C,\n\t\t0x8DD55994, 0x46898A31, 0xC01DF89F, 0x0B412B3A,\n\t\t0xFA1799EF, 0x314B4A4A, 0xB7DF38E4, 0x7C83EB41,\n\t\t0x6186DBF9, 0xAADA085C, 0x2C4E7AF2, 0xE712A957,\n\t\t0x15921919, 0xDECECABC, 0x585AB812, 0x93066BB7,\n\t\t0x8E035B0F, 0x455F88AA, 0xC3CBFA04, 0x089729A1,\n\t\t0xF9C19B74, 0x329D48D1, 0xB4093A7F, 0x7F55E9DA,\n\t\t0x6250D962, 0xA90C0AC7, 0x2F987869, 0xE4C4ABCC\n\t}, {\n\t\t0x00000000, 0xA6770BB4, 0x979F1129, 0x31E81A9D,\n\t\t0xF44F2413, 0x52382FA7, 0x63D0353A, 0xC5A73E8E,\n\t\t0x33EF4E67, 0x959845D3, 0xA4705F4E, 0x020754FA,\n\t\t0xC7A06A74, 0x61D761C0, 0x503F7B5D, 0xF64870E9,\n\t\t0x67DE9CCE, 0xC1A9977A, 0xF0418DE7, 0x56368653,\n\t\t0x9391B8DD, 0x35E6B369, 0x040EA9F4, 0xA279A240,\n\t\t0x5431D2A9, 0xF246D91D, 0xC3AEC380, 0x65D9C834,\n\t\t0xA07EF6BA, 0x0609FD0E, 0x37E1E793, 0x9196EC27,\n\t\t0xCFBD399C, 0x69CA3228, 0x582228B5, 0xFE552301,\n\t\t0x3BF21D8F, 0x9D85163B, 0xAC6D0CA6, 0x0A1A0712,\n\t\t0xFC5277FB, 0x5A257C4F, 0x6BCD66D2, 0xCDBA6D66,\n\t\t0x081D53E8, 0xAE6A585C, 0x9F8242C1, 0x39F54975,\n\t\t0xA863A552, 0x0E14AEE6, 0x3FFCB47B, 0x998BBFCF,\n\t\t0x5C2C8141, 0xFA5B8AF5, 0xCBB39068, 0x6DC49BDC,\n\t\t0x9B8CEB35, 0x3DFBE081, 0x0C13FA1C, 0xAA64F1A8,\n\t\t0x6FC3CF26, 0xC9B4C492, 0xF85CDE0F, 0x5E2BD5BB,\n\t\t0x440B7579, 0xE27C7ECD, 0xD3946450, 0x75E36FE4,\n\t\t0xB044516A, 0x16335ADE, 0x27DB4043, 0x81AC4BF7,\n\t\t0x77E43B1E, 0xD19330AA, 0xE07B2A37, 0x460C2183,\n\t\t0x83AB1F0D, 0x25DC14B9, 0x14340E24, 0xB2430590,\n\t\t0x23D5E9B7, 0x85A2E203, 0xB44AF89E, 0x123DF32A,\n\t\t0xD79ACDA4, 0x71EDC610, 0x4005DC8D, 0xE672D739,\n\t\t0x103AA7D0, 0xB64DAC64, 0x87A5B6F9, 0x21D2BD4D,\n\t\t0xE47583C3, 0x42028877, 0x73EA92EA, 0xD59D995E,\n\t\t0x8BB64CE5, 0x2DC14751, 0x1C295DCC, 0xBA5E5678,\n\t\t0x7FF968F6, 0xD98E6342, 0xE86679DF, 0x4E11726B,\n\t\t0xB8590282, 0x1E2E0936, 0x2FC613AB, 0x89B1181F,\n\t\t0x4C162691, 0xEA612D25, 0xDB8937B8, 0x7DFE3C0C,\n\t\t0xEC68D02B, 0x4A1FDB9F, 0x7BF7C102, 0xDD80CAB6,\n\t\t0x1827F438, 0xBE50FF8C, 0x8FB8E511, 0x29CFEEA5,\n\t\t0xDF879E4C, 0x79F095F8, 0x48188F65, 0xEE6F84D1,\n\t\t0x2BC8BA5F, 0x8DBFB1EB, 0xBC57AB76, 0x1A20A0C2,\n\t\t0x8816EAF2, 0x2E61E146, 0x1F89FBDB, 0xB9FEF06F,\n\t\t0x7C59CEE1, 0xDA2EC555, 0xEBC6DFC8, 0x4DB1D47C,\n\t\t0xBBF9A495, 0x1D8EAF21, 0x2C66B5BC, 0x8A11BE08,\n\t\t0x4FB68086, 0xE9C18B32, 0xD82991AF, 0x7E5E9A1B,\n\t\t0xEFC8763C, 0x49BF7D88, 0x78576715, 0xDE206CA1,\n\t\t0x1B87522F, 0xBDF0599B, 0x8C184306, 0x2A6F48B2,\n\t\t0xDC27385B, 0x7A5033EF, 0x4BB82972, 0xEDCF22C6,\n\t\t0x28681C48, 0x8E1F17FC, 0xBFF70D61, 0x198006D5,\n\t\t0x47ABD36E, 0xE1DCD8DA, 0xD034C247, 0x7643C9F3,\n\t\t0xB3E4F77D, 0x1593FCC9, 0x247BE654, 0x820CEDE0,\n\t\t0x74449D09, 0xD23396BD, 0xE3DB8C20, 0x45AC8794,\n\t\t0x800BB91A, 0x267CB2AE, 0x1794A833, 0xB1E3A387,\n\t\t0x20754FA0, 0x86024414, 0xB7EA5E89, 0x119D553D,\n\t\t0xD43A6BB3, 0x724D6007, 0x43A57A9A, 0xE5D2712E,\n\t\t0x139A01C7, 0xB5ED0A73, 0x840510EE, 0x22721B5A,\n\t\t0xE7D525D4, 0x41A22E60, 0x704A34FD, 0xD63D3F49,\n\t\t0xCC1D9F8B, 0x6A6A943F, 0x5B828EA2, 0xFDF58516,\n\t\t0x3852BB98, 0x9E25B02C, 0xAFCDAAB1, 0x09BAA105,\n\t\t0xFFF2D1EC, 0x5985DA58, 0x686DC0C5, 0xCE1ACB71,\n\t\t0x0BBDF5FF, 0xADCAFE4B, 0x9C22E4D6, 0x3A55EF62,\n\t\t0xABC30345, 0x0DB408F1, 0x3C5C126C, 0x9A2B19D8,\n\t\t0x5F8C2756, 0xF9FB2CE2, 0xC813367F, 0x6E643DCB,\n\t\t0x982C4D22, 0x3E5B4696, 0x0FB35C0B, 0xA9C457BF,\n\t\t0x6C636931, 0xCA146285, 0xFBFC7818, 0x5D8B73AC,\n\t\t0x03A0A617, 0xA5D7ADA3, 0x943FB73E, 0x3248BC8A,\n\t\t0xF7EF8204, 0x519889B0, 0x6070932D, 0xC6079899,\n\t\t0x304FE870, 0x9638E3C4, 0xA7D0F959, 0x01A7F2ED,\n\t\t0xC400CC63, 0x6277C7D7, 0x539FDD4A, 0xF5E8D6FE,\n\t\t0x647E3AD9, 0xC209316D, 0xF3E12BF0, 0x55962044,\n\t\t0x90311ECA, 0x3646157E, 0x07AE0FE3, 0xA1D90457,\n\t\t0x579174BE, 0xF1E67F0A, 0xC00E6597, 0x66796E23,\n\t\t0xA3DE50AD, 0x05A95B19, 0x34414184, 0x92364A30\n\t}, {\n\t\t0x00000000, 0xCCAA009E, 0x4225077D, 0x8E8F07E3,\n\t\t0x844A0EFA, 0x48E00E64, 0xC66F0987, 0x0AC50919,\n\t\t0xD3E51BB5, 0x1F4F1B2B, 0x91C01CC8, 0x5D6A1C56,\n\t\t0x57AF154F, 0x9B0515D1, 0x158A1232, 0xD92012AC,\n\t\t0x7CBB312B, 0xB01131B5, 0x3E9E3656, 0xF23436C8,\n\t\t0xF8F13FD1, 0x345B3F4F, 0xBAD438AC, 0x767E3832,\n\t\t0xAF5E2A9E, 0x63F42A00, 0xED7B2DE3, 0x21D12D7D,\n\t\t0x2B142464, 0xE7BE24FA, 0x69312319, 0xA59B2387,\n\t\t0xF9766256, 0x35DC62C8, 0xBB53652B, 0x77F965B5,\n\t\t0x7D3C6CAC, 0xB1966C32, 0x3F196BD1, 0xF3B36B4F,\n\t\t0x2A9379E3, 0xE639797D, 0x68B67E9E, 0xA41C7E00,\n\t\t0xAED97719, 0x62737787, 0xECFC7064, 0x205670FA,\n\t\t0x85CD537D, 0x496753E3, 0xC7E85400, 0x0B42549E,\n\t\t0x01875D87, 0xCD2D5D19, 0x43A25AFA, 0x8F085A64,\n\t\t0x562848C8, 0x9A824856, 0x140D4FB5, 0xD8A74F2B,\n\t\t0xD2624632, 0x1EC846AC, 0x9047414F, 0x5CED41D1,\n\t\t0x299DC2ED, 0xE537C273, 0x6BB8C590, 0xA712C50E,\n\t\t0xADD7CC17, 0x617DCC89, 0xEFF2CB6A, 0x2358CBF4,\n\t\t0xFA78D958, 0x36D2D9C6, 0xB85DDE25, 0x74F7DEBB,\n\t\t0x7E32D7A2, 0xB298D73C, 0x3C17D0DF, 0xF0BDD041,\n\t\t0x5526F3C6, 0x998CF358, 0x1703F4BB, 0xDBA9F425,\n\t\t0xD16CFD3C, 0x1DC6FDA2, 0x9349FA41, 0x5FE3FADF,\n\t\t0x86C3E873, 0x4A69E8ED, 0xC4E6EF0E, 0x084CEF90,\n\t\t0x0289E689, 0xCE23E617, 0x40ACE1F4, 0x8C06E16A,\n\t\t0xD0EBA0BB, 0x1C41A025, 0x92CEA7C6, 0x5E64A758,\n\t\t0x54A1AE41, 0x980BAEDF, 0x1684A93C, 0xDA2EA9A2,\n\t\t0x030EBB0E, 0xCFA4BB90, 0x412BBC73, 0x8D81BCED,\n\t\t0x8744B5F4, 0x4BEEB56A, 0xC561B289, 0x09CBB217,\n\t\t0xAC509190, 0x60FA910E, 0xEE7596ED, 0x22DF9673,\n\t\t0x281A9F6A, 0xE4B09FF4, 0x6A3F9817, 0xA6959889,\n\t\t0x7FB58A25, 0xB31F8ABB, 0x3D908D58, 0xF13A8DC6,\n\t\t0xFBFF84DF, 0x37558441, 0xB9DA83A2, 0x7570833C,\n\t\t0x533B85DA, 0x9F918544, 0x111E82A7, 0xDDB48239,\n\t\t0xD7718B20, 0x1BDB8BBE, 0x95548C5D, 0x59FE8CC3,\n\t\t0x80DE9E6F, 0x4C749EF1, 0xC2FB9912, 0x0E51998C,\n\t\t0x04949095, 0xC83E900B, 0x46B197E8, 0x8A1B9776,\n\t\t0x2F80B4F1, 0xE32AB46F, 0x6DA5B38C, 0xA10FB312,\n\t\t0xABCABA0B, 0x6760BA95, 0xE9EFBD76, 0x2545BDE8,\n\t\t0xFC65AF44, 0x30CFAFDA, 0xBE40A839, 0x72EAA8A7,\n\t\t0x782FA1BE, 0xB485A120, 0x3A0AA6C3, 0xF6A0A65D,\n\t\t0xAA4DE78C, 0x66E7E712, 0xE868E0F1, 0x24C2E06F,\n\t\t0x2E07E976, 0xE2ADE9E8, 0x6C22EE0B, 0xA088EE95,\n\t\t0x79A8FC39, 0xB502FCA7, 0x3B8DFB44, 0xF727FBDA,\n\t\t0xFDE2F2C3, 0x3148F25D, 0xBFC7F5BE, 0x736DF520,\n\t\t0xD6F6D6A7, 0x1A5CD639, 0x94D3D1DA, 0x5879D144,\n\t\t0x52BCD85D, 0x9E16D8C3, 0x1099DF20, 0xDC33DFBE,\n\t\t0x0513CD12, 0xC9B9CD8C, 0x4736CA6F, 0x8B9CCAF1,\n\t\t0x8159C3E8, 0x4DF3C376, 0xC37CC495, 0x0FD6C40B,\n\t\t0x7AA64737, 0xB60C47A9, 0x3883404A, 0xF42940D4,\n\t\t0xFEEC49CD, 0x32464953, 0xBCC94EB0, 0x70634E2E,\n\t\t0xA9435C82, 0x65E95C1C, 0xEB665BFF, 0x27CC5B61,\n\t\t0x2D095278, 0xE1A352E6, 0x6F2C5505, 0xA386559B,\n\t\t0x061D761C, 0xCAB77682, 0x44387161, 0x889271FF,\n\t\t0x825778E6, 0x4EFD7878, 0xC0727F9B, 0x0CD87F05,\n\t\t0xD5F86DA9, 0x19526D37, 0x97DD6AD4, 0x5B776A4A,\n\t\t0x51B26353, 0x9D1863CD, 0x1397642E, 0xDF3D64B0,\n\t\t0x83D02561, 0x4F7A25FF, 0xC1F5221C, 0x0D5F2282,\n\t\t0x079A2B9B, 0xCB302B05, 0x45BF2CE6, 0x89152C78,\n\t\t0x50353ED4, 0x9C9F3E4A, 0x121039A9, 0xDEBA3937,\n\t\t0xD47F302E, 0x18D530B0, 0x965A3753, 0x5AF037CD,\n\t\t0xFF6B144A, 0x33C114D4, 0xBD4E1337, 0x71E413A9,\n\t\t0x7B211AB0, 0xB78B1A2E, 0x39041DCD, 0xF5AE1D53,\n\t\t0x2C8E0FFF, 0xE0240F61, 0x6EAB0882, 0xA201081C,\n\t\t0xA8C40105, 0x646E019B, 0xEAE10678, 0x264B06E6\n\t}\n};\n"
  },
  {
    "path": "external/xz/liblzma/check/crc32_tablegen.c",
    "content": "///////////////////////////////////////////////////////////////////////////////\n//\n/// \\file       crc32_tablegen.c\n/// \\brief      Generate crc32_table_le.h and crc32_table_be.h\n///\n/// Compiling: gcc -std=c99 -o crc32_tablegen crc32_tablegen.c\n/// Add -DWORDS_BIGENDIAN to generate big endian table.\n/// Add -DLZ_HASH_TABLE to generate lz_encoder_hash_table.h (little endian).\n//\n//  Author:     Lasse Collin\n//\n//  This file has been put into the public domain.\n//  You can do whatever you want with this file.\n//\n///////////////////////////////////////////////////////////////////////////////\n\n#include <stdio.h>\n#include \"../../common/tuklib_integer.h\"\n\n\nstatic uint32_t crc32_table[8][256];\n\n\nstatic void\ninit_crc32_table(void)\n{\n\tstatic const uint32_t poly32 = UINT32_C(0xEDB88320);\n\n\tfor (size_t s = 0; s < 8; ++s) {\n\t\tfor (size_t b = 0; b < 256; ++b) {\n\t\t\tuint32_t r = s == 0 ? b : crc32_table[s - 1][b];\n\n\t\t\tfor (size_t i = 0; i < 8; ++i) {\n\t\t\t\tif (r & 1)\n\t\t\t\t\tr = (r >> 1) ^ poly32;\n\t\t\t\telse\n\t\t\t\t\tr >>= 1;\n\t\t\t}\n\n\t\t\tcrc32_table[s][b] = r;\n\t\t}\n\t}\n\n#ifdef WORDS_BIGENDIAN\n\tfor (size_t s = 0; s < 8; ++s)\n\t\tfor (size_t b = 0; b < 256; ++b)\n\t\t\tcrc32_table[s][b] = bswap32(crc32_table[s][b]);\n#endif\n\n\treturn;\n}\n\n\nstatic void\nprint_crc32_table(void)\n{\n\tprintf(\"/* This file has been automatically generated by \"\n\t\t\t\"crc32_tablegen.c. */\\n\\n\"\n\t\t\t\"const uint32_t lzma_crc32_table[8][256] = {\\n\\t{\");\n\n\tfor (size_t s = 0; s < 8; ++s) {\n\t\tfor (size_t b = 0; b < 256; ++b) {\n\t\t\tif ((b % 4) == 0)\n\t\t\t\tprintf(\"\\n\\t\\t\");\n\n\t\t\tprintf(\"0x%08\" PRIX32, crc32_table[s][b]);\n\n\t\t\tif (b != 255)\n\t\t\t\tprintf(\",%s\", (b+1) % 4 == 0 ? \"\" : \" \");\n\t\t}\n\n\t\tif (s == 7)\n\t\t\tprintf(\"\\n\\t}\\n};\\n\");\n\t\telse\n\t\t\tprintf(\"\\n\\t}, {\");\n\t}\n\n\treturn;\n}\n\n\nstatic void\nprint_lz_table(void)\n{\n\tprintf(\"/* This file has been automatically generated by \"\n\t\t\t\"crc32_tablegen.c. */\\n\\n\"\n\t\t\t\"const uint32_t lzma_lz_hash_table[256] = {\");\n\n\tfor (size_t b = 0; b < 256; ++b) {\n\t\tif ((b % 4) == 0)\n\t\t\tprintf(\"\\n\\t\");\n\n\t\tprintf(\"0x%08\" PRIX32, crc32_table[0][b]);\n\n\t\tif (b != 255)\n\t\t\tprintf(\",%s\", (b+1) % 4 == 0 ? \"\" : \" \");\n\t}\n\n\tprintf(\"\\n};\\n\");\n\n\treturn;\n}\n\n\nint\nmain(void)\n{\n\tinit_crc32_table();\n\n#ifdef LZ_HASH_TABLE\n\tprint_lz_table();\n#else\n\tprint_crc32_table();\n#endif\n\n\treturn 0;\n}\n"
  },
  {
    "path": "external/xz/liblzma/check/crc32_x86.S",
    "content": "/*\n * Speed-optimized CRC32 using slicing-by-eight algorithm\n *\n * This uses only i386 instructions, but it is optimized for i686 and later\n * (including e.g. Pentium II/III/IV, Athlon XP, and Core 2). For i586\n * (e.g. Pentium), slicing-by-four would be better, and even the C version\n * of slicing-by-eight built with gcc -march=i586 tends to be a little bit\n * better than this. Very few probably run this code on i586 or older x86\n * so this shouldn't be a problem in practice.\n *\n * Authors: Igor Pavlov (original version)\n *          Lasse Collin (AT&T syntax, PIC support, better portability)\n *\n * This file has been put into the public domain.\n * You can do whatever you want with this file.\n *\n * This code needs lzma_crc32_table, which can be created using the\n * following C code:\n\nuint32_t lzma_crc32_table[8][256];\n\nvoid\ninit_table(void)\n{\n\t// IEEE-802.3\n\tstatic const uint32_t poly32 = UINT32_C(0xEDB88320);\n\n\t// Castagnoli\n\t// static const uint32_t poly32 = UINT32_C(0x82F63B78);\n\n\t// Koopman\n\t// static const uint32_t poly32 = UINT32_C(0xEB31D82E);\n\n\tfor (size_t s = 0; s < 8; ++s) {\n\t\tfor (size_t b = 0; b < 256; ++b) {\n\t\t\tuint32_t r = s == 0 ? b : lzma_crc32_table[s - 1][b];\n\n\t\t\tfor (size_t i = 0; i < 8; ++i) {\n\t\t\t\tif (r & 1)\n\t\t\t\t\tr = (r >> 1) ^ poly32;\n\t\t\t\telse\n\t\t\t\t\tr >>= 1;\n\t\t\t}\n\n\t\t\tlzma_crc32_table[s][b] = r;\n\t\t}\n\t}\n}\n\n * The prototype of the CRC32 function:\n * extern uint32_t lzma_crc32(const uint8_t *buf, size_t size, uint32_t crc);\n */\n\n/*\n * On some systems, the functions need to be prefixed. The prefix is\n * usually an underscore.\n */\n#ifndef __USER_LABEL_PREFIX__\n#\tdefine __USER_LABEL_PREFIX__\n#endif\n#define MAKE_SYM_CAT(prefix, sym) prefix ## sym\n#define MAKE_SYM(prefix, sym) MAKE_SYM_CAT(prefix, sym)\n#define LZMA_CRC32 MAKE_SYM(__USER_LABEL_PREFIX__, lzma_crc32)\n#define LZMA_CRC32_TABLE MAKE_SYM(__USER_LABEL_PREFIX__, lzma_crc32_table)\n\n/*\n * Solaris assembler doesn't have .p2align, and Darwin uses .align\n * differently than GNU/Linux and Solaris.\n */\n#if defined(__APPLE__) || defined(__MSDOS__)\n#\tdefine ALIGN(pow2, abs) .align pow2\n#else\n#\tdefine ALIGN(pow2, abs) .align abs\n#endif\n\n\t.text\n\t.globl\tLZMA_CRC32\n\n#if !defined(__APPLE__) && !defined(_WIN32) && !defined(__CYGWIN__) \\\n\t\t&& !defined(__MSDOS__)\n\t.type\tLZMA_CRC32, @function\n#endif\n\n\tALIGN(4, 16)\nLZMA_CRC32:\n\t/*\n\t * Register usage:\n\t * %eax crc\n\t * %esi buf\n\t * %edi size or buf + size\n\t * %ebx lzma_crc32_table\n\t * %ebp Table index\n\t * %ecx Temporary\n\t * %edx Temporary\n\t */\n\tpushl\t%ebx\n\tpushl\t%esi\n\tpushl\t%edi\n\tpushl\t%ebp\n\tmovl\t0x14(%esp), %esi /* buf */\n\tmovl\t0x18(%esp), %edi /* size */\n\tmovl\t0x1C(%esp), %eax /* crc */\n\n\t/*\n\t * Store the address of lzma_crc32_table to %ebx. This is needed to\n\t * get position-independent code (PIC).\n\t *\n\t * The PIC macro is defined by libtool, while __PIC__ is defined\n\t * by GCC but only on some systems. Testing for both makes it simpler\n\t * to test this code without libtool, and keeps the code working also\n\t * when built with libtool but using something else than GCC.\n\t *\n\t * I understood that libtool may define PIC on Windows even though\n\t * the code in Windows DLLs is not PIC in sense that it is in ELF\n\t * binaries, so we need a separate check to always use the non-PIC\n\t * code on Windows.\n\t */\n#if (!defined(PIC) && !defined(__PIC__)) \\\n\t\t|| (defined(_WIN32) || defined(__CYGWIN__))\n\t/* Not PIC */\n\tmovl\t$ LZMA_CRC32_TABLE, %ebx\n#elif defined(__APPLE__)\n\t/* Mach-O */\n\tcall\t.L_get_pc\n.L_pic:\n\tleal\t.L_lzma_crc32_table$non_lazy_ptr-.L_pic(%ebx), %ebx\n\tmovl\t(%ebx), %ebx\n#else\n\t/* ELF */\n\tcall\t.L_get_pc\n\taddl\t$_GLOBAL_OFFSET_TABLE_, %ebx\n\tmovl\tLZMA_CRC32_TABLE@GOT(%ebx), %ebx\n#endif\n\n\t/* Complement the initial value. */\n\tnotl\t%eax\n\n\tALIGN(4, 16)\n.L_align:\n\t/*\n\t * Check if there is enough input to use slicing-by-eight.\n\t * We need 16 bytes, because the loop pre-reads eight bytes.\n\t */\n\tcmpl\t$16, %edi\n\tjb\t.L_rest\n\n\t/* Check if we have reached alignment of eight bytes. */\n\ttestl\t$7, %esi\n\tjz\t.L_slice\n\n\t/* Calculate CRC of the next input byte. */\n\tmovzbl\t(%esi), %ebp\n\tincl\t%esi\n\tmovzbl\t%al, %ecx\n\txorl\t%ecx, %ebp\n\tshrl\t$8, %eax\n\txorl\t(%ebx, %ebp, 4), %eax\n\tdecl\t%edi\n\tjmp\t.L_align\n\n\tALIGN(2, 4)\n.L_slice:\n\t/*\n\t * If we get here, there's at least 16 bytes of aligned input\n\t * available. Make %edi multiple of eight bytes. Store the possible\n\t * remainder over the \"size\" variable in the argument stack.\n\t */\n\tmovl\t%edi, 0x18(%esp)\n\tandl\t$-8, %edi\n\tsubl\t%edi, 0x18(%esp)\n\n\t/*\n\t * Let %edi be buf + size - 8 while running the main loop. This way\n\t * we can compare for equality to determine when exit the loop.\n\t */\n\taddl\t%esi, %edi\n\tsubl\t$8, %edi\n\n\t/* Read in the first eight aligned bytes. */\n\txorl\t(%esi), %eax\n\tmovl\t4(%esi), %ecx\n\tmovzbl\t%cl, %ebp\n\n.L_loop:\n\tmovl\t0x0C00(%ebx, %ebp, 4), %edx\n\tmovzbl\t%ch, %ebp\n\txorl\t0x0800(%ebx, %ebp, 4), %edx\n\tshrl\t$16, %ecx\n\txorl\t8(%esi), %edx\n\tmovzbl\t%cl, %ebp\n\txorl\t0x0400(%ebx, %ebp, 4), %edx\n\tmovzbl\t%ch, %ebp\n\txorl\t(%ebx, %ebp, 4), %edx\n\tmovzbl\t%al, %ebp\n\n\t/*\n\t * Read the next four bytes, for which the CRC is calculated\n\t * on the next interation of the loop.\n\t */\n\tmovl\t12(%esi), %ecx\n\n\txorl\t0x1C00(%ebx, %ebp, 4), %edx\n\tmovzbl\t%ah, %ebp\n\tshrl\t$16, %eax\n\txorl\t0x1800(%ebx, %ebp, 4), %edx\n\tmovzbl\t%ah, %ebp\n\tmovzbl\t%al, %eax\n\tmovl\t0x1400(%ebx, %eax, 4), %eax\n\taddl\t$8, %esi\n\txorl\t%edx, %eax\n\txorl\t0x1000(%ebx, %ebp, 4), %eax\n\n\t/* Check for end of aligned input. */\n\tcmpl\t%edi, %esi\n\tmovzbl\t%cl, %ebp\n\tjne\t.L_loop\n\n\t/*\n\t * Process the remaining eight bytes, which we have already\n\t * copied to %ecx and %edx.\n\t */\n\tmovl\t0x0C00(%ebx, %ebp, 4), %edx\n\tmovzbl\t%ch, %ebp\n\txorl\t0x0800(%ebx, %ebp, 4), %edx\n\tshrl\t$16, %ecx\n\tmovzbl\t%cl, %ebp\n\txorl\t0x0400(%ebx, %ebp, 4), %edx\n\tmovzbl\t%ch, %ebp\n\txorl\t(%ebx, %ebp, 4), %edx\n\tmovzbl\t%al, %ebp\n\n\txorl\t0x1C00(%ebx, %ebp, 4), %edx\n\tmovzbl\t%ah, %ebp\n\tshrl\t$16, %eax\n\txorl\t0x1800(%ebx, %ebp, 4), %edx\n\tmovzbl\t%ah, %ebp\n\tmovzbl\t%al, %eax\n\tmovl\t0x1400(%ebx, %eax, 4), %eax\n\taddl\t$8, %esi\n\txorl\t%edx, %eax\n\txorl\t0x1000(%ebx, %ebp, 4), %eax\n\n\t/* Copy the number of remaining bytes to %edi. */\n\tmovl\t0x18(%esp), %edi\n\n.L_rest:\n\t/* Check for end of input. */\n\ttestl\t%edi, %edi\n\tjz\t.L_return\n\n\t/* Calculate CRC of the next input byte. */\n\tmovzbl\t(%esi), %ebp\n\tincl\t%esi\n\tmovzbl\t%al, %ecx\n\txorl\t%ecx, %ebp\n\tshrl\t$8, %eax\n\txorl\t(%ebx, %ebp, 4), %eax\n\tdecl\t%edi\n\tjmp\t.L_rest\n\n.L_return:\n\t/* Complement the final value. */\n\tnotl\t%eax\n\n\tpopl\t%ebp\n\tpopl\t%edi\n\tpopl\t%esi\n\tpopl\t%ebx\n\tret\n\n#if defined(PIC) || defined(__PIC__)\n\tALIGN(4, 16)\n.L_get_pc:\n\tmovl\t(%esp), %ebx\n\tret\n#endif\n\n#if defined(__APPLE__) && (defined(PIC) || defined(__PIC__))\n\t/* Mach-O PIC */\n\t.section __IMPORT,__pointers,non_lazy_symbol_pointers\n.L_lzma_crc32_table$non_lazy_ptr:\n\t.indirect_symbol LZMA_CRC32_TABLE\n\t.long 0\n\n#elif defined(_WIN32) || defined(__CYGWIN__)\n#\tifdef DLL_EXPORT\n\t/* This is equivalent of __declspec(dllexport). */\n\t.section .drectve\n\t.ascii \" -export:lzma_crc32\"\n#\tendif\n\n#elif !defined(__MSDOS__)\n\t/* ELF */\n\t.size\tLZMA_CRC32, .-LZMA_CRC32\n#endif\n\n/*\n * This is needed to support non-executable stack. It's ugly to\n * use __linux__ here, but I don't know a way to detect when\n * we are using GNU assembler.\n */\n#if defined(__ELF__) && defined(__linux__)\n\t.section\t.note.GNU-stack,\"\",@progbits\n#endif\n"
  },
  {
    "path": "external/xz/liblzma/check/crc64_fast.c",
    "content": "///////////////////////////////////////////////////////////////////////////////\n//\n/// \\file       crc64.c\n/// \\brief      CRC64 calculation\n///\n/// Calculate the CRC64 using the slice-by-four algorithm. This is the same\n/// idea that is used in crc32_fast.c, but for CRC64 we use only four tables\n/// instead of eight to avoid increasing CPU cache usage.\n//\n//  Author:     Lasse Collin\n//\n//  This file has been put into the public domain.\n//  You can do whatever you want with this file.\n//\n///////////////////////////////////////////////////////////////////////////////\n\n#include \"check.h\"\n#include \"crc_macros.h\"\n\n\n#ifdef WORDS_BIGENDIAN\n#\tdefine A1(x) ((x) >> 56)\n#else\n#\tdefine A1 A\n#endif\n\n\n// See the comments in crc32_fast.c. They aren't duplicated here.\nextern LZMA_API(uint64_t)\nlzma_crc64(const uint8_t *buf, size_t size, uint64_t crc)\n{\n\tcrc = ~crc;\n\n#ifdef WORDS_BIGENDIAN\n\tcrc = bswap64(crc);\n#endif\n\n\tif (size > 4) {\n\t\twhile ((uintptr_t)(buf) & 3) {\n\t\t\tcrc = lzma_crc64_table[0][*buf++ ^ A1(crc)] ^ S8(crc);\n\t\t\t--size;\n\t\t}\n\n\t\tconst uint8_t *const limit = buf + (size & ~(size_t)(3));\n\t\tsize &= (size_t)(3);\n\n\t\twhile (buf < limit) {\n#ifdef WORDS_BIGENDIAN\n\t\t\tconst uint32_t tmp = (crc >> 32)\n\t\t\t\t\t^ aligned_read32ne(buf);\n#else\n\t\t\tconst uint32_t tmp = crc ^ aligned_read32ne(buf);\n#endif\n\t\t\tbuf += 4;\n\n\t\t\tcrc = lzma_crc64_table[3][A(tmp)]\n\t\t\t    ^ lzma_crc64_table[2][B(tmp)]\n\t\t\t    ^ S32(crc)\n\t\t\t    ^ lzma_crc64_table[1][C(tmp)]\n\t\t\t    ^ lzma_crc64_table[0][D(tmp)];\n\t\t}\n\t}\n\n\twhile (size-- != 0)\n\t\tcrc = lzma_crc64_table[0][*buf++ ^ A1(crc)] ^ S8(crc);\n\n#ifdef WORDS_BIGENDIAN\n\tcrc = bswap64(crc);\n#endif\n\n\treturn ~crc;\n}\n"
  },
  {
    "path": "external/xz/liblzma/check/crc64_small.c",
    "content": "///////////////////////////////////////////////////////////////////////////////\n//\n/// \\file       crc64_small.c\n/// \\brief      CRC64 calculation (size-optimized)\n//\n//  Author:     Lasse Collin\n//\n//  This file has been put into the public domain.\n//  You can do whatever you want with this file.\n//\n///////////////////////////////////////////////////////////////////////////////\n\n#include \"check.h\"\n\n\nstatic uint64_t crc64_table[256];\n\n\nstatic void\ncrc64_init(void)\n{\n\tstatic const uint64_t poly64 = UINT64_C(0xC96C5795D7870F42);\n\n\tfor (size_t b = 0; b < 256; ++b) {\n\t\tuint64_t r = b;\n\t\tfor (size_t i = 0; i < 8; ++i) {\n\t\t\tif (r & 1)\n\t\t\t\tr = (r >> 1) ^ poly64;\n\t\t\telse\n\t\t\t\tr >>= 1;\n\t\t}\n\n\t\tcrc64_table[b] = r;\n\t}\n\n\treturn;\n}\n\n\nextern LZMA_API(uint64_t)\nlzma_crc64(const uint8_t *buf, size_t size, uint64_t crc)\n{\n\tmythread_once(crc64_init);\n\n\tcrc = ~crc;\n\n\twhile (size != 0) {\n\t\tcrc = crc64_table[*buf++ ^ (crc & 0xFF)] ^ (crc >> 8);\n\t\t--size;\n\t}\n\n\treturn ~crc;\n}\n"
  },
  {
    "path": "external/xz/liblzma/check/crc64_table.c",
    "content": "///////////////////////////////////////////////////////////////////////////////\n//\n/// \\file       crc64_table.c\n/// \\brief      Precalculated CRC64 table with correct endianness\n//\n//  Author:     Lasse Collin\n//\n//  This file has been put into the public domain.\n//  You can do whatever you want with this file.\n//\n///////////////////////////////////////////////////////////////////////////////\n\n#include \"common.h\"\n\n// Having the declaration here silences clang -Wmissing-variable-declarations.\nextern const uint64_t lzma_crc64_table[4][256];\n\n#ifdef WORDS_BIGENDIAN\n#\tinclude \"crc64_table_be.h\"\n#else\n#\tinclude \"crc64_table_le.h\"\n#endif\n"
  },
  {
    "path": "external/xz/liblzma/check/crc64_table_be.h",
    "content": "/* This file has been automatically generated by crc64_tablegen.c. */\n\nconst uint64_t lzma_crc64_table[4][256] = {\n\t{\n\t\tUINT64_C(0x0000000000000000), UINT64_C(0x6F5FA703BE4C2EB3),\n\t\tUINT64_C(0x5BA040A8573684F4), UINT64_C(0x34FFE7ABE97AAA47),\n\t\tUINT64_C(0x335E8FFF84C3D07B), UINT64_C(0x5C0128FC3A8FFEC8),\n\t\tUINT64_C(0x68FECF57D3F5548F), UINT64_C(0x07A168546DB97A3C),\n\t\tUINT64_C(0x66BC1EFF0987A1F7), UINT64_C(0x09E3B9FCB7CB8F44),\n\t\tUINT64_C(0x3D1C5E575EB12503), UINT64_C(0x5243F954E0FD0BB0),\n\t\tUINT64_C(0x55E291008D44718C), UINT64_C(0x3ABD360333085F3F),\n\t\tUINT64_C(0x0E42D1A8DA72F578), UINT64_C(0x611D76AB643EDBCB),\n\t\tUINT64_C(0x4966335138A19B7D), UINT64_C(0x2639945286EDB5CE),\n\t\tUINT64_C(0x12C673F96F971F89), UINT64_C(0x7D99D4FAD1DB313A),\n\t\tUINT64_C(0x7A38BCAEBC624B06), UINT64_C(0x15671BAD022E65B5),\n\t\tUINT64_C(0x2198FC06EB54CFF2), UINT64_C(0x4EC75B055518E141),\n\t\tUINT64_C(0x2FDA2DAE31263A8A), UINT64_C(0x40858AAD8F6A1439),\n\t\tUINT64_C(0x747A6D066610BE7E), UINT64_C(0x1B25CA05D85C90CD),\n\t\tUINT64_C(0x1C84A251B5E5EAF1), UINT64_C(0x73DB05520BA9C442),\n\t\tUINT64_C(0x4724E2F9E2D36E05), UINT64_C(0x287B45FA5C9F40B6),\n\t\tUINT64_C(0x92CC66A2704237FB), UINT64_C(0xFD93C1A1CE0E1948),\n\t\tUINT64_C(0xC96C260A2774B30F), UINT64_C(0xA633810999389DBC),\n\t\tUINT64_C(0xA192E95DF481E780), UINT64_C(0xCECD4E5E4ACDC933),\n\t\tUINT64_C(0xFA32A9F5A3B76374), UINT64_C(0x956D0EF61DFB4DC7),\n\t\tUINT64_C(0xF470785D79C5960C), UINT64_C(0x9B2FDF5EC789B8BF),\n\t\tUINT64_C(0xAFD038F52EF312F8), UINT64_C(0xC08F9FF690BF3C4B),\n\t\tUINT64_C(0xC72EF7A2FD064677), UINT64_C(0xA87150A1434A68C4),\n\t\tUINT64_C(0x9C8EB70AAA30C283), UINT64_C(0xF3D11009147CEC30),\n\t\tUINT64_C(0xDBAA55F348E3AC86), UINT64_C(0xB4F5F2F0F6AF8235),\n\t\tUINT64_C(0x800A155B1FD52872), UINT64_C(0xEF55B258A19906C1),\n\t\tUINT64_C(0xE8F4DA0CCC207CFD), UINT64_C(0x87AB7D0F726C524E),\n\t\tUINT64_C(0xB3549AA49B16F809), UINT64_C(0xDC0B3DA7255AD6BA),\n\t\tUINT64_C(0xBD164B0C41640D71), UINT64_C(0xD249EC0FFF2823C2),\n\t\tUINT64_C(0xE6B60BA416528985), UINT64_C(0x89E9ACA7A81EA736),\n\t\tUINT64_C(0x8E48C4F3C5A7DD0A), UINT64_C(0xE11763F07BEBF3B9),\n\t\tUINT64_C(0xD5E8845B929159FE), UINT64_C(0xBAB723582CDD774D),\n\t\tUINT64_C(0xA187C3EBCA2BB664), UINT64_C(0xCED864E8746798D7),\n\t\tUINT64_C(0xFA2783439D1D3290), UINT64_C(0x9578244023511C23),\n\t\tUINT64_C(0x92D94C144EE8661F), UINT64_C(0xFD86EB17F0A448AC),\n\t\tUINT64_C(0xC9790CBC19DEE2EB), UINT64_C(0xA626ABBFA792CC58),\n\t\tUINT64_C(0xC73BDD14C3AC1793), UINT64_C(0xA8647A177DE03920),\n\t\tUINT64_C(0x9C9B9DBC949A9367), UINT64_C(0xF3C43ABF2AD6BDD4),\n\t\tUINT64_C(0xF46552EB476FC7E8), UINT64_C(0x9B3AF5E8F923E95B),\n\t\tUINT64_C(0xAFC512431059431C), UINT64_C(0xC09AB540AE156DAF),\n\t\tUINT64_C(0xE8E1F0BAF28A2D19), UINT64_C(0x87BE57B94CC603AA),\n\t\tUINT64_C(0xB341B012A5BCA9ED), UINT64_C(0xDC1E17111BF0875E),\n\t\tUINT64_C(0xDBBF7F457649FD62), UINT64_C(0xB4E0D846C805D3D1),\n\t\tUINT64_C(0x801F3FED217F7996), UINT64_C(0xEF4098EE9F335725),\n\t\tUINT64_C(0x8E5DEE45FB0D8CEE), UINT64_C(0xE10249464541A25D),\n\t\tUINT64_C(0xD5FDAEEDAC3B081A), UINT64_C(0xBAA209EE127726A9),\n\t\tUINT64_C(0xBD0361BA7FCE5C95), UINT64_C(0xD25CC6B9C1827226),\n\t\tUINT64_C(0xE6A3211228F8D861), UINT64_C(0x89FC861196B4F6D2),\n\t\tUINT64_C(0x334BA549BA69819F), UINT64_C(0x5C14024A0425AF2C),\n\t\tUINT64_C(0x68EBE5E1ED5F056B), UINT64_C(0x07B442E253132BD8),\n\t\tUINT64_C(0x00152AB63EAA51E4), UINT64_C(0x6F4A8DB580E67F57),\n\t\tUINT64_C(0x5BB56A1E699CD510), UINT64_C(0x34EACD1DD7D0FBA3),\n\t\tUINT64_C(0x55F7BBB6B3EE2068), UINT64_C(0x3AA81CB50DA20EDB),\n\t\tUINT64_C(0x0E57FB1EE4D8A49C), UINT64_C(0x61085C1D5A948A2F),\n\t\tUINT64_C(0x66A93449372DF013), UINT64_C(0x09F6934A8961DEA0),\n\t\tUINT64_C(0x3D0974E1601B74E7), UINT64_C(0x5256D3E2DE575A54),\n\t\tUINT64_C(0x7A2D961882C81AE2), UINT64_C(0x1572311B3C843451),\n\t\tUINT64_C(0x218DD6B0D5FE9E16), UINT64_C(0x4ED271B36BB2B0A5),\n\t\tUINT64_C(0x497319E7060BCA99), UINT64_C(0x262CBEE4B847E42A),\n\t\tUINT64_C(0x12D3594F513D4E6D), UINT64_C(0x7D8CFE4CEF7160DE),\n\t\tUINT64_C(0x1C9188E78B4FBB15), UINT64_C(0x73CE2FE4350395A6),\n\t\tUINT64_C(0x4731C84FDC793FE1), UINT64_C(0x286E6F4C62351152),\n\t\tUINT64_C(0x2FCF07180F8C6B6E), UINT64_C(0x4090A01BB1C045DD),\n\t\tUINT64_C(0x746F47B058BAEF9A), UINT64_C(0x1B30E0B3E6F6C129),\n\t\tUINT64_C(0x420F87D795576CC9), UINT64_C(0x2D5020D42B1B427A),\n\t\tUINT64_C(0x19AFC77FC261E83D), UINT64_C(0x76F0607C7C2DC68E),\n\t\tUINT64_C(0x715108281194BCB2), UINT64_C(0x1E0EAF2BAFD89201),\n\t\tUINT64_C(0x2AF1488046A23846), UINT64_C(0x45AEEF83F8EE16F5),\n\t\tUINT64_C(0x24B399289CD0CD3E), UINT64_C(0x4BEC3E2B229CE38D),\n\t\tUINT64_C(0x7F13D980CBE649CA), UINT64_C(0x104C7E8375AA6779),\n\t\tUINT64_C(0x17ED16D718131D45), UINT64_C(0x78B2B1D4A65F33F6),\n\t\tUINT64_C(0x4C4D567F4F2599B1), UINT64_C(0x2312F17CF169B702),\n\t\tUINT64_C(0x0B69B486ADF6F7B4), UINT64_C(0x6436138513BAD907),\n\t\tUINT64_C(0x50C9F42EFAC07340), UINT64_C(0x3F96532D448C5DF3),\n\t\tUINT64_C(0x38373B79293527CF), UINT64_C(0x57689C7A9779097C),\n\t\tUINT64_C(0x63977BD17E03A33B), UINT64_C(0x0CC8DCD2C04F8D88),\n\t\tUINT64_C(0x6DD5AA79A4715643), UINT64_C(0x028A0D7A1A3D78F0),\n\t\tUINT64_C(0x3675EAD1F347D2B7), UINT64_C(0x592A4DD24D0BFC04),\n\t\tUINT64_C(0x5E8B258620B28638), UINT64_C(0x31D482859EFEA88B),\n\t\tUINT64_C(0x052B652E778402CC), UINT64_C(0x6A74C22DC9C82C7F),\n\t\tUINT64_C(0xD0C3E175E5155B32), UINT64_C(0xBF9C46765B597581),\n\t\tUINT64_C(0x8B63A1DDB223DFC6), UINT64_C(0xE43C06DE0C6FF175),\n\t\tUINT64_C(0xE39D6E8A61D68B49), UINT64_C(0x8CC2C989DF9AA5FA),\n\t\tUINT64_C(0xB83D2E2236E00FBD), UINT64_C(0xD762892188AC210E),\n\t\tUINT64_C(0xB67FFF8AEC92FAC5), UINT64_C(0xD920588952DED476),\n\t\tUINT64_C(0xEDDFBF22BBA47E31), UINT64_C(0x8280182105E85082),\n\t\tUINT64_C(0x8521707568512ABE), UINT64_C(0xEA7ED776D61D040D),\n\t\tUINT64_C(0xDE8130DD3F67AE4A), UINT64_C(0xB1DE97DE812B80F9),\n\t\tUINT64_C(0x99A5D224DDB4C04F), UINT64_C(0xF6FA752763F8EEFC),\n\t\tUINT64_C(0xC205928C8A8244BB), UINT64_C(0xAD5A358F34CE6A08),\n\t\tUINT64_C(0xAAFB5DDB59771034), UINT64_C(0xC5A4FAD8E73B3E87),\n\t\tUINT64_C(0xF15B1D730E4194C0), UINT64_C(0x9E04BA70B00DBA73),\n\t\tUINT64_C(0xFF19CCDBD43361B8), UINT64_C(0x90466BD86A7F4F0B),\n\t\tUINT64_C(0xA4B98C738305E54C), UINT64_C(0xCBE62B703D49CBFF),\n\t\tUINT64_C(0xCC47432450F0B1C3), UINT64_C(0xA318E427EEBC9F70),\n\t\tUINT64_C(0x97E7038C07C63537), UINT64_C(0xF8B8A48FB98A1B84),\n\t\tUINT64_C(0xE388443C5F7CDAAD), UINT64_C(0x8CD7E33FE130F41E),\n\t\tUINT64_C(0xB8280494084A5E59), UINT64_C(0xD777A397B60670EA),\n\t\tUINT64_C(0xD0D6CBC3DBBF0AD6), UINT64_C(0xBF896CC065F32465),\n\t\tUINT64_C(0x8B768B6B8C898E22), UINT64_C(0xE4292C6832C5A091),\n\t\tUINT64_C(0x85345AC356FB7B5A), UINT64_C(0xEA6BFDC0E8B755E9),\n\t\tUINT64_C(0xDE941A6B01CDFFAE), UINT64_C(0xB1CBBD68BF81D11D),\n\t\tUINT64_C(0xB66AD53CD238AB21), UINT64_C(0xD935723F6C748592),\n\t\tUINT64_C(0xEDCA9594850E2FD5), UINT64_C(0x829532973B420166),\n\t\tUINT64_C(0xAAEE776D67DD41D0), UINT64_C(0xC5B1D06ED9916F63),\n\t\tUINT64_C(0xF14E37C530EBC524), UINT64_C(0x9E1190C68EA7EB97),\n\t\tUINT64_C(0x99B0F892E31E91AB), UINT64_C(0xF6EF5F915D52BF18),\n\t\tUINT64_C(0xC210B83AB428155F), UINT64_C(0xAD4F1F390A643BEC),\n\t\tUINT64_C(0xCC5269926E5AE027), UINT64_C(0xA30DCE91D016CE94),\n\t\tUINT64_C(0x97F2293A396C64D3), UINT64_C(0xF8AD8E3987204A60),\n\t\tUINT64_C(0xFF0CE66DEA99305C), UINT64_C(0x9053416E54D51EEF),\n\t\tUINT64_C(0xA4ACA6C5BDAFB4A8), UINT64_C(0xCBF301C603E39A1B),\n\t\tUINT64_C(0x7144229E2F3EED56), UINT64_C(0x1E1B859D9172C3E5),\n\t\tUINT64_C(0x2AE46236780869A2), UINT64_C(0x45BBC535C6444711),\n\t\tUINT64_C(0x421AAD61ABFD3D2D), UINT64_C(0x2D450A6215B1139E),\n\t\tUINT64_C(0x19BAEDC9FCCBB9D9), UINT64_C(0x76E54ACA4287976A),\n\t\tUINT64_C(0x17F83C6126B94CA1), UINT64_C(0x78A79B6298F56212),\n\t\tUINT64_C(0x4C587CC9718FC855), UINT64_C(0x2307DBCACFC3E6E6),\n\t\tUINT64_C(0x24A6B39EA27A9CDA), UINT64_C(0x4BF9149D1C36B269),\n\t\tUINT64_C(0x7F06F336F54C182E), UINT64_C(0x105954354B00369D),\n\t\tUINT64_C(0x382211CF179F762B), UINT64_C(0x577DB6CCA9D35898),\n\t\tUINT64_C(0x6382516740A9F2DF), UINT64_C(0x0CDDF664FEE5DC6C),\n\t\tUINT64_C(0x0B7C9E30935CA650), UINT64_C(0x642339332D1088E3),\n\t\tUINT64_C(0x50DCDE98C46A22A4), UINT64_C(0x3F83799B7A260C17),\n\t\tUINT64_C(0x5E9E0F301E18D7DC), UINT64_C(0x31C1A833A054F96F),\n\t\tUINT64_C(0x053E4F98492E5328), UINT64_C(0x6A61E89BF7627D9B),\n\t\tUINT64_C(0x6DC080CF9ADB07A7), UINT64_C(0x029F27CC24972914),\n\t\tUINT64_C(0x3660C067CDED8353), UINT64_C(0x593F676473A1ADE0)\n\t}, {\n\t\tUINT64_C(0x0000000000000000), UINT64_C(0x0DF1D05C9279E954),\n\t\tUINT64_C(0x1AE2A1B924F3D2A9), UINT64_C(0x171371E5B68A3BFD),\n\t\tUINT64_C(0xB1DA4DDC62497DC1), UINT64_C(0xBC2B9D80F0309495),\n\t\tUINT64_C(0xAB38EC6546BAAF68), UINT64_C(0xA6C93C39D4C3463C),\n\t\tUINT64_C(0xE7AB9517EE3D2210), UINT64_C(0xEA5A454B7C44CB44),\n\t\tUINT64_C(0xFD4934AECACEF0B9), UINT64_C(0xF0B8E4F258B719ED),\n\t\tUINT64_C(0x5671D8CB8C745FD1), UINT64_C(0x5B8008971E0DB685),\n\t\tUINT64_C(0x4C937972A8878D78), UINT64_C(0x4162A92E3AFE642C),\n\t\tUINT64_C(0xCE572B2FDC7B4420), UINT64_C(0xC3A6FB734E02AD74),\n\t\tUINT64_C(0xD4B58A96F8889689), UINT64_C(0xD9445ACA6AF17FDD),\n\t\tUINT64_C(0x7F8D66F3BE3239E1), UINT64_C(0x727CB6AF2C4BD0B5),\n\t\tUINT64_C(0x656FC74A9AC1EB48), UINT64_C(0x689E171608B8021C),\n\t\tUINT64_C(0x29FCBE3832466630), UINT64_C(0x240D6E64A03F8F64),\n\t\tUINT64_C(0x331E1F8116B5B499), UINT64_C(0x3EEFCFDD84CC5DCD),\n\t\tUINT64_C(0x9826F3E4500F1BF1), UINT64_C(0x95D723B8C276F2A5),\n\t\tUINT64_C(0x82C4525D74FCC958), UINT64_C(0x8F358201E685200C),\n\t\tUINT64_C(0x9CAF565EB8F78840), UINT64_C(0x915E86022A8E6114),\n\t\tUINT64_C(0x864DF7E79C045AE9), UINT64_C(0x8BBC27BB0E7DB3BD),\n\t\tUINT64_C(0x2D751B82DABEF581), UINT64_C(0x2084CBDE48C71CD5),\n\t\tUINT64_C(0x3797BA3BFE4D2728), UINT64_C(0x3A666A676C34CE7C),\n\t\tUINT64_C(0x7B04C34956CAAA50), UINT64_C(0x76F51315C4B34304),\n\t\tUINT64_C(0x61E662F0723978F9), UINT64_C(0x6C17B2ACE04091AD),\n\t\tUINT64_C(0xCADE8E953483D791), UINT64_C(0xC72F5EC9A6FA3EC5),\n\t\tUINT64_C(0xD03C2F2C10700538), UINT64_C(0xDDCDFF708209EC6C),\n\t\tUINT64_C(0x52F87D71648CCC60), UINT64_C(0x5F09AD2DF6F52534),\n\t\tUINT64_C(0x481ADCC8407F1EC9), UINT64_C(0x45EB0C94D206F79D),\n\t\tUINT64_C(0xE32230AD06C5B1A1), UINT64_C(0xEED3E0F194BC58F5),\n\t\tUINT64_C(0xF9C0911422366308), UINT64_C(0xF4314148B04F8A5C),\n\t\tUINT64_C(0xB553E8668AB1EE70), UINT64_C(0xB8A2383A18C80724),\n\t\tUINT64_C(0xAFB149DFAE423CD9), UINT64_C(0xA24099833C3BD58D),\n\t\tUINT64_C(0x0489A5BAE8F893B1), UINT64_C(0x097875E67A817AE5),\n\t\tUINT64_C(0x1E6B0403CC0B4118), UINT64_C(0x139AD45F5E72A84C),\n\t\tUINT64_C(0x385FADBC70EF1181), UINT64_C(0x35AE7DE0E296F8D5),\n\t\tUINT64_C(0x22BD0C05541CC328), UINT64_C(0x2F4CDC59C6652A7C),\n\t\tUINT64_C(0x8985E06012A66C40), UINT64_C(0x8474303C80DF8514),\n\t\tUINT64_C(0x936741D93655BEE9), UINT64_C(0x9E969185A42C57BD),\n\t\tUINT64_C(0xDFF438AB9ED23391), UINT64_C(0xD205E8F70CABDAC5),\n\t\tUINT64_C(0xC5169912BA21E138), UINT64_C(0xC8E7494E2858086C),\n\t\tUINT64_C(0x6E2E7577FC9B4E50), UINT64_C(0x63DFA52B6EE2A704),\n\t\tUINT64_C(0x74CCD4CED8689CF9), UINT64_C(0x793D04924A1175AD),\n\t\tUINT64_C(0xF6088693AC9455A1), UINT64_C(0xFBF956CF3EEDBCF5),\n\t\tUINT64_C(0xECEA272A88678708), UINT64_C(0xE11BF7761A1E6E5C),\n\t\tUINT64_C(0x47D2CB4FCEDD2860), UINT64_C(0x4A231B135CA4C134),\n\t\tUINT64_C(0x5D306AF6EA2EFAC9), UINT64_C(0x50C1BAAA7857139D),\n\t\tUINT64_C(0x11A3138442A977B1), UINT64_C(0x1C52C3D8D0D09EE5),\n\t\tUINT64_C(0x0B41B23D665AA518), UINT64_C(0x06B06261F4234C4C),\n\t\tUINT64_C(0xA0795E5820E00A70), UINT64_C(0xAD888E04B299E324),\n\t\tUINT64_C(0xBA9BFFE10413D8D9), UINT64_C(0xB76A2FBD966A318D),\n\t\tUINT64_C(0xA4F0FBE2C81899C1), UINT64_C(0xA9012BBE5A617095),\n\t\tUINT64_C(0xBE125A5BECEB4B68), UINT64_C(0xB3E38A077E92A23C),\n\t\tUINT64_C(0x152AB63EAA51E400), UINT64_C(0x18DB666238280D54),\n\t\tUINT64_C(0x0FC817878EA236A9), UINT64_C(0x0239C7DB1CDBDFFD),\n\t\tUINT64_C(0x435B6EF52625BBD1), UINT64_C(0x4EAABEA9B45C5285),\n\t\tUINT64_C(0x59B9CF4C02D66978), UINT64_C(0x54481F1090AF802C),\n\t\tUINT64_C(0xF2812329446CC610), UINT64_C(0xFF70F375D6152F44),\n\t\tUINT64_C(0xE8638290609F14B9), UINT64_C(0xE59252CCF2E6FDED),\n\t\tUINT64_C(0x6AA7D0CD1463DDE1), UINT64_C(0x67560091861A34B5),\n\t\tUINT64_C(0x7045717430900F48), UINT64_C(0x7DB4A128A2E9E61C),\n\t\tUINT64_C(0xDB7D9D11762AA020), UINT64_C(0xD68C4D4DE4534974),\n\t\tUINT64_C(0xC19F3CA852D97289), UINT64_C(0xCC6EECF4C0A09BDD),\n\t\tUINT64_C(0x8D0C45DAFA5EFFF1), UINT64_C(0x80FD9586682716A5),\n\t\tUINT64_C(0x97EEE463DEAD2D58), UINT64_C(0x9A1F343F4CD4C40C),\n\t\tUINT64_C(0x3CD6080698178230), UINT64_C(0x3127D85A0A6E6B64),\n\t\tUINT64_C(0x2634A9BFBCE45099), UINT64_C(0x2BC579E32E9DB9CD),\n\t\tUINT64_C(0xF5A054D6CA71FB90), UINT64_C(0xF851848A580812C4),\n\t\tUINT64_C(0xEF42F56FEE822939), UINT64_C(0xE2B325337CFBC06D),\n\t\tUINT64_C(0x447A190AA8388651), UINT64_C(0x498BC9563A416F05),\n\t\tUINT64_C(0x5E98B8B38CCB54F8), UINT64_C(0x536968EF1EB2BDAC),\n\t\tUINT64_C(0x120BC1C1244CD980), UINT64_C(0x1FFA119DB63530D4),\n\t\tUINT64_C(0x08E9607800BF0B29), UINT64_C(0x0518B02492C6E27D),\n\t\tUINT64_C(0xA3D18C1D4605A441), UINT64_C(0xAE205C41D47C4D15),\n\t\tUINT64_C(0xB9332DA462F676E8), UINT64_C(0xB4C2FDF8F08F9FBC),\n\t\tUINT64_C(0x3BF77FF9160ABFB0), UINT64_C(0x3606AFA5847356E4),\n\t\tUINT64_C(0x2115DE4032F96D19), UINT64_C(0x2CE40E1CA080844D),\n\t\tUINT64_C(0x8A2D32257443C271), UINT64_C(0x87DCE279E63A2B25),\n\t\tUINT64_C(0x90CF939C50B010D8), UINT64_C(0x9D3E43C0C2C9F98C),\n\t\tUINT64_C(0xDC5CEAEEF8379DA0), UINT64_C(0xD1AD3AB26A4E74F4),\n\t\tUINT64_C(0xC6BE4B57DCC44F09), UINT64_C(0xCB4F9B0B4EBDA65D),\n\t\tUINT64_C(0x6D86A7329A7EE061), UINT64_C(0x6077776E08070935),\n\t\tUINT64_C(0x7764068BBE8D32C8), UINT64_C(0x7A95D6D72CF4DB9C),\n\t\tUINT64_C(0x690F0288728673D0), UINT64_C(0x64FED2D4E0FF9A84),\n\t\tUINT64_C(0x73EDA3315675A179), UINT64_C(0x7E1C736DC40C482D),\n\t\tUINT64_C(0xD8D54F5410CF0E11), UINT64_C(0xD5249F0882B6E745),\n\t\tUINT64_C(0xC237EEED343CDCB8), UINT64_C(0xCFC63EB1A64535EC),\n\t\tUINT64_C(0x8EA4979F9CBB51C0), UINT64_C(0x835547C30EC2B894),\n\t\tUINT64_C(0x94463626B8488369), UINT64_C(0x99B7E67A2A316A3D),\n\t\tUINT64_C(0x3F7EDA43FEF22C01), UINT64_C(0x328F0A1F6C8BC555),\n\t\tUINT64_C(0x259C7BFADA01FEA8), UINT64_C(0x286DABA6487817FC),\n\t\tUINT64_C(0xA75829A7AEFD37F0), UINT64_C(0xAAA9F9FB3C84DEA4),\n\t\tUINT64_C(0xBDBA881E8A0EE559), UINT64_C(0xB04B584218770C0D),\n\t\tUINT64_C(0x1682647BCCB44A31), UINT64_C(0x1B73B4275ECDA365),\n\t\tUINT64_C(0x0C60C5C2E8479898), UINT64_C(0x0191159E7A3E71CC),\n\t\tUINT64_C(0x40F3BCB040C015E0), UINT64_C(0x4D026CECD2B9FCB4),\n\t\tUINT64_C(0x5A111D096433C749), UINT64_C(0x57E0CD55F64A2E1D),\n\t\tUINT64_C(0xF129F16C22896821), UINT64_C(0xFCD82130B0F08175),\n\t\tUINT64_C(0xEBCB50D5067ABA88), UINT64_C(0xE63A8089940353DC),\n\t\tUINT64_C(0xCDFFF96ABA9EEA11), UINT64_C(0xC00E293628E70345),\n\t\tUINT64_C(0xD71D58D39E6D38B8), UINT64_C(0xDAEC888F0C14D1EC),\n\t\tUINT64_C(0x7C25B4B6D8D797D0), UINT64_C(0x71D464EA4AAE7E84),\n\t\tUINT64_C(0x66C7150FFC244579), UINT64_C(0x6B36C5536E5DAC2D),\n\t\tUINT64_C(0x2A546C7D54A3C801), UINT64_C(0x27A5BC21C6DA2155),\n\t\tUINT64_C(0x30B6CDC470501AA8), UINT64_C(0x3D471D98E229F3FC),\n\t\tUINT64_C(0x9B8E21A136EAB5C0), UINT64_C(0x967FF1FDA4935C94),\n\t\tUINT64_C(0x816C801812196769), UINT64_C(0x8C9D504480608E3D),\n\t\tUINT64_C(0x03A8D24566E5AE31), UINT64_C(0x0E590219F49C4765),\n\t\tUINT64_C(0x194A73FC42167C98), UINT64_C(0x14BBA3A0D06F95CC),\n\t\tUINT64_C(0xB2729F9904ACD3F0), UINT64_C(0xBF834FC596D53AA4),\n\t\tUINT64_C(0xA8903E20205F0159), UINT64_C(0xA561EE7CB226E80D),\n\t\tUINT64_C(0xE403475288D88C21), UINT64_C(0xE9F2970E1AA16575),\n\t\tUINT64_C(0xFEE1E6EBAC2B5E88), UINT64_C(0xF31036B73E52B7DC),\n\t\tUINT64_C(0x55D90A8EEA91F1E0), UINT64_C(0x5828DAD278E818B4),\n\t\tUINT64_C(0x4F3BAB37CE622349), UINT64_C(0x42CA7B6B5C1BCA1D),\n\t\tUINT64_C(0x5150AF3402696251), UINT64_C(0x5CA17F6890108B05),\n\t\tUINT64_C(0x4BB20E8D269AB0F8), UINT64_C(0x4643DED1B4E359AC),\n\t\tUINT64_C(0xE08AE2E860201F90), UINT64_C(0xED7B32B4F259F6C4),\n\t\tUINT64_C(0xFA68435144D3CD39), UINT64_C(0xF799930DD6AA246D),\n\t\tUINT64_C(0xB6FB3A23EC544041), UINT64_C(0xBB0AEA7F7E2DA915),\n\t\tUINT64_C(0xAC199B9AC8A792E8), UINT64_C(0xA1E84BC65ADE7BBC),\n\t\tUINT64_C(0x072177FF8E1D3D80), UINT64_C(0x0AD0A7A31C64D4D4),\n\t\tUINT64_C(0x1DC3D646AAEEEF29), UINT64_C(0x1032061A3897067D),\n\t\tUINT64_C(0x9F07841BDE122671), UINT64_C(0x92F654474C6BCF25),\n\t\tUINT64_C(0x85E525A2FAE1F4D8), UINT64_C(0x8814F5FE68981D8C),\n\t\tUINT64_C(0x2EDDC9C7BC5B5BB0), UINT64_C(0x232C199B2E22B2E4),\n\t\tUINT64_C(0x343F687E98A88919), UINT64_C(0x39CEB8220AD1604D),\n\t\tUINT64_C(0x78AC110C302F0461), UINT64_C(0x755DC150A256ED35),\n\t\tUINT64_C(0x624EB0B514DCD6C8), UINT64_C(0x6FBF60E986A53F9C),\n\t\tUINT64_C(0xC9765CD0526679A0), UINT64_C(0xC4878C8CC01F90F4),\n\t\tUINT64_C(0xD394FD697695AB09), UINT64_C(0xDE652D35E4EC425D)\n\t}, {\n\t\tUINT64_C(0x0000000000000000), UINT64_C(0xCB6D6A914AE10B3F),\n\t\tUINT64_C(0x96DBD42295C2177E), UINT64_C(0x5DB6BEB3DF231C41),\n\t\tUINT64_C(0x2CB7A9452A852FFC), UINT64_C(0xE7DAC3D4606424C3),\n\t\tUINT64_C(0xBA6C7D67BF473882), UINT64_C(0x710117F6F5A633BD),\n\t\tUINT64_C(0xDD705D247FA5876A), UINT64_C(0x161D37B535448C55),\n\t\tUINT64_C(0x4BAB8906EA679014), UINT64_C(0x80C6E397A0869B2B),\n\t\tUINT64_C(0xF1C7F4615520A896), UINT64_C(0x3AAA9EF01FC1A3A9),\n\t\tUINT64_C(0x671C2043C0E2BFE8), UINT64_C(0xAC714AD28A03B4D7),\n\t\tUINT64_C(0xBAE1BA48FE4A0FD5), UINT64_C(0x718CD0D9B4AB04EA),\n\t\tUINT64_C(0x2C3A6E6A6B8818AB), UINT64_C(0xE75704FB21691394),\n\t\tUINT64_C(0x9656130DD4CF2029), UINT64_C(0x5D3B799C9E2E2B16),\n\t\tUINT64_C(0x008DC72F410D3757), UINT64_C(0xCBE0ADBE0BEC3C68),\n\t\tUINT64_C(0x6791E76C81EF88BF), UINT64_C(0xACFC8DFDCB0E8380),\n\t\tUINT64_C(0xF14A334E142D9FC1), UINT64_C(0x3A2759DF5ECC94FE),\n\t\tUINT64_C(0x4B264E29AB6AA743), UINT64_C(0x804B24B8E18BAC7C),\n\t\tUINT64_C(0xDDFD9A0B3EA8B03D), UINT64_C(0x1690F09A7449BB02),\n\t\tUINT64_C(0xF1DD7B3ED73AC638), UINT64_C(0x3AB011AF9DDBCD07),\n\t\tUINT64_C(0x6706AF1C42F8D146), UINT64_C(0xAC6BC58D0819DA79),\n\t\tUINT64_C(0xDD6AD27BFDBFE9C4), UINT64_C(0x1607B8EAB75EE2FB),\n\t\tUINT64_C(0x4BB10659687DFEBA), UINT64_C(0x80DC6CC8229CF585),\n\t\tUINT64_C(0x2CAD261AA89F4152), UINT64_C(0xE7C04C8BE27E4A6D),\n\t\tUINT64_C(0xBA76F2383D5D562C), UINT64_C(0x711B98A977BC5D13),\n\t\tUINT64_C(0x001A8F5F821A6EAE), UINT64_C(0xCB77E5CEC8FB6591),\n\t\tUINT64_C(0x96C15B7D17D879D0), UINT64_C(0x5DAC31EC5D3972EF),\n\t\tUINT64_C(0x4B3CC1762970C9ED), UINT64_C(0x8051ABE76391C2D2),\n\t\tUINT64_C(0xDDE71554BCB2DE93), UINT64_C(0x168A7FC5F653D5AC),\n\t\tUINT64_C(0x678B683303F5E611), UINT64_C(0xACE602A24914ED2E),\n\t\tUINT64_C(0xF150BC119637F16F), UINT64_C(0x3A3DD680DCD6FA50),\n\t\tUINT64_C(0x964C9C5256D54E87), UINT64_C(0x5D21F6C31C3445B8),\n\t\tUINT64_C(0x00974870C31759F9), UINT64_C(0xCBFA22E189F652C6),\n\t\tUINT64_C(0xBAFB35177C50617B), UINT64_C(0x71965F8636B16A44),\n\t\tUINT64_C(0x2C20E135E9927605), UINT64_C(0xE74D8BA4A3737D3A),\n\t\tUINT64_C(0xE2BBF77CAE758C71), UINT64_C(0x29D69DEDE494874E),\n\t\tUINT64_C(0x7460235E3BB79B0F), UINT64_C(0xBF0D49CF71569030),\n\t\tUINT64_C(0xCE0C5E3984F0A38D), UINT64_C(0x056134A8CE11A8B2),\n\t\tUINT64_C(0x58D78A1B1132B4F3), UINT64_C(0x93BAE08A5BD3BFCC),\n\t\tUINT64_C(0x3FCBAA58D1D00B1B), UINT64_C(0xF4A6C0C99B310024),\n\t\tUINT64_C(0xA9107E7A44121C65), UINT64_C(0x627D14EB0EF3175A),\n\t\tUINT64_C(0x137C031DFB5524E7), UINT64_C(0xD811698CB1B42FD8),\n\t\tUINT64_C(0x85A7D73F6E973399), UINT64_C(0x4ECABDAE247638A6),\n\t\tUINT64_C(0x585A4D34503F83A4), UINT64_C(0x933727A51ADE889B),\n\t\tUINT64_C(0xCE819916C5FD94DA), UINT64_C(0x05ECF3878F1C9FE5),\n\t\tUINT64_C(0x74EDE4717ABAAC58), UINT64_C(0xBF808EE0305BA767),\n\t\tUINT64_C(0xE2363053EF78BB26), UINT64_C(0x295B5AC2A599B019),\n\t\tUINT64_C(0x852A10102F9A04CE), UINT64_C(0x4E477A81657B0FF1),\n\t\tUINT64_C(0x13F1C432BA5813B0), UINT64_C(0xD89CAEA3F0B9188F),\n\t\tUINT64_C(0xA99DB955051F2B32), UINT64_C(0x62F0D3C44FFE200D),\n\t\tUINT64_C(0x3F466D7790DD3C4C), UINT64_C(0xF42B07E6DA3C3773),\n\t\tUINT64_C(0x13668C42794F4A49), UINT64_C(0xD80BE6D333AE4176),\n\t\tUINT64_C(0x85BD5860EC8D5D37), UINT64_C(0x4ED032F1A66C5608),\n\t\tUINT64_C(0x3FD1250753CA65B5), UINT64_C(0xF4BC4F96192B6E8A),\n\t\tUINT64_C(0xA90AF125C60872CB), UINT64_C(0x62679BB48CE979F4),\n\t\tUINT64_C(0xCE16D16606EACD23), UINT64_C(0x057BBBF74C0BC61C),\n\t\tUINT64_C(0x58CD05449328DA5D), UINT64_C(0x93A06FD5D9C9D162),\n\t\tUINT64_C(0xE2A178232C6FE2DF), UINT64_C(0x29CC12B2668EE9E0),\n\t\tUINT64_C(0x747AAC01B9ADF5A1), UINT64_C(0xBF17C690F34CFE9E),\n\t\tUINT64_C(0xA987360A8705459C), UINT64_C(0x62EA5C9BCDE44EA3),\n\t\tUINT64_C(0x3F5CE22812C752E2), UINT64_C(0xF43188B9582659DD),\n\t\tUINT64_C(0x85309F4FAD806A60), UINT64_C(0x4E5DF5DEE761615F),\n\t\tUINT64_C(0x13EB4B6D38427D1E), UINT64_C(0xD88621FC72A37621),\n\t\tUINT64_C(0x74F76B2EF8A0C2F6), UINT64_C(0xBF9A01BFB241C9C9),\n\t\tUINT64_C(0xE22CBF0C6D62D588), UINT64_C(0x2941D59D2783DEB7),\n\t\tUINT64_C(0x5840C26BD225ED0A), UINT64_C(0x932DA8FA98C4E635),\n\t\tUINT64_C(0xCE9B164947E7FA74), UINT64_C(0x05F67CD80D06F14B),\n\t\tUINT64_C(0xC477EFF95CEB18E3), UINT64_C(0x0F1A8568160A13DC),\n\t\tUINT64_C(0x52AC3BDBC9290F9D), UINT64_C(0x99C1514A83C804A2),\n\t\tUINT64_C(0xE8C046BC766E371F), UINT64_C(0x23AD2C2D3C8F3C20),\n\t\tUINT64_C(0x7E1B929EE3AC2061), UINT64_C(0xB576F80FA94D2B5E),\n\t\tUINT64_C(0x1907B2DD234E9F89), UINT64_C(0xD26AD84C69AF94B6),\n\t\tUINT64_C(0x8FDC66FFB68C88F7), UINT64_C(0x44B10C6EFC6D83C8),\n\t\tUINT64_C(0x35B01B9809CBB075), UINT64_C(0xFEDD7109432ABB4A),\n\t\tUINT64_C(0xA36BCFBA9C09A70B), UINT64_C(0x6806A52BD6E8AC34),\n\t\tUINT64_C(0x7E9655B1A2A11736), UINT64_C(0xB5FB3F20E8401C09),\n\t\tUINT64_C(0xE84D819337630048), UINT64_C(0x2320EB027D820B77),\n\t\tUINT64_C(0x5221FCF4882438CA), UINT64_C(0x994C9665C2C533F5),\n\t\tUINT64_C(0xC4FA28D61DE62FB4), UINT64_C(0x0F9742475707248B),\n\t\tUINT64_C(0xA3E60895DD04905C), UINT64_C(0x688B620497E59B63),\n\t\tUINT64_C(0x353DDCB748C68722), UINT64_C(0xFE50B62602278C1D),\n\t\tUINT64_C(0x8F51A1D0F781BFA0), UINT64_C(0x443CCB41BD60B49F),\n\t\tUINT64_C(0x198A75F26243A8DE), UINT64_C(0xD2E71F6328A2A3E1),\n\t\tUINT64_C(0x35AA94C78BD1DEDB), UINT64_C(0xFEC7FE56C130D5E4),\n\t\tUINT64_C(0xA37140E51E13C9A5), UINT64_C(0x681C2A7454F2C29A),\n\t\tUINT64_C(0x191D3D82A154F127), UINT64_C(0xD2705713EBB5FA18),\n\t\tUINT64_C(0x8FC6E9A03496E659), UINT64_C(0x44AB83317E77ED66),\n\t\tUINT64_C(0xE8DAC9E3F47459B1), UINT64_C(0x23B7A372BE95528E),\n\t\tUINT64_C(0x7E011DC161B64ECF), UINT64_C(0xB56C77502B5745F0),\n\t\tUINT64_C(0xC46D60A6DEF1764D), UINT64_C(0x0F000A3794107D72),\n\t\tUINT64_C(0x52B6B4844B336133), UINT64_C(0x99DBDE1501D26A0C),\n\t\tUINT64_C(0x8F4B2E8F759BD10E), UINT64_C(0x4426441E3F7ADA31),\n\t\tUINT64_C(0x1990FAADE059C670), UINT64_C(0xD2FD903CAAB8CD4F),\n\t\tUINT64_C(0xA3FC87CA5F1EFEF2), UINT64_C(0x6891ED5B15FFF5CD),\n\t\tUINT64_C(0x352753E8CADCE98C), UINT64_C(0xFE4A3979803DE2B3),\n\t\tUINT64_C(0x523B73AB0A3E5664), UINT64_C(0x9956193A40DF5D5B),\n\t\tUINT64_C(0xC4E0A7899FFC411A), UINT64_C(0x0F8DCD18D51D4A25),\n\t\tUINT64_C(0x7E8CDAEE20BB7998), UINT64_C(0xB5E1B07F6A5A72A7),\n\t\tUINT64_C(0xE8570ECCB5796EE6), UINT64_C(0x233A645DFF9865D9),\n\t\tUINT64_C(0x26CC1885F29E9492), UINT64_C(0xEDA17214B87F9FAD),\n\t\tUINT64_C(0xB017CCA7675C83EC), UINT64_C(0x7B7AA6362DBD88D3),\n\t\tUINT64_C(0x0A7BB1C0D81BBB6E), UINT64_C(0xC116DB5192FAB051),\n\t\tUINT64_C(0x9CA065E24DD9AC10), UINT64_C(0x57CD0F730738A72F),\n\t\tUINT64_C(0xFBBC45A18D3B13F8), UINT64_C(0x30D12F30C7DA18C7),\n\t\tUINT64_C(0x6D67918318F90486), UINT64_C(0xA60AFB1252180FB9),\n\t\tUINT64_C(0xD70BECE4A7BE3C04), UINT64_C(0x1C668675ED5F373B),\n\t\tUINT64_C(0x41D038C6327C2B7A), UINT64_C(0x8ABD5257789D2045),\n\t\tUINT64_C(0x9C2DA2CD0CD49B47), UINT64_C(0x5740C85C46359078),\n\t\tUINT64_C(0x0AF676EF99168C39), UINT64_C(0xC19B1C7ED3F78706),\n\t\tUINT64_C(0xB09A0B882651B4BB), UINT64_C(0x7BF761196CB0BF84),\n\t\tUINT64_C(0x2641DFAAB393A3C5), UINT64_C(0xED2CB53BF972A8FA),\n\t\tUINT64_C(0x415DFFE973711C2D), UINT64_C(0x8A30957839901712),\n\t\tUINT64_C(0xD7862BCBE6B30B53), UINT64_C(0x1CEB415AAC52006C),\n\t\tUINT64_C(0x6DEA56AC59F433D1), UINT64_C(0xA6873C3D131538EE),\n\t\tUINT64_C(0xFB31828ECC3624AF), UINT64_C(0x305CE81F86D72F90),\n\t\tUINT64_C(0xD71163BB25A452AA), UINT64_C(0x1C7C092A6F455995),\n\t\tUINT64_C(0x41CAB799B06645D4), UINT64_C(0x8AA7DD08FA874EEB),\n\t\tUINT64_C(0xFBA6CAFE0F217D56), UINT64_C(0x30CBA06F45C07669),\n\t\tUINT64_C(0x6D7D1EDC9AE36A28), UINT64_C(0xA610744DD0026117),\n\t\tUINT64_C(0x0A613E9F5A01D5C0), UINT64_C(0xC10C540E10E0DEFF),\n\t\tUINT64_C(0x9CBAEABDCFC3C2BE), UINT64_C(0x57D7802C8522C981),\n\t\tUINT64_C(0x26D697DA7084FA3C), UINT64_C(0xEDBBFD4B3A65F103),\n\t\tUINT64_C(0xB00D43F8E546ED42), UINT64_C(0x7B602969AFA7E67D),\n\t\tUINT64_C(0x6DF0D9F3DBEE5D7F), UINT64_C(0xA69DB362910F5640),\n\t\tUINT64_C(0xFB2B0DD14E2C4A01), UINT64_C(0x3046674004CD413E),\n\t\tUINT64_C(0x414770B6F16B7283), UINT64_C(0x8A2A1A27BB8A79BC),\n\t\tUINT64_C(0xD79CA49464A965FD), UINT64_C(0x1CF1CE052E486EC2),\n\t\tUINT64_C(0xB08084D7A44BDA15), UINT64_C(0x7BEDEE46EEAAD12A),\n\t\tUINT64_C(0x265B50F53189CD6B), UINT64_C(0xED363A647B68C654),\n\t\tUINT64_C(0x9C372D928ECEF5E9), UINT64_C(0x575A4703C42FFED6),\n\t\tUINT64_C(0x0AECF9B01B0CE297), UINT64_C(0xC181932151EDE9A8)\n\t}, {\n\t\tUINT64_C(0x0000000000000000), UINT64_C(0xDCA12C225E8AEE1D),\n\t\tUINT64_C(0xB8435944BC14DD3B), UINT64_C(0x64E27566E29E3326),\n\t\tUINT64_C(0x7087B2887829BA77), UINT64_C(0xAC269EAA26A3546A),\n\t\tUINT64_C(0xC8C4EBCCC43D674C), UINT64_C(0x1465C7EE9AB78951),\n\t\tUINT64_C(0xE00E6511F15274EF), UINT64_C(0x3CAF4933AFD89AF2),\n\t\tUINT64_C(0x584D3C554D46A9D4), UINT64_C(0x84EC107713CC47C9),\n\t\tUINT64_C(0x9089D799897BCE98), UINT64_C(0x4C28FBBBD7F12085),\n\t\tUINT64_C(0x28CA8EDD356F13A3), UINT64_C(0xF46BA2FF6BE5FDBE),\n\t\tUINT64_C(0x4503C48DC90A304C), UINT64_C(0x99A2E8AF9780DE51),\n\t\tUINT64_C(0xFD409DC9751EED77), UINT64_C(0x21E1B1EB2B94036A),\n\t\tUINT64_C(0x35847605B1238A3B), UINT64_C(0xE9255A27EFA96426),\n\t\tUINT64_C(0x8DC72F410D375700), UINT64_C(0x5166036353BDB91D),\n\t\tUINT64_C(0xA50DA19C385844A3), UINT64_C(0x79AC8DBE66D2AABE),\n\t\tUINT64_C(0x1D4EF8D8844C9998), UINT64_C(0xC1EFD4FADAC67785),\n\t\tUINT64_C(0xD58A13144071FED4), UINT64_C(0x092B3F361EFB10C9),\n\t\tUINT64_C(0x6DC94A50FC6523EF), UINT64_C(0xB1686672A2EFCDF2),\n\t\tUINT64_C(0x8A06881B93156098), UINT64_C(0x56A7A439CD9F8E85),\n\t\tUINT64_C(0x3245D15F2F01BDA3), UINT64_C(0xEEE4FD7D718B53BE),\n\t\tUINT64_C(0xFA813A93EB3CDAEF), UINT64_C(0x262016B1B5B634F2),\n\t\tUINT64_C(0x42C263D7572807D4), UINT64_C(0x9E634FF509A2E9C9),\n\t\tUINT64_C(0x6A08ED0A62471477), UINT64_C(0xB6A9C1283CCDFA6A),\n\t\tUINT64_C(0xD24BB44EDE53C94C), UINT64_C(0x0EEA986C80D92751),\n\t\tUINT64_C(0x1A8F5F821A6EAE00), UINT64_C(0xC62E73A044E4401D),\n\t\tUINT64_C(0xA2CC06C6A67A733B), UINT64_C(0x7E6D2AE4F8F09D26),\n\t\tUINT64_C(0xCF054C965A1F50D4), UINT64_C(0x13A460B40495BEC9),\n\t\tUINT64_C(0x774615D2E60B8DEF), UINT64_C(0xABE739F0B88163F2),\n\t\tUINT64_C(0xBF82FE1E2236EAA3), UINT64_C(0x6323D23C7CBC04BE),\n\t\tUINT64_C(0x07C1A75A9E223798), UINT64_C(0xDB608B78C0A8D985),\n\t\tUINT64_C(0x2F0B2987AB4D243B), UINT64_C(0xF3AA05A5F5C7CA26),\n\t\tUINT64_C(0x974870C31759F900), UINT64_C(0x4BE95CE149D3171D),\n\t\tUINT64_C(0x5F8C9B0FD3649E4C), UINT64_C(0x832DB72D8DEE7051),\n\t\tUINT64_C(0xE7CFC24B6F704377), UINT64_C(0x3B6EEE6931FAAD6A),\n\t\tUINT64_C(0x91131E980D8418A2), UINT64_C(0x4DB232BA530EF6BF),\n\t\tUINT64_C(0x295047DCB190C599), UINT64_C(0xF5F16BFEEF1A2B84),\n\t\tUINT64_C(0xE194AC1075ADA2D5), UINT64_C(0x3D3580322B274CC8),\n\t\tUINT64_C(0x59D7F554C9B97FEE), UINT64_C(0x8576D976973391F3),\n\t\tUINT64_C(0x711D7B89FCD66C4D), UINT64_C(0xADBC57ABA25C8250),\n\t\tUINT64_C(0xC95E22CD40C2B176), UINT64_C(0x15FF0EEF1E485F6B),\n\t\tUINT64_C(0x019AC90184FFD63A), UINT64_C(0xDD3BE523DA753827),\n\t\tUINT64_C(0xB9D9904538EB0B01), UINT64_C(0x6578BC676661E51C),\n\t\tUINT64_C(0xD410DA15C48E28EE), UINT64_C(0x08B1F6379A04C6F3),\n\t\tUINT64_C(0x6C538351789AF5D5), UINT64_C(0xB0F2AF7326101BC8),\n\t\tUINT64_C(0xA497689DBCA79299), UINT64_C(0x783644BFE22D7C84),\n\t\tUINT64_C(0x1CD431D900B34FA2), UINT64_C(0xC0751DFB5E39A1BF),\n\t\tUINT64_C(0x341EBF0435DC5C01), UINT64_C(0xE8BF93266B56B21C),\n\t\tUINT64_C(0x8C5DE64089C8813A), UINT64_C(0x50FCCA62D7426F27),\n\t\tUINT64_C(0x44990D8C4DF5E676), UINT64_C(0x983821AE137F086B),\n\t\tUINT64_C(0xFCDA54C8F1E13B4D), UINT64_C(0x207B78EAAF6BD550),\n\t\tUINT64_C(0x1B1596839E91783A), UINT64_C(0xC7B4BAA1C01B9627),\n\t\tUINT64_C(0xA356CFC72285A501), UINT64_C(0x7FF7E3E57C0F4B1C),\n\t\tUINT64_C(0x6B92240BE6B8C24D), UINT64_C(0xB7330829B8322C50),\n\t\tUINT64_C(0xD3D17D4F5AAC1F76), UINT64_C(0x0F70516D0426F16B),\n\t\tUINT64_C(0xFB1BF3926FC30CD5), UINT64_C(0x27BADFB03149E2C8),\n\t\tUINT64_C(0x4358AAD6D3D7D1EE), UINT64_C(0x9FF986F48D5D3FF3),\n\t\tUINT64_C(0x8B9C411A17EAB6A2), UINT64_C(0x573D6D38496058BF),\n\t\tUINT64_C(0x33DF185EABFE6B99), UINT64_C(0xEF7E347CF5748584),\n\t\tUINT64_C(0x5E16520E579B4876), UINT64_C(0x82B77E2C0911A66B),\n\t\tUINT64_C(0xE6550B4AEB8F954D), UINT64_C(0x3AF42768B5057B50),\n\t\tUINT64_C(0x2E91E0862FB2F201), UINT64_C(0xF230CCA471381C1C),\n\t\tUINT64_C(0x96D2B9C293A62F3A), UINT64_C(0x4A7395E0CD2CC127),\n\t\tUINT64_C(0xBE18371FA6C93C99), UINT64_C(0x62B91B3DF843D284),\n\t\tUINT64_C(0x065B6E5B1ADDE1A2), UINT64_C(0xDAFA427944570FBF),\n\t\tUINT64_C(0xCE9F8597DEE086EE), UINT64_C(0x123EA9B5806A68F3),\n\t\tUINT64_C(0x76DCDCD362F45BD5), UINT64_C(0xAA7DF0F13C7EB5C8),\n\t\tUINT64_C(0xA739329F30A7E9D6), UINT64_C(0x7B981EBD6E2D07CB),\n\t\tUINT64_C(0x1F7A6BDB8CB334ED), UINT64_C(0xC3DB47F9D239DAF0),\n\t\tUINT64_C(0xD7BE8017488E53A1), UINT64_C(0x0B1FAC351604BDBC),\n\t\tUINT64_C(0x6FFDD953F49A8E9A), UINT64_C(0xB35CF571AA106087),\n\t\tUINT64_C(0x4737578EC1F59D39), UINT64_C(0x9B967BAC9F7F7324),\n\t\tUINT64_C(0xFF740ECA7DE14002), UINT64_C(0x23D522E8236BAE1F),\n\t\tUINT64_C(0x37B0E506B9DC274E), UINT64_C(0xEB11C924E756C953),\n\t\tUINT64_C(0x8FF3BC4205C8FA75), UINT64_C(0x535290605B421468),\n\t\tUINT64_C(0xE23AF612F9ADD99A), UINT64_C(0x3E9BDA30A7273787),\n\t\tUINT64_C(0x5A79AF5645B904A1), UINT64_C(0x86D883741B33EABC),\n\t\tUINT64_C(0x92BD449A818463ED), UINT64_C(0x4E1C68B8DF0E8DF0),\n\t\tUINT64_C(0x2AFE1DDE3D90BED6), UINT64_C(0xF65F31FC631A50CB),\n\t\tUINT64_C(0x0234930308FFAD75), UINT64_C(0xDE95BF2156754368),\n\t\tUINT64_C(0xBA77CA47B4EB704E), UINT64_C(0x66D6E665EA619E53),\n\t\tUINT64_C(0x72B3218B70D61702), UINT64_C(0xAE120DA92E5CF91F),\n\t\tUINT64_C(0xCAF078CFCCC2CA39), UINT64_C(0x165154ED92482424),\n\t\tUINT64_C(0x2D3FBA84A3B2894E), UINT64_C(0xF19E96A6FD386753),\n\t\tUINT64_C(0x957CE3C01FA65475), UINT64_C(0x49DDCFE2412CBA68),\n\t\tUINT64_C(0x5DB8080CDB9B3339), UINT64_C(0x8119242E8511DD24),\n\t\tUINT64_C(0xE5FB5148678FEE02), UINT64_C(0x395A7D6A3905001F),\n\t\tUINT64_C(0xCD31DF9552E0FDA1), UINT64_C(0x1190F3B70C6A13BC),\n\t\tUINT64_C(0x757286D1EEF4209A), UINT64_C(0xA9D3AAF3B07ECE87),\n\t\tUINT64_C(0xBDB66D1D2AC947D6), UINT64_C(0x6117413F7443A9CB),\n\t\tUINT64_C(0x05F5345996DD9AED), UINT64_C(0xD954187BC85774F0),\n\t\tUINT64_C(0x683C7E096AB8B902), UINT64_C(0xB49D522B3432571F),\n\t\tUINT64_C(0xD07F274DD6AC6439), UINT64_C(0x0CDE0B6F88268A24),\n\t\tUINT64_C(0x18BBCC8112910375), UINT64_C(0xC41AE0A34C1BED68),\n\t\tUINT64_C(0xA0F895C5AE85DE4E), UINT64_C(0x7C59B9E7F00F3053),\n\t\tUINT64_C(0x88321B189BEACDED), UINT64_C(0x5493373AC56023F0),\n\t\tUINT64_C(0x3071425C27FE10D6), UINT64_C(0xECD06E7E7974FECB),\n\t\tUINT64_C(0xF8B5A990E3C3779A), UINT64_C(0x241485B2BD499987),\n\t\tUINT64_C(0x40F6F0D45FD7AAA1), UINT64_C(0x9C57DCF6015D44BC),\n\t\tUINT64_C(0x362A2C073D23F174), UINT64_C(0xEA8B002563A91F69),\n\t\tUINT64_C(0x8E69754381372C4F), UINT64_C(0x52C85961DFBDC252),\n\t\tUINT64_C(0x46AD9E8F450A4B03), UINT64_C(0x9A0CB2AD1B80A51E),\n\t\tUINT64_C(0xFEEEC7CBF91E9638), UINT64_C(0x224FEBE9A7947825),\n\t\tUINT64_C(0xD6244916CC71859B), UINT64_C(0x0A85653492FB6B86),\n\t\tUINT64_C(0x6E671052706558A0), UINT64_C(0xB2C63C702EEFB6BD),\n\t\tUINT64_C(0xA6A3FB9EB4583FEC), UINT64_C(0x7A02D7BCEAD2D1F1),\n\t\tUINT64_C(0x1EE0A2DA084CE2D7), UINT64_C(0xC2418EF856C60CCA),\n\t\tUINT64_C(0x7329E88AF429C138), UINT64_C(0xAF88C4A8AAA32F25),\n\t\tUINT64_C(0xCB6AB1CE483D1C03), UINT64_C(0x17CB9DEC16B7F21E),\n\t\tUINT64_C(0x03AE5A028C007B4F), UINT64_C(0xDF0F7620D28A9552),\n\t\tUINT64_C(0xBBED03463014A674), UINT64_C(0x674C2F646E9E4869),\n\t\tUINT64_C(0x93278D9B057BB5D7), UINT64_C(0x4F86A1B95BF15BCA),\n\t\tUINT64_C(0x2B64D4DFB96F68EC), UINT64_C(0xF7C5F8FDE7E586F1),\n\t\tUINT64_C(0xE3A03F137D520FA0), UINT64_C(0x3F01133123D8E1BD),\n\t\tUINT64_C(0x5BE36657C146D29B), UINT64_C(0x87424A759FCC3C86),\n\t\tUINT64_C(0xBC2CA41CAE3691EC), UINT64_C(0x608D883EF0BC7FF1),\n\t\tUINT64_C(0x046FFD5812224CD7), UINT64_C(0xD8CED17A4CA8A2CA),\n\t\tUINT64_C(0xCCAB1694D61F2B9B), UINT64_C(0x100A3AB68895C586),\n\t\tUINT64_C(0x74E84FD06A0BF6A0), UINT64_C(0xA84963F2348118BD),\n\t\tUINT64_C(0x5C22C10D5F64E503), UINT64_C(0x8083ED2F01EE0B1E),\n\t\tUINT64_C(0xE4619849E3703838), UINT64_C(0x38C0B46BBDFAD625),\n\t\tUINT64_C(0x2CA57385274D5F74), UINT64_C(0xF0045FA779C7B169),\n\t\tUINT64_C(0x94E62AC19B59824F), UINT64_C(0x484706E3C5D36C52),\n\t\tUINT64_C(0xF92F6091673CA1A0), UINT64_C(0x258E4CB339B64FBD),\n\t\tUINT64_C(0x416C39D5DB287C9B), UINT64_C(0x9DCD15F785A29286),\n\t\tUINT64_C(0x89A8D2191F151BD7), UINT64_C(0x5509FE3B419FF5CA),\n\t\tUINT64_C(0x31EB8B5DA301C6EC), UINT64_C(0xED4AA77FFD8B28F1),\n\t\tUINT64_C(0x19210580966ED54F), UINT64_C(0xC58029A2C8E43B52),\n\t\tUINT64_C(0xA1625CC42A7A0874), UINT64_C(0x7DC370E674F0E669),\n\t\tUINT64_C(0x69A6B708EE476F38), UINT64_C(0xB5079B2AB0CD8125),\n\t\tUINT64_C(0xD1E5EE4C5253B203), UINT64_C(0x0D44C26E0CD95C1E)\n\t}\n};\n"
  },
  {
    "path": "external/xz/liblzma/check/crc64_table_le.h",
    "content": "/* This file has been automatically generated by crc64_tablegen.c. */\n\nconst uint64_t lzma_crc64_table[4][256] = {\n\t{\n\t\tUINT64_C(0x0000000000000000), UINT64_C(0xB32E4CBE03A75F6F),\n\t\tUINT64_C(0xF4843657A840A05B), UINT64_C(0x47AA7AE9ABE7FF34),\n\t\tUINT64_C(0x7BD0C384FF8F5E33), UINT64_C(0xC8FE8F3AFC28015C),\n\t\tUINT64_C(0x8F54F5D357CFFE68), UINT64_C(0x3C7AB96D5468A107),\n\t\tUINT64_C(0xF7A18709FF1EBC66), UINT64_C(0x448FCBB7FCB9E309),\n\t\tUINT64_C(0x0325B15E575E1C3D), UINT64_C(0xB00BFDE054F94352),\n\t\tUINT64_C(0x8C71448D0091E255), UINT64_C(0x3F5F08330336BD3A),\n\t\tUINT64_C(0x78F572DAA8D1420E), UINT64_C(0xCBDB3E64AB761D61),\n\t\tUINT64_C(0x7D9BA13851336649), UINT64_C(0xCEB5ED8652943926),\n\t\tUINT64_C(0x891F976FF973C612), UINT64_C(0x3A31DBD1FAD4997D),\n\t\tUINT64_C(0x064B62BCAEBC387A), UINT64_C(0xB5652E02AD1B6715),\n\t\tUINT64_C(0xF2CF54EB06FC9821), UINT64_C(0x41E11855055BC74E),\n\t\tUINT64_C(0x8A3A2631AE2DDA2F), UINT64_C(0x39146A8FAD8A8540),\n\t\tUINT64_C(0x7EBE1066066D7A74), UINT64_C(0xCD905CD805CA251B),\n\t\tUINT64_C(0xF1EAE5B551A2841C), UINT64_C(0x42C4A90B5205DB73),\n\t\tUINT64_C(0x056ED3E2F9E22447), UINT64_C(0xB6409F5CFA457B28),\n\t\tUINT64_C(0xFB374270A266CC92), UINT64_C(0x48190ECEA1C193FD),\n\t\tUINT64_C(0x0FB374270A266CC9), UINT64_C(0xBC9D3899098133A6),\n\t\tUINT64_C(0x80E781F45DE992A1), UINT64_C(0x33C9CD4A5E4ECDCE),\n\t\tUINT64_C(0x7463B7A3F5A932FA), UINT64_C(0xC74DFB1DF60E6D95),\n\t\tUINT64_C(0x0C96C5795D7870F4), UINT64_C(0xBFB889C75EDF2F9B),\n\t\tUINT64_C(0xF812F32EF538D0AF), UINT64_C(0x4B3CBF90F69F8FC0),\n\t\tUINT64_C(0x774606FDA2F72EC7), UINT64_C(0xC4684A43A15071A8),\n\t\tUINT64_C(0x83C230AA0AB78E9C), UINT64_C(0x30EC7C140910D1F3),\n\t\tUINT64_C(0x86ACE348F355AADB), UINT64_C(0x3582AFF6F0F2F5B4),\n\t\tUINT64_C(0x7228D51F5B150A80), UINT64_C(0xC10699A158B255EF),\n\t\tUINT64_C(0xFD7C20CC0CDAF4E8), UINT64_C(0x4E526C720F7DAB87),\n\t\tUINT64_C(0x09F8169BA49A54B3), UINT64_C(0xBAD65A25A73D0BDC),\n\t\tUINT64_C(0x710D64410C4B16BD), UINT64_C(0xC22328FF0FEC49D2),\n\t\tUINT64_C(0x85895216A40BB6E6), UINT64_C(0x36A71EA8A7ACE989),\n\t\tUINT64_C(0x0ADDA7C5F3C4488E), UINT64_C(0xB9F3EB7BF06317E1),\n\t\tUINT64_C(0xFE5991925B84E8D5), UINT64_C(0x4D77DD2C5823B7BA),\n\t\tUINT64_C(0x64B62BCAEBC387A1), UINT64_C(0xD7986774E864D8CE),\n\t\tUINT64_C(0x90321D9D438327FA), UINT64_C(0x231C512340247895),\n\t\tUINT64_C(0x1F66E84E144CD992), UINT64_C(0xAC48A4F017EB86FD),\n\t\tUINT64_C(0xEBE2DE19BC0C79C9), UINT64_C(0x58CC92A7BFAB26A6),\n\t\tUINT64_C(0x9317ACC314DD3BC7), UINT64_C(0x2039E07D177A64A8),\n\t\tUINT64_C(0x67939A94BC9D9B9C), UINT64_C(0xD4BDD62ABF3AC4F3),\n\t\tUINT64_C(0xE8C76F47EB5265F4), UINT64_C(0x5BE923F9E8F53A9B),\n\t\tUINT64_C(0x1C4359104312C5AF), UINT64_C(0xAF6D15AE40B59AC0),\n\t\tUINT64_C(0x192D8AF2BAF0E1E8), UINT64_C(0xAA03C64CB957BE87),\n\t\tUINT64_C(0xEDA9BCA512B041B3), UINT64_C(0x5E87F01B11171EDC),\n\t\tUINT64_C(0x62FD4976457FBFDB), UINT64_C(0xD1D305C846D8E0B4),\n\t\tUINT64_C(0x96797F21ED3F1F80), UINT64_C(0x2557339FEE9840EF),\n\t\tUINT64_C(0xEE8C0DFB45EE5D8E), UINT64_C(0x5DA24145464902E1),\n\t\tUINT64_C(0x1A083BACEDAEFDD5), UINT64_C(0xA9267712EE09A2BA),\n\t\tUINT64_C(0x955CCE7FBA6103BD), UINT64_C(0x267282C1B9C65CD2),\n\t\tUINT64_C(0x61D8F8281221A3E6), UINT64_C(0xD2F6B4961186FC89),\n\t\tUINT64_C(0x9F8169BA49A54B33), UINT64_C(0x2CAF25044A02145C),\n\t\tUINT64_C(0x6B055FEDE1E5EB68), UINT64_C(0xD82B1353E242B407),\n\t\tUINT64_C(0xE451AA3EB62A1500), UINT64_C(0x577FE680B58D4A6F),\n\t\tUINT64_C(0x10D59C691E6AB55B), UINT64_C(0xA3FBD0D71DCDEA34),\n\t\tUINT64_C(0x6820EEB3B6BBF755), UINT64_C(0xDB0EA20DB51CA83A),\n\t\tUINT64_C(0x9CA4D8E41EFB570E), UINT64_C(0x2F8A945A1D5C0861),\n\t\tUINT64_C(0x13F02D374934A966), UINT64_C(0xA0DE61894A93F609),\n\t\tUINT64_C(0xE7741B60E174093D), UINT64_C(0x545A57DEE2D35652),\n\t\tUINT64_C(0xE21AC88218962D7A), UINT64_C(0x5134843C1B317215),\n\t\tUINT64_C(0x169EFED5B0D68D21), UINT64_C(0xA5B0B26BB371D24E),\n\t\tUINT64_C(0x99CA0B06E7197349), UINT64_C(0x2AE447B8E4BE2C26),\n\t\tUINT64_C(0x6D4E3D514F59D312), UINT64_C(0xDE6071EF4CFE8C7D),\n\t\tUINT64_C(0x15BB4F8BE788911C), UINT64_C(0xA6950335E42FCE73),\n\t\tUINT64_C(0xE13F79DC4FC83147), UINT64_C(0x521135624C6F6E28),\n\t\tUINT64_C(0x6E6B8C0F1807CF2F), UINT64_C(0xDD45C0B11BA09040),\n\t\tUINT64_C(0x9AEFBA58B0476F74), UINT64_C(0x29C1F6E6B3E0301B),\n\t\tUINT64_C(0xC96C5795D7870F42), UINT64_C(0x7A421B2BD420502D),\n\t\tUINT64_C(0x3DE861C27FC7AF19), UINT64_C(0x8EC62D7C7C60F076),\n\t\tUINT64_C(0xB2BC941128085171), UINT64_C(0x0192D8AF2BAF0E1E),\n\t\tUINT64_C(0x4638A2468048F12A), UINT64_C(0xF516EEF883EFAE45),\n\t\tUINT64_C(0x3ECDD09C2899B324), UINT64_C(0x8DE39C222B3EEC4B),\n\t\tUINT64_C(0xCA49E6CB80D9137F), UINT64_C(0x7967AA75837E4C10),\n\t\tUINT64_C(0x451D1318D716ED17), UINT64_C(0xF6335FA6D4B1B278),\n\t\tUINT64_C(0xB199254F7F564D4C), UINT64_C(0x02B769F17CF11223),\n\t\tUINT64_C(0xB4F7F6AD86B4690B), UINT64_C(0x07D9BA1385133664),\n\t\tUINT64_C(0x4073C0FA2EF4C950), UINT64_C(0xF35D8C442D53963F),\n\t\tUINT64_C(0xCF273529793B3738), UINT64_C(0x7C0979977A9C6857),\n\t\tUINT64_C(0x3BA3037ED17B9763), UINT64_C(0x888D4FC0D2DCC80C),\n\t\tUINT64_C(0x435671A479AAD56D), UINT64_C(0xF0783D1A7A0D8A02),\n\t\tUINT64_C(0xB7D247F3D1EA7536), UINT64_C(0x04FC0B4DD24D2A59),\n\t\tUINT64_C(0x3886B22086258B5E), UINT64_C(0x8BA8FE9E8582D431),\n\t\tUINT64_C(0xCC0284772E652B05), UINT64_C(0x7F2CC8C92DC2746A),\n\t\tUINT64_C(0x325B15E575E1C3D0), UINT64_C(0x8175595B76469CBF),\n\t\tUINT64_C(0xC6DF23B2DDA1638B), UINT64_C(0x75F16F0CDE063CE4),\n\t\tUINT64_C(0x498BD6618A6E9DE3), UINT64_C(0xFAA59ADF89C9C28C),\n\t\tUINT64_C(0xBD0FE036222E3DB8), UINT64_C(0x0E21AC88218962D7),\n\t\tUINT64_C(0xC5FA92EC8AFF7FB6), UINT64_C(0x76D4DE52895820D9),\n\t\tUINT64_C(0x317EA4BB22BFDFED), UINT64_C(0x8250E80521188082),\n\t\tUINT64_C(0xBE2A516875702185), UINT64_C(0x0D041DD676D77EEA),\n\t\tUINT64_C(0x4AAE673FDD3081DE), UINT64_C(0xF9802B81DE97DEB1),\n\t\tUINT64_C(0x4FC0B4DD24D2A599), UINT64_C(0xFCEEF8632775FAF6),\n\t\tUINT64_C(0xBB44828A8C9205C2), UINT64_C(0x086ACE348F355AAD),\n\t\tUINT64_C(0x34107759DB5DFBAA), UINT64_C(0x873E3BE7D8FAA4C5),\n\t\tUINT64_C(0xC094410E731D5BF1), UINT64_C(0x73BA0DB070BA049E),\n\t\tUINT64_C(0xB86133D4DBCC19FF), UINT64_C(0x0B4F7F6AD86B4690),\n\t\tUINT64_C(0x4CE50583738CB9A4), UINT64_C(0xFFCB493D702BE6CB),\n\t\tUINT64_C(0xC3B1F050244347CC), UINT64_C(0x709FBCEE27E418A3),\n\t\tUINT64_C(0x3735C6078C03E797), UINT64_C(0x841B8AB98FA4B8F8),\n\t\tUINT64_C(0xADDA7C5F3C4488E3), UINT64_C(0x1EF430E13FE3D78C),\n\t\tUINT64_C(0x595E4A08940428B8), UINT64_C(0xEA7006B697A377D7),\n\t\tUINT64_C(0xD60ABFDBC3CBD6D0), UINT64_C(0x6524F365C06C89BF),\n\t\tUINT64_C(0x228E898C6B8B768B), UINT64_C(0x91A0C532682C29E4),\n\t\tUINT64_C(0x5A7BFB56C35A3485), UINT64_C(0xE955B7E8C0FD6BEA),\n\t\tUINT64_C(0xAEFFCD016B1A94DE), UINT64_C(0x1DD181BF68BDCBB1),\n\t\tUINT64_C(0x21AB38D23CD56AB6), UINT64_C(0x9285746C3F7235D9),\n\t\tUINT64_C(0xD52F0E859495CAED), UINT64_C(0x6601423B97329582),\n\t\tUINT64_C(0xD041DD676D77EEAA), UINT64_C(0x636F91D96ED0B1C5),\n\t\tUINT64_C(0x24C5EB30C5374EF1), UINT64_C(0x97EBA78EC690119E),\n\t\tUINT64_C(0xAB911EE392F8B099), UINT64_C(0x18BF525D915FEFF6),\n\t\tUINT64_C(0x5F1528B43AB810C2), UINT64_C(0xEC3B640A391F4FAD),\n\t\tUINT64_C(0x27E05A6E926952CC), UINT64_C(0x94CE16D091CE0DA3),\n\t\tUINT64_C(0xD3646C393A29F297), UINT64_C(0x604A2087398EADF8),\n\t\tUINT64_C(0x5C3099EA6DE60CFF), UINT64_C(0xEF1ED5546E415390),\n\t\tUINT64_C(0xA8B4AFBDC5A6ACA4), UINT64_C(0x1B9AE303C601F3CB),\n\t\tUINT64_C(0x56ED3E2F9E224471), UINT64_C(0xE5C372919D851B1E),\n\t\tUINT64_C(0xA26908783662E42A), UINT64_C(0x114744C635C5BB45),\n\t\tUINT64_C(0x2D3DFDAB61AD1A42), UINT64_C(0x9E13B115620A452D),\n\t\tUINT64_C(0xD9B9CBFCC9EDBA19), UINT64_C(0x6A978742CA4AE576),\n\t\tUINT64_C(0xA14CB926613CF817), UINT64_C(0x1262F598629BA778),\n\t\tUINT64_C(0x55C88F71C97C584C), UINT64_C(0xE6E6C3CFCADB0723),\n\t\tUINT64_C(0xDA9C7AA29EB3A624), UINT64_C(0x69B2361C9D14F94B),\n\t\tUINT64_C(0x2E184CF536F3067F), UINT64_C(0x9D36004B35545910),\n\t\tUINT64_C(0x2B769F17CF112238), UINT64_C(0x9858D3A9CCB67D57),\n\t\tUINT64_C(0xDFF2A94067518263), UINT64_C(0x6CDCE5FE64F6DD0C),\n\t\tUINT64_C(0x50A65C93309E7C0B), UINT64_C(0xE388102D33392364),\n\t\tUINT64_C(0xA4226AC498DEDC50), UINT64_C(0x170C267A9B79833F),\n\t\tUINT64_C(0xDCD7181E300F9E5E), UINT64_C(0x6FF954A033A8C131),\n\t\tUINT64_C(0x28532E49984F3E05), UINT64_C(0x9B7D62F79BE8616A),\n\t\tUINT64_C(0xA707DB9ACF80C06D), UINT64_C(0x14299724CC279F02),\n\t\tUINT64_C(0x5383EDCD67C06036), UINT64_C(0xE0ADA17364673F59)\n\t}, {\n\t\tUINT64_C(0x0000000000000000), UINT64_C(0x54E979925CD0F10D),\n\t\tUINT64_C(0xA9D2F324B9A1E21A), UINT64_C(0xFD3B8AB6E5711317),\n\t\tUINT64_C(0xC17D4962DC4DDAB1), UINT64_C(0x959430F0809D2BBC),\n\t\tUINT64_C(0x68AFBA4665EC38AB), UINT64_C(0x3C46C3D4393CC9A6),\n\t\tUINT64_C(0x10223DEE1795ABE7), UINT64_C(0x44CB447C4B455AEA),\n\t\tUINT64_C(0xB9F0CECAAE3449FD), UINT64_C(0xED19B758F2E4B8F0),\n\t\tUINT64_C(0xD15F748CCBD87156), UINT64_C(0x85B60D1E9708805B),\n\t\tUINT64_C(0x788D87A87279934C), UINT64_C(0x2C64FE3A2EA96241),\n\t\tUINT64_C(0x20447BDC2F2B57CE), UINT64_C(0x74AD024E73FBA6C3),\n\t\tUINT64_C(0x899688F8968AB5D4), UINT64_C(0xDD7FF16ACA5A44D9),\n\t\tUINT64_C(0xE13932BEF3668D7F), UINT64_C(0xB5D04B2CAFB67C72),\n\t\tUINT64_C(0x48EBC19A4AC76F65), UINT64_C(0x1C02B80816179E68),\n\t\tUINT64_C(0x3066463238BEFC29), UINT64_C(0x648F3FA0646E0D24),\n\t\tUINT64_C(0x99B4B516811F1E33), UINT64_C(0xCD5DCC84DDCFEF3E),\n\t\tUINT64_C(0xF11B0F50E4F32698), UINT64_C(0xA5F276C2B823D795),\n\t\tUINT64_C(0x58C9FC745D52C482), UINT64_C(0x0C2085E60182358F),\n\t\tUINT64_C(0x4088F7B85E56AF9C), UINT64_C(0x14618E2A02865E91),\n\t\tUINT64_C(0xE95A049CE7F74D86), UINT64_C(0xBDB37D0EBB27BC8B),\n\t\tUINT64_C(0x81F5BEDA821B752D), UINT64_C(0xD51CC748DECB8420),\n\t\tUINT64_C(0x28274DFE3BBA9737), UINT64_C(0x7CCE346C676A663A),\n\t\tUINT64_C(0x50AACA5649C3047B), UINT64_C(0x0443B3C41513F576),\n\t\tUINT64_C(0xF9783972F062E661), UINT64_C(0xAD9140E0ACB2176C),\n\t\tUINT64_C(0x91D78334958EDECA), UINT64_C(0xC53EFAA6C95E2FC7),\n\t\tUINT64_C(0x380570102C2F3CD0), UINT64_C(0x6CEC098270FFCDDD),\n\t\tUINT64_C(0x60CC8C64717DF852), UINT64_C(0x3425F5F62DAD095F),\n\t\tUINT64_C(0xC91E7F40C8DC1A48), UINT64_C(0x9DF706D2940CEB45),\n\t\tUINT64_C(0xA1B1C506AD3022E3), UINT64_C(0xF558BC94F1E0D3EE),\n\t\tUINT64_C(0x086336221491C0F9), UINT64_C(0x5C8A4FB0484131F4),\n\t\tUINT64_C(0x70EEB18A66E853B5), UINT64_C(0x2407C8183A38A2B8),\n\t\tUINT64_C(0xD93C42AEDF49B1AF), UINT64_C(0x8DD53B3C839940A2),\n\t\tUINT64_C(0xB193F8E8BAA58904), UINT64_C(0xE57A817AE6757809),\n\t\tUINT64_C(0x18410BCC03046B1E), UINT64_C(0x4CA8725E5FD49A13),\n\t\tUINT64_C(0x8111EF70BCAD5F38), UINT64_C(0xD5F896E2E07DAE35),\n\t\tUINT64_C(0x28C31C54050CBD22), UINT64_C(0x7C2A65C659DC4C2F),\n\t\tUINT64_C(0x406CA61260E08589), UINT64_C(0x1485DF803C307484),\n\t\tUINT64_C(0xE9BE5536D9416793), UINT64_C(0xBD572CA48591969E),\n\t\tUINT64_C(0x9133D29EAB38F4DF), UINT64_C(0xC5DAAB0CF7E805D2),\n\t\tUINT64_C(0x38E121BA129916C5), UINT64_C(0x6C0858284E49E7C8),\n\t\tUINT64_C(0x504E9BFC77752E6E), UINT64_C(0x04A7E26E2BA5DF63),\n\t\tUINT64_C(0xF99C68D8CED4CC74), UINT64_C(0xAD75114A92043D79),\n\t\tUINT64_C(0xA15594AC938608F6), UINT64_C(0xF5BCED3ECF56F9FB),\n\t\tUINT64_C(0x088767882A27EAEC), UINT64_C(0x5C6E1E1A76F71BE1),\n\t\tUINT64_C(0x6028DDCE4FCBD247), UINT64_C(0x34C1A45C131B234A),\n\t\tUINT64_C(0xC9FA2EEAF66A305D), UINT64_C(0x9D135778AABAC150),\n\t\tUINT64_C(0xB177A9428413A311), UINT64_C(0xE59ED0D0D8C3521C),\n\t\tUINT64_C(0x18A55A663DB2410B), UINT64_C(0x4C4C23F46162B006),\n\t\tUINT64_C(0x700AE020585E79A0), UINT64_C(0x24E399B2048E88AD),\n\t\tUINT64_C(0xD9D81304E1FF9BBA), UINT64_C(0x8D316A96BD2F6AB7),\n\t\tUINT64_C(0xC19918C8E2FBF0A4), UINT64_C(0x9570615ABE2B01A9),\n\t\tUINT64_C(0x684BEBEC5B5A12BE), UINT64_C(0x3CA2927E078AE3B3),\n\t\tUINT64_C(0x00E451AA3EB62A15), UINT64_C(0x540D28386266DB18),\n\t\tUINT64_C(0xA936A28E8717C80F), UINT64_C(0xFDDFDB1CDBC73902),\n\t\tUINT64_C(0xD1BB2526F56E5B43), UINT64_C(0x85525CB4A9BEAA4E),\n\t\tUINT64_C(0x7869D6024CCFB959), UINT64_C(0x2C80AF90101F4854),\n\t\tUINT64_C(0x10C66C44292381F2), UINT64_C(0x442F15D675F370FF),\n\t\tUINT64_C(0xB9149F60908263E8), UINT64_C(0xEDFDE6F2CC5292E5),\n\t\tUINT64_C(0xE1DD6314CDD0A76A), UINT64_C(0xB5341A8691005667),\n\t\tUINT64_C(0x480F903074714570), UINT64_C(0x1CE6E9A228A1B47D),\n\t\tUINT64_C(0x20A02A76119D7DDB), UINT64_C(0x744953E44D4D8CD6),\n\t\tUINT64_C(0x8972D952A83C9FC1), UINT64_C(0xDD9BA0C0F4EC6ECC),\n\t\tUINT64_C(0xF1FF5EFADA450C8D), UINT64_C(0xA51627688695FD80),\n\t\tUINT64_C(0x582DADDE63E4EE97), UINT64_C(0x0CC4D44C3F341F9A),\n\t\tUINT64_C(0x308217980608D63C), UINT64_C(0x646B6E0A5AD82731),\n\t\tUINT64_C(0x9950E4BCBFA93426), UINT64_C(0xCDB99D2EE379C52B),\n\t\tUINT64_C(0x90FB71CAD654A0F5), UINT64_C(0xC41208588A8451F8),\n\t\tUINT64_C(0x392982EE6FF542EF), UINT64_C(0x6DC0FB7C3325B3E2),\n\t\tUINT64_C(0x518638A80A197A44), UINT64_C(0x056F413A56C98B49),\n\t\tUINT64_C(0xF854CB8CB3B8985E), UINT64_C(0xACBDB21EEF686953),\n\t\tUINT64_C(0x80D94C24C1C10B12), UINT64_C(0xD43035B69D11FA1F),\n\t\tUINT64_C(0x290BBF007860E908), UINT64_C(0x7DE2C69224B01805),\n\t\tUINT64_C(0x41A405461D8CD1A3), UINT64_C(0x154D7CD4415C20AE),\n\t\tUINT64_C(0xE876F662A42D33B9), UINT64_C(0xBC9F8FF0F8FDC2B4),\n\t\tUINT64_C(0xB0BF0A16F97FF73B), UINT64_C(0xE4567384A5AF0636),\n\t\tUINT64_C(0x196DF93240DE1521), UINT64_C(0x4D8480A01C0EE42C),\n\t\tUINT64_C(0x71C2437425322D8A), UINT64_C(0x252B3AE679E2DC87),\n\t\tUINT64_C(0xD810B0509C93CF90), UINT64_C(0x8CF9C9C2C0433E9D),\n\t\tUINT64_C(0xA09D37F8EEEA5CDC), UINT64_C(0xF4744E6AB23AADD1),\n\t\tUINT64_C(0x094FC4DC574BBEC6), UINT64_C(0x5DA6BD4E0B9B4FCB),\n\t\tUINT64_C(0x61E07E9A32A7866D), UINT64_C(0x350907086E777760),\n\t\tUINT64_C(0xC8328DBE8B066477), UINT64_C(0x9CDBF42CD7D6957A),\n\t\tUINT64_C(0xD073867288020F69), UINT64_C(0x849AFFE0D4D2FE64),\n\t\tUINT64_C(0x79A1755631A3ED73), UINT64_C(0x2D480CC46D731C7E),\n\t\tUINT64_C(0x110ECF10544FD5D8), UINT64_C(0x45E7B682089F24D5),\n\t\tUINT64_C(0xB8DC3C34EDEE37C2), UINT64_C(0xEC3545A6B13EC6CF),\n\t\tUINT64_C(0xC051BB9C9F97A48E), UINT64_C(0x94B8C20EC3475583),\n\t\tUINT64_C(0x698348B826364694), UINT64_C(0x3D6A312A7AE6B799),\n\t\tUINT64_C(0x012CF2FE43DA7E3F), UINT64_C(0x55C58B6C1F0A8F32),\n\t\tUINT64_C(0xA8FE01DAFA7B9C25), UINT64_C(0xFC177848A6AB6D28),\n\t\tUINT64_C(0xF037FDAEA72958A7), UINT64_C(0xA4DE843CFBF9A9AA),\n\t\tUINT64_C(0x59E50E8A1E88BABD), UINT64_C(0x0D0C771842584BB0),\n\t\tUINT64_C(0x314AB4CC7B648216), UINT64_C(0x65A3CD5E27B4731B),\n\t\tUINT64_C(0x989847E8C2C5600C), UINT64_C(0xCC713E7A9E159101),\n\t\tUINT64_C(0xE015C040B0BCF340), UINT64_C(0xB4FCB9D2EC6C024D),\n\t\tUINT64_C(0x49C73364091D115A), UINT64_C(0x1D2E4AF655CDE057),\n\t\tUINT64_C(0x216889226CF129F1), UINT64_C(0x7581F0B03021D8FC),\n\t\tUINT64_C(0x88BA7A06D550CBEB), UINT64_C(0xDC53039489803AE6),\n\t\tUINT64_C(0x11EA9EBA6AF9FFCD), UINT64_C(0x4503E72836290EC0),\n\t\tUINT64_C(0xB8386D9ED3581DD7), UINT64_C(0xECD1140C8F88ECDA),\n\t\tUINT64_C(0xD097D7D8B6B4257C), UINT64_C(0x847EAE4AEA64D471),\n\t\tUINT64_C(0x794524FC0F15C766), UINT64_C(0x2DAC5D6E53C5366B),\n\t\tUINT64_C(0x01C8A3547D6C542A), UINT64_C(0x5521DAC621BCA527),\n\t\tUINT64_C(0xA81A5070C4CDB630), UINT64_C(0xFCF329E2981D473D),\n\t\tUINT64_C(0xC0B5EA36A1218E9B), UINT64_C(0x945C93A4FDF17F96),\n\t\tUINT64_C(0x6967191218806C81), UINT64_C(0x3D8E608044509D8C),\n\t\tUINT64_C(0x31AEE56645D2A803), UINT64_C(0x65479CF41902590E),\n\t\tUINT64_C(0x987C1642FC734A19), UINT64_C(0xCC956FD0A0A3BB14),\n\t\tUINT64_C(0xF0D3AC04999F72B2), UINT64_C(0xA43AD596C54F83BF),\n\t\tUINT64_C(0x59015F20203E90A8), UINT64_C(0x0DE826B27CEE61A5),\n\t\tUINT64_C(0x218CD888524703E4), UINT64_C(0x7565A11A0E97F2E9),\n\t\tUINT64_C(0x885E2BACEBE6E1FE), UINT64_C(0xDCB7523EB73610F3),\n\t\tUINT64_C(0xE0F191EA8E0AD955), UINT64_C(0xB418E878D2DA2858),\n\t\tUINT64_C(0x492362CE37AB3B4F), UINT64_C(0x1DCA1B5C6B7BCA42),\n\t\tUINT64_C(0x5162690234AF5051), UINT64_C(0x058B1090687FA15C),\n\t\tUINT64_C(0xF8B09A268D0EB24B), UINT64_C(0xAC59E3B4D1DE4346),\n\t\tUINT64_C(0x901F2060E8E28AE0), UINT64_C(0xC4F659F2B4327BED),\n\t\tUINT64_C(0x39CDD344514368FA), UINT64_C(0x6D24AAD60D9399F7),\n\t\tUINT64_C(0x414054EC233AFBB6), UINT64_C(0x15A92D7E7FEA0ABB),\n\t\tUINT64_C(0xE892A7C89A9B19AC), UINT64_C(0xBC7BDE5AC64BE8A1),\n\t\tUINT64_C(0x803D1D8EFF772107), UINT64_C(0xD4D4641CA3A7D00A),\n\t\tUINT64_C(0x29EFEEAA46D6C31D), UINT64_C(0x7D0697381A063210),\n\t\tUINT64_C(0x712612DE1B84079F), UINT64_C(0x25CF6B4C4754F692),\n\t\tUINT64_C(0xD8F4E1FAA225E585), UINT64_C(0x8C1D9868FEF51488),\n\t\tUINT64_C(0xB05B5BBCC7C9DD2E), UINT64_C(0xE4B2222E9B192C23),\n\t\tUINT64_C(0x1989A8987E683F34), UINT64_C(0x4D60D10A22B8CE39),\n\t\tUINT64_C(0x61042F300C11AC78), UINT64_C(0x35ED56A250C15D75),\n\t\tUINT64_C(0xC8D6DC14B5B04E62), UINT64_C(0x9C3FA586E960BF6F),\n\t\tUINT64_C(0xA0796652D05C76C9), UINT64_C(0xF4901FC08C8C87C4),\n\t\tUINT64_C(0x09AB957669FD94D3), UINT64_C(0x5D42ECE4352D65DE)\n\t}, {\n\t\tUINT64_C(0x0000000000000000), UINT64_C(0x3F0BE14A916A6DCB),\n\t\tUINT64_C(0x7E17C29522D4DB96), UINT64_C(0x411C23DFB3BEB65D),\n\t\tUINT64_C(0xFC2F852A45A9B72C), UINT64_C(0xC3246460D4C3DAE7),\n\t\tUINT64_C(0x823847BF677D6CBA), UINT64_C(0xBD33A6F5F6170171),\n\t\tUINT64_C(0x6A87A57F245D70DD), UINT64_C(0x558C4435B5371D16),\n\t\tUINT64_C(0x149067EA0689AB4B), UINT64_C(0x2B9B86A097E3C680),\n\t\tUINT64_C(0x96A8205561F4C7F1), UINT64_C(0xA9A3C11FF09EAA3A),\n\t\tUINT64_C(0xE8BFE2C043201C67), UINT64_C(0xD7B4038AD24A71AC),\n\t\tUINT64_C(0xD50F4AFE48BAE1BA), UINT64_C(0xEA04ABB4D9D08C71),\n\t\tUINT64_C(0xAB18886B6A6E3A2C), UINT64_C(0x94136921FB0457E7),\n\t\tUINT64_C(0x2920CFD40D135696), UINT64_C(0x162B2E9E9C793B5D),\n\t\tUINT64_C(0x57370D412FC78D00), UINT64_C(0x683CEC0BBEADE0CB),\n\t\tUINT64_C(0xBF88EF816CE79167), UINT64_C(0x80830ECBFD8DFCAC),\n\t\tUINT64_C(0xC19F2D144E334AF1), UINT64_C(0xFE94CC5EDF59273A),\n\t\tUINT64_C(0x43A76AAB294E264B), UINT64_C(0x7CAC8BE1B8244B80),\n\t\tUINT64_C(0x3DB0A83E0B9AFDDD), UINT64_C(0x02BB49749AF09016),\n\t\tUINT64_C(0x38C63AD73E7BDDF1), UINT64_C(0x07CDDB9DAF11B03A),\n\t\tUINT64_C(0x46D1F8421CAF0667), UINT64_C(0x79DA19088DC56BAC),\n\t\tUINT64_C(0xC4E9BFFD7BD26ADD), UINT64_C(0xFBE25EB7EAB80716),\n\t\tUINT64_C(0xBAFE7D685906B14B), UINT64_C(0x85F59C22C86CDC80),\n\t\tUINT64_C(0x52419FA81A26AD2C), UINT64_C(0x6D4A7EE28B4CC0E7),\n\t\tUINT64_C(0x2C565D3D38F276BA), UINT64_C(0x135DBC77A9981B71),\n\t\tUINT64_C(0xAE6E1A825F8F1A00), UINT64_C(0x9165FBC8CEE577CB),\n\t\tUINT64_C(0xD079D8177D5BC196), UINT64_C(0xEF72395DEC31AC5D),\n\t\tUINT64_C(0xEDC9702976C13C4B), UINT64_C(0xD2C29163E7AB5180),\n\t\tUINT64_C(0x93DEB2BC5415E7DD), UINT64_C(0xACD553F6C57F8A16),\n\t\tUINT64_C(0x11E6F50333688B67), UINT64_C(0x2EED1449A202E6AC),\n\t\tUINT64_C(0x6FF1379611BC50F1), UINT64_C(0x50FAD6DC80D63D3A),\n\t\tUINT64_C(0x874ED556529C4C96), UINT64_C(0xB845341CC3F6215D),\n\t\tUINT64_C(0xF95917C370489700), UINT64_C(0xC652F689E122FACB),\n\t\tUINT64_C(0x7B61507C1735FBBA), UINT64_C(0x446AB136865F9671),\n\t\tUINT64_C(0x057692E935E1202C), UINT64_C(0x3A7D73A3A48B4DE7),\n\t\tUINT64_C(0x718C75AE7CF7BBE2), UINT64_C(0x4E8794E4ED9DD629),\n\t\tUINT64_C(0x0F9BB73B5E236074), UINT64_C(0x30905671CF490DBF),\n\t\tUINT64_C(0x8DA3F084395E0CCE), UINT64_C(0xB2A811CEA8346105),\n\t\tUINT64_C(0xF3B432111B8AD758), UINT64_C(0xCCBFD35B8AE0BA93),\n\t\tUINT64_C(0x1B0BD0D158AACB3F), UINT64_C(0x2400319BC9C0A6F4),\n\t\tUINT64_C(0x651C12447A7E10A9), UINT64_C(0x5A17F30EEB147D62),\n\t\tUINT64_C(0xE72455FB1D037C13), UINT64_C(0xD82FB4B18C6911D8),\n\t\tUINT64_C(0x9933976E3FD7A785), UINT64_C(0xA6387624AEBDCA4E),\n\t\tUINT64_C(0xA4833F50344D5A58), UINT64_C(0x9B88DE1AA5273793),\n\t\tUINT64_C(0xDA94FDC5169981CE), UINT64_C(0xE59F1C8F87F3EC05),\n\t\tUINT64_C(0x58ACBA7A71E4ED74), UINT64_C(0x67A75B30E08E80BF),\n\t\tUINT64_C(0x26BB78EF533036E2), UINT64_C(0x19B099A5C25A5B29),\n\t\tUINT64_C(0xCE049A2F10102A85), UINT64_C(0xF10F7B65817A474E),\n\t\tUINT64_C(0xB01358BA32C4F113), UINT64_C(0x8F18B9F0A3AE9CD8),\n\t\tUINT64_C(0x322B1F0555B99DA9), UINT64_C(0x0D20FE4FC4D3F062),\n\t\tUINT64_C(0x4C3CDD90776D463F), UINT64_C(0x73373CDAE6072BF4),\n\t\tUINT64_C(0x494A4F79428C6613), UINT64_C(0x7641AE33D3E60BD8),\n\t\tUINT64_C(0x375D8DEC6058BD85), UINT64_C(0x08566CA6F132D04E),\n\t\tUINT64_C(0xB565CA530725D13F), UINT64_C(0x8A6E2B19964FBCF4),\n\t\tUINT64_C(0xCB7208C625F10AA9), UINT64_C(0xF479E98CB49B6762),\n\t\tUINT64_C(0x23CDEA0666D116CE), UINT64_C(0x1CC60B4CF7BB7B05),\n\t\tUINT64_C(0x5DDA28934405CD58), UINT64_C(0x62D1C9D9D56FA093),\n\t\tUINT64_C(0xDFE26F2C2378A1E2), UINT64_C(0xE0E98E66B212CC29),\n\t\tUINT64_C(0xA1F5ADB901AC7A74), UINT64_C(0x9EFE4CF390C617BF),\n\t\tUINT64_C(0x9C4505870A3687A9), UINT64_C(0xA34EE4CD9B5CEA62),\n\t\tUINT64_C(0xE252C71228E25C3F), UINT64_C(0xDD592658B98831F4),\n\t\tUINT64_C(0x606A80AD4F9F3085), UINT64_C(0x5F6161E7DEF55D4E),\n\t\tUINT64_C(0x1E7D42386D4BEB13), UINT64_C(0x2176A372FC2186D8),\n\t\tUINT64_C(0xF6C2A0F82E6BF774), UINT64_C(0xC9C941B2BF019ABF),\n\t\tUINT64_C(0x88D5626D0CBF2CE2), UINT64_C(0xB7DE83279DD54129),\n\t\tUINT64_C(0x0AED25D26BC24058), UINT64_C(0x35E6C498FAA82D93),\n\t\tUINT64_C(0x74FAE74749169BCE), UINT64_C(0x4BF1060DD87CF605),\n\t\tUINT64_C(0xE318EB5CF9EF77C4), UINT64_C(0xDC130A1668851A0F),\n\t\tUINT64_C(0x9D0F29C9DB3BAC52), UINT64_C(0xA204C8834A51C199),\n\t\tUINT64_C(0x1F376E76BC46C0E8), UINT64_C(0x203C8F3C2D2CAD23),\n\t\tUINT64_C(0x6120ACE39E921B7E), UINT64_C(0x5E2B4DA90FF876B5),\n\t\tUINT64_C(0x899F4E23DDB20719), UINT64_C(0xB694AF694CD86AD2),\n\t\tUINT64_C(0xF7888CB6FF66DC8F), UINT64_C(0xC8836DFC6E0CB144),\n\t\tUINT64_C(0x75B0CB09981BB035), UINT64_C(0x4ABB2A430971DDFE),\n\t\tUINT64_C(0x0BA7099CBACF6BA3), UINT64_C(0x34ACE8D62BA50668),\n\t\tUINT64_C(0x3617A1A2B155967E), UINT64_C(0x091C40E8203FFBB5),\n\t\tUINT64_C(0x4800633793814DE8), UINT64_C(0x770B827D02EB2023),\n\t\tUINT64_C(0xCA382488F4FC2152), UINT64_C(0xF533C5C265964C99),\n\t\tUINT64_C(0xB42FE61DD628FAC4), UINT64_C(0x8B2407574742970F),\n\t\tUINT64_C(0x5C9004DD9508E6A3), UINT64_C(0x639BE59704628B68),\n\t\tUINT64_C(0x2287C648B7DC3D35), UINT64_C(0x1D8C270226B650FE),\n\t\tUINT64_C(0xA0BF81F7D0A1518F), UINT64_C(0x9FB460BD41CB3C44),\n\t\tUINT64_C(0xDEA84362F2758A19), UINT64_C(0xE1A3A228631FE7D2),\n\t\tUINT64_C(0xDBDED18BC794AA35), UINT64_C(0xE4D530C156FEC7FE),\n\t\tUINT64_C(0xA5C9131EE54071A3), UINT64_C(0x9AC2F254742A1C68),\n\t\tUINT64_C(0x27F154A1823D1D19), UINT64_C(0x18FAB5EB135770D2),\n\t\tUINT64_C(0x59E69634A0E9C68F), UINT64_C(0x66ED777E3183AB44),\n\t\tUINT64_C(0xB15974F4E3C9DAE8), UINT64_C(0x8E5295BE72A3B723),\n\t\tUINT64_C(0xCF4EB661C11D017E), UINT64_C(0xF045572B50776CB5),\n\t\tUINT64_C(0x4D76F1DEA6606DC4), UINT64_C(0x727D1094370A000F),\n\t\tUINT64_C(0x3361334B84B4B652), UINT64_C(0x0C6AD20115DEDB99),\n\t\tUINT64_C(0x0ED19B758F2E4B8F), UINT64_C(0x31DA7A3F1E442644),\n\t\tUINT64_C(0x70C659E0ADFA9019), UINT64_C(0x4FCDB8AA3C90FDD2),\n\t\tUINT64_C(0xF2FE1E5FCA87FCA3), UINT64_C(0xCDF5FF155BED9168),\n\t\tUINT64_C(0x8CE9DCCAE8532735), UINT64_C(0xB3E23D8079394AFE),\n\t\tUINT64_C(0x64563E0AAB733B52), UINT64_C(0x5B5DDF403A195699),\n\t\tUINT64_C(0x1A41FC9F89A7E0C4), UINT64_C(0x254A1DD518CD8D0F),\n\t\tUINT64_C(0x9879BB20EEDA8C7E), UINT64_C(0xA7725A6A7FB0E1B5),\n\t\tUINT64_C(0xE66E79B5CC0E57E8), UINT64_C(0xD96598FF5D643A23),\n\t\tUINT64_C(0x92949EF28518CC26), UINT64_C(0xAD9F7FB81472A1ED),\n\t\tUINT64_C(0xEC835C67A7CC17B0), UINT64_C(0xD388BD2D36A67A7B),\n\t\tUINT64_C(0x6EBB1BD8C0B17B0A), UINT64_C(0x51B0FA9251DB16C1),\n\t\tUINT64_C(0x10ACD94DE265A09C), UINT64_C(0x2FA73807730FCD57),\n\t\tUINT64_C(0xF8133B8DA145BCFB), UINT64_C(0xC718DAC7302FD130),\n\t\tUINT64_C(0x8604F9188391676D), UINT64_C(0xB90F185212FB0AA6),\n\t\tUINT64_C(0x043CBEA7E4EC0BD7), UINT64_C(0x3B375FED7586661C),\n\t\tUINT64_C(0x7A2B7C32C638D041), UINT64_C(0x45209D785752BD8A),\n\t\tUINT64_C(0x479BD40CCDA22D9C), UINT64_C(0x789035465CC84057),\n\t\tUINT64_C(0x398C1699EF76F60A), UINT64_C(0x0687F7D37E1C9BC1),\n\t\tUINT64_C(0xBBB45126880B9AB0), UINT64_C(0x84BFB06C1961F77B),\n\t\tUINT64_C(0xC5A393B3AADF4126), UINT64_C(0xFAA872F93BB52CED),\n\t\tUINT64_C(0x2D1C7173E9FF5D41), UINT64_C(0x121790397895308A),\n\t\tUINT64_C(0x530BB3E6CB2B86D7), UINT64_C(0x6C0052AC5A41EB1C),\n\t\tUINT64_C(0xD133F459AC56EA6D), UINT64_C(0xEE3815133D3C87A6),\n\t\tUINT64_C(0xAF2436CC8E8231FB), UINT64_C(0x902FD7861FE85C30),\n\t\tUINT64_C(0xAA52A425BB6311D7), UINT64_C(0x9559456F2A097C1C),\n\t\tUINT64_C(0xD44566B099B7CA41), UINT64_C(0xEB4E87FA08DDA78A),\n\t\tUINT64_C(0x567D210FFECAA6FB), UINT64_C(0x6976C0456FA0CB30),\n\t\tUINT64_C(0x286AE39ADC1E7D6D), UINT64_C(0x176102D04D7410A6),\n\t\tUINT64_C(0xC0D5015A9F3E610A), UINT64_C(0xFFDEE0100E540CC1),\n\t\tUINT64_C(0xBEC2C3CFBDEABA9C), UINT64_C(0x81C922852C80D757),\n\t\tUINT64_C(0x3CFA8470DA97D626), UINT64_C(0x03F1653A4BFDBBED),\n\t\tUINT64_C(0x42ED46E5F8430DB0), UINT64_C(0x7DE6A7AF6929607B),\n\t\tUINT64_C(0x7F5DEEDBF3D9F06D), UINT64_C(0x40560F9162B39DA6),\n\t\tUINT64_C(0x014A2C4ED10D2BFB), UINT64_C(0x3E41CD0440674630),\n\t\tUINT64_C(0x83726BF1B6704741), UINT64_C(0xBC798ABB271A2A8A),\n\t\tUINT64_C(0xFD65A96494A49CD7), UINT64_C(0xC26E482E05CEF11C),\n\t\tUINT64_C(0x15DA4BA4D78480B0), UINT64_C(0x2AD1AAEE46EEED7B),\n\t\tUINT64_C(0x6BCD8931F5505B26), UINT64_C(0x54C6687B643A36ED),\n\t\tUINT64_C(0xE9F5CE8E922D379C), UINT64_C(0xD6FE2FC403475A57),\n\t\tUINT64_C(0x97E20C1BB0F9EC0A), UINT64_C(0xA8E9ED51219381C1)\n\t}, {\n\t\tUINT64_C(0x0000000000000000), UINT64_C(0x1DEE8A5E222CA1DC),\n\t\tUINT64_C(0x3BDD14BC445943B8), UINT64_C(0x26339EE26675E264),\n\t\tUINT64_C(0x77BA297888B28770), UINT64_C(0x6A54A326AA9E26AC),\n\t\tUINT64_C(0x4C673DC4CCEBC4C8), UINT64_C(0x5189B79AEEC76514),\n\t\tUINT64_C(0xEF7452F111650EE0), UINT64_C(0xF29AD8AF3349AF3C),\n\t\tUINT64_C(0xD4A9464D553C4D58), UINT64_C(0xC947CC137710EC84),\n\t\tUINT64_C(0x98CE7B8999D78990), UINT64_C(0x8520F1D7BBFB284C),\n\t\tUINT64_C(0xA3136F35DD8ECA28), UINT64_C(0xBEFDE56BFFA26BF4),\n\t\tUINT64_C(0x4C300AC98DC40345), UINT64_C(0x51DE8097AFE8A299),\n\t\tUINT64_C(0x77ED1E75C99D40FD), UINT64_C(0x6A03942BEBB1E121),\n\t\tUINT64_C(0x3B8A23B105768435), UINT64_C(0x2664A9EF275A25E9),\n\t\tUINT64_C(0x0057370D412FC78D), UINT64_C(0x1DB9BD5363036651),\n\t\tUINT64_C(0xA34458389CA10DA5), UINT64_C(0xBEAAD266BE8DAC79),\n\t\tUINT64_C(0x98994C84D8F84E1D), UINT64_C(0x8577C6DAFAD4EFC1),\n\t\tUINT64_C(0xD4FE714014138AD5), UINT64_C(0xC910FB1E363F2B09),\n\t\tUINT64_C(0xEF2365FC504AC96D), UINT64_C(0xF2CDEFA2726668B1),\n\t\tUINT64_C(0x986015931B88068A), UINT64_C(0x858E9FCD39A4A756),\n\t\tUINT64_C(0xA3BD012F5FD14532), UINT64_C(0xBE538B717DFDE4EE),\n\t\tUINT64_C(0xEFDA3CEB933A81FA), UINT64_C(0xF234B6B5B1162026),\n\t\tUINT64_C(0xD4072857D763C242), UINT64_C(0xC9E9A209F54F639E),\n\t\tUINT64_C(0x771447620AED086A), UINT64_C(0x6AFACD3C28C1A9B6),\n\t\tUINT64_C(0x4CC953DE4EB44BD2), UINT64_C(0x5127D9806C98EA0E),\n\t\tUINT64_C(0x00AE6E1A825F8F1A), UINT64_C(0x1D40E444A0732EC6),\n\t\tUINT64_C(0x3B737AA6C606CCA2), UINT64_C(0x269DF0F8E42A6D7E),\n\t\tUINT64_C(0xD4501F5A964C05CF), UINT64_C(0xC9BE9504B460A413),\n\t\tUINT64_C(0xEF8D0BE6D2154677), UINT64_C(0xF26381B8F039E7AB),\n\t\tUINT64_C(0xA3EA36221EFE82BF), UINT64_C(0xBE04BC7C3CD22363),\n\t\tUINT64_C(0x9837229E5AA7C107), UINT64_C(0x85D9A8C0788B60DB),\n\t\tUINT64_C(0x3B244DAB87290B2F), UINT64_C(0x26CAC7F5A505AAF3),\n\t\tUINT64_C(0x00F95917C3704897), UINT64_C(0x1D17D349E15CE94B),\n\t\tUINT64_C(0x4C9E64D30F9B8C5F), UINT64_C(0x5170EE8D2DB72D83),\n\t\tUINT64_C(0x7743706F4BC2CFE7), UINT64_C(0x6AADFA3169EE6E3B),\n\t\tUINT64_C(0xA218840D981E1391), UINT64_C(0xBFF60E53BA32B24D),\n\t\tUINT64_C(0x99C590B1DC475029), UINT64_C(0x842B1AEFFE6BF1F5),\n\t\tUINT64_C(0xD5A2AD7510AC94E1), UINT64_C(0xC84C272B3280353D),\n\t\tUINT64_C(0xEE7FB9C954F5D759), UINT64_C(0xF391339776D97685),\n\t\tUINT64_C(0x4D6CD6FC897B1D71), UINT64_C(0x50825CA2AB57BCAD),\n\t\tUINT64_C(0x76B1C240CD225EC9), UINT64_C(0x6B5F481EEF0EFF15),\n\t\tUINT64_C(0x3AD6FF8401C99A01), UINT64_C(0x273875DA23E53BDD),\n\t\tUINT64_C(0x010BEB384590D9B9), UINT64_C(0x1CE5616667BC7865),\n\t\tUINT64_C(0xEE288EC415DA10D4), UINT64_C(0xF3C6049A37F6B108),\n\t\tUINT64_C(0xD5F59A785183536C), UINT64_C(0xC81B102673AFF2B0),\n\t\tUINT64_C(0x9992A7BC9D6897A4), UINT64_C(0x847C2DE2BF443678),\n\t\tUINT64_C(0xA24FB300D931D41C), UINT64_C(0xBFA1395EFB1D75C0),\n\t\tUINT64_C(0x015CDC3504BF1E34), UINT64_C(0x1CB2566B2693BFE8),\n\t\tUINT64_C(0x3A81C88940E65D8C), UINT64_C(0x276F42D762CAFC50),\n\t\tUINT64_C(0x76E6F54D8C0D9944), UINT64_C(0x6B087F13AE213898),\n\t\tUINT64_C(0x4D3BE1F1C854DAFC), UINT64_C(0x50D56BAFEA787B20),\n\t\tUINT64_C(0x3A78919E8396151B), UINT64_C(0x27961BC0A1BAB4C7),\n\t\tUINT64_C(0x01A58522C7CF56A3), UINT64_C(0x1C4B0F7CE5E3F77F),\n\t\tUINT64_C(0x4DC2B8E60B24926B), UINT64_C(0x502C32B8290833B7),\n\t\tUINT64_C(0x761FAC5A4F7DD1D3), UINT64_C(0x6BF126046D51700F),\n\t\tUINT64_C(0xD50CC36F92F31BFB), UINT64_C(0xC8E24931B0DFBA27),\n\t\tUINT64_C(0xEED1D7D3D6AA5843), UINT64_C(0xF33F5D8DF486F99F),\n\t\tUINT64_C(0xA2B6EA171A419C8B), UINT64_C(0xBF586049386D3D57),\n\t\tUINT64_C(0x996BFEAB5E18DF33), UINT64_C(0x848574F57C347EEF),\n\t\tUINT64_C(0x76489B570E52165E), UINT64_C(0x6BA611092C7EB782),\n\t\tUINT64_C(0x4D958FEB4A0B55E6), UINT64_C(0x507B05B56827F43A),\n\t\tUINT64_C(0x01F2B22F86E0912E), UINT64_C(0x1C1C3871A4CC30F2),\n\t\tUINT64_C(0x3A2FA693C2B9D296), UINT64_C(0x27C12CCDE095734A),\n\t\tUINT64_C(0x993CC9A61F3718BE), UINT64_C(0x84D243F83D1BB962),\n\t\tUINT64_C(0xA2E1DD1A5B6E5B06), UINT64_C(0xBF0F57447942FADA),\n\t\tUINT64_C(0xEE86E0DE97859FCE), UINT64_C(0xF3686A80B5A93E12),\n\t\tUINT64_C(0xD55BF462D3DCDC76), UINT64_C(0xC8B57E3CF1F07DAA),\n\t\tUINT64_C(0xD6E9A7309F3239A7), UINT64_C(0xCB072D6EBD1E987B),\n\t\tUINT64_C(0xED34B38CDB6B7A1F), UINT64_C(0xF0DA39D2F947DBC3),\n\t\tUINT64_C(0xA1538E481780BED7), UINT64_C(0xBCBD041635AC1F0B),\n\t\tUINT64_C(0x9A8E9AF453D9FD6F), UINT64_C(0x876010AA71F55CB3),\n\t\tUINT64_C(0x399DF5C18E573747), UINT64_C(0x24737F9FAC7B969B),\n\t\tUINT64_C(0x0240E17DCA0E74FF), UINT64_C(0x1FAE6B23E822D523),\n\t\tUINT64_C(0x4E27DCB906E5B037), UINT64_C(0x53C956E724C911EB),\n\t\tUINT64_C(0x75FAC80542BCF38F), UINT64_C(0x6814425B60905253),\n\t\tUINT64_C(0x9AD9ADF912F63AE2), UINT64_C(0x873727A730DA9B3E),\n\t\tUINT64_C(0xA104B94556AF795A), UINT64_C(0xBCEA331B7483D886),\n\t\tUINT64_C(0xED6384819A44BD92), UINT64_C(0xF08D0EDFB8681C4E),\n\t\tUINT64_C(0xD6BE903DDE1DFE2A), UINT64_C(0xCB501A63FC315FF6),\n\t\tUINT64_C(0x75ADFF0803933402), UINT64_C(0x6843755621BF95DE),\n\t\tUINT64_C(0x4E70EBB447CA77BA), UINT64_C(0x539E61EA65E6D666),\n\t\tUINT64_C(0x0217D6708B21B372), UINT64_C(0x1FF95C2EA90D12AE),\n\t\tUINT64_C(0x39CAC2CCCF78F0CA), UINT64_C(0x24244892ED545116),\n\t\tUINT64_C(0x4E89B2A384BA3F2D), UINT64_C(0x536738FDA6969EF1),\n\t\tUINT64_C(0x7554A61FC0E37C95), UINT64_C(0x68BA2C41E2CFDD49),\n\t\tUINT64_C(0x39339BDB0C08B85D), UINT64_C(0x24DD11852E241981),\n\t\tUINT64_C(0x02EE8F674851FBE5), UINT64_C(0x1F0005396A7D5A39),\n\t\tUINT64_C(0xA1FDE05295DF31CD), UINT64_C(0xBC136A0CB7F39011),\n\t\tUINT64_C(0x9A20F4EED1867275), UINT64_C(0x87CE7EB0F3AAD3A9),\n\t\tUINT64_C(0xD647C92A1D6DB6BD), UINT64_C(0xCBA943743F411761),\n\t\tUINT64_C(0xED9ADD965934F505), UINT64_C(0xF07457C87B1854D9),\n\t\tUINT64_C(0x02B9B86A097E3C68), UINT64_C(0x1F5732342B529DB4),\n\t\tUINT64_C(0x3964ACD64D277FD0), UINT64_C(0x248A26886F0BDE0C),\n\t\tUINT64_C(0x7503911281CCBB18), UINT64_C(0x68ED1B4CA3E01AC4),\n\t\tUINT64_C(0x4EDE85AEC595F8A0), UINT64_C(0x53300FF0E7B9597C),\n\t\tUINT64_C(0xEDCDEA9B181B3288), UINT64_C(0xF02360C53A379354),\n\t\tUINT64_C(0xD610FE275C427130), UINT64_C(0xCBFE74797E6ED0EC),\n\t\tUINT64_C(0x9A77C3E390A9B5F8), UINT64_C(0x879949BDB2851424),\n\t\tUINT64_C(0xA1AAD75FD4F0F640), UINT64_C(0xBC445D01F6DC579C),\n\t\tUINT64_C(0x74F1233D072C2A36), UINT64_C(0x691FA96325008BEA),\n\t\tUINT64_C(0x4F2C37814375698E), UINT64_C(0x52C2BDDF6159C852),\n\t\tUINT64_C(0x034B0A458F9EAD46), UINT64_C(0x1EA5801BADB20C9A),\n\t\tUINT64_C(0x38961EF9CBC7EEFE), UINT64_C(0x257894A7E9EB4F22),\n\t\tUINT64_C(0x9B8571CC164924D6), UINT64_C(0x866BFB923465850A),\n\t\tUINT64_C(0xA05865705210676E), UINT64_C(0xBDB6EF2E703CC6B2),\n\t\tUINT64_C(0xEC3F58B49EFBA3A6), UINT64_C(0xF1D1D2EABCD7027A),\n\t\tUINT64_C(0xD7E24C08DAA2E01E), UINT64_C(0xCA0CC656F88E41C2),\n\t\tUINT64_C(0x38C129F48AE82973), UINT64_C(0x252FA3AAA8C488AF),\n\t\tUINT64_C(0x031C3D48CEB16ACB), UINT64_C(0x1EF2B716EC9DCB17),\n\t\tUINT64_C(0x4F7B008C025AAE03), UINT64_C(0x52958AD220760FDF),\n\t\tUINT64_C(0x74A614304603EDBB), UINT64_C(0x69489E6E642F4C67),\n\t\tUINT64_C(0xD7B57B059B8D2793), UINT64_C(0xCA5BF15BB9A1864F),\n\t\tUINT64_C(0xEC686FB9DFD4642B), UINT64_C(0xF186E5E7FDF8C5F7),\n\t\tUINT64_C(0xA00F527D133FA0E3), UINT64_C(0xBDE1D8233113013F),\n\t\tUINT64_C(0x9BD246C15766E35B), UINT64_C(0x863CCC9F754A4287),\n\t\tUINT64_C(0xEC9136AE1CA42CBC), UINT64_C(0xF17FBCF03E888D60),\n\t\tUINT64_C(0xD74C221258FD6F04), UINT64_C(0xCAA2A84C7AD1CED8),\n\t\tUINT64_C(0x9B2B1FD69416ABCC), UINT64_C(0x86C59588B63A0A10),\n\t\tUINT64_C(0xA0F60B6AD04FE874), UINT64_C(0xBD188134F26349A8),\n\t\tUINT64_C(0x03E5645F0DC1225C), UINT64_C(0x1E0BEE012FED8380),\n\t\tUINT64_C(0x383870E3499861E4), UINT64_C(0x25D6FABD6BB4C038),\n\t\tUINT64_C(0x745F4D278573A52C), UINT64_C(0x69B1C779A75F04F0),\n\t\tUINT64_C(0x4F82599BC12AE694), UINT64_C(0x526CD3C5E3064748),\n\t\tUINT64_C(0xA0A13C6791602FF9), UINT64_C(0xBD4FB639B34C8E25),\n\t\tUINT64_C(0x9B7C28DBD5396C41), UINT64_C(0x8692A285F715CD9D),\n\t\tUINT64_C(0xD71B151F19D2A889), UINT64_C(0xCAF59F413BFE0955),\n\t\tUINT64_C(0xECC601A35D8BEB31), UINT64_C(0xF1288BFD7FA74AED),\n\t\tUINT64_C(0x4FD56E9680052119), UINT64_C(0x523BE4C8A22980C5),\n\t\tUINT64_C(0x74087A2AC45C62A1), UINT64_C(0x69E6F074E670C37D),\n\t\tUINT64_C(0x386F47EE08B7A669), UINT64_C(0x2581CDB02A9B07B5),\n\t\tUINT64_C(0x03B253524CEEE5D1), UINT64_C(0x1E5CD90C6EC2440D)\n\t}\n};\n"
  },
  {
    "path": "external/xz/liblzma/check/crc64_tablegen.c",
    "content": "///////////////////////////////////////////////////////////////////////////////\n//\n/// \\file       crc64_tablegen.c\n/// \\brief      Generate crc64_table_le.h and crc64_table_be.h\n///\n/// Compiling: gcc -std=c99 -o crc64_tablegen crc64_tablegen.c\n/// Add -DWORDS_BIGENDIAN to generate big endian table.\n//\n//  Author:     Lasse Collin\n//\n//  This file has been put into the public domain.\n//  You can do whatever you want with this file.\n//\n///////////////////////////////////////////////////////////////////////////////\n\n#include <stdio.h>\n#include \"../../common/tuklib_integer.h\"\n\n\nstatic uint64_t crc64_table[4][256];\n\n\nextern void\ninit_crc64_table(void)\n{\n\tstatic const uint64_t poly64 = UINT64_C(0xC96C5795D7870F42);\n\n\tfor (size_t s = 0; s < 4; ++s) {\n\t\tfor (size_t b = 0; b < 256; ++b) {\n\t\t\tuint64_t r = s == 0 ? b : crc64_table[s - 1][b];\n\n\t\t\tfor (size_t i = 0; i < 8; ++i) {\n\t\t\t\tif (r & 1)\n\t\t\t\t\tr = (r >> 1) ^ poly64;\n\t\t\t\telse\n\t\t\t\t\tr >>= 1;\n\t\t\t}\n\n\t\t\tcrc64_table[s][b] = r;\n\t\t}\n\t}\n\n#ifdef WORDS_BIGENDIAN\n\tfor (size_t s = 0; s < 4; ++s)\n\t\tfor (size_t b = 0; b < 256; ++b)\n\t\t\tcrc64_table[s][b] = bswap64(crc64_table[s][b]);\n#endif\n\n\treturn;\n}\n\n\nstatic void\nprint_crc64_table(void)\n{\n\tprintf(\"/* This file has been automatically generated by \"\n\t\t\t\"crc64_tablegen.c. */\\n\\n\"\n\t\t\t\"const uint64_t lzma_crc64_table[4][256] = {\\n\\t{\");\n\n\tfor (size_t s = 0; s < 4; ++s) {\n\t\tfor (size_t b = 0; b < 256; ++b) {\n\t\t\tif ((b % 2) == 0)\n\t\t\t\tprintf(\"\\n\\t\\t\");\n\n\t\t\tprintf(\"UINT64_C(0x%016\" PRIX64 \")\",\n\t\t\t\t\tcrc64_table[s][b]);\n\n\t\t\tif (b != 255)\n\t\t\t\tprintf(\",%s\", (b+1) % 2 == 0 ? \"\" : \" \");\n\t\t}\n\n\t\tif (s == 3)\n\t\t\tprintf(\"\\n\\t}\\n};\\n\");\n\t\telse\n\t\t\tprintf(\"\\n\\t}, {\");\n\t}\n\n\treturn;\n}\n\n\nint\nmain(void)\n{\n\tinit_crc64_table();\n\tprint_crc64_table();\n\treturn 0;\n}\n"
  },
  {
    "path": "external/xz/liblzma/check/crc64_x86.S",
    "content": "/*\n * Speed-optimized CRC64 using slicing-by-four algorithm\n *\n * This uses only i386 instructions, but it is optimized for i686 and later\n * (including e.g. Pentium II/III/IV, Athlon XP, and Core 2).\n *\n * Authors: Igor Pavlov (original CRC32 assembly code)\n *          Lasse Collin (CRC64 adaptation of the modified CRC32 code)\n *\n * This file has been put into the public domain.\n * You can do whatever you want with this file.\n *\n * This code needs lzma_crc64_table, which can be created using the\n * following C code:\n\nuint64_t lzma_crc64_table[4][256];\n\nvoid\ninit_table(void)\n{\n\t// ECMA-182\n\tstatic const uint64_t poly64 = UINT64_C(0xC96C5795D7870F42);\n\n\tfor (size_t s = 0; s < 4; ++s) {\n\t\tfor (size_t b = 0; b < 256; ++b) {\n\t\t\tuint64_t r = s == 0 ? b : lzma_crc64_table[s - 1][b];\n\n\t\t\tfor (size_t i = 0; i < 8; ++i) {\n\t\t\t\tif (r & 1)\n\t\t\t\t\tr = (r >> 1) ^ poly64;\n\t\t\t\telse\n\t\t\t\t\tr >>= 1;\n\t\t\t}\n\n\t\t\tlzma_crc64_table[s][b] = r;\n\t\t}\n\t}\n}\n\n * The prototype of the CRC64 function:\n * extern uint64_t lzma_crc64(const uint8_t *buf, size_t size, uint64_t crc);\n */\n\n/*\n * On some systems, the functions need to be prefixed. The prefix is\n * usually an underscore.\n */\n#ifndef __USER_LABEL_PREFIX__\n#\tdefine __USER_LABEL_PREFIX__\n#endif\n#define MAKE_SYM_CAT(prefix, sym) prefix ## sym\n#define MAKE_SYM(prefix, sym) MAKE_SYM_CAT(prefix, sym)\n#define LZMA_CRC64 MAKE_SYM(__USER_LABEL_PREFIX__, lzma_crc64)\n#define LZMA_CRC64_TABLE MAKE_SYM(__USER_LABEL_PREFIX__, lzma_crc64_table)\n\n/*\n * Solaris assembler doesn't have .p2align, and Darwin uses .align\n * differently than GNU/Linux and Solaris.\n */\n#if defined(__APPLE__) || defined(__MSDOS__)\n#\tdefine ALIGN(pow2, abs) .align pow2\n#else\n#\tdefine ALIGN(pow2, abs) .align abs\n#endif\n\n\t.text\n\t.globl\tLZMA_CRC64\n\n#if !defined(__APPLE__) && !defined(_WIN32) && !defined(__CYGWIN__) \\\n\t\t&& !defined(__MSDOS__)\n\t.type\tLZMA_CRC64, @function\n#endif\n\n\tALIGN(4, 16)\nLZMA_CRC64:\n\t/*\n\t * Register usage:\n\t * %eax crc LSB\n\t * %edx crc MSB\n\t * %esi buf\n\t * %edi size or buf + size\n\t * %ebx lzma_crc64_table\n\t * %ebp Table index\n\t * %ecx Temporary\n\t */\n\tpushl\t%ebx\n\tpushl\t%esi\n\tpushl\t%edi\n\tpushl\t%ebp\n\tmovl\t0x14(%esp), %esi /* buf */\n\tmovl\t0x18(%esp), %edi /* size */\n\tmovl\t0x1C(%esp), %eax /* crc LSB */\n\tmovl\t0x20(%esp), %edx /* crc MSB */\n\n\t/*\n\t * Store the address of lzma_crc64_table to %ebx. This is needed to\n\t * get position-independent code (PIC).\n\t *\n\t * The PIC macro is defined by libtool, while __PIC__ is defined\n\t * by GCC but only on some systems. Testing for both makes it simpler\n\t * to test this code without libtool, and keeps the code working also\n\t * when built with libtool but using something else than GCC.\n\t *\n\t * I understood that libtool may define PIC on Windows even though\n\t * the code in Windows DLLs is not PIC in sense that it is in ELF\n\t * binaries, so we need a separate check to always use the non-PIC\n\t * code on Windows.\n\t */\n#if (!defined(PIC) && !defined(__PIC__)) \\\n\t\t|| (defined(_WIN32) || defined(__CYGWIN__))\n\t/* Not PIC */\n\tmovl\t$ LZMA_CRC64_TABLE, %ebx\n#elif defined(__APPLE__)\n\t/* Mach-O */\n\tcall\t.L_get_pc\n.L_pic:\n\tleal\t.L_lzma_crc64_table$non_lazy_ptr-.L_pic(%ebx), %ebx\n\tmovl\t(%ebx), %ebx\n#else\n\t/* ELF */\n\tcall\t.L_get_pc\n\taddl\t$_GLOBAL_OFFSET_TABLE_, %ebx\n\tmovl\tLZMA_CRC64_TABLE@GOT(%ebx), %ebx\n#endif\n\n\t/* Complement the initial value. */\n\tnotl\t%eax\n\tnotl\t%edx\n\n.L_align:\n\t/*\n\t * Check if there is enough input to use slicing-by-four.\n\t * We need eight bytes, because the loop pre-reads four bytes.\n\t */\n\tcmpl\t$8, %edi\n\tjb\t.L_rest\n\n\t/* Check if we have reached alignment of four bytes. */\n\ttestl\t$3, %esi\n\tjz\t.L_slice\n\n\t/* Calculate CRC of the next input byte. */\n\tmovzbl\t(%esi), %ebp\n\tincl\t%esi\n\tmovzbl\t%al, %ecx\n\txorl\t%ecx, %ebp\n\tshrdl\t$8, %edx, %eax\n\txorl\t(%ebx, %ebp, 8), %eax\n\tshrl\t$8, %edx\n\txorl\t4(%ebx, %ebp, 8), %edx\n\tdecl\t%edi\n\tjmp\t.L_align\n\n.L_slice:\n\t/*\n\t * If we get here, there's at least eight bytes of aligned input\n\t * available. Make %edi multiple of four bytes. Store the possible\n\t * remainder over the \"size\" variable in the argument stack.\n\t */\n\tmovl\t%edi, 0x18(%esp)\n\tandl\t$-4, %edi\n\tsubl\t%edi, 0x18(%esp)\n\n\t/*\n\t * Let %edi be buf + size - 4 while running the main loop. This way\n\t * we can compare for equality to determine when exit the loop.\n\t */\n\taddl\t%esi, %edi\n\tsubl\t$4, %edi\n\n\t/* Read in the first four aligned bytes. */\n\tmovl\t(%esi), %ecx\n\n.L_loop:\n\txorl\t%eax, %ecx\n\tmovzbl\t%cl, %ebp\n\tmovl\t0x1800(%ebx, %ebp, 8), %eax\n\txorl\t%edx, %eax\n\tmovl\t0x1804(%ebx, %ebp, 8), %edx\n\tmovzbl\t%ch, %ebp\n\txorl\t0x1000(%ebx, %ebp, 8), %eax\n\txorl\t0x1004(%ebx, %ebp, 8), %edx\n\tshrl\t$16, %ecx\n\tmovzbl\t%cl, %ebp\n\txorl\t0x0800(%ebx, %ebp, 8), %eax\n\txorl\t0x0804(%ebx, %ebp, 8), %edx\n\tmovzbl\t%ch, %ebp\n\taddl\t$4, %esi\n\txorl\t(%ebx, %ebp, 8), %eax\n\txorl\t4(%ebx, %ebp, 8), %edx\n\n\t/* Check for end of aligned input. */\n\tcmpl\t%edi, %esi\n\n\t/*\n\t * Copy the next input byte to %ecx. It is slightly faster to\n\t * read it here than at the top of the loop.\n\t */\n\tmovl\t(%esi), %ecx\n\tjb\t.L_loop\n\n\t/*\n\t * Process the remaining four bytes, which we have already\n\t * copied to %ecx.\n\t */\n\txorl\t%eax, %ecx\n\tmovzbl\t%cl, %ebp\n\tmovl\t0x1800(%ebx, %ebp, 8), %eax\n\txorl\t%edx, %eax\n\tmovl\t0x1804(%ebx, %ebp, 8), %edx\n\tmovzbl\t%ch, %ebp\n\txorl\t0x1000(%ebx, %ebp, 8), %eax\n\txorl\t0x1004(%ebx, %ebp, 8), %edx\n\tshrl\t$16, %ecx\n\tmovzbl\t%cl, %ebp\n\txorl\t0x0800(%ebx, %ebp, 8), %eax\n\txorl\t0x0804(%ebx, %ebp, 8), %edx\n\tmovzbl\t%ch, %ebp\n\taddl\t$4, %esi\n\txorl\t(%ebx, %ebp, 8), %eax\n\txorl\t4(%ebx, %ebp, 8), %edx\n\n\t/* Copy the number of remaining bytes to %edi. */\n\tmovl\t0x18(%esp), %edi\n\n.L_rest:\n\t/* Check for end of input. */\n\ttestl\t%edi, %edi\n\tjz\t.L_return\n\n\t/* Calculate CRC of the next input byte. */\n\tmovzbl\t(%esi), %ebp\n\tincl\t%esi\n\tmovzbl\t%al, %ecx\n\txorl\t%ecx, %ebp\n\tshrdl\t$8, %edx, %eax\n\txorl\t(%ebx, %ebp, 8), %eax\n\tshrl\t$8, %edx\n\txorl\t4(%ebx, %ebp, 8), %edx\n\tdecl\t%edi\n\tjmp\t.L_rest\n\n.L_return:\n\t/* Complement the final value. */\n\tnotl\t%eax\n\tnotl\t%edx\n\n\tpopl\t%ebp\n\tpopl\t%edi\n\tpopl\t%esi\n\tpopl\t%ebx\n\tret\n\n#if defined(PIC) || defined(__PIC__)\n\tALIGN(4, 16)\n.L_get_pc:\n\tmovl\t(%esp), %ebx\n\tret\n#endif\n\n#if defined(__APPLE__) && (defined(PIC) || defined(__PIC__))\n\t/* Mach-O PIC */\n\t.section __IMPORT,__pointers,non_lazy_symbol_pointers\n.L_lzma_crc64_table$non_lazy_ptr:\n\t.indirect_symbol LZMA_CRC64_TABLE\n\t.long 0\n\n#elif defined(_WIN32) || defined(__CYGWIN__)\n#\tifdef DLL_EXPORT\n\t/* This is equivalent of __declspec(dllexport). */\n\t.section .drectve\n\t.ascii \" -export:lzma_crc64\"\n#\tendif\n\n#elif !defined(__MSDOS__)\n\t/* ELF */\n\t.size\tLZMA_CRC64, .-LZMA_CRC64\n#endif\n\n/*\n * This is needed to support non-executable stack. It's ugly to\n * use __linux__ here, but I don't know a way to detect when\n * we are using GNU assembler.\n */\n#if defined(__ELF__) && defined(__linux__)\n\t.section\t.note.GNU-stack,\"\",@progbits\n#endif\n"
  },
  {
    "path": "external/xz/liblzma/check/crc_macros.h",
    "content": "///////////////////////////////////////////////////////////////////////////////\n//\n/// \\file       crc_macros.h\n/// \\brief      Some endian-dependent macros for CRC32 and CRC64\n//\n//  Author:     Lasse Collin\n//\n//  This file has been put into the public domain.\n//  You can do whatever you want with this file.\n//\n///////////////////////////////////////////////////////////////////////////////\n\n#ifdef WORDS_BIGENDIAN\n#\tdefine A(x) ((x) >> 24)\n#\tdefine B(x) (((x) >> 16) & 0xFF)\n#\tdefine C(x) (((x) >> 8) & 0xFF)\n#\tdefine D(x) ((x) & 0xFF)\n\n#\tdefine S8(x) ((x) << 8)\n#\tdefine S32(x) ((x) << 32)\n\n#else\n#\tdefine A(x) ((x) & 0xFF)\n#\tdefine B(x) (((x) >> 8) & 0xFF)\n#\tdefine C(x) (((x) >> 16) & 0xFF)\n#\tdefine D(x) ((x) >> 24)\n\n#\tdefine S8(x) ((x) >> 8)\n#\tdefine S32(x) ((x) >> 32)\n#endif\n"
  },
  {
    "path": "external/xz/liblzma/check/sha256.c",
    "content": "///////////////////////////////////////////////////////////////////////////////\n//\n/// \\file       sha256.c\n/// \\brief      SHA-256\n///\n/// \\todo       Crypto++ has x86 ASM optimizations. They use SSE so if they\n///             are imported to liblzma, SSE instructions need to be used\n///             conditionally to keep the code working on older boxes.\n//\n//  This code is based on the code found from 7-Zip, which has a modified\n//  version of the SHA-256 found from Crypto++ <http://www.cryptopp.com/>.\n//  The code was modified a little to fit into liblzma.\n//\n//  Authors:    Kevin Springle\n//              Wei Dai\n//              Igor Pavlov\n//              Lasse Collin\n//\n//  This file has been put into the public domain.\n//  You can do whatever you want with this file.\n//\n///////////////////////////////////////////////////////////////////////////////\n\n#include \"check.h\"\n\n// Rotate a uint32_t. GCC can optimize this to a rotate instruction\n// at least on x86.\nstatic inline uint32_t\nrotr_32(uint32_t num, unsigned amount)\n{\n        return (num >> amount) | (num << (32 - amount));\n}\n\n#define blk0(i) (W[i] = conv32be(data[i]))\n#define blk2(i) (W[i & 15] += s1(W[(i - 2) & 15]) + W[(i - 7) & 15] \\\n\t\t+ s0(W[(i - 15) & 15]))\n\n#define Ch(x, y, z) (z ^ (x & (y ^ z)))\n#define Maj(x, y, z) ((x & (y ^ z)) + (y & z))\n\n#define a(i) T[(0 - i) & 7]\n#define b(i) T[(1 - i) & 7]\n#define c(i) T[(2 - i) & 7]\n#define d(i) T[(3 - i) & 7]\n#define e(i) T[(4 - i) & 7]\n#define f(i) T[(5 - i) & 7]\n#define g(i) T[(6 - i) & 7]\n#define h(i) T[(7 - i) & 7]\n\n#define R(i, j, blk) \\\n\th(i) += S1(e(i)) + Ch(e(i), f(i), g(i)) + SHA256_K[i + j] + blk; \\\n\td(i) += h(i); \\\n\th(i) += S0(a(i)) + Maj(a(i), b(i), c(i))\n#define R0(i) R(i, 0, blk0(i))\n#define R2(i) R(i, j, blk2(i))\n\n#define S0(x) rotr_32(x ^ rotr_32(x ^ rotr_32(x, 9), 11), 2)\n#define S1(x) rotr_32(x ^ rotr_32(x ^ rotr_32(x, 14), 5), 6)\n#define s0(x) (rotr_32(x ^ rotr_32(x, 11), 7) ^ (x >> 3))\n#define s1(x) (rotr_32(x ^ rotr_32(x, 2), 17) ^ (x >> 10))\n\n\nstatic const uint32_t SHA256_K[64] = {\n\t0x428A2F98, 0x71374491, 0xB5C0FBCF, 0xE9B5DBA5,\n\t0x3956C25B, 0x59F111F1, 0x923F82A4, 0xAB1C5ED5,\n\t0xD807AA98, 0x12835B01, 0x243185BE, 0x550C7DC3,\n\t0x72BE5D74, 0x80DEB1FE, 0x9BDC06A7, 0xC19BF174,\n\t0xE49B69C1, 0xEFBE4786, 0x0FC19DC6, 0x240CA1CC,\n\t0x2DE92C6F, 0x4A7484AA, 0x5CB0A9DC, 0x76F988DA,\n\t0x983E5152, 0xA831C66D, 0xB00327C8, 0xBF597FC7,\n\t0xC6E00BF3, 0xD5A79147, 0x06CA6351, 0x14292967,\n\t0x27B70A85, 0x2E1B2138, 0x4D2C6DFC, 0x53380D13,\n\t0x650A7354, 0x766A0ABB, 0x81C2C92E, 0x92722C85,\n\t0xA2BFE8A1, 0xA81A664B, 0xC24B8B70, 0xC76C51A3,\n\t0xD192E819, 0xD6990624, 0xF40E3585, 0x106AA070,\n\t0x19A4C116, 0x1E376C08, 0x2748774C, 0x34B0BCB5,\n\t0x391C0CB3, 0x4ED8AA4A, 0x5B9CCA4F, 0x682E6FF3,\n\t0x748F82EE, 0x78A5636F, 0x84C87814, 0x8CC70208,\n\t0x90BEFFFA, 0xA4506CEB, 0xBEF9A3F7, 0xC67178F2,\n};\n\n\nstatic void\ntransform(uint32_t state[8], const uint32_t data[16])\n{\n\tuint32_t W[16];\n\tuint32_t T[8];\n\n\t// Copy state[] to working vars.\n\tmemcpy(T, state, sizeof(T));\n\n\t// The first 16 operations unrolled\n\tR0( 0); R0( 1); R0( 2); R0( 3);\n\tR0( 4); R0( 5); R0( 6); R0( 7);\n\tR0( 8); R0( 9); R0(10); R0(11);\n\tR0(12); R0(13); R0(14); R0(15);\n\n\t// The remaining 48 operations partially unrolled\n\tfor (unsigned int j = 16; j < 64; j += 16) {\n\t\tR2( 0); R2( 1); R2( 2); R2( 3);\n\t\tR2( 4); R2( 5); R2( 6); R2( 7);\n\t\tR2( 8); R2( 9); R2(10); R2(11);\n\t\tR2(12); R2(13); R2(14); R2(15);\n\t}\n\n\t// Add the working vars back into state[].\n\tstate[0] += a(0);\n\tstate[1] += b(0);\n\tstate[2] += c(0);\n\tstate[3] += d(0);\n\tstate[4] += e(0);\n\tstate[5] += f(0);\n\tstate[6] += g(0);\n\tstate[7] += h(0);\n}\n\n\nstatic void\nprocess(lzma_check_state *check)\n{\n\ttransform(check->state.sha256.state, check->buffer.u32);\n\treturn;\n}\n\n\nextern void\nlzma_sha256_init(lzma_check_state *check)\n{\n\tstatic const uint32_t s[8] = {\n\t\t0x6A09E667, 0xBB67AE85, 0x3C6EF372, 0xA54FF53A,\n\t\t0x510E527F, 0x9B05688C, 0x1F83D9AB, 0x5BE0CD19,\n\t};\n\n\tmemcpy(check->state.sha256.state, s, sizeof(s));\n\tcheck->state.sha256.size = 0;\n\n\treturn;\n}\n\n\nextern void\nlzma_sha256_update(const uint8_t *buf, size_t size, lzma_check_state *check)\n{\n\t// Copy the input data into a properly aligned temporary buffer.\n\t// This way we can be called with arbitrarily sized buffers\n\t// (no need to be multiple of 64 bytes), and the code works also\n\t// on architectures that don't allow unaligned memory access.\n\twhile (size > 0) {\n\t\tconst size_t copy_start = check->state.sha256.size & 0x3F;\n\t\tsize_t copy_size = 64 - copy_start;\n\t\tif (copy_size > size)\n\t\t\tcopy_size = size;\n\n\t\tmemcpy(check->buffer.u8 + copy_start, buf, copy_size);\n\n\t\tbuf += copy_size;\n\t\tsize -= copy_size;\n\t\tcheck->state.sha256.size += copy_size;\n\n\t\tif ((check->state.sha256.size & 0x3F) == 0)\n\t\t\tprocess(check);\n\t}\n\n\treturn;\n}\n\n\nextern void\nlzma_sha256_finish(lzma_check_state *check)\n{\n\t// Add padding as described in RFC 3174 (it describes SHA-1 but\n\t// the same padding style is used for SHA-256 too).\n\tsize_t pos = check->state.sha256.size & 0x3F;\n\tcheck->buffer.u8[pos++] = 0x80;\n\n\twhile (pos != 64 - 8) {\n\t\tif (pos == 64) {\n\t\t\tprocess(check);\n\t\t\tpos = 0;\n\t\t}\n\n\t\tcheck->buffer.u8[pos++] = 0x00;\n\t}\n\n\t// Convert the message size from bytes to bits.\n\tcheck->state.sha256.size *= 8;\n\n\tcheck->buffer.u64[(64 - 8) / 8] = conv64be(check->state.sha256.size);\n\n\tprocess(check);\n\n\tfor (size_t i = 0; i < 8; ++i)\n\t\tcheck->buffer.u32[i] = conv32be(check->state.sha256.state[i]);\n\n\treturn;\n}\n"
  },
  {
    "path": "external/xz/liblzma/common/Makefile.inc",
    "content": "##\n## Author: Lasse Collin\n##\n## This file has been put into the public domain.\n## You can do whatever you want with this file.\n##\n\nliblzma_la_SOURCES += \\\n\tcommon/common.c \\\n\tcommon/common.h \\\n\tcommon/memcmplen.h \\\n\tcommon/block_util.c \\\n\tcommon/easy_preset.c \\\n\tcommon/easy_preset.h \\\n\tcommon/filter_common.c \\\n\tcommon/filter_common.h \\\n\tcommon/hardware_physmem.c \\\n\tcommon/index.c \\\n\tcommon/index.h \\\n\tcommon/stream_flags_common.c \\\n\tcommon/stream_flags_common.h \\\n\tcommon/vli_size.c\n\nif COND_THREADS\nliblzma_la_SOURCES += common/hardware_cputhreads.c\nendif\n\nif COND_MAIN_ENCODER\nliblzma_la_SOURCES += \\\n\tcommon/alone_encoder.c \\\n\tcommon/block_buffer_encoder.c \\\n\tcommon/block_buffer_encoder.h \\\n\tcommon/block_encoder.c \\\n\tcommon/block_encoder.h \\\n\tcommon/block_header_encoder.c \\\n\tcommon/easy_buffer_encoder.c \\\n\tcommon/easy_encoder.c \\\n\tcommon/easy_encoder_memusage.c \\\n\tcommon/filter_buffer_encoder.c \\\n\tcommon/filter_encoder.c \\\n\tcommon/filter_encoder.h \\\n\tcommon/filter_flags_encoder.c \\\n\tcommon/index_encoder.c \\\n\tcommon/index_encoder.h \\\n\tcommon/stream_buffer_encoder.c \\\n\tcommon/stream_encoder.c \\\n\tcommon/stream_flags_encoder.c \\\n\tcommon/vli_encoder.c\n\nif COND_THREADS\nliblzma_la_SOURCES += \\\n\tcommon/outqueue.c \\\n\tcommon/outqueue.h \\\n\tcommon/stream_encoder_mt.c\nendif\nendif\n\nif COND_MAIN_DECODER\nliblzma_la_SOURCES += \\\n\tcommon/alone_decoder.c \\\n\tcommon/alone_decoder.h \\\n\tcommon/auto_decoder.c \\\n\tcommon/block_buffer_decoder.c \\\n\tcommon/block_decoder.c \\\n\tcommon/block_decoder.h \\\n\tcommon/block_header_decoder.c \\\n\tcommon/easy_decoder_memusage.c \\\n\tcommon/filter_buffer_decoder.c \\\n\tcommon/filter_decoder.c \\\n\tcommon/filter_decoder.h \\\n\tcommon/filter_flags_decoder.c \\\n\tcommon/index_decoder.c \\\n\tcommon/index_hash.c \\\n\tcommon/stream_buffer_decoder.c \\\n\tcommon/stream_decoder.c \\\n\tcommon/stream_decoder.h \\\n\tcommon/stream_flags_decoder.c \\\n\tcommon/vli_decoder.c\nendif\n"
  },
  {
    "path": "external/xz/liblzma/common/alone_decoder.c",
    "content": "///////////////////////////////////////////////////////////////////////////////\n//\n/// \\file       alone_decoder.c\n/// \\brief      Decoder for LZMA_Alone files\n//\n//  Author:     Lasse Collin\n//\n//  This file has been put into the public domain.\n//  You can do whatever you want with this file.\n//\n///////////////////////////////////////////////////////////////////////////////\n\n#include \"alone_decoder.h\"\n#include \"lzma_decoder.h\"\n#include \"lz_decoder.h\"\n\n\ntypedef struct {\n\tlzma_next_coder next;\n\n\tenum {\n\t\tSEQ_PROPERTIES,\n\t\tSEQ_DICTIONARY_SIZE,\n\t\tSEQ_UNCOMPRESSED_SIZE,\n\t\tSEQ_CODER_INIT,\n\t\tSEQ_CODE,\n\t} sequence;\n\n\t/// If true, reject files that are unlikely to be .lzma files.\n\t/// If false, more non-.lzma files get accepted and will give\n\t/// LZMA_DATA_ERROR either immediately or after a few output bytes.\n\tbool picky;\n\n\t/// Position in the header fields\n\tsize_t pos;\n\n\t/// Uncompressed size decoded from the header\n\tlzma_vli uncompressed_size;\n\n\t/// Memory usage limit\n\tuint64_t memlimit;\n\n\t/// Amount of memory actually needed (only an estimate)\n\tuint64_t memusage;\n\n\t/// Options decoded from the header needed to initialize\n\t/// the LZMA decoder\n\tlzma_options_lzma options;\n} lzma_alone_coder;\n\n\nstatic lzma_ret\nalone_decode(void *coder_ptr, const lzma_allocator *allocator,\n\t\tconst uint8_t *restrict in, size_t *restrict in_pos,\n\t\tsize_t in_size, uint8_t *restrict out,\n\t\tsize_t *restrict out_pos, size_t out_size,\n\t\tlzma_action action)\n{\n\tlzma_alone_coder *coder = coder_ptr;\n\n\twhile (*out_pos < out_size\n\t\t\t&& (coder->sequence == SEQ_CODE || *in_pos < in_size))\n\tswitch (coder->sequence) {\n\tcase SEQ_PROPERTIES:\n\t\tif (lzma_lzma_lclppb_decode(&coder->options, in[*in_pos]))\n\t\t\treturn LZMA_FORMAT_ERROR;\n\n\t\tcoder->sequence = SEQ_DICTIONARY_SIZE;\n\t\t++*in_pos;\n\t\tbreak;\n\n\tcase SEQ_DICTIONARY_SIZE:\n\t\tcoder->options.dict_size\n\t\t\t\t|= (size_t)(in[*in_pos]) << (coder->pos * 8);\n\n\t\tif (++coder->pos == 4) {\n\t\t\tif (coder->picky && coder->options.dict_size\n\t\t\t\t\t!= UINT32_MAX) {\n\t\t\t\t// A hack to ditch tons of false positives:\n\t\t\t\t// We allow only dictionary sizes that are\n\t\t\t\t// 2^n or 2^n + 2^(n-1). LZMA_Alone created\n\t\t\t\t// only files with 2^n, but accepts any\n\t\t\t\t// dictionary size.\n\t\t\t\tuint32_t d = coder->options.dict_size - 1;\n\t\t\t\td |= d >> 2;\n\t\t\t\td |= d >> 3;\n\t\t\t\td |= d >> 4;\n\t\t\t\td |= d >> 8;\n\t\t\t\td |= d >> 16;\n\t\t\t\t++d;\n\n\t\t\t\tif (d != coder->options.dict_size)\n\t\t\t\t\treturn LZMA_FORMAT_ERROR;\n\t\t\t}\n\n\t\t\tcoder->pos = 0;\n\t\t\tcoder->sequence = SEQ_UNCOMPRESSED_SIZE;\n\t\t}\n\n\t\t++*in_pos;\n\t\tbreak;\n\n\tcase SEQ_UNCOMPRESSED_SIZE:\n\t\tcoder->uncompressed_size\n\t\t\t\t|= (lzma_vli)(in[*in_pos]) << (coder->pos * 8);\n\t\t++*in_pos;\n\t\tif (++coder->pos < 8)\n\t\t\tbreak;\n\n\t\t// Another hack to ditch false positives: Assume that\n\t\t// if the uncompressed size is known, it must be less\n\t\t// than 256 GiB.\n\t\tif (coder->picky\n\t\t\t\t&& coder->uncompressed_size != LZMA_VLI_UNKNOWN\n\t\t\t\t&& coder->uncompressed_size\n\t\t\t\t\t>= (LZMA_VLI_C(1) << 38))\n\t\t\treturn LZMA_FORMAT_ERROR;\n\n\t\t// Calculate the memory usage so that it is ready\n\t\t// for SEQ_CODER_INIT.\n\t\tcoder->memusage = lzma_lzma_decoder_memusage(&coder->options)\n\t\t\t\t+ LZMA_MEMUSAGE_BASE;\n\n\t\tcoder->pos = 0;\n\t\tcoder->sequence = SEQ_CODER_INIT;\n\n\t// Fall through\n\n\tcase SEQ_CODER_INIT: {\n\t\tif (coder->memusage > coder->memlimit)\n\t\t\treturn LZMA_MEMLIMIT_ERROR;\n\n\t\tlzma_filter_info filters[2] = {\n\t\t\t{\n\t\t\t\t.init = &lzma_lzma_decoder_init,\n\t\t\t\t.options = &coder->options,\n\t\t\t}, {\n\t\t\t\t.init = NULL,\n\t\t\t}\n\t\t};\n\n\t\tconst lzma_ret ret = lzma_next_filter_init(&coder->next,\n\t\t\t\tallocator, filters);\n\t\tif (ret != LZMA_OK)\n\t\t\treturn ret;\n\n\t\t// Use a hack to set the uncompressed size.\n\t\tlzma_lz_decoder_uncompressed(coder->next.coder,\n\t\t\t\tcoder->uncompressed_size);\n\n\t\tcoder->sequence = SEQ_CODE;\n\t\tbreak;\n\t}\n\n\tcase SEQ_CODE: {\n\t\treturn coder->next.code(coder->next.coder,\n\t\t\t\tallocator, in, in_pos, in_size,\n\t\t\t\tout, out_pos, out_size, action);\n\t}\n\n\tdefault:\n\t\treturn LZMA_PROG_ERROR;\n\t}\n\n\treturn LZMA_OK;\n}\n\n\nstatic void\nalone_decoder_end(void *coder_ptr, const lzma_allocator *allocator)\n{\n\tlzma_alone_coder *coder = coder_ptr;\n\tlzma_next_end(&coder->next, allocator);\n\tlzma_free(coder, allocator);\n\treturn;\n}\n\n\nstatic lzma_ret\nalone_decoder_memconfig(void *coder_ptr, uint64_t *memusage,\n\t\tuint64_t *old_memlimit, uint64_t new_memlimit)\n{\n\tlzma_alone_coder *coder = coder_ptr;\n\n\t*memusage = coder->memusage;\n\t*old_memlimit = coder->memlimit;\n\n\tif (new_memlimit != 0) {\n\t\tif (new_memlimit < coder->memusage)\n\t\t\treturn LZMA_MEMLIMIT_ERROR;\n\n\t\tcoder->memlimit = new_memlimit;\n\t}\n\n\treturn LZMA_OK;\n}\n\n\nextern lzma_ret\nlzma_alone_decoder_init(lzma_next_coder *next, const lzma_allocator *allocator,\n\t\tuint64_t memlimit, bool picky)\n{\n\tlzma_next_coder_init(&lzma_alone_decoder_init, next, allocator);\n\n\tlzma_alone_coder *coder = next->coder;\n\n\tif (coder == NULL) {\n\t\tcoder = lzma_alloc(sizeof(lzma_alone_coder), allocator);\n\t\tif (coder == NULL)\n\t\t\treturn LZMA_MEM_ERROR;\n\n\t\tnext->coder = coder;\n\t\tnext->code = &alone_decode;\n\t\tnext->end = &alone_decoder_end;\n\t\tnext->memconfig = &alone_decoder_memconfig;\n\t\tcoder->next = LZMA_NEXT_CODER_INIT;\n\t}\n\n\tcoder->sequence = SEQ_PROPERTIES;\n\tcoder->picky = picky;\n\tcoder->pos = 0;\n\tcoder->options.dict_size = 0;\n\tcoder->options.preset_dict = NULL;\n\tcoder->options.preset_dict_size = 0;\n\tcoder->uncompressed_size = 0;\n\tcoder->memlimit = my_max(1, memlimit);\n\tcoder->memusage = LZMA_MEMUSAGE_BASE;\n\n\treturn LZMA_OK;\n}\n\n\nextern LZMA_API(lzma_ret)\nlzma_alone_decoder(lzma_stream *strm, uint64_t memlimit)\n{\n\tlzma_next_strm_init(lzma_alone_decoder_init, strm, memlimit, false);\n\n\tstrm->internal->supported_actions[LZMA_RUN] = true;\n\tstrm->internal->supported_actions[LZMA_FINISH] = true;\n\n\treturn LZMA_OK;\n}\n"
  },
  {
    "path": "external/xz/liblzma/common/alone_decoder.h",
    "content": "///////////////////////////////////////////////////////////////////////////////\n//\n/// \\file       alone_decoder.h\n/// \\brief      Decoder for LZMA_Alone files\n//\n//  Author:     Lasse Collin\n//\n//  This file has been put into the public domain.\n//  You can do whatever you want with this file.\n//\n///////////////////////////////////////////////////////////////////////////////\n\n#ifndef LZMA_ALONE_DECODER_H\n#define LZMA_ALONE_DECODER_H\n\n#include \"common.h\"\n\n\nextern lzma_ret lzma_alone_decoder_init(\n\t\tlzma_next_coder *next, const lzma_allocator *allocator,\n\t\tuint64_t memlimit, bool picky);\n\n#endif\n"
  },
  {
    "path": "external/xz/liblzma/common/alone_encoder.c",
    "content": "///////////////////////////////////////////////////////////////////////////////\n//\n/// \\file       alone_encoder.c\n/// \\brief      Encoder for LZMA_Alone files\n//\n//  Author:     Lasse Collin\n//\n//  This file has been put into the public domain.\n//  You can do whatever you want with this file.\n//\n///////////////////////////////////////////////////////////////////////////////\n\n#include \"common.h\"\n#include \"lzma_encoder.h\"\n\n\n#define ALONE_HEADER_SIZE (1 + 4 + 8)\n\n\ntypedef struct {\n\tlzma_next_coder next;\n\n\tenum {\n\t\tSEQ_HEADER,\n\t\tSEQ_CODE,\n\t} sequence;\n\n\tsize_t header_pos;\n\tuint8_t header[ALONE_HEADER_SIZE];\n} lzma_alone_coder;\n\n\nstatic lzma_ret\nalone_encode(void *coder_ptr, const lzma_allocator *allocator,\n\t\tconst uint8_t *restrict in, size_t *restrict in_pos,\n\t\tsize_t in_size, uint8_t *restrict out,\n\t\tsize_t *restrict out_pos, size_t out_size,\n\t\tlzma_action action)\n{\n\tlzma_alone_coder *coder = coder_ptr;\n\n\twhile (*out_pos < out_size)\n\tswitch (coder->sequence) {\n\tcase SEQ_HEADER:\n\t\tlzma_bufcpy(coder->header, &coder->header_pos,\n\t\t\t\tALONE_HEADER_SIZE,\n\t\t\t\tout, out_pos, out_size);\n\t\tif (coder->header_pos < ALONE_HEADER_SIZE)\n\t\t\treturn LZMA_OK;\n\n\t\tcoder->sequence = SEQ_CODE;\n\t\tbreak;\n\n\tcase SEQ_CODE:\n\t\treturn coder->next.code(coder->next.coder,\n\t\t\t\tallocator, in, in_pos, in_size,\n\t\t\t\tout, out_pos, out_size, action);\n\n\tdefault:\n\t\tassert(0);\n\t\treturn LZMA_PROG_ERROR;\n\t}\n\n\treturn LZMA_OK;\n}\n\n\nstatic void\nalone_encoder_end(void *coder_ptr, const lzma_allocator *allocator)\n{\n\tlzma_alone_coder *coder = coder_ptr;\n\tlzma_next_end(&coder->next, allocator);\n\tlzma_free(coder, allocator);\n\treturn;\n}\n\n\n// At least for now, this is not used by any internal function.\nstatic lzma_ret\nalone_encoder_init(lzma_next_coder *next, const lzma_allocator *allocator,\n\t\tconst lzma_options_lzma *options)\n{\n\tlzma_next_coder_init(&alone_encoder_init, next, allocator);\n\n\tlzma_alone_coder *coder = next->coder;\n\n\tif (coder == NULL) {\n\t\tcoder = lzma_alloc(sizeof(lzma_alone_coder), allocator);\n\t\tif (coder == NULL)\n\t\t\treturn LZMA_MEM_ERROR;\n\n\t\tnext->coder = coder;\n\t\tnext->code = &alone_encode;\n\t\tnext->end = &alone_encoder_end;\n\t\tcoder->next = LZMA_NEXT_CODER_INIT;\n\t}\n\n\t// Basic initializations\n\tcoder->sequence = SEQ_HEADER;\n\tcoder->header_pos = 0;\n\n\t// Encode the header:\n\t// - Properties (1 byte)\n\tif (lzma_lzma_lclppb_encode(options, coder->header))\n\t\treturn LZMA_OPTIONS_ERROR;\n\n\t// - Dictionary size (4 bytes)\n\tif (options->dict_size < LZMA_DICT_SIZE_MIN)\n\t\treturn LZMA_OPTIONS_ERROR;\n\n\t// Round up to the next 2^n or 2^n + 2^(n - 1) depending on which\n\t// one is the next unless it is UINT32_MAX. While the header would\n\t// allow any 32-bit integer, we do this to keep the decoder of liblzma\n\t// accepting the resulting files.\n\tuint32_t d = options->dict_size - 1;\n\td |= d >> 2;\n\td |= d >> 3;\n\td |= d >> 4;\n\td |= d >> 8;\n\td |= d >> 16;\n\tif (d != UINT32_MAX)\n\t\t++d;\n\n\twrite32le(coder->header + 1, d);\n\n\t// - Uncompressed size (always unknown and using EOPM)\n\tmemset(coder->header + 1 + 4, 0xFF, 8);\n\n\t// Initialize the LZMA encoder.\n\tconst lzma_filter_info filters[2] = {\n\t\t{\n\t\t\t.init = &lzma_lzma_encoder_init,\n\t\t\t.options = (void *)(options),\n\t\t}, {\n\t\t\t.init = NULL,\n\t\t}\n\t};\n\n\treturn lzma_next_filter_init(&coder->next, allocator, filters);\n}\n\n\n/*\nextern lzma_ret\nlzma_alone_encoder_init(lzma_next_coder *next, const lzma_allocator *allocator,\n\t\tconst lzma_options_alone *options)\n{\n\tlzma_next_coder_init(&alone_encoder_init, next, allocator, options);\n}\n*/\n\n\nextern LZMA_API(lzma_ret)\nlzma_alone_encoder(lzma_stream *strm, const lzma_options_lzma *options)\n{\n\tlzma_next_strm_init(alone_encoder_init, strm, options);\n\n\tstrm->internal->supported_actions[LZMA_RUN] = true;\n\tstrm->internal->supported_actions[LZMA_FINISH] = true;\n\n\treturn LZMA_OK;\n}\n"
  },
  {
    "path": "external/xz/liblzma/common/auto_decoder.c",
    "content": "///////////////////////////////////////////////////////////////////////////////\n//\n/// \\file       auto_decoder.c\n/// \\brief      Autodetect between .xz Stream and .lzma (LZMA_Alone) formats\n//\n//  Author:     Lasse Collin\n//\n//  This file has been put into the public domain.\n//  You can do whatever you want with this file.\n//\n///////////////////////////////////////////////////////////////////////////////\n\n#include \"stream_decoder.h\"\n#include \"alone_decoder.h\"\n\n\ntypedef struct {\n\t/// Stream decoder or LZMA_Alone decoder\n\tlzma_next_coder next;\n\n\tuint64_t memlimit;\n\tuint32_t flags;\n\n\tenum {\n\t\tSEQ_INIT,\n\t\tSEQ_CODE,\n\t\tSEQ_FINISH,\n\t} sequence;\n} lzma_auto_coder;\n\n\nstatic lzma_ret\nauto_decode(void *coder_ptr, const lzma_allocator *allocator,\n\t\tconst uint8_t *restrict in, size_t *restrict in_pos,\n\t\tsize_t in_size, uint8_t *restrict out,\n\t\tsize_t *restrict out_pos, size_t out_size, lzma_action action)\n{\n\tlzma_auto_coder *coder = coder_ptr;\n\n\tswitch (coder->sequence) {\n\tcase SEQ_INIT:\n\t\tif (*in_pos >= in_size)\n\t\t\treturn LZMA_OK;\n\n\t\t// Update the sequence now, because we want to continue from\n\t\t// SEQ_CODE even if we return some LZMA_*_CHECK.\n\t\tcoder->sequence = SEQ_CODE;\n\n\t\t// Detect the file format. For now this is simple, since if\n\t\t// it doesn't start with 0xFD (the first magic byte of the\n\t\t// new format), it has to be LZMA_Alone, or something that\n\t\t// we don't support at all.\n\t\tif (in[*in_pos] == 0xFD) {\n\t\t\treturn_if_error(lzma_stream_decoder_init(\n\t\t\t\t\t&coder->next, allocator,\n\t\t\t\t\tcoder->memlimit, coder->flags));\n\t\t} else {\n\t\t\treturn_if_error(lzma_alone_decoder_init(&coder->next,\n\t\t\t\t\tallocator, coder->memlimit, true));\n\n\t\t\t// If the application wants to know about missing\n\t\t\t// integrity check or about the check in general, we\n\t\t\t// need to handle it here, because LZMA_Alone decoder\n\t\t\t// doesn't accept any flags.\n\t\t\tif (coder->flags & LZMA_TELL_NO_CHECK)\n\t\t\t\treturn LZMA_NO_CHECK;\n\n\t\t\tif (coder->flags & LZMA_TELL_ANY_CHECK)\n\t\t\t\treturn LZMA_GET_CHECK;\n\t\t}\n\n\t// Fall through\n\n\tcase SEQ_CODE: {\n\t\tconst lzma_ret ret = coder->next.code(\n\t\t\t\tcoder->next.coder, allocator,\n\t\t\t\tin, in_pos, in_size,\n\t\t\t\tout, out_pos, out_size, action);\n\t\tif (ret != LZMA_STREAM_END\n\t\t\t\t|| (coder->flags & LZMA_CONCATENATED) == 0)\n\t\t\treturn ret;\n\n\t\tcoder->sequence = SEQ_FINISH;\n\t}\n\n\t// Fall through\n\n\tcase SEQ_FINISH:\n\t\t// When LZMA_DECODE_CONCATENATED was used and we were decoding\n\t\t// LZMA_Alone file, we need to check check that there is no\n\t\t// trailing garbage and wait for LZMA_FINISH.\n\t\tif (*in_pos < in_size)\n\t\t\treturn LZMA_DATA_ERROR;\n\n\t\treturn action == LZMA_FINISH ? LZMA_STREAM_END : LZMA_OK;\n\n\tdefault:\n\t\tassert(0);\n\t\treturn LZMA_PROG_ERROR;\n\t}\n}\n\n\nstatic void\nauto_decoder_end(void *coder_ptr, const lzma_allocator *allocator)\n{\n\tlzma_auto_coder *coder = coder_ptr;\n\tlzma_next_end(&coder->next, allocator);\n\tlzma_free(coder, allocator);\n\treturn;\n}\n\n\nstatic lzma_check\nauto_decoder_get_check(const void *coder_ptr)\n{\n\tconst lzma_auto_coder *coder = coder_ptr;\n\n\t// It is LZMA_Alone if get_check is NULL.\n\treturn coder->next.get_check == NULL ? LZMA_CHECK_NONE\n\t\t\t: coder->next.get_check(coder->next.coder);\n}\n\n\nstatic lzma_ret\nauto_decoder_memconfig(void *coder_ptr, uint64_t *memusage,\n\t\tuint64_t *old_memlimit, uint64_t new_memlimit)\n{\n\tlzma_auto_coder *coder = coder_ptr;\n\n\tlzma_ret ret;\n\n\tif (coder->next.memconfig != NULL) {\n\t\tret = coder->next.memconfig(coder->next.coder,\n\t\t\t\tmemusage, old_memlimit, new_memlimit);\n\t\tassert(*old_memlimit == coder->memlimit);\n\t} else {\n\t\t// No coder is configured yet. Use the base value as\n\t\t// the current memory usage.\n\t\t*memusage = LZMA_MEMUSAGE_BASE;\n\t\t*old_memlimit = coder->memlimit;\n\n\t\tret = LZMA_OK;\n\t\tif (new_memlimit != 0 && new_memlimit < *memusage)\n\t\t\tret = LZMA_MEMLIMIT_ERROR;\n\t}\n\n\tif (ret == LZMA_OK && new_memlimit != 0)\n\t\tcoder->memlimit = new_memlimit;\n\n\treturn ret;\n}\n\n\nstatic lzma_ret\nauto_decoder_init(lzma_next_coder *next, const lzma_allocator *allocator,\n\t\tuint64_t memlimit, uint32_t flags)\n{\n\tlzma_next_coder_init(&auto_decoder_init, next, allocator);\n\n\tif (flags & ~LZMA_SUPPORTED_FLAGS)\n\t\treturn LZMA_OPTIONS_ERROR;\n\n\tlzma_auto_coder *coder = next->coder;\n\tif (coder == NULL) {\n\t\tcoder = lzma_alloc(sizeof(lzma_auto_coder), allocator);\n\t\tif (coder == NULL)\n\t\t\treturn LZMA_MEM_ERROR;\n\n\t\tnext->coder = coder;\n\t\tnext->code = &auto_decode;\n\t\tnext->end = &auto_decoder_end;\n\t\tnext->get_check = &auto_decoder_get_check;\n\t\tnext->memconfig = &auto_decoder_memconfig;\n\t\tcoder->next = LZMA_NEXT_CODER_INIT;\n\t}\n\n\tcoder->memlimit = my_max(1, memlimit);\n\tcoder->flags = flags;\n\tcoder->sequence = SEQ_INIT;\n\n\treturn LZMA_OK;\n}\n\n\nextern LZMA_API(lzma_ret)\nlzma_auto_decoder(lzma_stream *strm, uint64_t memlimit, uint32_t flags)\n{\n\tlzma_next_strm_init(auto_decoder_init, strm, memlimit, flags);\n\n\tstrm->internal->supported_actions[LZMA_RUN] = true;\n\tstrm->internal->supported_actions[LZMA_FINISH] = true;\n\n\treturn LZMA_OK;\n}\n"
  },
  {
    "path": "external/xz/liblzma/common/block_buffer_decoder.c",
    "content": "///////////////////////////////////////////////////////////////////////////////\n//\n/// \\file       block_buffer_decoder.c\n/// \\brief      Single-call .xz Block decoder\n//\n//  Author:     Lasse Collin\n//\n//  This file has been put into the public domain.\n//  You can do whatever you want with this file.\n//\n///////////////////////////////////////////////////////////////////////////////\n\n#include \"block_decoder.h\"\n\n\nextern LZMA_API(lzma_ret)\nlzma_block_buffer_decode(lzma_block *block, const lzma_allocator *allocator,\n\t\tconst uint8_t *in, size_t *in_pos, size_t in_size,\n\t\tuint8_t *out, size_t *out_pos, size_t out_size)\n{\n\tif (in_pos == NULL || (in == NULL && *in_pos != in_size)\n\t\t\t|| *in_pos > in_size || out_pos == NULL\n\t\t\t|| (out == NULL && *out_pos != out_size)\n\t\t\t|| *out_pos > out_size)\n\t\treturn LZMA_PROG_ERROR;\n\n\t// Initialize the Block decoder.\n\tlzma_next_coder block_decoder = LZMA_NEXT_CODER_INIT;\n\tlzma_ret ret = lzma_block_decoder_init(\n\t\t\t&block_decoder, allocator, block);\n\n\tif (ret == LZMA_OK) {\n\t\t// Save the positions so that we can restore them in case\n\t\t// an error occurs.\n\t\tconst size_t in_start = *in_pos;\n\t\tconst size_t out_start = *out_pos;\n\n\t\t// Do the actual decoding.\n\t\tret = block_decoder.code(block_decoder.coder, allocator,\n\t\t\t\tin, in_pos, in_size, out, out_pos, out_size,\n\t\t\t\tLZMA_FINISH);\n\n\t\tif (ret == LZMA_STREAM_END) {\n\t\t\tret = LZMA_OK;\n\t\t} else {\n\t\t\tif (ret == LZMA_OK) {\n\t\t\t\t// Either the input was truncated or the\n\t\t\t\t// output buffer was too small.\n\t\t\t\tassert(*in_pos == in_size\n\t\t\t\t\t\t|| *out_pos == out_size);\n\n\t\t\t\t// If all the input was consumed, then the\n\t\t\t\t// input is truncated, even if the output\n\t\t\t\t// buffer is also full. This is because\n\t\t\t\t// processing the last byte of the Block\n\t\t\t\t// never produces output.\n\t\t\t\t//\n\t\t\t\t// NOTE: This assumption may break when new\n\t\t\t\t// filters are added, if the end marker of\n\t\t\t\t// the filter doesn't consume at least one\n\t\t\t\t// complete byte.\n\t\t\t\tif (*in_pos == in_size)\n\t\t\t\t\tret = LZMA_DATA_ERROR;\n\t\t\t\telse\n\t\t\t\t\tret = LZMA_BUF_ERROR;\n\t\t\t}\n\n\t\t\t// Restore the positions.\n\t\t\t*in_pos = in_start;\n\t\t\t*out_pos = out_start;\n\t\t}\n\t}\n\n\t// Free the decoder memory. This needs to be done even if\n\t// initialization fails, because the internal API doesn't\n\t// require the initialization function to free its memory on error.\n\tlzma_next_end(&block_decoder, allocator);\n\n\treturn ret;\n}\n"
  },
  {
    "path": "external/xz/liblzma/common/block_buffer_encoder.c",
    "content": "///////////////////////////////////////////////////////////////////////////////\n//\n/// \\file       block_buffer_encoder.c\n/// \\brief      Single-call .xz Block encoder\n//\n//  Author:     Lasse Collin\n//\n//  This file has been put into the public domain.\n//  You can do whatever you want with this file.\n//\n///////////////////////////////////////////////////////////////////////////////\n\n#include \"block_buffer_encoder.h\"\n#include \"block_encoder.h\"\n#include \"filter_encoder.h\"\n#include \"lzma2_encoder.h\"\n#include \"check.h\"\n\n\n/// Estimate the maximum size of the Block Header and Check fields for\n/// a Block that uses LZMA2 uncompressed chunks. We could use\n/// lzma_block_header_size() but this is simpler.\n///\n/// Block Header Size + Block Flags + Compressed Size\n/// + Uncompressed Size + Filter Flags for LZMA2 + CRC32 + Check\n/// and round up to the next multiple of four to take Header Padding\n/// into account.\n#define HEADERS_BOUND ((1 + 1 + 2 * LZMA_VLI_BYTES_MAX + 3 + 4 \\\n\t\t+ LZMA_CHECK_SIZE_MAX + 3) & ~3)\n\n\nstatic uint64_t\nlzma2_bound(uint64_t uncompressed_size)\n{\n\t// Prevent integer overflow in overhead calculation.\n\tif (uncompressed_size > COMPRESSED_SIZE_MAX)\n\t\treturn 0;\n\n\t// Calculate the exact overhead of the LZMA2 headers: Round\n\t// uncompressed_size up to the next multiple of LZMA2_CHUNK_MAX,\n\t// multiply by the size of per-chunk header, and add one byte for\n\t// the end marker.\n\tconst uint64_t overhead = ((uncompressed_size + LZMA2_CHUNK_MAX - 1)\n\t\t\t\t/ LZMA2_CHUNK_MAX)\n\t\t\t* LZMA2_HEADER_UNCOMPRESSED + 1;\n\n\t// Catch the possible integer overflow.\n\tif (COMPRESSED_SIZE_MAX - overhead < uncompressed_size)\n\t\treturn 0;\n\n\treturn uncompressed_size + overhead;\n}\n\n\nextern uint64_t\nlzma_block_buffer_bound64(uint64_t uncompressed_size)\n{\n\t// If the data doesn't compress, we always use uncompressed\n\t// LZMA2 chunks.\n\tuint64_t lzma2_size = lzma2_bound(uncompressed_size);\n\tif (lzma2_size == 0)\n\t\treturn 0;\n\n\t// Take Block Padding into account.\n\tlzma2_size = (lzma2_size + 3) & ~UINT64_C(3);\n\n\t// No risk of integer overflow because lzma2_bound() already takes\n\t// into account the size of the headers in the Block.\n\treturn HEADERS_BOUND + lzma2_size;\n}\n\n\nextern LZMA_API(size_t)\nlzma_block_buffer_bound(size_t uncompressed_size)\n{\n\tuint64_t ret = lzma_block_buffer_bound64(uncompressed_size);\n\n#if SIZE_MAX < UINT64_MAX\n\t// Catch the possible integer overflow on 32-bit systems.\n\tif (ret > SIZE_MAX)\n\t\treturn 0;\n#endif\n\n\treturn ret;\n}\n\n\nstatic lzma_ret\nblock_encode_uncompressed(lzma_block *block, const uint8_t *in, size_t in_size,\n\t\tuint8_t *out, size_t *out_pos, size_t out_size)\n{\n\t// Use LZMA2 uncompressed chunks. We wouldn't need a dictionary at\n\t// all, but LZMA2 always requires a dictionary, so use the minimum\n\t// value to minimize memory usage of the decoder.\n\tlzma_options_lzma lzma2 = {\n\t\t.dict_size = LZMA_DICT_SIZE_MIN,\n\t};\n\n\tlzma_filter filters[2];\n\tfilters[0].id = LZMA_FILTER_LZMA2;\n\tfilters[0].options = &lzma2;\n\tfilters[1].id = LZMA_VLI_UNKNOWN;\n\n\t// Set the above filter options to *block temporarily so that we can\n\t// encode the Block Header.\n\tlzma_filter *filters_orig = block->filters;\n\tblock->filters = filters;\n\n\tif (lzma_block_header_size(block) != LZMA_OK) {\n\t\tblock->filters = filters_orig;\n\t\treturn LZMA_PROG_ERROR;\n\t}\n\n\t// Check that there's enough output space. The caller has already\n\t// set block->compressed_size to what lzma2_bound() has returned,\n\t// so we can reuse that value. We know that compressed_size is a\n\t// known valid VLI and header_size is a small value so their sum\n\t// will never overflow.\n\tassert(block->compressed_size == lzma2_bound(in_size));\n\tif (out_size - *out_pos\n\t\t\t< block->header_size + block->compressed_size) {\n\t\tblock->filters = filters_orig;\n\t\treturn LZMA_BUF_ERROR;\n\t}\n\n\tif (lzma_block_header_encode(block, out + *out_pos) != LZMA_OK) {\n\t\tblock->filters = filters_orig;\n\t\treturn LZMA_PROG_ERROR;\n\t}\n\n\tblock->filters = filters_orig;\n\t*out_pos += block->header_size;\n\n\t// Encode the data using LZMA2 uncompressed chunks.\n\tsize_t in_pos = 0;\n\tuint8_t control = 0x01; // Dictionary reset\n\n\twhile (in_pos < in_size) {\n\t\t// Control byte: Indicate uncompressed chunk, of which\n\t\t// the first resets the dictionary.\n\t\tout[(*out_pos)++] = control;\n\t\tcontrol = 0x02; // No dictionary reset\n\n\t\t// Size of the uncompressed chunk\n\t\tconst size_t copy_size\n\t\t\t\t= my_min(in_size - in_pos, LZMA2_CHUNK_MAX);\n\t\tout[(*out_pos)++] = (copy_size - 1) >> 8;\n\t\tout[(*out_pos)++] = (copy_size - 1) & 0xFF;\n\n\t\t// The actual data\n\t\tassert(*out_pos + copy_size <= out_size);\n\t\tmemcpy(out + *out_pos, in + in_pos, copy_size);\n\n\t\tin_pos += copy_size;\n\t\t*out_pos += copy_size;\n\t}\n\n\t// End marker\n\tout[(*out_pos)++] = 0x00;\n\tassert(*out_pos <= out_size);\n\n\treturn LZMA_OK;\n}\n\n\nstatic lzma_ret\nblock_encode_normal(lzma_block *block, const lzma_allocator *allocator,\n\t\tconst uint8_t *in, size_t in_size,\n\t\tuint8_t *out, size_t *out_pos, size_t out_size)\n{\n\t// Find out the size of the Block Header.\n\treturn_if_error(lzma_block_header_size(block));\n\n\t// Reserve space for the Block Header and skip it for now.\n\tif (out_size - *out_pos <= block->header_size)\n\t\treturn LZMA_BUF_ERROR;\n\n\tconst size_t out_start = *out_pos;\n\t*out_pos += block->header_size;\n\n\t// Limit out_size so that we stop encoding if the output would grow\n\t// bigger than what uncompressed Block would be.\n\tif (out_size - *out_pos > block->compressed_size)\n\t\tout_size = *out_pos + block->compressed_size;\n\n\t// TODO: In many common cases this could be optimized to use\n\t// significantly less memory.\n\tlzma_next_coder raw_encoder = LZMA_NEXT_CODER_INIT;\n\tlzma_ret ret = lzma_raw_encoder_init(\n\t\t\t&raw_encoder, allocator, block->filters);\n\n\tif (ret == LZMA_OK) {\n\t\tsize_t in_pos = 0;\n\t\tret = raw_encoder.code(raw_encoder.coder, allocator,\n\t\t\t\tin, &in_pos, in_size, out, out_pos, out_size,\n\t\t\t\tLZMA_FINISH);\n\t}\n\n\t// NOTE: This needs to be run even if lzma_raw_encoder_init() failed.\n\tlzma_next_end(&raw_encoder, allocator);\n\n\tif (ret == LZMA_STREAM_END) {\n\t\t// Compression was successful. Write the Block Header.\n\t\tblock->compressed_size\n\t\t\t\t= *out_pos - (out_start + block->header_size);\n\t\tret = lzma_block_header_encode(block, out + out_start);\n\t\tif (ret != LZMA_OK)\n\t\t\tret = LZMA_PROG_ERROR;\n\n\t} else if (ret == LZMA_OK) {\n\t\t// Output buffer became full.\n\t\tret = LZMA_BUF_ERROR;\n\t}\n\n\t// Reset *out_pos if something went wrong.\n\tif (ret != LZMA_OK)\n\t\t*out_pos = out_start;\n\n\treturn ret;\n}\n\n\nstatic lzma_ret\nblock_buffer_encode(lzma_block *block, const lzma_allocator *allocator,\n\t\tconst uint8_t *in, size_t in_size,\n\t\tuint8_t *out, size_t *out_pos, size_t out_size,\n\t\tbool try_to_compress)\n{\n\t// Validate the arguments.\n\tif (block == NULL || (in == NULL && in_size != 0) || out == NULL\n\t\t\t|| out_pos == NULL || *out_pos > out_size)\n\t\treturn LZMA_PROG_ERROR;\n\n\t// The contents of the structure may depend on the version so\n\t// check the version before validating the contents of *block.\n\tif (block->version > 1)\n\t\treturn LZMA_OPTIONS_ERROR;\n\n\tif ((unsigned int)(block->check) > LZMA_CHECK_ID_MAX\n\t\t\t|| (try_to_compress && block->filters == NULL))\n\t\treturn LZMA_PROG_ERROR;\n\n\tif (!lzma_check_is_supported(block->check))\n\t\treturn LZMA_UNSUPPORTED_CHECK;\n\n\t// Size of a Block has to be a multiple of four, so limit the size\n\t// here already. This way we don't need to check it again when adding\n\t// Block Padding.\n\tout_size -= (out_size - *out_pos) & 3;\n\n\t// Get the size of the Check field.\n\tconst size_t check_size = lzma_check_size(block->check);\n\tassert(check_size != UINT32_MAX);\n\n\t// Reserve space for the Check field.\n\tif (out_size - *out_pos <= check_size)\n\t\treturn LZMA_BUF_ERROR;\n\n\tout_size -= check_size;\n\n\t// Initialize block->uncompressed_size and calculate the worst-case\n\t// value for block->compressed_size.\n\tblock->uncompressed_size = in_size;\n\tblock->compressed_size = lzma2_bound(in_size);\n\tif (block->compressed_size == 0)\n\t\treturn LZMA_DATA_ERROR;\n\n\t// Do the actual compression.\n\tlzma_ret ret = LZMA_BUF_ERROR;\n\tif (try_to_compress)\n\t\tret = block_encode_normal(block, allocator,\n\t\t\t\tin, in_size, out, out_pos, out_size);\n\n\tif (ret != LZMA_OK) {\n\t\t// If the error was something else than output buffer\n\t\t// becoming full, return the error now.\n\t\tif (ret != LZMA_BUF_ERROR)\n\t\t\treturn ret;\n\n\t\t// The data was uncompressible (at least with the options\n\t\t// given to us) or the output buffer was too small. Use the\n\t\t// uncompressed chunks of LZMA2 to wrap the data into a valid\n\t\t// Block. If we haven't been given enough output space, even\n\t\t// this may fail.\n\t\treturn_if_error(block_encode_uncompressed(block, in, in_size,\n\t\t\t\tout, out_pos, out_size));\n\t}\n\n\tassert(*out_pos <= out_size);\n\n\t// Block Padding. No buffer overflow here, because we already adjusted\n\t// out_size so that (out_size - out_start) is a multiple of four.\n\t// Thus, if the buffer is full, the loop body can never run.\n\tfor (size_t i = (size_t)(block->compressed_size); i & 3; ++i) {\n\t\tassert(*out_pos < out_size);\n\t\tout[(*out_pos)++] = 0x00;\n\t}\n\n\t// If there's no Check field, we are done now.\n\tif (check_size > 0) {\n\t\t// Calculate the integrity check. We reserved space for\n\t\t// the Check field earlier so we don't need to check for\n\t\t// available output space here.\n\t\tlzma_check_state check;\n\t\tlzma_check_init(&check, block->check);\n\t\tlzma_check_update(&check, block->check, in, in_size);\n\t\tlzma_check_finish(&check, block->check);\n\n\t\tmemcpy(block->raw_check, check.buffer.u8, check_size);\n\t\tmemcpy(out + *out_pos, check.buffer.u8, check_size);\n\t\t*out_pos += check_size;\n\t}\n\n\treturn LZMA_OK;\n}\n\n\nextern LZMA_API(lzma_ret)\nlzma_block_buffer_encode(lzma_block *block, const lzma_allocator *allocator,\n\t\tconst uint8_t *in, size_t in_size,\n\t\tuint8_t *out, size_t *out_pos, size_t out_size)\n{\n\treturn block_buffer_encode(block, allocator,\n\t\t\tin, in_size, out, out_pos, out_size, true);\n}\n\n\nextern LZMA_API(lzma_ret)\nlzma_block_uncomp_encode(lzma_block *block,\n\t\tconst uint8_t *in, size_t in_size,\n\t\tuint8_t *out, size_t *out_pos, size_t out_size)\n{\n\t// It won't allocate any memory from heap so no need\n\t// for lzma_allocator.\n\treturn block_buffer_encode(block, NULL,\n\t\t\tin, in_size, out, out_pos, out_size, false);\n}\n"
  },
  {
    "path": "external/xz/liblzma/common/block_buffer_encoder.h",
    "content": "///////////////////////////////////////////////////////////////////////////////\n//\n/// \\file       block_buffer_encoder.h\n/// \\brief      Single-call .xz Block encoder\n//\n//  Author:     Lasse Collin\n//\n//  This file has been put into the public domain.\n//  You can do whatever you want with this file.\n//\n///////////////////////////////////////////////////////////////////////////////\n\n#ifndef LZMA_BLOCK_BUFFER_ENCODER_H\n#define LZMA_BLOCK_BUFFER_ENCODER_H\n\n#include \"common.h\"\n\n\n/// uint64_t version of lzma_block_buffer_bound(). It is used by\n/// stream_encoder_mt.c. Probably the original lzma_block_buffer_bound()\n/// should have been 64-bit, but fixing it would break the ABI.\nextern uint64_t lzma_block_buffer_bound64(uint64_t uncompressed_size);\n\n#endif\n"
  },
  {
    "path": "external/xz/liblzma/common/block_decoder.c",
    "content": "///////////////////////////////////////////////////////////////////////////////\n//\n/// \\file       block_decoder.c\n/// \\brief      Decodes .xz Blocks\n//\n//  Author:     Lasse Collin\n//\n//  This file has been put into the public domain.\n//  You can do whatever you want with this file.\n//\n///////////////////////////////////////////////////////////////////////////////\n\n#include \"block_decoder.h\"\n#include \"filter_decoder.h\"\n#include \"check.h\"\n\n\ntypedef struct {\n\tenum {\n\t\tSEQ_CODE,\n\t\tSEQ_PADDING,\n\t\tSEQ_CHECK,\n\t} sequence;\n\n\t/// The filters in the chain; initialized with lzma_raw_decoder_init().\n\tlzma_next_coder next;\n\n\t/// Decoding options; we also write Compressed Size and Uncompressed\n\t/// Size back to this structure when the decoding has been finished.\n\tlzma_block *block;\n\n\t/// Compressed Size calculated while decoding\n\tlzma_vli compressed_size;\n\n\t/// Uncompressed Size calculated while decoding\n\tlzma_vli uncompressed_size;\n\n\t/// Maximum allowed Compressed Size; this takes into account the\n\t/// size of the Block Header and Check fields when Compressed Size\n\t/// is unknown.\n\tlzma_vli compressed_limit;\n\n\t/// Position when reading the Check field\n\tsize_t check_pos;\n\n\t/// Check of the uncompressed data\n\tlzma_check_state check;\n\n\t/// True if the integrity check won't be calculated and verified.\n\tbool ignore_check;\n} lzma_block_coder;\n\n\nstatic inline bool\nupdate_size(lzma_vli *size, lzma_vli add, lzma_vli limit)\n{\n\tif (limit > LZMA_VLI_MAX)\n\t\tlimit = LZMA_VLI_MAX;\n\n\tif (limit < *size || limit - *size < add)\n\t\treturn true;\n\n\t*size += add;\n\n\treturn false;\n}\n\n\nstatic inline bool\nis_size_valid(lzma_vli size, lzma_vli reference)\n{\n\treturn reference == LZMA_VLI_UNKNOWN || reference == size;\n}\n\n\nstatic lzma_ret\nblock_decode(void *coder_ptr, const lzma_allocator *allocator,\n\t\tconst uint8_t *restrict in, size_t *restrict in_pos,\n\t\tsize_t in_size, uint8_t *restrict out,\n\t\tsize_t *restrict out_pos, size_t out_size, lzma_action action)\n{\n\tlzma_block_coder *coder = coder_ptr;\n\n\tswitch (coder->sequence) {\n\tcase SEQ_CODE: {\n\t\tconst size_t in_start = *in_pos;\n\t\tconst size_t out_start = *out_pos;\n\n\t\tconst lzma_ret ret = coder->next.code(coder->next.coder,\n\t\t\t\tallocator, in, in_pos, in_size,\n\t\t\t\tout, out_pos, out_size, action);\n\n\t\tconst size_t in_used = *in_pos - in_start;\n\t\tconst size_t out_used = *out_pos - out_start;\n\n\t\t// NOTE: We compare to compressed_limit here, which prevents\n\t\t// the total size of the Block growing past LZMA_VLI_MAX.\n\t\tif (update_size(&coder->compressed_size, in_used,\n\t\t\t\t\tcoder->compressed_limit)\n\t\t\t\t|| update_size(&coder->uncompressed_size,\n\t\t\t\t\tout_used,\n\t\t\t\t\tcoder->block->uncompressed_size))\n\t\t\treturn LZMA_DATA_ERROR;\n\n\t\tif (!coder->ignore_check)\n\t\t\tlzma_check_update(&coder->check, coder->block->check,\n\t\t\t\t\tout + out_start, out_used);\n\n\t\tif (ret != LZMA_STREAM_END)\n\t\t\treturn ret;\n\n\t\t// Compressed and Uncompressed Sizes are now at their final\n\t\t// values. Verify that they match the values given to us.\n\t\tif (!is_size_valid(coder->compressed_size,\n\t\t\t\t\tcoder->block->compressed_size)\n\t\t\t\t|| !is_size_valid(coder->uncompressed_size,\n\t\t\t\t\tcoder->block->uncompressed_size))\n\t\t\treturn LZMA_DATA_ERROR;\n\n\t\t// Copy the values into coder->block. The caller\n\t\t// may use this information to construct Index.\n\t\tcoder->block->compressed_size = coder->compressed_size;\n\t\tcoder->block->uncompressed_size = coder->uncompressed_size;\n\n\t\tcoder->sequence = SEQ_PADDING;\n\t}\n\n\t// Fall through\n\n\tcase SEQ_PADDING:\n\t\t// Compressed Data is padded to a multiple of four bytes.\n\t\twhile (coder->compressed_size & 3) {\n\t\t\tif (*in_pos >= in_size)\n\t\t\t\treturn LZMA_OK;\n\n\t\t\t// We use compressed_size here just get the Padding\n\t\t\t// right. The actual Compressed Size was stored to\n\t\t\t// coder->block already, and won't be modified by\n\t\t\t// us anymore.\n\t\t\t++coder->compressed_size;\n\n\t\t\tif (in[(*in_pos)++] != 0x00)\n\t\t\t\treturn LZMA_DATA_ERROR;\n\t\t}\n\n\t\tif (coder->block->check == LZMA_CHECK_NONE)\n\t\t\treturn LZMA_STREAM_END;\n\n\t\tif (!coder->ignore_check)\n\t\t\tlzma_check_finish(&coder->check, coder->block->check);\n\n\t\tcoder->sequence = SEQ_CHECK;\n\n\t// Fall through\n\n\tcase SEQ_CHECK: {\n\t\tconst size_t check_size = lzma_check_size(coder->block->check);\n\t\tlzma_bufcpy(in, in_pos, in_size, coder->block->raw_check,\n\t\t\t\t&coder->check_pos, check_size);\n\t\tif (coder->check_pos < check_size)\n\t\t\treturn LZMA_OK;\n\n\t\t// Validate the Check only if we support it.\n\t\t// coder->check.buffer may be uninitialized\n\t\t// when the Check ID is not supported.\n\t\tif (!coder->ignore_check\n\t\t\t\t&& lzma_check_is_supported(coder->block->check)\n\t\t\t\t&& memcmp(coder->block->raw_check,\n\t\t\t\t\tcoder->check.buffer.u8,\n\t\t\t\t\tcheck_size) != 0)\n\t\t\treturn LZMA_DATA_ERROR;\n\n\t\treturn LZMA_STREAM_END;\n\t}\n\t}\n\n\treturn LZMA_PROG_ERROR;\n}\n\n\nstatic void\nblock_decoder_end(void *coder_ptr, const lzma_allocator *allocator)\n{\n\tlzma_block_coder *coder = coder_ptr;\n\tlzma_next_end(&coder->next, allocator);\n\tlzma_free(coder, allocator);\n\treturn;\n}\n\n\nextern lzma_ret\nlzma_block_decoder_init(lzma_next_coder *next, const lzma_allocator *allocator,\n\t\tlzma_block *block)\n{\n\tlzma_next_coder_init(&lzma_block_decoder_init, next, allocator);\n\n\t// Validate the options. lzma_block_unpadded_size() does that for us\n\t// except for Uncompressed Size and filters. Filters are validated\n\t// by the raw decoder.\n\tif (lzma_block_unpadded_size(block) == 0\n\t\t\t|| !lzma_vli_is_valid(block->uncompressed_size))\n\t\treturn LZMA_PROG_ERROR;\n\n\t// Allocate *next->coder if needed.\n\tlzma_block_coder *coder = next->coder;\n\tif (coder == NULL) {\n\t\tcoder = lzma_alloc(sizeof(lzma_block_coder), allocator);\n\t\tif (coder == NULL)\n\t\t\treturn LZMA_MEM_ERROR;\n\n\t\tnext->coder = coder;\n\t\tnext->code = &block_decode;\n\t\tnext->end = &block_decoder_end;\n\t\tcoder->next = LZMA_NEXT_CODER_INIT;\n\t}\n\n\t// Basic initializations\n\tcoder->sequence = SEQ_CODE;\n\tcoder->block = block;\n\tcoder->compressed_size = 0;\n\tcoder->uncompressed_size = 0;\n\n\t// If Compressed Size is not known, we calculate the maximum allowed\n\t// value so that encoded size of the Block (including Block Padding)\n\t// is still a valid VLI and a multiple of four.\n\tcoder->compressed_limit\n\t\t\t= block->compressed_size == LZMA_VLI_UNKNOWN\n\t\t\t\t? (LZMA_VLI_MAX & ~LZMA_VLI_C(3))\n\t\t\t\t\t- block->header_size\n\t\t\t\t\t- lzma_check_size(block->check)\n\t\t\t\t: block->compressed_size;\n\n\t// Initialize the check. It's caller's problem if the Check ID is not\n\t// supported, and the Block decoder cannot verify the Check field.\n\t// Caller can test lzma_check_is_supported(block->check).\n\tcoder->check_pos = 0;\n\tlzma_check_init(&coder->check, block->check);\n\n\tcoder->ignore_check = block->version >= 1\n\t\t\t? block->ignore_check : false;\n\n\t// Initialize the filter chain.\n\treturn lzma_raw_decoder_init(&coder->next, allocator,\n\t\t\tblock->filters);\n}\n\n\nextern LZMA_API(lzma_ret)\nlzma_block_decoder(lzma_stream *strm, lzma_block *block)\n{\n\tlzma_next_strm_init(lzma_block_decoder_init, strm, block);\n\n\tstrm->internal->supported_actions[LZMA_RUN] = true;\n\tstrm->internal->supported_actions[LZMA_FINISH] = true;\n\n\treturn LZMA_OK;\n}\n"
  },
  {
    "path": "external/xz/liblzma/common/block_decoder.h",
    "content": "///////////////////////////////////////////////////////////////////////////////\n//\n/// \\file       block_decoder.h\n/// \\brief      Decodes .xz Blocks\n//\n//  Author:     Lasse Collin\n//\n//  This file has been put into the public domain.\n//  You can do whatever you want with this file.\n//\n///////////////////////////////////////////////////////////////////////////////\n\n#ifndef LZMA_BLOCK_DECODER_H\n#define LZMA_BLOCK_DECODER_H\n\n#include \"common.h\"\n\n\nextern lzma_ret lzma_block_decoder_init(lzma_next_coder *next,\n\t\tconst lzma_allocator *allocator, lzma_block *block);\n\n#endif\n"
  },
  {
    "path": "external/xz/liblzma/common/block_encoder.c",
    "content": "///////////////////////////////////////////////////////////////////////////////\n//\n/// \\file       block_encoder.c\n/// \\brief      Encodes .xz Blocks\n//\n//  Author:     Lasse Collin\n//\n//  This file has been put into the public domain.\n//  You can do whatever you want with this file.\n//\n///////////////////////////////////////////////////////////////////////////////\n\n#include \"block_encoder.h\"\n#include \"filter_encoder.h\"\n#include \"check.h\"\n\n\ntypedef struct {\n\t/// The filters in the chain; initialized with lzma_raw_decoder_init().\n\tlzma_next_coder next;\n\n\t/// Encoding options; we also write Unpadded Size, Compressed Size,\n\t/// and Uncompressed Size back to this structure when the encoding\n\t/// has been finished.\n\tlzma_block *block;\n\n\tenum {\n\t\tSEQ_CODE,\n\t\tSEQ_PADDING,\n\t\tSEQ_CHECK,\n\t} sequence;\n\n\t/// Compressed Size calculated while encoding\n\tlzma_vli compressed_size;\n\n\t/// Uncompressed Size calculated while encoding\n\tlzma_vli uncompressed_size;\n\n\t/// Position in the Check field\n\tsize_t pos;\n\n\t/// Check of the uncompressed data\n\tlzma_check_state check;\n} lzma_block_coder;\n\n\nstatic lzma_ret\nblock_encode(void *coder_ptr, const lzma_allocator *allocator,\n\t\tconst uint8_t *restrict in, size_t *restrict in_pos,\n\t\tsize_t in_size, uint8_t *restrict out,\n\t\tsize_t *restrict out_pos, size_t out_size, lzma_action action)\n{\n\tlzma_block_coder *coder = coder_ptr;\n\n\t// Check that our amount of input stays in proper limits.\n\tif (LZMA_VLI_MAX - coder->uncompressed_size < in_size - *in_pos)\n\t\treturn LZMA_DATA_ERROR;\n\n\tswitch (coder->sequence) {\n\tcase SEQ_CODE: {\n\t\tconst size_t in_start = *in_pos;\n\t\tconst size_t out_start = *out_pos;\n\n\t\tconst lzma_ret ret = coder->next.code(coder->next.coder,\n\t\t\t\tallocator, in, in_pos, in_size,\n\t\t\t\tout, out_pos, out_size, action);\n\n\t\tconst size_t in_used = *in_pos - in_start;\n\t\tconst size_t out_used = *out_pos - out_start;\n\n\t\tif (COMPRESSED_SIZE_MAX - coder->compressed_size < out_used)\n\t\t\treturn LZMA_DATA_ERROR;\n\n\t\tcoder->compressed_size += out_used;\n\n\t\t// No need to check for overflow because we have already\n\t\t// checked it at the beginning of this function.\n\t\tcoder->uncompressed_size += in_used;\n\n\t\tlzma_check_update(&coder->check, coder->block->check,\n\t\t\t\tin + in_start, in_used);\n\n\t\tif (ret != LZMA_STREAM_END || action == LZMA_SYNC_FLUSH)\n\t\t\treturn ret;\n\n\t\tassert(*in_pos == in_size);\n\t\tassert(action == LZMA_FINISH);\n\n\t\t// Copy the values into coder->block. The caller\n\t\t// may use this information to construct Index.\n\t\tcoder->block->compressed_size = coder->compressed_size;\n\t\tcoder->block->uncompressed_size = coder->uncompressed_size;\n\n\t\tcoder->sequence = SEQ_PADDING;\n\t}\n\n\t// Fall through\n\n\tcase SEQ_PADDING:\n\t\t// Pad Compressed Data to a multiple of four bytes. We can\n\t\t// use coder->compressed_size for this since we don't need\n\t\t// it for anything else anymore.\n\t\twhile (coder->compressed_size & 3) {\n\t\t\tif (*out_pos >= out_size)\n\t\t\t\treturn LZMA_OK;\n\n\t\t\tout[*out_pos] = 0x00;\n\t\t\t++*out_pos;\n\t\t\t++coder->compressed_size;\n\t\t}\n\n\t\tif (coder->block->check == LZMA_CHECK_NONE)\n\t\t\treturn LZMA_STREAM_END;\n\n\t\tlzma_check_finish(&coder->check, coder->block->check);\n\n\t\tcoder->sequence = SEQ_CHECK;\n\n\t// Fall through\n\n\tcase SEQ_CHECK: {\n\t\tconst size_t check_size = lzma_check_size(coder->block->check);\n\t\tlzma_bufcpy(coder->check.buffer.u8, &coder->pos, check_size,\n\t\t\t\tout, out_pos, out_size);\n\t\tif (coder->pos < check_size)\n\t\t\treturn LZMA_OK;\n\n\t\tmemcpy(coder->block->raw_check, coder->check.buffer.u8,\n\t\t\t\tcheck_size);\n\t\treturn LZMA_STREAM_END;\n\t}\n\t}\n\n\treturn LZMA_PROG_ERROR;\n}\n\n\nstatic void\nblock_encoder_end(void *coder_ptr, const lzma_allocator *allocator)\n{\n\tlzma_block_coder *coder = coder_ptr;\n\tlzma_next_end(&coder->next, allocator);\n\tlzma_free(coder, allocator);\n\treturn;\n}\n\n\nstatic lzma_ret\nblock_encoder_update(void *coder_ptr, const lzma_allocator *allocator,\n\t\tconst lzma_filter *filters lzma_attribute((__unused__)),\n\t\tconst lzma_filter *reversed_filters)\n{\n\tlzma_block_coder *coder = coder_ptr;\n\n\tif (coder->sequence != SEQ_CODE)\n\t\treturn LZMA_PROG_ERROR;\n\n\treturn lzma_next_filter_update(\n\t\t\t&coder->next, allocator, reversed_filters);\n}\n\n\nextern lzma_ret\nlzma_block_encoder_init(lzma_next_coder *next, const lzma_allocator *allocator,\n\t\tlzma_block *block)\n{\n\tlzma_next_coder_init(&lzma_block_encoder_init, next, allocator);\n\n\tif (block == NULL)\n\t\treturn LZMA_PROG_ERROR;\n\n\t// The contents of the structure may depend on the version so\n\t// check the version first.\n\tif (block->version > 1)\n\t\treturn LZMA_OPTIONS_ERROR;\n\n\t// If the Check ID is not supported, we cannot calculate the check and\n\t// thus not create a proper Block.\n\tif ((unsigned int)(block->check) > LZMA_CHECK_ID_MAX)\n\t\treturn LZMA_PROG_ERROR;\n\n\tif (!lzma_check_is_supported(block->check))\n\t\treturn LZMA_UNSUPPORTED_CHECK;\n\n\t// Allocate and initialize *next->coder if needed.\n\tlzma_block_coder *coder = next->coder;\n\tif (coder == NULL) {\n\t\tcoder = lzma_alloc(sizeof(lzma_block_coder), allocator);\n\t\tif (coder == NULL)\n\t\t\treturn LZMA_MEM_ERROR;\n\n\t\tnext->coder = coder;\n\t\tnext->code = &block_encode;\n\t\tnext->end = &block_encoder_end;\n\t\tnext->update = &block_encoder_update;\n\t\tcoder->next = LZMA_NEXT_CODER_INIT;\n\t}\n\n\t// Basic initializations\n\tcoder->sequence = SEQ_CODE;\n\tcoder->block = block;\n\tcoder->compressed_size = 0;\n\tcoder->uncompressed_size = 0;\n\tcoder->pos = 0;\n\n\t// Initialize the check\n\tlzma_check_init(&coder->check, block->check);\n\n\t// Initialize the requested filters.\n\treturn lzma_raw_encoder_init(&coder->next, allocator, block->filters);\n}\n\n\nextern LZMA_API(lzma_ret)\nlzma_block_encoder(lzma_stream *strm, lzma_block *block)\n{\n\tlzma_next_strm_init(lzma_block_encoder_init, strm, block);\n\n\tstrm->internal->supported_actions[LZMA_RUN] = true;\n\tstrm->internal->supported_actions[LZMA_FINISH] = true;\n\n\treturn LZMA_OK;\n}\n"
  },
  {
    "path": "external/xz/liblzma/common/block_encoder.h",
    "content": "///////////////////////////////////////////////////////////////////////////////\n//\n/// \\file       block_encoder.h\n/// \\brief      Encodes .xz Blocks\n//\n//  Author:     Lasse Collin\n//\n//  This file has been put into the public domain.\n//  You can do whatever you want with this file.\n//\n///////////////////////////////////////////////////////////////////////////////\n\n#ifndef LZMA_BLOCK_ENCODER_H\n#define LZMA_BLOCK_ENCODER_H\n\n#include \"common.h\"\n\n\n/// \\brief      Biggest Compressed Size value that the Block encoder supports\n///\n/// The maximum size of a single Block is limited by the maximum size of\n/// a Stream, which in theory is 2^63 - 3 bytes (i.e. LZMA_VLI_MAX - 3).\n/// While the size is really big and no one should hit it in practice, we\n/// take it into account in some places anyway to catch some errors e.g. if\n/// application passes insanely big value to some function.\n///\n/// We could take into account the headers etc. to determine the exact\n/// maximum size of the Compressed Data field, but the complexity would give\n/// us nothing useful. Instead, limit the size of Compressed Data so that\n/// even with biggest possible Block Header and Check fields the total\n/// encoded size of the Block stays as a valid VLI. This doesn't guarantee\n/// that the size of the Stream doesn't grow too big, but that problem is\n/// taken care outside the Block handling code.\n///\n/// ~LZMA_VLI_C(3) is to guarantee that if we need padding at the end of\n/// the Compressed Data field, it will still stay in the proper limit.\n///\n/// This constant is in this file because it is needed in both\n/// block_encoder.c and block_buffer_encoder.c.\n#define COMPRESSED_SIZE_MAX ((LZMA_VLI_MAX - LZMA_BLOCK_HEADER_SIZE_MAX \\\n\t\t- LZMA_CHECK_SIZE_MAX) & ~LZMA_VLI_C(3))\n\n\nextern lzma_ret lzma_block_encoder_init(lzma_next_coder *next,\n\t\tconst lzma_allocator *allocator, lzma_block *block);\n\n#endif\n"
  },
  {
    "path": "external/xz/liblzma/common/block_header_decoder.c",
    "content": "///////////////////////////////////////////////////////////////////////////////\n//\n/// \\file       block_header_decoder.c\n/// \\brief      Decodes Block Header from .xz files\n//\n//  Author:     Lasse Collin\n//\n//  This file has been put into the public domain.\n//  You can do whatever you want with this file.\n//\n///////////////////////////////////////////////////////////////////////////////\n\n#include \"common.h\"\n#include \"check.h\"\n\n\nstatic void\nfree_properties(lzma_block *block, const lzma_allocator *allocator)\n{\n\t// Free allocated filter options. The last array member is not\n\t// touched after the initialization in the beginning of\n\t// lzma_block_header_decode(), so we don't need to touch that here.\n\tfor (size_t i = 0; i < LZMA_FILTERS_MAX; ++i) {\n\t\tlzma_free(block->filters[i].options, allocator);\n\t\tblock->filters[i].id = LZMA_VLI_UNKNOWN;\n\t\tblock->filters[i].options = NULL;\n\t}\n\n\treturn;\n}\n\n\nextern LZMA_API(lzma_ret)\nlzma_block_header_decode(lzma_block *block,\n\t\tconst lzma_allocator *allocator, const uint8_t *in)\n{\n\t// NOTE: We consider the header to be corrupt not only when the\n\t// CRC32 doesn't match, but also when variable-length integers\n\t// are invalid or over 63 bits, or if the header is too small\n\t// to contain the claimed information.\n\n\t// Initialize the filter options array. This way the caller can\n\t// safely free() the options even if an error occurs in this function.\n\tfor (size_t i = 0; i <= LZMA_FILTERS_MAX; ++i) {\n\t\tblock->filters[i].id = LZMA_VLI_UNKNOWN;\n\t\tblock->filters[i].options = NULL;\n\t}\n\n\t// Versions 0 and 1 are supported. If a newer version was specified,\n\t// we need to downgrade it.\n\tif (block->version > 1)\n\t\tblock->version = 1;\n\n\t// This isn't a Block Header option, but since the decompressor will\n\t// read it if version >= 1, it's better to initialize it here than\n\t// to expect the caller to do it since in almost all cases this\n\t// should be false.\n\tblock->ignore_check = false;\n\n\t// Validate Block Header Size and Check type. The caller must have\n\t// already set these, so it is a programming error if this test fails.\n\tif (lzma_block_header_size_decode(in[0]) != block->header_size\n\t\t\t|| (unsigned int)(block->check) > LZMA_CHECK_ID_MAX)\n\t\treturn LZMA_PROG_ERROR;\n\n\t// Exclude the CRC32 field.\n\tconst size_t in_size = block->header_size - 4;\n\n\t// Verify CRC32\n\tif (lzma_crc32(in, in_size, 0) != read32le(in + in_size))\n\t\treturn LZMA_DATA_ERROR;\n\n\t// Check for unsupported flags.\n\tif (in[1] & 0x3C)\n\t\treturn LZMA_OPTIONS_ERROR;\n\n\t// Start after the Block Header Size and Block Flags fields.\n\tsize_t in_pos = 2;\n\n\t// Compressed Size\n\tif (in[1] & 0x40) {\n\t\treturn_if_error(lzma_vli_decode(&block->compressed_size,\n\t\t\t\tNULL, in, &in_pos, in_size));\n\n\t\t// Validate Compressed Size. This checks that it isn't zero\n\t\t// and that the total size of the Block is a valid VLI.\n\t\tif (lzma_block_unpadded_size(block) == 0)\n\t\t\treturn LZMA_DATA_ERROR;\n\t} else {\n\t\tblock->compressed_size = LZMA_VLI_UNKNOWN;\n\t}\n\n\t// Uncompressed Size\n\tif (in[1] & 0x80)\n\t\treturn_if_error(lzma_vli_decode(&block->uncompressed_size,\n\t\t\t\tNULL, in, &in_pos, in_size));\n\telse\n\t\tblock->uncompressed_size = LZMA_VLI_UNKNOWN;\n\n\t// Filter Flags\n\tconst size_t filter_count = (in[1] & 3U) + 1;\n\tfor (size_t i = 0; i < filter_count; ++i) {\n\t\tconst lzma_ret ret = lzma_filter_flags_decode(\n\t\t\t\t&block->filters[i], allocator,\n\t\t\t\tin, &in_pos, in_size);\n\t\tif (ret != LZMA_OK) {\n\t\t\tfree_properties(block, allocator);\n\t\t\treturn ret;\n\t\t}\n\t}\n\n\t// Padding\n\twhile (in_pos < in_size) {\n\t\tif (in[in_pos++] != 0x00) {\n\t\t\tfree_properties(block, allocator);\n\n\t\t\t// Possibly some new field present so use\n\t\t\t// LZMA_OPTIONS_ERROR instead of LZMA_DATA_ERROR.\n\t\t\treturn LZMA_OPTIONS_ERROR;\n\t\t}\n\t}\n\n\treturn LZMA_OK;\n}\n"
  },
  {
    "path": "external/xz/liblzma/common/block_header_encoder.c",
    "content": "///////////////////////////////////////////////////////////////////////////////\n//\n/// \\file       block_header_encoder.c\n/// \\brief      Encodes Block Header for .xz files\n//\n//  Author:     Lasse Collin\n//\n//  This file has been put into the public domain.\n//  You can do whatever you want with this file.\n//\n///////////////////////////////////////////////////////////////////////////////\n\n#include \"common.h\"\n#include \"check.h\"\n\n\nextern LZMA_API(lzma_ret)\nlzma_block_header_size(lzma_block *block)\n{\n\tif (block->version > 1)\n\t\treturn LZMA_OPTIONS_ERROR;\n\n\t// Block Header Size + Block Flags + CRC32.\n\tuint32_t size = 1 + 1 + 4;\n\n\t// Compressed Size\n\tif (block->compressed_size != LZMA_VLI_UNKNOWN) {\n\t\tconst uint32_t add = lzma_vli_size(block->compressed_size);\n\t\tif (add == 0 || block->compressed_size == 0)\n\t\t\treturn LZMA_PROG_ERROR;\n\n\t\tsize += add;\n\t}\n\n\t// Uncompressed Size\n\tif (block->uncompressed_size != LZMA_VLI_UNKNOWN) {\n\t\tconst uint32_t add = lzma_vli_size(block->uncompressed_size);\n\t\tif (add == 0)\n\t\t\treturn LZMA_PROG_ERROR;\n\n\t\tsize += add;\n\t}\n\n\t// List of Filter Flags\n\tif (block->filters == NULL || block->filters[0].id == LZMA_VLI_UNKNOWN)\n\t\treturn LZMA_PROG_ERROR;\n\n\tfor (size_t i = 0; block->filters[i].id != LZMA_VLI_UNKNOWN; ++i) {\n\t\t// Don't allow too many filters.\n\t\tif (i == LZMA_FILTERS_MAX)\n\t\t\treturn LZMA_PROG_ERROR;\n\n\t\tuint32_t add;\n\t\treturn_if_error(lzma_filter_flags_size(&add,\n\t\t\t\tblock->filters + i));\n\n\t\tsize += add;\n\t}\n\n\t// Pad to a multiple of four bytes.\n\tblock->header_size = (size + 3) & ~UINT32_C(3);\n\n\t// NOTE: We don't verify that the encoded size of the Block stays\n\t// within limits. This is because it is possible that we are called\n\t// with exaggerated Compressed Size (e.g. LZMA_VLI_MAX) to reserve\n\t// space for Block Header, and later called again with lower,\n\t// real values.\n\n\treturn LZMA_OK;\n}\n\n\nextern LZMA_API(lzma_ret)\nlzma_block_header_encode(const lzma_block *block, uint8_t *out)\n{\n\t// Validate everything but filters.\n\tif (lzma_block_unpadded_size(block) == 0\n\t\t\t|| !lzma_vli_is_valid(block->uncompressed_size))\n\t\treturn LZMA_PROG_ERROR;\n\n\t// Indicate the size of the buffer _excluding_ the CRC32 field.\n\tconst size_t out_size = block->header_size - 4;\n\n\t// Store the Block Header Size.\n\tout[0] = out_size / 4;\n\n\t// We write Block Flags in pieces.\n\tout[1] = 0x00;\n\tsize_t out_pos = 2;\n\n\t// Compressed Size\n\tif (block->compressed_size != LZMA_VLI_UNKNOWN) {\n\t\treturn_if_error(lzma_vli_encode(block->compressed_size, NULL,\n\t\t\t\tout, &out_pos, out_size));\n\n\t\tout[1] |= 0x40;\n\t}\n\n\t// Uncompressed Size\n\tif (block->uncompressed_size != LZMA_VLI_UNKNOWN) {\n\t\treturn_if_error(lzma_vli_encode(block->uncompressed_size, NULL,\n\t\t\t\tout, &out_pos, out_size));\n\n\t\tout[1] |= 0x80;\n\t}\n\n\t// Filter Flags\n\tif (block->filters == NULL || block->filters[0].id == LZMA_VLI_UNKNOWN)\n\t\treturn LZMA_PROG_ERROR;\n\n\tsize_t filter_count = 0;\n\tdo {\n\t\t// There can be a maximum of four filters.\n\t\tif (filter_count == LZMA_FILTERS_MAX)\n\t\t\treturn LZMA_PROG_ERROR;\n\n\t\treturn_if_error(lzma_filter_flags_encode(\n\t\t\t\tblock->filters + filter_count,\n\t\t\t\tout, &out_pos, out_size));\n\n\t} while (block->filters[++filter_count].id != LZMA_VLI_UNKNOWN);\n\n\tout[1] |= filter_count - 1;\n\n\t// Padding\n\tmemzero(out + out_pos, out_size - out_pos);\n\n\t// CRC32\n\twrite32le(out + out_size, lzma_crc32(out, out_size, 0));\n\n\treturn LZMA_OK;\n}\n"
  },
  {
    "path": "external/xz/liblzma/common/block_util.c",
    "content": "///////////////////////////////////////////////////////////////////////////////\n//\n/// \\file       block_util.c\n/// \\brief      Utility functions to handle lzma_block\n//\n//  Author:     Lasse Collin\n//\n//  This file has been put into the public domain.\n//  You can do whatever you want with this file.\n//\n///////////////////////////////////////////////////////////////////////////////\n\n#include \"common.h\"\n#include \"index.h\"\n\n\nextern LZMA_API(lzma_ret)\nlzma_block_compressed_size(lzma_block *block, lzma_vli unpadded_size)\n{\n\t// Validate everything but Uncompressed Size and filters.\n\tif (lzma_block_unpadded_size(block) == 0)\n\t\treturn LZMA_PROG_ERROR;\n\n\tconst uint32_t container_size = block->header_size\n\t\t\t+ lzma_check_size(block->check);\n\n\t// Validate that Compressed Size will be greater than zero.\n\tif (unpadded_size <= container_size)\n\t\treturn LZMA_DATA_ERROR;\n\n\t// Calculate what Compressed Size is supposed to be.\n\t// If Compressed Size was present in Block Header,\n\t// compare that the new value matches it.\n\tconst lzma_vli compressed_size = unpadded_size - container_size;\n\tif (block->compressed_size != LZMA_VLI_UNKNOWN\n\t\t\t&& block->compressed_size != compressed_size)\n\t\treturn LZMA_DATA_ERROR;\n\n\tblock->compressed_size = compressed_size;\n\n\treturn LZMA_OK;\n}\n\n\nextern LZMA_API(lzma_vli)\nlzma_block_unpadded_size(const lzma_block *block)\n{\n\t// Validate the values that we are interested in i.e. all but\n\t// Uncompressed Size and the filters.\n\t//\n\t// NOTE: This function is used for validation too, so it is\n\t// essential that these checks are always done even if\n\t// Compressed Size is unknown.\n\tif (block == NULL || block->version > 1\n\t\t\t|| block->header_size < LZMA_BLOCK_HEADER_SIZE_MIN\n\t\t\t|| block->header_size > LZMA_BLOCK_HEADER_SIZE_MAX\n\t\t\t|| (block->header_size & 3)\n\t\t\t|| !lzma_vli_is_valid(block->compressed_size)\n\t\t\t|| block->compressed_size == 0\n\t\t\t|| (unsigned int)(block->check) > LZMA_CHECK_ID_MAX)\n\t\treturn 0;\n\n\t// If Compressed Size is unknown, return that we cannot know\n\t// size of the Block either.\n\tif (block->compressed_size == LZMA_VLI_UNKNOWN)\n\t\treturn LZMA_VLI_UNKNOWN;\n\n\t// Calculate Unpadded Size and validate it.\n\tconst lzma_vli unpadded_size = block->compressed_size\n\t\t\t\t+ block->header_size\n\t\t\t\t+ lzma_check_size(block->check);\n\n\tassert(unpadded_size >= UNPADDED_SIZE_MIN);\n\tif (unpadded_size > UNPADDED_SIZE_MAX)\n\t\treturn 0;\n\n\treturn unpadded_size;\n}\n\n\nextern LZMA_API(lzma_vli)\nlzma_block_total_size(const lzma_block *block)\n{\n\tlzma_vli unpadded_size = lzma_block_unpadded_size(block);\n\n\tif (unpadded_size != LZMA_VLI_UNKNOWN)\n\t\tunpadded_size = vli_ceil4(unpadded_size);\n\n\treturn unpadded_size;\n}\n"
  },
  {
    "path": "external/xz/liblzma/common/common.c",
    "content": "///////////////////////////////////////////////////////////////////////////////\n//\n/// \\file       common.c\n/// \\brief      Common functions needed in many places in liblzma\n//\n//  Author:     Lasse Collin\n//\n//  This file has been put into the public domain.\n//  You can do whatever you want with this file.\n//\n///////////////////////////////////////////////////////////////////////////////\n\n#include \"common.h\"\n\n\n/////////////\n// Version //\n/////////////\n\nextern LZMA_API(uint32_t)\nlzma_version_number(void)\n{\n\treturn LZMA_VERSION;\n}\n\n\nextern LZMA_API(const char *)\nlzma_version_string(void)\n{\n\treturn LZMA_VERSION_STRING;\n}\n\n\n///////////////////////\n// Memory allocation //\n///////////////////////\n\nextern void * lzma_attribute((__malloc__)) lzma_attr_alloc_size(1)\nlzma_alloc(size_t size, const lzma_allocator *allocator)\n{\n\t// Some malloc() variants return NULL if called with size == 0.\n\tif (size == 0)\n\t\tsize = 1;\n\n\tvoid *ptr;\n\n\tif (allocator != NULL && allocator->alloc != NULL)\n\t\tptr = allocator->alloc(allocator->opaque, 1, size);\n\telse\n\t\tptr = malloc(size);\n\n\treturn ptr;\n}\n\n\nextern void * lzma_attribute((__malloc__)) lzma_attr_alloc_size(1)\nlzma_alloc_zero(size_t size, const lzma_allocator *allocator)\n{\n\t// Some calloc() variants return NULL if called with size == 0.\n\tif (size == 0)\n\t\tsize = 1;\n\n\tvoid *ptr;\n\n\tif (allocator != NULL && allocator->alloc != NULL) {\n\t\tptr = allocator->alloc(allocator->opaque, 1, size);\n\t\tif (ptr != NULL)\n\t\t\tmemzero(ptr, size);\n\t} else {\n\t\tptr = calloc(1, size);\n\t}\n\n\treturn ptr;\n}\n\n\nextern void\nlzma_free(void *ptr, const lzma_allocator *allocator)\n{\n\tif (allocator != NULL && allocator->free != NULL)\n\t\tallocator->free(allocator->opaque, ptr);\n\telse\n\t\tfree(ptr);\n\n\treturn;\n}\n\n\n//////////\n// Misc //\n//////////\n\nextern size_t\nlzma_bufcpy(const uint8_t *restrict in, size_t *restrict in_pos,\n\t\tsize_t in_size, uint8_t *restrict out,\n\t\tsize_t *restrict out_pos, size_t out_size)\n{\n\tconst size_t in_avail = in_size - *in_pos;\n\tconst size_t out_avail = out_size - *out_pos;\n\tconst size_t copy_size = my_min(in_avail, out_avail);\n\n\t// Call memcpy() only if there is something to copy. If there is\n\t// nothing to copy, in or out might be NULL and then the memcpy()\n\t// call would trigger undefined behavior.\n\tif (copy_size > 0)\n\t\tmemcpy(out + *out_pos, in + *in_pos, copy_size);\n\n\t*in_pos += copy_size;\n\t*out_pos += copy_size;\n\n\treturn copy_size;\n}\n\n\nextern lzma_ret\nlzma_next_filter_init(lzma_next_coder *next, const lzma_allocator *allocator,\n\t\tconst lzma_filter_info *filters)\n{\n\tlzma_next_coder_init(filters[0].init, next, allocator);\n\tnext->id = filters[0].id;\n\treturn filters[0].init == NULL\n\t\t\t? LZMA_OK : filters[0].init(next, allocator, filters);\n}\n\n\nextern lzma_ret\nlzma_next_filter_update(lzma_next_coder *next, const lzma_allocator *allocator,\n\t\tconst lzma_filter *reversed_filters)\n{\n\t// Check that the application isn't trying to change the Filter ID.\n\t// End of filters is indicated with LZMA_VLI_UNKNOWN in both\n\t// reversed_filters[0].id and next->id.\n\tif (reversed_filters[0].id != next->id)\n\t\treturn LZMA_PROG_ERROR;\n\n\tif (reversed_filters[0].id == LZMA_VLI_UNKNOWN)\n\t\treturn LZMA_OK;\n\n\tassert(next->update != NULL);\n\treturn next->update(next->coder, allocator, NULL, reversed_filters);\n}\n\n\nextern void\nlzma_next_end(lzma_next_coder *next, const lzma_allocator *allocator)\n{\n\tif (next->init != (uintptr_t)(NULL)) {\n\t\t// To avoid tiny end functions that simply call\n\t\t// lzma_free(coder, allocator), we allow leaving next->end\n\t\t// NULL and call lzma_free() here.\n\t\tif (next->end != NULL)\n\t\t\tnext->end(next->coder, allocator);\n\t\telse\n\t\t\tlzma_free(next->coder, allocator);\n\n\t\t// Reset the variables so the we don't accidentally think\n\t\t// that it is an already initialized coder.\n\t\t*next = LZMA_NEXT_CODER_INIT;\n\t}\n\n\treturn;\n}\n\n\n//////////////////////////////////////\n// External to internal API wrapper //\n//////////////////////////////////////\n\nextern lzma_ret\nlzma_strm_init(lzma_stream *strm)\n{\n\tif (strm == NULL)\n\t\treturn LZMA_PROG_ERROR;\n\n\tif (strm->internal == NULL) {\n\t\tstrm->internal = lzma_alloc(sizeof(lzma_internal),\n\t\t\t\tstrm->allocator);\n\t\tif (strm->internal == NULL)\n\t\t\treturn LZMA_MEM_ERROR;\n\n\t\tstrm->internal->next = LZMA_NEXT_CODER_INIT;\n\t}\n\n\tmemzero(strm->internal->supported_actions,\n\t\t\tsizeof(strm->internal->supported_actions));\n\tstrm->internal->sequence = ISEQ_RUN;\n\tstrm->internal->allow_buf_error = false;\n\n\tstrm->total_in = 0;\n\tstrm->total_out = 0;\n\n\treturn LZMA_OK;\n}\n\n\nextern LZMA_API(lzma_ret)\nlzma_code(lzma_stream *strm, lzma_action action)\n{\n\t// Sanity checks\n\tif ((strm->next_in == NULL && strm->avail_in != 0)\n\t\t\t|| (strm->next_out == NULL && strm->avail_out != 0)\n\t\t\t|| strm->internal == NULL\n\t\t\t|| strm->internal->next.code == NULL\n\t\t\t|| (unsigned int)(action) > LZMA_ACTION_MAX\n\t\t\t|| !strm->internal->supported_actions[action])\n\t\treturn LZMA_PROG_ERROR;\n\n\t// Check if unsupported members have been set to non-zero or non-NULL,\n\t// which would indicate that some new feature is wanted.\n\tif (strm->reserved_ptr1 != NULL\n\t\t\t|| strm->reserved_ptr2 != NULL\n\t\t\t|| strm->reserved_ptr3 != NULL\n\t\t\t|| strm->reserved_ptr4 != NULL\n\t\t\t|| strm->reserved_int1 != 0\n\t\t\t|| strm->reserved_int2 != 0\n\t\t\t|| strm->reserved_int3 != 0\n\t\t\t|| strm->reserved_int4 != 0\n\t\t\t|| strm->reserved_enum1 != LZMA_RESERVED_ENUM\n\t\t\t|| strm->reserved_enum2 != LZMA_RESERVED_ENUM)\n\t\treturn LZMA_OPTIONS_ERROR;\n\n\tswitch (strm->internal->sequence) {\n\tcase ISEQ_RUN:\n\t\tswitch (action) {\n\t\tcase LZMA_RUN:\n\t\t\tbreak;\n\n\t\tcase LZMA_SYNC_FLUSH:\n\t\t\tstrm->internal->sequence = ISEQ_SYNC_FLUSH;\n\t\t\tbreak;\n\n\t\tcase LZMA_FULL_FLUSH:\n\t\t\tstrm->internal->sequence = ISEQ_FULL_FLUSH;\n\t\t\tbreak;\n\n\t\tcase LZMA_FINISH:\n\t\t\tstrm->internal->sequence = ISEQ_FINISH;\n\t\t\tbreak;\n\n\t\tcase LZMA_FULL_BARRIER:\n\t\t\tstrm->internal->sequence = ISEQ_FULL_BARRIER;\n\t\t\tbreak;\n\t\t}\n\n\t\tbreak;\n\n\tcase ISEQ_SYNC_FLUSH:\n\t\t// The same action must be used until we return\n\t\t// LZMA_STREAM_END, and the amount of input must not change.\n\t\tif (action != LZMA_SYNC_FLUSH\n\t\t\t\t|| strm->internal->avail_in != strm->avail_in)\n\t\t\treturn LZMA_PROG_ERROR;\n\n\t\tbreak;\n\n\tcase ISEQ_FULL_FLUSH:\n\t\tif (action != LZMA_FULL_FLUSH\n\t\t\t\t|| strm->internal->avail_in != strm->avail_in)\n\t\t\treturn LZMA_PROG_ERROR;\n\n\t\tbreak;\n\n\tcase ISEQ_FINISH:\n\t\tif (action != LZMA_FINISH\n\t\t\t\t|| strm->internal->avail_in != strm->avail_in)\n\t\t\treturn LZMA_PROG_ERROR;\n\n\t\tbreak;\n\n\tcase ISEQ_FULL_BARRIER:\n\t\tif (action != LZMA_FULL_BARRIER\n\t\t\t\t|| strm->internal->avail_in != strm->avail_in)\n\t\t\treturn LZMA_PROG_ERROR;\n\n\t\tbreak;\n\n\tcase ISEQ_END:\n\t\treturn LZMA_STREAM_END;\n\n\tcase ISEQ_ERROR:\n\tdefault:\n\t\treturn LZMA_PROG_ERROR;\n\t}\n\n\tsize_t in_pos = 0;\n\tsize_t out_pos = 0;\n\tlzma_ret ret = strm->internal->next.code(\n\t\t\tstrm->internal->next.coder, strm->allocator,\n\t\t\tstrm->next_in, &in_pos, strm->avail_in,\n\t\t\tstrm->next_out, &out_pos, strm->avail_out, action);\n\n\tstrm->next_in += in_pos;\n\tstrm->avail_in -= in_pos;\n\tstrm->total_in += in_pos;\n\n\tstrm->next_out += out_pos;\n\tstrm->avail_out -= out_pos;\n\tstrm->total_out += out_pos;\n\n\tstrm->internal->avail_in = strm->avail_in;\n\n\t// Cast is needed to silence a warning about LZMA_TIMED_OUT, which\n\t// isn't part of lzma_ret enumeration.\n\tswitch ((unsigned int)(ret)) {\n\tcase LZMA_OK:\n\t\t// Don't return LZMA_BUF_ERROR when it happens the first time.\n\t\t// This is to avoid returning LZMA_BUF_ERROR when avail_out\n\t\t// was zero but still there was no more data left to written\n\t\t// to next_out.\n\t\tif (out_pos == 0 && in_pos == 0) {\n\t\t\tif (strm->internal->allow_buf_error)\n\t\t\t\tret = LZMA_BUF_ERROR;\n\t\t\telse\n\t\t\t\tstrm->internal->allow_buf_error = true;\n\t\t} else {\n\t\t\tstrm->internal->allow_buf_error = false;\n\t\t}\n\t\tbreak;\n\n\tcase LZMA_TIMED_OUT:\n\t\tstrm->internal->allow_buf_error = false;\n\t\tret = LZMA_OK;\n\t\tbreak;\n\n\tcase LZMA_STREAM_END:\n\t\tif (strm->internal->sequence == ISEQ_SYNC_FLUSH\n\t\t\t\t|| strm->internal->sequence == ISEQ_FULL_FLUSH\n\t\t\t\t|| strm->internal->sequence\n\t\t\t\t\t== ISEQ_FULL_BARRIER)\n\t\t\tstrm->internal->sequence = ISEQ_RUN;\n\t\telse\n\t\t\tstrm->internal->sequence = ISEQ_END;\n\n\t// Fall through\n\n\tcase LZMA_NO_CHECK:\n\tcase LZMA_UNSUPPORTED_CHECK:\n\tcase LZMA_GET_CHECK:\n\tcase LZMA_MEMLIMIT_ERROR:\n\t\t// Something else than LZMA_OK, but not a fatal error,\n\t\t// that is, coding may be continued (except if ISEQ_END).\n\t\tstrm->internal->allow_buf_error = false;\n\t\tbreak;\n\n\tdefault:\n\t\t// All the other errors are fatal; coding cannot be continued.\n\t\tassert(ret != LZMA_BUF_ERROR);\n\t\tstrm->internal->sequence = ISEQ_ERROR;\n\t\tbreak;\n\t}\n\n\treturn ret;\n}\n\n\nextern LZMA_API(void)\nlzma_end(lzma_stream *strm)\n{\n\tif (strm != NULL && strm->internal != NULL) {\n\t\tlzma_next_end(&strm->internal->next, strm->allocator);\n\t\tlzma_free(strm->internal, strm->allocator);\n\t\tstrm->internal = NULL;\n\t}\n\n\treturn;\n}\n\n\nextern LZMA_API(void)\nlzma_get_progress(lzma_stream *strm,\n\t\tuint64_t *progress_in, uint64_t *progress_out)\n{\n\tif (strm->internal->next.get_progress != NULL) {\n\t\tstrm->internal->next.get_progress(strm->internal->next.coder,\n\t\t\t\tprogress_in, progress_out);\n\t} else {\n\t\t*progress_in = strm->total_in;\n\t\t*progress_out = strm->total_out;\n\t}\n\n\treturn;\n}\n\n\nextern LZMA_API(lzma_check)\nlzma_get_check(const lzma_stream *strm)\n{\n\t// Return LZMA_CHECK_NONE if we cannot know the check type.\n\t// It's a bug in the application if this happens.\n\tif (strm->internal->next.get_check == NULL)\n\t\treturn LZMA_CHECK_NONE;\n\n\treturn strm->internal->next.get_check(strm->internal->next.coder);\n}\n\n\nextern LZMA_API(uint64_t)\nlzma_memusage(const lzma_stream *strm)\n{\n\tuint64_t memusage;\n\tuint64_t old_memlimit;\n\n\tif (strm == NULL || strm->internal == NULL\n\t\t\t|| strm->internal->next.memconfig == NULL\n\t\t\t|| strm->internal->next.memconfig(\n\t\t\t\tstrm->internal->next.coder,\n\t\t\t\t&memusage, &old_memlimit, 0) != LZMA_OK)\n\t\treturn 0;\n\n\treturn memusage;\n}\n\n\nextern LZMA_API(uint64_t)\nlzma_memlimit_get(const lzma_stream *strm)\n{\n\tuint64_t old_memlimit;\n\tuint64_t memusage;\n\n\tif (strm == NULL || strm->internal == NULL\n\t\t\t|| strm->internal->next.memconfig == NULL\n\t\t\t|| strm->internal->next.memconfig(\n\t\t\t\tstrm->internal->next.coder,\n\t\t\t\t&memusage, &old_memlimit, 0) != LZMA_OK)\n\t\treturn 0;\n\n\treturn old_memlimit;\n}\n\n\nextern LZMA_API(lzma_ret)\nlzma_memlimit_set(lzma_stream *strm, uint64_t new_memlimit)\n{\n\t// Dummy variables to simplify memconfig functions\n\tuint64_t old_memlimit;\n\tuint64_t memusage;\n\n\tif (strm == NULL || strm->internal == NULL\n\t\t\t|| strm->internal->next.memconfig == NULL)\n\t\treturn LZMA_PROG_ERROR;\n\n\t// Zero is a special value that cannot be used as an actual limit.\n\t// If 0 was specified, use 1 instead.\n\tif (new_memlimit == 0)\n\t\tnew_memlimit = 1;\n\n\treturn strm->internal->next.memconfig(strm->internal->next.coder,\n\t\t\t&memusage, &old_memlimit, new_memlimit);\n}\n"
  },
  {
    "path": "external/xz/liblzma/common/common.h",
    "content": "///////////////////////////////////////////////////////////////////////////////\n//\n/// \\file       common.h\n/// \\brief      Definitions common to the whole liblzma library\n//\n//  Author:     Lasse Collin\n//\n//  This file has been put into the public domain.\n//  You can do whatever you want with this file.\n//\n///////////////////////////////////////////////////////////////////////////////\n\n#ifndef LZMA_COMMON_H\n#define LZMA_COMMON_H\n\n#include \"sysdefs.h\"\n#include \"mythread.h\"\n#include \"tuklib_integer.h\"\n\n#if defined(_WIN32) || defined(__CYGWIN__)\n#\tifdef DLL_EXPORT\n#\t\tdefine LZMA_API_EXPORT __declspec(dllexport)\n#\telse\n#\t\tdefine LZMA_API_EXPORT\n#\tendif\n// Don't use ifdef or defined() below.\n#elif HAVE_VISIBILITY\n#\tdefine LZMA_API_EXPORT __attribute__((__visibility__(\"default\")))\n#else\n#\tdefine LZMA_API_EXPORT\n#endif\n\n#define LZMA_API(type) LZMA_API_EXPORT type LZMA_API_CALL\n\n#include \"lzma.h\"\n\n// These allow helping the compiler in some often-executed branches, whose\n// result is almost always the same.\n#ifdef __GNUC__\n#\tdefine likely(expr) __builtin_expect(expr, true)\n#\tdefine unlikely(expr) __builtin_expect(expr, false)\n#else\n#\tdefine likely(expr) (expr)\n#\tdefine unlikely(expr) (expr)\n#endif\n\n\n/// Size of temporary buffers needed in some filters\n#define LZMA_BUFFER_SIZE 4096\n\n\n/// Maximum number of worker threads within one multithreaded component.\n/// The limit exists solely to make it simpler to prevent integer overflows\n/// when allocating structures etc. This should be big enough for now...\n/// the code won't scale anywhere close to this number anyway.\n#define LZMA_THREADS_MAX 16384\n\n\n/// Starting value for memory usage estimates. Instead of calculating size\n/// of _every_ structure and taking into account malloc() overhead etc., we\n/// add a base size to all memory usage estimates. It's not very accurate\n/// but should be easily good enough.\n#define LZMA_MEMUSAGE_BASE (UINT64_C(1) << 15)\n\n/// Start of internal Filter ID space. These IDs must never be used\n/// in Streams.\n#define LZMA_FILTER_RESERVED_START (LZMA_VLI_C(1) << 62)\n\n\n/// Supported flags that can be passed to lzma_stream_decoder()\n/// or lzma_auto_decoder().\n#define LZMA_SUPPORTED_FLAGS \\\n\t( LZMA_TELL_NO_CHECK \\\n\t| LZMA_TELL_UNSUPPORTED_CHECK \\\n\t| LZMA_TELL_ANY_CHECK \\\n\t| LZMA_IGNORE_CHECK \\\n\t| LZMA_CONCATENATED )\n\n\n/// Largest valid lzma_action value as unsigned integer.\n#define LZMA_ACTION_MAX ((unsigned int)(LZMA_FULL_BARRIER))\n\n\n/// Special return value (lzma_ret) to indicate that a timeout was reached\n/// and lzma_code() must not return LZMA_BUF_ERROR. This is converted to\n/// LZMA_OK in lzma_code(). This is not in the lzma_ret enumeration because\n/// there's no need to have it in the public API.\n#define LZMA_TIMED_OUT 32\n\n\ntypedef struct lzma_next_coder_s lzma_next_coder;\n\ntypedef struct lzma_filter_info_s lzma_filter_info;\n\n\n/// Type of a function used to initialize a filter encoder or decoder\ntypedef lzma_ret (*lzma_init_function)(\n\t\tlzma_next_coder *next, const lzma_allocator *allocator,\n\t\tconst lzma_filter_info *filters);\n\n/// Type of a function to do some kind of coding work (filters, Stream,\n/// Block encoders/decoders etc.). Some special coders use don't use both\n/// input and output buffers, but for simplicity they still use this same\n/// function prototype.\ntypedef lzma_ret (*lzma_code_function)(\n\t\tvoid *coder, const lzma_allocator *allocator,\n\t\tconst uint8_t *restrict in, size_t *restrict in_pos,\n\t\tsize_t in_size, uint8_t *restrict out,\n\t\tsize_t *restrict out_pos, size_t out_size,\n\t\tlzma_action action);\n\n/// Type of a function to free the memory allocated for the coder\ntypedef void (*lzma_end_function)(\n\t\tvoid *coder, const lzma_allocator *allocator);\n\n\n/// Raw coder validates and converts an array of lzma_filter structures to\n/// an array of lzma_filter_info structures. This array is used with\n/// lzma_next_filter_init to initialize the filter chain.\nstruct lzma_filter_info_s {\n\t/// Filter ID. This is used only by the encoder\n\t/// with lzma_filters_update().\n\tlzma_vli id;\n\n\t/// Pointer to function used to initialize the filter.\n\t/// This is NULL to indicate end of array.\n\tlzma_init_function init;\n\n\t/// Pointer to filter's options structure\n\tvoid *options;\n};\n\n\n/// Hold data and function pointers of the next filter in the chain.\nstruct lzma_next_coder_s {\n\t/// Pointer to coder-specific data\n\tvoid *coder;\n\n\t/// Filter ID. This is LZMA_VLI_UNKNOWN when this structure doesn't\n\t/// point to a filter coder.\n\tlzma_vli id;\n\n\t/// \"Pointer\" to init function. This is never called here.\n\t/// We need only to detect if we are initializing a coder\n\t/// that was allocated earlier. See lzma_next_coder_init and\n\t/// lzma_next_strm_init macros in this file.\n\tuintptr_t init;\n\n\t/// Pointer to function to do the actual coding\n\tlzma_code_function code;\n\n\t/// Pointer to function to free lzma_next_coder.coder. This can\n\t/// be NULL; in that case, lzma_free is called to free\n\t/// lzma_next_coder.coder.\n\tlzma_end_function end;\n\n\t/// Pointer to a function to get progress information. If this is NULL,\n\t/// lzma_stream.total_in and .total_out are used instead.\n\tvoid (*get_progress)(void *coder,\n\t\t\tuint64_t *progress_in, uint64_t *progress_out);\n\n\t/// Pointer to function to return the type of the integrity check.\n\t/// Most coders won't support this.\n\tlzma_check (*get_check)(const void *coder);\n\n\t/// Pointer to function to get and/or change the memory usage limit.\n\t/// If new_memlimit == 0, the limit is not changed.\n\tlzma_ret (*memconfig)(void *coder, uint64_t *memusage,\n\t\t\tuint64_t *old_memlimit, uint64_t new_memlimit);\n\n\t/// Update the filter-specific options or the whole filter chain\n\t/// in the encoder.\n\tlzma_ret (*update)(void *coder, const lzma_allocator *allocator,\n\t\t\tconst lzma_filter *filters,\n\t\t\tconst lzma_filter *reversed_filters);\n};\n\n\n/// Macro to initialize lzma_next_coder structure\n#define LZMA_NEXT_CODER_INIT \\\n\t(lzma_next_coder){ \\\n\t\t.coder = NULL, \\\n\t\t.init = (uintptr_t)(NULL), \\\n\t\t.id = LZMA_VLI_UNKNOWN, \\\n\t\t.code = NULL, \\\n\t\t.end = NULL, \\\n\t\t.get_progress = NULL, \\\n\t\t.get_check = NULL, \\\n\t\t.memconfig = NULL, \\\n\t\t.update = NULL, \\\n\t}\n\n\n/// Internal data for lzma_strm_init, lzma_code, and lzma_end. A pointer to\n/// this is stored in lzma_stream.\nstruct lzma_internal_s {\n\t/// The actual coder that should do something useful\n\tlzma_next_coder next;\n\n\t/// Track the state of the coder. This is used to validate arguments\n\t/// so that the actual coders can rely on e.g. that LZMA_SYNC_FLUSH\n\t/// is used on every call to lzma_code until next.code has returned\n\t/// LZMA_STREAM_END.\n\tenum {\n\t\tISEQ_RUN,\n\t\tISEQ_SYNC_FLUSH,\n\t\tISEQ_FULL_FLUSH,\n\t\tISEQ_FINISH,\n\t\tISEQ_FULL_BARRIER,\n\t\tISEQ_END,\n\t\tISEQ_ERROR,\n\t} sequence;\n\n\t/// A copy of lzma_stream avail_in. This is used to verify that the\n\t/// amount of input doesn't change once e.g. LZMA_FINISH has been\n\t/// used.\n\tsize_t avail_in;\n\n\t/// Indicates which lzma_action values are allowed by next.code.\n\tbool supported_actions[LZMA_ACTION_MAX + 1];\n\n\t/// If true, lzma_code will return LZMA_BUF_ERROR if no progress was\n\t/// made (no input consumed and no output produced by next.code).\n\tbool allow_buf_error;\n};\n\n\n/// Allocates memory\nextern void *lzma_alloc(size_t size, const lzma_allocator *allocator)\n\t\tlzma_attribute((__malloc__)) lzma_attr_alloc_size(1);\n\n/// Allocates memory and zeroes it (like calloc()). This can be faster\n/// than lzma_alloc() + memzero() while being backward compatible with\n/// custom allocators.\nextern void * lzma_attribute((__malloc__)) lzma_attr_alloc_size(1)\n\t\tlzma_alloc_zero(size_t size, const lzma_allocator *allocator);\n\n/// Frees memory\nextern void lzma_free(void *ptr, const lzma_allocator *allocator);\n\n\n/// Allocates strm->internal if it is NULL, and initializes *strm and\n/// strm->internal. This function is only called via lzma_next_strm_init macro.\nextern lzma_ret lzma_strm_init(lzma_stream *strm);\n\n/// Initializes the next filter in the chain, if any. This takes care of\n/// freeing the memory of previously initialized filter if it is different\n/// than the filter being initialized now. This way the actual filter\n/// initialization functions don't need to use lzma_next_coder_init macro.\nextern lzma_ret lzma_next_filter_init(lzma_next_coder *next,\n\t\tconst lzma_allocator *allocator,\n\t\tconst lzma_filter_info *filters);\n\n/// Update the next filter in the chain, if any. This checks that\n/// the application is not trying to change the Filter IDs.\nextern lzma_ret lzma_next_filter_update(\n\t\tlzma_next_coder *next, const lzma_allocator *allocator,\n\t\tconst lzma_filter *reversed_filters);\n\n/// Frees the memory allocated for next->coder either using next->end or,\n/// if next->end is NULL, using lzma_free.\nextern void lzma_next_end(lzma_next_coder *next,\n\t\tconst lzma_allocator *allocator);\n\n\n/// Copy as much data as possible from in[] to out[] and update *in_pos\n/// and *out_pos accordingly. Returns the number of bytes copied.\nextern size_t lzma_bufcpy(const uint8_t *restrict in, size_t *restrict in_pos,\n\t\tsize_t in_size, uint8_t *restrict out,\n\t\tsize_t *restrict out_pos, size_t out_size);\n\n\n/// \\brief      Return if expression doesn't evaluate to LZMA_OK\n///\n/// There are several situations where we want to return immediately\n/// with the value of expr if it isn't LZMA_OK. This macro shortens\n/// the code a little.\n#define return_if_error(expr) \\\ndo { \\\n\tconst lzma_ret ret_ = (expr); \\\n\tif (ret_ != LZMA_OK) \\\n\t\treturn ret_; \\\n} while (0)\n\n\n/// If next isn't already initialized, free the previous coder. Then mark\n/// that next is _possibly_ initialized for the coder using this macro.\n/// \"Possibly\" means that if e.g. allocation of next->coder fails, the\n/// structure isn't actually initialized for this coder, but leaving\n/// next->init to func is still OK.\n#define lzma_next_coder_init(func, next, allocator) \\\ndo { \\\n\tif ((uintptr_t)(func) != (next)->init) \\\n\t\tlzma_next_end(next, allocator); \\\n\t(next)->init = (uintptr_t)(func); \\\n} while (0)\n\n\n/// Initializes lzma_strm and calls func() to initialize strm->internal->next.\n/// (The function being called will use lzma_next_coder_init()). If\n/// initialization fails, memory that wasn't freed by func() is freed\n/// along strm->internal.\n#define lzma_next_strm_init(func, strm, ...) \\\ndo { \\\n\treturn_if_error(lzma_strm_init(strm)); \\\n\tconst lzma_ret ret_ = func(&(strm)->internal->next, \\\n\t\t\t(strm)->allocator, __VA_ARGS__); \\\n\tif (ret_ != LZMA_OK) { \\\n\t\tlzma_end(strm); \\\n\t\treturn ret_; \\\n\t} \\\n} while (0)\n\n#endif\n"
  },
  {
    "path": "external/xz/liblzma/common/easy_buffer_encoder.c",
    "content": "///////////////////////////////////////////////////////////////////////////////\n//\n/// \\file       easy_buffer_encoder.c\n/// \\brief      Easy single-call .xz Stream encoder\n//\n//  Author:     Lasse Collin\n//\n//  This file has been put into the public domain.\n//  You can do whatever you want with this file.\n//\n///////////////////////////////////////////////////////////////////////////////\n\n#include \"easy_preset.h\"\n\n\nextern LZMA_API(lzma_ret)\nlzma_easy_buffer_encode(uint32_t preset, lzma_check check,\n\t\tconst lzma_allocator *allocator, const uint8_t *in,\n\t\tsize_t in_size, uint8_t *out, size_t *out_pos, size_t out_size)\n{\n\tlzma_options_easy opt_easy;\n\tif (lzma_easy_preset(&opt_easy, preset))\n\t\treturn LZMA_OPTIONS_ERROR;\n\n\treturn lzma_stream_buffer_encode(opt_easy.filters, check,\n\t\t\tallocator, in, in_size, out, out_pos, out_size);\n}\n"
  },
  {
    "path": "external/xz/liblzma/common/easy_decoder_memusage.c",
    "content": "///////////////////////////////////////////////////////////////////////////////\n//\n/// \\file       easy_decoder_memusage.c\n/// \\brief      Decoder memory usage calculation to match easy encoder presets\n//\n//  Author:     Lasse Collin\n//\n//  This file has been put into the public domain.\n//  You can do whatever you want with this file.\n//\n///////////////////////////////////////////////////////////////////////////////\n\n#include \"easy_preset.h\"\n\n\nextern LZMA_API(uint64_t)\nlzma_easy_decoder_memusage(uint32_t preset)\n{\n\tlzma_options_easy opt_easy;\n\tif (lzma_easy_preset(&opt_easy, preset))\n\t\treturn UINT32_MAX;\n\n\treturn lzma_raw_decoder_memusage(opt_easy.filters);\n}\n"
  },
  {
    "path": "external/xz/liblzma/common/easy_encoder.c",
    "content": "///////////////////////////////////////////////////////////////////////////////\n//\n/// \\file       easy_encoder.c\n/// \\brief      Easy .xz Stream encoder initialization\n//\n//  Author:     Lasse Collin\n//\n//  This file has been put into the public domain.\n//  You can do whatever you want with this file.\n//\n///////////////////////////////////////////////////////////////////////////////\n\n#include \"easy_preset.h\"\n\n\nextern LZMA_API(lzma_ret)\nlzma_easy_encoder(lzma_stream *strm, uint32_t preset, lzma_check check)\n{\n\tlzma_options_easy opt_easy;\n\tif (lzma_easy_preset(&opt_easy, preset))\n\t\treturn LZMA_OPTIONS_ERROR;\n\n\treturn lzma_stream_encoder(strm, opt_easy.filters, check);\n}\n"
  },
  {
    "path": "external/xz/liblzma/common/easy_encoder_memusage.c",
    "content": "///////////////////////////////////////////////////////////////////////////////\n//\n/// \\file       easy_encoder_memusage.c\n/// \\brief      Easy .xz Stream encoder memory usage calculation\n//\n//  Author:     Lasse Collin\n//\n//  This file has been put into the public domain.\n//  You can do whatever you want with this file.\n//\n///////////////////////////////////////////////////////////////////////////////\n\n#include \"easy_preset.h\"\n\n\nextern LZMA_API(uint64_t)\nlzma_easy_encoder_memusage(uint32_t preset)\n{\n\tlzma_options_easy opt_easy;\n\tif (lzma_easy_preset(&opt_easy, preset))\n\t\treturn UINT32_MAX;\n\n\treturn lzma_raw_encoder_memusage(opt_easy.filters);\n}\n"
  },
  {
    "path": "external/xz/liblzma/common/easy_preset.c",
    "content": "///////////////////////////////////////////////////////////////////////////////\n//\n/// \\file       easy_preset.c\n/// \\brief      Preset handling for easy encoder and decoder\n//\n//  Author:     Lasse Collin\n//\n//  This file has been put into the public domain.\n//  You can do whatever you want with this file.\n//\n///////////////////////////////////////////////////////////////////////////////\n\n#include \"easy_preset.h\"\n\n\nextern bool\nlzma_easy_preset(lzma_options_easy *opt_easy, uint32_t preset)\n{\n\tif (lzma_lzma_preset(&opt_easy->opt_lzma, preset))\n\t\treturn true;\n\n\topt_easy->filters[0].id = LZMA_FILTER_LZMA2;\n\topt_easy->filters[0].options = &opt_easy->opt_lzma;\n\topt_easy->filters[1].id = LZMA_VLI_UNKNOWN;\n\n\treturn false;\n}\n"
  },
  {
    "path": "external/xz/liblzma/common/easy_preset.h",
    "content": "///////////////////////////////////////////////////////////////////////////////\n//\n/// \\file       easy_preset.h\n/// \\brief      Preset handling for easy encoder and decoder\n//\n//  Author:     Lasse Collin\n//\n//  This file has been put into the public domain.\n//  You can do whatever you want with this file.\n//\n///////////////////////////////////////////////////////////////////////////////\n\n#include \"common.h\"\n\n\ntypedef struct {\n\t/// We need to keep the filters array available in case\n\t/// LZMA_FULL_FLUSH is used.\n\tlzma_filter filters[LZMA_FILTERS_MAX + 1];\n\n\t/// Options for LZMA2\n\tlzma_options_lzma opt_lzma;\n\n\t// Options for more filters can be added later, so this struct\n\t// is not ready to be put into the public API.\n\n} lzma_options_easy;\n\n\n/// Set *easy to the settings given by the preset. Returns true on error,\n/// false on success.\nextern bool lzma_easy_preset(lzma_options_easy *easy, uint32_t preset);\n"
  },
  {
    "path": "external/xz/liblzma/common/filter_buffer_decoder.c",
    "content": "///////////////////////////////////////////////////////////////////////////////\n//\n/// \\file       filter_buffer_decoder.c\n/// \\brief      Single-call raw decoding\n//\n//  Author:     Lasse Collin\n//\n//  This file has been put into the public domain.\n//  You can do whatever you want with this file.\n//\n///////////////////////////////////////////////////////////////////////////////\n\n#include \"filter_decoder.h\"\n\n\nextern LZMA_API(lzma_ret)\nlzma_raw_buffer_decode(\n\t\tconst lzma_filter *filters, const lzma_allocator *allocator,\n\t\tconst uint8_t *in, size_t *in_pos, size_t in_size,\n\t\tuint8_t *out, size_t *out_pos, size_t out_size)\n{\n\t// Validate what isn't validated later in filter_common.c.\n\tif (in == NULL || in_pos == NULL || *in_pos > in_size || out == NULL\n\t\t\t|| out_pos == NULL || *out_pos > out_size)\n\t\treturn LZMA_PROG_ERROR;\n\n\t// Initialize the decoer.\n\tlzma_next_coder next = LZMA_NEXT_CODER_INIT;\n\treturn_if_error(lzma_raw_decoder_init(&next, allocator, filters));\n\n\t// Store the positions so that we can restore them if something\n\t// goes wrong.\n\tconst size_t in_start = *in_pos;\n\tconst size_t out_start = *out_pos;\n\n\t// Do the actual decoding and free decoder's memory.\n\tlzma_ret ret = next.code(next.coder, allocator, in, in_pos, in_size,\n\t\t\tout, out_pos, out_size, LZMA_FINISH);\n\n\tif (ret == LZMA_STREAM_END) {\n\t\tret = LZMA_OK;\n\t} else {\n\t\tif (ret == LZMA_OK) {\n\t\t\t// Either the input was truncated or the\n\t\t\t// output buffer was too small.\n\t\t\tassert(*in_pos == in_size || *out_pos == out_size);\n\n\t\t\tif (*in_pos != in_size) {\n\t\t\t\t// Since input wasn't consumed completely,\n\t\t\t\t// the output buffer became full and is\n\t\t\t\t// too small.\n\t\t\t\tret = LZMA_BUF_ERROR;\n\n\t\t\t} else if (*out_pos != out_size) {\n\t\t\t\t// Since output didn't became full, the input\n\t\t\t\t// has to be truncated.\n\t\t\t\tret = LZMA_DATA_ERROR;\n\n\t\t\t} else {\n\t\t\t\t// All the input was consumed and output\n\t\t\t\t// buffer is full. Now we don't immediately\n\t\t\t\t// know the reason for the error. Try\n\t\t\t\t// decoding one more byte. If it succeeds,\n\t\t\t\t// then the output buffer was too small. If\n\t\t\t\t// we cannot get a new output byte, the input\n\t\t\t\t// is truncated.\n\t\t\t\tuint8_t tmp[1];\n\t\t\t\tsize_t tmp_pos = 0;\n\t\t\t\t(void)next.code(next.coder, allocator,\n\t\t\t\t\t\tin, in_pos, in_size,\n\t\t\t\t\t\ttmp, &tmp_pos, 1, LZMA_FINISH);\n\n\t\t\t\tif (tmp_pos == 1)\n\t\t\t\t\tret = LZMA_BUF_ERROR;\n\t\t\t\telse\n\t\t\t\t\tret = LZMA_DATA_ERROR;\n\t\t\t}\n\t\t}\n\n\t\t// Restore the positions.\n\t\t*in_pos = in_start;\n\t\t*out_pos = out_start;\n\t}\n\n\tlzma_next_end(&next, allocator);\n\n\treturn ret;\n}\n"
  },
  {
    "path": "external/xz/liblzma/common/filter_buffer_encoder.c",
    "content": "///////////////////////////////////////////////////////////////////////////////\n//\n/// \\file       filter_buffer_encoder.c\n/// \\brief      Single-call raw encoding\n//\n//  Author:     Lasse Collin\n//\n//  This file has been put into the public domain.\n//  You can do whatever you want with this file.\n//\n///////////////////////////////////////////////////////////////////////////////\n\n#include \"filter_encoder.h\"\n\n\nextern LZMA_API(lzma_ret)\nlzma_raw_buffer_encode(\n\t\tconst lzma_filter *filters, const lzma_allocator *allocator,\n\t\tconst uint8_t *in, size_t in_size,\n\t\tuint8_t *out, size_t *out_pos, size_t out_size)\n{\n\t// Validate what isn't validated later in filter_common.c.\n\tif ((in == NULL && in_size != 0) || out == NULL\n\t\t\t|| out_pos == NULL || *out_pos > out_size)\n\t\treturn LZMA_PROG_ERROR;\n\n\t// Initialize the encoder\n\tlzma_next_coder next = LZMA_NEXT_CODER_INIT;\n\treturn_if_error(lzma_raw_encoder_init(&next, allocator, filters));\n\n\t// Store the output position so that we can restore it if\n\t// something goes wrong.\n\tconst size_t out_start = *out_pos;\n\n\t// Do the actual encoding and free coder's memory.\n\tsize_t in_pos = 0;\n\tlzma_ret ret = next.code(next.coder, allocator, in, &in_pos, in_size,\n\t\t\tout, out_pos, out_size, LZMA_FINISH);\n\tlzma_next_end(&next, allocator);\n\n\tif (ret == LZMA_STREAM_END) {\n\t\tret = LZMA_OK;\n\t} else {\n\t\tif (ret == LZMA_OK) {\n\t\t\t// Output buffer was too small.\n\t\t\tassert(*out_pos == out_size);\n\t\t\tret = LZMA_BUF_ERROR;\n\t\t}\n\n\t\t// Restore the output position.\n\t\t*out_pos = out_start;\n\t}\n\n\treturn ret;\n}\n"
  },
  {
    "path": "external/xz/liblzma/common/filter_common.c",
    "content": "///////////////////////////////////////////////////////////////////////////////\n//\n/// \\file       filter_common.c\n/// \\brief      Filter-specific stuff common for both encoder and decoder\n//\n//  Author:     Lasse Collin\n//\n//  This file has been put into the public domain.\n//  You can do whatever you want with this file.\n//\n///////////////////////////////////////////////////////////////////////////////\n\n#include \"filter_common.h\"\n\n\nstatic const struct {\n\t/// Filter ID\n\tlzma_vli id;\n\n\t/// Size of the filter-specific options structure\n\tsize_t options_size;\n\n\t/// True if it is OK to use this filter as non-last filter in\n\t/// the chain.\n\tbool non_last_ok;\n\n\t/// True if it is OK to use this filter as the last filter in\n\t/// the chain.\n\tbool last_ok;\n\n\t/// True if the filter may change the size of the data (that is, the\n\t/// amount of encoded output can be different than the amount of\n\t/// uncompressed input).\n\tbool changes_size;\n\n} features[] = {\n#if defined (HAVE_ENCODER_LZMA1) || defined(HAVE_DECODER_LZMA1)\n\t{\n\t\t.id = LZMA_FILTER_LZMA1,\n\t\t.options_size = sizeof(lzma_options_lzma),\n\t\t.non_last_ok = false,\n\t\t.last_ok = true,\n\t\t.changes_size = true,\n\t},\n#endif\n#if defined(HAVE_ENCODER_LZMA2) || defined(HAVE_DECODER_LZMA2)\n\t{\n\t\t.id = LZMA_FILTER_LZMA2,\n\t\t.options_size = sizeof(lzma_options_lzma),\n\t\t.non_last_ok = false,\n\t\t.last_ok = true,\n\t\t.changes_size = true,\n\t},\n#endif\n#if defined(HAVE_ENCODER_X86) || defined(HAVE_DECODER_X86)\n\t{\n\t\t.id = LZMA_FILTER_X86,\n\t\t.options_size = sizeof(lzma_options_bcj),\n\t\t.non_last_ok = true,\n\t\t.last_ok = false,\n\t\t.changes_size = false,\n\t},\n#endif\n#if defined(HAVE_ENCODER_POWERPC) || defined(HAVE_DECODER_POWERPC)\n\t{\n\t\t.id = LZMA_FILTER_POWERPC,\n\t\t.options_size = sizeof(lzma_options_bcj),\n\t\t.non_last_ok = true,\n\t\t.last_ok = false,\n\t\t.changes_size = false,\n\t},\n#endif\n#if defined(HAVE_ENCODER_IA64) || defined(HAVE_DECODER_IA64)\n\t{\n\t\t.id = LZMA_FILTER_IA64,\n\t\t.options_size = sizeof(lzma_options_bcj),\n\t\t.non_last_ok = true,\n\t\t.last_ok = false,\n\t\t.changes_size = false,\n\t},\n#endif\n#if defined(HAVE_ENCODER_ARM) || defined(HAVE_DECODER_ARM)\n\t{\n\t\t.id = LZMA_FILTER_ARM,\n\t\t.options_size = sizeof(lzma_options_bcj),\n\t\t.non_last_ok = true,\n\t\t.last_ok = false,\n\t\t.changes_size = false,\n\t},\n#endif\n#if defined(HAVE_ENCODER_ARMTHUMB) || defined(HAVE_DECODER_ARMTHUMB)\n\t{\n\t\t.id = LZMA_FILTER_ARMTHUMB,\n\t\t.options_size = sizeof(lzma_options_bcj),\n\t\t.non_last_ok = true,\n\t\t.last_ok = false,\n\t\t.changes_size = false,\n\t},\n#endif\n#if defined(HAVE_ENCODER_SPARC) || defined(HAVE_DECODER_SPARC)\n\t{\n\t\t.id = LZMA_FILTER_SPARC,\n\t\t.options_size = sizeof(lzma_options_bcj),\n\t\t.non_last_ok = true,\n\t\t.last_ok = false,\n\t\t.changes_size = false,\n\t},\n#endif\n#if defined(HAVE_ENCODER_DELTA) || defined(HAVE_DECODER_DELTA)\n\t{\n\t\t.id = LZMA_FILTER_DELTA,\n\t\t.options_size = sizeof(lzma_options_delta),\n\t\t.non_last_ok = true,\n\t\t.last_ok = false,\n\t\t.changes_size = false,\n\t},\n#endif\n\t{\n\t\t.id = LZMA_VLI_UNKNOWN\n\t}\n};\n\n\nextern LZMA_API(lzma_ret)\nlzma_filters_copy(const lzma_filter *src, lzma_filter *dest,\n\t\tconst lzma_allocator *allocator)\n{\n\tif (src == NULL || dest == NULL)\n\t\treturn LZMA_PROG_ERROR;\n\n\tlzma_ret ret;\n\tsize_t i;\n\tfor (i = 0; src[i].id != LZMA_VLI_UNKNOWN; ++i) {\n\t\t// There must be a maximum of four filters plus\n\t\t// the array terminator.\n\t\tif (i == LZMA_FILTERS_MAX) {\n\t\t\tret = LZMA_OPTIONS_ERROR;\n\t\t\tgoto error;\n\t\t}\n\n\t\tdest[i].id = src[i].id;\n\n\t\tif (src[i].options == NULL) {\n\t\t\tdest[i].options = NULL;\n\t\t} else {\n\t\t\t// See if the filter is supported only when the\n\t\t\t// options is not NULL. This might be convenient\n\t\t\t// sometimes if the app is actually copying only\n\t\t\t// a partial filter chain with a place holder ID.\n\t\t\t//\n\t\t\t// When options is not NULL, the Filter ID must be\n\t\t\t// supported by us, because otherwise we don't know\n\t\t\t// how big the options are.\n\t\t\tsize_t j;\n\t\t\tfor (j = 0; src[i].id != features[j].id; ++j) {\n\t\t\t\tif (features[j].id == LZMA_VLI_UNKNOWN) {\n\t\t\t\t\tret = LZMA_OPTIONS_ERROR;\n\t\t\t\t\tgoto error;\n\t\t\t\t}\n\t\t\t}\n\n\t\t\t// Allocate and copy the options.\n\t\t\tdest[i].options = lzma_alloc(features[j].options_size,\n\t\t\t\t\tallocator);\n\t\t\tif (dest[i].options == NULL) {\n\t\t\t\tret = LZMA_MEM_ERROR;\n\t\t\t\tgoto error;\n\t\t\t}\n\n\t\t\tmemcpy(dest[i].options, src[i].options,\n\t\t\t\t\tfeatures[j].options_size);\n\t\t}\n\t}\n\n\t// Terminate the filter array.\n\tassert(i <= LZMA_FILTERS_MAX + 1);\n\tdest[i].id = LZMA_VLI_UNKNOWN;\n\tdest[i].options = NULL;\n\n\treturn LZMA_OK;\n\nerror:\n\t// Free the options which we have already allocated.\n\twhile (i-- > 0) {\n\t\tlzma_free(dest[i].options, allocator);\n\t\tdest[i].options = NULL;\n\t}\n\n\treturn ret;\n}\n\n\nstatic lzma_ret\nvalidate_chain(const lzma_filter *filters, size_t *count)\n{\n\t// There must be at least one filter.\n\tif (filters == NULL || filters[0].id == LZMA_VLI_UNKNOWN)\n\t\treturn LZMA_PROG_ERROR;\n\n\t// Number of non-last filters that may change the size of the data\n\t// significantly (that is, more than 1-2 % or so).\n\tsize_t changes_size_count = 0;\n\n\t// True if it is OK to add a new filter after the current filter.\n\tbool non_last_ok = true;\n\n\t// True if the last filter in the given chain is actually usable as\n\t// the last filter. Only filters that support embedding End of Payload\n\t// Marker can be used as the last filter in the chain.\n\tbool last_ok = false;\n\n\tsize_t i = 0;\n\tdo {\n\t\tsize_t j;\n\t\tfor (j = 0; filters[i].id != features[j].id; ++j)\n\t\t\tif (features[j].id == LZMA_VLI_UNKNOWN)\n\t\t\t\treturn LZMA_OPTIONS_ERROR;\n\n\t\t// If the previous filter in the chain cannot be a non-last\n\t\t// filter, the chain is invalid.\n\t\tif (!non_last_ok)\n\t\t\treturn LZMA_OPTIONS_ERROR;\n\n\t\tnon_last_ok = features[j].non_last_ok;\n\t\tlast_ok = features[j].last_ok;\n\t\tchanges_size_count += features[j].changes_size;\n\n\t} while (filters[++i].id != LZMA_VLI_UNKNOWN);\n\n\t// There must be 1-4 filters. The last filter must be usable as\n\t// the last filter in the chain. A maximum of three filters are\n\t// allowed to change the size of the data.\n\tif (i > LZMA_FILTERS_MAX || !last_ok || changes_size_count > 3)\n\t\treturn LZMA_OPTIONS_ERROR;\n\n\t*count = i;\n\treturn LZMA_OK;\n}\n\n\nextern lzma_ret\nlzma_raw_coder_init(lzma_next_coder *next, const lzma_allocator *allocator,\n\t\tconst lzma_filter *options,\n\t\tlzma_filter_find coder_find, bool is_encoder)\n{\n\t// Do some basic validation and get the number of filters.\n\tsize_t count;\n\treturn_if_error(validate_chain(options, &count));\n\n\t// Set the filter functions and copy the options pointer.\n\tlzma_filter_info filters[LZMA_FILTERS_MAX + 1];\n\tif (is_encoder) {\n\t\tfor (size_t i = 0; i < count; ++i) {\n\t\t\t// The order of the filters is reversed in the\n\t\t\t// encoder. It allows more efficient handling\n\t\t\t// of the uncompressed data.\n\t\t\tconst size_t j = count - i - 1;\n\n\t\t\tconst lzma_filter_coder *const fc\n\t\t\t\t\t= coder_find(options[i].id);\n\t\t\tif (fc == NULL || fc->init == NULL)\n\t\t\t\treturn LZMA_OPTIONS_ERROR;\n\n\t\t\tfilters[j].id = options[i].id;\n\t\t\tfilters[j].init = fc->init;\n\t\t\tfilters[j].options = options[i].options;\n\t\t}\n\t} else {\n\t\tfor (size_t i = 0; i < count; ++i) {\n\t\t\tconst lzma_filter_coder *const fc\n\t\t\t\t\t= coder_find(options[i].id);\n\t\t\tif (fc == NULL || fc->init == NULL)\n\t\t\t\treturn LZMA_OPTIONS_ERROR;\n\n\t\t\tfilters[i].id = options[i].id;\n\t\t\tfilters[i].init = fc->init;\n\t\t\tfilters[i].options = options[i].options;\n\t\t}\n\t}\n\n\t// Terminate the array.\n\tfilters[count].id = LZMA_VLI_UNKNOWN;\n\tfilters[count].init = NULL;\n\n\t// Initialize the filters.\n\tconst lzma_ret ret = lzma_next_filter_init(next, allocator, filters);\n\tif (ret != LZMA_OK)\n\t\tlzma_next_end(next, allocator);\n\n\treturn ret;\n}\n\n\nextern uint64_t\nlzma_raw_coder_memusage(lzma_filter_find coder_find,\n\t\tconst lzma_filter *filters)\n{\n\t// The chain has to have at least one filter.\n\t{\n\t\tsize_t tmp;\n\t\tif (validate_chain(filters, &tmp) != LZMA_OK)\n\t\t\treturn UINT64_MAX;\n\t}\n\n\tuint64_t total = 0;\n\tsize_t i = 0;\n\n\tdo {\n\t\tconst lzma_filter_coder *const fc\n\t\t\t\t = coder_find(filters[i].id);\n\t\tif (fc == NULL)\n\t\t\treturn UINT64_MAX; // Unsupported Filter ID\n\n\t\tif (fc->memusage == NULL) {\n\t\t\t// This filter doesn't have a function to calculate\n\t\t\t// the memory usage and validate the options. Such\n\t\t\t// filters need only little memory, so we use 1 KiB\n\t\t\t// as a good estimate. They also accept all possible\n\t\t\t// options, so there's no need to worry about lack\n\t\t\t// of validation.\n\t\t\ttotal += 1024;\n\t\t} else {\n\t\t\t// Call the filter-specific memory usage calculation\n\t\t\t// function.\n\t\t\tconst uint64_t usage\n\t\t\t\t\t= fc->memusage(filters[i].options);\n\t\t\tif (usage == UINT64_MAX)\n\t\t\t\treturn UINT64_MAX; // Invalid options\n\n\t\t\ttotal += usage;\n\t\t}\n\t} while (filters[++i].id != LZMA_VLI_UNKNOWN);\n\n\t// Add some fixed amount of extra. It's to compensate memory usage\n\t// of Stream, Block etc. coders, malloc() overhead, stack etc.\n\treturn total + LZMA_MEMUSAGE_BASE;\n}\n"
  },
  {
    "path": "external/xz/liblzma/common/filter_common.h",
    "content": "///////////////////////////////////////////////////////////////////////////////\n//\n/// \\file       filter_common.h\n/// \\brief      Filter-specific stuff common for both encoder and decoder\n//\n//  Author:     Lasse Collin\n//\n//  This file has been put into the public domain.\n//  You can do whatever you want with this file.\n//\n///////////////////////////////////////////////////////////////////////////////\n\n#ifndef LZMA_FILTER_COMMON_H\n#define LZMA_FILTER_COMMON_H\n\n#include \"common.h\"\n\n\n/// Both lzma_filter_encoder and lzma_filter_decoder begin with these members.\ntypedef struct {\n\t/// Filter ID\n\tlzma_vli id;\n\n\t/// Initializes the filter encoder and calls lzma_next_filter_init()\n\t/// for filters + 1.\n\tlzma_init_function init;\n\n\t/// Calculates memory usage of the encoder. If the options are\n\t/// invalid, UINT64_MAX is returned.\n\tuint64_t (*memusage)(const void *options);\n\n} lzma_filter_coder;\n\n\ntypedef const lzma_filter_coder *(*lzma_filter_find)(lzma_vli id);\n\n\nextern lzma_ret lzma_raw_coder_init(\n\t\tlzma_next_coder *next, const lzma_allocator *allocator,\n\t\tconst lzma_filter *filters,\n\t\tlzma_filter_find coder_find, bool is_encoder);\n\n\nextern uint64_t lzma_raw_coder_memusage(lzma_filter_find coder_find,\n\t\tconst lzma_filter *filters);\n\n\n#endif\n"
  },
  {
    "path": "external/xz/liblzma/common/filter_decoder.c",
    "content": "///////////////////////////////////////////////////////////////////////////////\n//\n/// \\file       filter_decoder.c\n/// \\brief      Filter ID mapping to filter-specific functions\n//\n//  Author:     Lasse Collin\n//\n//  This file has been put into the public domain.\n//  You can do whatever you want with this file.\n//\n///////////////////////////////////////////////////////////////////////////////\n\n#include \"filter_decoder.h\"\n#include \"filter_common.h\"\n#include \"lzma_decoder.h\"\n#include \"lzma2_decoder.h\"\n#include \"simple_decoder.h\"\n#include \"delta_decoder.h\"\n\n\ntypedef struct {\n\t/// Filter ID\n\tlzma_vli id;\n\n\t/// Initializes the filter encoder and calls lzma_next_filter_init()\n\t/// for filters + 1.\n\tlzma_init_function init;\n\n\t/// Calculates memory usage of the encoder. If the options are\n\t/// invalid, UINT64_MAX is returned.\n\tuint64_t (*memusage)(const void *options);\n\n\t/// Decodes Filter Properties.\n\t///\n\t/// \\return     - LZMA_OK: Properties decoded successfully.\n\t///             - LZMA_OPTIONS_ERROR: Unsupported properties\n\t///             - LZMA_MEM_ERROR: Memory allocation failed.\n\tlzma_ret (*props_decode)(\n\t\t\tvoid **options, const lzma_allocator *allocator,\n\t\t\tconst uint8_t *props, size_t props_size);\n\n} lzma_filter_decoder;\n\n\nstatic const lzma_filter_decoder decoders[] = {\n#ifdef HAVE_DECODER_LZMA1\n\t{\n\t\t.id = LZMA_FILTER_LZMA1,\n\t\t.init = &lzma_lzma_decoder_init,\n\t\t.memusage = &lzma_lzma_decoder_memusage,\n\t\t.props_decode = &lzma_lzma_props_decode,\n\t},\n#endif\n#ifdef HAVE_DECODER_LZMA2\n\t{\n\t\t.id = LZMA_FILTER_LZMA2,\n\t\t.init = &lzma_lzma2_decoder_init,\n\t\t.memusage = &lzma_lzma2_decoder_memusage,\n\t\t.props_decode = &lzma_lzma2_props_decode,\n\t},\n#endif\n#ifdef HAVE_DECODER_X86\n\t{\n\t\t.id = LZMA_FILTER_X86,\n\t\t.init = &lzma_simple_x86_decoder_init,\n\t\t.memusage = NULL,\n\t\t.props_decode = &lzma_simple_props_decode,\n\t},\n#endif\n#ifdef HAVE_DECODER_POWERPC\n\t{\n\t\t.id = LZMA_FILTER_POWERPC,\n\t\t.init = &lzma_simple_powerpc_decoder_init,\n\t\t.memusage = NULL,\n\t\t.props_decode = &lzma_simple_props_decode,\n\t},\n#endif\n#ifdef HAVE_DECODER_IA64\n\t{\n\t\t.id = LZMA_FILTER_IA64,\n\t\t.init = &lzma_simple_ia64_decoder_init,\n\t\t.memusage = NULL,\n\t\t.props_decode = &lzma_simple_props_decode,\n\t},\n#endif\n#ifdef HAVE_DECODER_ARM\n\t{\n\t\t.id = LZMA_FILTER_ARM,\n\t\t.init = &lzma_simple_arm_decoder_init,\n\t\t.memusage = NULL,\n\t\t.props_decode = &lzma_simple_props_decode,\n\t},\n#endif\n#ifdef HAVE_DECODER_ARMTHUMB\n\t{\n\t\t.id = LZMA_FILTER_ARMTHUMB,\n\t\t.init = &lzma_simple_armthumb_decoder_init,\n\t\t.memusage = NULL,\n\t\t.props_decode = &lzma_simple_props_decode,\n\t},\n#endif\n#ifdef HAVE_DECODER_SPARC\n\t{\n\t\t.id = LZMA_FILTER_SPARC,\n\t\t.init = &lzma_simple_sparc_decoder_init,\n\t\t.memusage = NULL,\n\t\t.props_decode = &lzma_simple_props_decode,\n\t},\n#endif\n#ifdef HAVE_DECODER_DELTA\n\t{\n\t\t.id = LZMA_FILTER_DELTA,\n\t\t.init = &lzma_delta_decoder_init,\n\t\t.memusage = &lzma_delta_coder_memusage,\n\t\t.props_decode = &lzma_delta_props_decode,\n\t},\n#endif\n};\n\n\nstatic const lzma_filter_decoder *\ndecoder_find(lzma_vli id)\n{\n\tfor (size_t i = 0; i < ARRAY_SIZE(decoders); ++i)\n\t\tif (decoders[i].id == id)\n\t\t\treturn decoders + i;\n\n\treturn NULL;\n}\n\n\nextern LZMA_API(lzma_bool)\nlzma_filter_decoder_is_supported(lzma_vli id)\n{\n\treturn decoder_find(id) != NULL;\n}\n\n\nextern lzma_ret\nlzma_raw_decoder_init(lzma_next_coder *next, const lzma_allocator *allocator,\n\t\tconst lzma_filter *options)\n{\n\treturn lzma_raw_coder_init(next, allocator,\n\t\t\toptions, (lzma_filter_find)(&decoder_find), false);\n}\n\n\nextern LZMA_API(lzma_ret)\nlzma_raw_decoder(lzma_stream *strm, const lzma_filter *options)\n{\n\tlzma_next_strm_init(lzma_raw_decoder_init, strm, options);\n\n\tstrm->internal->supported_actions[LZMA_RUN] = true;\n\tstrm->internal->supported_actions[LZMA_FINISH] = true;\n\n\treturn LZMA_OK;\n}\n\n\nextern LZMA_API(uint64_t)\nlzma_raw_decoder_memusage(const lzma_filter *filters)\n{\n\treturn lzma_raw_coder_memusage(\n\t\t\t(lzma_filter_find)(&decoder_find), filters);\n}\n\n\nextern LZMA_API(lzma_ret)\nlzma_properties_decode(lzma_filter *filter, const lzma_allocator *allocator,\n\t\tconst uint8_t *props, size_t props_size)\n{\n\t// Make it always NULL so that the caller can always safely free() it.\n\tfilter->options = NULL;\n\n\tconst lzma_filter_decoder *const fd = decoder_find(filter->id);\n\tif (fd == NULL)\n\t\treturn LZMA_OPTIONS_ERROR;\n\n\tif (fd->props_decode == NULL)\n\t\treturn props_size == 0 ? LZMA_OK : LZMA_OPTIONS_ERROR;\n\n\treturn fd->props_decode(\n\t\t\t&filter->options, allocator, props, props_size);\n}\n"
  },
  {
    "path": "external/xz/liblzma/common/filter_decoder.h",
    "content": "///////////////////////////////////////////////////////////////////////////////\n//\n/// \\file       filter_decoder.h\n/// \\brief      Filter ID mapping to filter-specific functions\n//\n//  Author:     Lasse Collin\n//\n//  This file has been put into the public domain.\n//  You can do whatever you want with this file.\n//\n///////////////////////////////////////////////////////////////////////////////\n\n#ifndef LZMA_FILTER_DECODER_H\n#define LZMA_FILTER_DECODER_H\n\n#include \"common.h\"\n\n\nextern lzma_ret lzma_raw_decoder_init(\n\t\tlzma_next_coder *next, const lzma_allocator *allocator,\n\t\tconst lzma_filter *options);\n\n#endif\n"
  },
  {
    "path": "external/xz/liblzma/common/filter_encoder.c",
    "content": "///////////////////////////////////////////////////////////////////////////////\n//\n/// \\file       filter_decoder.c\n/// \\brief      Filter ID mapping to filter-specific functions\n//\n//  Author:     Lasse Collin\n//\n//  This file has been put into the public domain.\n//  You can do whatever you want with this file.\n//\n///////////////////////////////////////////////////////////////////////////////\n\n#include \"filter_encoder.h\"\n#include \"filter_common.h\"\n#include \"lzma_encoder.h\"\n#include \"lzma2_encoder.h\"\n#include \"simple_encoder.h\"\n#include \"delta_encoder.h\"\n\n\ntypedef struct {\n\t/// Filter ID\n\tlzma_vli id;\n\n\t/// Initializes the filter encoder and calls lzma_next_filter_init()\n\t/// for filters + 1.\n\tlzma_init_function init;\n\n\t/// Calculates memory usage of the encoder. If the options are\n\t/// invalid, UINT64_MAX is returned.\n\tuint64_t (*memusage)(const void *options);\n\n\t/// Calculates the recommended Uncompressed Size for .xz Blocks to\n\t/// which the input data can be split to make multithreaded\n\t/// encoding possible. If this is NULL, it is assumed that\n\t/// the encoder is fast enough with single thread.\n\tuint64_t (*block_size)(const void *options);\n\n\t/// Tells the size of the Filter Properties field. If options are\n\t/// invalid, UINT32_MAX is returned. If this is NULL, props_size_fixed\n\t/// is used.\n\tlzma_ret (*props_size_get)(uint32_t *size, const void *options);\n\tuint32_t props_size_fixed;\n\n\t/// Encodes Filter Properties.\n\t///\n\t/// \\return     - LZMA_OK: Properties encoded successfully.\n\t///             - LZMA_OPTIONS_ERROR: Unsupported options\n\t///             - LZMA_PROG_ERROR: Invalid options or not enough\n\t///               output space\n\tlzma_ret (*props_encode)(const void *options, uint8_t *out);\n\n} lzma_filter_encoder;\n\n\nstatic const lzma_filter_encoder encoders[] = {\n#ifdef HAVE_ENCODER_LZMA1\n\t{\n\t\t.id = LZMA_FILTER_LZMA1,\n\t\t.init = &lzma_lzma_encoder_init,\n\t\t.memusage = &lzma_lzma_encoder_memusage,\n\t\t.block_size = NULL, // FIXME\n\t\t.props_size_get = NULL,\n\t\t.props_size_fixed = 5,\n\t\t.props_encode = &lzma_lzma_props_encode,\n\t},\n#endif\n#ifdef HAVE_ENCODER_LZMA2\n\t{\n\t\t.id = LZMA_FILTER_LZMA2,\n\t\t.init = &lzma_lzma2_encoder_init,\n\t\t.memusage = &lzma_lzma2_encoder_memusage,\n\t\t.block_size = &lzma_lzma2_block_size, // FIXME\n\t\t.props_size_get = NULL,\n\t\t.props_size_fixed = 1,\n\t\t.props_encode = &lzma_lzma2_props_encode,\n\t},\n#endif\n#ifdef HAVE_ENCODER_X86\n\t{\n\t\t.id = LZMA_FILTER_X86,\n\t\t.init = &lzma_simple_x86_encoder_init,\n\t\t.memusage = NULL,\n\t\t.block_size = NULL,\n\t\t.props_size_get = &lzma_simple_props_size,\n\t\t.props_encode = &lzma_simple_props_encode,\n\t},\n#endif\n#ifdef HAVE_ENCODER_POWERPC\n\t{\n\t\t.id = LZMA_FILTER_POWERPC,\n\t\t.init = &lzma_simple_powerpc_encoder_init,\n\t\t.memusage = NULL,\n\t\t.block_size = NULL,\n\t\t.props_size_get = &lzma_simple_props_size,\n\t\t.props_encode = &lzma_simple_props_encode,\n\t},\n#endif\n#ifdef HAVE_ENCODER_IA64\n\t{\n\t\t.id = LZMA_FILTER_IA64,\n\t\t.init = &lzma_simple_ia64_encoder_init,\n\t\t.memusage = NULL,\n\t\t.block_size = NULL,\n\t\t.props_size_get = &lzma_simple_props_size,\n\t\t.props_encode = &lzma_simple_props_encode,\n\t},\n#endif\n#ifdef HAVE_ENCODER_ARM\n\t{\n\t\t.id = LZMA_FILTER_ARM,\n\t\t.init = &lzma_simple_arm_encoder_init,\n\t\t.memusage = NULL,\n\t\t.block_size = NULL,\n\t\t.props_size_get = &lzma_simple_props_size,\n\t\t.props_encode = &lzma_simple_props_encode,\n\t},\n#endif\n#ifdef HAVE_ENCODER_ARMTHUMB\n\t{\n\t\t.id = LZMA_FILTER_ARMTHUMB,\n\t\t.init = &lzma_simple_armthumb_encoder_init,\n\t\t.memusage = NULL,\n\t\t.block_size = NULL,\n\t\t.props_size_get = &lzma_simple_props_size,\n\t\t.props_encode = &lzma_simple_props_encode,\n\t},\n#endif\n#ifdef HAVE_ENCODER_SPARC\n\t{\n\t\t.id = LZMA_FILTER_SPARC,\n\t\t.init = &lzma_simple_sparc_encoder_init,\n\t\t.memusage = NULL,\n\t\t.block_size = NULL,\n\t\t.props_size_get = &lzma_simple_props_size,\n\t\t.props_encode = &lzma_simple_props_encode,\n\t},\n#endif\n#ifdef HAVE_ENCODER_DELTA\n\t{\n\t\t.id = LZMA_FILTER_DELTA,\n\t\t.init = &lzma_delta_encoder_init,\n\t\t.memusage = &lzma_delta_coder_memusage,\n\t\t.block_size = NULL,\n\t\t.props_size_get = NULL,\n\t\t.props_size_fixed = 1,\n\t\t.props_encode = &lzma_delta_props_encode,\n\t},\n#endif\n};\n\n\nstatic const lzma_filter_encoder *\nencoder_find(lzma_vli id)\n{\n\tfor (size_t i = 0; i < ARRAY_SIZE(encoders); ++i)\n\t\tif (encoders[i].id == id)\n\t\t\treturn encoders + i;\n\n\treturn NULL;\n}\n\n\nextern LZMA_API(lzma_bool)\nlzma_filter_encoder_is_supported(lzma_vli id)\n{\n\treturn encoder_find(id) != NULL;\n}\n\n\nextern LZMA_API(lzma_ret)\nlzma_filters_update(lzma_stream *strm, const lzma_filter *filters)\n{\n\tif (strm->internal->next.update == NULL)\n\t\treturn LZMA_PROG_ERROR;\n\n\t// Validate the filter chain.\n\tif (lzma_raw_encoder_memusage(filters) == UINT64_MAX)\n\t\treturn LZMA_OPTIONS_ERROR;\n\n\t// The actual filter chain in the encoder is reversed. Some things\n\t// still want the normal order chain, so we provide both.\n\tsize_t count = 1;\n\twhile (filters[count].id != LZMA_VLI_UNKNOWN)\n\t\t++count;\n\n\tlzma_filter reversed_filters[LZMA_FILTERS_MAX + 1];\n\tfor (size_t i = 0; i < count; ++i)\n\t\treversed_filters[count - i - 1] = filters[i];\n\n\treversed_filters[count].id = LZMA_VLI_UNKNOWN;\n\n\treturn strm->internal->next.update(strm->internal->next.coder,\n\t\t\tstrm->allocator, filters, reversed_filters);\n}\n\n\nextern lzma_ret\nlzma_raw_encoder_init(lzma_next_coder *next, const lzma_allocator *allocator,\n\t\tconst lzma_filter *options)\n{\n\treturn lzma_raw_coder_init(next, allocator,\n\t\t\toptions, (lzma_filter_find)(&encoder_find), true);\n}\n\n\nextern LZMA_API(lzma_ret)\nlzma_raw_encoder(lzma_stream *strm, const lzma_filter *options)\n{\n\tlzma_next_strm_init(lzma_raw_coder_init, strm, options,\n\t\t\t(lzma_filter_find)(&encoder_find), true);\n\n\tstrm->internal->supported_actions[LZMA_RUN] = true;\n\tstrm->internal->supported_actions[LZMA_SYNC_FLUSH] = true;\n\tstrm->internal->supported_actions[LZMA_FINISH] = true;\n\n\treturn LZMA_OK;\n}\n\n\nextern LZMA_API(uint64_t)\nlzma_raw_encoder_memusage(const lzma_filter *filters)\n{\n\treturn lzma_raw_coder_memusage(\n\t\t\t(lzma_filter_find)(&encoder_find), filters);\n}\n\n\nextern uint64_t\nlzma_mt_block_size(const lzma_filter *filters)\n{\n\tuint64_t max = 0;\n\n\tfor (size_t i = 0; filters[i].id != LZMA_VLI_UNKNOWN; ++i) {\n\t\tconst lzma_filter_encoder *const fe\n\t\t\t\t= encoder_find(filters[i].id);\n\t\tif (fe->block_size != NULL) {\n\t\t\tconst uint64_t size\n\t\t\t\t\t= fe->block_size(filters[i].options);\n\t\t\tif (size == 0)\n\t\t\t\treturn 0;\n\n\t\t\tif (size > max)\n\t\t\t\tmax = size;\n\t\t}\n\t}\n\n\treturn max;\n}\n\n\nextern LZMA_API(lzma_ret)\nlzma_properties_size(uint32_t *size, const lzma_filter *filter)\n{\n\tconst lzma_filter_encoder *const fe = encoder_find(filter->id);\n\tif (fe == NULL) {\n\t\t// Unknown filter - if the Filter ID is a proper VLI,\n\t\t// return LZMA_OPTIONS_ERROR instead of LZMA_PROG_ERROR,\n\t\t// because it's possible that we just don't have support\n\t\t// compiled in for the requested filter.\n\t\treturn filter->id <= LZMA_VLI_MAX\n\t\t\t\t? LZMA_OPTIONS_ERROR : LZMA_PROG_ERROR;\n\t}\n\n\tif (fe->props_size_get == NULL) {\n\t\t// No props_size_get() function, use props_size_fixed.\n\t\t*size = fe->props_size_fixed;\n\t\treturn LZMA_OK;\n\t}\n\n\treturn fe->props_size_get(size, filter->options);\n}\n\n\nextern LZMA_API(lzma_ret)\nlzma_properties_encode(const lzma_filter *filter, uint8_t *props)\n{\n\tconst lzma_filter_encoder *const fe = encoder_find(filter->id);\n\tif (fe == NULL)\n\t\treturn LZMA_PROG_ERROR;\n\n\tif (fe->props_encode == NULL)\n\t\treturn LZMA_OK;\n\n\treturn fe->props_encode(filter->options, props);\n}\n"
  },
  {
    "path": "external/xz/liblzma/common/filter_encoder.h",
    "content": "///////////////////////////////////////////////////////////////////////////////\n//\n/// \\file       filter_encoder.c\n/// \\brief      Filter ID mapping to filter-specific functions\n//\n//  Author:     Lasse Collin\n//\n//  This file has been put into the public domain.\n//  You can do whatever you want with this file.\n//\n///////////////////////////////////////////////////////////////////////////////\n\n#ifndef LZMA_FILTER_ENCODER_H\n#define LZMA_FILTER_ENCODER_H\n\n#include \"common.h\"\n\n\n// FIXME: Might become a part of the public API.\nextern uint64_t lzma_mt_block_size(const lzma_filter *filters);\n\n\nextern lzma_ret lzma_raw_encoder_init(\n\t\tlzma_next_coder *next, const lzma_allocator *allocator,\n\t\tconst lzma_filter *filters);\n\n#endif\n"
  },
  {
    "path": "external/xz/liblzma/common/filter_flags_decoder.c",
    "content": "///////////////////////////////////////////////////////////////////////////////\n//\n/// \\file       filter_flags_decoder.c\n/// \\brief      Decodes a Filter Flags field\n//\n//  Author:     Lasse Collin\n//\n//  This file has been put into the public domain.\n//  You can do whatever you want with this file.\n//\n///////////////////////////////////////////////////////////////////////////////\n\n#include \"filter_decoder.h\"\n\n\nextern LZMA_API(lzma_ret)\nlzma_filter_flags_decode(\n\t\tlzma_filter *filter, const lzma_allocator *allocator,\n\t\tconst uint8_t *in, size_t *in_pos, size_t in_size)\n{\n\t// Set the pointer to NULL so the caller can always safely free it.\n\tfilter->options = NULL;\n\n\t// Filter ID\n\treturn_if_error(lzma_vli_decode(&filter->id, NULL,\n\t\t\tin, in_pos, in_size));\n\n\tif (filter->id >= LZMA_FILTER_RESERVED_START)\n\t\treturn LZMA_DATA_ERROR;\n\n\t// Size of Properties\n\tlzma_vli props_size;\n\treturn_if_error(lzma_vli_decode(&props_size, NULL,\n\t\t\tin, in_pos, in_size));\n\n\t// Filter Properties\n\tif (in_size - *in_pos < props_size)\n\t\treturn LZMA_DATA_ERROR;\n\n\tconst lzma_ret ret = lzma_properties_decode(\n\t\t\tfilter, allocator, in + *in_pos, props_size);\n\n\t*in_pos += props_size;\n\n\treturn ret;\n}\n"
  },
  {
    "path": "external/xz/liblzma/common/filter_flags_encoder.c",
    "content": "///////////////////////////////////////////////////////////////////////////////\n//\n/// \\file       filter_flags_encoder.c\n/// \\brief      Encodes a Filter Flags field\n//\n//  Author:     Lasse Collin\n//\n//  This file has been put into the public domain.\n//  You can do whatever you want with this file.\n//\n///////////////////////////////////////////////////////////////////////////////\n\n#include \"filter_encoder.h\"\n\n\nextern LZMA_API(lzma_ret)\nlzma_filter_flags_size(uint32_t *size, const lzma_filter *filter)\n{\n\tif (filter->id >= LZMA_FILTER_RESERVED_START)\n\t\treturn LZMA_PROG_ERROR;\n\n\treturn_if_error(lzma_properties_size(size, filter));\n\n\t*size += lzma_vli_size(filter->id) + lzma_vli_size(*size);\n\n\treturn LZMA_OK;\n}\n\n\nextern LZMA_API(lzma_ret)\nlzma_filter_flags_encode(const lzma_filter *filter,\n\t\tuint8_t *out, size_t *out_pos, size_t out_size)\n{\n\t// Filter ID\n\tif (filter->id >= LZMA_FILTER_RESERVED_START)\n\t\treturn LZMA_PROG_ERROR;\n\n\treturn_if_error(lzma_vli_encode(filter->id, NULL,\n\t\t\tout, out_pos, out_size));\n\n\t// Size of Properties\n\tuint32_t props_size;\n\treturn_if_error(lzma_properties_size(&props_size, filter));\n\treturn_if_error(lzma_vli_encode(props_size, NULL,\n\t\t\tout, out_pos, out_size));\n\n\t// Filter Properties\n\tif (out_size - *out_pos < props_size)\n\t\treturn LZMA_PROG_ERROR;\n\n\treturn_if_error(lzma_properties_encode(filter, out + *out_pos));\n\n\t*out_pos += props_size;\n\n\treturn LZMA_OK;\n}\n"
  },
  {
    "path": "external/xz/liblzma/common/hardware_cputhreads.c",
    "content": "///////////////////////////////////////////////////////////////////////////////\n//\n/// \\file       hardware_cputhreads.c\n/// \\brief      Get the number of CPU threads or cores\n//\n//  Author:     Lasse Collin\n//\n//  This file has been put into the public domain.\n//  You can do whatever you want with this file.\n//\n///////////////////////////////////////////////////////////////////////////////\n\n#include \"common.h\"\n\n#include \"tuklib_cpucores.h\"\n\n\nextern LZMA_API(uint32_t)\nlzma_cputhreads(void)\n{\n\treturn tuklib_cpucores();\n}\n"
  },
  {
    "path": "external/xz/liblzma/common/hardware_physmem.c",
    "content": "///////////////////////////////////////////////////////////////////////////////\n//\n/// \\file       hardware_physmem.c\n/// \\brief      Get the total amount of physical memory (RAM)\n//\n//  Author:     Jonathan Nieder\n//\n//  This file has been put into the public domain.\n//  You can do whatever you want with this file.\n//\n///////////////////////////////////////////////////////////////////////////////\n\n#include \"common.h\"\n\n#include \"tuklib_physmem.h\"\n\n\nextern LZMA_API(uint64_t)\nlzma_physmem(void)\n{\n\t// It is simpler to make lzma_physmem() a wrapper for\n\t// tuklib_physmem() than to hack appropriate symbol visibility\n\t// support for the tuklib modules.\n\treturn tuklib_physmem();\n}\n"
  },
  {
    "path": "external/xz/liblzma/common/index.c",
    "content": "///////////////////////////////////////////////////////////////////////////////\n//\n/// \\file       index.c\n/// \\brief      Handling of .xz Indexes and some other Stream information\n//\n//  Author:     Lasse Collin\n//\n//  This file has been put into the public domain.\n//  You can do whatever you want with this file.\n//\n///////////////////////////////////////////////////////////////////////////////\n\n#include \"index.h\"\n#include \"stream_flags_common.h\"\n\n\n/// \\brief      How many Records to allocate at once\n///\n/// This should be big enough to avoid making lots of tiny allocations\n/// but small enough to avoid too much unused memory at once.\n#define INDEX_GROUP_SIZE 512\n\n\n/// \\brief      How many Records can be allocated at once at maximum\n#define PREALLOC_MAX ((SIZE_MAX - sizeof(index_group)) / sizeof(index_record))\n\n\n/// \\brief      Base structure for index_stream and index_group structures\ntypedef struct index_tree_node_s index_tree_node;\nstruct index_tree_node_s {\n\t/// Uncompressed start offset of this Stream (relative to the\n\t/// beginning of the file) or Block (relative to the beginning\n\t/// of the Stream)\n\tlzma_vli uncompressed_base;\n\n\t/// Compressed start offset of this Stream or Block\n\tlzma_vli compressed_base;\n\n\tindex_tree_node *parent;\n\tindex_tree_node *left;\n\tindex_tree_node *right;\n};\n\n\n/// \\brief      AVL tree to hold index_stream or index_group structures\ntypedef struct {\n\t/// Root node\n\tindex_tree_node *root;\n\n\t/// Leftmost node. Since the tree will be filled sequentially,\n\t/// this won't change after the first node has been added to\n\t/// the tree.\n\tindex_tree_node *leftmost;\n\n\t/// The rightmost node in the tree. Since the tree is filled\n\t/// sequentially, this is always the node where to add the new data.\n\tindex_tree_node *rightmost;\n\n\t/// Number of nodes in the tree\n\tuint32_t count;\n\n} index_tree;\n\n\ntypedef struct {\n\tlzma_vli uncompressed_sum;\n\tlzma_vli unpadded_sum;\n} index_record;\n\n\ntypedef struct {\n\t/// Every Record group is part of index_stream.groups tree.\n\tindex_tree_node node;\n\n\t/// Number of Blocks in this Stream before this group.\n\tlzma_vli number_base;\n\n\t/// Number of Records that can be put in records[].\n\tsize_t allocated;\n\n\t/// Index of the last Record in use.\n\tsize_t last;\n\n\t/// The sizes in this array are stored as cumulative sums relative\n\t/// to the beginning of the Stream. This makes it possible to\n\t/// use binary search in lzma_index_locate().\n\t///\n\t/// Note that the cumulative summing is done specially for\n\t/// unpadded_sum: The previous value is rounded up to the next\n\t/// multiple of four before adding the Unpadded Size of the new\n\t/// Block. The total encoded size of the Blocks in the Stream\n\t/// is records[last].unpadded_sum in the last Record group of\n\t/// the Stream.\n\t///\n\t/// For example, if the Unpadded Sizes are 39, 57, and 81, the\n\t/// stored values are 39, 97 (40 + 57), and 181 (100 + 181).\n\t/// The total encoded size of these Blocks is 184.\n\t///\n\t/// This is a flexible array, because it makes easy to optimize\n\t/// memory usage in case someone concatenates many Streams that\n\t/// have only one or few Blocks.\n\tindex_record records[];\n\n} index_group;\n\n\ntypedef struct {\n\t/// Every index_stream is a node in the tree of Streams.\n\tindex_tree_node node;\n\n\t/// Number of this Stream (first one is 1)\n\tuint32_t number;\n\n\t/// Total number of Blocks before this Stream\n\tlzma_vli block_number_base;\n\n\t/// Record groups of this Stream are stored in a tree.\n\t/// It's a T-tree with AVL-tree balancing. There are\n\t/// INDEX_GROUP_SIZE Records per node by default.\n\t/// This keeps the number of memory allocations reasonable\n\t/// and finding a Record is fast.\n\tindex_tree groups;\n\n\t/// Number of Records in this Stream\n\tlzma_vli record_count;\n\n\t/// Size of the List of Records field in this Stream. This is used\n\t/// together with record_count to calculate the size of the Index\n\t/// field and thus the total size of the Stream.\n\tlzma_vli index_list_size;\n\n\t/// Stream Flags of this Stream. This is meaningful only if\n\t/// the Stream Flags have been told us with lzma_index_stream_flags().\n\t/// Initially stream_flags.version is set to UINT32_MAX to indicate\n\t/// that the Stream Flags are unknown.\n\tlzma_stream_flags stream_flags;\n\n\t/// Amount of Stream Padding after this Stream. This defaults to\n\t/// zero and can be set with lzma_index_stream_padding().\n\tlzma_vli stream_padding;\n\n} index_stream;\n\n\nstruct lzma_index_s {\n\t/// AVL-tree containing the Stream(s). Often there is just one\n\t/// Stream, but using a tree keeps lookups fast even when there\n\t/// are many concatenated Streams.\n\tindex_tree streams;\n\n\t/// Uncompressed size of all the Blocks in the Stream(s)\n\tlzma_vli uncompressed_size;\n\n\t/// Total size of all the Blocks in the Stream(s)\n\tlzma_vli total_size;\n\n\t/// Total number of Records in all Streams in this lzma_index\n\tlzma_vli record_count;\n\n\t/// Size of the List of Records field if all the Streams in this\n\t/// lzma_index were packed into a single Stream (makes it simpler to\n\t/// take many .xz files and combine them into a single Stream).\n\t///\n\t/// This value together with record_count is needed to calculate\n\t/// Backward Size that is stored into Stream Footer.\n\tlzma_vli index_list_size;\n\n\t/// How many Records to allocate at once in lzma_index_append().\n\t/// This defaults to INDEX_GROUP_SIZE but can be overridden with\n\t/// lzma_index_prealloc().\n\tsize_t prealloc;\n\n\t/// Bitmask indicating what integrity check types have been used\n\t/// as set by lzma_index_stream_flags(). The bit of the last Stream\n\t/// is not included here, since it is possible to change it by\n\t/// calling lzma_index_stream_flags() again.\n\tuint32_t checks;\n};\n\n\nstatic void\nindex_tree_init(index_tree *tree)\n{\n\ttree->root = NULL;\n\ttree->leftmost = NULL;\n\ttree->rightmost = NULL;\n\ttree->count = 0;\n\treturn;\n}\n\n\n/// Helper for index_tree_end()\nstatic void\nindex_tree_node_end(index_tree_node *node, const lzma_allocator *allocator,\n\t\tvoid (*free_func)(void *node, const lzma_allocator *allocator))\n{\n\t// The tree won't ever be very huge, so recursion should be fine.\n\t// 20 levels in the tree is likely quite a lot already in practice.\n\tif (node->left != NULL)\n\t\tindex_tree_node_end(node->left, allocator, free_func);\n\n\tif (node->right != NULL)\n\t\tindex_tree_node_end(node->right, allocator, free_func);\n\n\tfree_func(node, allocator);\n\treturn;\n}\n\n\n/// Free the memory allocated for a tree. Each node is freed using the\n/// given free_func which is either &lzma_free or &index_stream_end.\n/// The latter is used to free the Record groups from each index_stream\n/// before freeing the index_stream itself.\nstatic void\nindex_tree_end(index_tree *tree, const lzma_allocator *allocator,\n\t\tvoid (*free_func)(void *node, const lzma_allocator *allocator))\n{\n\tassert(free_func != NULL);\n\n\tif (tree->root != NULL)\n\t\tindex_tree_node_end(tree->root, allocator, free_func);\n\n\treturn;\n}\n\n\n/// Add a new node to the tree. node->uncompressed_base and\n/// node->compressed_base must have been set by the caller already.\nstatic void\nindex_tree_append(index_tree *tree, index_tree_node *node)\n{\n\tnode->parent = tree->rightmost;\n\tnode->left = NULL;\n\tnode->right = NULL;\n\n\t++tree->count;\n\n\t// Handle the special case of adding the first node.\n\tif (tree->root == NULL) {\n\t\ttree->root = node;\n\t\ttree->leftmost = node;\n\t\ttree->rightmost = node;\n\t\treturn;\n\t}\n\n\t// The tree is always filled sequentially.\n\tassert(tree->rightmost->uncompressed_base <= node->uncompressed_base);\n\tassert(tree->rightmost->compressed_base < node->compressed_base);\n\n\t// Add the new node after the rightmost node. It's the correct\n\t// place due to the reason above.\n\ttree->rightmost->right = node;\n\ttree->rightmost = node;\n\n\t// Balance the AVL-tree if needed. We don't need to keep the balance\n\t// factors in nodes, because we always fill the tree sequentially,\n\t// and thus know the state of the tree just by looking at the node\n\t// count. From the node count we can calculate how many steps to go\n\t// up in the tree to find the rotation root.\n\tuint32_t up = tree->count ^ (UINT32_C(1) << bsr32(tree->count));\n\tif (up != 0) {\n\t\t// Locate the root node for the rotation.\n\t\tup = ctz32(tree->count) + 2;\n\t\tdo {\n\t\t\tnode = node->parent;\n\t\t} while (--up > 0);\n\n\t\t// Rotate left using node as the rotation root.\n\t\tindex_tree_node *pivot = node->right;\n\n\t\tif (node->parent == NULL) {\n\t\t\ttree->root = pivot;\n\t\t} else {\n\t\t\tassert(node->parent->right == node);\n\t\t\tnode->parent->right = pivot;\n\t\t}\n\n\t\tpivot->parent = node->parent;\n\n\t\tnode->right = pivot->left;\n\t\tif (node->right != NULL)\n\t\t\tnode->right->parent = node;\n\n\t\tpivot->left = node;\n\t\tnode->parent = pivot;\n\t}\n\n\treturn;\n}\n\n\n/// Get the next node in the tree. Return NULL if there are no more nodes.\nstatic void *\nindex_tree_next(const index_tree_node *node)\n{\n\tif (node->right != NULL) {\n\t\tnode = node->right;\n\t\twhile (node->left != NULL)\n\t\t\tnode = node->left;\n\n\t\treturn (void *)(node);\n\t}\n\n\twhile (node->parent != NULL && node->parent->right == node)\n\t\tnode = node->parent;\n\n\treturn (void *)(node->parent);\n}\n\n\n/// Locate a node that contains the given uncompressed offset. It is\n/// caller's job to check that target is not bigger than the uncompressed\n/// size of the tree (the last node would be returned in that case still).\nstatic void *\nindex_tree_locate(const index_tree *tree, lzma_vli target)\n{\n\tconst index_tree_node *result = NULL;\n\tconst index_tree_node *node = tree->root;\n\n\tassert(tree->leftmost == NULL\n\t\t\t|| tree->leftmost->uncompressed_base == 0);\n\n\t// Consecutive nodes may have the same uncompressed_base.\n\t// We must pick the rightmost one.\n\twhile (node != NULL) {\n\t\tif (node->uncompressed_base > target) {\n\t\t\tnode = node->left;\n\t\t} else {\n\t\t\tresult = node;\n\t\t\tnode = node->right;\n\t\t}\n\t}\n\n\treturn (void *)(result);\n}\n\n\n/// Allocate and initialize a new Stream using the given base offsets.\nstatic index_stream *\nindex_stream_init(lzma_vli compressed_base, lzma_vli uncompressed_base,\n\t\tuint32_t stream_number, lzma_vli block_number_base,\n\t\tconst lzma_allocator *allocator)\n{\n\tindex_stream *s = lzma_alloc(sizeof(index_stream), allocator);\n\tif (s == NULL)\n\t\treturn NULL;\n\n\ts->node.uncompressed_base = uncompressed_base;\n\ts->node.compressed_base = compressed_base;\n\ts->node.parent = NULL;\n\ts->node.left = NULL;\n\ts->node.right = NULL;\n\n\ts->number = stream_number;\n\ts->block_number_base = block_number_base;\n\n\tindex_tree_init(&s->groups);\n\n\ts->record_count = 0;\n\ts->index_list_size = 0;\n\ts->stream_flags.version = UINT32_MAX;\n\ts->stream_padding = 0;\n\n\treturn s;\n}\n\n\n/// Free the memory allocated for a Stream and its Record groups.\nstatic void\nindex_stream_end(void *node, const lzma_allocator *allocator)\n{\n\tindex_stream *s = node;\n\tindex_tree_end(&s->groups, allocator, &lzma_free);\n\tlzma_free(s, allocator);\n\treturn;\n}\n\n\nstatic lzma_index *\nindex_init_plain(const lzma_allocator *allocator)\n{\n\tlzma_index *i = lzma_alloc(sizeof(lzma_index), allocator);\n\tif (i != NULL) {\n\t\tindex_tree_init(&i->streams);\n\t\ti->uncompressed_size = 0;\n\t\ti->total_size = 0;\n\t\ti->record_count = 0;\n\t\ti->index_list_size = 0;\n\t\ti->prealloc = INDEX_GROUP_SIZE;\n\t\ti->checks = 0;\n\t}\n\n\treturn i;\n}\n\n\nextern LZMA_API(lzma_index *)\nlzma_index_init(const lzma_allocator *allocator)\n{\n\tlzma_index *i = index_init_plain(allocator);\n\tif (i == NULL)\n\t\treturn NULL;\n\n\tindex_stream *s = index_stream_init(0, 0, 1, 0, allocator);\n\tif (s == NULL) {\n\t\tlzma_free(i, allocator);\n\t\treturn NULL;\n\t}\n\n\tindex_tree_append(&i->streams, &s->node);\n\n\treturn i;\n}\n\n\nextern LZMA_API(void)\nlzma_index_end(lzma_index *i, const lzma_allocator *allocator)\n{\n\t// NOTE: If you modify this function, check also the bottom\n\t// of lzma_index_cat().\n\tif (i != NULL) {\n\t\tindex_tree_end(&i->streams, allocator, &index_stream_end);\n\t\tlzma_free(i, allocator);\n\t}\n\n\treturn;\n}\n\n\nextern void\nlzma_index_prealloc(lzma_index *i, lzma_vli records)\n{\n\tif (records > PREALLOC_MAX)\n\t\trecords = PREALLOC_MAX;\n\n\ti->prealloc = (size_t)(records);\n\treturn;\n}\n\n\nextern LZMA_API(uint64_t)\nlzma_index_memusage(lzma_vli streams, lzma_vli blocks)\n{\n\t// This calculates an upper bound that is only a little bit\n\t// bigger than the exact maximum memory usage with the given\n\t// parameters.\n\n\t// Typical malloc() overhead is 2 * sizeof(void *) but we take\n\t// a little bit extra just in case. Using LZMA_MEMUSAGE_BASE\n\t// instead would give too inaccurate estimate.\n\tconst size_t alloc_overhead = 4 * sizeof(void *);\n\n\t// Amount of memory needed for each Stream base structures.\n\t// We assume that every Stream has at least one Block and\n\t// thus at least one group.\n\tconst size_t stream_base = sizeof(index_stream)\n\t\t\t+ sizeof(index_group) + 2 * alloc_overhead;\n\n\t// Amount of memory needed per group.\n\tconst size_t group_base = sizeof(index_group)\n\t\t\t+ INDEX_GROUP_SIZE * sizeof(index_record)\n\t\t\t+ alloc_overhead;\n\n\t// Number of groups. There may actually be more, but that overhead\n\t// has been taken into account in stream_base already.\n\tconst lzma_vli groups\n\t\t\t= (blocks + INDEX_GROUP_SIZE - 1) / INDEX_GROUP_SIZE;\n\n\t// Memory used by index_stream and index_group structures.\n\tconst uint64_t streams_mem = streams * stream_base;\n\tconst uint64_t groups_mem = groups * group_base;\n\n\t// Memory used by the base structure.\n\tconst uint64_t index_base = sizeof(lzma_index) + alloc_overhead;\n\n\t// Validate the arguments and catch integer overflows.\n\t// Maximum number of Streams is \"only\" UINT32_MAX, because\n\t// that limit is used by the tree containing the Streams.\n\tconst uint64_t limit = UINT64_MAX - index_base;\n\tif (streams == 0 || streams > UINT32_MAX || blocks > LZMA_VLI_MAX\n\t\t\t|| streams > limit / stream_base\n\t\t\t|| groups > limit / group_base\n\t\t\t|| limit - streams_mem < groups_mem)\n\t\treturn UINT64_MAX;\n\n\treturn index_base + streams_mem + groups_mem;\n}\n\n\nextern LZMA_API(uint64_t)\nlzma_index_memused(const lzma_index *i)\n{\n\treturn lzma_index_memusage(i->streams.count, i->record_count);\n}\n\n\nextern LZMA_API(lzma_vli)\nlzma_index_block_count(const lzma_index *i)\n{\n\treturn i->record_count;\n}\n\n\nextern LZMA_API(lzma_vli)\nlzma_index_stream_count(const lzma_index *i)\n{\n\treturn i->streams.count;\n}\n\n\nextern LZMA_API(lzma_vli)\nlzma_index_size(const lzma_index *i)\n{\n\treturn index_size(i->record_count, i->index_list_size);\n}\n\n\nextern LZMA_API(lzma_vli)\nlzma_index_total_size(const lzma_index *i)\n{\n\treturn i->total_size;\n}\n\n\nextern LZMA_API(lzma_vli)\nlzma_index_stream_size(const lzma_index *i)\n{\n\t// Stream Header + Blocks + Index + Stream Footer\n\treturn LZMA_STREAM_HEADER_SIZE + i->total_size\n\t\t\t+ index_size(i->record_count, i->index_list_size)\n\t\t\t+ LZMA_STREAM_HEADER_SIZE;\n}\n\n\nstatic lzma_vli\nindex_file_size(lzma_vli compressed_base, lzma_vli unpadded_sum,\n\t\tlzma_vli record_count, lzma_vli index_list_size,\n\t\tlzma_vli stream_padding)\n{\n\t// Earlier Streams and Stream Paddings + Stream Header\n\t// + Blocks + Index + Stream Footer + Stream Padding\n\t//\n\t// This might go over LZMA_VLI_MAX due to too big unpadded_sum\n\t// when this function is used in lzma_index_append().\n\tlzma_vli file_size = compressed_base + 2 * LZMA_STREAM_HEADER_SIZE\n\t\t\t+ stream_padding + vli_ceil4(unpadded_sum);\n\tif (file_size > LZMA_VLI_MAX)\n\t\treturn LZMA_VLI_UNKNOWN;\n\n\t// The same applies here.\n\tfile_size += index_size(record_count, index_list_size);\n\tif (file_size > LZMA_VLI_MAX)\n\t\treturn LZMA_VLI_UNKNOWN;\n\n\treturn file_size;\n}\n\n\nextern LZMA_API(lzma_vli)\nlzma_index_file_size(const lzma_index *i)\n{\n\tconst index_stream *s = (const index_stream *)(i->streams.rightmost);\n\tconst index_group *g = (const index_group *)(s->groups.rightmost);\n\treturn index_file_size(s->node.compressed_base,\n\t\t\tg == NULL ? 0 : g->records[g->last].unpadded_sum,\n\t\t\ts->record_count, s->index_list_size,\n\t\t\ts->stream_padding);\n}\n\n\nextern LZMA_API(lzma_vli)\nlzma_index_uncompressed_size(const lzma_index *i)\n{\n\treturn i->uncompressed_size;\n}\n\n\nextern LZMA_API(uint32_t)\nlzma_index_checks(const lzma_index *i)\n{\n\tuint32_t checks = i->checks;\n\n\t// Get the type of the Check of the last Stream too.\n\tconst index_stream *s = (const index_stream *)(i->streams.rightmost);\n\tif (s->stream_flags.version != UINT32_MAX)\n\t\tchecks |= UINT32_C(1) << s->stream_flags.check;\n\n\treturn checks;\n}\n\n\nextern uint32_t\nlzma_index_padding_size(const lzma_index *i)\n{\n\treturn (LZMA_VLI_C(4) - index_size_unpadded(\n\t\t\ti->record_count, i->index_list_size)) & 3;\n}\n\n\nextern LZMA_API(lzma_ret)\nlzma_index_stream_flags(lzma_index *i, const lzma_stream_flags *stream_flags)\n{\n\tif (i == NULL || stream_flags == NULL)\n\t\treturn LZMA_PROG_ERROR;\n\n\t// Validate the Stream Flags.\n\treturn_if_error(lzma_stream_flags_compare(\n\t\t\tstream_flags, stream_flags));\n\n\tindex_stream *s = (index_stream *)(i->streams.rightmost);\n\ts->stream_flags = *stream_flags;\n\n\treturn LZMA_OK;\n}\n\n\nextern LZMA_API(lzma_ret)\nlzma_index_stream_padding(lzma_index *i, lzma_vli stream_padding)\n{\n\tif (i == NULL || stream_padding > LZMA_VLI_MAX\n\t\t\t|| (stream_padding & 3) != 0)\n\t\treturn LZMA_PROG_ERROR;\n\n\tindex_stream *s = (index_stream *)(i->streams.rightmost);\n\n\t// Check that the new value won't make the file grow too big.\n\tconst lzma_vli old_stream_padding = s->stream_padding;\n\ts->stream_padding = 0;\n\tif (lzma_index_file_size(i) + stream_padding > LZMA_VLI_MAX) {\n\t\ts->stream_padding = old_stream_padding;\n\t\treturn LZMA_DATA_ERROR;\n\t}\n\n\ts->stream_padding = stream_padding;\n\treturn LZMA_OK;\n}\n\n\nextern LZMA_API(lzma_ret)\nlzma_index_append(lzma_index *i, const lzma_allocator *allocator,\n\t\tlzma_vli unpadded_size, lzma_vli uncompressed_size)\n{\n\t// Validate.\n\tif (i == NULL || unpadded_size < UNPADDED_SIZE_MIN\n\t\t\t|| unpadded_size > UNPADDED_SIZE_MAX\n\t\t\t|| uncompressed_size > LZMA_VLI_MAX)\n\t\treturn LZMA_PROG_ERROR;\n\n\tindex_stream *s = (index_stream *)(i->streams.rightmost);\n\tindex_group *g = (index_group *)(s->groups.rightmost);\n\n\tconst lzma_vli compressed_base = g == NULL ? 0\n\t\t\t: vli_ceil4(g->records[g->last].unpadded_sum);\n\tconst lzma_vli uncompressed_base = g == NULL ? 0\n\t\t\t: g->records[g->last].uncompressed_sum;\n\tconst uint32_t index_list_size_add = lzma_vli_size(unpadded_size)\n\t\t\t+ lzma_vli_size(uncompressed_size);\n\n\t// Check that the file size will stay within limits.\n\tif (index_file_size(s->node.compressed_base,\n\t\t\tcompressed_base + unpadded_size, s->record_count + 1,\n\t\t\ts->index_list_size + index_list_size_add,\n\t\t\ts->stream_padding) == LZMA_VLI_UNKNOWN)\n\t\treturn LZMA_DATA_ERROR;\n\n\t// The size of the Index field must not exceed the maximum value\n\t// that can be stored in the Backward Size field.\n\tif (index_size(i->record_count + 1,\n\t\t\ti->index_list_size + index_list_size_add)\n\t\t\t> LZMA_BACKWARD_SIZE_MAX)\n\t\treturn LZMA_DATA_ERROR;\n\n\tif (g != NULL && g->last + 1 < g->allocated) {\n\t\t// There is space in the last group at least for one Record.\n\t\t++g->last;\n\t} else {\n\t\t// We need to allocate a new group.\n\t\tg = lzma_alloc(sizeof(index_group)\n\t\t\t\t+ i->prealloc * sizeof(index_record),\n\t\t\t\tallocator);\n\t\tif (g == NULL)\n\t\t\treturn LZMA_MEM_ERROR;\n\n\t\tg->last = 0;\n\t\tg->allocated = i->prealloc;\n\n\t\t// Reset prealloc so that if the application happens to\n\t\t// add new Records, the allocation size will be sane.\n\t\ti->prealloc = INDEX_GROUP_SIZE;\n\n\t\t// Set the start offsets of this group.\n\t\tg->node.uncompressed_base = uncompressed_base;\n\t\tg->node.compressed_base = compressed_base;\n\t\tg->number_base = s->record_count + 1;\n\n\t\t// Add the new group to the Stream.\n\t\tindex_tree_append(&s->groups, &g->node);\n\t}\n\n\t// Add the new Record to the group.\n\tg->records[g->last].uncompressed_sum\n\t\t\t= uncompressed_base + uncompressed_size;\n\tg->records[g->last].unpadded_sum\n\t\t\t= compressed_base + unpadded_size;\n\n\t// Update the totals.\n\t++s->record_count;\n\ts->index_list_size += index_list_size_add;\n\n\ti->total_size += vli_ceil4(unpadded_size);\n\ti->uncompressed_size += uncompressed_size;\n\t++i->record_count;\n\ti->index_list_size += index_list_size_add;\n\n\treturn LZMA_OK;\n}\n\n\n/// Structure to pass info to index_cat_helper()\ntypedef struct {\n\t/// Uncompressed size of the destination\n\tlzma_vli uncompressed_size;\n\n\t/// Compressed file size of the destination\n\tlzma_vli file_size;\n\n\t/// Same as above but for Block numbers\n\tlzma_vli block_number_add;\n\n\t/// Number of Streams that were in the destination index before we\n\t/// started appending new Streams from the source index. This is\n\t/// used to fix the Stream numbering.\n\tuint32_t stream_number_add;\n\n\t/// Destination index' Stream tree\n\tindex_tree *streams;\n\n} index_cat_info;\n\n\n/// Add the Stream nodes from the source index to dest using recursion.\n/// Simplest iterative traversal of the source tree wouldn't work, because\n/// we update the pointers in nodes when moving them to the destination tree.\nstatic void\nindex_cat_helper(const index_cat_info *info, index_stream *this)\n{\n\tindex_stream *left = (index_stream *)(this->node.left);\n\tindex_stream *right = (index_stream *)(this->node.right);\n\n\tif (left != NULL)\n\t\tindex_cat_helper(info, left);\n\n\tthis->node.uncompressed_base += info->uncompressed_size;\n\tthis->node.compressed_base += info->file_size;\n\tthis->number += info->stream_number_add;\n\tthis->block_number_base += info->block_number_add;\n\tindex_tree_append(info->streams, &this->node);\n\n\tif (right != NULL)\n\t\tindex_cat_helper(info, right);\n\n\treturn;\n}\n\n\nextern LZMA_API(lzma_ret)\nlzma_index_cat(lzma_index *restrict dest, lzma_index *restrict src,\n\t\tconst lzma_allocator *allocator)\n{\n\tconst lzma_vli dest_file_size = lzma_index_file_size(dest);\n\n\t// Check that we don't exceed the file size limits.\n\tif (dest_file_size + lzma_index_file_size(src) > LZMA_VLI_MAX\n\t\t\t|| dest->uncompressed_size + src->uncompressed_size\n\t\t\t\t> LZMA_VLI_MAX)\n\t\treturn LZMA_DATA_ERROR;\n\n\t// Check that the encoded size of the combined lzma_indexes stays\n\t// within limits. In theory, this should be done only if we know\n\t// that the user plans to actually combine the Streams and thus\n\t// construct a single Index (probably rare). However, exceeding\n\t// this limit is quite theoretical, so we do this check always\n\t// to simplify things elsewhere.\n\t{\n\t\tconst lzma_vli dest_size = index_size_unpadded(\n\t\t\t\tdest->record_count, dest->index_list_size);\n\t\tconst lzma_vli src_size = index_size_unpadded(\n\t\t\t\tsrc->record_count, src->index_list_size);\n\t\tif (vli_ceil4(dest_size + src_size) > LZMA_BACKWARD_SIZE_MAX)\n\t\t\treturn LZMA_DATA_ERROR;\n\t}\n\n\t// Optimize the last group to minimize memory usage. Allocation has\n\t// to be done before modifying dest or src.\n\t{\n\t\tindex_stream *s = (index_stream *)(dest->streams.rightmost);\n\t\tindex_group *g = (index_group *)(s->groups.rightmost);\n\t\tif (g != NULL && g->last + 1 < g->allocated) {\n\t\t\tassert(g->node.left == NULL);\n\t\t\tassert(g->node.right == NULL);\n\n\t\t\tindex_group *newg = lzma_alloc(sizeof(index_group)\n\t\t\t\t\t+ (g->last + 1)\n\t\t\t\t\t* sizeof(index_record),\n\t\t\t\t\tallocator);\n\t\t\tif (newg == NULL)\n\t\t\t\treturn LZMA_MEM_ERROR;\n\n\t\t\tnewg->node = g->node;\n\t\t\tnewg->allocated = g->last + 1;\n\t\t\tnewg->last = g->last;\n\t\t\tnewg->number_base = g->number_base;\n\n\t\t\tmemcpy(newg->records, g->records, newg->allocated\n\t\t\t\t\t* sizeof(index_record));\n\n\t\t\tif (g->node.parent != NULL) {\n\t\t\t\tassert(g->node.parent->right == &g->node);\n\t\t\t\tg->node.parent->right = &newg->node;\n\t\t\t}\n\n\t\t\tif (s->groups.leftmost == &g->node) {\n\t\t\t\tassert(s->groups.root == &g->node);\n\t\t\t\ts->groups.leftmost = &newg->node;\n\t\t\t\ts->groups.root = &newg->node;\n\t\t\t}\n\n\t\t\tassert(s->groups.rightmost == &g->node);\n\t\t\ts->groups.rightmost = &newg->node;\n\n\t\t\tlzma_free(g, allocator);\n\n\t\t\t// NOTE: newg isn't leaked here because\n\t\t\t// newg == (void *)&newg->node.\n\t\t}\n\t}\n\n\t// Add all the Streams from src to dest. Update the base offsets\n\t// of each Stream from src.\n\tconst index_cat_info info = {\n\t\t.uncompressed_size = dest->uncompressed_size,\n\t\t.file_size = dest_file_size,\n\t\t.stream_number_add = dest->streams.count,\n\t\t.block_number_add = dest->record_count,\n\t\t.streams = &dest->streams,\n\t};\n\tindex_cat_helper(&info, (index_stream *)(src->streams.root));\n\n\t// Update info about all the combined Streams.\n\tdest->uncompressed_size += src->uncompressed_size;\n\tdest->total_size += src->total_size;\n\tdest->record_count += src->record_count;\n\tdest->index_list_size += src->index_list_size;\n\tdest->checks = lzma_index_checks(dest) | src->checks;\n\n\t// There's nothing else left in src than the base structure.\n\tlzma_free(src, allocator);\n\n\treturn LZMA_OK;\n}\n\n\n/// Duplicate an index_stream.\nstatic index_stream *\nindex_dup_stream(const index_stream *src, const lzma_allocator *allocator)\n{\n\t// Catch a somewhat theoretical integer overflow.\n\tif (src->record_count > PREALLOC_MAX)\n\t\treturn NULL;\n\n\t// Allocate and initialize a new Stream.\n\tindex_stream *dest = index_stream_init(src->node.compressed_base,\n\t\t\tsrc->node.uncompressed_base, src->number,\n\t\t\tsrc->block_number_base, allocator);\n\tif (dest == NULL)\n\t\treturn NULL;\n\n\t// Copy the overall information.\n\tdest->record_count = src->record_count;\n\tdest->index_list_size = src->index_list_size;\n\tdest->stream_flags = src->stream_flags;\n\tdest->stream_padding = src->stream_padding;\n\n\t// Return if there are no groups to duplicate.\n\tif (src->groups.leftmost == NULL)\n\t\treturn dest;\n\n\t// Allocate memory for the Records. We put all the Records into\n\t// a single group. It's simplest and also tends to make\n\t// lzma_index_locate() a little bit faster with very big Indexes.\n\tindex_group *destg = lzma_alloc(sizeof(index_group)\n\t\t\t+ src->record_count * sizeof(index_record),\n\t\t\tallocator);\n\tif (destg == NULL) {\n\t\tindex_stream_end(dest, allocator);\n\t\treturn NULL;\n\t}\n\n\t// Initialize destg.\n\tdestg->node.uncompressed_base = 0;\n\tdestg->node.compressed_base = 0;\n\tdestg->number_base = 1;\n\tdestg->allocated = src->record_count;\n\tdestg->last = src->record_count - 1;\n\n\t// Go through all the groups in src and copy the Records into destg.\n\tconst index_group *srcg = (const index_group *)(src->groups.leftmost);\n\tsize_t i = 0;\n\tdo {\n\t\tmemcpy(destg->records + i, srcg->records,\n\t\t\t\t(srcg->last + 1) * sizeof(index_record));\n\t\ti += srcg->last + 1;\n\t\tsrcg = index_tree_next(&srcg->node);\n\t} while (srcg != NULL);\n\n\tassert(i == destg->allocated);\n\n\t// Add the group to the new Stream.\n\tindex_tree_append(&dest->groups, &destg->node);\n\n\treturn dest;\n}\n\n\nextern LZMA_API(lzma_index *)\nlzma_index_dup(const lzma_index *src, const lzma_allocator *allocator)\n{\n\t// Allocate the base structure (no initial Stream).\n\tlzma_index *dest = index_init_plain(allocator);\n\tif (dest == NULL)\n\t\treturn NULL;\n\n\t// Copy the totals.\n\tdest->uncompressed_size = src->uncompressed_size;\n\tdest->total_size = src->total_size;\n\tdest->record_count = src->record_count;\n\tdest->index_list_size = src->index_list_size;\n\n\t// Copy the Streams and the groups in them.\n\tconst index_stream *srcstream\n\t\t\t= (const index_stream *)(src->streams.leftmost);\n\tdo {\n\t\tindex_stream *deststream = index_dup_stream(\n\t\t\t\tsrcstream, allocator);\n\t\tif (deststream == NULL) {\n\t\t\tlzma_index_end(dest, allocator);\n\t\t\treturn NULL;\n\t\t}\n\n\t\tindex_tree_append(&dest->streams, &deststream->node);\n\n\t\tsrcstream = index_tree_next(&srcstream->node);\n\t} while (srcstream != NULL);\n\n\treturn dest;\n}\n\n\n/// Indexing for lzma_index_iter.internal[]\nenum {\n\tITER_INDEX,\n\tITER_STREAM,\n\tITER_GROUP,\n\tITER_RECORD,\n\tITER_METHOD,\n};\n\n\n/// Values for lzma_index_iter.internal[ITER_METHOD].s\nenum {\n\tITER_METHOD_NORMAL,\n\tITER_METHOD_NEXT,\n\tITER_METHOD_LEFTMOST,\n};\n\n\nstatic void\niter_set_info(lzma_index_iter *iter)\n{\n\tconst lzma_index *i = iter->internal[ITER_INDEX].p;\n\tconst index_stream *stream = iter->internal[ITER_STREAM].p;\n\tconst index_group *group = iter->internal[ITER_GROUP].p;\n\tconst size_t record = iter->internal[ITER_RECORD].s;\n\n\t// lzma_index_iter.internal must not contain a pointer to the last\n\t// group in the index, because that may be reallocated by\n\t// lzma_index_cat().\n\tif (group == NULL) {\n\t\t// There are no groups.\n\t\tassert(stream->groups.root == NULL);\n\t\titer->internal[ITER_METHOD].s = ITER_METHOD_LEFTMOST;\n\n\t} else if (i->streams.rightmost != &stream->node\n\t\t\t|| stream->groups.rightmost != &group->node) {\n\t\t// The group is not not the last group in the index.\n\t\titer->internal[ITER_METHOD].s = ITER_METHOD_NORMAL;\n\n\t} else if (stream->groups.leftmost != &group->node) {\n\t\t// The group isn't the only group in the Stream, thus we\n\t\t// know that it must have a parent group i.e. it's not\n\t\t// the root node.\n\t\tassert(stream->groups.root != &group->node);\n\t\tassert(group->node.parent->right == &group->node);\n\t\titer->internal[ITER_METHOD].s = ITER_METHOD_NEXT;\n\t\titer->internal[ITER_GROUP].p = group->node.parent;\n\n\t} else {\n\t\t// The Stream has only one group.\n\t\tassert(stream->groups.root == &group->node);\n\t\tassert(group->node.parent == NULL);\n\t\titer->internal[ITER_METHOD].s = ITER_METHOD_LEFTMOST;\n\t\titer->internal[ITER_GROUP].p = NULL;\n\t}\n\n\t// NOTE: lzma_index_iter.stream.number is lzma_vli but we use uint32_t\n\t// internally.\n\titer->stream.number = stream->number;\n\titer->stream.block_count = stream->record_count;\n\titer->stream.compressed_offset = stream->node.compressed_base;\n\titer->stream.uncompressed_offset = stream->node.uncompressed_base;\n\n\t// iter->stream.flags will be NULL if the Stream Flags haven't been\n\t// set with lzma_index_stream_flags().\n\titer->stream.flags = stream->stream_flags.version == UINT32_MAX\n\t\t\t? NULL : &stream->stream_flags;\n\titer->stream.padding = stream->stream_padding;\n\n\tif (stream->groups.rightmost == NULL) {\n\t\t// Stream has no Blocks.\n\t\titer->stream.compressed_size = index_size(0, 0)\n\t\t\t\t+ 2 * LZMA_STREAM_HEADER_SIZE;\n\t\titer->stream.uncompressed_size = 0;\n\t} else {\n\t\tconst index_group *g = (const index_group *)(\n\t\t\t\tstream->groups.rightmost);\n\n\t\t// Stream Header + Stream Footer + Index + Blocks\n\t\titer->stream.compressed_size = 2 * LZMA_STREAM_HEADER_SIZE\n\t\t\t\t+ index_size(stream->record_count,\n\t\t\t\t\tstream->index_list_size)\n\t\t\t\t+ vli_ceil4(g->records[g->last].unpadded_sum);\n\t\titer->stream.uncompressed_size\n\t\t\t\t= g->records[g->last].uncompressed_sum;\n\t}\n\n\tif (group != NULL) {\n\t\titer->block.number_in_stream = group->number_base + record;\n\t\titer->block.number_in_file = iter->block.number_in_stream\n\t\t\t\t+ stream->block_number_base;\n\n\t\titer->block.compressed_stream_offset\n\t\t\t\t= record == 0 ? group->node.compressed_base\n\t\t\t\t: vli_ceil4(group->records[\n\t\t\t\t\trecord - 1].unpadded_sum);\n\t\titer->block.uncompressed_stream_offset\n\t\t\t\t= record == 0 ? group->node.uncompressed_base\n\t\t\t\t: group->records[record - 1].uncompressed_sum;\n\n\t\titer->block.uncompressed_size\n\t\t\t\t= group->records[record].uncompressed_sum\n\t\t\t\t- iter->block.uncompressed_stream_offset;\n\t\titer->block.unpadded_size\n\t\t\t\t= group->records[record].unpadded_sum\n\t\t\t\t- iter->block.compressed_stream_offset;\n\t\titer->block.total_size = vli_ceil4(iter->block.unpadded_size);\n\n\t\titer->block.compressed_stream_offset\n\t\t\t\t+= LZMA_STREAM_HEADER_SIZE;\n\n\t\titer->block.compressed_file_offset\n\t\t\t\t= iter->block.compressed_stream_offset\n\t\t\t\t+ iter->stream.compressed_offset;\n\t\titer->block.uncompressed_file_offset\n\t\t\t\t= iter->block.uncompressed_stream_offset\n\t\t\t\t+ iter->stream.uncompressed_offset;\n\t}\n\n\treturn;\n}\n\n\nextern LZMA_API(void)\nlzma_index_iter_init(lzma_index_iter *iter, const lzma_index *i)\n{\n\titer->internal[ITER_INDEX].p = i;\n\tlzma_index_iter_rewind(iter);\n\treturn;\n}\n\n\nextern LZMA_API(void)\nlzma_index_iter_rewind(lzma_index_iter *iter)\n{\n\titer->internal[ITER_STREAM].p = NULL;\n\titer->internal[ITER_GROUP].p = NULL;\n\titer->internal[ITER_RECORD].s = 0;\n\titer->internal[ITER_METHOD].s = ITER_METHOD_NORMAL;\n\treturn;\n}\n\n\nextern LZMA_API(lzma_bool)\nlzma_index_iter_next(lzma_index_iter *iter, lzma_index_iter_mode mode)\n{\n\t// Catch unsupported mode values.\n\tif ((unsigned int)(mode) > LZMA_INDEX_ITER_NONEMPTY_BLOCK)\n\t\treturn true;\n\n\tconst lzma_index *i = iter->internal[ITER_INDEX].p;\n\tconst index_stream *stream = iter->internal[ITER_STREAM].p;\n\tconst index_group *group = NULL;\n\tsize_t record = iter->internal[ITER_RECORD].s;\n\n\t// If we are being asked for the next Stream, leave group to NULL\n\t// so that the rest of the this function thinks that this Stream\n\t// has no groups and will thus go to the next Stream.\n\tif (mode != LZMA_INDEX_ITER_STREAM) {\n\t\t// Get the pointer to the current group. See iter_set_inf()\n\t\t// for explanation.\n\t\tswitch (iter->internal[ITER_METHOD].s) {\n\t\tcase ITER_METHOD_NORMAL:\n\t\t\tgroup = iter->internal[ITER_GROUP].p;\n\t\t\tbreak;\n\n\t\tcase ITER_METHOD_NEXT:\n\t\t\tgroup = index_tree_next(iter->internal[ITER_GROUP].p);\n\t\t\tbreak;\n\n\t\tcase ITER_METHOD_LEFTMOST:\n\t\t\tgroup = (const index_group *)(\n\t\t\t\t\tstream->groups.leftmost);\n\t\t\tbreak;\n\t\t}\n\t}\n\nagain:\n\tif (stream == NULL) {\n\t\t// We at the beginning of the lzma_index.\n\t\t// Locate the first Stream.\n\t\tstream = (const index_stream *)(i->streams.leftmost);\n\t\tif (mode >= LZMA_INDEX_ITER_BLOCK) {\n\t\t\t// Since we are being asked to return information\n\t\t\t// about the first a Block, skip Streams that have\n\t\t\t// no Blocks.\n\t\t\twhile (stream->groups.leftmost == NULL) {\n\t\t\t\tstream = index_tree_next(&stream->node);\n\t\t\t\tif (stream == NULL)\n\t\t\t\t\treturn true;\n\t\t\t}\n\t\t}\n\n\t\t// Start from the first Record in the Stream.\n\t\tgroup = (const index_group *)(stream->groups.leftmost);\n\t\trecord = 0;\n\n\t} else if (group != NULL && record < group->last) {\n\t\t// The next Record is in the same group.\n\t\t++record;\n\n\t} else {\n\t\t// This group has no more Records or this Stream has\n\t\t// no Blocks at all.\n\t\trecord = 0;\n\n\t\t// If group is not NULL, this Stream has at least one Block\n\t\t// and thus at least one group. Find the next group.\n\t\tif (group != NULL)\n\t\t\tgroup = index_tree_next(&group->node);\n\n\t\tif (group == NULL) {\n\t\t\t// This Stream has no more Records. Find the next\n\t\t\t// Stream. If we are being asked to return information\n\t\t\t// about a Block, we skip empty Streams.\n\t\t\tdo {\n\t\t\t\tstream = index_tree_next(&stream->node);\n\t\t\t\tif (stream == NULL)\n\t\t\t\t\treturn true;\n\t\t\t} while (mode >= LZMA_INDEX_ITER_BLOCK\n\t\t\t\t\t&& stream->groups.leftmost == NULL);\n\n\t\t\tgroup = (const index_group *)(\n\t\t\t\t\tstream->groups.leftmost);\n\t\t}\n\t}\n\n\tif (mode == LZMA_INDEX_ITER_NONEMPTY_BLOCK) {\n\t\t// We need to look for the next Block again if this Block\n\t\t// is empty.\n\t\tif (record == 0) {\n\t\t\tif (group->node.uncompressed_base\n\t\t\t\t\t== group->records[0].uncompressed_sum)\n\t\t\t\tgoto again;\n\t\t} else if (group->records[record - 1].uncompressed_sum\n\t\t\t\t== group->records[record].uncompressed_sum) {\n\t\t\tgoto again;\n\t\t}\n\t}\n\n\titer->internal[ITER_STREAM].p = stream;\n\titer->internal[ITER_GROUP].p = group;\n\titer->internal[ITER_RECORD].s = record;\n\n\titer_set_info(iter);\n\n\treturn false;\n}\n\n\nextern LZMA_API(lzma_bool)\nlzma_index_iter_locate(lzma_index_iter *iter, lzma_vli target)\n{\n\tconst lzma_index *i = iter->internal[ITER_INDEX].p;\n\n\t// If the target is past the end of the file, return immediately.\n\tif (i->uncompressed_size <= target)\n\t\treturn true;\n\n\t// Locate the Stream containing the target offset.\n\tconst index_stream *stream = index_tree_locate(&i->streams, target);\n\tassert(stream != NULL);\n\ttarget -= stream->node.uncompressed_base;\n\n\t// Locate the group containing the target offset.\n\tconst index_group *group = index_tree_locate(&stream->groups, target);\n\tassert(group != NULL);\n\n\t// Use binary search to locate the exact Record. It is the first\n\t// Record whose uncompressed_sum is greater than target.\n\t// This is because we want the rightmost Record that fullfills the\n\t// search criterion. It is possible that there are empty Blocks;\n\t// we don't want to return them.\n\tsize_t left = 0;\n\tsize_t right = group->last;\n\n\twhile (left < right) {\n\t\tconst size_t pos = left + (right - left) / 2;\n\t\tif (group->records[pos].uncompressed_sum <= target)\n\t\t\tleft = pos + 1;\n\t\telse\n\t\t\tright = pos;\n\t}\n\n\titer->internal[ITER_STREAM].p = stream;\n\titer->internal[ITER_GROUP].p = group;\n\titer->internal[ITER_RECORD].s = left;\n\n\titer_set_info(iter);\n\n\treturn false;\n}\n"
  },
  {
    "path": "external/xz/liblzma/common/index.h",
    "content": "///////////////////////////////////////////////////////////////////////////////\n//\n/// \\file       index.h\n/// \\brief      Handling of Index\n//\n//  Author:     Lasse Collin\n//\n//  This file has been put into the public domain.\n//  You can do whatever you want with this file.\n//\n///////////////////////////////////////////////////////////////////////////////\n\n#ifndef LZMA_INDEX_H\n#define LZMA_INDEX_H\n\n#include \"common.h\"\n\n\n/// Minimum Unpadded Size\n#define UNPADDED_SIZE_MIN LZMA_VLI_C(5)\n\n/// Maximum Unpadded Size\n#define UNPADDED_SIZE_MAX (LZMA_VLI_MAX & ~LZMA_VLI_C(3))\n\n\n/// Get the size of the Index Padding field. This is needed by Index encoder\n/// and decoder, but applications should have no use for this.\nextern uint32_t lzma_index_padding_size(const lzma_index *i);\n\n\n/// Set for how many Records to allocate memory the next time\n/// lzma_index_append() needs to allocate space for a new Record.\n/// This is used only by the Index decoder.\nextern void lzma_index_prealloc(lzma_index *i, lzma_vli records);\n\n\n/// Round the variable-length integer to the next multiple of four.\nstatic inline lzma_vli\nvli_ceil4(lzma_vli vli)\n{\n\tassert(vli <= LZMA_VLI_MAX);\n\treturn (vli + 3) & ~LZMA_VLI_C(3);\n}\n\n\n/// Calculate the size of the Index field excluding Index Padding\nstatic inline lzma_vli\nindex_size_unpadded(lzma_vli count, lzma_vli index_list_size)\n{\n\t// Index Indicator + Number of Records + List of Records + CRC32\n\treturn 1 + lzma_vli_size(count) + index_list_size + 4;\n}\n\n\n/// Calculate the size of the Index field including Index Padding\nstatic inline lzma_vli\nindex_size(lzma_vli count, lzma_vli index_list_size)\n{\n\treturn vli_ceil4(index_size_unpadded(count, index_list_size));\n}\n\n\n/// Calculate the total size of the Stream\nstatic inline lzma_vli\nindex_stream_size(lzma_vli blocks_size,\n\t\tlzma_vli count, lzma_vli index_list_size)\n{\n\treturn LZMA_STREAM_HEADER_SIZE + blocks_size\n\t\t\t+ index_size(count, index_list_size)\n\t\t\t+ LZMA_STREAM_HEADER_SIZE;\n}\n\n#endif\n"
  },
  {
    "path": "external/xz/liblzma/common/index_decoder.c",
    "content": "///////////////////////////////////////////////////////////////////////////////\n//\n/// \\file       index_decoder.c\n/// \\brief      Decodes the Index field\n//\n//  Author:     Lasse Collin\n//\n//  This file has been put into the public domain.\n//  You can do whatever you want with this file.\n//\n///////////////////////////////////////////////////////////////////////////////\n\n#include \"index.h\"\n#include \"check.h\"\n\n\ntypedef struct {\n\tenum {\n\t\tSEQ_INDICATOR,\n\t\tSEQ_COUNT,\n\t\tSEQ_MEMUSAGE,\n\t\tSEQ_UNPADDED,\n\t\tSEQ_UNCOMPRESSED,\n\t\tSEQ_PADDING_INIT,\n\t\tSEQ_PADDING,\n\t\tSEQ_CRC32,\n\t} sequence;\n\n\t/// Memory usage limit\n\tuint64_t memlimit;\n\n\t/// Target Index\n\tlzma_index *index;\n\n\t/// Pointer give by the application, which is set after\n\t/// successful decoding.\n\tlzma_index **index_ptr;\n\n\t/// Number of Records left to decode.\n\tlzma_vli count;\n\n\t/// The most recent Unpadded Size field\n\tlzma_vli unpadded_size;\n\n\t/// The most recent Uncompressed Size field\n\tlzma_vli uncompressed_size;\n\n\t/// Position in integers\n\tsize_t pos;\n\n\t/// CRC32 of the List of Records field\n\tuint32_t crc32;\n} lzma_index_coder;\n\n\nstatic lzma_ret\nindex_decode(void *coder_ptr, const lzma_allocator *allocator,\n\t\tconst uint8_t *restrict in, size_t *restrict in_pos,\n\t\tsize_t in_size,\n\t\tuint8_t *restrict out lzma_attribute((__unused__)),\n\t\tsize_t *restrict out_pos lzma_attribute((__unused__)),\n\t\tsize_t out_size lzma_attribute((__unused__)),\n\t\tlzma_action action lzma_attribute((__unused__)))\n{\n\tlzma_index_coder *coder = coder_ptr;\n\n\t// Similar optimization as in index_encoder.c\n\tconst size_t in_start = *in_pos;\n\tlzma_ret ret = LZMA_OK;\n\n\twhile (*in_pos < in_size)\n\tswitch (coder->sequence) {\n\tcase SEQ_INDICATOR:\n\t\t// Return LZMA_DATA_ERROR instead of e.g. LZMA_PROG_ERROR or\n\t\t// LZMA_FORMAT_ERROR, because a typical usage case for Index\n\t\t// decoder is when parsing the Stream backwards. If seeking\n\t\t// backward from the Stream Footer gives us something that\n\t\t// doesn't begin with Index Indicator, the file is considered\n\t\t// corrupt, not \"programming error\" or \"unrecognized file\n\t\t// format\". One could argue that the application should\n\t\t// verify the Index Indicator before trying to decode the\n\t\t// Index, but well, I suppose it is simpler this way.\n\t\tif (in[(*in_pos)++] != 0x00)\n\t\t\treturn LZMA_DATA_ERROR;\n\n\t\tcoder->sequence = SEQ_COUNT;\n\t\tbreak;\n\n\tcase SEQ_COUNT:\n\t\tret = lzma_vli_decode(&coder->count, &coder->pos,\n\t\t\t\tin, in_pos, in_size);\n\t\tif (ret != LZMA_STREAM_END)\n\t\t\tgoto out;\n\n\t\tcoder->pos = 0;\n\t\tcoder->sequence = SEQ_MEMUSAGE;\n\n\t// Fall through\n\n\tcase SEQ_MEMUSAGE:\n\t\tif (lzma_index_memusage(1, coder->count) > coder->memlimit) {\n\t\t\tret = LZMA_MEMLIMIT_ERROR;\n\t\t\tgoto out;\n\t\t}\n\n\t\t// Tell the Index handling code how many Records this\n\t\t// Index has to allow it to allocate memory more efficiently.\n\t\tlzma_index_prealloc(coder->index, coder->count);\n\n\t\tret = LZMA_OK;\n\t\tcoder->sequence = coder->count == 0\n\t\t\t\t? SEQ_PADDING_INIT : SEQ_UNPADDED;\n\t\tbreak;\n\n\tcase SEQ_UNPADDED:\n\tcase SEQ_UNCOMPRESSED: {\n\t\tlzma_vli *size = coder->sequence == SEQ_UNPADDED\n\t\t\t\t? &coder->unpadded_size\n\t\t\t\t: &coder->uncompressed_size;\n\n\t\tret = lzma_vli_decode(size, &coder->pos,\n\t\t\t\tin, in_pos, in_size);\n\t\tif (ret != LZMA_STREAM_END)\n\t\t\tgoto out;\n\n\t\tret = LZMA_OK;\n\t\tcoder->pos = 0;\n\n\t\tif (coder->sequence == SEQ_UNPADDED) {\n\t\t\t// Validate that encoded Unpadded Size isn't too small\n\t\t\t// or too big.\n\t\t\tif (coder->unpadded_size < UNPADDED_SIZE_MIN\n\t\t\t\t\t|| coder->unpadded_size\n\t\t\t\t\t\t> UNPADDED_SIZE_MAX)\n\t\t\t\treturn LZMA_DATA_ERROR;\n\n\t\t\tcoder->sequence = SEQ_UNCOMPRESSED;\n\t\t} else {\n\t\t\t// Add the decoded Record to the Index.\n\t\t\treturn_if_error(lzma_index_append(\n\t\t\t\t\tcoder->index, allocator,\n\t\t\t\t\tcoder->unpadded_size,\n\t\t\t\t\tcoder->uncompressed_size));\n\n\t\t\t// Check if this was the last Record.\n\t\t\tcoder->sequence = --coder->count == 0\n\t\t\t\t\t? SEQ_PADDING_INIT\n\t\t\t\t\t: SEQ_UNPADDED;\n\t\t}\n\n\t\tbreak;\n\t}\n\n\tcase SEQ_PADDING_INIT:\n\t\tcoder->pos = lzma_index_padding_size(coder->index);\n\t\tcoder->sequence = SEQ_PADDING;\n\n\t// Fall through\n\n\tcase SEQ_PADDING:\n\t\tif (coder->pos > 0) {\n\t\t\t--coder->pos;\n\t\t\tif (in[(*in_pos)++] != 0x00)\n\t\t\t\treturn LZMA_DATA_ERROR;\n\n\t\t\tbreak;\n\t\t}\n\n\t\t// Finish the CRC32 calculation.\n\t\tcoder->crc32 = lzma_crc32(in + in_start,\n\t\t\t\t*in_pos - in_start, coder->crc32);\n\n\t\tcoder->sequence = SEQ_CRC32;\n\n\t// Fall through\n\n\tcase SEQ_CRC32:\n\t\tdo {\n\t\t\tif (*in_pos == in_size)\n\t\t\t\treturn LZMA_OK;\n\n\t\t\tif (((coder->crc32 >> (coder->pos * 8)) & 0xFF)\n\t\t\t\t\t!= in[(*in_pos)++])\n\t\t\t\treturn LZMA_DATA_ERROR;\n\n\t\t} while (++coder->pos < 4);\n\n\t\t// Decoding was successful, now we can let the application\n\t\t// see the decoded Index.\n\t\t*coder->index_ptr = coder->index;\n\n\t\t// Make index NULL so we don't free it unintentionally.\n\t\tcoder->index = NULL;\n\n\t\treturn LZMA_STREAM_END;\n\n\tdefault:\n\t\tassert(0);\n\t\treturn LZMA_PROG_ERROR;\n\t}\n\nout:\n\t// Update the CRC32,\n\tcoder->crc32 = lzma_crc32(in + in_start,\n\t\t\t*in_pos - in_start, coder->crc32);\n\n\treturn ret;\n}\n\n\nstatic void\nindex_decoder_end(void *coder_ptr, const lzma_allocator *allocator)\n{\n\tlzma_index_coder *coder = coder_ptr;\n\tlzma_index_end(coder->index, allocator);\n\tlzma_free(coder, allocator);\n\treturn;\n}\n\n\nstatic lzma_ret\nindex_decoder_memconfig(void *coder_ptr, uint64_t *memusage,\n\t\tuint64_t *old_memlimit, uint64_t new_memlimit)\n{\n\tlzma_index_coder *coder = coder_ptr;\n\n\t*memusage = lzma_index_memusage(1, coder->count);\n\t*old_memlimit = coder->memlimit;\n\n\tif (new_memlimit != 0) {\n\t\tif (new_memlimit < *memusage)\n\t\t\treturn LZMA_MEMLIMIT_ERROR;\n\n\t\tcoder->memlimit = new_memlimit;\n\t}\n\n\treturn LZMA_OK;\n}\n\n\nstatic lzma_ret\nindex_decoder_reset(lzma_index_coder *coder, const lzma_allocator *allocator,\n\t\tlzma_index **i, uint64_t memlimit)\n{\n\t// Remember the pointer given by the application. We will set it\n\t// to point to the decoded Index only if decoding is successful.\n\t// Before that, keep it NULL so that applications can always safely\n\t// pass it to lzma_index_end() no matter did decoding succeed or not.\n\tcoder->index_ptr = i;\n\t*i = NULL;\n\n\t// We always allocate a new lzma_index.\n\tcoder->index = lzma_index_init(allocator);\n\tif (coder->index == NULL)\n\t\treturn LZMA_MEM_ERROR;\n\n\t// Initialize the rest.\n\tcoder->sequence = SEQ_INDICATOR;\n\tcoder->memlimit = my_max(1, memlimit);\n\tcoder->count = 0; // Needs to be initialized due to _memconfig().\n\tcoder->pos = 0;\n\tcoder->crc32 = 0;\n\n\treturn LZMA_OK;\n}\n\n\nstatic lzma_ret\nindex_decoder_init(lzma_next_coder *next, const lzma_allocator *allocator,\n\t\tlzma_index **i, uint64_t memlimit)\n{\n\tlzma_next_coder_init(&index_decoder_init, next, allocator);\n\n\tif (i == NULL)\n\t\treturn LZMA_PROG_ERROR;\n\n\tlzma_index_coder *coder = next->coder;\n\tif (coder == NULL) {\n\t\tcoder = lzma_alloc(sizeof(lzma_index_coder), allocator);\n\t\tif (coder == NULL)\n\t\t\treturn LZMA_MEM_ERROR;\n\n\t\tnext->coder = coder;\n\t\tnext->code = &index_decode;\n\t\tnext->end = &index_decoder_end;\n\t\tnext->memconfig = &index_decoder_memconfig;\n\t\tcoder->index = NULL;\n\t} else {\n\t\tlzma_index_end(coder->index, allocator);\n\t}\n\n\treturn index_decoder_reset(coder, allocator, i, memlimit);\n}\n\n\nextern LZMA_API(lzma_ret)\nlzma_index_decoder(lzma_stream *strm, lzma_index **i, uint64_t memlimit)\n{\n\tlzma_next_strm_init(index_decoder_init, strm, i, memlimit);\n\n\tstrm->internal->supported_actions[LZMA_RUN] = true;\n\tstrm->internal->supported_actions[LZMA_FINISH] = true;\n\n\treturn LZMA_OK;\n}\n\n\nextern LZMA_API(lzma_ret)\nlzma_index_buffer_decode(lzma_index **i, uint64_t *memlimit,\n\t\tconst lzma_allocator *allocator,\n\t\tconst uint8_t *in, size_t *in_pos, size_t in_size)\n{\n\t// Sanity checks\n\tif (i == NULL || memlimit == NULL\n\t\t\t|| in == NULL || in_pos == NULL || *in_pos > in_size)\n\t\treturn LZMA_PROG_ERROR;\n\n\t// Initialize the decoder.\n\tlzma_index_coder coder;\n\treturn_if_error(index_decoder_reset(&coder, allocator, i, *memlimit));\n\n\t// Store the input start position so that we can restore it in case\n\t// of an error.\n\tconst size_t in_start = *in_pos;\n\n\t// Do the actual decoding.\n\tlzma_ret ret = index_decode(&coder, allocator, in, in_pos, in_size,\n\t\t\tNULL, NULL, 0, LZMA_RUN);\n\n\tif (ret == LZMA_STREAM_END) {\n\t\tret = LZMA_OK;\n\t} else {\n\t\t// Something went wrong, free the Index structure and restore\n\t\t// the input position.\n\t\tlzma_index_end(coder.index, allocator);\n\t\t*in_pos = in_start;\n\n\t\tif (ret == LZMA_OK) {\n\t\t\t// The input is truncated or otherwise corrupt.\n\t\t\t// Use LZMA_DATA_ERROR instead of LZMA_BUF_ERROR\n\t\t\t// like lzma_vli_decode() does in single-call mode.\n\t\t\tret = LZMA_DATA_ERROR;\n\n\t\t} else if (ret == LZMA_MEMLIMIT_ERROR) {\n\t\t\t// Tell the caller how much memory would have\n\t\t\t// been needed.\n\t\t\t*memlimit = lzma_index_memusage(1, coder.count);\n\t\t}\n\t}\n\n\treturn ret;\n}\n"
  },
  {
    "path": "external/xz/liblzma/common/index_encoder.c",
    "content": "///////////////////////////////////////////////////////////////////////////////\n//\n/// \\file       index_encoder.c\n/// \\brief      Encodes the Index field\n//\n//  Author:     Lasse Collin\n//\n//  This file has been put into the public domain.\n//  You can do whatever you want with this file.\n//\n///////////////////////////////////////////////////////////////////////////////\n\n#include \"index_encoder.h\"\n#include \"index.h\"\n#include \"check.h\"\n\n\ntypedef struct {\n\tenum {\n\t\tSEQ_INDICATOR,\n\t\tSEQ_COUNT,\n\t\tSEQ_UNPADDED,\n\t\tSEQ_UNCOMPRESSED,\n\t\tSEQ_NEXT,\n\t\tSEQ_PADDING,\n\t\tSEQ_CRC32,\n\t} sequence;\n\n\t/// Index being encoded\n\tconst lzma_index *index;\n\n\t/// Iterator for the Index being encoded\n\tlzma_index_iter iter;\n\n\t/// Position in integers\n\tsize_t pos;\n\n\t/// CRC32 of the List of Records field\n\tuint32_t crc32;\n} lzma_index_coder;\n\n\nstatic lzma_ret\nindex_encode(void *coder_ptr,\n\t\tconst lzma_allocator *allocator lzma_attribute((__unused__)),\n\t\tconst uint8_t *restrict in lzma_attribute((__unused__)),\n\t\tsize_t *restrict in_pos lzma_attribute((__unused__)),\n\t\tsize_t in_size lzma_attribute((__unused__)),\n\t\tuint8_t *restrict out, size_t *restrict out_pos,\n\t\tsize_t out_size,\n\t\tlzma_action action lzma_attribute((__unused__)))\n{\n\tlzma_index_coder *coder = coder_ptr;\n\n\t// Position where to start calculating CRC32. The idea is that we\n\t// need to call lzma_crc32() only once per call to index_encode().\n\tconst size_t out_start = *out_pos;\n\n\t// Return value to use if we return at the end of this function.\n\t// We use \"goto out\" to jump out of the while-switch construct\n\t// instead of returning directly, because that way we don't need\n\t// to copypaste the lzma_crc32() call to many places.\n\tlzma_ret ret = LZMA_OK;\n\n\twhile (*out_pos < out_size)\n\tswitch (coder->sequence) {\n\tcase SEQ_INDICATOR:\n\t\tout[*out_pos] = 0x00;\n\t\t++*out_pos;\n\t\tcoder->sequence = SEQ_COUNT;\n\t\tbreak;\n\n\tcase SEQ_COUNT: {\n\t\tconst lzma_vli count = lzma_index_block_count(coder->index);\n\t\tret = lzma_vli_encode(count, &coder->pos,\n\t\t\t\tout, out_pos, out_size);\n\t\tif (ret != LZMA_STREAM_END)\n\t\t\tgoto out;\n\n\t\tret = LZMA_OK;\n\t\tcoder->pos = 0;\n\t\tcoder->sequence = SEQ_NEXT;\n\t\tbreak;\n\t}\n\n\tcase SEQ_NEXT:\n\t\tif (lzma_index_iter_next(\n\t\t\t\t&coder->iter, LZMA_INDEX_ITER_BLOCK)) {\n\t\t\t// Get the size of the Index Padding field.\n\t\t\tcoder->pos = lzma_index_padding_size(coder->index);\n\t\t\tassert(coder->pos <= 3);\n\t\t\tcoder->sequence = SEQ_PADDING;\n\t\t\tbreak;\n\t\t}\n\n\t\tcoder->sequence = SEQ_UNPADDED;\n\n\t// Fall through\n\n\tcase SEQ_UNPADDED:\n\tcase SEQ_UNCOMPRESSED: {\n\t\tconst lzma_vli size = coder->sequence == SEQ_UNPADDED\n\t\t\t\t? coder->iter.block.unpadded_size\n\t\t\t\t: coder->iter.block.uncompressed_size;\n\n\t\tret = lzma_vli_encode(size, &coder->pos,\n\t\t\t\tout, out_pos, out_size);\n\t\tif (ret != LZMA_STREAM_END)\n\t\t\tgoto out;\n\n\t\tret = LZMA_OK;\n\t\tcoder->pos = 0;\n\n\t\t// Advance to SEQ_UNCOMPRESSED or SEQ_NEXT.\n\t\t++coder->sequence;\n\t\tbreak;\n\t}\n\n\tcase SEQ_PADDING:\n\t\tif (coder->pos > 0) {\n\t\t\t--coder->pos;\n\t\t\tout[(*out_pos)++] = 0x00;\n\t\t\tbreak;\n\t\t}\n\n\t\t// Finish the CRC32 calculation.\n\t\tcoder->crc32 = lzma_crc32(out + out_start,\n\t\t\t\t*out_pos - out_start, coder->crc32);\n\n\t\tcoder->sequence = SEQ_CRC32;\n\n\t// Fall through\n\n\tcase SEQ_CRC32:\n\t\t// We don't use the main loop, because we don't want\n\t\t// coder->crc32 to be touched anymore.\n\t\tdo {\n\t\t\tif (*out_pos == out_size)\n\t\t\t\treturn LZMA_OK;\n\n\t\t\tout[*out_pos] = (coder->crc32 >> (coder->pos * 8))\n\t\t\t\t\t& 0xFF;\n\t\t\t++*out_pos;\n\n\t\t} while (++coder->pos < 4);\n\n\t\treturn LZMA_STREAM_END;\n\n\tdefault:\n\t\tassert(0);\n\t\treturn LZMA_PROG_ERROR;\n\t}\n\nout:\n\t// Update the CRC32.\n\tcoder->crc32 = lzma_crc32(out + out_start,\n\t\t\t*out_pos - out_start, coder->crc32);\n\n\treturn ret;\n}\n\n\nstatic void\nindex_encoder_end(void *coder, const lzma_allocator *allocator)\n{\n\tlzma_free(coder, allocator);\n\treturn;\n}\n\n\nstatic void\nindex_encoder_reset(lzma_index_coder *coder, const lzma_index *i)\n{\n\tlzma_index_iter_init(&coder->iter, i);\n\n\tcoder->sequence = SEQ_INDICATOR;\n\tcoder->index = i;\n\tcoder->pos = 0;\n\tcoder->crc32 = 0;\n\n\treturn;\n}\n\n\nextern lzma_ret\nlzma_index_encoder_init(lzma_next_coder *next, const lzma_allocator *allocator,\n\t\tconst lzma_index *i)\n{\n\tlzma_next_coder_init(&lzma_index_encoder_init, next, allocator);\n\n\tif (i == NULL)\n\t\treturn LZMA_PROG_ERROR;\n\n\tif (next->coder == NULL) {\n\t\tnext->coder = lzma_alloc(sizeof(lzma_index_coder), allocator);\n\t\tif (next->coder == NULL)\n\t\t\treturn LZMA_MEM_ERROR;\n\n\t\tnext->code = &index_encode;\n\t\tnext->end = &index_encoder_end;\n\t}\n\n\tindex_encoder_reset(next->coder, i);\n\n\treturn LZMA_OK;\n}\n\n\nextern LZMA_API(lzma_ret)\nlzma_index_encoder(lzma_stream *strm, const lzma_index *i)\n{\n\tlzma_next_strm_init(lzma_index_encoder_init, strm, i);\n\n\tstrm->internal->supported_actions[LZMA_RUN] = true;\n\tstrm->internal->supported_actions[LZMA_FINISH] = true;\n\n\treturn LZMA_OK;\n}\n\n\nextern LZMA_API(lzma_ret)\nlzma_index_buffer_encode(const lzma_index *i,\n\t\tuint8_t *out, size_t *out_pos, size_t out_size)\n{\n\t// Validate the arguments.\n\tif (i == NULL || out == NULL || out_pos == NULL || *out_pos > out_size)\n\t\treturn LZMA_PROG_ERROR;\n\n\t// Don't try to encode if there's not enough output space.\n\tif (out_size - *out_pos < lzma_index_size(i))\n\t\treturn LZMA_BUF_ERROR;\n\n\t// The Index encoder needs just one small data structure so we can\n\t// allocate it on stack.\n\tlzma_index_coder coder;\n\tindex_encoder_reset(&coder, i);\n\n\t// Do the actual encoding. This should never fail, but store\n\t// the original *out_pos just in case.\n\tconst size_t out_start = *out_pos;\n\tlzma_ret ret = index_encode(&coder, NULL, NULL, NULL, 0,\n\t\t\tout, out_pos, out_size, LZMA_RUN);\n\n\tif (ret == LZMA_STREAM_END) {\n\t\tret = LZMA_OK;\n\t} else {\n\t\t// We should never get here, but just in case, restore the\n\t\t// output position and set the error accordingly if something\n\t\t// goes wrong and debugging isn't enabled.\n\t\tassert(0);\n\t\t*out_pos = out_start;\n\t\tret = LZMA_PROG_ERROR;\n\t}\n\n\treturn ret;\n}\n"
  },
  {
    "path": "external/xz/liblzma/common/index_encoder.h",
    "content": "///////////////////////////////////////////////////////////////////////////////\n//\n/// \\file       index_encoder.h\n/// \\brief      Encodes the Index field\n//\n//  Author:     Lasse Collin\n//\n//  This file has been put into the public domain.\n//  You can do whatever you want with this file.\n//\n///////////////////////////////////////////////////////////////////////////////\n\n#ifndef LZMA_INDEX_ENCODER_H\n#define LZMA_INDEX_ENCODER_H\n\n#include \"common.h\"\n\n\nextern lzma_ret lzma_index_encoder_init(lzma_next_coder *next,\n\t\tconst lzma_allocator *allocator, const lzma_index *i);\n\n\n#endif\n"
  },
  {
    "path": "external/xz/liblzma/common/index_hash.c",
    "content": "///////////////////////////////////////////////////////////////////////////////\n//\n/// \\file       index_hash.c\n/// \\brief      Validates Index by using a hash function\n//\n//  Author:     Lasse Collin\n//\n//  This file has been put into the public domain.\n//  You can do whatever you want with this file.\n//\n///////////////////////////////////////////////////////////////////////////////\n\n#include \"common.h\"\n#include \"index.h\"\n#include \"check.h\"\n\n\ntypedef struct {\n\t/// Sum of the Block sizes (including Block Padding)\n\tlzma_vli blocks_size;\n\n\t/// Sum of the Uncompressed Size fields\n\tlzma_vli uncompressed_size;\n\n\t/// Number of Records\n\tlzma_vli count;\n\n\t/// Size of the List of Index Records as bytes\n\tlzma_vli index_list_size;\n\n\t/// Check calculated from Unpadded Sizes and Uncompressed Sizes.\n\tlzma_check_state check;\n\n} lzma_index_hash_info;\n\n\nstruct lzma_index_hash_s {\n\tenum {\n\t\tSEQ_BLOCK,\n\t\tSEQ_COUNT,\n\t\tSEQ_UNPADDED,\n\t\tSEQ_UNCOMPRESSED,\n\t\tSEQ_PADDING_INIT,\n\t\tSEQ_PADDING,\n\t\tSEQ_CRC32,\n\t} sequence;\n\n\t/// Information collected while decoding the actual Blocks.\n\tlzma_index_hash_info blocks;\n\n\t/// Information collected from the Index field.\n\tlzma_index_hash_info records;\n\n\t/// Number of Records not fully decoded\n\tlzma_vli remaining;\n\n\t/// Unpadded Size currently being read from an Index Record.\n\tlzma_vli unpadded_size;\n\n\t/// Uncompressed Size currently being read from an Index Record.\n\tlzma_vli uncompressed_size;\n\n\t/// Position in variable-length integers when decoding them from\n\t/// the List of Records.\n\tsize_t pos;\n\n\t/// CRC32 of the Index\n\tuint32_t crc32;\n};\n\n\nextern LZMA_API(lzma_index_hash *)\nlzma_index_hash_init(lzma_index_hash *index_hash,\n\t\tconst lzma_allocator *allocator)\n{\n\tif (index_hash == NULL) {\n\t\tindex_hash = lzma_alloc(sizeof(lzma_index_hash), allocator);\n\t\tif (index_hash == NULL)\n\t\t\treturn NULL;\n\t}\n\n\tindex_hash->sequence = SEQ_BLOCK;\n\tindex_hash->blocks.blocks_size = 0;\n\tindex_hash->blocks.uncompressed_size = 0;\n\tindex_hash->blocks.count = 0;\n\tindex_hash->blocks.index_list_size = 0;\n\tindex_hash->records.blocks_size = 0;\n\tindex_hash->records.uncompressed_size = 0;\n\tindex_hash->records.count = 0;\n\tindex_hash->records.index_list_size = 0;\n\tindex_hash->unpadded_size = 0;\n\tindex_hash->uncompressed_size = 0;\n\tindex_hash->pos = 0;\n\tindex_hash->crc32 = 0;\n\n\t// These cannot fail because LZMA_CHECK_BEST is known to be supported.\n\t(void)lzma_check_init(&index_hash->blocks.check, LZMA_CHECK_BEST);\n\t(void)lzma_check_init(&index_hash->records.check, LZMA_CHECK_BEST);\n\n\treturn index_hash;\n}\n\n\nextern LZMA_API(void)\nlzma_index_hash_end(lzma_index_hash *index_hash,\n\t\tconst lzma_allocator *allocator)\n{\n\tlzma_free(index_hash, allocator);\n\treturn;\n}\n\n\nextern LZMA_API(lzma_vli)\nlzma_index_hash_size(const lzma_index_hash *index_hash)\n{\n\t// Get the size of the Index from ->blocks instead of ->records for\n\t// cases where application wants to know the Index Size before\n\t// decoding the Index.\n\treturn index_size(index_hash->blocks.count,\n\t\t\tindex_hash->blocks.index_list_size);\n}\n\n\n/// Updates the sizes and the hash without any validation.\nstatic lzma_ret\nhash_append(lzma_index_hash_info *info, lzma_vli unpadded_size,\n\t\tlzma_vli uncompressed_size)\n{\n\tinfo->blocks_size += vli_ceil4(unpadded_size);\n\tinfo->uncompressed_size += uncompressed_size;\n\tinfo->index_list_size += lzma_vli_size(unpadded_size)\n\t\t\t+ lzma_vli_size(uncompressed_size);\n\t++info->count;\n\n\tconst lzma_vli sizes[2] = { unpadded_size, uncompressed_size };\n\tlzma_check_update(&info->check, LZMA_CHECK_BEST,\n\t\t\t(const uint8_t *)(sizes), sizeof(sizes));\n\n\treturn LZMA_OK;\n}\n\n\nextern LZMA_API(lzma_ret)\nlzma_index_hash_append(lzma_index_hash *index_hash, lzma_vli unpadded_size,\n\t\tlzma_vli uncompressed_size)\n{\n\t// Validate the arguments.\n\tif (index_hash->sequence != SEQ_BLOCK\n\t\t\t|| unpadded_size < UNPADDED_SIZE_MIN\n\t\t\t|| unpadded_size > UNPADDED_SIZE_MAX\n\t\t\t|| uncompressed_size > LZMA_VLI_MAX)\n\t\treturn LZMA_PROG_ERROR;\n\n\t// Update the hash.\n\treturn_if_error(hash_append(&index_hash->blocks,\n\t\t\tunpadded_size, uncompressed_size));\n\n\t// Validate the properties of *info are still in allowed limits.\n\tif (index_hash->blocks.blocks_size > LZMA_VLI_MAX\n\t\t\t|| index_hash->blocks.uncompressed_size > LZMA_VLI_MAX\n\t\t\t|| index_size(index_hash->blocks.count,\n\t\t\t\t\tindex_hash->blocks.index_list_size)\n\t\t\t\t> LZMA_BACKWARD_SIZE_MAX\n\t\t\t|| index_stream_size(index_hash->blocks.blocks_size,\n\t\t\t\t\tindex_hash->blocks.count,\n\t\t\t\t\tindex_hash->blocks.index_list_size)\n\t\t\t\t> LZMA_VLI_MAX)\n\t\treturn LZMA_DATA_ERROR;\n\n\treturn LZMA_OK;\n}\n\n\nextern LZMA_API(lzma_ret)\nlzma_index_hash_decode(lzma_index_hash *index_hash, const uint8_t *in,\n\t\tsize_t *in_pos, size_t in_size)\n{\n\t// Catch zero input buffer here, because in contrast to Index encoder\n\t// and decoder functions, applications call this function directly\n\t// instead of via lzma_code(), which does the buffer checking.\n\tif (*in_pos >= in_size)\n\t\treturn LZMA_BUF_ERROR;\n\n\t// NOTE: This function has many similarities to index_encode() and\n\t// index_decode() functions found from index_encoder.c and\n\t// index_decoder.c. See the comments especially in index_encoder.c.\n\tconst size_t in_start = *in_pos;\n\tlzma_ret ret = LZMA_OK;\n\n\twhile (*in_pos < in_size)\n\tswitch (index_hash->sequence) {\n\tcase SEQ_BLOCK:\n\t\t// Check the Index Indicator is present.\n\t\tif (in[(*in_pos)++] != 0x00)\n\t\t\treturn LZMA_DATA_ERROR;\n\n\t\tindex_hash->sequence = SEQ_COUNT;\n\t\tbreak;\n\n\tcase SEQ_COUNT: {\n\t\tret = lzma_vli_decode(&index_hash->remaining,\n\t\t\t\t&index_hash->pos, in, in_pos, in_size);\n\t\tif (ret != LZMA_STREAM_END)\n\t\t\tgoto out;\n\n\t\t// The count must match the count of the Blocks decoded.\n\t\tif (index_hash->remaining != index_hash->blocks.count)\n\t\t\treturn LZMA_DATA_ERROR;\n\n\t\tret = LZMA_OK;\n\t\tindex_hash->pos = 0;\n\n\t\t// Handle the special case when there are no Blocks.\n\t\tindex_hash->sequence = index_hash->remaining == 0\n\t\t\t\t? SEQ_PADDING_INIT : SEQ_UNPADDED;\n\t\tbreak;\n\t}\n\n\tcase SEQ_UNPADDED:\n\tcase SEQ_UNCOMPRESSED: {\n\t\tlzma_vli *size = index_hash->sequence == SEQ_UNPADDED\n\t\t\t\t? &index_hash->unpadded_size\n\t\t\t\t: &index_hash->uncompressed_size;\n\n\t\tret = lzma_vli_decode(size, &index_hash->pos,\n\t\t\t\tin, in_pos, in_size);\n\t\tif (ret != LZMA_STREAM_END)\n\t\t\tgoto out;\n\n\t\tret = LZMA_OK;\n\t\tindex_hash->pos = 0;\n\n\t\tif (index_hash->sequence == SEQ_UNPADDED) {\n\t\t\tif (index_hash->unpadded_size < UNPADDED_SIZE_MIN\n\t\t\t\t\t|| index_hash->unpadded_size\n\t\t\t\t\t\t> UNPADDED_SIZE_MAX)\n\t\t\t\treturn LZMA_DATA_ERROR;\n\n\t\t\tindex_hash->sequence = SEQ_UNCOMPRESSED;\n\t\t} else {\n\t\t\t// Update the hash.\n\t\t\treturn_if_error(hash_append(&index_hash->records,\n\t\t\t\t\tindex_hash->unpadded_size,\n\t\t\t\t\tindex_hash->uncompressed_size));\n\n\t\t\t// Verify that we don't go over the known sizes. Note\n\t\t\t// that this validation is simpler than the one used\n\t\t\t// in lzma_index_hash_append(), because here we know\n\t\t\t// that values in index_hash->blocks are already\n\t\t\t// validated and we are fine as long as we don't\n\t\t\t// exceed them in index_hash->records.\n\t\t\tif (index_hash->blocks.blocks_size\n\t\t\t\t\t< index_hash->records.blocks_size\n\t\t\t\t\t|| index_hash->blocks.uncompressed_size\n\t\t\t\t\t< index_hash->records.uncompressed_size\n\t\t\t\t\t|| index_hash->blocks.index_list_size\n\t\t\t\t\t< index_hash->records.index_list_size)\n\t\t\t\treturn LZMA_DATA_ERROR;\n\n\t\t\t// Check if this was the last Record.\n\t\t\tindex_hash->sequence = --index_hash->remaining == 0\n\t\t\t\t\t? SEQ_PADDING_INIT : SEQ_UNPADDED;\n\t\t}\n\n\t\tbreak;\n\t}\n\n\tcase SEQ_PADDING_INIT:\n\t\tindex_hash->pos = (LZMA_VLI_C(4) - index_size_unpadded(\n\t\t\t\tindex_hash->records.count,\n\t\t\t\tindex_hash->records.index_list_size)) & 3;\n\t\tindex_hash->sequence = SEQ_PADDING;\n\n\t// Fall through\n\n\tcase SEQ_PADDING:\n\t\tif (index_hash->pos > 0) {\n\t\t\t--index_hash->pos;\n\t\t\tif (in[(*in_pos)++] != 0x00)\n\t\t\t\treturn LZMA_DATA_ERROR;\n\n\t\t\tbreak;\n\t\t}\n\n\t\t// Compare the sizes.\n\t\tif (index_hash->blocks.blocks_size\n\t\t\t\t!= index_hash->records.blocks_size\n\t\t\t\t|| index_hash->blocks.uncompressed_size\n\t\t\t\t!= index_hash->records.uncompressed_size\n\t\t\t\t|| index_hash->blocks.index_list_size\n\t\t\t\t!= index_hash->records.index_list_size)\n\t\t\treturn LZMA_DATA_ERROR;\n\n\t\t// Finish the hashes and compare them.\n\t\tlzma_check_finish(&index_hash->blocks.check, LZMA_CHECK_BEST);\n\t\tlzma_check_finish(&index_hash->records.check, LZMA_CHECK_BEST);\n\t\tif (memcmp(index_hash->blocks.check.buffer.u8,\n\t\t\t\tindex_hash->records.check.buffer.u8,\n\t\t\t\tlzma_check_size(LZMA_CHECK_BEST)) != 0)\n\t\t\treturn LZMA_DATA_ERROR;\n\n\t\t// Finish the CRC32 calculation.\n\t\tindex_hash->crc32 = lzma_crc32(in + in_start,\n\t\t\t\t*in_pos - in_start, index_hash->crc32);\n\n\t\tindex_hash->sequence = SEQ_CRC32;\n\n\t// Fall through\n\n\tcase SEQ_CRC32:\n\t\tdo {\n\t\t\tif (*in_pos == in_size)\n\t\t\t\treturn LZMA_OK;\n\n\t\t\tif (((index_hash->crc32 >> (index_hash->pos * 8))\n\t\t\t\t\t& 0xFF) != in[(*in_pos)++])\n\t\t\t\treturn LZMA_DATA_ERROR;\n\n\t\t} while (++index_hash->pos < 4);\n\n\t\treturn LZMA_STREAM_END;\n\n\tdefault:\n\t\tassert(0);\n\t\treturn LZMA_PROG_ERROR;\n\t}\n\nout:\n\t// Update the CRC32,\n\tindex_hash->crc32 = lzma_crc32(in + in_start,\n\t\t\t*in_pos - in_start, index_hash->crc32);\n\n\treturn ret;\n}\n"
  },
  {
    "path": "external/xz/liblzma/common/memcmplen.h",
    "content": "///////////////////////////////////////////////////////////////////////////////\n//\n/// \\file       memcmplen.h\n/// \\brief      Optimized comparison of two buffers\n//\n//  Author:     Lasse Collin\n//\n//  This file has been put into the public domain.\n//  You can do whatever you want with this file.\n//\n///////////////////////////////////////////////////////////////////////////////\n\n#ifndef LZMA_MEMCMPLEN_H\n#define LZMA_MEMCMPLEN_H\n\n#include \"common.h\"\n\n#ifdef HAVE_IMMINTRIN_H\n#\tinclude <immintrin.h>\n#endif\n\n\n/// Find out how many equal bytes the two buffers have.\n///\n/// \\param      buf1    First buffer\n/// \\param      buf2    Second buffer\n/// \\param      len     How many bytes have already been compared and will\n///                     be assumed to match\n/// \\param      limit   How many bytes to compare at most, including the\n///                     already-compared bytes. This must be significantly\n///                     smaller than UINT32_MAX to avoid integer overflows.\n///                     Up to LZMA_MEMCMPLEN_EXTRA bytes may be read past\n///                     the specified limit from both buf1 and buf2.\n///\n/// \\return     Number of equal bytes in the buffers is returned.\n///             This is always at least len and at most limit.\n///\n/// \\note       LZMA_MEMCMPLEN_EXTRA defines how many extra bytes may be read.\n///             It's rounded up to 2^n. This extra amount needs to be\n///             allocated in the buffers being used. It needs to be\n///             initialized too to keep Valgrind quiet.\nstatic inline uint32_t lzma_attribute((__always_inline__))\nlzma_memcmplen(const uint8_t *buf1, const uint8_t *buf2,\n\t\tuint32_t len, uint32_t limit)\n{\n\tassert(len <= limit);\n\tassert(limit <= UINT32_MAX / 2);\n\n#if defined(TUKLIB_FAST_UNALIGNED_ACCESS) \\\n\t\t&& ((TUKLIB_GNUC_REQ(3, 4) && defined(__x86_64__)) \\\n\t\t\t|| (defined(__INTEL_COMPILER) && defined(__x86_64__)) \\\n\t\t\t|| (defined(__INTEL_COMPILER) && defined(_M_X64)) \\\n\t\t\t|| (defined(_MSC_VER) && defined(_M_X64)))\n\t// NOTE: This will use 64-bit unaligned access which\n\t// TUKLIB_FAST_UNALIGNED_ACCESS wasn't meant to permit, but\n\t// it's convenient here at least as long as it's x86-64 only.\n\t//\n\t// I keep this x86-64 only for now since that's where I know this\n\t// to be a good method. This may be fine on other 64-bit CPUs too.\n\t// On big endian one should use xor instead of subtraction and switch\n\t// to __builtin_clzll().\n#define LZMA_MEMCMPLEN_EXTRA 8\n\twhile (len < limit) {\n\t\tconst uint64_t x = read64ne(buf1 + len) - read64ne(buf2 + len);\n\t\tif (x != 0) {\n#\tif defined(_M_X64) // MSVC or Intel C compiler on Windows\n\t\t\tunsigned long tmp;\n\t\t\t_BitScanForward64(&tmp, x);\n\t\t\tlen += (uint32_t)tmp >> 3;\n#\telse // GCC, clang, or Intel C compiler\n\t\t\tlen += (uint32_t)__builtin_ctzll(x) >> 3;\n#\tendif\n\t\t\treturn my_min(len, limit);\n\t\t}\n\n\t\tlen += 8;\n\t}\n\n\treturn limit;\n\n#elif defined(TUKLIB_FAST_UNALIGNED_ACCESS) \\\n\t\t&& defined(HAVE__MM_MOVEMASK_EPI8) \\\n\t\t&& ((defined(__GNUC__) && defined(__SSE2_MATH__)) \\\n\t\t\t|| (defined(__INTEL_COMPILER) && defined(__SSE2__)) \\\n\t\t\t|| (defined(_MSC_VER) && defined(_M_IX86_FP) \\\n\t\t\t\t&& _M_IX86_FP >= 2))\n\t// NOTE: Like above, this will use 128-bit unaligned access which\n\t// TUKLIB_FAST_UNALIGNED_ACCESS wasn't meant to permit.\n\t//\n\t// SSE2 version for 32-bit and 64-bit x86. On x86-64 the above\n\t// version is sometimes significantly faster and sometimes\n\t// slightly slower than this SSE2 version, so this SSE2\n\t// version isn't used on x86-64.\n#\tdefine LZMA_MEMCMPLEN_EXTRA 16\n\twhile (len < limit) {\n\t\tconst uint32_t x = 0xFFFF ^ _mm_movemask_epi8(_mm_cmpeq_epi8(\n\t\t\t_mm_loadu_si128((const __m128i *)(buf1 + len)),\n\t\t\t_mm_loadu_si128((const __m128i *)(buf2 + len))));\n\n\t\tif (x != 0) {\n\t\t\tlen += ctz32(x);\n\t\t\treturn my_min(len, limit);\n\t\t}\n\n\t\tlen += 16;\n\t}\n\n\treturn limit;\n\n#elif defined(TUKLIB_FAST_UNALIGNED_ACCESS) && !defined(WORDS_BIGENDIAN)\n\t// Generic 32-bit little endian method\n#\tdefine LZMA_MEMCMPLEN_EXTRA 4\n\twhile (len < limit) {\n\t\tuint32_t x = read32ne(buf1 + len) - read32ne(buf2 + len);\n\t\tif (x != 0) {\n\t\t\tif ((x & 0xFFFF) == 0) {\n\t\t\t\tlen += 2;\n\t\t\t\tx >>= 16;\n\t\t\t}\n\n\t\t\tif ((x & 0xFF) == 0)\n\t\t\t\t++len;\n\n\t\t\treturn my_min(len, limit);\n\t\t}\n\n\t\tlen += 4;\n\t}\n\n\treturn limit;\n\n#elif defined(TUKLIB_FAST_UNALIGNED_ACCESS) && defined(WORDS_BIGENDIAN)\n\t// Generic 32-bit big endian method\n#\tdefine LZMA_MEMCMPLEN_EXTRA 4\n\twhile (len < limit) {\n\t\tuint32_t x = read32ne(buf1 + len) ^ read32ne(buf2 + len);\n\t\tif (x != 0) {\n\t\t\tif ((x & 0xFFFF0000) == 0) {\n\t\t\t\tlen += 2;\n\t\t\t\tx <<= 16;\n\t\t\t}\n\n\t\t\tif ((x & 0xFF000000) == 0)\n\t\t\t\t++len;\n\n\t\t\treturn my_min(len, limit);\n\t\t}\n\n\t\tlen += 4;\n\t}\n\n\treturn limit;\n\n#else\n\t// Simple portable version that doesn't use unaligned access.\n#\tdefine LZMA_MEMCMPLEN_EXTRA 0\n\twhile (len < limit && buf1[len] == buf2[len])\n\t\t++len;\n\n\treturn len;\n#endif\n}\n\n#endif\n"
  },
  {
    "path": "external/xz/liblzma/common/outqueue.c",
    "content": "///////////////////////////////////////////////////////////////////////////////\n//\n/// \\file       outqueue.c\n/// \\brief      Output queue handling in multithreaded coding\n//\n//  Author:     Lasse Collin\n//\n//  This file has been put into the public domain.\n//  You can do whatever you want with this file.\n//\n///////////////////////////////////////////////////////////////////////////////\n\n#include \"outqueue.h\"\n\n\n/// This is to ease integer overflow checking: We may allocate up to\n/// 2 * LZMA_THREADS_MAX buffers and we need some extra memory for other\n/// data structures (that's the second /2).\n#define BUF_SIZE_MAX (UINT64_MAX / LZMA_THREADS_MAX / 2 / 2)\n\n\nstatic lzma_ret\nget_options(uint64_t *bufs_alloc_size, uint32_t *bufs_count,\n\t\tuint64_t buf_size_max, uint32_t threads)\n{\n\tif (threads > LZMA_THREADS_MAX || buf_size_max > BUF_SIZE_MAX)\n\t\treturn LZMA_OPTIONS_ERROR;\n\n\t// The number of buffers is twice the number of threads.\n\t// This wastes RAM but keeps the threads busy when buffers\n\t// finish out of order.\n\t//\n\t// NOTE: If this is changed, update BUF_SIZE_MAX too.\n\t*bufs_count = threads * 2;\n\t*bufs_alloc_size = *bufs_count * buf_size_max;\n\n\treturn LZMA_OK;\n}\n\n\nextern uint64_t\nlzma_outq_memusage(uint64_t buf_size_max, uint32_t threads)\n{\n\tuint64_t bufs_alloc_size;\n\tuint32_t bufs_count;\n\n\tif (get_options(&bufs_alloc_size, &bufs_count, buf_size_max, threads)\n\t\t\t!= LZMA_OK)\n\t\treturn UINT64_MAX;\n\n\treturn sizeof(lzma_outq) + bufs_count * sizeof(lzma_outbuf)\n\t\t\t+ bufs_alloc_size;\n}\n\n\nextern lzma_ret\nlzma_outq_init(lzma_outq *outq, const lzma_allocator *allocator,\n\t\tuint64_t buf_size_max, uint32_t threads)\n{\n\tuint64_t bufs_alloc_size;\n\tuint32_t bufs_count;\n\n\t// Set bufs_count and bufs_alloc_size.\n\treturn_if_error(get_options(&bufs_alloc_size, &bufs_count,\n\t\t\tbuf_size_max, threads));\n\n\t// Allocate memory if needed.\n\tif (outq->buf_size_max != buf_size_max\n\t\t\t|| outq->bufs_allocated != bufs_count) {\n\t\tlzma_outq_end(outq, allocator);\n\n#if SIZE_MAX < UINT64_MAX\n\t\tif (bufs_alloc_size > SIZE_MAX)\n\t\t\treturn LZMA_MEM_ERROR;\n#endif\n\n\t\toutq->bufs = lzma_alloc(bufs_count * sizeof(lzma_outbuf),\n\t\t\t\tallocator);\n\t\toutq->bufs_mem = lzma_alloc((size_t)(bufs_alloc_size),\n\t\t\t\tallocator);\n\n\t\tif (outq->bufs == NULL || outq->bufs_mem == NULL) {\n\t\t\tlzma_outq_end(outq, allocator);\n\t\t\treturn LZMA_MEM_ERROR;\n\t\t}\n\t}\n\n\t// Initialize the rest of the main structure. Initialization of\n\t// outq->bufs[] is done when they are actually needed.\n\toutq->buf_size_max = (size_t)(buf_size_max);\n\toutq->bufs_allocated = bufs_count;\n\toutq->bufs_pos = 0;\n\toutq->bufs_used = 0;\n\toutq->read_pos = 0;\n\n\treturn LZMA_OK;\n}\n\n\nextern void\nlzma_outq_end(lzma_outq *outq, const lzma_allocator *allocator)\n{\n\tlzma_free(outq->bufs, allocator);\n\toutq->bufs = NULL;\n\n\tlzma_free(outq->bufs_mem, allocator);\n\toutq->bufs_mem = NULL;\n\n\treturn;\n}\n\n\nextern lzma_outbuf *\nlzma_outq_get_buf(lzma_outq *outq)\n{\n\t// Caller must have checked it with lzma_outq_has_buf().\n\tassert(outq->bufs_used < outq->bufs_allocated);\n\n\t// Initialize the new buffer.\n\tlzma_outbuf *buf = &outq->bufs[outq->bufs_pos];\n\tbuf->buf = outq->bufs_mem + outq->bufs_pos * outq->buf_size_max;\n\tbuf->size = 0;\n\tbuf->finished = false;\n\n\t// Update the queue state.\n\tif (++outq->bufs_pos == outq->bufs_allocated)\n\t\toutq->bufs_pos = 0;\n\n\t++outq->bufs_used;\n\n\treturn buf;\n}\n\n\nextern bool\nlzma_outq_is_readable(const lzma_outq *outq)\n{\n\tuint32_t i = outq->bufs_pos - outq->bufs_used;\n\tif (outq->bufs_pos < outq->bufs_used)\n\t\ti += outq->bufs_allocated;\n\n\treturn outq->bufs[i].finished;\n}\n\n\nextern lzma_ret\nlzma_outq_read(lzma_outq *restrict outq, uint8_t *restrict out,\n\t\tsize_t *restrict out_pos, size_t out_size,\n\t\tlzma_vli *restrict unpadded_size,\n\t\tlzma_vli *restrict uncompressed_size)\n{\n\t// There must be at least one buffer from which to read.\n\tif (outq->bufs_used == 0)\n\t\treturn LZMA_OK;\n\n\t// Get the buffer.\n\tuint32_t i = outq->bufs_pos - outq->bufs_used;\n\tif (outq->bufs_pos < outq->bufs_used)\n\t\ti += outq->bufs_allocated;\n\n\tlzma_outbuf *buf = &outq->bufs[i];\n\n\t// If it isn't finished yet, we cannot read from it.\n\tif (!buf->finished)\n\t\treturn LZMA_OK;\n\n\t// Copy from the buffer to output.\n\tlzma_bufcpy(buf->buf, &outq->read_pos, buf->size,\n\t\t\tout, out_pos, out_size);\n\n\t// Return if we didn't get all the data from the buffer.\n\tif (outq->read_pos < buf->size)\n\t\treturn LZMA_OK;\n\n\t// The buffer was finished. Tell the caller its size information.\n\t*unpadded_size = buf->unpadded_size;\n\t*uncompressed_size = buf->uncompressed_size;\n\n\t// Free this buffer for further use.\n\t--outq->bufs_used;\n\toutq->read_pos = 0;\n\n\treturn LZMA_STREAM_END;\n}\n"
  },
  {
    "path": "external/xz/liblzma/common/outqueue.h",
    "content": "///////////////////////////////////////////////////////////////////////////////\n//\n/// \\file       outqueue.h\n/// \\brief      Output queue handling in multithreaded coding\n//\n//  Author:     Lasse Collin\n//\n//  This file has been put into the public domain.\n//  You can do whatever you want with this file.\n//\n///////////////////////////////////////////////////////////////////////////////\n\n#include \"common.h\"\n\n\n/// Output buffer for a single thread\ntypedef struct {\n\t/// Pointer to the output buffer of lzma_outq.buf_size_max bytes\n\tuint8_t *buf;\n\n\t/// Amount of data written to buf\n\tsize_t size;\n\n\t/// Additional size information\n\tlzma_vli unpadded_size;\n\tlzma_vli uncompressed_size;\n\n\t/// True when no more data will be written into this buffer.\n\t///\n\t/// \\note       This is read by another thread and thus access\n\t///             to this variable needs a mutex.\n\tbool finished;\n\n} lzma_outbuf;\n\n\ntypedef struct {\n\t/// Array of buffers that are used cyclically.\n\tlzma_outbuf *bufs;\n\n\t/// Memory allocated for all the buffers\n\tuint8_t *bufs_mem;\n\n\t/// Amount of buffer space available in each buffer\n\tsize_t buf_size_max;\n\n\t/// Number of buffers allocated\n\tuint32_t bufs_allocated;\n\n\t/// Position in the bufs array. The next buffer to be taken\n\t/// into use is bufs[bufs_pos].\n\tuint32_t bufs_pos;\n\n\t/// Number of buffers in use\n\tuint32_t bufs_used;\n\n\t/// Position in the buffer in lzma_outq_read()\n\tsize_t read_pos;\n\n} lzma_outq;\n\n\n/**\n * \\brief       Calculate the memory usage of an output queue\n *\n * \\return      Approximate memory usage in bytes or UINT64_MAX on error.\n */\nextern uint64_t lzma_outq_memusage(uint64_t buf_size_max, uint32_t threads);\n\n\n/// \\brief      Initialize an output queue\n///\n/// \\param      outq            Pointer to an output queue. Before calling\n///                             this function the first time, *outq should\n///                             have been zeroed with memzero() so that this\n///                             function knows that there are no previous\n///                             allocations to free.\n/// \\param      allocator       Pointer to allocator or NULL\n/// \\param      buf_size_max    Maximum amount of data that a single buffer\n///                             in the queue may need to store.\n/// \\param      threads         Number of buffers that may be in use\n///                             concurrently. Note that more than this number\n///                             of buffers will actually get allocated to\n///                             improve performance when buffers finish\n///                             out of order.\n///\n/// \\return     - LZMA_OK\n///             - LZMA_MEM_ERROR\n///\nextern lzma_ret lzma_outq_init(\n\t\tlzma_outq *outq, const lzma_allocator *allocator,\n\t\tuint64_t buf_size_max, uint32_t threads);\n\n\n/// \\brief      Free the memory associated with the output queue\nextern void lzma_outq_end(lzma_outq *outq, const lzma_allocator *allocator);\n\n\n/// \\brief      Get a new buffer\n///\n/// lzma_outq_has_buf() must be used to check that there is a buffer\n/// available before calling lzma_outq_get_buf().\n///\nextern lzma_outbuf *lzma_outq_get_buf(lzma_outq *outq);\n\n\n/// \\brief      Test if there is data ready to be read\n///\n/// Call to this function must be protected with the same mutex that\n/// is used to protect lzma_outbuf.finished.\n///\nextern bool lzma_outq_is_readable(const lzma_outq *outq);\n\n\n/// \\brief      Read finished data\n///\n/// \\param      outq            Pointer to an output queue\n/// \\param      out             Beginning of the output buffer\n/// \\param      out_pos         The next byte will be written to\n///                             out[*out_pos].\n/// \\param      out_size        Size of the out buffer; the first byte into\n///                             which no data is written to is out[out_size].\n/// \\param      unpadded_size   Unpadded Size from the Block encoder\n/// \\param      uncompressed_size Uncompressed Size from the Block encoder\n///\n/// \\return     - LZMA: All OK. Either no data was available or the buffer\n///               being read didn't become empty yet.\n///             - LZMA_STREAM_END: The buffer being read was finished.\n///               *unpadded_size and *uncompressed_size were set.\n///\n/// \\note       This reads lzma_outbuf.finished variables and thus call\n///             to this function needs to be protected with a mutex.\n///\nextern lzma_ret lzma_outq_read(lzma_outq *restrict outq,\n\t\tuint8_t *restrict out, size_t *restrict out_pos,\n\t\tsize_t out_size, lzma_vli *restrict unpadded_size,\n\t\tlzma_vli *restrict uncompressed_size);\n\n\n/// \\brief      Test if there is at least one buffer free\n///\n/// This must be used before getting a new buffer with lzma_outq_get_buf().\n///\nstatic inline bool\nlzma_outq_has_buf(const lzma_outq *outq)\n{\n\treturn outq->bufs_used < outq->bufs_allocated;\n}\n\n\n/// \\brief      Test if the queue is completely empty\nstatic inline bool\nlzma_outq_is_empty(const lzma_outq *outq)\n{\n\treturn outq->bufs_used == 0;\n}\n"
  },
  {
    "path": "external/xz/liblzma/common/stream_buffer_decoder.c",
    "content": "///////////////////////////////////////////////////////////////////////////////\n//\n/// \\file       stream_buffer_decoder.c\n/// \\brief      Single-call .xz Stream decoder\n//\n//  Author:     Lasse Collin\n//\n//  This file has been put into the public domain.\n//  You can do whatever you want with this file.\n//\n///////////////////////////////////////////////////////////////////////////////\n\n#include \"stream_decoder.h\"\n\n\nextern LZMA_API(lzma_ret)\nlzma_stream_buffer_decode(uint64_t *memlimit, uint32_t flags,\n\t\tconst lzma_allocator *allocator,\n\t\tconst uint8_t *in, size_t *in_pos, size_t in_size,\n\t\tuint8_t *out, size_t *out_pos, size_t out_size)\n{\n\t// Sanity checks\n\tif (in_pos == NULL || (in == NULL && *in_pos != in_size)\n\t\t\t|| *in_pos > in_size || out_pos == NULL\n\t\t\t|| (out == NULL && *out_pos != out_size)\n\t\t\t|| *out_pos > out_size)\n\t\treturn LZMA_PROG_ERROR;\n\n\t// Catch flags that are not allowed in buffer-to-buffer decoding.\n\tif (flags & LZMA_TELL_ANY_CHECK)\n\t\treturn LZMA_PROG_ERROR;\n\n\t// Initialize the Stream decoder.\n\t// TODO: We need something to tell the decoder that it can use the\n\t// output buffer as workspace, and thus save significant amount of RAM.\n\tlzma_next_coder stream_decoder = LZMA_NEXT_CODER_INIT;\n\tlzma_ret ret = lzma_stream_decoder_init(\n\t\t\t&stream_decoder, allocator, *memlimit, flags);\n\n\tif (ret == LZMA_OK) {\n\t\t// Save the positions so that we can restore them in case\n\t\t// an error occurs.\n\t\tconst size_t in_start = *in_pos;\n\t\tconst size_t out_start = *out_pos;\n\n\t\t// Do the actual decoding.\n\t\tret = stream_decoder.code(stream_decoder.coder, allocator,\n\t\t\t\tin, in_pos, in_size, out, out_pos, out_size,\n\t\t\t\tLZMA_FINISH);\n\n\t\tif (ret == LZMA_STREAM_END) {\n\t\t\tret = LZMA_OK;\n\t\t} else {\n\t\t\t// Something went wrong, restore the positions.\n\t\t\t*in_pos = in_start;\n\t\t\t*out_pos = out_start;\n\n\t\t\tif (ret == LZMA_OK) {\n\t\t\t\t// Either the input was truncated or the\n\t\t\t\t// output buffer was too small.\n\t\t\t\tassert(*in_pos == in_size\n\t\t\t\t\t\t|| *out_pos == out_size);\n\n\t\t\t\t// If all the input was consumed, then the\n\t\t\t\t// input is truncated, even if the output\n\t\t\t\t// buffer is also full. This is because\n\t\t\t\t// processing the last byte of the Stream\n\t\t\t\t// never produces output.\n\t\t\t\tif (*in_pos == in_size)\n\t\t\t\t\tret = LZMA_DATA_ERROR;\n\t\t\t\telse\n\t\t\t\t\tret = LZMA_BUF_ERROR;\n\n\t\t\t} else if (ret == LZMA_MEMLIMIT_ERROR) {\n\t\t\t\t// Let the caller know how much memory would\n\t\t\t\t// have been needed.\n\t\t\t\tuint64_t memusage;\n\t\t\t\t(void)stream_decoder.memconfig(\n\t\t\t\t\t\tstream_decoder.coder,\n\t\t\t\t\t\tmemlimit, &memusage, 0);\n\t\t\t}\n\t\t}\n\t}\n\n\t// Free the decoder memory. This needs to be done even if\n\t// initialization fails, because the internal API doesn't\n\t// require the initialization function to free its memory on error.\n\tlzma_next_end(&stream_decoder, allocator);\n\n\treturn ret;\n}\n"
  },
  {
    "path": "external/xz/liblzma/common/stream_buffer_encoder.c",
    "content": "///////////////////////////////////////////////////////////////////////////////\n//\n/// \\file       stream_buffer_encoder.c\n/// \\brief      Single-call .xz Stream encoder\n//\n//  Author:     Lasse Collin\n//\n//  This file has been put into the public domain.\n//  You can do whatever you want with this file.\n//\n///////////////////////////////////////////////////////////////////////////////\n\n#include \"index.h\"\n\n\n/// Maximum size of Index that has exactly one Record.\n/// Index Indicator + Number of Records + Record + CRC32 rounded up to\n/// the next multiple of four.\n#define INDEX_BOUND ((1 + 1 + 2 * LZMA_VLI_BYTES_MAX + 4 + 3) & ~3)\n\n/// Stream Header, Stream Footer, and Index\n#define HEADERS_BOUND (2 * LZMA_STREAM_HEADER_SIZE + INDEX_BOUND)\n\n\nextern LZMA_API(size_t)\nlzma_stream_buffer_bound(size_t uncompressed_size)\n{\n\t// Get the maximum possible size of a Block.\n\tconst size_t block_bound = lzma_block_buffer_bound(uncompressed_size);\n\tif (block_bound == 0)\n\t\treturn 0;\n\n\t// Catch the possible integer overflow and also prevent the size of\n\t// the Stream exceeding LZMA_VLI_MAX (theoretically possible on\n\t// 64-bit systems).\n\tif (my_min(SIZE_MAX, LZMA_VLI_MAX) - block_bound < HEADERS_BOUND)\n\t\treturn 0;\n\n\treturn block_bound + HEADERS_BOUND;\n}\n\n\nextern LZMA_API(lzma_ret)\nlzma_stream_buffer_encode(lzma_filter *filters, lzma_check check,\n\t\tconst lzma_allocator *allocator,\n\t\tconst uint8_t *in, size_t in_size,\n\t\tuint8_t *out, size_t *out_pos_ptr, size_t out_size)\n{\n\t// Sanity checks\n\tif (filters == NULL || (unsigned int)(check) > LZMA_CHECK_ID_MAX\n\t\t\t|| (in == NULL && in_size != 0) || out == NULL\n\t\t\t|| out_pos_ptr == NULL || *out_pos_ptr > out_size)\n\t\treturn LZMA_PROG_ERROR;\n\n\tif (!lzma_check_is_supported(check))\n\t\treturn LZMA_UNSUPPORTED_CHECK;\n\n\t// Note for the paranoids: Index encoder prevents the Stream from\n\t// getting too big and still being accepted with LZMA_OK, and Block\n\t// encoder catches if the input is too big. So we don't need to\n\t// separately check if the buffers are too big.\n\n\t// Use a local copy. We update *out_pos_ptr only if everything\n\t// succeeds.\n\tsize_t out_pos = *out_pos_ptr;\n\n\t// Check that there's enough space for both Stream Header and\n\t// Stream Footer.\n\tif (out_size - out_pos <= 2 * LZMA_STREAM_HEADER_SIZE)\n\t\treturn LZMA_BUF_ERROR;\n\n\t// Reserve space for Stream Footer so we don't need to check for\n\t// available space again before encoding Stream Footer.\n\tout_size -= LZMA_STREAM_HEADER_SIZE;\n\n\t// Encode the Stream Header.\n\tlzma_stream_flags stream_flags = {\n\t\t.version = 0,\n\t\t.check = check,\n\t};\n\n\tif (lzma_stream_header_encode(&stream_flags, out + out_pos)\n\t\t\t!= LZMA_OK)\n\t\treturn LZMA_PROG_ERROR;\n\n\tout_pos += LZMA_STREAM_HEADER_SIZE;\n\n\t// Encode a Block but only if there is at least one byte of input.\n\tlzma_block block = {\n\t\t.version = 0,\n\t\t.check = check,\n\t\t.filters = filters,\n\t};\n\n\tif (in_size > 0)\n\t\treturn_if_error(lzma_block_buffer_encode(&block, allocator,\n\t\t\t\tin, in_size, out, &out_pos, out_size));\n\n\t// Index\n\t{\n\t\t// Create an Index. It will have one Record if there was\n\t\t// at least one byte of input to encode. Otherwise the\n\t\t// Index will be empty.\n\t\tlzma_index *i = lzma_index_init(allocator);\n\t\tif (i == NULL)\n\t\t\treturn LZMA_MEM_ERROR;\n\n\t\tlzma_ret ret = LZMA_OK;\n\n\t\tif (in_size > 0)\n\t\t\tret = lzma_index_append(i, allocator,\n\t\t\t\t\tlzma_block_unpadded_size(&block),\n\t\t\t\t\tblock.uncompressed_size);\n\n\t\t// If adding the Record was successful, encode the Index\n\t\t// and get its size which will be stored into Stream Footer.\n\t\tif (ret == LZMA_OK) {\n\t\t\tret = lzma_index_buffer_encode(\n\t\t\t\t\ti, out, &out_pos, out_size);\n\n\t\t\tstream_flags.backward_size = lzma_index_size(i);\n\t\t}\n\n\t\tlzma_index_end(i, allocator);\n\n\t\tif (ret != LZMA_OK)\n\t\t\treturn ret;\n\t}\n\n\t// Stream Footer. We have already reserved space for this.\n\tif (lzma_stream_footer_encode(&stream_flags, out + out_pos)\n\t\t\t!= LZMA_OK)\n\t\treturn LZMA_PROG_ERROR;\n\n\tout_pos += LZMA_STREAM_HEADER_SIZE;\n\n\t// Everything went fine, make the new output position available\n\t// to the application.\n\t*out_pos_ptr = out_pos;\n\treturn LZMA_OK;\n}\n"
  },
  {
    "path": "external/xz/liblzma/common/stream_decoder.c",
    "content": "///////////////////////////////////////////////////////////////////////////////\n//\n/// \\file       stream_decoder.c\n/// \\brief      Decodes .xz Streams\n//\n//  Author:     Lasse Collin\n//\n//  This file has been put into the public domain.\n//  You can do whatever you want with this file.\n//\n///////////////////////////////////////////////////////////////////////////////\n\n#include \"stream_decoder.h\"\n#include \"block_decoder.h\"\n\n\ntypedef struct {\n\tenum {\n\t\tSEQ_STREAM_HEADER,\n\t\tSEQ_BLOCK_HEADER,\n\t\tSEQ_BLOCK,\n\t\tSEQ_INDEX,\n\t\tSEQ_STREAM_FOOTER,\n\t\tSEQ_STREAM_PADDING,\n\t} sequence;\n\n\t/// Block or Metadata decoder. This takes little memory and the same\n\t/// data structure can be used to decode every Block Header, so it's\n\t/// a good idea to have a separate lzma_next_coder structure for it.\n\tlzma_next_coder block_decoder;\n\n\t/// Block options decoded by the Block Header decoder and used by\n\t/// the Block decoder.\n\tlzma_block block_options;\n\n\t/// Stream Flags from Stream Header\n\tlzma_stream_flags stream_flags;\n\n\t/// Index is hashed so that it can be compared to the sizes of Blocks\n\t/// with O(1) memory usage.\n\tlzma_index_hash *index_hash;\n\n\t/// Memory usage limit\n\tuint64_t memlimit;\n\n\t/// Amount of memory actually needed (only an estimate)\n\tuint64_t memusage;\n\n\t/// If true, LZMA_NO_CHECK is returned if the Stream has\n\t/// no integrity check.\n\tbool tell_no_check;\n\n\t/// If true, LZMA_UNSUPPORTED_CHECK is returned if the Stream has\n\t/// an integrity check that isn't supported by this liblzma build.\n\tbool tell_unsupported_check;\n\n\t/// If true, LZMA_GET_CHECK is returned after decoding Stream Header.\n\tbool tell_any_check;\n\n\t/// If true, we will tell the Block decoder to skip calculating\n\t/// and verifying the integrity check.\n\tbool ignore_check;\n\n\t/// If true, we will decode concatenated Streams that possibly have\n\t/// Stream Padding between or after them. LZMA_STREAM_END is returned\n\t/// once the application isn't giving us any new input, and we aren't\n\t/// in the middle of a Stream, and possible Stream Padding is a\n\t/// multiple of four bytes.\n\tbool concatenated;\n\n\t/// When decoding concatenated Streams, this is true as long as we\n\t/// are decoding the first Stream. This is needed to avoid misleading\n\t/// LZMA_FORMAT_ERROR in case the later Streams don't have valid magic\n\t/// bytes.\n\tbool first_stream;\n\n\t/// Write position in buffer[] and position in Stream Padding\n\tsize_t pos;\n\n\t/// Buffer to hold Stream Header, Block Header, and Stream Footer.\n\t/// Block Header has biggest maximum size.\n\tuint8_t buffer[LZMA_BLOCK_HEADER_SIZE_MAX];\n} lzma_stream_coder;\n\n\nstatic lzma_ret\nstream_decoder_reset(lzma_stream_coder *coder, const lzma_allocator *allocator)\n{\n\t// Initialize the Index hash used to verify the Index.\n\tcoder->index_hash = lzma_index_hash_init(coder->index_hash, allocator);\n\tif (coder->index_hash == NULL)\n\t\treturn LZMA_MEM_ERROR;\n\n\t// Reset the rest of the variables.\n\tcoder->sequence = SEQ_STREAM_HEADER;\n\tcoder->pos = 0;\n\n\treturn LZMA_OK;\n}\n\n\nstatic lzma_ret\nstream_decode(void *coder_ptr, const lzma_allocator *allocator,\n\t\tconst uint8_t *restrict in, size_t *restrict in_pos,\n\t\tsize_t in_size, uint8_t *restrict out,\n\t\tsize_t *restrict out_pos, size_t out_size, lzma_action action)\n{\n\tlzma_stream_coder *coder = coder_ptr;\n\n\t// When decoding the actual Block, it may be able to produce more\n\t// output even if we don't give it any new input.\n\twhile (true)\n\tswitch (coder->sequence) {\n\tcase SEQ_STREAM_HEADER: {\n\t\t// Copy the Stream Header to the internal buffer.\n\t\tlzma_bufcpy(in, in_pos, in_size, coder->buffer, &coder->pos,\n\t\t\t\tLZMA_STREAM_HEADER_SIZE);\n\n\t\t// Return if we didn't get the whole Stream Header yet.\n\t\tif (coder->pos < LZMA_STREAM_HEADER_SIZE)\n\t\t\treturn LZMA_OK;\n\n\t\tcoder->pos = 0;\n\n\t\t// Decode the Stream Header.\n\t\tconst lzma_ret ret = lzma_stream_header_decode(\n\t\t\t\t&coder->stream_flags, coder->buffer);\n\t\tif (ret != LZMA_OK)\n\t\t\treturn ret == LZMA_FORMAT_ERROR && !coder->first_stream\n\t\t\t\t\t? LZMA_DATA_ERROR : ret;\n\n\t\t// If we are decoding concatenated Streams, and the later\n\t\t// Streams have invalid Header Magic Bytes, we give\n\t\t// LZMA_DATA_ERROR instead of LZMA_FORMAT_ERROR.\n\t\tcoder->first_stream = false;\n\n\t\t// Copy the type of the Check so that Block Header and Block\n\t\t// decoders see it.\n\t\tcoder->block_options.check = coder->stream_flags.check;\n\n\t\t// Even if we return LZMA_*_CHECK below, we want\n\t\t// to continue from Block Header decoding.\n\t\tcoder->sequence = SEQ_BLOCK_HEADER;\n\n\t\t// Detect if there's no integrity check or if it is\n\t\t// unsupported if those were requested by the application.\n\t\tif (coder->tell_no_check && coder->stream_flags.check\n\t\t\t\t== LZMA_CHECK_NONE)\n\t\t\treturn LZMA_NO_CHECK;\n\n\t\tif (coder->tell_unsupported_check\n\t\t\t\t&& !lzma_check_is_supported(\n\t\t\t\t\tcoder->stream_flags.check))\n\t\t\treturn LZMA_UNSUPPORTED_CHECK;\n\n\t\tif (coder->tell_any_check)\n\t\t\treturn LZMA_GET_CHECK;\n\t}\n\n\t// Fall through\n\n\tcase SEQ_BLOCK_HEADER: {\n\t\tif (*in_pos >= in_size)\n\t\t\treturn LZMA_OK;\n\n\t\tif (coder->pos == 0) {\n\t\t\t// Detect if it's Index.\n\t\t\tif (in[*in_pos] == 0x00) {\n\t\t\t\tcoder->sequence = SEQ_INDEX;\n\t\t\t\tbreak;\n\t\t\t}\n\n\t\t\t// Calculate the size of the Block Header. Note that\n\t\t\t// Block Header decoder wants to see this byte too\n\t\t\t// so don't advance *in_pos.\n\t\t\tcoder->block_options.header_size\n\t\t\t\t\t= lzma_block_header_size_decode(\n\t\t\t\t\t\tin[*in_pos]);\n\t\t}\n\n\t\t// Copy the Block Header to the internal buffer.\n\t\tlzma_bufcpy(in, in_pos, in_size, coder->buffer, &coder->pos,\n\t\t\t\tcoder->block_options.header_size);\n\n\t\t// Return if we didn't get the whole Block Header yet.\n\t\tif (coder->pos < coder->block_options.header_size)\n\t\t\treturn LZMA_OK;\n\n\t\tcoder->pos = 0;\n\n\t\t// Version 1 is needed to support the .ignore_check option.\n\t\tcoder->block_options.version = 1;\n\n\t\t// Set up a buffer to hold the filter chain. Block Header\n\t\t// decoder will initialize all members of this array so\n\t\t// we don't need to do it here.\n\t\tlzma_filter filters[LZMA_FILTERS_MAX + 1];\n\t\tcoder->block_options.filters = filters;\n\n\t\t// Decode the Block Header.\n\t\treturn_if_error(lzma_block_header_decode(&coder->block_options,\n\t\t\t\tallocator, coder->buffer));\n\n\t\t// If LZMA_IGNORE_CHECK was used, this flag needs to be set.\n\t\t// It has to be set after lzma_block_header_decode() because\n\t\t// it always resets this to false.\n\t\tcoder->block_options.ignore_check = coder->ignore_check;\n\n\t\t// Check the memory usage limit.\n\t\tconst uint64_t memusage = lzma_raw_decoder_memusage(filters);\n\t\tlzma_ret ret;\n\n\t\tif (memusage == UINT64_MAX) {\n\t\t\t// One or more unknown Filter IDs.\n\t\t\tret = LZMA_OPTIONS_ERROR;\n\t\t} else {\n\t\t\t// Now we can set coder->memusage since we know that\n\t\t\t// the filter chain is valid. We don't want\n\t\t\t// lzma_memusage() to return UINT64_MAX in case of\n\t\t\t// invalid filter chain.\n\t\t\tcoder->memusage = memusage;\n\n\t\t\tif (memusage > coder->memlimit) {\n\t\t\t\t// The chain would need too much memory.\n\t\t\t\tret = LZMA_MEMLIMIT_ERROR;\n\t\t\t} else {\n\t\t\t\t// Memory usage is OK.\n\t\t\t\t// Initialize the Block decoder.\n\t\t\t\tret = lzma_block_decoder_init(\n\t\t\t\t\t\t&coder->block_decoder,\n\t\t\t\t\t\tallocator,\n\t\t\t\t\t\t&coder->block_options);\n\t\t\t}\n\t\t}\n\n\t\t// Free the allocated filter options since they are needed\n\t\t// only to initialize the Block decoder.\n\t\tfor (size_t i = 0; i < LZMA_FILTERS_MAX; ++i)\n\t\t\tlzma_free(filters[i].options, allocator);\n\n\t\tcoder->block_options.filters = NULL;\n\n\t\t// Check if memory usage calculation and Block enocoder\n\t\t// initialization succeeded.\n\t\tif (ret != LZMA_OK)\n\t\t\treturn ret;\n\n\t\tcoder->sequence = SEQ_BLOCK;\n\t}\n\n\t// Fall through\n\n\tcase SEQ_BLOCK: {\n\t\tconst lzma_ret ret = coder->block_decoder.code(\n\t\t\t\tcoder->block_decoder.coder, allocator,\n\t\t\t\tin, in_pos, in_size, out, out_pos, out_size,\n\t\t\t\taction);\n\n\t\tif (ret != LZMA_STREAM_END)\n\t\t\treturn ret;\n\n\t\t// Block decoded successfully. Add the new size pair to\n\t\t// the Index hash.\n\t\treturn_if_error(lzma_index_hash_append(coder->index_hash,\n\t\t\t\tlzma_block_unpadded_size(\n\t\t\t\t\t&coder->block_options),\n\t\t\t\tcoder->block_options.uncompressed_size));\n\n\t\tcoder->sequence = SEQ_BLOCK_HEADER;\n\t\tbreak;\n\t}\n\n\tcase SEQ_INDEX: {\n\t\t// If we don't have any input, don't call\n\t\t// lzma_index_hash_decode() since it would return\n\t\t// LZMA_BUF_ERROR, which we must not do here.\n\t\tif (*in_pos >= in_size)\n\t\t\treturn LZMA_OK;\n\n\t\t// Decode the Index and compare it to the hash calculated\n\t\t// from the sizes of the Blocks (if any).\n\t\tconst lzma_ret ret = lzma_index_hash_decode(coder->index_hash,\n\t\t\t\tin, in_pos, in_size);\n\t\tif (ret != LZMA_STREAM_END)\n\t\t\treturn ret;\n\n\t\tcoder->sequence = SEQ_STREAM_FOOTER;\n\t}\n\n\t// Fall through\n\n\tcase SEQ_STREAM_FOOTER: {\n\t\t// Copy the Stream Footer to the internal buffer.\n\t\tlzma_bufcpy(in, in_pos, in_size, coder->buffer, &coder->pos,\n\t\t\t\tLZMA_STREAM_HEADER_SIZE);\n\n\t\t// Return if we didn't get the whole Stream Footer yet.\n\t\tif (coder->pos < LZMA_STREAM_HEADER_SIZE)\n\t\t\treturn LZMA_OK;\n\n\t\tcoder->pos = 0;\n\n\t\t// Decode the Stream Footer. The decoder gives\n\t\t// LZMA_FORMAT_ERROR if the magic bytes don't match,\n\t\t// so convert that return code to LZMA_DATA_ERROR.\n\t\tlzma_stream_flags footer_flags;\n\t\tconst lzma_ret ret = lzma_stream_footer_decode(\n\t\t\t\t&footer_flags, coder->buffer);\n\t\tif (ret != LZMA_OK)\n\t\t\treturn ret == LZMA_FORMAT_ERROR\n\t\t\t\t\t? LZMA_DATA_ERROR : ret;\n\n\t\t// Check that Index Size stored in the Stream Footer matches\n\t\t// the real size of the Index field.\n\t\tif (lzma_index_hash_size(coder->index_hash)\n\t\t\t\t!= footer_flags.backward_size)\n\t\t\treturn LZMA_DATA_ERROR;\n\n\t\t// Compare that the Stream Flags fields are identical in\n\t\t// both Stream Header and Stream Footer.\n\t\treturn_if_error(lzma_stream_flags_compare(\n\t\t\t\t&coder->stream_flags, &footer_flags));\n\n\t\tif (!coder->concatenated)\n\t\t\treturn LZMA_STREAM_END;\n\n\t\tcoder->sequence = SEQ_STREAM_PADDING;\n\t}\n\n\t// Fall through\n\n\tcase SEQ_STREAM_PADDING:\n\t\tassert(coder->concatenated);\n\n\t\t// Skip over possible Stream Padding.\n\t\twhile (true) {\n\t\t\tif (*in_pos >= in_size) {\n\t\t\t\t// Unless LZMA_FINISH was used, we cannot\n\t\t\t\t// know if there's more input coming later.\n\t\t\t\tif (action != LZMA_FINISH)\n\t\t\t\t\treturn LZMA_OK;\n\n\t\t\t\t// Stream Padding must be a multiple of\n\t\t\t\t// four bytes.\n\t\t\t\treturn coder->pos == 0\n\t\t\t\t\t\t? LZMA_STREAM_END\n\t\t\t\t\t\t: LZMA_DATA_ERROR;\n\t\t\t}\n\n\t\t\t// If the byte is not zero, it probably indicates\n\t\t\t// beginning of a new Stream (or the file is corrupt).\n\t\t\tif (in[*in_pos] != 0x00)\n\t\t\t\tbreak;\n\n\t\t\t++*in_pos;\n\t\t\tcoder->pos = (coder->pos + 1) & 3;\n\t\t}\n\n\t\t// Stream Padding must be a multiple of four bytes (empty\n\t\t// Stream Padding is OK).\n\t\tif (coder->pos != 0) {\n\t\t\t++*in_pos;\n\t\t\treturn LZMA_DATA_ERROR;\n\t\t}\n\n\t\t// Prepare to decode the next Stream.\n\t\treturn_if_error(stream_decoder_reset(coder, allocator));\n\t\tbreak;\n\n\tdefault:\n\t\tassert(0);\n\t\treturn LZMA_PROG_ERROR;\n\t}\n\n\t// Never reached\n}\n\n\nstatic void\nstream_decoder_end(void *coder_ptr, const lzma_allocator *allocator)\n{\n\tlzma_stream_coder *coder = coder_ptr;\n\tlzma_next_end(&coder->block_decoder, allocator);\n\tlzma_index_hash_end(coder->index_hash, allocator);\n\tlzma_free(coder, allocator);\n\treturn;\n}\n\n\nstatic lzma_check\nstream_decoder_get_check(const void *coder_ptr)\n{\n\tconst lzma_stream_coder *coder = coder_ptr;\n\treturn coder->stream_flags.check;\n}\n\n\nstatic lzma_ret\nstream_decoder_memconfig(void *coder_ptr, uint64_t *memusage,\n\t\tuint64_t *old_memlimit, uint64_t new_memlimit)\n{\n\tlzma_stream_coder *coder = coder_ptr;\n\n\t*memusage = coder->memusage;\n\t*old_memlimit = coder->memlimit;\n\n\tif (new_memlimit != 0) {\n\t\tif (new_memlimit < coder->memusage)\n\t\t\treturn LZMA_MEMLIMIT_ERROR;\n\n\t\tcoder->memlimit = new_memlimit;\n\t}\n\n\treturn LZMA_OK;\n}\n\n\nextern lzma_ret\nlzma_stream_decoder_init(\n\t\tlzma_next_coder *next, const lzma_allocator *allocator,\n\t\tuint64_t memlimit, uint32_t flags)\n{\n\tlzma_next_coder_init(&lzma_stream_decoder_init, next, allocator);\n\n\tif (flags & ~LZMA_SUPPORTED_FLAGS)\n\t\treturn LZMA_OPTIONS_ERROR;\n\n\tlzma_stream_coder *coder = next->coder;\n\tif (coder == NULL) {\n\t\tcoder = lzma_alloc(sizeof(lzma_stream_coder), allocator);\n\t\tif (coder == NULL)\n\t\t\treturn LZMA_MEM_ERROR;\n\n\t\tnext->coder = coder;\n\t\tnext->code = &stream_decode;\n\t\tnext->end = &stream_decoder_end;\n\t\tnext->get_check = &stream_decoder_get_check;\n\t\tnext->memconfig = &stream_decoder_memconfig;\n\n\t\tcoder->block_decoder = LZMA_NEXT_CODER_INIT;\n\t\tcoder->index_hash = NULL;\n\t}\n\n\tcoder->memlimit = my_max(1, memlimit);\n\tcoder->memusage = LZMA_MEMUSAGE_BASE;\n\tcoder->tell_no_check = (flags & LZMA_TELL_NO_CHECK) != 0;\n\tcoder->tell_unsupported_check\n\t\t\t= (flags & LZMA_TELL_UNSUPPORTED_CHECK) != 0;\n\tcoder->tell_any_check = (flags & LZMA_TELL_ANY_CHECK) != 0;\n\tcoder->ignore_check = (flags & LZMA_IGNORE_CHECK) != 0;\n\tcoder->concatenated = (flags & LZMA_CONCATENATED) != 0;\n\tcoder->first_stream = true;\n\n\treturn stream_decoder_reset(coder, allocator);\n}\n\n\nextern LZMA_API(lzma_ret)\nlzma_stream_decoder(lzma_stream *strm, uint64_t memlimit, uint32_t flags)\n{\n\tlzma_next_strm_init(lzma_stream_decoder_init, strm, memlimit, flags);\n\n\tstrm->internal->supported_actions[LZMA_RUN] = true;\n\tstrm->internal->supported_actions[LZMA_FINISH] = true;\n\n\treturn LZMA_OK;\n}\n"
  },
  {
    "path": "external/xz/liblzma/common/stream_decoder.h",
    "content": "///////////////////////////////////////////////////////////////////////////////\n//\n/// \\file       stream_decoder.h\n/// \\brief      Decodes .xz Streams\n//\n//  Author:     Lasse Collin\n//\n//  This file has been put into the public domain.\n//  You can do whatever you want with this file.\n//\n///////////////////////////////////////////////////////////////////////////////\n\n#ifndef LZMA_STREAM_DECODER_H\n#define LZMA_STREAM_DECODER_H\n\n#include \"common.h\"\n\nextern lzma_ret lzma_stream_decoder_init(\n\t\tlzma_next_coder *next, const lzma_allocator *allocator,\n\t\tuint64_t memlimit, uint32_t flags);\n\n#endif\n"
  },
  {
    "path": "external/xz/liblzma/common/stream_encoder.c",
    "content": "///////////////////////////////////////////////////////////////////////////////\n//\n/// \\file       stream_encoder.c\n/// \\brief      Encodes .xz Streams\n//\n//  Author:     Lasse Collin\n//\n//  This file has been put into the public domain.\n//  You can do whatever you want with this file.\n//\n///////////////////////////////////////////////////////////////////////////////\n\n#include \"block_encoder.h\"\n#include \"index_encoder.h\"\n\n\ntypedef struct {\n\tenum {\n\t\tSEQ_STREAM_HEADER,\n\t\tSEQ_BLOCK_INIT,\n\t\tSEQ_BLOCK_HEADER,\n\t\tSEQ_BLOCK_ENCODE,\n\t\tSEQ_INDEX_ENCODE,\n\t\tSEQ_STREAM_FOOTER,\n\t} sequence;\n\n\t/// True if Block encoder has been initialized by\n\t/// stream_encoder_init() or stream_encoder_update()\n\t/// and thus doesn't need to be initialized in stream_encode().\n\tbool block_encoder_is_initialized;\n\n\t/// Block\n\tlzma_next_coder block_encoder;\n\n\t/// Options for the Block encoder\n\tlzma_block block_options;\n\n\t/// The filter chain currently in use\n\tlzma_filter filters[LZMA_FILTERS_MAX + 1];\n\n\t/// Index encoder. This is separate from Block encoder, because this\n\t/// doesn't take much memory, and when encoding multiple Streams\n\t/// with the same encoding options we avoid reallocating memory.\n\tlzma_next_coder index_encoder;\n\n\t/// Index to hold sizes of the Blocks\n\tlzma_index *index;\n\n\t/// Read position in buffer[]\n\tsize_t buffer_pos;\n\n\t/// Total number of bytes in buffer[]\n\tsize_t buffer_size;\n\n\t/// Buffer to hold Stream Header, Block Header, and Stream Footer.\n\t/// Block Header has biggest maximum size.\n\tuint8_t buffer[LZMA_BLOCK_HEADER_SIZE_MAX];\n} lzma_stream_coder;\n\n\nstatic lzma_ret\nblock_encoder_init(lzma_stream_coder *coder, const lzma_allocator *allocator)\n{\n\t// Prepare the Block options. Even though Block encoder doesn't need\n\t// compressed_size, uncompressed_size, and header_size to be\n\t// initialized, it is a good idea to do it here, because this way\n\t// we catch if someone gave us Filter ID that cannot be used in\n\t// Blocks/Streams.\n\tcoder->block_options.compressed_size = LZMA_VLI_UNKNOWN;\n\tcoder->block_options.uncompressed_size = LZMA_VLI_UNKNOWN;\n\n\treturn_if_error(lzma_block_header_size(&coder->block_options));\n\n\t// Initialize the actual Block encoder.\n\treturn lzma_block_encoder_init(&coder->block_encoder, allocator,\n\t\t\t&coder->block_options);\n}\n\n\nstatic lzma_ret\nstream_encode(void *coder_ptr, const lzma_allocator *allocator,\n\t\tconst uint8_t *restrict in, size_t *restrict in_pos,\n\t\tsize_t in_size, uint8_t *restrict out,\n\t\tsize_t *restrict out_pos, size_t out_size, lzma_action action)\n{\n\tlzma_stream_coder *coder = coder_ptr;\n\n\t// Main loop\n\twhile (*out_pos < out_size)\n\tswitch (coder->sequence) {\n\tcase SEQ_STREAM_HEADER:\n\tcase SEQ_BLOCK_HEADER:\n\tcase SEQ_STREAM_FOOTER:\n\t\tlzma_bufcpy(coder->buffer, &coder->buffer_pos,\n\t\t\t\tcoder->buffer_size, out, out_pos, out_size);\n\t\tif (coder->buffer_pos < coder->buffer_size)\n\t\t\treturn LZMA_OK;\n\n\t\tif (coder->sequence == SEQ_STREAM_FOOTER)\n\t\t\treturn LZMA_STREAM_END;\n\n\t\tcoder->buffer_pos = 0;\n\t\t++coder->sequence;\n\t\tbreak;\n\n\tcase SEQ_BLOCK_INIT: {\n\t\tif (*in_pos == in_size) {\n\t\t\t// If we are requested to flush or finish the current\n\t\t\t// Block, return LZMA_STREAM_END immediately since\n\t\t\t// there's nothing to do.\n\t\t\tif (action != LZMA_FINISH)\n\t\t\t\treturn action == LZMA_RUN\n\t\t\t\t\t\t? LZMA_OK : LZMA_STREAM_END;\n\n\t\t\t// The application had used LZMA_FULL_FLUSH to finish\n\t\t\t// the previous Block, but now wants to finish without\n\t\t\t// encoding new data, or it is simply creating an\n\t\t\t// empty Stream with no Blocks.\n\t\t\t//\n\t\t\t// Initialize the Index encoder, and continue to\n\t\t\t// actually encoding the Index.\n\t\t\treturn_if_error(lzma_index_encoder_init(\n\t\t\t\t\t&coder->index_encoder, allocator,\n\t\t\t\t\tcoder->index));\n\t\t\tcoder->sequence = SEQ_INDEX_ENCODE;\n\t\t\tbreak;\n\t\t}\n\n\t\t// Initialize the Block encoder unless it was already\n\t\t// initialized by stream_encoder_init() or\n\t\t// stream_encoder_update().\n\t\tif (!coder->block_encoder_is_initialized)\n\t\t\treturn_if_error(block_encoder_init(coder, allocator));\n\n\t\t// Make it false so that we don't skip the initialization\n\t\t// with the next Block.\n\t\tcoder->block_encoder_is_initialized = false;\n\n\t\t// Encode the Block Header. This shouldn't fail since we have\n\t\t// already initialized the Block encoder.\n\t\tif (lzma_block_header_encode(&coder->block_options,\n\t\t\t\tcoder->buffer) != LZMA_OK)\n\t\t\treturn LZMA_PROG_ERROR;\n\n\t\tcoder->buffer_size = coder->block_options.header_size;\n\t\tcoder->sequence = SEQ_BLOCK_HEADER;\n\t\tbreak;\n\t}\n\n\tcase SEQ_BLOCK_ENCODE: {\n\t\tstatic const lzma_action convert[LZMA_ACTION_MAX + 1] = {\n\t\t\tLZMA_RUN,\n\t\t\tLZMA_SYNC_FLUSH,\n\t\t\tLZMA_FINISH,\n\t\t\tLZMA_FINISH,\n\t\t\tLZMA_FINISH,\n\t\t};\n\n\t\tconst lzma_ret ret = coder->block_encoder.code(\n\t\t\t\tcoder->block_encoder.coder, allocator,\n\t\t\t\tin, in_pos, in_size,\n\t\t\t\tout, out_pos, out_size, convert[action]);\n\t\tif (ret != LZMA_STREAM_END || action == LZMA_SYNC_FLUSH)\n\t\t\treturn ret;\n\n\t\t// Add a new Index Record.\n\t\tconst lzma_vli unpadded_size = lzma_block_unpadded_size(\n\t\t\t\t&coder->block_options);\n\t\tassert(unpadded_size != 0);\n\t\treturn_if_error(lzma_index_append(coder->index, allocator,\n\t\t\t\tunpadded_size,\n\t\t\t\tcoder->block_options.uncompressed_size));\n\n\t\tcoder->sequence = SEQ_BLOCK_INIT;\n\t\tbreak;\n\t}\n\n\tcase SEQ_INDEX_ENCODE: {\n\t\t// Call the Index encoder. It doesn't take any input, so\n\t\t// those pointers can be NULL.\n\t\tconst lzma_ret ret = coder->index_encoder.code(\n\t\t\t\tcoder->index_encoder.coder, allocator,\n\t\t\t\tNULL, NULL, 0,\n\t\t\t\tout, out_pos, out_size, LZMA_RUN);\n\t\tif (ret != LZMA_STREAM_END)\n\t\t\treturn ret;\n\n\t\t// Encode the Stream Footer into coder->buffer.\n\t\tconst lzma_stream_flags stream_flags = {\n\t\t\t.version = 0,\n\t\t\t.backward_size = lzma_index_size(coder->index),\n\t\t\t.check = coder->block_options.check,\n\t\t};\n\n\t\tif (lzma_stream_footer_encode(&stream_flags, coder->buffer)\n\t\t\t\t!= LZMA_OK)\n\t\t\treturn LZMA_PROG_ERROR;\n\n\t\tcoder->buffer_size = LZMA_STREAM_HEADER_SIZE;\n\t\tcoder->sequence = SEQ_STREAM_FOOTER;\n\t\tbreak;\n\t}\n\n\tdefault:\n\t\tassert(0);\n\t\treturn LZMA_PROG_ERROR;\n\t}\n\n\treturn LZMA_OK;\n}\n\n\nstatic void\nstream_encoder_end(void *coder_ptr, const lzma_allocator *allocator)\n{\n\tlzma_stream_coder *coder = coder_ptr;\n\n\tlzma_next_end(&coder->block_encoder, allocator);\n\tlzma_next_end(&coder->index_encoder, allocator);\n\tlzma_index_end(coder->index, allocator);\n\n\tfor (size_t i = 0; coder->filters[i].id != LZMA_VLI_UNKNOWN; ++i)\n\t\tlzma_free(coder->filters[i].options, allocator);\n\n\tlzma_free(coder, allocator);\n\treturn;\n}\n\n\nstatic lzma_ret\nstream_encoder_update(void *coder_ptr, const lzma_allocator *allocator,\n\t\tconst lzma_filter *filters,\n\t\tconst lzma_filter *reversed_filters)\n{\n\tlzma_stream_coder *coder = coder_ptr;\n\n\tif (coder->sequence <= SEQ_BLOCK_INIT) {\n\t\t// There is no incomplete Block waiting to be finished,\n\t\t// thus we can change the whole filter chain. Start by\n\t\t// trying to initialize the Block encoder with the new\n\t\t// chain. This way we detect if the chain is valid.\n\t\tcoder->block_encoder_is_initialized = false;\n\t\tcoder->block_options.filters = (lzma_filter *)(filters);\n\t\tconst lzma_ret ret = block_encoder_init(coder, allocator);\n\t\tcoder->block_options.filters = coder->filters;\n\t\tif (ret != LZMA_OK)\n\t\t\treturn ret;\n\n\t\tcoder->block_encoder_is_initialized = true;\n\n\t} else if (coder->sequence <= SEQ_BLOCK_ENCODE) {\n\t\t// We are in the middle of a Block. Try to update only\n\t\t// the filter-specific options.\n\t\treturn_if_error(coder->block_encoder.update(\n\t\t\t\tcoder->block_encoder.coder, allocator,\n\t\t\t\tfilters, reversed_filters));\n\t} else {\n\t\t// Trying to update the filter chain when we are already\n\t\t// encoding Index or Stream Footer.\n\t\treturn LZMA_PROG_ERROR;\n\t}\n\n\t// Free the copy of the old chain and make a copy of the new chain.\n\tfor (size_t i = 0; coder->filters[i].id != LZMA_VLI_UNKNOWN; ++i)\n\t\tlzma_free(coder->filters[i].options, allocator);\n\n\treturn lzma_filters_copy(filters, coder->filters, allocator);\n}\n\n\nstatic lzma_ret\nstream_encoder_init(lzma_next_coder *next, const lzma_allocator *allocator,\n\t\tconst lzma_filter *filters, lzma_check check)\n{\n\tlzma_next_coder_init(&stream_encoder_init, next, allocator);\n\n\tif (filters == NULL)\n\t\treturn LZMA_PROG_ERROR;\n\n\tlzma_stream_coder *coder = next->coder;\n\n\tif (coder == NULL) {\n\t\tcoder = lzma_alloc(sizeof(lzma_stream_coder), allocator);\n\t\tif (coder == NULL)\n\t\t\treturn LZMA_MEM_ERROR;\n\n\t\tnext->coder = coder;\n\t\tnext->code = &stream_encode;\n\t\tnext->end = &stream_encoder_end;\n\t\tnext->update = &stream_encoder_update;\n\n\t\tcoder->filters[0].id = LZMA_VLI_UNKNOWN;\n\t\tcoder->block_encoder = LZMA_NEXT_CODER_INIT;\n\t\tcoder->index_encoder = LZMA_NEXT_CODER_INIT;\n\t\tcoder->index = NULL;\n\t}\n\n\t// Basic initializations\n\tcoder->sequence = SEQ_STREAM_HEADER;\n\tcoder->block_options.version = 0;\n\tcoder->block_options.check = check;\n\n\t// Initialize the Index\n\tlzma_index_end(coder->index, allocator);\n\tcoder->index = lzma_index_init(allocator);\n\tif (coder->index == NULL)\n\t\treturn LZMA_MEM_ERROR;\n\n\t// Encode the Stream Header\n\tlzma_stream_flags stream_flags = {\n\t\t.version = 0,\n\t\t.check = check,\n\t};\n\treturn_if_error(lzma_stream_header_encode(\n\t\t\t&stream_flags, coder->buffer));\n\n\tcoder->buffer_pos = 0;\n\tcoder->buffer_size = LZMA_STREAM_HEADER_SIZE;\n\n\t// Initialize the Block encoder. This way we detect unsupported\n\t// filter chains when initializing the Stream encoder instead of\n\t// giving an error after Stream Header has already written out.\n\treturn stream_encoder_update(coder, allocator, filters, NULL);\n}\n\n\nextern LZMA_API(lzma_ret)\nlzma_stream_encoder(lzma_stream *strm,\n\t\tconst lzma_filter *filters, lzma_check check)\n{\n\tlzma_next_strm_init(stream_encoder_init, strm, filters, check);\n\n\tstrm->internal->supported_actions[LZMA_RUN] = true;\n\tstrm->internal->supported_actions[LZMA_SYNC_FLUSH] = true;\n\tstrm->internal->supported_actions[LZMA_FULL_FLUSH] = true;\n\tstrm->internal->supported_actions[LZMA_FULL_BARRIER] = true;\n\tstrm->internal->supported_actions[LZMA_FINISH] = true;\n\n\treturn LZMA_OK;\n}\n"
  },
  {
    "path": "external/xz/liblzma/common/stream_encoder_mt.c",
    "content": "///////////////////////////////////////////////////////////////////////////////\n//\n/// \\file       stream_encoder_mt.c\n/// \\brief      Multithreaded .xz Stream encoder\n//\n//  Author:     Lasse Collin\n//\n//  This file has been put into the public domain.\n//  You can do whatever you want with this file.\n//\n///////////////////////////////////////////////////////////////////////////////\n\n#include \"filter_encoder.h\"\n#include \"easy_preset.h\"\n#include \"block_encoder.h\"\n#include \"block_buffer_encoder.h\"\n#include \"index_encoder.h\"\n#include \"outqueue.h\"\n\n\n/// Maximum supported block size. This makes it simpler to prevent integer\n/// overflows if we are given unusually large block size.\n#define BLOCK_SIZE_MAX (UINT64_MAX / LZMA_THREADS_MAX)\n\n\ntypedef enum {\n\t/// Waiting for work.\n\tTHR_IDLE,\n\n\t/// Encoding is in progress.\n\tTHR_RUN,\n\n\t/// Encoding is in progress but no more input data will\n\t/// be read.\n\tTHR_FINISH,\n\n\t/// The main thread wants the thread to stop whatever it was doing\n\t/// but not exit.\n\tTHR_STOP,\n\n\t/// The main thread wants the thread to exit. We could use\n\t/// cancellation but since there's stopped anyway, this is lazier.\n\tTHR_EXIT,\n\n} worker_state;\n\ntypedef struct lzma_stream_coder_s lzma_stream_coder;\n\ntypedef struct worker_thread_s worker_thread;\nstruct worker_thread_s {\n\tworker_state state;\n\n\t/// Input buffer of coder->block_size bytes. The main thread will\n\t/// put new input into this and update in_size accordingly. Once\n\t/// no more input is coming, state will be set to THR_FINISH.\n\tuint8_t *in;\n\n\t/// Amount of data available in the input buffer. This is modified\n\t/// only by the main thread.\n\tsize_t in_size;\n\n\t/// Output buffer for this thread. This is set by the main\n\t/// thread every time a new Block is started with this thread\n\t/// structure.\n\tlzma_outbuf *outbuf;\n\n\t/// Pointer to the main structure is needed when putting this\n\t/// thread back to the stack of free threads.\n\tlzma_stream_coder *coder;\n\n\t/// The allocator is set by the main thread. Since a copy of the\n\t/// pointer is kept here, the application must not change the\n\t/// allocator before calling lzma_end().\n\tconst lzma_allocator *allocator;\n\n\t/// Amount of uncompressed data that has already been compressed.\n\tuint64_t progress_in;\n\n\t/// Amount of compressed data that is ready.\n\tuint64_t progress_out;\n\n\t/// Block encoder\n\tlzma_next_coder block_encoder;\n\n\t/// Compression options for this Block\n\tlzma_block block_options;\n\n\t/// Next structure in the stack of free worker threads.\n\tworker_thread *next;\n\n\tmythread_mutex mutex;\n\tmythread_cond cond;\n\n\t/// The ID of this thread is used to join the thread\n\t/// when it's not needed anymore.\n\tmythread thread_id;\n};\n\n\nstruct lzma_stream_coder_s {\n\tenum {\n\t\tSEQ_STREAM_HEADER,\n\t\tSEQ_BLOCK,\n\t\tSEQ_INDEX,\n\t\tSEQ_STREAM_FOOTER,\n\t} sequence;\n\n\t/// Start a new Block every block_size bytes of input unless\n\t/// LZMA_FULL_FLUSH or LZMA_FULL_BARRIER is used earlier.\n\tsize_t block_size;\n\n\t/// The filter chain currently in use\n\tlzma_filter filters[LZMA_FILTERS_MAX + 1];\n\n\n\t/// Index to hold sizes of the Blocks\n\tlzma_index *index;\n\n\t/// Index encoder\n\tlzma_next_coder index_encoder;\n\n\n\t/// Stream Flags for encoding the Stream Header and Stream Footer.\n\tlzma_stream_flags stream_flags;\n\n\t/// Buffer to hold Stream Header and Stream Footer.\n\tuint8_t header[LZMA_STREAM_HEADER_SIZE];\n\n\t/// Read position in header[]\n\tsize_t header_pos;\n\n\n\t/// Output buffer queue for compressed data\n\tlzma_outq outq;\n\n\n\t/// Maximum wait time if cannot use all the input and cannot\n\t/// fill the output buffer. This is in milliseconds.\n\tuint32_t timeout;\n\n\n\t/// Error code from a worker thread\n\tlzma_ret thread_error;\n\n\t/// Array of allocated thread-specific structures\n\tworker_thread *threads;\n\n\t/// Number of structures in \"threads\" above. This is also the\n\t/// number of threads that will be created at maximum.\n\tuint32_t threads_max;\n\n\t/// Number of thread structures that have been initialized, and\n\t/// thus the number of worker threads actually created so far.\n\tuint32_t threads_initialized;\n\n\t/// Stack of free threads. When a thread finishes, it puts itself\n\t/// back into this stack. This starts as empty because threads\n\t/// are created only when actually needed.\n\tworker_thread *threads_free;\n\n\t/// The most recent worker thread to which the main thread writes\n\t/// the new input from the application.\n\tworker_thread *thr;\n\n\n\t/// Amount of uncompressed data in Blocks that have already\n\t/// been finished.\n\tuint64_t progress_in;\n\n\t/// Amount of compressed data in Stream Header + Blocks that\n\t/// have already been finished.\n\tuint64_t progress_out;\n\n\n\tmythread_mutex mutex;\n\tmythread_cond cond;\n};\n\n\n/// Tell the main thread that something has gone wrong.\nstatic void\nworker_error(worker_thread *thr, lzma_ret ret)\n{\n\tassert(ret != LZMA_OK);\n\tassert(ret != LZMA_STREAM_END);\n\n\tmythread_sync(thr->coder->mutex) {\n\t\tif (thr->coder->thread_error == LZMA_OK)\n\t\t\tthr->coder->thread_error = ret;\n\n\t\tmythread_cond_signal(&thr->coder->cond);\n\t}\n\n\treturn;\n}\n\n\nstatic worker_state\nworker_encode(worker_thread *thr, worker_state state)\n{\n\tassert(thr->progress_in == 0);\n\tassert(thr->progress_out == 0);\n\n\t// Set the Block options.\n\tthr->block_options = (lzma_block){\n\t\t.version = 0,\n\t\t.check = thr->coder->stream_flags.check,\n\t\t.compressed_size = thr->coder->outq.buf_size_max,\n\t\t.uncompressed_size = thr->coder->block_size,\n\n\t\t// TODO: To allow changing the filter chain, the filters\n\t\t// array must be copied to each worker_thread.\n\t\t.filters = thr->coder->filters,\n\t};\n\n\t// Calculate maximum size of the Block Header. This amount is\n\t// reserved in the beginning of the buffer so that Block Header\n\t// along with Compressed Size and Uncompressed Size can be\n\t// written there.\n\tlzma_ret ret = lzma_block_header_size(&thr->block_options);\n\tif (ret != LZMA_OK) {\n\t\tworker_error(thr, ret);\n\t\treturn THR_STOP;\n\t}\n\n\t// Initialize the Block encoder.\n\tret = lzma_block_encoder_init(&thr->block_encoder,\n\t\t\tthr->allocator, &thr->block_options);\n\tif (ret != LZMA_OK) {\n\t\tworker_error(thr, ret);\n\t\treturn THR_STOP;\n\t}\n\n\tsize_t in_pos = 0;\n\tsize_t in_size = 0;\n\n\tthr->outbuf->size = thr->block_options.header_size;\n\tconst size_t out_size = thr->coder->outq.buf_size_max;\n\n\tdo {\n\t\tmythread_sync(thr->mutex) {\n\t\t\t// Store in_pos and out_pos into *thr so that\n\t\t\t// an application may read them via\n\t\t\t// lzma_get_progress() to get progress information.\n\t\t\t//\n\t\t\t// NOTE: These aren't updated when the encoding\n\t\t\t// finishes. Instead, the final values are taken\n\t\t\t// later from thr->outbuf.\n\t\t\tthr->progress_in = in_pos;\n\t\t\tthr->progress_out = thr->outbuf->size;\n\n\t\t\twhile (in_size == thr->in_size\n\t\t\t\t\t&& thr->state == THR_RUN)\n\t\t\t\tmythread_cond_wait(&thr->cond, &thr->mutex);\n\n\t\t\tstate = thr->state;\n\t\t\tin_size = thr->in_size;\n\t\t}\n\n\t\t// Return if we were asked to stop or exit.\n\t\tif (state >= THR_STOP)\n\t\t\treturn state;\n\n\t\tlzma_action action = state == THR_FINISH\n\t\t\t\t? LZMA_FINISH : LZMA_RUN;\n\n\t\t// Limit the amount of input given to the Block encoder\n\t\t// at once. This way this thread can react fairly quickly\n\t\t// if the main thread wants us to stop or exit.\n\t\tstatic const size_t in_chunk_max = 16384;\n\t\tsize_t in_limit = in_size;\n\t\tif (in_size - in_pos > in_chunk_max) {\n\t\t\tin_limit = in_pos + in_chunk_max;\n\t\t\taction = LZMA_RUN;\n\t\t}\n\n\t\tret = thr->block_encoder.code(\n\t\t\t\tthr->block_encoder.coder, thr->allocator,\n\t\t\t\tthr->in, &in_pos, in_limit, thr->outbuf->buf,\n\t\t\t\t&thr->outbuf->size, out_size, action);\n\t} while (ret == LZMA_OK && thr->outbuf->size < out_size);\n\n\tswitch (ret) {\n\tcase LZMA_STREAM_END:\n\t\tassert(state == THR_FINISH);\n\n\t\t// Encode the Block Header. By doing it after\n\t\t// the compression, we can store the Compressed Size\n\t\t// and Uncompressed Size fields.\n\t\tret = lzma_block_header_encode(&thr->block_options,\n\t\t\t\tthr->outbuf->buf);\n\t\tif (ret != LZMA_OK) {\n\t\t\tworker_error(thr, ret);\n\t\t\treturn THR_STOP;\n\t\t}\n\n\t\tbreak;\n\n\tcase LZMA_OK:\n\t\t// The data was incompressible. Encode it using uncompressed\n\t\t// LZMA2 chunks.\n\t\t//\n\t\t// First wait that we have gotten all the input.\n\t\tmythread_sync(thr->mutex) {\n\t\t\twhile (thr->state == THR_RUN)\n\t\t\t\tmythread_cond_wait(&thr->cond, &thr->mutex);\n\n\t\t\tstate = thr->state;\n\t\t\tin_size = thr->in_size;\n\t\t}\n\n\t\tif (state >= THR_STOP)\n\t\t\treturn state;\n\n\t\t// Do the encoding. This takes care of the Block Header too.\n\t\tthr->outbuf->size = 0;\n\t\tret = lzma_block_uncomp_encode(&thr->block_options,\n\t\t\t\tthr->in, in_size, thr->outbuf->buf,\n\t\t\t\t&thr->outbuf->size, out_size);\n\n\t\t// It shouldn't fail.\n\t\tif (ret != LZMA_OK) {\n\t\t\tworker_error(thr, LZMA_PROG_ERROR);\n\t\t\treturn THR_STOP;\n\t\t}\n\n\t\tbreak;\n\n\tdefault:\n\t\tworker_error(thr, ret);\n\t\treturn THR_STOP;\n\t}\n\n\t// Set the size information that will be read by the main thread\n\t// to write the Index field.\n\tthr->outbuf->unpadded_size\n\t\t\t= lzma_block_unpadded_size(&thr->block_options);\n\tassert(thr->outbuf->unpadded_size != 0);\n\tthr->outbuf->uncompressed_size = thr->block_options.uncompressed_size;\n\n\treturn THR_FINISH;\n}\n\n\nstatic MYTHREAD_RET_TYPE\nworker_start(void *thr_ptr)\n{\n\tworker_thread *thr = thr_ptr;\n\tworker_state state = THR_IDLE; // Init to silence a warning\n\n\twhile (true) {\n\t\t// Wait for work.\n\t\tmythread_sync(thr->mutex) {\n\t\t\twhile (true) {\n\t\t\t\t// The thread is already idle so if we are\n\t\t\t\t// requested to stop, just set the state.\n\t\t\t\tif (thr->state == THR_STOP) {\n\t\t\t\t\tthr->state = THR_IDLE;\n\t\t\t\t\tmythread_cond_signal(&thr->cond);\n\t\t\t\t}\n\n\t\t\t\tstate = thr->state;\n\t\t\t\tif (state != THR_IDLE)\n\t\t\t\t\tbreak;\n\n\t\t\t\tmythread_cond_wait(&thr->cond, &thr->mutex);\n\t\t\t}\n\t\t}\n\n\t\tassert(state != THR_IDLE);\n\t\tassert(state != THR_STOP);\n\n\t\tif (state <= THR_FINISH)\n\t\t\tstate = worker_encode(thr, state);\n\n\t\tif (state == THR_EXIT)\n\t\t\tbreak;\n\n\t\t// Mark the thread as idle unless the main thread has\n\t\t// told us to exit. Signal is needed for the case\n\t\t// where the main thread is waiting for the threads to stop.\n\t\tmythread_sync(thr->mutex) {\n\t\t\tif (thr->state != THR_EXIT) {\n\t\t\t\tthr->state = THR_IDLE;\n\t\t\t\tmythread_cond_signal(&thr->cond);\n\t\t\t}\n\t\t}\n\n\t\tmythread_sync(thr->coder->mutex) {\n\t\t\t// Mark the output buffer as finished if\n\t\t\t// no errors occurred.\n\t\t\tthr->outbuf->finished = state == THR_FINISH;\n\n\t\t\t// Update the main progress info.\n\t\t\tthr->coder->progress_in\n\t\t\t\t\t+= thr->outbuf->uncompressed_size;\n\t\t\tthr->coder->progress_out += thr->outbuf->size;\n\t\t\tthr->progress_in = 0;\n\t\t\tthr->progress_out = 0;\n\n\t\t\t// Return this thread to the stack of free threads.\n\t\t\tthr->next = thr->coder->threads_free;\n\t\t\tthr->coder->threads_free = thr;\n\n\t\t\tmythread_cond_signal(&thr->coder->cond);\n\t\t}\n\t}\n\n\t// Exiting, free the resources.\n\tmythread_mutex_destroy(&thr->mutex);\n\tmythread_cond_destroy(&thr->cond);\n\n\tlzma_next_end(&thr->block_encoder, thr->allocator);\n\tlzma_free(thr->in, thr->allocator);\n\treturn MYTHREAD_RET_VALUE;\n}\n\n\n/// Make the threads stop but not exit. Optionally wait for them to stop.\nstatic void\nthreads_stop(lzma_stream_coder *coder, bool wait_for_threads)\n{\n\t// Tell the threads to stop.\n\tfor (uint32_t i = 0; i < coder->threads_initialized; ++i) {\n\t\tmythread_sync(coder->threads[i].mutex) {\n\t\t\tcoder->threads[i].state = THR_STOP;\n\t\t\tmythread_cond_signal(&coder->threads[i].cond);\n\t\t}\n\t}\n\n\tif (!wait_for_threads)\n\t\treturn;\n\n\t// Wait for the threads to settle in the idle state.\n\tfor (uint32_t i = 0; i < coder->threads_initialized; ++i) {\n\t\tmythread_sync(coder->threads[i].mutex) {\n\t\t\twhile (coder->threads[i].state != THR_IDLE)\n\t\t\t\tmythread_cond_wait(&coder->threads[i].cond,\n\t\t\t\t\t\t&coder->threads[i].mutex);\n\t\t}\n\t}\n\n\treturn;\n}\n\n\n/// Stop the threads and free the resources associated with them.\n/// Wait until the threads have exited.\nstatic void\nthreads_end(lzma_stream_coder *coder, const lzma_allocator *allocator)\n{\n\tfor (uint32_t i = 0; i < coder->threads_initialized; ++i) {\n\t\tmythread_sync(coder->threads[i].mutex) {\n\t\t\tcoder->threads[i].state = THR_EXIT;\n\t\t\tmythread_cond_signal(&coder->threads[i].cond);\n\t\t}\n\t}\n\n\tfor (uint32_t i = 0; i < coder->threads_initialized; ++i) {\n\t\tint ret = mythread_join(coder->threads[i].thread_id);\n\t\tassert(ret == 0);\n\t\t(void)ret;\n\t}\n\n\tlzma_free(coder->threads, allocator);\n\treturn;\n}\n\n\n/// Initialize a new worker_thread structure and create a new thread.\nstatic lzma_ret\ninitialize_new_thread(lzma_stream_coder *coder,\n\t\tconst lzma_allocator *allocator)\n{\n\tworker_thread *thr = &coder->threads[coder->threads_initialized];\n\n\tthr->in = lzma_alloc(coder->block_size, allocator);\n\tif (thr->in == NULL)\n\t\treturn LZMA_MEM_ERROR;\n\n\tif (mythread_mutex_init(&thr->mutex))\n\t\tgoto error_mutex;\n\n\tif (mythread_cond_init(&thr->cond))\n\t\tgoto error_cond;\n\n\tthr->state = THR_IDLE;\n\tthr->allocator = allocator;\n\tthr->coder = coder;\n\tthr->progress_in = 0;\n\tthr->progress_out = 0;\n\tthr->block_encoder = LZMA_NEXT_CODER_INIT;\n\n\tif (mythread_create(&thr->thread_id, &worker_start, thr))\n\t\tgoto error_thread;\n\n\t++coder->threads_initialized;\n\tcoder->thr = thr;\n\n\treturn LZMA_OK;\n\nerror_thread:\n\tmythread_cond_destroy(&thr->cond);\n\nerror_cond:\n\tmythread_mutex_destroy(&thr->mutex);\n\nerror_mutex:\n\tlzma_free(thr->in, allocator);\n\treturn LZMA_MEM_ERROR;\n}\n\n\nstatic lzma_ret\nget_thread(lzma_stream_coder *coder, const lzma_allocator *allocator)\n{\n\t// If there are no free output subqueues, there is no\n\t// point to try getting a thread.\n\tif (!lzma_outq_has_buf(&coder->outq))\n\t\treturn LZMA_OK;\n\n\t// If there is a free structure on the stack, use it.\n\tmythread_sync(coder->mutex) {\n\t\tif (coder->threads_free != NULL) {\n\t\t\tcoder->thr = coder->threads_free;\n\t\t\tcoder->threads_free = coder->threads_free->next;\n\t\t}\n\t}\n\n\tif (coder->thr == NULL) {\n\t\t// If there are no uninitialized structures left, return.\n\t\tif (coder->threads_initialized == coder->threads_max)\n\t\t\treturn LZMA_OK;\n\n\t\t// Initialize a new thread.\n\t\treturn_if_error(initialize_new_thread(coder, allocator));\n\t}\n\n\t// Reset the parts of the thread state that have to be done\n\t// in the main thread.\n\tmythread_sync(coder->thr->mutex) {\n\t\tcoder->thr->state = THR_RUN;\n\t\tcoder->thr->in_size = 0;\n\t\tcoder->thr->outbuf = lzma_outq_get_buf(&coder->outq);\n\t\tmythread_cond_signal(&coder->thr->cond);\n\t}\n\n\treturn LZMA_OK;\n}\n\n\nstatic lzma_ret\nstream_encode_in(lzma_stream_coder *coder, const lzma_allocator *allocator,\n\t\tconst uint8_t *restrict in, size_t *restrict in_pos,\n\t\tsize_t in_size, lzma_action action)\n{\n\twhile (*in_pos < in_size\n\t\t\t|| (coder->thr != NULL && action != LZMA_RUN)) {\n\t\tif (coder->thr == NULL) {\n\t\t\t// Get a new thread.\n\t\t\tconst lzma_ret ret = get_thread(coder, allocator);\n\t\t\tif (coder->thr == NULL)\n\t\t\t\treturn ret;\n\t\t}\n\n\t\t// Copy the input data to thread's buffer.\n\t\tsize_t thr_in_size = coder->thr->in_size;\n\t\tlzma_bufcpy(in, in_pos, in_size, coder->thr->in,\n\t\t\t\t&thr_in_size, coder->block_size);\n\n\t\t// Tell the Block encoder to finish if\n\t\t//  - it has got block_size bytes of input; or\n\t\t//  - all input was used and LZMA_FINISH, LZMA_FULL_FLUSH,\n\t\t//    or LZMA_FULL_BARRIER was used.\n\t\t//\n\t\t// TODO: LZMA_SYNC_FLUSH and LZMA_SYNC_BARRIER.\n\t\tconst bool finish = thr_in_size == coder->block_size\n\t\t\t\t|| (*in_pos == in_size && action != LZMA_RUN);\n\n\t\tbool block_error = false;\n\n\t\tmythread_sync(coder->thr->mutex) {\n\t\t\tif (coder->thr->state == THR_IDLE) {\n\t\t\t\t// Something has gone wrong with the Block\n\t\t\t\t// encoder. It has set coder->thread_error\n\t\t\t\t// which we will read a few lines later.\n\t\t\t\tblock_error = true;\n\t\t\t} else {\n\t\t\t\t// Tell the Block encoder its new amount\n\t\t\t\t// of input and update the state if needed.\n\t\t\t\tcoder->thr->in_size = thr_in_size;\n\n\t\t\t\tif (finish)\n\t\t\t\t\tcoder->thr->state = THR_FINISH;\n\n\t\t\t\tmythread_cond_signal(&coder->thr->cond);\n\t\t\t}\n\t\t}\n\n\t\tif (block_error) {\n\t\t\tlzma_ret ret;\n\n\t\t\tmythread_sync(coder->mutex) {\n\t\t\t\tret = coder->thread_error;\n\t\t\t}\n\n\t\t\treturn ret;\n\t\t}\n\n\t\tif (finish)\n\t\t\tcoder->thr = NULL;\n\t}\n\n\treturn LZMA_OK;\n}\n\n\n/// Wait until more input can be consumed, more output can be read, or\n/// an optional timeout is reached.\nstatic bool\nwait_for_work(lzma_stream_coder *coder, mythread_condtime *wait_abs,\n\t\tbool *has_blocked, bool has_input)\n{\n\tif (coder->timeout != 0 && !*has_blocked) {\n\t\t// Every time when stream_encode_mt() is called via\n\t\t// lzma_code(), *has_blocked starts as false. We set it\n\t\t// to true here and calculate the absolute time when\n\t\t// we must return if there's nothing to do.\n\t\t//\n\t\t// The idea of *has_blocked is to avoid unneeded calls\n\t\t// to mythread_condtime_set(), which may do a syscall\n\t\t// depending on the operating system.\n\t\t*has_blocked = true;\n\t\tmythread_condtime_set(wait_abs, &coder->cond, coder->timeout);\n\t}\n\n\tbool timed_out = false;\n\n\tmythread_sync(coder->mutex) {\n\t\t// There are four things that we wait. If one of them\n\t\t// becomes possible, we return.\n\t\t//  - If there is input left, we need to get a free\n\t\t//    worker thread and an output buffer for it.\n\t\t//  - Data ready to be read from the output queue.\n\t\t//  - A worker thread indicates an error.\n\t\t//  - Time out occurs.\n\t\twhile ((!has_input || coder->threads_free == NULL\n\t\t\t\t\t|| !lzma_outq_has_buf(&coder->outq))\n\t\t\t\t&& !lzma_outq_is_readable(&coder->outq)\n\t\t\t\t&& coder->thread_error == LZMA_OK\n\t\t\t\t&& !timed_out) {\n\t\t\tif (coder->timeout != 0)\n\t\t\t\ttimed_out = mythread_cond_timedwait(\n\t\t\t\t\t\t&coder->cond, &coder->mutex,\n\t\t\t\t\t\twait_abs) != 0;\n\t\t\telse\n\t\t\t\tmythread_cond_wait(&coder->cond,\n\t\t\t\t\t\t&coder->mutex);\n\t\t}\n\t}\n\n\treturn timed_out;\n}\n\n\nstatic lzma_ret\nstream_encode_mt(void *coder_ptr, const lzma_allocator *allocator,\n\t\tconst uint8_t *restrict in, size_t *restrict in_pos,\n\t\tsize_t in_size, uint8_t *restrict out,\n\t\tsize_t *restrict out_pos, size_t out_size, lzma_action action)\n{\n\tlzma_stream_coder *coder = coder_ptr;\n\n\tswitch (coder->sequence) {\n\tcase SEQ_STREAM_HEADER:\n\t\tlzma_bufcpy(coder->header, &coder->header_pos,\n\t\t\t\tsizeof(coder->header),\n\t\t\t\tout, out_pos, out_size);\n\t\tif (coder->header_pos < sizeof(coder->header))\n\t\t\treturn LZMA_OK;\n\n\t\tcoder->header_pos = 0;\n\t\tcoder->sequence = SEQ_BLOCK;\n\n\t// Fall through\n\n\tcase SEQ_BLOCK: {\n\t\t// Initialized to silence warnings.\n\t\tlzma_vli unpadded_size = 0;\n\t\tlzma_vli uncompressed_size = 0;\n\t\tlzma_ret ret = LZMA_OK;\n\n\t\t// These are for wait_for_work().\n\t\tbool has_blocked = false;\n\t\tmythread_condtime wait_abs;\n\n\t\twhile (true) {\n\t\t\tmythread_sync(coder->mutex) {\n\t\t\t\t// Check for Block encoder errors.\n\t\t\t\tret = coder->thread_error;\n\t\t\t\tif (ret != LZMA_OK) {\n\t\t\t\t\tassert(ret != LZMA_STREAM_END);\n\t\t\t\t\tbreak; // Break out of mythread_sync.\n\t\t\t\t}\n\n\t\t\t\t// Try to read compressed data to out[].\n\t\t\t\tret = lzma_outq_read(&coder->outq,\n\t\t\t\t\t\tout, out_pos, out_size,\n\t\t\t\t\t\t&unpadded_size,\n\t\t\t\t\t\t&uncompressed_size);\n\t\t\t}\n\n\t\t\tif (ret == LZMA_STREAM_END) {\n\t\t\t\t// End of Block. Add it to the Index.\n\t\t\t\tret = lzma_index_append(coder->index,\n\t\t\t\t\t\tallocator, unpadded_size,\n\t\t\t\t\t\tuncompressed_size);\n\n\t\t\t\t// If we didn't fill the output buffer yet,\n\t\t\t\t// try to read more data. Maybe the next\n\t\t\t\t// outbuf has been finished already too.\n\t\t\t\tif (*out_pos < out_size)\n\t\t\t\t\tcontinue;\n\t\t\t}\n\n\t\t\tif (ret != LZMA_OK) {\n\t\t\t\t// coder->thread_error was set or\n\t\t\t\t// lzma_index_append() failed.\n\t\t\t\tthreads_stop(coder, false);\n\t\t\t\treturn ret;\n\t\t\t}\n\n\t\t\t// Try to give uncompressed data to a worker thread.\n\t\t\tret = stream_encode_in(coder, allocator,\n\t\t\t\t\tin, in_pos, in_size, action);\n\t\t\tif (ret != LZMA_OK) {\n\t\t\t\tthreads_stop(coder, false);\n\t\t\t\treturn ret;\n\t\t\t}\n\n\t\t\t// See if we should wait or return.\n\t\t\t//\n\t\t\t// TODO: LZMA_SYNC_FLUSH and LZMA_SYNC_BARRIER.\n\t\t\tif (*in_pos == in_size) {\n\t\t\t\t// LZMA_RUN: More data is probably coming\n\t\t\t\t// so return to let the caller fill the\n\t\t\t\t// input buffer.\n\t\t\t\tif (action == LZMA_RUN)\n\t\t\t\t\treturn LZMA_OK;\n\n\t\t\t\t// LZMA_FULL_BARRIER: The same as with\n\t\t\t\t// LZMA_RUN but tell the caller that the\n\t\t\t\t// barrier was completed.\n\t\t\t\tif (action == LZMA_FULL_BARRIER)\n\t\t\t\t\treturn LZMA_STREAM_END;\n\n\t\t\t\t// Finishing or flushing isn't completed until\n\t\t\t\t// all input data has been encoded and copied\n\t\t\t\t// to the output buffer.\n\t\t\t\tif (lzma_outq_is_empty(&coder->outq)) {\n\t\t\t\t\t// LZMA_FINISH: Continue to encode\n\t\t\t\t\t// the Index field.\n\t\t\t\t\tif (action == LZMA_FINISH)\n\t\t\t\t\t\tbreak;\n\n\t\t\t\t\t// LZMA_FULL_FLUSH: Return to tell\n\t\t\t\t\t// the caller that flushing was\n\t\t\t\t\t// completed.\n\t\t\t\t\tif (action == LZMA_FULL_FLUSH)\n\t\t\t\t\t\treturn LZMA_STREAM_END;\n\t\t\t\t}\n\t\t\t}\n\n\t\t\t// Return if there is no output space left.\n\t\t\t// This check must be done after testing the input\n\t\t\t// buffer, because we might want to use a different\n\t\t\t// return code.\n\t\t\tif (*out_pos == out_size)\n\t\t\t\treturn LZMA_OK;\n\n\t\t\t// Neither in nor out has been used completely.\n\t\t\t// Wait until there's something we can do.\n\t\t\tif (wait_for_work(coder, &wait_abs, &has_blocked,\n\t\t\t\t\t*in_pos < in_size))\n\t\t\t\treturn LZMA_TIMED_OUT;\n\t\t}\n\n\t\t// All Blocks have been encoded and the threads have stopped.\n\t\t// Prepare to encode the Index field.\n\t\treturn_if_error(lzma_index_encoder_init(\n\t\t\t\t&coder->index_encoder, allocator,\n\t\t\t\tcoder->index));\n\t\tcoder->sequence = SEQ_INDEX;\n\n\t\t// Update the progress info to take the Index and\n\t\t// Stream Footer into account. Those are very fast to encode\n\t\t// so in terms of progress information they can be thought\n\t\t// to be ready to be copied out.\n\t\tcoder->progress_out += lzma_index_size(coder->index)\n\t\t\t\t+ LZMA_STREAM_HEADER_SIZE;\n\t}\n\n\t// Fall through\n\n\tcase SEQ_INDEX: {\n\t\t// Call the Index encoder. It doesn't take any input, so\n\t\t// those pointers can be NULL.\n\t\tconst lzma_ret ret = coder->index_encoder.code(\n\t\t\t\tcoder->index_encoder.coder, allocator,\n\t\t\t\tNULL, NULL, 0,\n\t\t\t\tout, out_pos, out_size, LZMA_RUN);\n\t\tif (ret != LZMA_STREAM_END)\n\t\t\treturn ret;\n\n\t\t// Encode the Stream Footer into coder->buffer.\n\t\tcoder->stream_flags.backward_size\n\t\t\t\t= lzma_index_size(coder->index);\n\t\tif (lzma_stream_footer_encode(&coder->stream_flags,\n\t\t\t\tcoder->header) != LZMA_OK)\n\t\t\treturn LZMA_PROG_ERROR;\n\n\t\tcoder->sequence = SEQ_STREAM_FOOTER;\n\t}\n\n\t// Fall through\n\n\tcase SEQ_STREAM_FOOTER:\n\t\tlzma_bufcpy(coder->header, &coder->header_pos,\n\t\t\t\tsizeof(coder->header),\n\t\t\t\tout, out_pos, out_size);\n\t\treturn coder->header_pos < sizeof(coder->header)\n\t\t\t\t? LZMA_OK : LZMA_STREAM_END;\n\t}\n\n\tassert(0);\n\treturn LZMA_PROG_ERROR;\n}\n\n\nstatic void\nstream_encoder_mt_end(void *coder_ptr, const lzma_allocator *allocator)\n{\n\tlzma_stream_coder *coder = coder_ptr;\n\n\t// Threads must be killed before the output queue can be freed.\n\tthreads_end(coder, allocator);\n\tlzma_outq_end(&coder->outq, allocator);\n\n\tfor (size_t i = 0; coder->filters[i].id != LZMA_VLI_UNKNOWN; ++i)\n\t\tlzma_free(coder->filters[i].options, allocator);\n\n\tlzma_next_end(&coder->index_encoder, allocator);\n\tlzma_index_end(coder->index, allocator);\n\n\tmythread_cond_destroy(&coder->cond);\n\tmythread_mutex_destroy(&coder->mutex);\n\n\tlzma_free(coder, allocator);\n\treturn;\n}\n\n\n/// Options handling for lzma_stream_encoder_mt_init() and\n/// lzma_stream_encoder_mt_memusage()\nstatic lzma_ret\nget_options(const lzma_mt *options, lzma_options_easy *opt_easy,\n\t\tconst lzma_filter **filters, uint64_t *block_size,\n\t\tuint64_t *outbuf_size_max)\n{\n\t// Validate some of the options.\n\tif (options == NULL)\n\t\treturn LZMA_PROG_ERROR;\n\n\tif (options->flags != 0 || options->threads == 0\n\t\t\t|| options->threads > LZMA_THREADS_MAX)\n\t\treturn LZMA_OPTIONS_ERROR;\n\n\tif (options->filters != NULL) {\n\t\t// Filter chain was given, use it as is.\n\t\t*filters = options->filters;\n\t} else {\n\t\t// Use a preset.\n\t\tif (lzma_easy_preset(opt_easy, options->preset))\n\t\t\treturn LZMA_OPTIONS_ERROR;\n\n\t\t*filters = opt_easy->filters;\n\t}\n\n\t// Block size\n\tif (options->block_size > 0) {\n\t\tif (options->block_size > BLOCK_SIZE_MAX)\n\t\t\treturn LZMA_OPTIONS_ERROR;\n\n\t\t*block_size = options->block_size;\n\t} else {\n\t\t// Determine the Block size from the filter chain.\n\t\t*block_size = lzma_mt_block_size(*filters);\n\t\tif (*block_size == 0)\n\t\t\treturn LZMA_OPTIONS_ERROR;\n\n\t\tassert(*block_size <= BLOCK_SIZE_MAX);\n\t}\n\n\t// Calculate the maximum amount output that a single output buffer\n\t// may need to hold. This is the same as the maximum total size of\n\t// a Block.\n\t*outbuf_size_max = lzma_block_buffer_bound64(*block_size);\n\tif (*outbuf_size_max == 0)\n\t\treturn LZMA_MEM_ERROR;\n\n\treturn LZMA_OK;\n}\n\n\nstatic void\nget_progress(void *coder_ptr, uint64_t *progress_in, uint64_t *progress_out)\n{\n\tlzma_stream_coder *coder = coder_ptr;\n\n\t// Lock coder->mutex to prevent finishing threads from moving their\n\t// progress info from the worker_thread structure to lzma_stream_coder.\n\tmythread_sync(coder->mutex) {\n\t\t*progress_in = coder->progress_in;\n\t\t*progress_out = coder->progress_out;\n\n\t\tfor (size_t i = 0; i < coder->threads_initialized; ++i) {\n\t\t\tmythread_sync(coder->threads[i].mutex) {\n\t\t\t\t*progress_in += coder->threads[i].progress_in;\n\t\t\t\t*progress_out += coder->threads[i]\n\t\t\t\t\t\t.progress_out;\n\t\t\t}\n\t\t}\n\t}\n\n\treturn;\n}\n\n\nstatic lzma_ret\nstream_encoder_mt_init(lzma_next_coder *next, const lzma_allocator *allocator,\n\t\tconst lzma_mt *options)\n{\n\tlzma_next_coder_init(&stream_encoder_mt_init, next, allocator);\n\n\t// Get the filter chain.\n\tlzma_options_easy easy;\n\tconst lzma_filter *filters;\n\tuint64_t block_size;\n\tuint64_t outbuf_size_max;\n\treturn_if_error(get_options(options, &easy, &filters,\n\t\t\t&block_size, &outbuf_size_max));\n\n#if SIZE_MAX < UINT64_MAX\n\tif (block_size > SIZE_MAX)\n\t\treturn LZMA_MEM_ERROR;\n#endif\n\n\t// Validate the filter chain so that we can give an error in this\n\t// function instead of delaying it to the first call to lzma_code().\n\t// The memory usage calculation verifies the filter chain as\n\t// a side effect so we take advantage of that.\n\tif (lzma_raw_encoder_memusage(filters) == UINT64_MAX)\n\t\treturn LZMA_OPTIONS_ERROR;\n\n\t// Validate the Check ID.\n\tif ((unsigned int)(options->check) > LZMA_CHECK_ID_MAX)\n\t\treturn LZMA_PROG_ERROR;\n\n\tif (!lzma_check_is_supported(options->check))\n\t\treturn LZMA_UNSUPPORTED_CHECK;\n\n\t// Allocate and initialize the base structure if needed.\n\tlzma_stream_coder *coder = next->coder;\n\tif (coder == NULL) {\n\t\tcoder = lzma_alloc(sizeof(lzma_stream_coder), allocator);\n\t\tif (coder == NULL)\n\t\t\treturn LZMA_MEM_ERROR;\n\n\t\tnext->coder = coder;\n\n\t\t// For the mutex and condition variable initializations\n\t\t// the error handling has to be done here because\n\t\t// stream_encoder_mt_end() doesn't know if they have\n\t\t// already been initialized or not.\n\t\tif (mythread_mutex_init(&coder->mutex)) {\n\t\t\tlzma_free(coder, allocator);\n\t\t\tnext->coder = NULL;\n\t\t\treturn LZMA_MEM_ERROR;\n\t\t}\n\n\t\tif (mythread_cond_init(&coder->cond)) {\n\t\t\tmythread_mutex_destroy(&coder->mutex);\n\t\t\tlzma_free(coder, allocator);\n\t\t\tnext->coder = NULL;\n\t\t\treturn LZMA_MEM_ERROR;\n\t\t}\n\n\t\tnext->code = &stream_encode_mt;\n\t\tnext->end = &stream_encoder_mt_end;\n\t\tnext->get_progress = &get_progress;\n// \t\tnext->update = &stream_encoder_mt_update;\n\n\t\tcoder->filters[0].id = LZMA_VLI_UNKNOWN;\n\t\tcoder->index_encoder = LZMA_NEXT_CODER_INIT;\n\t\tcoder->index = NULL;\n\t\tmemzero(&coder->outq, sizeof(coder->outq));\n\t\tcoder->threads = NULL;\n\t\tcoder->threads_max = 0;\n\t\tcoder->threads_initialized = 0;\n\t}\n\n\t// Basic initializations\n\tcoder->sequence = SEQ_STREAM_HEADER;\n\tcoder->block_size = (size_t)(block_size);\n\tcoder->thread_error = LZMA_OK;\n\tcoder->thr = NULL;\n\n\t// Allocate the thread-specific base structures.\n\tassert(options->threads > 0);\n\tif (coder->threads_max != options->threads) {\n\t\tthreads_end(coder, allocator);\n\n\t\tcoder->threads = NULL;\n\t\tcoder->threads_max = 0;\n\n\t\tcoder->threads_initialized = 0;\n\t\tcoder->threads_free = NULL;\n\n\t\tcoder->threads = lzma_alloc(\n\t\t\t\toptions->threads * sizeof(worker_thread),\n\t\t\t\tallocator);\n\t\tif (coder->threads == NULL)\n\t\t\treturn LZMA_MEM_ERROR;\n\n\t\tcoder->threads_max = options->threads;\n\t} else {\n\t\t// Reuse the old structures and threads. Tell the running\n\t\t// threads to stop and wait until they have stopped.\n\t\tthreads_stop(coder, true);\n\t}\n\n\t// Output queue\n\treturn_if_error(lzma_outq_init(&coder->outq, allocator,\n\t\t\toutbuf_size_max, options->threads));\n\n\t// Timeout\n\tcoder->timeout = options->timeout;\n\n\t// Free the old filter chain and copy the new one.\n\tfor (size_t i = 0; coder->filters[i].id != LZMA_VLI_UNKNOWN; ++i)\n\t\tlzma_free(coder->filters[i].options, allocator);\n\n\treturn_if_error(lzma_filters_copy(\n\t\t\tfilters, coder->filters, allocator));\n\n\t// Index\n\tlzma_index_end(coder->index, allocator);\n\tcoder->index = lzma_index_init(allocator);\n\tif (coder->index == NULL)\n\t\treturn LZMA_MEM_ERROR;\n\n\t// Stream Header\n\tcoder->stream_flags.version = 0;\n\tcoder->stream_flags.check = options->check;\n\treturn_if_error(lzma_stream_header_encode(\n\t\t\t&coder->stream_flags, coder->header));\n\n\tcoder->header_pos = 0;\n\n\t// Progress info\n\tcoder->progress_in = 0;\n\tcoder->progress_out = LZMA_STREAM_HEADER_SIZE;\n\n\treturn LZMA_OK;\n}\n\n\nextern LZMA_API(lzma_ret)\nlzma_stream_encoder_mt(lzma_stream *strm, const lzma_mt *options)\n{\n\tlzma_next_strm_init(stream_encoder_mt_init, strm, options);\n\n\tstrm->internal->supported_actions[LZMA_RUN] = true;\n// \tstrm->internal->supported_actions[LZMA_SYNC_FLUSH] = true;\n\tstrm->internal->supported_actions[LZMA_FULL_FLUSH] = true;\n\tstrm->internal->supported_actions[LZMA_FULL_BARRIER] = true;\n\tstrm->internal->supported_actions[LZMA_FINISH] = true;\n\n\treturn LZMA_OK;\n}\n\n\n// This function name is a monster but it's consistent with the older\n// monster names. :-( 31 chars is the max that C99 requires so in that\n// sense it's not too long. ;-)\nextern LZMA_API(uint64_t)\nlzma_stream_encoder_mt_memusage(const lzma_mt *options)\n{\n\tlzma_options_easy easy;\n\tconst lzma_filter *filters;\n\tuint64_t block_size;\n\tuint64_t outbuf_size_max;\n\n\tif (get_options(options, &easy, &filters, &block_size,\n\t\t\t&outbuf_size_max) != LZMA_OK)\n\t\treturn UINT64_MAX;\n\n\t// Memory usage of the input buffers\n\tconst uint64_t inbuf_memusage = options->threads * block_size;\n\n\t// Memory usage of the filter encoders\n\tuint64_t filters_memusage = lzma_raw_encoder_memusage(filters);\n\tif (filters_memusage == UINT64_MAX)\n\t\treturn UINT64_MAX;\n\n\tfilters_memusage *= options->threads;\n\n\t// Memory usage of the output queue\n\tconst uint64_t outq_memusage = lzma_outq_memusage(\n\t\t\toutbuf_size_max, options->threads);\n\tif (outq_memusage == UINT64_MAX)\n\t\treturn UINT64_MAX;\n\n\t// Sum them with overflow checking.\n\tuint64_t total_memusage = LZMA_MEMUSAGE_BASE\n\t\t\t+ sizeof(lzma_stream_coder)\n\t\t\t+ options->threads * sizeof(worker_thread);\n\n\tif (UINT64_MAX - total_memusage < inbuf_memusage)\n\t\treturn UINT64_MAX;\n\n\ttotal_memusage += inbuf_memusage;\n\n\tif (UINT64_MAX - total_memusage < filters_memusage)\n\t\treturn UINT64_MAX;\n\n\ttotal_memusage += filters_memusage;\n\n\tif (UINT64_MAX - total_memusage < outq_memusage)\n\t\treturn UINT64_MAX;\n\n\treturn total_memusage + outq_memusage;\n}\n"
  },
  {
    "path": "external/xz/liblzma/common/stream_flags_common.c",
    "content": "///////////////////////////////////////////////////////////////////////////////\n//\n/// \\file       stream_flags_common.c\n/// \\brief      Common stuff for Stream flags coders\n//\n//  Author:     Lasse Collin\n//\n//  This file has been put into the public domain.\n//  You can do whatever you want with this file.\n//\n///////////////////////////////////////////////////////////////////////////////\n\n#include \"stream_flags_common.h\"\n\n\nconst uint8_t lzma_header_magic[6] = { 0xFD, 0x37, 0x7A, 0x58, 0x5A, 0x00 };\nconst uint8_t lzma_footer_magic[2] = { 0x59, 0x5A };\n\n\nextern LZMA_API(lzma_ret)\nlzma_stream_flags_compare(\n\t\tconst lzma_stream_flags *a, const lzma_stream_flags *b)\n{\n\t// We can compare only version 0 structures.\n\tif (a->version != 0 || b->version != 0)\n\t\treturn LZMA_OPTIONS_ERROR;\n\n\t// Check type\n\tif ((unsigned int)(a->check) > LZMA_CHECK_ID_MAX\n\t\t\t|| (unsigned int)(b->check) > LZMA_CHECK_ID_MAX)\n\t\treturn LZMA_PROG_ERROR;\n\n\tif (a->check != b->check)\n\t\treturn LZMA_DATA_ERROR;\n\n\t// Backward Sizes are compared only if they are known in both.\n\tif (a->backward_size != LZMA_VLI_UNKNOWN\n\t\t\t&& b->backward_size != LZMA_VLI_UNKNOWN) {\n\t\tif (!is_backward_size_valid(a) || !is_backward_size_valid(b))\n\t\t\treturn LZMA_PROG_ERROR;\n\n\t\tif (a->backward_size != b->backward_size)\n\t\t\treturn LZMA_DATA_ERROR;\n\t}\n\n\treturn LZMA_OK;\n}\n"
  },
  {
    "path": "external/xz/liblzma/common/stream_flags_common.h",
    "content": "///////////////////////////////////////////////////////////////////////////////\n//\n/// \\file       stream_flags_common.h\n/// \\brief      Common stuff for Stream flags coders\n//\n//  Author:     Lasse Collin\n//\n//  This file has been put into the public domain.\n//  You can do whatever you want with this file.\n//\n///////////////////////////////////////////////////////////////////////////////\n\n#ifndef LZMA_STREAM_FLAGS_COMMON_H\n#define LZMA_STREAM_FLAGS_COMMON_H\n\n#include \"common.h\"\n\n/// Size of the Stream Flags field\n#define LZMA_STREAM_FLAGS_SIZE 2\n\nextern const uint8_t lzma_header_magic[6];\nextern const uint8_t lzma_footer_magic[2];\n\n\nstatic inline bool\nis_backward_size_valid(const lzma_stream_flags *options)\n{\n\treturn options->backward_size >= LZMA_BACKWARD_SIZE_MIN\n\t\t\t&& options->backward_size <= LZMA_BACKWARD_SIZE_MAX\n\t\t\t&& (options->backward_size & 3) == 0;\n}\n\n#endif\n"
  },
  {
    "path": "external/xz/liblzma/common/stream_flags_decoder.c",
    "content": "///////////////////////////////////////////////////////////////////////////////\n//\n/// \\file       stream_flags_decoder.c\n/// \\brief      Decodes Stream Header and Stream Footer from .xz files\n//\n//  Author:     Lasse Collin\n//\n//  This file has been put into the public domain.\n//  You can do whatever you want with this file.\n//\n///////////////////////////////////////////////////////////////////////////////\n\n#include \"stream_flags_common.h\"\n\n\nstatic bool\nstream_flags_decode(lzma_stream_flags *options, const uint8_t *in)\n{\n\t// Reserved bits must be unset.\n\tif (in[0] != 0x00 || (in[1] & 0xF0))\n\t\treturn true;\n\n\toptions->version = 0;\n\toptions->check = in[1] & 0x0F;\n\n\treturn false;\n}\n\n\nextern LZMA_API(lzma_ret)\nlzma_stream_header_decode(lzma_stream_flags *options, const uint8_t *in)\n{\n\t// Magic\n\tif (memcmp(in, lzma_header_magic, sizeof(lzma_header_magic)) != 0)\n\t\treturn LZMA_FORMAT_ERROR;\n\n\t// Verify the CRC32 so we can distinguish between corrupt\n\t// and unsupported files.\n\tconst uint32_t crc = lzma_crc32(in + sizeof(lzma_header_magic),\n\t\t\tLZMA_STREAM_FLAGS_SIZE, 0);\n\tif (crc != read32le(in + sizeof(lzma_header_magic)\n\t\t\t+ LZMA_STREAM_FLAGS_SIZE))\n\t\treturn LZMA_DATA_ERROR;\n\n\t// Stream Flags\n\tif (stream_flags_decode(options, in + sizeof(lzma_header_magic)))\n\t\treturn LZMA_OPTIONS_ERROR;\n\n\t// Set Backward Size to indicate unknown value. That way\n\t// lzma_stream_flags_compare() can be used to compare Stream Header\n\t// and Stream Footer while keeping it useful also for comparing\n\t// two Stream Footers.\n\toptions->backward_size = LZMA_VLI_UNKNOWN;\n\n\treturn LZMA_OK;\n}\n\n\nextern LZMA_API(lzma_ret)\nlzma_stream_footer_decode(lzma_stream_flags *options, const uint8_t *in)\n{\n\t// Magic\n\tif (memcmp(in + sizeof(uint32_t) * 2 + LZMA_STREAM_FLAGS_SIZE,\n\t\t\tlzma_footer_magic, sizeof(lzma_footer_magic)) != 0)\n\t\treturn LZMA_FORMAT_ERROR;\n\n\t// CRC32\n\tconst uint32_t crc = lzma_crc32(in + sizeof(uint32_t),\n\t\t\tsizeof(uint32_t) + LZMA_STREAM_FLAGS_SIZE, 0);\n\tif (crc != read32le(in))\n\t\treturn LZMA_DATA_ERROR;\n\n\t// Stream Flags\n\tif (stream_flags_decode(options, in + sizeof(uint32_t) * 2))\n\t\treturn LZMA_OPTIONS_ERROR;\n\n\t// Backward Size\n\toptions->backward_size = read32le(in + sizeof(uint32_t));\n\toptions->backward_size = (options->backward_size + 1) * 4;\n\n\treturn LZMA_OK;\n}\n"
  },
  {
    "path": "external/xz/liblzma/common/stream_flags_encoder.c",
    "content": "///////////////////////////////////////////////////////////////////////////////\n//\n/// \\file       stream_flags_encoder.c\n/// \\brief      Encodes Stream Header and Stream Footer for .xz files\n//\n//  Author:     Lasse Collin\n//\n//  This file has been put into the public domain.\n//  You can do whatever you want with this file.\n//\n///////////////////////////////////////////////////////////////////////////////\n\n#include \"stream_flags_common.h\"\n\n\nstatic bool\nstream_flags_encode(const lzma_stream_flags *options, uint8_t *out)\n{\n\tif ((unsigned int)(options->check) > LZMA_CHECK_ID_MAX)\n\t\treturn true;\n\n\tout[0] = 0x00;\n\tout[1] = options->check;\n\n\treturn false;\n}\n\n\nextern LZMA_API(lzma_ret)\nlzma_stream_header_encode(const lzma_stream_flags *options, uint8_t *out)\n{\n\tassert(sizeof(lzma_header_magic) + LZMA_STREAM_FLAGS_SIZE\n\t\t\t+ 4 == LZMA_STREAM_HEADER_SIZE);\n\n\tif (options->version != 0)\n\t\treturn LZMA_OPTIONS_ERROR;\n\n\t// Magic\n\tmemcpy(out, lzma_header_magic, sizeof(lzma_header_magic));\n\n\t// Stream Flags\n\tif (stream_flags_encode(options, out + sizeof(lzma_header_magic)))\n\t\treturn LZMA_PROG_ERROR;\n\n\t// CRC32 of the Stream Header\n\tconst uint32_t crc = lzma_crc32(out + sizeof(lzma_header_magic),\n\t\t\tLZMA_STREAM_FLAGS_SIZE, 0);\n\n\twrite32le(out + sizeof(lzma_header_magic) + LZMA_STREAM_FLAGS_SIZE,\n\t\t\tcrc);\n\n\treturn LZMA_OK;\n}\n\n\nextern LZMA_API(lzma_ret)\nlzma_stream_footer_encode(const lzma_stream_flags *options, uint8_t *out)\n{\n\tassert(2 * 4 + LZMA_STREAM_FLAGS_SIZE + sizeof(lzma_footer_magic)\n\t\t\t== LZMA_STREAM_HEADER_SIZE);\n\n\tif (options->version != 0)\n\t\treturn LZMA_OPTIONS_ERROR;\n\n\t// Backward Size\n\tif (!is_backward_size_valid(options))\n\t\treturn LZMA_PROG_ERROR;\n\n\twrite32le(out + 4, options->backward_size / 4 - 1);\n\n\t// Stream Flags\n\tif (stream_flags_encode(options, out + 2 * 4))\n\t\treturn LZMA_PROG_ERROR;\n\n\t// CRC32\n\tconst uint32_t crc = lzma_crc32(\n\t\t\tout + 4, 4 + LZMA_STREAM_FLAGS_SIZE, 0);\n\n\twrite32le(out, crc);\n\n\t// Magic\n\tmemcpy(out + 2 * 4 + LZMA_STREAM_FLAGS_SIZE,\n\t\t\tlzma_footer_magic, sizeof(lzma_footer_magic));\n\n\treturn LZMA_OK;\n}\n"
  },
  {
    "path": "external/xz/liblzma/common/vli_decoder.c",
    "content": "///////////////////////////////////////////////////////////////////////////////\n//\n/// \\file       vli_decoder.c\n/// \\brief      Decodes variable-length integers\n//\n//  Author:     Lasse Collin\n//\n//  This file has been put into the public domain.\n//  You can do whatever you want with this file.\n//\n///////////////////////////////////////////////////////////////////////////////\n\n#include \"common.h\"\n\n\nextern LZMA_API(lzma_ret)\nlzma_vli_decode(lzma_vli *restrict vli, size_t *vli_pos,\n\t\tconst uint8_t *restrict in, size_t *restrict in_pos,\n\t\tsize_t in_size)\n{\n\t// If we haven't been given vli_pos, work in single-call mode.\n\tsize_t vli_pos_internal = 0;\n\tif (vli_pos == NULL) {\n\t\tvli_pos = &vli_pos_internal;\n\t\t*vli = 0;\n\n\t\t// If there's no input, use LZMA_DATA_ERROR. This way it is\n\t\t// easy to decode VLIs from buffers that have known size,\n\t\t// and get the correct error code in case the buffer is\n\t\t// too short.\n\t\tif (*in_pos >= in_size)\n\t\t\treturn LZMA_DATA_ERROR;\n\n\t} else {\n\t\t// Initialize *vli when starting to decode a new integer.\n\t\tif (*vli_pos == 0)\n\t\t\t*vli = 0;\n\n\t\t// Validate the arguments.\n\t\tif (*vli_pos >= LZMA_VLI_BYTES_MAX\n\t\t\t\t|| (*vli >> (*vli_pos * 7)) != 0)\n\t\t\treturn LZMA_PROG_ERROR;;\n\n\t\tif (*in_pos >= in_size)\n\t\t\treturn LZMA_BUF_ERROR;\n\t}\n\n\tdo {\n\t\t// Read the next byte. Use a temporary variable so that we\n\t\t// can update *in_pos immediately.\n\t\tconst uint8_t byte = in[*in_pos];\n\t\t++*in_pos;\n\n\t\t// Add the newly read byte to *vli.\n\t\t*vli += (lzma_vli)(byte & 0x7F) << (*vli_pos * 7);\n\t\t++*vli_pos;\n\n\t\t// Check if this is the last byte of a multibyte integer.\n\t\tif ((byte & 0x80) == 0) {\n\t\t\t// We don't allow using variable-length integers as\n\t\t\t// padding i.e. the encoding must use the most the\n\t\t\t// compact form.\n\t\t\tif (byte == 0x00 && *vli_pos > 1)\n\t\t\t\treturn LZMA_DATA_ERROR;\n\n\t\t\treturn vli_pos == &vli_pos_internal\n\t\t\t\t\t? LZMA_OK : LZMA_STREAM_END;\n\t\t}\n\n\t\t// There is at least one more byte coming. If we have already\n\t\t// read maximum number of bytes, the integer is considered\n\t\t// corrupt.\n\t\t//\n\t\t// If we need bigger integers in future, old versions liblzma\n\t\t// will confusingly indicate the file being corrupt instead of\n\t\t// unsupported. I suppose it's still better this way, because\n\t\t// in the foreseeable future (writing this in 2008) the only\n\t\t// reason why files would appear having over 63-bit integers\n\t\t// is that the files are simply corrupt.\n\t\tif (*vli_pos == LZMA_VLI_BYTES_MAX)\n\t\t\treturn LZMA_DATA_ERROR;\n\n\t} while (*in_pos < in_size);\n\n\treturn vli_pos == &vli_pos_internal ? LZMA_DATA_ERROR : LZMA_OK;\n}\n"
  },
  {
    "path": "external/xz/liblzma/common/vli_encoder.c",
    "content": "///////////////////////////////////////////////////////////////////////////////\n//\n/// \\file       vli_encoder.c\n/// \\brief      Encodes variable-length integers\n//\n//  Author:     Lasse Collin\n//\n//  This file has been put into the public domain.\n//  You can do whatever you want with this file.\n//\n///////////////////////////////////////////////////////////////////////////////\n\n#include \"common.h\"\n\n\nextern LZMA_API(lzma_ret)\nlzma_vli_encode(lzma_vli vli, size_t *vli_pos,\n\t\tuint8_t *restrict out, size_t *restrict out_pos,\n\t\tsize_t out_size)\n{\n\t// If we haven't been given vli_pos, work in single-call mode.\n\tsize_t vli_pos_internal = 0;\n\tif (vli_pos == NULL) {\n\t\tvli_pos = &vli_pos_internal;\n\n\t\t// In single-call mode, we expect that the caller has\n\t\t// reserved enough output space.\n\t\tif (*out_pos >= out_size)\n\t\t\treturn LZMA_PROG_ERROR;\n\t} else {\n\t\t// This never happens when we are called by liblzma, but\n\t\t// may happen if called directly from an application.\n\t\tif (*out_pos >= out_size)\n\t\t\treturn LZMA_BUF_ERROR;\n\t}\n\n\t// Validate the arguments.\n\tif (*vli_pos >= LZMA_VLI_BYTES_MAX || vli > LZMA_VLI_MAX)\n\t\treturn LZMA_PROG_ERROR;\n\n\t// Shift vli so that the next bits to encode are the lowest. In\n\t// single-call mode this never changes vli since *vli_pos is zero.\n\tvli >>= *vli_pos * 7;\n\n\t// Write the non-last bytes in a loop.\n\twhile (vli >= 0x80) {\n\t\t// We don't need *vli_pos during this function call anymore,\n\t\t// but update it here so that it is ready if we need to\n\t\t// return before the whole integer has been decoded.\n\t\t++*vli_pos;\n\t\tassert(*vli_pos < LZMA_VLI_BYTES_MAX);\n\n\t\t// Write the next byte.\n\t\tout[*out_pos] = (uint8_t)(vli) | 0x80;\n\t\tvli >>= 7;\n\n\t\tif (++*out_pos == out_size)\n\t\t\treturn vli_pos == &vli_pos_internal\n\t\t\t\t\t? LZMA_PROG_ERROR : LZMA_OK;\n\t}\n\n\t// Write the last byte.\n\tout[*out_pos] = (uint8_t)(vli);\n\t++*out_pos;\n\t++*vli_pos;\n\n\treturn vli_pos == &vli_pos_internal ? LZMA_OK : LZMA_STREAM_END;\n\n}\n"
  },
  {
    "path": "external/xz/liblzma/common/vli_size.c",
    "content": "///////////////////////////////////////////////////////////////////////////////\n//\n/// \\file       vli_size.c\n/// \\brief      Calculates the encoded size of a variable-length integer\n//\n//  Author:     Lasse Collin\n//\n//  This file has been put into the public domain.\n//  You can do whatever you want with this file.\n//\n///////////////////////////////////////////////////////////////////////////////\n\n#include \"common.h\"\n\n\nextern LZMA_API(uint32_t)\nlzma_vli_size(lzma_vli vli)\n{\n\tif (vli > LZMA_VLI_MAX)\n\t\treturn 0;\n\n\tuint32_t i = 0;\n\tdo {\n\t\tvli >>= 7;\n\t\t++i;\n\t} while (vli != 0);\n\n\tassert(i <= LZMA_VLI_BYTES_MAX);\n\treturn i;\n}\n"
  },
  {
    "path": "external/xz/liblzma/delta/delta_common.c",
    "content": "///////////////////////////////////////////////////////////////////////////////\n//\n/// \\file       delta_common.c\n/// \\brief      Common stuff for Delta encoder and decoder\n//\n//  Author:     Lasse Collin\n//\n//  This file has been put into the public domain.\n//  You can do whatever you want with this file.\n//\n///////////////////////////////////////////////////////////////////////////////\n\n#include \"delta_common.h\"\n#include \"delta_private.h\"\n\n\nstatic void\ndelta_coder_end(void *coder_ptr, const lzma_allocator *allocator)\n{\n\tlzma_delta_coder *coder = coder_ptr;\n\tlzma_next_end(&coder->next, allocator);\n\tlzma_free(coder, allocator);\n\treturn;\n}\n\n\nextern lzma_ret\nlzma_delta_coder_init(lzma_next_coder *next, const lzma_allocator *allocator,\n\t\tconst lzma_filter_info *filters)\n{\n\t// Allocate memory for the decoder if needed.\n\tlzma_delta_coder *coder = next->coder;\n\tif (coder == NULL) {\n\t\tcoder = lzma_alloc(sizeof(lzma_delta_coder), allocator);\n\t\tif (coder == NULL)\n\t\t\treturn LZMA_MEM_ERROR;\n\n\t\tnext->coder = coder;\n\n\t\t// End function is the same for encoder and decoder.\n\t\tnext->end = &delta_coder_end;\n\t\tcoder->next = LZMA_NEXT_CODER_INIT;\n\t}\n\n\t// Validate the options.\n\tif (lzma_delta_coder_memusage(filters[0].options) == UINT64_MAX)\n\t\treturn LZMA_OPTIONS_ERROR;\n\n\t// Set the delta distance.\n\tconst lzma_options_delta *opt = filters[0].options;\n\tcoder->distance = opt->dist;\n\n\t// Initialize the rest of the variables.\n\tcoder->pos = 0;\n\tmemzero(coder->history, LZMA_DELTA_DIST_MAX);\n\n\t// Initialize the next decoder in the chain, if any.\n\treturn lzma_next_filter_init(&coder->next, allocator, filters + 1);\n}\n\n\nextern uint64_t\nlzma_delta_coder_memusage(const void *options)\n{\n\tconst lzma_options_delta *opt = options;\n\n\tif (opt == NULL || opt->type != LZMA_DELTA_TYPE_BYTE\n\t\t\t|| opt->dist < LZMA_DELTA_DIST_MIN\n\t\t\t|| opt->dist > LZMA_DELTA_DIST_MAX)\n\t\treturn UINT64_MAX;\n\n\treturn sizeof(lzma_delta_coder);\n}\n"
  },
  {
    "path": "external/xz/liblzma/delta/delta_common.h",
    "content": "///////////////////////////////////////////////////////////////////////////////\n//\n/// \\file       delta_common.h\n/// \\brief      Common stuff for Delta encoder and decoder\n//\n//  Author:     Lasse Collin\n//\n//  This file has been put into the public domain.\n//  You can do whatever you want with this file.\n//\n///////////////////////////////////////////////////////////////////////////////\n\n#ifndef LZMA_DELTA_COMMON_H\n#define LZMA_DELTA_COMMON_H\n\n#include \"common.h\"\n\nextern uint64_t lzma_delta_coder_memusage(const void *options);\n\n#endif\n"
  },
  {
    "path": "external/xz/liblzma/delta/delta_decoder.c",
    "content": "///////////////////////////////////////////////////////////////////////////////\n//\n/// \\file       delta_decoder.c\n/// \\brief      Delta filter decoder\n//\n//  Author:     Lasse Collin\n//\n//  This file has been put into the public domain.\n//  You can do whatever you want with this file.\n//\n///////////////////////////////////////////////////////////////////////////////\n\n#include \"delta_decoder.h\"\n#include \"delta_private.h\"\n\n\nstatic void\ndecode_buffer(lzma_delta_coder *coder, uint8_t *buffer, size_t size)\n{\n\tconst size_t distance = coder->distance;\n\n\tfor (size_t i = 0; i < size; ++i) {\n\t\tbuffer[i] += coder->history[(distance + coder->pos) & 0xFF];\n\t\tcoder->history[coder->pos-- & 0xFF] = buffer[i];\n\t}\n}\n\n\nstatic lzma_ret\ndelta_decode(void *coder_ptr, const lzma_allocator *allocator,\n\t\tconst uint8_t *restrict in, size_t *restrict in_pos,\n\t\tsize_t in_size, uint8_t *restrict out,\n\t\tsize_t *restrict out_pos, size_t out_size, lzma_action action)\n{\n\tlzma_delta_coder *coder = coder_ptr;\n\n\tassert(coder->next.code != NULL);\n\n\tconst size_t out_start = *out_pos;\n\n\tconst lzma_ret ret = coder->next.code(coder->next.coder, allocator,\n\t\t\tin, in_pos, in_size, out, out_pos, out_size,\n\t\t\taction);\n\n\tdecode_buffer(coder, out + out_start, *out_pos - out_start);\n\n\treturn ret;\n}\n\n\nextern lzma_ret\nlzma_delta_decoder_init(lzma_next_coder *next, const lzma_allocator *allocator,\n\t\tconst lzma_filter_info *filters)\n{\n\tnext->code = &delta_decode;\n\treturn lzma_delta_coder_init(next, allocator, filters);\n}\n\n\nextern lzma_ret\nlzma_delta_props_decode(void **options, const lzma_allocator *allocator,\n\t\tconst uint8_t *props, size_t props_size)\n{\n\tif (props_size != 1)\n\t\treturn LZMA_OPTIONS_ERROR;\n\n\tlzma_options_delta *opt\n\t\t\t= lzma_alloc(sizeof(lzma_options_delta), allocator);\n\tif (opt == NULL)\n\t\treturn LZMA_MEM_ERROR;\n\n\topt->type = LZMA_DELTA_TYPE_BYTE;\n\topt->dist = props[0] + 1U;\n\n\t*options = opt;\n\n\treturn LZMA_OK;\n}\n"
  },
  {
    "path": "external/xz/liblzma/delta/delta_decoder.h",
    "content": "///////////////////////////////////////////////////////////////////////////////\n//\n/// \\file       delta_decoder.h\n/// \\brief      Delta filter decoder\n//\n//  Author:     Lasse Collin\n//\n//  This file has been put into the public domain.\n//  You can do whatever you want with this file.\n//\n///////////////////////////////////////////////////////////////////////////////\n\n#ifndef LZMA_DELTA_DECODER_H\n#define LZMA_DELTA_DECODER_H\n\n#include \"delta_common.h\"\n\nextern lzma_ret lzma_delta_decoder_init(lzma_next_coder *next,\n\t\tconst lzma_allocator *allocator,\n\t\tconst lzma_filter_info *filters);\n\nextern lzma_ret lzma_delta_props_decode(\n\t\tvoid **options, const lzma_allocator *allocator,\n\t\tconst uint8_t *props, size_t props_size);\n\n#endif\n"
  },
  {
    "path": "external/xz/liblzma/delta/delta_encoder.c",
    "content": "///////////////////////////////////////////////////////////////////////////////\n//\n/// \\file       delta_encoder.c\n/// \\brief      Delta filter encoder\n//\n//  Author:     Lasse Collin\n//\n//  This file has been put into the public domain.\n//  You can do whatever you want with this file.\n//\n///////////////////////////////////////////////////////////////////////////////\n\n#include \"delta_encoder.h\"\n#include \"delta_private.h\"\n\n\n/// Copies and encodes the data at the same time. This is used when Delta\n/// is the first filter in the chain (and thus the last filter in the\n/// encoder's filter stack).\nstatic void\ncopy_and_encode(lzma_delta_coder *coder,\n\t\tconst uint8_t *restrict in, uint8_t *restrict out, size_t size)\n{\n\tconst size_t distance = coder->distance;\n\n\tfor (size_t i = 0; i < size; ++i) {\n\t\tconst uint8_t tmp = coder->history[\n\t\t\t\t(distance + coder->pos) & 0xFF];\n\t\tcoder->history[coder->pos-- & 0xFF] = in[i];\n\t\tout[i] = in[i] - tmp;\n\t}\n}\n\n\n/// Encodes the data in place. This is used when we are the last filter\n/// in the chain (and thus non-last filter in the encoder's filter stack).\nstatic void\nencode_in_place(lzma_delta_coder *coder, uint8_t *buffer, size_t size)\n{\n\tconst size_t distance = coder->distance;\n\n\tfor (size_t i = 0; i < size; ++i) {\n\t\tconst uint8_t tmp = coder->history[\n\t\t\t\t(distance + coder->pos) & 0xFF];\n\t\tcoder->history[coder->pos-- & 0xFF] = buffer[i];\n\t\tbuffer[i] -= tmp;\n\t}\n}\n\n\nstatic lzma_ret\ndelta_encode(void *coder_ptr, const lzma_allocator *allocator,\n\t\tconst uint8_t *restrict in, size_t *restrict in_pos,\n\t\tsize_t in_size, uint8_t *restrict out,\n\t\tsize_t *restrict out_pos, size_t out_size, lzma_action action)\n{\n\tlzma_delta_coder *coder = coder_ptr;\n\n\tlzma_ret ret;\n\n\tif (coder->next.code == NULL) {\n\t\tconst size_t in_avail = in_size - *in_pos;\n\t\tconst size_t out_avail = out_size - *out_pos;\n\t\tconst size_t size = my_min(in_avail, out_avail);\n\n\t\tcopy_and_encode(coder, in + *in_pos, out + *out_pos, size);\n\n\t\t*in_pos += size;\n\t\t*out_pos += size;\n\n\t\tret = action != LZMA_RUN && *in_pos == in_size\n\t\t\t\t? LZMA_STREAM_END : LZMA_OK;\n\n\t} else {\n\t\tconst size_t out_start = *out_pos;\n\n\t\tret = coder->next.code(coder->next.coder, allocator,\n\t\t\t\tin, in_pos, in_size, out, out_pos, out_size,\n\t\t\t\taction);\n\n\t\tencode_in_place(coder, out + out_start, *out_pos - out_start);\n\t}\n\n\treturn ret;\n}\n\n\nstatic lzma_ret\ndelta_encoder_update(void *coder_ptr, const lzma_allocator *allocator,\n\t\tconst lzma_filter *filters_null lzma_attribute((__unused__)),\n\t\tconst lzma_filter *reversed_filters)\n{\n\tlzma_delta_coder *coder = coder_ptr;\n\n\t// Delta doesn't and will never support changing the options in\n\t// the middle of encoding. If the app tries to change them, we\n\t// simply ignore them.\n\treturn lzma_next_filter_update(\n\t\t\t&coder->next, allocator, reversed_filters + 1);\n}\n\n\nextern lzma_ret\nlzma_delta_encoder_init(lzma_next_coder *next, const lzma_allocator *allocator,\n\t\tconst lzma_filter_info *filters)\n{\n\tnext->code = &delta_encode;\n\tnext->update = &delta_encoder_update;\n\treturn lzma_delta_coder_init(next, allocator, filters);\n}\n\n\nextern lzma_ret\nlzma_delta_props_encode(const void *options, uint8_t *out)\n{\n\t// The caller must have already validated the options, so it's\n\t// LZMA_PROG_ERROR if they are invalid.\n\tif (lzma_delta_coder_memusage(options) == UINT64_MAX)\n\t\treturn LZMA_PROG_ERROR;\n\n\tconst lzma_options_delta *opt = options;\n\tout[0] = opt->dist - LZMA_DELTA_DIST_MIN;\n\n\treturn LZMA_OK;\n}\n"
  },
  {
    "path": "external/xz/liblzma/delta/delta_encoder.h",
    "content": "///////////////////////////////////////////////////////////////////////////////\n//\n/// \\file       delta_encoder.h\n/// \\brief      Delta filter encoder\n//\n//  Author:     Lasse Collin\n//\n//  This file has been put into the public domain.\n//  You can do whatever you want with this file.\n//\n///////////////////////////////////////////////////////////////////////////////\n\n#ifndef LZMA_DELTA_ENCODER_H\n#define LZMA_DELTA_ENCODER_H\n\n#include \"delta_common.h\"\n\nextern lzma_ret lzma_delta_encoder_init(lzma_next_coder *next,\n\t\tconst lzma_allocator *allocator,\n\t\tconst lzma_filter_info *filters);\n\nextern lzma_ret lzma_delta_props_encode(const void *options, uint8_t *out);\n\n#endif\n"
  },
  {
    "path": "external/xz/liblzma/delta/delta_private.h",
    "content": "///////////////////////////////////////////////////////////////////////////////\n//\n/// \\file       delta_private.h\n/// \\brief      Private common stuff for Delta encoder and decoder\n//\n//  Author:     Lasse Collin\n//\n//  This file has been put into the public domain.\n//  You can do whatever you want with this file.\n//\n///////////////////////////////////////////////////////////////////////////////\n\n#ifndef LZMA_DELTA_PRIVATE_H\n#define LZMA_DELTA_PRIVATE_H\n\n#include \"delta_common.h\"\n\ntypedef struct {\n\t/// Next coder in the chain\n\tlzma_next_coder next;\n\n\t/// Delta distance\n\tsize_t distance;\n\n\t/// Position in history[]\n\tuint8_t pos;\n\n\t/// Buffer to hold history of the original data\n\tuint8_t history[LZMA_DELTA_DIST_MAX];\n} lzma_delta_coder;\n\n\nextern lzma_ret lzma_delta_coder_init(\n\t\tlzma_next_coder *next, const lzma_allocator *allocator,\n\t\tconst lzma_filter_info *filters);\n\n#endif\n"
  },
  {
    "path": "external/xz/liblzma/lz/lz_decoder.c",
    "content": "///////////////////////////////////////////////////////////////////////////////\n//\n/// \\file       lz_decoder.c\n/// \\brief      LZ out window\n///\n//  Authors:    Igor Pavlov\n//              Lasse Collin\n//\n//  This file has been put into the public domain.\n//  You can do whatever you want with this file.\n//\n///////////////////////////////////////////////////////////////////////////////\n\n// liblzma supports multiple LZ77-based filters. The LZ part is shared\n// between these filters. The LZ code takes care of dictionary handling\n// and passing the data between filters in the chain. The filter-specific\n// part decodes from the input buffer to the dictionary.\n\n\n#include \"lz_decoder.h\"\n\n\ntypedef struct {\n\t/// Dictionary (history buffer)\n\tlzma_dict dict;\n\n\t/// The actual LZ-based decoder e.g. LZMA\n\tlzma_lz_decoder lz;\n\n\t/// Next filter in the chain, if any. Note that LZMA and LZMA2 are\n\t/// only allowed as the last filter, but the long-range filter in\n\t/// future can be in the middle of the chain.\n\tlzma_next_coder next;\n\n\t/// True if the next filter in the chain has returned LZMA_STREAM_END.\n\tbool next_finished;\n\n\t/// True if the LZ decoder (e.g. LZMA) has detected end of payload\n\t/// marker. This may become true before next_finished becomes true.\n\tbool this_finished;\n\n\t/// Temporary buffer needed when the LZ-based filter is not the last\n\t/// filter in the chain. The output of the next filter is first\n\t/// decoded into buffer[], which is then used as input for the actual\n\t/// LZ-based decoder.\n\tstruct {\n\t\tsize_t pos;\n\t\tsize_t size;\n\t\tuint8_t buffer[LZMA_BUFFER_SIZE];\n\t} temp;\n} lzma_coder;\n\n\nstatic void\nlz_decoder_reset(lzma_coder *coder)\n{\n\tcoder->dict.pos = 0;\n\tcoder->dict.full = 0;\n\tcoder->dict.buf[coder->dict.size - 1] = '\\0';\n\tcoder->dict.need_reset = false;\n\treturn;\n}\n\n\nstatic lzma_ret\ndecode_buffer(lzma_coder *coder,\n\t\tconst uint8_t *restrict in, size_t *restrict in_pos,\n\t\tsize_t in_size, uint8_t *restrict out,\n\t\tsize_t *restrict out_pos, size_t out_size)\n{\n\twhile (true) {\n\t\t// Wrap the dictionary if needed.\n\t\tif (coder->dict.pos == coder->dict.size)\n\t\t\tcoder->dict.pos = 0;\n\n\t\t// Store the current dictionary position. It is needed to know\n\t\t// where to start copying to the out[] buffer.\n\t\tconst size_t dict_start = coder->dict.pos;\n\n\t\t// Calculate how much we allow coder->lz.code() to decode.\n\t\t// It must not decode past the end of the dictionary\n\t\t// buffer, and we don't want it to decode more than is\n\t\t// actually needed to fill the out[] buffer.\n\t\tcoder->dict.limit = coder->dict.pos\n\t\t\t\t+ my_min(out_size - *out_pos,\n\t\t\t\t\tcoder->dict.size - coder->dict.pos);\n\n\t\t// Call the coder->lz.code() to do the actual decoding.\n\t\tconst lzma_ret ret = coder->lz.code(\n\t\t\t\tcoder->lz.coder, &coder->dict,\n\t\t\t\tin, in_pos, in_size);\n\n\t\t// Copy the decoded data from the dictionary to the out[]\n\t\t// buffer. Do it conditionally because out can be NULL\n\t\t// (in which case copy_size is always 0). Calling memcpy()\n\t\t// with a null-pointer is undefined even if the third\n\t\t// argument is 0.\n\t\tconst size_t copy_size = coder->dict.pos - dict_start;\n\t\tassert(copy_size <= out_size - *out_pos);\n\n\t\tif (copy_size > 0)\n\t\t\tmemcpy(out + *out_pos, coder->dict.buf + dict_start,\n\t\t\t\t\tcopy_size);\n\n\t\t*out_pos += copy_size;\n\n\t\t// Reset the dictionary if so requested by coder->lz.code().\n\t\tif (coder->dict.need_reset) {\n\t\t\tlz_decoder_reset(coder);\n\n\t\t\t// Since we reset dictionary, we don't check if\n\t\t\t// dictionary became full.\n\t\t\tif (ret != LZMA_OK || *out_pos == out_size)\n\t\t\t\treturn ret;\n\t\t} else {\n\t\t\t// Return if everything got decoded or an error\n\t\t\t// occurred, or if there's no more data to decode.\n\t\t\t//\n\t\t\t// Note that detecting if there's something to decode\n\t\t\t// is done by looking if dictionary become full\n\t\t\t// instead of looking if *in_pos == in_size. This\n\t\t\t// is because it is possible that all the input was\n\t\t\t// consumed already but some data is pending to be\n\t\t\t// written to the dictionary.\n\t\t\tif (ret != LZMA_OK || *out_pos == out_size\n\t\t\t\t\t|| coder->dict.pos < coder->dict.size)\n\t\t\t\treturn ret;\n\t\t}\n\t}\n}\n\n\nstatic lzma_ret\nlz_decode(void *coder_ptr, const lzma_allocator *allocator,\n\t\tconst uint8_t *restrict in, size_t *restrict in_pos,\n\t\tsize_t in_size, uint8_t *restrict out,\n\t\tsize_t *restrict out_pos, size_t out_size,\n\t\tlzma_action action)\n{\n\tlzma_coder *coder = coder_ptr;\n\n\tif (coder->next.code == NULL)\n\t\treturn decode_buffer(coder, in, in_pos, in_size,\n\t\t\t\tout, out_pos, out_size);\n\n\t// We aren't the last coder in the chain, we need to decode\n\t// our input to a temporary buffer.\n\twhile (*out_pos < out_size) {\n\t\t// Fill the temporary buffer if it is empty.\n\t\tif (!coder->next_finished\n\t\t\t\t&& coder->temp.pos == coder->temp.size) {\n\t\t\tcoder->temp.pos = 0;\n\t\t\tcoder->temp.size = 0;\n\n\t\t\tconst lzma_ret ret = coder->next.code(\n\t\t\t\t\tcoder->next.coder,\n\t\t\t\t\tallocator, in, in_pos, in_size,\n\t\t\t\t\tcoder->temp.buffer, &coder->temp.size,\n\t\t\t\t\tLZMA_BUFFER_SIZE, action);\n\n\t\t\tif (ret == LZMA_STREAM_END)\n\t\t\t\tcoder->next_finished = true;\n\t\t\telse if (ret != LZMA_OK || coder->temp.size == 0)\n\t\t\t\treturn ret;\n\t\t}\n\n\t\tif (coder->this_finished) {\n\t\t\tif (coder->temp.size != 0)\n\t\t\t\treturn LZMA_DATA_ERROR;\n\n\t\t\tif (coder->next_finished)\n\t\t\t\treturn LZMA_STREAM_END;\n\n\t\t\treturn LZMA_OK;\n\t\t}\n\n\t\tconst lzma_ret ret = decode_buffer(coder, coder->temp.buffer,\n\t\t\t\t&coder->temp.pos, coder->temp.size,\n\t\t\t\tout, out_pos, out_size);\n\n\t\tif (ret == LZMA_STREAM_END)\n\t\t\tcoder->this_finished = true;\n\t\telse if (ret != LZMA_OK)\n\t\t\treturn ret;\n\t\telse if (coder->next_finished && *out_pos < out_size)\n\t\t\treturn LZMA_DATA_ERROR;\n\t}\n\n\treturn LZMA_OK;\n}\n\n\nstatic void\nlz_decoder_end(void *coder_ptr, const lzma_allocator *allocator)\n{\n\tlzma_coder *coder = coder_ptr;\n\n\tlzma_next_end(&coder->next, allocator);\n\tlzma_free(coder->dict.buf, allocator);\n\n\tif (coder->lz.end != NULL)\n\t\tcoder->lz.end(coder->lz.coder, allocator);\n\telse\n\t\tlzma_free(coder->lz.coder, allocator);\n\n\tlzma_free(coder, allocator);\n\treturn;\n}\n\n\nextern lzma_ret\nlzma_lz_decoder_init(lzma_next_coder *next, const lzma_allocator *allocator,\n\t\tconst lzma_filter_info *filters,\n\t\tlzma_ret (*lz_init)(lzma_lz_decoder *lz,\n\t\t\tconst lzma_allocator *allocator, const void *options,\n\t\t\tlzma_lz_options *lz_options))\n{\n\t// Allocate the base structure if it isn't already allocated.\n\tlzma_coder *coder = next->coder;\n\tif (coder == NULL) {\n\t\tcoder = lzma_alloc(sizeof(lzma_coder), allocator);\n\t\tif (coder == NULL)\n\t\t\treturn LZMA_MEM_ERROR;\n\n\t\tnext->coder = coder;\n\t\tnext->code = &lz_decode;\n\t\tnext->end = &lz_decoder_end;\n\n\t\tcoder->dict.buf = NULL;\n\t\tcoder->dict.size = 0;\n\t\tcoder->lz = LZMA_LZ_DECODER_INIT;\n\t\tcoder->next = LZMA_NEXT_CODER_INIT;\n\t}\n\n\t// Allocate and initialize the LZ-based decoder. It will also give\n\t// us the dictionary size.\n\tlzma_lz_options lz_options;\n\treturn_if_error(lz_init(&coder->lz, allocator,\n\t\t\tfilters[0].options, &lz_options));\n\n\t// If the dictionary size is very small, increase it to 4096 bytes.\n\t// This is to prevent constant wrapping of the dictionary, which\n\t// would slow things down. The downside is that since we don't check\n\t// separately for the real dictionary size, we may happily accept\n\t// corrupt files.\n\tif (lz_options.dict_size < 4096)\n\t\tlz_options.dict_size = 4096;\n\n\t// Make dictionary size a multiple of 16. Some LZ-based decoders like\n\t// LZMA use the lowest bits lzma_dict.pos to know the alignment of the\n\t// data. Aligned buffer is also good when memcpying from the\n\t// dictionary to the output buffer, since applications are\n\t// recommended to give aligned buffers to liblzma.\n\t//\n\t// Avoid integer overflow.\n\tif (lz_options.dict_size > SIZE_MAX - 15)\n\t\treturn LZMA_MEM_ERROR;\n\n\tlz_options.dict_size = (lz_options.dict_size + 15) & ~((size_t)(15));\n\n\t// Allocate and initialize the dictionary.\n\tif (coder->dict.size != lz_options.dict_size) {\n\t\tlzma_free(coder->dict.buf, allocator);\n\t\tcoder->dict.buf\n\t\t\t\t= lzma_alloc(lz_options.dict_size, allocator);\n\t\tif (coder->dict.buf == NULL)\n\t\t\treturn LZMA_MEM_ERROR;\n\n\t\tcoder->dict.size = lz_options.dict_size;\n\t}\n\n\tlz_decoder_reset(next->coder);\n\n\t// Use the preset dictionary if it was given to us.\n\tif (lz_options.preset_dict != NULL\n\t\t\t&& lz_options.preset_dict_size > 0) {\n\t\t// If the preset dictionary is bigger than the actual\n\t\t// dictionary, copy only the tail.\n\t\tconst size_t copy_size = my_min(lz_options.preset_dict_size,\n\t\t\t\tlz_options.dict_size);\n\t\tconst size_t offset = lz_options.preset_dict_size - copy_size;\n\t\tmemcpy(coder->dict.buf, lz_options.preset_dict + offset,\n\t\t\t\tcopy_size);\n\t\tcoder->dict.pos = copy_size;\n\t\tcoder->dict.full = copy_size;\n\t}\n\n\t// Miscellaneous initializations\n\tcoder->next_finished = false;\n\tcoder->this_finished = false;\n\tcoder->temp.pos = 0;\n\tcoder->temp.size = 0;\n\n\t// Initialize the next filter in the chain, if any.\n\treturn lzma_next_filter_init(&coder->next, allocator, filters + 1);\n}\n\n\nextern uint64_t\nlzma_lz_decoder_memusage(size_t dictionary_size)\n{\n\treturn sizeof(lzma_coder) + (uint64_t)(dictionary_size);\n}\n\n\nextern void\nlzma_lz_decoder_uncompressed(void *coder_ptr, lzma_vli uncompressed_size)\n{\n\tlzma_coder *coder = coder_ptr;\n\tcoder->lz.set_uncompressed(coder->lz.coder, uncompressed_size);\n}\n"
  },
  {
    "path": "external/xz/liblzma/lz/lz_decoder.h",
    "content": "///////////////////////////////////////////////////////////////////////////////\n//\n/// \\file       lz_decoder.h\n/// \\brief      LZ out window\n///\n//  Authors:    Igor Pavlov\n//              Lasse Collin\n//\n//  This file has been put into the public domain.\n//  You can do whatever you want with this file.\n//\n///////////////////////////////////////////////////////////////////////////////\n\n#ifndef LZMA_LZ_DECODER_H\n#define LZMA_LZ_DECODER_H\n\n#include \"common.h\"\n\n\ntypedef struct {\n\t/// Pointer to the dictionary buffer. It can be an allocated buffer\n\t/// internal to liblzma, or it can a be a buffer given by the\n\t/// application when in single-call mode (not implemented yet).\n\tuint8_t *buf;\n\n\t/// Write position in dictionary. The next byte will be written to\n\t/// buf[pos].\n\tsize_t pos;\n\n\t/// Indicates how full the dictionary is. This is used by\n\t/// dict_is_distance_valid() to detect corrupt files that would\n\t/// read beyond the beginning of the dictionary.\n\tsize_t full;\n\n\t/// Write limit\n\tsize_t limit;\n\n\t/// Size of the dictionary\n\tsize_t size;\n\n\t/// True when dictionary should be reset before decoding more data.\n\tbool need_reset;\n\n} lzma_dict;\n\n\ntypedef struct {\n\tsize_t dict_size;\n\tconst uint8_t *preset_dict;\n\tsize_t preset_dict_size;\n} lzma_lz_options;\n\n\ntypedef struct {\n\t/// Data specific to the LZ-based decoder\n\tvoid *coder;\n\n\t/// Function to decode from in[] to *dict\n\tlzma_ret (*code)(void *coder,\n\t\t\tlzma_dict *restrict dict, const uint8_t *restrict in,\n\t\t\tsize_t *restrict in_pos, size_t in_size);\n\n\tvoid (*reset)(void *coder, const void *options);\n\n\t/// Set the uncompressed size\n\tvoid (*set_uncompressed)(void *coder, lzma_vli uncompressed_size);\n\n\t/// Free allocated resources\n\tvoid (*end)(void *coder, const lzma_allocator *allocator);\n\n} lzma_lz_decoder;\n\n\n#define LZMA_LZ_DECODER_INIT \\\n\t(lzma_lz_decoder){ \\\n\t\t.coder = NULL, \\\n\t\t.code = NULL, \\\n\t\t.reset = NULL, \\\n\t\t.set_uncompressed = NULL, \\\n\t\t.end = NULL, \\\n\t}\n\n\nextern lzma_ret lzma_lz_decoder_init(lzma_next_coder *next,\n\t\tconst lzma_allocator *allocator,\n\t\tconst lzma_filter_info *filters,\n\t\tlzma_ret (*lz_init)(lzma_lz_decoder *lz,\n\t\t\tconst lzma_allocator *allocator, const void *options,\n\t\t\tlzma_lz_options *lz_options));\n\nextern uint64_t lzma_lz_decoder_memusage(size_t dictionary_size);\n\nextern void lzma_lz_decoder_uncompressed(\n\t\tvoid *coder, lzma_vli uncompressed_size);\n\n\n//////////////////////\n// Inline functions //\n//////////////////////\n\n/// Get a byte from the history buffer.\nstatic inline uint8_t\ndict_get(const lzma_dict *const dict, const uint32_t distance)\n{\n\treturn dict->buf[dict->pos - distance - 1\n\t\t\t+ (distance < dict->pos ? 0 : dict->size)];\n}\n\n\n/// Test if dictionary is empty.\nstatic inline bool\ndict_is_empty(const lzma_dict *const dict)\n{\n\treturn dict->full == 0;\n}\n\n\n/// Validate the match distance\nstatic inline bool\ndict_is_distance_valid(const lzma_dict *const dict, const size_t distance)\n{\n\treturn dict->full > distance;\n}\n\n\n/// Repeat *len bytes at distance.\nstatic inline bool\ndict_repeat(lzma_dict *dict, uint32_t distance, uint32_t *len)\n{\n\t// Don't write past the end of the dictionary.\n\tconst size_t dict_avail = dict->limit - dict->pos;\n\tuint32_t left = my_min(dict_avail, *len);\n\t*len -= left;\n\n\t// Repeat a block of data from the history. Because memcpy() is faster\n\t// than copying byte by byte in a loop, the copying process gets split\n\t// into three cases.\n\tif (distance < left) {\n\t\t// Source and target areas overlap, thus we can't use\n\t\t// memcpy() nor even memmove() safely.\n\t\tdo {\n\t\t\tdict->buf[dict->pos] = dict_get(dict, distance);\n\t\t\t++dict->pos;\n\t\t} while (--left > 0);\n\n\t} else if (distance < dict->pos) {\n\t\t// The easiest and fastest case\n\t\tmemcpy(dict->buf + dict->pos,\n\t\t\t\tdict->buf + dict->pos - distance - 1,\n\t\t\t\tleft);\n\t\tdict->pos += left;\n\n\t} else {\n\t\t// The bigger the dictionary, the more rare this\n\t\t// case occurs. We need to \"wrap\" the dict, thus\n\t\t// we might need two memcpy() to copy all the data.\n\t\tassert(dict->full == dict->size);\n\t\tconst uint32_t copy_pos\n\t\t\t\t= dict->pos - distance - 1 + dict->size;\n\t\tuint32_t copy_size = dict->size - copy_pos;\n\n\t\tif (copy_size < left) {\n\t\t\tmemmove(dict->buf + dict->pos, dict->buf + copy_pos,\n\t\t\t\t\tcopy_size);\n\t\t\tdict->pos += copy_size;\n\t\t\tcopy_size = left - copy_size;\n\t\t\tmemcpy(dict->buf + dict->pos, dict->buf, copy_size);\n\t\t\tdict->pos += copy_size;\n\t\t} else {\n\t\t\tmemmove(dict->buf + dict->pos, dict->buf + copy_pos,\n\t\t\t\t\tleft);\n\t\t\tdict->pos += left;\n\t\t}\n\t}\n\n\t// Update how full the dictionary is.\n\tif (dict->full < dict->pos)\n\t\tdict->full = dict->pos;\n\n\treturn unlikely(*len != 0);\n}\n\n\n/// Puts one byte into the dictionary. Returns true if the dictionary was\n/// already full and the byte couldn't be added.\nstatic inline bool\ndict_put(lzma_dict *dict, uint8_t byte)\n{\n\tif (unlikely(dict->pos == dict->limit))\n\t\treturn true;\n\n\tdict->buf[dict->pos++] = byte;\n\n\tif (dict->pos > dict->full)\n\t\tdict->full = dict->pos;\n\n\treturn false;\n}\n\n\n/// Copies arbitrary amount of data into the dictionary.\nstatic inline void\ndict_write(lzma_dict *restrict dict, const uint8_t *restrict in,\n\t\tsize_t *restrict in_pos, size_t in_size,\n\t\tsize_t *restrict left)\n{\n\t// NOTE: If we are being given more data than the size of the\n\t// dictionary, it could be possible to optimize the LZ decoder\n\t// so that not everything needs to go through the dictionary.\n\t// This shouldn't be very common thing in practice though, and\n\t// the slowdown of one extra memcpy() isn't bad compared to how\n\t// much time it would have taken if the data were compressed.\n\n\tif (in_size - *in_pos > *left)\n\t\tin_size = *in_pos + *left;\n\n\t*left -= lzma_bufcpy(in, in_pos, in_size,\n\t\t\tdict->buf, &dict->pos, dict->limit);\n\n\tif (dict->pos > dict->full)\n\t\tdict->full = dict->pos;\n\n\treturn;\n}\n\n\nstatic inline void\ndict_reset(lzma_dict *dict)\n{\n\tdict->need_reset = true;\n\treturn;\n}\n\n#endif\n"
  },
  {
    "path": "external/xz/liblzma/lz/lz_encoder.c",
    "content": "///////////////////////////////////////////////////////////////////////////////\n//\n/// \\file       lz_encoder.c\n/// \\brief      LZ in window\n///\n//  Authors:    Igor Pavlov\n//              Lasse Collin\n//\n//  This file has been put into the public domain.\n//  You can do whatever you want with this file.\n//\n///////////////////////////////////////////////////////////////////////////////\n\n#include \"lz_encoder.h\"\n#include \"lz_encoder_hash.h\"\n\n// See lz_encoder_hash.h. This is a bit hackish but avoids making\n// endianness a conditional in makefiles.\n#if defined(WORDS_BIGENDIAN) && !defined(HAVE_SMALL)\n#\tinclude \"lz_encoder_hash_table.h\"\n#endif\n\n#include \"memcmplen.h\"\n\n\ntypedef struct {\n\t/// LZ-based encoder e.g. LZMA\n\tlzma_lz_encoder lz;\n\n\t/// History buffer and match finder\n\tlzma_mf mf;\n\n\t/// Next coder in the chain\n\tlzma_next_coder next;\n} lzma_coder;\n\n\n/// \\brief      Moves the data in the input window to free space for new data\n///\n/// mf->buffer is a sliding input window, which keeps mf->keep_size_before\n/// bytes of input history available all the time. Now and then we need to\n/// \"slide\" the buffer to make space for the new data to the end of the\n/// buffer. At the same time, data older than keep_size_before is dropped.\n///\nstatic void\nmove_window(lzma_mf *mf)\n{\n\t// Align the move to a multiple of 16 bytes. Some LZ-based encoders\n\t// like LZMA use the lowest bits of mf->read_pos to know the\n\t// alignment of the uncompressed data. We also get better speed\n\t// for memmove() with aligned buffers.\n\tassert(mf->read_pos > mf->keep_size_before);\n\tconst uint32_t move_offset\n\t\t= (mf->read_pos - mf->keep_size_before) & ~UINT32_C(15);\n\n\tassert(mf->write_pos > move_offset);\n\tconst size_t move_size = mf->write_pos - move_offset;\n\n\tassert(move_offset + move_size <= mf->size);\n\n\tmemmove(mf->buffer, mf->buffer + move_offset, move_size);\n\n\tmf->offset += move_offset;\n\tmf->read_pos -= move_offset;\n\tmf->read_limit -= move_offset;\n\tmf->write_pos -= move_offset;\n\n\treturn;\n}\n\n\n/// \\brief      Tries to fill the input window (mf->buffer)\n///\n/// If we are the last encoder in the chain, our input data is in in[].\n/// Otherwise we call the next filter in the chain to process in[] and\n/// write its output to mf->buffer.\n///\n/// This function must not be called once it has returned LZMA_STREAM_END.\n///\nstatic lzma_ret\nfill_window(lzma_coder *coder, const lzma_allocator *allocator,\n\t\tconst uint8_t *in, size_t *in_pos, size_t in_size,\n\t\tlzma_action action)\n{\n\tassert(coder->mf.read_pos <= coder->mf.write_pos);\n\n\t// Move the sliding window if needed.\n\tif (coder->mf.read_pos >= coder->mf.size - coder->mf.keep_size_after)\n\t\tmove_window(&coder->mf);\n\n\t// Maybe this is ugly, but lzma_mf uses uint32_t for most things\n\t// (which I find cleanest), but we need size_t here when filling\n\t// the history window.\n\tsize_t write_pos = coder->mf.write_pos;\n\tlzma_ret ret;\n\tif (coder->next.code == NULL) {\n\t\t// Not using a filter, simply memcpy() as much as possible.\n\t\tlzma_bufcpy(in, in_pos, in_size, coder->mf.buffer,\n\t\t\t\t&write_pos, coder->mf.size);\n\n\t\tret = action != LZMA_RUN && *in_pos == in_size\n\t\t\t\t? LZMA_STREAM_END : LZMA_OK;\n\n\t} else {\n\t\tret = coder->next.code(coder->next.coder, allocator,\n\t\t\t\tin, in_pos, in_size,\n\t\t\t\tcoder->mf.buffer, &write_pos,\n\t\t\t\tcoder->mf.size, action);\n\t}\n\n\tcoder->mf.write_pos = write_pos;\n\n\t// Silence Valgrind. lzma_memcmplen() can read extra bytes\n\t// and Valgrind will give warnings if those bytes are uninitialized\n\t// because Valgrind cannot see that the values of the uninitialized\n\t// bytes are eventually ignored.\n\tmemzero(coder->mf.buffer + write_pos, LZMA_MEMCMPLEN_EXTRA);\n\n\t// If end of stream has been reached or flushing completed, we allow\n\t// the encoder to process all the input (that is, read_pos is allowed\n\t// to reach write_pos). Otherwise we keep keep_size_after bytes\n\t// available as prebuffer.\n\tif (ret == LZMA_STREAM_END) {\n\t\tassert(*in_pos == in_size);\n\t\tret = LZMA_OK;\n\t\tcoder->mf.action = action;\n\t\tcoder->mf.read_limit = coder->mf.write_pos;\n\n\t} else if (coder->mf.write_pos > coder->mf.keep_size_after) {\n\t\t// This needs to be done conditionally, because if we got\n\t\t// only little new input, there may be too little input\n\t\t// to do any encoding yet.\n\t\tcoder->mf.read_limit = coder->mf.write_pos\n\t\t\t\t- coder->mf.keep_size_after;\n\t}\n\n\t// Restart the match finder after finished LZMA_SYNC_FLUSH.\n\tif (coder->mf.pending > 0\n\t\t\t&& coder->mf.read_pos < coder->mf.read_limit) {\n\t\t// Match finder may update coder->pending and expects it to\n\t\t// start from zero, so use a temporary variable.\n\t\tconst uint32_t pending = coder->mf.pending;\n\t\tcoder->mf.pending = 0;\n\n\t\t// Rewind read_pos so that the match finder can hash\n\t\t// the pending bytes.\n\t\tassert(coder->mf.read_pos >= pending);\n\t\tcoder->mf.read_pos -= pending;\n\n\t\t// Call the skip function directly instead of using\n\t\t// mf_skip(), since we don't want to touch mf->read_ahead.\n\t\tcoder->mf.skip(&coder->mf, pending);\n\t}\n\n\treturn ret;\n}\n\n\nstatic lzma_ret\nlz_encode(void *coder_ptr, const lzma_allocator *allocator,\n\t\tconst uint8_t *restrict in, size_t *restrict in_pos,\n\t\tsize_t in_size,\n\t\tuint8_t *restrict out, size_t *restrict out_pos,\n\t\tsize_t out_size, lzma_action action)\n{\n\tlzma_coder *coder = coder_ptr;\n\n\twhile (*out_pos < out_size\n\t\t\t&& (*in_pos < in_size || action != LZMA_RUN)) {\n\t\t// Read more data to coder->mf.buffer if needed.\n\t\tif (coder->mf.action == LZMA_RUN && coder->mf.read_pos\n\t\t\t\t>= coder->mf.read_limit)\n\t\t\treturn_if_error(fill_window(coder, allocator,\n\t\t\t\t\tin, in_pos, in_size, action));\n\n\t\t// Encode\n\t\tconst lzma_ret ret = coder->lz.code(coder->lz.coder,\n\t\t\t\t&coder->mf, out, out_pos, out_size);\n\t\tif (ret != LZMA_OK) {\n\t\t\t// Setting this to LZMA_RUN for cases when we are\n\t\t\t// flushing. It doesn't matter when finishing or if\n\t\t\t// an error occurred.\n\t\t\tcoder->mf.action = LZMA_RUN;\n\t\t\treturn ret;\n\t\t}\n\t}\n\n\treturn LZMA_OK;\n}\n\n\nstatic bool\nlz_encoder_prepare(lzma_mf *mf, const lzma_allocator *allocator,\n\t\tconst lzma_lz_options *lz_options)\n{\n\t// For now, the dictionary size is limited to 1.5 GiB. This may grow\n\t// in the future if needed, but it needs a little more work than just\n\t// changing this check.\n\tif (lz_options->dict_size < LZMA_DICT_SIZE_MIN\n\t\t\t|| lz_options->dict_size\n\t\t\t\t> (UINT32_C(1) << 30) + (UINT32_C(1) << 29)\n\t\t\t|| lz_options->nice_len > lz_options->match_len_max)\n\t\treturn true;\n\n\tmf->keep_size_before = lz_options->before_size + lz_options->dict_size;\n\n\tmf->keep_size_after = lz_options->after_size\n\t\t\t+ lz_options->match_len_max;\n\n\t// To avoid constant memmove()s, allocate some extra space. Since\n\t// memmove()s become more expensive when the size of the buffer\n\t// increases, we reserve more space when a large dictionary is\n\t// used to make the memmove() calls rarer.\n\t//\n\t// This works with dictionaries up to about 3 GiB. If bigger\n\t// dictionary is wanted, some extra work is needed:\n\t//   - Several variables in lzma_mf have to be changed from uint32_t\n\t//     to size_t.\n\t//   - Memory usage calculation needs something too, e.g. use uint64_t\n\t//     for mf->size.\n\tuint32_t reserve = lz_options->dict_size / 2;\n\tif (reserve > (UINT32_C(1) << 30))\n\t\treserve /= 2;\n\n\treserve += (lz_options->before_size + lz_options->match_len_max\n\t\t\t+ lz_options->after_size) / 2 + (UINT32_C(1) << 19);\n\n\tconst uint32_t old_size = mf->size;\n\tmf->size = mf->keep_size_before + reserve + mf->keep_size_after;\n\n\t// Deallocate the old history buffer if it exists but has different\n\t// size than what is needed now.\n\tif (mf->buffer != NULL && old_size != mf->size) {\n\t\tlzma_free(mf->buffer, allocator);\n\t\tmf->buffer = NULL;\n\t}\n\n\t// Match finder options\n\tmf->match_len_max = lz_options->match_len_max;\n\tmf->nice_len = lz_options->nice_len;\n\n\t// cyclic_size has to stay smaller than 2 Gi. Note that this doesn't\n\t// mean limiting dictionary size to less than 2 GiB. With a match\n\t// finder that uses multibyte resolution (hashes start at e.g. every\n\t// fourth byte), cyclic_size would stay below 2 Gi even when\n\t// dictionary size is greater than 2 GiB.\n\t//\n\t// It would be possible to allow cyclic_size >= 2 Gi, but then we\n\t// would need to be careful to use 64-bit types in various places\n\t// (size_t could do since we would need bigger than 32-bit address\n\t// space anyway). It would also require either zeroing a multigigabyte\n\t// buffer at initialization (waste of time and RAM) or allow\n\t// normalization in lz_encoder_mf.c to access uninitialized\n\t// memory to keep the code simpler. The current way is simple and\n\t// still allows pretty big dictionaries, so I don't expect these\n\t// limits to change.\n\tmf->cyclic_size = lz_options->dict_size + 1;\n\n\t// Validate the match finder ID and setup the function pointers.\n\tswitch (lz_options->match_finder) {\n#ifdef HAVE_MF_HC3\n\tcase LZMA_MF_HC3:\n\t\tmf->find = &lzma_mf_hc3_find;\n\t\tmf->skip = &lzma_mf_hc3_skip;\n\t\tbreak;\n#endif\n#ifdef HAVE_MF_HC4\n\tcase LZMA_MF_HC4:\n\t\tmf->find = &lzma_mf_hc4_find;\n\t\tmf->skip = &lzma_mf_hc4_skip;\n\t\tbreak;\n#endif\n#ifdef HAVE_MF_BT2\n\tcase LZMA_MF_BT2:\n\t\tmf->find = &lzma_mf_bt2_find;\n\t\tmf->skip = &lzma_mf_bt2_skip;\n\t\tbreak;\n#endif\n#ifdef HAVE_MF_BT3\n\tcase LZMA_MF_BT3:\n\t\tmf->find = &lzma_mf_bt3_find;\n\t\tmf->skip = &lzma_mf_bt3_skip;\n\t\tbreak;\n#endif\n#ifdef HAVE_MF_BT4\n\tcase LZMA_MF_BT4:\n\t\tmf->find = &lzma_mf_bt4_find;\n\t\tmf->skip = &lzma_mf_bt4_skip;\n\t\tbreak;\n#endif\n\n\tdefault:\n\t\treturn true;\n\t}\n\n\t// Calculate the sizes of mf->hash and mf->son and check that\n\t// nice_len is big enough for the selected match finder.\n\tconst uint32_t hash_bytes = lz_options->match_finder & 0x0F;\n\tif (hash_bytes > mf->nice_len)\n\t\treturn true;\n\n\tconst bool is_bt = (lz_options->match_finder & 0x10) != 0;\n\tuint32_t hs;\n\n\tif (hash_bytes == 2) {\n\t\ths = 0xFFFF;\n\t} else {\n\t\t// Round dictionary size up to the next 2^n - 1 so it can\n\t\t// be used as a hash mask.\n\t\ths = lz_options->dict_size - 1;\n\t\ths |= hs >> 1;\n\t\ths |= hs >> 2;\n\t\ths |= hs >> 4;\n\t\ths |= hs >> 8;\n\t\ths >>= 1;\n\t\ths |= 0xFFFF;\n\n\t\tif (hs > (UINT32_C(1) << 24)) {\n\t\t\tif (hash_bytes == 3)\n\t\t\t\ths = (UINT32_C(1) << 24) - 1;\n\t\t\telse\n\t\t\t\ths >>= 1;\n\t\t}\n\t}\n\n\tmf->hash_mask = hs;\n\n\t++hs;\n\tif (hash_bytes > 2)\n\t\ths += HASH_2_SIZE;\n\tif (hash_bytes > 3)\n\t\ths += HASH_3_SIZE;\n/*\n\tNo match finder uses this at the moment.\n\tif (mf->hash_bytes > 4)\n\t\ths += HASH_4_SIZE;\n*/\n\n\tconst uint32_t old_hash_count = mf->hash_count;\n\tconst uint32_t old_sons_count = mf->sons_count;\n\tmf->hash_count = hs;\n\tmf->sons_count = mf->cyclic_size;\n\tif (is_bt)\n\t\tmf->sons_count *= 2;\n\n\t// Deallocate the old hash array if it exists and has different size\n\t// than what is needed now.\n\tif (old_hash_count != mf->hash_count\n\t\t\t|| old_sons_count != mf->sons_count) {\n\t\tlzma_free(mf->hash, allocator);\n\t\tmf->hash = NULL;\n\n\t\tlzma_free(mf->son, allocator);\n\t\tmf->son = NULL;\n\t}\n\n\t// Maximum number of match finder cycles\n\tmf->depth = lz_options->depth;\n\tif (mf->depth == 0) {\n\t\tif (is_bt)\n\t\t\tmf->depth = 16 + mf->nice_len / 2;\n\t\telse\n\t\t\tmf->depth = 4 + mf->nice_len / 4;\n\t}\n\n\treturn false;\n}\n\n\nstatic bool\nlz_encoder_init(lzma_mf *mf, const lzma_allocator *allocator,\n\t\tconst lzma_lz_options *lz_options)\n{\n\t// Allocate the history buffer.\n\tif (mf->buffer == NULL) {\n\t\t// lzma_memcmplen() is used for the dictionary buffer\n\t\t// so we need to allocate a few extra bytes to prevent\n\t\t// it from reading past the end of the buffer.\n\t\tmf->buffer = lzma_alloc(mf->size + LZMA_MEMCMPLEN_EXTRA,\n\t\t\t\tallocator);\n\t\tif (mf->buffer == NULL)\n\t\t\treturn true;\n\n\t\t// Keep Valgrind happy with lzma_memcmplen() and initialize\n\t\t// the extra bytes whose value may get read but which will\n\t\t// effectively get ignored.\n\t\tmemzero(mf->buffer + mf->size, LZMA_MEMCMPLEN_EXTRA);\n\t}\n\n\t// Use cyclic_size as initial mf->offset. This allows\n\t// avoiding a few branches in the match finders. The downside is\n\t// that match finder needs to be normalized more often, which may\n\t// hurt performance with huge dictionaries.\n\tmf->offset = mf->cyclic_size;\n\tmf->read_pos = 0;\n\tmf->read_ahead = 0;\n\tmf->read_limit = 0;\n\tmf->write_pos = 0;\n\tmf->pending = 0;\n\n#if UINT32_MAX >= SIZE_MAX / 4\n\t// Check for integer overflow. (Huge dictionaries are not\n\t// possible on 32-bit CPU.)\n\tif (mf->hash_count > SIZE_MAX / sizeof(uint32_t)\n\t\t\t|| mf->sons_count > SIZE_MAX / sizeof(uint32_t))\n\t\treturn true;\n#endif\n\n\t// Allocate and initialize the hash table. Since EMPTY_HASH_VALUE\n\t// is zero, we can use lzma_alloc_zero() or memzero() for mf->hash.\n\t//\n\t// We don't need to initialize mf->son, but not doing that may\n\t// make Valgrind complain in normalization (see normalize() in\n\t// lz_encoder_mf.c). Skipping the initialization is *very* good\n\t// when big dictionary is used but only small amount of data gets\n\t// actually compressed: most of the mf->son won't get actually\n\t// allocated by the kernel, so we avoid wasting RAM and improve\n\t// initialization speed a lot.\n\tif (mf->hash == NULL) {\n\t\tmf->hash = lzma_alloc_zero(mf->hash_count * sizeof(uint32_t),\n\t\t\t\tallocator);\n\t\tmf->son = lzma_alloc(mf->sons_count * sizeof(uint32_t),\n\t\t\t\tallocator);\n\n\t\tif (mf->hash == NULL || mf->son == NULL) {\n\t\t\tlzma_free(mf->hash, allocator);\n\t\t\tmf->hash = NULL;\n\n\t\t\tlzma_free(mf->son, allocator);\n\t\t\tmf->son = NULL;\n\n\t\t\treturn true;\n\t\t}\n\t} else {\n/*\n\t\tfor (uint32_t i = 0; i < mf->hash_count; ++i)\n\t\t\tmf->hash[i] = EMPTY_HASH_VALUE;\n*/\n\t\tmemzero(mf->hash, mf->hash_count * sizeof(uint32_t));\n\t}\n\n\tmf->cyclic_pos = 0;\n\n\t// Handle preset dictionary.\n\tif (lz_options->preset_dict != NULL\n\t\t\t&& lz_options->preset_dict_size > 0) {\n\t\t// If the preset dictionary is bigger than the actual\n\t\t// dictionary, use only the tail.\n\t\tmf->write_pos = my_min(lz_options->preset_dict_size, mf->size);\n\t\tmemcpy(mf->buffer, lz_options->preset_dict\n\t\t\t\t+ lz_options->preset_dict_size - mf->write_pos,\n\t\t\t\tmf->write_pos);\n\t\tmf->action = LZMA_SYNC_FLUSH;\n\t\tmf->skip(mf, mf->write_pos);\n\t}\n\n\tmf->action = LZMA_RUN;\n\n\treturn false;\n}\n\n\nextern uint64_t\nlzma_lz_encoder_memusage(const lzma_lz_options *lz_options)\n{\n\t// Old buffers must not exist when calling lz_encoder_prepare().\n\tlzma_mf mf = {\n\t\t.buffer = NULL,\n\t\t.hash = NULL,\n\t\t.son = NULL,\n\t\t.hash_count = 0,\n\t\t.sons_count = 0,\n\t};\n\n\t// Setup the size information into mf.\n\tif (lz_encoder_prepare(&mf, NULL, lz_options))\n\t\treturn UINT64_MAX;\n\n\t// Calculate the memory usage.\n\treturn ((uint64_t)(mf.hash_count) + mf.sons_count) * sizeof(uint32_t)\n\t\t\t+ mf.size + sizeof(lzma_coder);\n}\n\n\nstatic void\nlz_encoder_end(void *coder_ptr, const lzma_allocator *allocator)\n{\n\tlzma_coder *coder = coder_ptr;\n\n\tlzma_next_end(&coder->next, allocator);\n\n\tlzma_free(coder->mf.son, allocator);\n\tlzma_free(coder->mf.hash, allocator);\n\tlzma_free(coder->mf.buffer, allocator);\n\n\tif (coder->lz.end != NULL)\n\t\tcoder->lz.end(coder->lz.coder, allocator);\n\telse\n\t\tlzma_free(coder->lz.coder, allocator);\n\n\tlzma_free(coder, allocator);\n\treturn;\n}\n\n\nstatic lzma_ret\nlz_encoder_update(void *coder_ptr, const lzma_allocator *allocator,\n\t\tconst lzma_filter *filters_null lzma_attribute((__unused__)),\n\t\tconst lzma_filter *reversed_filters)\n{\n\tlzma_coder *coder = coder_ptr;\n\n\tif (coder->lz.options_update == NULL)\n\t\treturn LZMA_PROG_ERROR;\n\n\treturn_if_error(coder->lz.options_update(\n\t\t\tcoder->lz.coder, reversed_filters));\n\n\treturn lzma_next_filter_update(\n\t\t\t&coder->next, allocator, reversed_filters + 1);\n}\n\n\nextern lzma_ret\nlzma_lz_encoder_init(lzma_next_coder *next, const lzma_allocator *allocator,\n\t\tconst lzma_filter_info *filters,\n\t\tlzma_ret (*lz_init)(lzma_lz_encoder *lz,\n\t\t\tconst lzma_allocator *allocator, const void *options,\n\t\t\tlzma_lz_options *lz_options))\n{\n#ifdef HAVE_SMALL\n\t// We need that the CRC32 table has been initialized.\n\tlzma_crc32_init();\n#endif\n\n\t// Allocate and initialize the base data structure.\n\tlzma_coder *coder = next->coder;\n\tif (coder == NULL) {\n\t\tcoder = lzma_alloc(sizeof(lzma_coder), allocator);\n\t\tif (coder == NULL)\n\t\t\treturn LZMA_MEM_ERROR;\n\n\t\tnext->coder = coder;\n\t\tnext->code = &lz_encode;\n\t\tnext->end = &lz_encoder_end;\n\t\tnext->update = &lz_encoder_update;\n\n\t\tcoder->lz.coder = NULL;\n\t\tcoder->lz.code = NULL;\n\t\tcoder->lz.end = NULL;\n\n\t\t// mf.size is initialized to silence Valgrind\n\t\t// when used on optimized binaries (GCC may reorder\n\t\t// code in a way that Valgrind gets unhappy).\n\t\tcoder->mf.buffer = NULL;\n\t\tcoder->mf.size = 0;\n\t\tcoder->mf.hash = NULL;\n\t\tcoder->mf.son = NULL;\n\t\tcoder->mf.hash_count = 0;\n\t\tcoder->mf.sons_count = 0;\n\n\t\tcoder->next = LZMA_NEXT_CODER_INIT;\n\t}\n\n\t// Initialize the LZ-based encoder.\n\tlzma_lz_options lz_options;\n\treturn_if_error(lz_init(&coder->lz, allocator,\n\t\t\tfilters[0].options, &lz_options));\n\n\t// Setup the size information into coder->mf and deallocate\n\t// old buffers if they have wrong size.\n\tif (lz_encoder_prepare(&coder->mf, allocator, &lz_options))\n\t\treturn LZMA_OPTIONS_ERROR;\n\n\t// Allocate new buffers if needed, and do the rest of\n\t// the initialization.\n\tif (lz_encoder_init(&coder->mf, allocator, &lz_options))\n\t\treturn LZMA_MEM_ERROR;\n\n\t// Initialize the next filter in the chain, if any.\n\treturn lzma_next_filter_init(&coder->next, allocator, filters + 1);\n}\n\n\nextern LZMA_API(lzma_bool)\nlzma_mf_is_supported(lzma_match_finder mf)\n{\n\tbool ret = false;\n\n#ifdef HAVE_MF_HC3\n\tif (mf == LZMA_MF_HC3)\n\t\tret = true;\n#endif\n\n#ifdef HAVE_MF_HC4\n\tif (mf == LZMA_MF_HC4)\n\t\tret = true;\n#endif\n\n#ifdef HAVE_MF_BT2\n\tif (mf == LZMA_MF_BT2)\n\t\tret = true;\n#endif\n\n#ifdef HAVE_MF_BT3\n\tif (mf == LZMA_MF_BT3)\n\t\tret = true;\n#endif\n\n#ifdef HAVE_MF_BT4\n\tif (mf == LZMA_MF_BT4)\n\t\tret = true;\n#endif\n\n\treturn ret;\n}\n"
  },
  {
    "path": "external/xz/liblzma/lz/lz_encoder.h",
    "content": "///////////////////////////////////////////////////////////////////////////////\n//\n/// \\file       lz_encoder.h\n/// \\brief      LZ in window and match finder API\n///\n//  Authors:    Igor Pavlov\n//              Lasse Collin\n//\n//  This file has been put into the public domain.\n//  You can do whatever you want with this file.\n//\n///////////////////////////////////////////////////////////////////////////////\n\n#ifndef LZMA_LZ_ENCODER_H\n#define LZMA_LZ_ENCODER_H\n\n#include \"common.h\"\n\n\n/// A table of these is used by the LZ-based encoder to hold\n/// the length-distance pairs found by the match finder.\ntypedef struct {\n\tuint32_t len;\n\tuint32_t dist;\n} lzma_match;\n\n\ntypedef struct lzma_mf_s lzma_mf;\nstruct lzma_mf_s {\n\t///////////////\n\t// In Window //\n\t///////////////\n\n\t/// Pointer to buffer with data to be compressed\n\tuint8_t *buffer;\n\n\t/// Total size of the allocated buffer (that is, including all\n\t/// the extra space)\n\tuint32_t size;\n\n\t/// Number of bytes that must be kept available in our input history.\n\t/// That is, once keep_size_before bytes have been processed,\n\t/// buffer[read_pos - keep_size_before] is the oldest byte that\n\t/// must be available for reading.\n\tuint32_t keep_size_before;\n\n\t/// Number of bytes that must be kept in buffer after read_pos.\n\t/// That is, read_pos <= write_pos - keep_size_after as long as\n\t/// action is LZMA_RUN; when action != LZMA_RUN, read_pos is allowed\n\t/// to reach write_pos so that the last bytes get encoded too.\n\tuint32_t keep_size_after;\n\n\t/// Match finders store locations of matches using 32-bit integers.\n\t/// To avoid adjusting several megabytes of integers every time the\n\t/// input window is moved with move_window, we only adjust the\n\t/// offset of the buffer. Thus, buffer[value_in_hash_table - offset]\n\t/// is the byte pointed by value_in_hash_table.\n\tuint32_t offset;\n\n\t/// buffer[read_pos] is the next byte to run through the match\n\t/// finder. This is incremented in the match finder once the byte\n\t/// has been processed.\n\tuint32_t read_pos;\n\n\t/// Number of bytes that have been ran through the match finder, but\n\t/// which haven't been encoded by the LZ-based encoder yet.\n\tuint32_t read_ahead;\n\n\t/// As long as read_pos is less than read_limit, there is enough\n\t/// input available in buffer for at least one encoding loop.\n\t///\n\t/// Because of the stateful API, read_limit may and will get greater\n\t/// than read_pos quite often. This is taken into account when\n\t/// calculating the value for keep_size_after.\n\tuint32_t read_limit;\n\n\t/// buffer[write_pos] is the first byte that doesn't contain valid\n\t/// uncompressed data; that is, the next input byte will be copied\n\t/// to buffer[write_pos].\n\tuint32_t write_pos;\n\n\t/// Number of bytes not hashed before read_pos. This is needed to\n\t/// restart the match finder after LZMA_SYNC_FLUSH.\n\tuint32_t pending;\n\n\t//////////////////\n\t// Match Finder //\n\t//////////////////\n\n\t/// Find matches. Returns the number of distance-length pairs written\n\t/// to the matches array. This is called only via lzma_mf_find().\n\tuint32_t (*find)(lzma_mf *mf, lzma_match *matches);\n\n\t/// Skips num bytes. This is like find() but doesn't make the\n\t/// distance-length pairs available, thus being a little faster.\n\t/// This is called only via mf_skip().\n\tvoid (*skip)(lzma_mf *mf, uint32_t num);\n\n\tuint32_t *hash;\n\tuint32_t *son;\n\tuint32_t cyclic_pos;\n\tuint32_t cyclic_size; // Must be dictionary size + 1.\n\tuint32_t hash_mask;\n\n\t/// Maximum number of loops in the match finder\n\tuint32_t depth;\n\n\t/// Maximum length of a match that the match finder will try to find.\n\tuint32_t nice_len;\n\n\t/// Maximum length of a match supported by the LZ-based encoder.\n\t/// If the longest match found by the match finder is nice_len,\n\t/// mf_find() tries to expand it up to match_len_max bytes.\n\tuint32_t match_len_max;\n\n\t/// When running out of input, binary tree match finders need to know\n\t/// if it is due to flushing or finishing. The action is used also\n\t/// by the LZ-based encoders themselves.\n\tlzma_action action;\n\n\t/// Number of elements in hash[]\n\tuint32_t hash_count;\n\n\t/// Number of elements in son[]\n\tuint32_t sons_count;\n};\n\n\ntypedef struct {\n\t/// Extra amount of data to keep available before the \"actual\"\n\t/// dictionary.\n\tsize_t before_size;\n\n\t/// Size of the history buffer\n\tsize_t dict_size;\n\n\t/// Extra amount of data to keep available after the \"actual\"\n\t/// dictionary.\n\tsize_t after_size;\n\n\t/// Maximum length of a match that the LZ-based encoder can accept.\n\t/// This is used to extend matches of length nice_len to the\n\t/// maximum possible length.\n\tsize_t match_len_max;\n\n\t/// Match finder will search matches up to this length.\n\t/// This must be less than or equal to match_len_max.\n\tsize_t nice_len;\n\n\t/// Type of the match finder to use\n\tlzma_match_finder match_finder;\n\n\t/// Maximum search depth\n\tuint32_t depth;\n\n\t/// TODO: Comment\n\tconst uint8_t *preset_dict;\n\n\tuint32_t preset_dict_size;\n\n} lzma_lz_options;\n\n\n// The total usable buffer space at any moment outside the match finder:\n// before_size + dict_size + after_size + match_len_max\n//\n// In reality, there's some extra space allocated to prevent the number of\n// memmove() calls reasonable. The bigger the dict_size is, the bigger\n// this extra buffer will be since with bigger dictionaries memmove() would\n// also take longer.\n//\n// A single encoder loop in the LZ-based encoder may call the match finder\n// (mf_find() or mf_skip()) at most after_size times. In other words,\n// a single encoder loop may increment lzma_mf.read_pos at most after_size\n// times. Since matches are looked up to\n// lzma_mf.buffer[lzma_mf.read_pos + match_len_max - 1], the total\n// amount of extra buffer needed after dict_size becomes\n// after_size + match_len_max.\n//\n// before_size has two uses. The first one is to keep literals available\n// in cases when the LZ-based encoder has made some read ahead.\n// TODO: Maybe this could be changed by making the LZ-based encoders to\n// store the actual literals as they do with length-distance pairs.\n//\n// Algorithms such as LZMA2 first try to compress a chunk, and then check\n// if the encoded result is smaller than the uncompressed one. If the chunk\n// was uncompressible, it is better to store it in uncompressed form in\n// the output stream. To do this, the whole uncompressed chunk has to be\n// still available in the history buffer. before_size achieves that.\n\n\ntypedef struct {\n\t/// Data specific to the LZ-based encoder\n\tvoid *coder;\n\n\t/// Function to encode from *dict to out[]\n\tlzma_ret (*code)(void *coder,\n\t\t\tlzma_mf *restrict mf, uint8_t *restrict out,\n\t\t\tsize_t *restrict out_pos, size_t out_size);\n\n\t/// Free allocated resources\n\tvoid (*end)(void *coder, const lzma_allocator *allocator);\n\n\t/// Update the options in the middle of the encoding.\n\tlzma_ret (*options_update)(void *coder, const lzma_filter *filter);\n\n} lzma_lz_encoder;\n\n\n// Basic steps:\n//  1. Input gets copied into the dictionary.\n//  2. Data in dictionary gets run through the match finder byte by byte.\n//  3. The literals and matches are encoded using e.g. LZMA.\n//\n// The bytes that have been ran through the match finder, but not encoded yet,\n// are called `read ahead'.\n\n\n/// Get pointer to the first byte not ran through the match finder\nstatic inline const uint8_t *\nmf_ptr(const lzma_mf *mf)\n{\n\treturn mf->buffer + mf->read_pos;\n}\n\n\n/// Get the number of bytes that haven't been ran through the match finder yet.\nstatic inline uint32_t\nmf_avail(const lzma_mf *mf)\n{\n\treturn mf->write_pos - mf->read_pos;\n}\n\n\n/// Get the number of bytes that haven't been encoded yet (some of these\n/// bytes may have been ran through the match finder though).\nstatic inline uint32_t\nmf_unencoded(const lzma_mf *mf)\n{\n\treturn mf->write_pos - mf->read_pos + mf->read_ahead;\n}\n\n\n/// Calculate the absolute offset from the beginning of the most recent\n/// dictionary reset. Only the lowest four bits are important, so there's no\n/// problem that we don't know the 64-bit size of the data encoded so far.\n///\n/// NOTE: When moving the input window, we need to do it so that the lowest\n/// bits of dict->read_pos are not modified to keep this macro working\n/// as intended.\nstatic inline uint32_t\nmf_position(const lzma_mf *mf)\n{\n\treturn mf->read_pos - mf->read_ahead;\n}\n\n\n/// Since everything else begins with mf_, use it also for lzma_mf_find().\n#define mf_find lzma_mf_find\n\n\n/// Skip the given number of bytes. This is used when a good match was found.\n/// For example, if mf_find() finds a match of 200 bytes long, the first byte\n/// of that match was already consumed by mf_find(), and the rest 199 bytes\n/// have to be skipped with mf_skip(mf, 199).\nstatic inline void\nmf_skip(lzma_mf *mf, uint32_t amount)\n{\n\tif (amount != 0) {\n\t\tmf->skip(mf, amount);\n\t\tmf->read_ahead += amount;\n\t}\n}\n\n\n/// Copies at most *left number of bytes from the history buffer\n/// to out[]. This is needed by LZMA2 to encode uncompressed chunks.\nstatic inline void\nmf_read(lzma_mf *mf, uint8_t *out, size_t *out_pos, size_t out_size,\n\t\tsize_t *left)\n{\n\tconst size_t out_avail = out_size - *out_pos;\n\tconst size_t copy_size = my_min(out_avail, *left);\n\n\tassert(mf->read_ahead == 0);\n\tassert(mf->read_pos >= *left);\n\n\tmemcpy(out + *out_pos, mf->buffer + mf->read_pos - *left,\n\t\t\tcopy_size);\n\n\t*out_pos += copy_size;\n\t*left -= copy_size;\n\treturn;\n}\n\n\nextern lzma_ret lzma_lz_encoder_init(\n\t\tlzma_next_coder *next, const lzma_allocator *allocator,\n\t\tconst lzma_filter_info *filters,\n\t\tlzma_ret (*lz_init)(lzma_lz_encoder *lz,\n\t\t\tconst lzma_allocator *allocator, const void *options,\n\t\t\tlzma_lz_options *lz_options));\n\n\nextern uint64_t lzma_lz_encoder_memusage(const lzma_lz_options *lz_options);\n\n\n// These are only for LZ encoder's internal use.\nextern uint32_t lzma_mf_find(\n\t\tlzma_mf *mf, uint32_t *count, lzma_match *matches);\n\nextern uint32_t lzma_mf_hc3_find(lzma_mf *dict, lzma_match *matches);\nextern void lzma_mf_hc3_skip(lzma_mf *dict, uint32_t amount);\n\nextern uint32_t lzma_mf_hc4_find(lzma_mf *dict, lzma_match *matches);\nextern void lzma_mf_hc4_skip(lzma_mf *dict, uint32_t amount);\n\nextern uint32_t lzma_mf_bt2_find(lzma_mf *dict, lzma_match *matches);\nextern void lzma_mf_bt2_skip(lzma_mf *dict, uint32_t amount);\n\nextern uint32_t lzma_mf_bt3_find(lzma_mf *dict, lzma_match *matches);\nextern void lzma_mf_bt3_skip(lzma_mf *dict, uint32_t amount);\n\nextern uint32_t lzma_mf_bt4_find(lzma_mf *dict, lzma_match *matches);\nextern void lzma_mf_bt4_skip(lzma_mf *dict, uint32_t amount);\n\n#endif\n"
  },
  {
    "path": "external/xz/liblzma/lz/lz_encoder_hash.h",
    "content": "///////////////////////////////////////////////////////////////////////////////\n//\n/// \\file       lz_encoder_hash.h\n/// \\brief      Hash macros for match finders\n//\n//  Author:     Igor Pavlov\n//\n//  This file has been put into the public domain.\n//  You can do whatever you want with this file.\n//\n///////////////////////////////////////////////////////////////////////////////\n\n#ifndef LZMA_LZ_ENCODER_HASH_H\n#define LZMA_LZ_ENCODER_HASH_H\n\n#if defined(WORDS_BIGENDIAN) && !defined(HAVE_SMALL)\n\t// This is to make liblzma produce the same output on big endian\n\t// systems that it does on little endian systems. lz_encoder.c\n\t// takes care of including the actual table.\n\textern const uint32_t lzma_lz_hash_table[256];\n#\tdefine hash_table lzma_lz_hash_table\n#else\n#\tinclude \"check.h\"\n#\tdefine hash_table lzma_crc32_table[0]\n#endif\n\n#define HASH_2_SIZE (UINT32_C(1) << 10)\n#define HASH_3_SIZE (UINT32_C(1) << 16)\n#define HASH_4_SIZE (UINT32_C(1) << 20)\n\n#define HASH_2_MASK (HASH_2_SIZE - 1)\n#define HASH_3_MASK (HASH_3_SIZE - 1)\n#define HASH_4_MASK (HASH_4_SIZE - 1)\n\n#define FIX_3_HASH_SIZE (HASH_2_SIZE)\n#define FIX_4_HASH_SIZE (HASH_2_SIZE + HASH_3_SIZE)\n#define FIX_5_HASH_SIZE (HASH_2_SIZE + HASH_3_SIZE + HASH_4_SIZE)\n\n// Endianness doesn't matter in hash_2_calc() (no effect on the output).\n#ifdef TUKLIB_FAST_UNALIGNED_ACCESS\n#\tdefine hash_2_calc() \\\n\t\tconst uint32_t hash_value = read16ne(cur)\n#else\n#\tdefine hash_2_calc() \\\n\t\tconst uint32_t hash_value \\\n\t\t\t= (uint32_t)(cur[0]) | ((uint32_t)(cur[1]) << 8)\n#endif\n\n#define hash_3_calc() \\\n\tconst uint32_t temp = hash_table[cur[0]] ^ cur[1]; \\\n\tconst uint32_t hash_2_value = temp & HASH_2_MASK; \\\n\tconst uint32_t hash_value \\\n\t\t\t= (temp ^ ((uint32_t)(cur[2]) << 8)) & mf->hash_mask\n\n#define hash_4_calc() \\\n\tconst uint32_t temp = hash_table[cur[0]] ^ cur[1]; \\\n\tconst uint32_t hash_2_value = temp & HASH_2_MASK; \\\n\tconst uint32_t hash_3_value \\\n\t\t\t= (temp ^ ((uint32_t)(cur[2]) << 8)) & HASH_3_MASK; \\\n\tconst uint32_t hash_value = (temp ^ ((uint32_t)(cur[2]) << 8) \\\n\t\t\t^ (hash_table[cur[3]] << 5)) & mf->hash_mask\n\n\n// The following are not currently used.\n\n#define hash_5_calc() \\\n\tconst uint32_t temp = hash_table[cur[0]] ^ cur[1]; \\\n\tconst uint32_t hash_2_value = temp & HASH_2_MASK; \\\n\tconst uint32_t hash_3_value \\\n\t\t\t= (temp ^ ((uint32_t)(cur[2]) << 8)) & HASH_3_MASK; \\\n\tuint32_t hash_4_value = (temp ^ ((uint32_t)(cur[2]) << 8) ^ \\\n\t\t\t^ hash_table[cur[3]] << 5); \\\n\tconst uint32_t hash_value \\\n\t\t\t= (hash_4_value ^ (hash_table[cur[4]] << 3)) \\\n\t\t\t\t& mf->hash_mask; \\\n\thash_4_value &= HASH_4_MASK\n\n/*\n#define hash_zip_calc() \\\n\tconst uint32_t hash_value \\\n\t\t\t= (((uint32_t)(cur[0]) | ((uint32_t)(cur[1]) << 8)) \\\n\t\t\t\t^ hash_table[cur[2]]) & 0xFFFF\n*/\n\n#define hash_zip_calc() \\\n\tconst uint32_t hash_value \\\n\t\t\t= (((uint32_t)(cur[2]) | ((uint32_t)(cur[0]) << 8)) \\\n\t\t\t\t^ hash_table[cur[1]]) & 0xFFFF\n\n#define mt_hash_2_calc() \\\n\tconst uint32_t hash_2_value \\\n\t\t\t= (hash_table[cur[0]] ^ cur[1]) & HASH_2_MASK\n\n#define mt_hash_3_calc() \\\n\tconst uint32_t temp = hash_table[cur[0]] ^ cur[1]; \\\n\tconst uint32_t hash_2_value = temp & HASH_2_MASK; \\\n\tconst uint32_t hash_3_value \\\n\t\t\t= (temp ^ ((uint32_t)(cur[2]) << 8)) & HASH_3_MASK\n\n#define mt_hash_4_calc() \\\n\tconst uint32_t temp = hash_table[cur[0]] ^ cur[1]; \\\n\tconst uint32_t hash_2_value = temp & HASH_2_MASK; \\\n\tconst uint32_t hash_3_value \\\n\t\t\t= (temp ^ ((uint32_t)(cur[2]) << 8)) & HASH_3_MASK; \\\n\tconst uint32_t hash_4_value = (temp ^ ((uint32_t)(cur[2]) << 8) ^ \\\n\t\t\t(hash_table[cur[3]] << 5)) & HASH_4_MASK\n\n#endif\n"
  },
  {
    "path": "external/xz/liblzma/lz/lz_encoder_hash_table.h",
    "content": "/* This file has been automatically generated by crc32_tablegen.c. */\n\nconst uint32_t lzma_lz_hash_table[256] = {\n\t0x00000000, 0x77073096, 0xEE0E612C, 0x990951BA,\n\t0x076DC419, 0x706AF48F, 0xE963A535, 0x9E6495A3,\n\t0x0EDB8832, 0x79DCB8A4, 0xE0D5E91E, 0x97D2D988,\n\t0x09B64C2B, 0x7EB17CBD, 0xE7B82D07, 0x90BF1D91,\n\t0x1DB71064, 0x6AB020F2, 0xF3B97148, 0x84BE41DE,\n\t0x1ADAD47D, 0x6DDDE4EB, 0xF4D4B551, 0x83D385C7,\n\t0x136C9856, 0x646BA8C0, 0xFD62F97A, 0x8A65C9EC,\n\t0x14015C4F, 0x63066CD9, 0xFA0F3D63, 0x8D080DF5,\n\t0x3B6E20C8, 0x4C69105E, 0xD56041E4, 0xA2677172,\n\t0x3C03E4D1, 0x4B04D447, 0xD20D85FD, 0xA50AB56B,\n\t0x35B5A8FA, 0x42B2986C, 0xDBBBC9D6, 0xACBCF940,\n\t0x32D86CE3, 0x45DF5C75, 0xDCD60DCF, 0xABD13D59,\n\t0x26D930AC, 0x51DE003A, 0xC8D75180, 0xBFD06116,\n\t0x21B4F4B5, 0x56B3C423, 0xCFBA9599, 0xB8BDA50F,\n\t0x2802B89E, 0x5F058808, 0xC60CD9B2, 0xB10BE924,\n\t0x2F6F7C87, 0x58684C11, 0xC1611DAB, 0xB6662D3D,\n\t0x76DC4190, 0x01DB7106, 0x98D220BC, 0xEFD5102A,\n\t0x71B18589, 0x06B6B51F, 0x9FBFE4A5, 0xE8B8D433,\n\t0x7807C9A2, 0x0F00F934, 0x9609A88E, 0xE10E9818,\n\t0x7F6A0DBB, 0x086D3D2D, 0x91646C97, 0xE6635C01,\n\t0x6B6B51F4, 0x1C6C6162, 0x856530D8, 0xF262004E,\n\t0x6C0695ED, 0x1B01A57B, 0x8208F4C1, 0xF50FC457,\n\t0x65B0D9C6, 0x12B7E950, 0x8BBEB8EA, 0xFCB9887C,\n\t0x62DD1DDF, 0x15DA2D49, 0x8CD37CF3, 0xFBD44C65,\n\t0x4DB26158, 0x3AB551CE, 0xA3BC0074, 0xD4BB30E2,\n\t0x4ADFA541, 0x3DD895D7, 0xA4D1C46D, 0xD3D6F4FB,\n\t0x4369E96A, 0x346ED9FC, 0xAD678846, 0xDA60B8D0,\n\t0x44042D73, 0x33031DE5, 0xAA0A4C5F, 0xDD0D7CC9,\n\t0x5005713C, 0x270241AA, 0xBE0B1010, 0xC90C2086,\n\t0x5768B525, 0x206F85B3, 0xB966D409, 0xCE61E49F,\n\t0x5EDEF90E, 0x29D9C998, 0xB0D09822, 0xC7D7A8B4,\n\t0x59B33D17, 0x2EB40D81, 0xB7BD5C3B, 0xC0BA6CAD,\n\t0xEDB88320, 0x9ABFB3B6, 0x03B6E20C, 0x74B1D29A,\n\t0xEAD54739, 0x9DD277AF, 0x04DB2615, 0x73DC1683,\n\t0xE3630B12, 0x94643B84, 0x0D6D6A3E, 0x7A6A5AA8,\n\t0xE40ECF0B, 0x9309FF9D, 0x0A00AE27, 0x7D079EB1,\n\t0xF00F9344, 0x8708A3D2, 0x1E01F268, 0x6906C2FE,\n\t0xF762575D, 0x806567CB, 0x196C3671, 0x6E6B06E7,\n\t0xFED41B76, 0x89D32BE0, 0x10DA7A5A, 0x67DD4ACC,\n\t0xF9B9DF6F, 0x8EBEEFF9, 0x17B7BE43, 0x60B08ED5,\n\t0xD6D6A3E8, 0xA1D1937E, 0x38D8C2C4, 0x4FDFF252,\n\t0xD1BB67F1, 0xA6BC5767, 0x3FB506DD, 0x48B2364B,\n\t0xD80D2BDA, 0xAF0A1B4C, 0x36034AF6, 0x41047A60,\n\t0xDF60EFC3, 0xA867DF55, 0x316E8EEF, 0x4669BE79,\n\t0xCB61B38C, 0xBC66831A, 0x256FD2A0, 0x5268E236,\n\t0xCC0C7795, 0xBB0B4703, 0x220216B9, 0x5505262F,\n\t0xC5BA3BBE, 0xB2BD0B28, 0x2BB45A92, 0x5CB36A04,\n\t0xC2D7FFA7, 0xB5D0CF31, 0x2CD99E8B, 0x5BDEAE1D,\n\t0x9B64C2B0, 0xEC63F226, 0x756AA39C, 0x026D930A,\n\t0x9C0906A9, 0xEB0E363F, 0x72076785, 0x05005713,\n\t0x95BF4A82, 0xE2B87A14, 0x7BB12BAE, 0x0CB61B38,\n\t0x92D28E9B, 0xE5D5BE0D, 0x7CDCEFB7, 0x0BDBDF21,\n\t0x86D3D2D4, 0xF1D4E242, 0x68DDB3F8, 0x1FDA836E,\n\t0x81BE16CD, 0xF6B9265B, 0x6FB077E1, 0x18B74777,\n\t0x88085AE6, 0xFF0F6A70, 0x66063BCA, 0x11010B5C,\n\t0x8F659EFF, 0xF862AE69, 0x616BFFD3, 0x166CCF45,\n\t0xA00AE278, 0xD70DD2EE, 0x4E048354, 0x3903B3C2,\n\t0xA7672661, 0xD06016F7, 0x4969474D, 0x3E6E77DB,\n\t0xAED16A4A, 0xD9D65ADC, 0x40DF0B66, 0x37D83BF0,\n\t0xA9BCAE53, 0xDEBB9EC5, 0x47B2CF7F, 0x30B5FFE9,\n\t0xBDBDF21C, 0xCABAC28A, 0x53B39330, 0x24B4A3A6,\n\t0xBAD03605, 0xCDD70693, 0x54DE5729, 0x23D967BF,\n\t0xB3667A2E, 0xC4614AB8, 0x5D681B02, 0x2A6F2B94,\n\t0xB40BBE37, 0xC30C8EA1, 0x5A05DF1B, 0x2D02EF8D\n};\n"
  },
  {
    "path": "external/xz/liblzma/lz/lz_encoder_mf.c",
    "content": "///////////////////////////////////////////////////////////////////////////////\n//\n/// \\file       lz_encoder_mf.c\n/// \\brief      Match finders\n///\n//  Authors:    Igor Pavlov\n//              Lasse Collin\n//\n//  This file has been put into the public domain.\n//  You can do whatever you want with this file.\n//\n///////////////////////////////////////////////////////////////////////////////\n\n#include \"lz_encoder.h\"\n#include \"lz_encoder_hash.h\"\n#include \"memcmplen.h\"\n\n\n/// \\brief      Find matches starting from the current byte\n///\n/// \\return     The length of the longest match found\nextern uint32_t\nlzma_mf_find(lzma_mf *mf, uint32_t *count_ptr, lzma_match *matches)\n{\n\t// Call the match finder. It returns the number of length-distance\n\t// pairs found.\n\t// FIXME: Minimum count is zero, what _exactly_ is the maximum?\n\tconst uint32_t count = mf->find(mf, matches);\n\n\t// Length of the longest match; assume that no matches were found\n\t// and thus the maximum length is zero.\n\tuint32_t len_best = 0;\n\n\tif (count > 0) {\n#ifndef NDEBUG\n\t\t// Validate the matches.\n\t\tfor (uint32_t i = 0; i < count; ++i) {\n\t\t\tassert(matches[i].len <= mf->nice_len);\n\t\t\tassert(matches[i].dist < mf->read_pos);\n\t\t\tassert(memcmp(mf_ptr(mf) - 1,\n\t\t\t\tmf_ptr(mf) - matches[i].dist - 2,\n\t\t\t\tmatches[i].len) == 0);\n\t\t}\n#endif\n\n\t\t// The last used element in the array contains\n\t\t// the longest match.\n\t\tlen_best = matches[count - 1].len;\n\n\t\t// If a match of maximum search length was found, try to\n\t\t// extend the match to maximum possible length.\n\t\tif (len_best == mf->nice_len) {\n\t\t\t// The limit for the match length is either the\n\t\t\t// maximum match length supported by the LZ-based\n\t\t\t// encoder or the number of bytes left in the\n\t\t\t// dictionary, whichever is smaller.\n\t\t\tuint32_t limit = mf_avail(mf) + 1;\n\t\t\tif (limit > mf->match_len_max)\n\t\t\t\tlimit = mf->match_len_max;\n\n\t\t\t// Pointer to the byte we just ran through\n\t\t\t// the match finder.\n\t\t\tconst uint8_t *p1 = mf_ptr(mf) - 1;\n\n\t\t\t// Pointer to the beginning of the match. We need -1\n\t\t\t// here because the match distances are zero based.\n\t\t\tconst uint8_t *p2 = p1 - matches[count - 1].dist - 1;\n\n\t\t\tlen_best = lzma_memcmplen(p1, p2, len_best, limit);\n\t\t}\n\t}\n\n\t*count_ptr = count;\n\n\t// Finally update the read position to indicate that match finder was\n\t// run for this dictionary offset.\n\t++mf->read_ahead;\n\n\treturn len_best;\n}\n\n\n/// Hash value to indicate unused element in the hash. Since we start the\n/// positions from dict_size + 1, zero is always too far to qualify\n/// as usable match position.\n#define EMPTY_HASH_VALUE 0\n\n\n/// Normalization must be done when lzma_mf.offset + lzma_mf.read_pos\n/// reaches MUST_NORMALIZE_POS.\n#define MUST_NORMALIZE_POS UINT32_MAX\n\n\n/// \\brief      Normalizes hash values\n///\n/// The hash arrays store positions of match candidates. The positions are\n/// relative to an arbitrary offset that is not the same as the absolute\n/// offset in the input stream. The relative position of the current byte\n/// is lzma_mf.offset + lzma_mf.read_pos. The distances of the matches are\n/// the differences of the current read position and the position found from\n/// the hash.\n///\n/// To prevent integer overflows of the offsets stored in the hash arrays,\n/// we need to \"normalize\" the stored values now and then. During the\n/// normalization, we drop values that indicate distance greater than the\n/// dictionary size, thus making space for new values.\nstatic void\nnormalize(lzma_mf *mf)\n{\n\tassert(mf->read_pos + mf->offset == MUST_NORMALIZE_POS);\n\n\t// In future we may not want to touch the lowest bits, because there\n\t// may be match finders that use larger resolution than one byte.\n\tconst uint32_t subvalue\n\t\t\t= (MUST_NORMALIZE_POS - mf->cyclic_size);\n\t\t\t\t// & ~((UINT32_C(1) << 10) - 1);\n\n\tfor (uint32_t i = 0; i < mf->hash_count; ++i) {\n\t\t// If the distance is greater than the dictionary size,\n\t\t// we can simply mark the hash element as empty.\n\t\tif (mf->hash[i] <= subvalue)\n\t\t\tmf->hash[i] = EMPTY_HASH_VALUE;\n\t\telse\n\t\t\tmf->hash[i] -= subvalue;\n\t}\n\n\tfor (uint32_t i = 0; i < mf->sons_count; ++i) {\n\t\t// Do the same for mf->son.\n\t\t//\n\t\t// NOTE: There may be uninitialized elements in mf->son.\n\t\t// Valgrind may complain that the \"if\" below depends on\n\t\t// an uninitialized value. In this case it is safe to ignore\n\t\t// the warning. See also the comments in lz_encoder_init()\n\t\t// in lz_encoder.c.\n\t\tif (mf->son[i] <= subvalue)\n\t\t\tmf->son[i] = EMPTY_HASH_VALUE;\n\t\telse\n\t\t\tmf->son[i] -= subvalue;\n\t}\n\n\t// Update offset to match the new locations.\n\tmf->offset -= subvalue;\n\n\treturn;\n}\n\n\n/// Mark the current byte as processed from point of view of the match finder.\nstatic void\nmove_pos(lzma_mf *mf)\n{\n\tif (++mf->cyclic_pos == mf->cyclic_size)\n\t\tmf->cyclic_pos = 0;\n\n\t++mf->read_pos;\n\tassert(mf->read_pos <= mf->write_pos);\n\n\tif (unlikely(mf->read_pos + mf->offset == UINT32_MAX))\n\t\tnormalize(mf);\n}\n\n\n/// When flushing, we cannot run the match finder unless there is nice_len\n/// bytes available in the dictionary. Instead, we skip running the match\n/// finder (indicating that no match was found), and count how many bytes we\n/// have ignored this way.\n///\n/// When new data is given after the flushing was completed, the match finder\n/// is restarted by rewinding mf->read_pos backwards by mf->pending. Then\n/// the missed bytes are added to the hash using the match finder's skip\n/// function (with small amount of input, it may start using mf->pending\n/// again if flushing).\n///\n/// Due to this rewinding, we don't touch cyclic_pos or test for\n/// normalization. It will be done when the match finder's skip function\n/// catches up after a flush.\nstatic void\nmove_pending(lzma_mf *mf)\n{\n\t++mf->read_pos;\n\tassert(mf->read_pos <= mf->write_pos);\n\t++mf->pending;\n}\n\n\n/// Calculate len_limit and determine if there is enough input to run\n/// the actual match finder code. Sets up \"cur\" and \"pos\". This macro\n/// is used by all find functions and binary tree skip functions. Hash\n/// chain skip function doesn't need len_limit so a simpler code is used\n/// in them.\n#define header(is_bt, len_min, ret_op) \\\n\tuint32_t len_limit = mf_avail(mf); \\\n\tif (mf->nice_len <= len_limit) { \\\n\t\tlen_limit = mf->nice_len; \\\n\t} else if (len_limit < (len_min) \\\n\t\t\t|| (is_bt && mf->action == LZMA_SYNC_FLUSH)) { \\\n\t\tassert(mf->action != LZMA_RUN); \\\n\t\tmove_pending(mf); \\\n\t\tret_op; \\\n\t} \\\n\tconst uint8_t *cur = mf_ptr(mf); \\\n\tconst uint32_t pos = mf->read_pos + mf->offset\n\n\n/// Header for find functions. \"return 0\" indicates that zero matches\n/// were found.\n#define header_find(is_bt, len_min) \\\n\theader(is_bt, len_min, return 0); \\\n\tuint32_t matches_count = 0\n\n\n/// Header for a loop in a skip function. \"continue\" tells to skip the rest\n/// of the code in the loop.\n#define header_skip(is_bt, len_min) \\\n\theader(is_bt, len_min, continue)\n\n\n/// Calls hc_find_func() or bt_find_func() and calculates the total number\n/// of matches found. Updates the dictionary position and returns the number\n/// of matches found.\n#define call_find(func, len_best) \\\ndo { \\\n\tmatches_count = func(len_limit, pos, cur, cur_match, mf->depth, \\\n\t\t\t\tmf->son, mf->cyclic_pos, mf->cyclic_size, \\\n\t\t\t\tmatches + matches_count, len_best) \\\n\t\t\t- matches; \\\n\tmove_pos(mf); \\\n\treturn matches_count; \\\n} while (0)\n\n\n////////////////\n// Hash Chain //\n////////////////\n\n#if defined(HAVE_MF_HC3) || defined(HAVE_MF_HC4)\n///\n///\n/// \\param      len_limit       Don't look for matches longer than len_limit.\n/// \\param      pos             lzma_mf.read_pos + lzma_mf.offset\n/// \\param      cur             Pointer to current byte (mf_ptr(mf))\n/// \\param      cur_match       Start position of the current match candidate\n/// \\param      depth           Maximum length of the hash chain\n/// \\param      son             lzma_mf.son (contains the hash chain)\n/// \\param      cyclic_pos\n/// \\param      cyclic_size\n/// \\param      matches         Array to hold the matches.\n/// \\param      len_best        The length of the longest match found so far.\nstatic lzma_match *\nhc_find_func(\n\t\tconst uint32_t len_limit,\n\t\tconst uint32_t pos,\n\t\tconst uint8_t *const cur,\n\t\tuint32_t cur_match,\n\t\tuint32_t depth,\n\t\tuint32_t *const son,\n\t\tconst uint32_t cyclic_pos,\n\t\tconst uint32_t cyclic_size,\n\t\tlzma_match *matches,\n\t\tuint32_t len_best)\n{\n\tson[cyclic_pos] = cur_match;\n\n\twhile (true) {\n\t\tconst uint32_t delta = pos - cur_match;\n\t\tif (depth-- == 0 || delta >= cyclic_size)\n\t\t\treturn matches;\n\n\t\tconst uint8_t *const pb = cur - delta;\n\t\tcur_match = son[cyclic_pos - delta\n\t\t\t\t+ (delta > cyclic_pos ? cyclic_size : 0)];\n\n\t\tif (pb[len_best] == cur[len_best] && pb[0] == cur[0]) {\n\t\t\tuint32_t len = lzma_memcmplen(pb, cur, 1, len_limit);\n\n\t\t\tif (len_best < len) {\n\t\t\t\tlen_best = len;\n\t\t\t\tmatches->len = len;\n\t\t\t\tmatches->dist = delta - 1;\n\t\t\t\t++matches;\n\n\t\t\t\tif (len == len_limit)\n\t\t\t\t\treturn matches;\n\t\t\t}\n\t\t}\n\t}\n}\n\n\n#define hc_find(len_best) \\\n\tcall_find(hc_find_func, len_best)\n\n\n#define hc_skip() \\\ndo { \\\n\tmf->son[mf->cyclic_pos] = cur_match; \\\n\tmove_pos(mf); \\\n} while (0)\n\n#endif\n\n\n#ifdef HAVE_MF_HC3\nextern uint32_t\nlzma_mf_hc3_find(lzma_mf *mf, lzma_match *matches)\n{\n\theader_find(false, 3);\n\n\thash_3_calc();\n\n\tconst uint32_t delta2 = pos - mf->hash[hash_2_value];\n\tconst uint32_t cur_match = mf->hash[FIX_3_HASH_SIZE + hash_value];\n\n\tmf->hash[hash_2_value] = pos;\n\tmf->hash[FIX_3_HASH_SIZE + hash_value] = pos;\n\n\tuint32_t len_best = 2;\n\n\tif (delta2 < mf->cyclic_size && *(cur - delta2) == *cur) {\n\t\tlen_best = lzma_memcmplen(cur - delta2, cur,\n\t\t\t\tlen_best, len_limit);\n\n\t\tmatches[0].len = len_best;\n\t\tmatches[0].dist = delta2 - 1;\n\t\tmatches_count = 1;\n\n\t\tif (len_best == len_limit) {\n\t\t\thc_skip();\n\t\t\treturn 1; // matches_count\n\t\t}\n\t}\n\n\thc_find(len_best);\n}\n\n\nextern void\nlzma_mf_hc3_skip(lzma_mf *mf, uint32_t amount)\n{\n\tdo {\n\t\tif (mf_avail(mf) < 3) {\n\t\t\tmove_pending(mf);\n\t\t\tcontinue;\n\t\t}\n\n\t\tconst uint8_t *cur = mf_ptr(mf);\n\t\tconst uint32_t pos = mf->read_pos + mf->offset;\n\n\t\thash_3_calc();\n\n\t\tconst uint32_t cur_match\n\t\t\t\t= mf->hash[FIX_3_HASH_SIZE + hash_value];\n\n\t\tmf->hash[hash_2_value] = pos;\n\t\tmf->hash[FIX_3_HASH_SIZE + hash_value] = pos;\n\n\t\thc_skip();\n\n\t} while (--amount != 0);\n}\n#endif\n\n\n#ifdef HAVE_MF_HC4\nextern uint32_t\nlzma_mf_hc4_find(lzma_mf *mf, lzma_match *matches)\n{\n\theader_find(false, 4);\n\n\thash_4_calc();\n\n\tuint32_t delta2 = pos - mf->hash[hash_2_value];\n\tconst uint32_t delta3\n\t\t\t= pos - mf->hash[FIX_3_HASH_SIZE + hash_3_value];\n\tconst uint32_t cur_match = mf->hash[FIX_4_HASH_SIZE + hash_value];\n\n\tmf->hash[hash_2_value ] = pos;\n\tmf->hash[FIX_3_HASH_SIZE + hash_3_value] = pos;\n\tmf->hash[FIX_4_HASH_SIZE + hash_value] = pos;\n\n\tuint32_t len_best = 1;\n\n\tif (delta2 < mf->cyclic_size && *(cur - delta2) == *cur) {\n\t\tlen_best = 2;\n\t\tmatches[0].len = 2;\n\t\tmatches[0].dist = delta2 - 1;\n\t\tmatches_count = 1;\n\t}\n\n\tif (delta2 != delta3 && delta3 < mf->cyclic_size\n\t\t\t&& *(cur - delta3) == *cur) {\n\t\tlen_best = 3;\n\t\tmatches[matches_count++].dist = delta3 - 1;\n\t\tdelta2 = delta3;\n\t}\n\n\tif (matches_count != 0) {\n\t\tlen_best = lzma_memcmplen(cur - delta2, cur,\n\t\t\t\tlen_best, len_limit);\n\n\t\tmatches[matches_count - 1].len = len_best;\n\n\t\tif (len_best == len_limit) {\n\t\t\thc_skip();\n\t\t\treturn matches_count;\n\t\t}\n\t}\n\n\tif (len_best < 3)\n\t\tlen_best = 3;\n\n\thc_find(len_best);\n}\n\n\nextern void\nlzma_mf_hc4_skip(lzma_mf *mf, uint32_t amount)\n{\n\tdo {\n\t\tif (mf_avail(mf) < 4) {\n\t\t\tmove_pending(mf);\n\t\t\tcontinue;\n\t\t}\n\n\t\tconst uint8_t *cur = mf_ptr(mf);\n\t\tconst uint32_t pos = mf->read_pos + mf->offset;\n\n\t\thash_4_calc();\n\n\t\tconst uint32_t cur_match\n\t\t\t\t= mf->hash[FIX_4_HASH_SIZE + hash_value];\n\n\t\tmf->hash[hash_2_value] = pos;\n\t\tmf->hash[FIX_3_HASH_SIZE + hash_3_value] = pos;\n\t\tmf->hash[FIX_4_HASH_SIZE + hash_value] = pos;\n\n\t\thc_skip();\n\n\t} while (--amount != 0);\n}\n#endif\n\n\n/////////////////\n// Binary Tree //\n/////////////////\n\n#if defined(HAVE_MF_BT2) || defined(HAVE_MF_BT3) || defined(HAVE_MF_BT4)\nstatic lzma_match *\nbt_find_func(\n\t\tconst uint32_t len_limit,\n\t\tconst uint32_t pos,\n\t\tconst uint8_t *const cur,\n\t\tuint32_t cur_match,\n\t\tuint32_t depth,\n\t\tuint32_t *const son,\n\t\tconst uint32_t cyclic_pos,\n\t\tconst uint32_t cyclic_size,\n\t\tlzma_match *matches,\n\t\tuint32_t len_best)\n{\n\tuint32_t *ptr0 = son + (cyclic_pos << 1) + 1;\n\tuint32_t *ptr1 = son + (cyclic_pos << 1);\n\n\tuint32_t len0 = 0;\n\tuint32_t len1 = 0;\n\n\twhile (true) {\n\t\tconst uint32_t delta = pos - cur_match;\n\t\tif (depth-- == 0 || delta >= cyclic_size) {\n\t\t\t*ptr0 = EMPTY_HASH_VALUE;\n\t\t\t*ptr1 = EMPTY_HASH_VALUE;\n\t\t\treturn matches;\n\t\t}\n\n\t\tuint32_t *const pair = son + ((cyclic_pos - delta\n\t\t\t\t+ (delta > cyclic_pos ? cyclic_size : 0))\n\t\t\t\t<< 1);\n\n\t\tconst uint8_t *const pb = cur - delta;\n\t\tuint32_t len = my_min(len0, len1);\n\n\t\tif (pb[len] == cur[len]) {\n\t\t\tlen = lzma_memcmplen(pb, cur, len + 1, len_limit);\n\n\t\t\tif (len_best < len) {\n\t\t\t\tlen_best = len;\n\t\t\t\tmatches->len = len;\n\t\t\t\tmatches->dist = delta - 1;\n\t\t\t\t++matches;\n\n\t\t\t\tif (len == len_limit) {\n\t\t\t\t\t*ptr1 = pair[0];\n\t\t\t\t\t*ptr0 = pair[1];\n\t\t\t\t\treturn matches;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\tif (pb[len] < cur[len]) {\n\t\t\t*ptr1 = cur_match;\n\t\t\tptr1 = pair + 1;\n\t\t\tcur_match = *ptr1;\n\t\t\tlen1 = len;\n\t\t} else {\n\t\t\t*ptr0 = cur_match;\n\t\t\tptr0 = pair;\n\t\t\tcur_match = *ptr0;\n\t\t\tlen0 = len;\n\t\t}\n\t}\n}\n\n\nstatic void\nbt_skip_func(\n\t\tconst uint32_t len_limit,\n\t\tconst uint32_t pos,\n\t\tconst uint8_t *const cur,\n\t\tuint32_t cur_match,\n\t\tuint32_t depth,\n\t\tuint32_t *const son,\n\t\tconst uint32_t cyclic_pos,\n\t\tconst uint32_t cyclic_size)\n{\n\tuint32_t *ptr0 = son + (cyclic_pos << 1) + 1;\n\tuint32_t *ptr1 = son + (cyclic_pos << 1);\n\n\tuint32_t len0 = 0;\n\tuint32_t len1 = 0;\n\n\twhile (true) {\n\t\tconst uint32_t delta = pos - cur_match;\n\t\tif (depth-- == 0 || delta >= cyclic_size) {\n\t\t\t*ptr0 = EMPTY_HASH_VALUE;\n\t\t\t*ptr1 = EMPTY_HASH_VALUE;\n\t\t\treturn;\n\t\t}\n\n\t\tuint32_t *pair = son + ((cyclic_pos - delta\n\t\t\t\t+ (delta > cyclic_pos ? cyclic_size : 0))\n\t\t\t\t<< 1);\n\t\tconst uint8_t *pb = cur - delta;\n\t\tuint32_t len = my_min(len0, len1);\n\n\t\tif (pb[len] == cur[len]) {\n\t\t\tlen = lzma_memcmplen(pb, cur, len + 1, len_limit);\n\n\t\t\tif (len == len_limit) {\n\t\t\t\t*ptr1 = pair[0];\n\t\t\t\t*ptr0 = pair[1];\n\t\t\t\treturn;\n\t\t\t}\n\t\t}\n\n\t\tif (pb[len] < cur[len]) {\n\t\t\t*ptr1 = cur_match;\n\t\t\tptr1 = pair + 1;\n\t\t\tcur_match = *ptr1;\n\t\t\tlen1 = len;\n\t\t} else {\n\t\t\t*ptr0 = cur_match;\n\t\t\tptr0 = pair;\n\t\t\tcur_match = *ptr0;\n\t\t\tlen0 = len;\n\t\t}\n\t}\n}\n\n\n#define bt_find(len_best) \\\n\tcall_find(bt_find_func, len_best)\n\n#define bt_skip() \\\ndo { \\\n\tbt_skip_func(len_limit, pos, cur, cur_match, mf->depth, \\\n\t\t\tmf->son, mf->cyclic_pos, \\\n\t\t\tmf->cyclic_size); \\\n\tmove_pos(mf); \\\n} while (0)\n\n#endif\n\n\n#ifdef HAVE_MF_BT2\nextern uint32_t\nlzma_mf_bt2_find(lzma_mf *mf, lzma_match *matches)\n{\n\theader_find(true, 2);\n\n\thash_2_calc();\n\n\tconst uint32_t cur_match = mf->hash[hash_value];\n\tmf->hash[hash_value] = pos;\n\n\tbt_find(1);\n}\n\n\nextern void\nlzma_mf_bt2_skip(lzma_mf *mf, uint32_t amount)\n{\n\tdo {\n\t\theader_skip(true, 2);\n\n\t\thash_2_calc();\n\n\t\tconst uint32_t cur_match = mf->hash[hash_value];\n\t\tmf->hash[hash_value] = pos;\n\n\t\tbt_skip();\n\n\t} while (--amount != 0);\n}\n#endif\n\n\n#ifdef HAVE_MF_BT3\nextern uint32_t\nlzma_mf_bt3_find(lzma_mf *mf, lzma_match *matches)\n{\n\theader_find(true, 3);\n\n\thash_3_calc();\n\n\tconst uint32_t delta2 = pos - mf->hash[hash_2_value];\n\tconst uint32_t cur_match = mf->hash[FIX_3_HASH_SIZE + hash_value];\n\n\tmf->hash[hash_2_value] = pos;\n\tmf->hash[FIX_3_HASH_SIZE + hash_value] = pos;\n\n\tuint32_t len_best = 2;\n\n\tif (delta2 < mf->cyclic_size && *(cur - delta2) == *cur) {\n\t\tlen_best = lzma_memcmplen(\n\t\t\t\tcur, cur - delta2, len_best, len_limit);\n\n\t\tmatches[0].len = len_best;\n\t\tmatches[0].dist = delta2 - 1;\n\t\tmatches_count = 1;\n\n\t\tif (len_best == len_limit) {\n\t\t\tbt_skip();\n\t\t\treturn 1; // matches_count\n\t\t}\n\t}\n\n\tbt_find(len_best);\n}\n\n\nextern void\nlzma_mf_bt3_skip(lzma_mf *mf, uint32_t amount)\n{\n\tdo {\n\t\theader_skip(true, 3);\n\n\t\thash_3_calc();\n\n\t\tconst uint32_t cur_match\n\t\t\t\t= mf->hash[FIX_3_HASH_SIZE + hash_value];\n\n\t\tmf->hash[hash_2_value] = pos;\n\t\tmf->hash[FIX_3_HASH_SIZE + hash_value] = pos;\n\n\t\tbt_skip();\n\n\t} while (--amount != 0);\n}\n#endif\n\n\n#ifdef HAVE_MF_BT4\nextern uint32_t\nlzma_mf_bt4_find(lzma_mf *mf, lzma_match *matches)\n{\n\theader_find(true, 4);\n\n\thash_4_calc();\n\n\tuint32_t delta2 = pos - mf->hash[hash_2_value];\n\tconst uint32_t delta3\n\t\t\t= pos - mf->hash[FIX_3_HASH_SIZE + hash_3_value];\n\tconst uint32_t cur_match = mf->hash[FIX_4_HASH_SIZE + hash_value];\n\n\tmf->hash[hash_2_value] = pos;\n\tmf->hash[FIX_3_HASH_SIZE + hash_3_value] = pos;\n\tmf->hash[FIX_4_HASH_SIZE + hash_value] = pos;\n\n\tuint32_t len_best = 1;\n\n\tif (delta2 < mf->cyclic_size && *(cur - delta2) == *cur) {\n\t\tlen_best = 2;\n\t\tmatches[0].len = 2;\n\t\tmatches[0].dist = delta2 - 1;\n\t\tmatches_count = 1;\n\t}\n\n\tif (delta2 != delta3 && delta3 < mf->cyclic_size\n\t\t\t&& *(cur - delta3) == *cur) {\n\t\tlen_best = 3;\n\t\tmatches[matches_count++].dist = delta3 - 1;\n\t\tdelta2 = delta3;\n\t}\n\n\tif (matches_count != 0) {\n\t\tlen_best = lzma_memcmplen(\n\t\t\t\tcur, cur - delta2, len_best, len_limit);\n\n\t\tmatches[matches_count - 1].len = len_best;\n\n\t\tif (len_best == len_limit) {\n\t\t\tbt_skip();\n\t\t\treturn matches_count;\n\t\t}\n\t}\n\n\tif (len_best < 3)\n\t\tlen_best = 3;\n\n\tbt_find(len_best);\n}\n\n\nextern void\nlzma_mf_bt4_skip(lzma_mf *mf, uint32_t amount)\n{\n\tdo {\n\t\theader_skip(true, 4);\n\n\t\thash_4_calc();\n\n\t\tconst uint32_t cur_match\n\t\t\t\t= mf->hash[FIX_4_HASH_SIZE + hash_value];\n\n\t\tmf->hash[hash_2_value] = pos;\n\t\tmf->hash[FIX_3_HASH_SIZE + hash_3_value] = pos;\n\t\tmf->hash[FIX_4_HASH_SIZE + hash_value] = pos;\n\n\t\tbt_skip();\n\n\t} while (--amount != 0);\n}\n#endif\n"
  },
  {
    "path": "external/xz/liblzma/lzma/fastpos.h",
    "content": "///////////////////////////////////////////////////////////////////////////////\n//\n/// \\file       fastpos.h\n/// \\brief      Kind of two-bit version of bit scan reverse\n///\n//  Authors:    Igor Pavlov\n//              Lasse Collin\n//\n//  This file has been put into the public domain.\n//  You can do whatever you want with this file.\n//\n///////////////////////////////////////////////////////////////////////////////\n\n#ifndef LZMA_FASTPOS_H\n#define LZMA_FASTPOS_H\n\n// LZMA encodes match distances by storing the highest two bits using\n// a six-bit value [0, 63], and then the missing lower bits.\n// Dictionary size is also stored using this encoding in the .xz\n// file format header.\n//\n// fastpos.h provides a way to quickly find out the correct six-bit\n// values. The following table gives some examples of this encoding:\n//\n//     dist   return\n//       0       0\n//       1       1\n//       2       2\n//       3       3\n//       4       4\n//       5       4\n//       6       5\n//       7       5\n//       8       6\n//      11       6\n//      12       7\n//     ...      ...\n//      15       7\n//      16       8\n//      17       8\n//     ...      ...\n//      23       8\n//      24       9\n//      25       9\n//     ...      ...\n//\n//\n// Provided functions or macros\n// ----------------------------\n//\n// get_dist_slot(dist) is the basic version. get_dist_slot_2(dist)\n// assumes that dist >= FULL_DISTANCES, thus the result is at least\n// FULL_DISTANCES_BITS * 2. Using get_dist_slot(dist) instead of\n// get_dist_slot_2(dist) would give the same result, but get_dist_slot_2(dist)\n// should be tiny bit faster due to the assumption being made.\n//\n//\n// Size vs. speed\n// --------------\n//\n// With some CPUs that have fast BSR (bit scan reverse) instruction, the\n// size optimized version is slightly faster than the bigger table based\n// approach. Such CPUs include Intel Pentium Pro, Pentium II, Pentium III\n// and Core 2 (possibly others). AMD K7 seems to have slower BSR, but that\n// would still have speed roughly comparable to the table version. Older\n// x86 CPUs like the original Pentium have very slow BSR; on those systems\n// the table version is a lot faster.\n//\n// On some CPUs, the table version is a lot faster when using position\n// dependent code, but with position independent code the size optimized\n// version is slightly faster. This occurs at least on 32-bit SPARC (no\n// ASM optimizations).\n//\n// I'm making the table version the default, because that has good speed\n// on all systems I have tried. The size optimized version is sometimes\n// slightly faster, but sometimes it is a lot slower.\n\n#ifdef HAVE_SMALL\n#\tdefine get_dist_slot(dist) \\\n\t\t((dist) <= 4 ? (dist) : get_dist_slot_2(dist))\n\nstatic inline uint32_t\nget_dist_slot_2(uint32_t dist)\n{\n\tconst uint32_t i = bsr32(dist);\n\treturn (i + i) + ((dist >> (i - 1)) & 1);\n}\n\n\n#else\n\n#define FASTPOS_BITS 13\n\nextern const uint8_t lzma_fastpos[1 << FASTPOS_BITS];\n\n\n#define fastpos_shift(extra, n) \\\n\t((extra) + (n) * (FASTPOS_BITS - 1))\n\n#define fastpos_limit(extra, n) \\\n\t(UINT32_C(1) << (FASTPOS_BITS + fastpos_shift(extra, n)))\n\n#define fastpos_result(dist, extra, n) \\\n\t(uint32_t)(lzma_fastpos[(dist) >> fastpos_shift(extra, n)]) \\\n\t\t\t+ 2 * fastpos_shift(extra, n)\n\n\nstatic inline uint32_t\nget_dist_slot(uint32_t dist)\n{\n\t// If it is small enough, we can pick the result directly from\n\t// the precalculated table.\n\tif (dist < fastpos_limit(0, 0))\n\t\treturn lzma_fastpos[dist];\n\n\tif (dist < fastpos_limit(0, 1))\n\t\treturn fastpos_result(dist, 0, 1);\n\n\treturn fastpos_result(dist, 0, 2);\n}\n\n\n#ifdef FULL_DISTANCES_BITS\nstatic inline uint32_t\nget_dist_slot_2(uint32_t dist)\n{\n\tassert(dist >= FULL_DISTANCES);\n\n\tif (dist < fastpos_limit(FULL_DISTANCES_BITS - 1, 0))\n\t\treturn fastpos_result(dist, FULL_DISTANCES_BITS - 1, 0);\n\n\tif (dist < fastpos_limit(FULL_DISTANCES_BITS - 1, 1))\n\t\treturn fastpos_result(dist, FULL_DISTANCES_BITS - 1, 1);\n\n\treturn fastpos_result(dist, FULL_DISTANCES_BITS - 1, 2);\n}\n#endif\n\n#endif\n\n#endif\n"
  },
  {
    "path": "external/xz/liblzma/lzma/fastpos_table.c",
    "content": "/* This file has been automatically generated by fastpos_tablegen.c. */\n\n#include \"common.h\"\n#include \"fastpos.h\"\n\nconst uint8_t lzma_fastpos[1 << FASTPOS_BITS] = {\n\t  0,  1,  2,  3,  4,  4,  5,  5,  6,  6,  6,  6,  7,  7,  7,  7,\n\t  8,  8,  8,  8,  8,  8,  8,  8,  9,  9,  9,  9,  9,  9,  9,  9,\n\t 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10,\n\t 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11,\n\t 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12,\n\t 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12,\n\t 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13,\n\t 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13,\n\t 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14,\n\t 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14,\n\t 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14,\n\t 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14,\n\t 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15,\n\t 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15,\n\t 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15,\n\t 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15,\n\t 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16,\n\t 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16,\n\t 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16,\n\t 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16,\n\t 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16,\n\t 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16,\n\t 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16,\n\t 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16,\n\t 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17,\n\t 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17,\n\t 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17,\n\t 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17,\n\t 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17,\n\t 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17,\n\t 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17,\n\t 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17,\n\t 18, 18, 18, 18, 18, 18, 18, 18, 18, 18, 18, 18, 18, 18, 18, 18,\n\t 18, 18, 18, 18, 18, 18, 18, 18, 18, 18, 18, 18, 18, 18, 18, 18,\n\t 18, 18, 18, 18, 18, 18, 18, 18, 18, 18, 18, 18, 18, 18, 18, 18,\n\t 18, 18, 18, 18, 18, 18, 18, 18, 18, 18, 18, 18, 18, 18, 18, 18,\n\t 18, 18, 18, 18, 18, 18, 18, 18, 18, 18, 18, 18, 18, 18, 18, 18,\n\t 18, 18, 18, 18, 18, 18, 18, 18, 18, 18, 18, 18, 18, 18, 18, 18,\n\t 18, 18, 18, 18, 18, 18, 18, 18, 18, 18, 18, 18, 18, 18, 18, 18,\n\t 18, 18, 18, 18, 18, 18, 18, 18, 18, 18, 18, 18, 18, 18, 18, 18,\n\t 18, 18, 18, 18, 18, 18, 18, 18, 18, 18, 18, 18, 18, 18, 18, 18,\n\t 18, 18, 18, 18, 18, 18, 18, 18, 18, 18, 18, 18, 18, 18, 18, 18,\n\t 18, 18, 18, 18, 18, 18, 18, 18, 18, 18, 18, 18, 18, 18, 18, 18,\n\t 18, 18, 18, 18, 18, 18, 18, 18, 18, 18, 18, 18, 18, 18, 18, 18,\n\t 18, 18, 18, 18, 18, 18, 18, 18, 18, 18, 18, 18, 18, 18, 18, 18,\n\t 18, 18, 18, 18, 18, 18, 18, 18, 18, 18, 18, 18, 18, 18, 18, 18,\n\t 18, 18, 18, 18, 18, 18, 18, 18, 18, 18, 18, 18, 18, 18, 18, 18,\n\t 18, 18, 18, 18, 18, 18, 18, 18, 18, 18, 18, 18, 18, 18, 18, 18,\n\t 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19,\n\t 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19,\n\t 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19,\n\t 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19,\n\t 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19,\n\t 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19,\n\t 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19,\n\t 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19,\n\t 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19,\n\t 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19,\n\t 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19,\n\t 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19,\n\t 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19,\n\t 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19,\n\t 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19,\n\t 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19,\n\t 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20,\n\t 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20,\n\t 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20,\n\t 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20,\n\t 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20,\n\t 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20,\n\t 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20,\n\t 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20,\n\t 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20,\n\t 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20,\n\t 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20,\n\t 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20,\n\t 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20,\n\t 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20,\n\t 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20,\n\t 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20,\n\t 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20,\n\t 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20,\n\t 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20,\n\t 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20,\n\t 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20,\n\t 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20,\n\t 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20,\n\t 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20,\n\t 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20,\n\t 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20,\n\t 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20,\n\t 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20,\n\t 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20,\n\t 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20,\n\t 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20,\n\t 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20,\n\t 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21,\n\t 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21,\n\t 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21,\n\t 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21,\n\t 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21,\n\t 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21,\n\t 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21,\n\t 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21,\n\t 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21,\n\t 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21,\n\t 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21,\n\t 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21,\n\t 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21,\n\t 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21,\n\t 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21,\n\t 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21,\n\t 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21,\n\t 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21,\n\t 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21,\n\t 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21,\n\t 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21,\n\t 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21,\n\t 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21,\n\t 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21,\n\t 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21,\n\t 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21,\n\t 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21,\n\t 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21,\n\t 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21,\n\t 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21,\n\t 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21,\n\t 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21,\n\t 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22,\n\t 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22,\n\t 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22,\n\t 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22,\n\t 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22,\n\t 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22,\n\t 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22,\n\t 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22,\n\t 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22,\n\t 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22,\n\t 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22,\n\t 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22,\n\t 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22,\n\t 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22,\n\t 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22,\n\t 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22,\n\t 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22,\n\t 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22,\n\t 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22,\n\t 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22,\n\t 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22,\n\t 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22,\n\t 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22,\n\t 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22,\n\t 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22,\n\t 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22,\n\t 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22,\n\t 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22,\n\t 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22,\n\t 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22,\n\t 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22,\n\t 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22,\n\t 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22,\n\t 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22,\n\t 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22,\n\t 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22,\n\t 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22,\n\t 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22,\n\t 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22,\n\t 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22,\n\t 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22,\n\t 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22,\n\t 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22,\n\t 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22,\n\t 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22,\n\t 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22,\n\t 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22,\n\t 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22,\n\t 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22,\n\t 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22,\n\t 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22,\n\t 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22,\n\t 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22,\n\t 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22,\n\t 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22,\n\t 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22,\n\t 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22,\n\t 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22,\n\t 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22,\n\t 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22,\n\t 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22,\n\t 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22,\n\t 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22,\n\t 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22,\n\t 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23,\n\t 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23,\n\t 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23,\n\t 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23,\n\t 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23,\n\t 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23,\n\t 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23,\n\t 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23,\n\t 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23,\n\t 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23,\n\t 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23,\n\t 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23,\n\t 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23,\n\t 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23,\n\t 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23,\n\t 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23,\n\t 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23,\n\t 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23,\n\t 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23,\n\t 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23,\n\t 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23,\n\t 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23,\n\t 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23,\n\t 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23,\n\t 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23,\n\t 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23,\n\t 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23,\n\t 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23,\n\t 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23,\n\t 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23,\n\t 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23,\n\t 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23,\n\t 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23,\n\t 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23,\n\t 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23,\n\t 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23,\n\t 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23,\n\t 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23,\n\t 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23,\n\t 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23,\n\t 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23,\n\t 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23,\n\t 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23,\n\t 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23,\n\t 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23,\n\t 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23,\n\t 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23,\n\t 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23,\n\t 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23,\n\t 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23,\n\t 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23,\n\t 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23,\n\t 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23,\n\t 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23,\n\t 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23,\n\t 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23,\n\t 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23,\n\t 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23,\n\t 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23,\n\t 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23,\n\t 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23,\n\t 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23,\n\t 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23,\n\t 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23,\n\t 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24,\n\t 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24,\n\t 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24,\n\t 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24,\n\t 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24,\n\t 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24,\n\t 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24,\n\t 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24,\n\t 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24,\n\t 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24,\n\t 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24,\n\t 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24,\n\t 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24,\n\t 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24,\n\t 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24,\n\t 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24,\n\t 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24,\n\t 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24,\n\t 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24,\n\t 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24,\n\t 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24,\n\t 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24,\n\t 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24,\n\t 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24,\n\t 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24,\n\t 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24,\n\t 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24,\n\t 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24,\n\t 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24,\n\t 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24,\n\t 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24,\n\t 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24,\n\t 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24,\n\t 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24,\n\t 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24,\n\t 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24,\n\t 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24,\n\t 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24,\n\t 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24,\n\t 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24,\n\t 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24,\n\t 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24,\n\t 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24,\n\t 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24,\n\t 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24,\n\t 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24,\n\t 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24,\n\t 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24,\n\t 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24,\n\t 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24,\n\t 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24,\n\t 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24,\n\t 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24,\n\t 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24,\n\t 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24,\n\t 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24,\n\t 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24,\n\t 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24,\n\t 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24,\n\t 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24,\n\t 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24,\n\t 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24,\n\t 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24,\n\t 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24,\n\t 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24,\n\t 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24,\n\t 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24,\n\t 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24,\n\t 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24,\n\t 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24,\n\t 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24,\n\t 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24,\n\t 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24,\n\t 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24,\n\t 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24,\n\t 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24,\n\t 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24,\n\t 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24,\n\t 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24,\n\t 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24,\n\t 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24,\n\t 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24,\n\t 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24,\n\t 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24,\n\t 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24,\n\t 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24,\n\t 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24,\n\t 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24,\n\t 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24,\n\t 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24,\n\t 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24,\n\t 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24,\n\t 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24,\n\t 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24,\n\t 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24,\n\t 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24,\n\t 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24,\n\t 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24,\n\t 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24,\n\t 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24,\n\t 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24,\n\t 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24,\n\t 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24,\n\t 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24,\n\t 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24,\n\t 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24,\n\t 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24,\n\t 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24,\n\t 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24,\n\t 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24,\n\t 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24,\n\t 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24,\n\t 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24,\n\t 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24,\n\t 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24,\n\t 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24,\n\t 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24,\n\t 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24,\n\t 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24,\n\t 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24,\n\t 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24,\n\t 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24,\n\t 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24,\n\t 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24,\n\t 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24,\n\t 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24,\n\t 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24,\n\t 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24,\n\t 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25,\n\t 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25,\n\t 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25,\n\t 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25,\n\t 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25,\n\t 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25,\n\t 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25,\n\t 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25,\n\t 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25,\n\t 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25,\n\t 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25,\n\t 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25,\n\t 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25,\n\t 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25,\n\t 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25,\n\t 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25,\n\t 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25,\n\t 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25,\n\t 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25,\n\t 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25,\n\t 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25,\n\t 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25,\n\t 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25,\n\t 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25,\n\t 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25,\n\t 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25,\n\t 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25,\n\t 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25,\n\t 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25,\n\t 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25,\n\t 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25,\n\t 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25,\n\t 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25,\n\t 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25,\n\t 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25,\n\t 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25,\n\t 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25,\n\t 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25,\n\t 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25,\n\t 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25,\n\t 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25,\n\t 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25,\n\t 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25,\n\t 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25,\n\t 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25,\n\t 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25,\n\t 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25,\n\t 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25,\n\t 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25,\n\t 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25,\n\t 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25,\n\t 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25,\n\t 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25,\n\t 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25,\n\t 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25,\n\t 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25,\n\t 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25,\n\t 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25,\n\t 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25,\n\t 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25,\n\t 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25,\n\t 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25,\n\t 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25,\n\t 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25,\n\t 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25,\n\t 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25,\n\t 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25,\n\t 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25,\n\t 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25,\n\t 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25,\n\t 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25,\n\t 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25,\n\t 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25,\n\t 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25,\n\t 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25,\n\t 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25,\n\t 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25,\n\t 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25,\n\t 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25,\n\t 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25,\n\t 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25,\n\t 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25,\n\t 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25,\n\t 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25,\n\t 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25,\n\t 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25,\n\t 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25,\n\t 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25,\n\t 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25,\n\t 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25,\n\t 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25,\n\t 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25,\n\t 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25,\n\t 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25,\n\t 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25,\n\t 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25,\n\t 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25,\n\t 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25,\n\t 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25,\n\t 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25,\n\t 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25,\n\t 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25,\n\t 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25,\n\t 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25,\n\t 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25,\n\t 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25,\n\t 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25,\n\t 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25,\n\t 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25,\n\t 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25,\n\t 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25,\n\t 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25,\n\t 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25,\n\t 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25,\n\t 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25,\n\t 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25,\n\t 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25,\n\t 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25,\n\t 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25,\n\t 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25,\n\t 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25,\n\t 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25,\n\t 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25,\n\t 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25,\n\t 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25,\n\t 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25,\n\t 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25,\n\t 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25\n};\n"
  },
  {
    "path": "external/xz/liblzma/lzma/fastpos_tablegen.c",
    "content": "///////////////////////////////////////////////////////////////////////////////\n//\n/// \\file       fastpos_tablegen.c\n/// \\brief      Generates the lzma_fastpos[] lookup table\n///\n//  Authors:    Igor Pavlov\n//              Lasse Collin\n//\n//  This file has been put into the public domain.\n//  You can do whatever you want with this file.\n//\n///////////////////////////////////////////////////////////////////////////////\n\n#include <inttypes.h>\n#include <stdio.h>\n#include \"fastpos.h\"\n\n\nint\nmain(void)\n{\n\tuint8_t fastpos[1 << FASTPOS_BITS];\n\n\tconst uint8_t fast_slots = 2 * FASTPOS_BITS;\n\tuint32_t c = 2;\n\n\tfastpos[0] = 0;\n\tfastpos[1] = 1;\n\n\tfor (uint8_t slot_fast = 2; slot_fast < fast_slots; ++slot_fast) {\n\t\tconst uint32_t k = 1 << ((slot_fast >> 1) - 1);\n\t\tfor (uint32_t j = 0; j < k; ++j, ++c)\n\t\t\tfastpos[c] = slot_fast;\n\t}\n\n\tprintf(\"/* This file has been automatically generated \"\n\t\t\t\"by fastpos_tablegen.c. */\\n\\n\"\n\t\t\t\"#include \\\"common.h\\\"\\n\"\n\t\t\t\"#include \\\"fastpos.h\\\"\\n\\n\"\n\t\t\t\"const uint8_t lzma_fastpos[1 << FASTPOS_BITS] = {\");\n\n\tfor (size_t i = 0; i < (1 << FASTPOS_BITS); ++i) {\n\t\tif (i % 16 == 0)\n\t\t\tprintf(\"\\n\\t\");\n\n\t\tprintf(\"%3u\", (unsigned int)(fastpos[i]));\n\n\t\tif (i != (1 << FASTPOS_BITS) - 1)\n\t\t\tprintf(\",\");\n\t}\n\n\tprintf(\"\\n};\\n\");\n\n\treturn 0;\n}\n"
  },
  {
    "path": "external/xz/liblzma/lzma/lzma2_decoder.c",
    "content": "///////////////////////////////////////////////////////////////////////////////\n//\n/// \\file       lzma2_decoder.c\n/// \\brief      LZMA2 decoder\n///\n//  Authors:    Igor Pavlov\n//              Lasse Collin\n//\n//  This file has been put into the public domain.\n//  You can do whatever you want with this file.\n//\n///////////////////////////////////////////////////////////////////////////////\n\n#include \"lzma2_decoder.h\"\n#include \"lz_decoder.h\"\n#include \"lzma_decoder.h\"\n\n\ntypedef struct {\n\tenum sequence {\n\t\tSEQ_CONTROL,\n\t\tSEQ_UNCOMPRESSED_1,\n\t\tSEQ_UNCOMPRESSED_2,\n\t\tSEQ_COMPRESSED_0,\n\t\tSEQ_COMPRESSED_1,\n\t\tSEQ_PROPERTIES,\n\t\tSEQ_LZMA,\n\t\tSEQ_COPY,\n\t} sequence;\n\n\t/// Sequence after the size fields have been decoded.\n\tenum sequence next_sequence;\n\n\t/// LZMA decoder\n\tlzma_lz_decoder lzma;\n\n\t/// Uncompressed size of LZMA chunk\n\tsize_t uncompressed_size;\n\n\t/// Compressed size of the chunk (naturally equals to uncompressed\n\t/// size of uncompressed chunk)\n\tsize_t compressed_size;\n\n\t/// True if properties are needed. This is false before the\n\t/// first LZMA chunk.\n\tbool need_properties;\n\n\t/// True if dictionary reset is needed. This is false before the\n\t/// first chunk (LZMA or uncompressed).\n\tbool need_dictionary_reset;\n\n\tlzma_options_lzma options;\n} lzma_lzma2_coder;\n\n\nstatic lzma_ret\nlzma2_decode(void *coder_ptr, lzma_dict *restrict dict,\n\t\tconst uint8_t *restrict in, size_t *restrict in_pos,\n\t\tsize_t in_size)\n{\n\tlzma_lzma2_coder *restrict coder = coder_ptr;\n\n\t// With SEQ_LZMA it is possible that no new input is needed to do\n\t// some progress. The rest of the sequences assume that there is\n\t// at least one byte of input.\n\twhile (*in_pos < in_size || coder->sequence == SEQ_LZMA)\n\tswitch (coder->sequence) {\n\tcase SEQ_CONTROL: {\n\t\tconst uint32_t control = in[*in_pos];\n\t\t++*in_pos;\n\n\t\t// End marker\n\t\tif (control == 0x00)\n\t\t\treturn LZMA_STREAM_END;\n\n\t\tif (control >= 0xE0 || control == 1) {\n\t\t\t// Dictionary reset implies that next LZMA chunk has\n\t\t\t// to set new properties.\n\t\t\tcoder->need_properties = true;\n\t\t\tcoder->need_dictionary_reset = true;\n\t\t} else if (coder->need_dictionary_reset) {\n\t\t\treturn LZMA_DATA_ERROR;\n\t\t}\n\n\t\tif (control >= 0x80) {\n\t\t\t// LZMA chunk. The highest five bits of the\n\t\t\t// uncompressed size are taken from the control byte.\n\t\t\tcoder->uncompressed_size = (control & 0x1F) << 16;\n\t\t\tcoder->sequence = SEQ_UNCOMPRESSED_1;\n\n\t\t\t// See if there are new properties or if we need to\n\t\t\t// reset the state.\n\t\t\tif (control >= 0xC0) {\n\t\t\t\t// When there are new properties, state reset\n\t\t\t\t// is done at SEQ_PROPERTIES.\n\t\t\t\tcoder->need_properties = false;\n\t\t\t\tcoder->next_sequence = SEQ_PROPERTIES;\n\n\t\t\t} else if (coder->need_properties) {\n\t\t\t\treturn LZMA_DATA_ERROR;\n\n\t\t\t} else {\n\t\t\t\tcoder->next_sequence = SEQ_LZMA;\n\n\t\t\t\t// If only state reset is wanted with old\n\t\t\t\t// properties, do the resetting here for\n\t\t\t\t// simplicity.\n\t\t\t\tif (control >= 0xA0)\n\t\t\t\t\tcoder->lzma.reset(coder->lzma.coder,\n\t\t\t\t\t\t\t&coder->options);\n\t\t\t}\n\t\t} else {\n\t\t\t// Invalid control values\n\t\t\tif (control > 2)\n\t\t\t\treturn LZMA_DATA_ERROR;\n\n\t\t\t// It's uncompressed chunk\n\t\t\tcoder->sequence = SEQ_COMPRESSED_0;\n\t\t\tcoder->next_sequence = SEQ_COPY;\n\t\t}\n\n\t\tif (coder->need_dictionary_reset) {\n\t\t\t// Finish the dictionary reset and let the caller\n\t\t\t// flush the dictionary to the actual output buffer.\n\t\t\tcoder->need_dictionary_reset = false;\n\t\t\tdict_reset(dict);\n\t\t\treturn LZMA_OK;\n\t\t}\n\n\t\tbreak;\n\t}\n\n\tcase SEQ_UNCOMPRESSED_1:\n\t\tcoder->uncompressed_size += (uint32_t)(in[(*in_pos)++]) << 8;\n\t\tcoder->sequence = SEQ_UNCOMPRESSED_2;\n\t\tbreak;\n\n\tcase SEQ_UNCOMPRESSED_2:\n\t\tcoder->uncompressed_size += in[(*in_pos)++] + 1U;\n\t\tcoder->sequence = SEQ_COMPRESSED_0;\n\t\tcoder->lzma.set_uncompressed(coder->lzma.coder,\n\t\t\t\tcoder->uncompressed_size);\n\t\tbreak;\n\n\tcase SEQ_COMPRESSED_0:\n\t\tcoder->compressed_size = (uint32_t)(in[(*in_pos)++]) << 8;\n\t\tcoder->sequence = SEQ_COMPRESSED_1;\n\t\tbreak;\n\n\tcase SEQ_COMPRESSED_1:\n\t\tcoder->compressed_size += in[(*in_pos)++] + 1U;\n\t\tcoder->sequence = coder->next_sequence;\n\t\tbreak;\n\n\tcase SEQ_PROPERTIES:\n\t\tif (lzma_lzma_lclppb_decode(&coder->options, in[(*in_pos)++]))\n\t\t\treturn LZMA_DATA_ERROR;\n\n\t\tcoder->lzma.reset(coder->lzma.coder, &coder->options);\n\n\t\tcoder->sequence = SEQ_LZMA;\n\t\tbreak;\n\n\tcase SEQ_LZMA: {\n\t\t// Store the start offset so that we can update\n\t\t// coder->compressed_size later.\n\t\tconst size_t in_start = *in_pos;\n\n\t\t// Decode from in[] to *dict.\n\t\tconst lzma_ret ret = coder->lzma.code(coder->lzma.coder,\n\t\t\t\tdict, in, in_pos, in_size);\n\n\t\t// Validate and update coder->compressed_size.\n\t\tconst size_t in_used = *in_pos - in_start;\n\t\tif (in_used > coder->compressed_size)\n\t\t\treturn LZMA_DATA_ERROR;\n\n\t\tcoder->compressed_size -= in_used;\n\n\t\t// Return if we didn't finish the chunk, or an error occurred.\n\t\tif (ret != LZMA_STREAM_END)\n\t\t\treturn ret;\n\n\t\t// The LZMA decoder must have consumed the whole chunk now.\n\t\t// We don't need to worry about uncompressed size since it\n\t\t// is checked by the LZMA decoder.\n\t\tif (coder->compressed_size != 0)\n\t\t\treturn LZMA_DATA_ERROR;\n\n\t\tcoder->sequence = SEQ_CONTROL;\n\t\tbreak;\n\t}\n\n\tcase SEQ_COPY: {\n\t\t// Copy from input to the dictionary as is.\n\t\tdict_write(dict, in, in_pos, in_size, &coder->compressed_size);\n\t\tif (coder->compressed_size != 0)\n\t\t\treturn LZMA_OK;\n\n\t\tcoder->sequence = SEQ_CONTROL;\n\t\tbreak;\n\t}\n\n\tdefault:\n\t\tassert(0);\n\t\treturn LZMA_PROG_ERROR;\n\t}\n\n\treturn LZMA_OK;\n}\n\n\nstatic void\nlzma2_decoder_end(void *coder_ptr, const lzma_allocator *allocator)\n{\n\tlzma_lzma2_coder *coder = coder_ptr;\n\n\tassert(coder->lzma.end == NULL);\n\tlzma_free(coder->lzma.coder, allocator);\n\n\tlzma_free(coder, allocator);\n\n\treturn;\n}\n\n\nstatic lzma_ret\nlzma2_decoder_init(lzma_lz_decoder *lz, const lzma_allocator *allocator,\n\t\tconst void *opt, lzma_lz_options *lz_options)\n{\n\tlzma_lzma2_coder *coder = lz->coder;\n\tif (coder == NULL) {\n\t\tcoder = lzma_alloc(sizeof(lzma_lzma2_coder), allocator);\n\t\tif (coder == NULL)\n\t\t\treturn LZMA_MEM_ERROR;\n\n\t\tlz->coder = coder;\n\t\tlz->code = &lzma2_decode;\n\t\tlz->end = &lzma2_decoder_end;\n\n\t\tcoder->lzma = LZMA_LZ_DECODER_INIT;\n\t}\n\n\tconst lzma_options_lzma *options = opt;\n\n\tcoder->sequence = SEQ_CONTROL;\n\tcoder->need_properties = true;\n\tcoder->need_dictionary_reset = options->preset_dict == NULL\n\t\t\t|| options->preset_dict_size == 0;\n\n\treturn lzma_lzma_decoder_create(&coder->lzma,\n\t\t\tallocator, options, lz_options);\n}\n\n\nextern lzma_ret\nlzma_lzma2_decoder_init(lzma_next_coder *next, const lzma_allocator *allocator,\n\t\tconst lzma_filter_info *filters)\n{\n\t// LZMA2 can only be the last filter in the chain. This is enforced\n\t// by the raw_decoder initialization.\n\tassert(filters[1].init == NULL);\n\n\treturn lzma_lz_decoder_init(next, allocator, filters,\n\t\t\t&lzma2_decoder_init);\n}\n\n\nextern uint64_t\nlzma_lzma2_decoder_memusage(const void *options)\n{\n\treturn sizeof(lzma_lzma2_coder)\n\t\t\t+ lzma_lzma_decoder_memusage_nocheck(options);\n}\n\n\nextern lzma_ret\nlzma_lzma2_props_decode(void **options, const lzma_allocator *allocator,\n\t\tconst uint8_t *props, size_t props_size)\n{\n\tif (props_size != 1)\n\t\treturn LZMA_OPTIONS_ERROR;\n\n\t// Check that reserved bits are unset.\n\tif (props[0] & 0xC0)\n\t\treturn LZMA_OPTIONS_ERROR;\n\n\t// Decode the dictionary size.\n\tif (props[0] > 40)\n\t\treturn LZMA_OPTIONS_ERROR;\n\n\tlzma_options_lzma *opt = lzma_alloc(\n\t\t\tsizeof(lzma_options_lzma), allocator);\n\tif (opt == NULL)\n\t\treturn LZMA_MEM_ERROR;\n\n\tif (props[0] == 40) {\n\t\topt->dict_size = UINT32_MAX;\n\t} else {\n\t\topt->dict_size = 2 | (props[0] & 1U);\n\t\topt->dict_size <<= props[0] / 2U + 11;\n\t}\n\n\topt->preset_dict = NULL;\n\topt->preset_dict_size = 0;\n\n\t*options = opt;\n\n\treturn LZMA_OK;\n}\n"
  },
  {
    "path": "external/xz/liblzma/lzma/lzma2_decoder.h",
    "content": "///////////////////////////////////////////////////////////////////////////////\n//\n/// \\file       lzma2_decoder.h\n/// \\brief      LZMA2 decoder\n///\n//  Authors:    Igor Pavlov\n//              Lasse Collin\n//\n//  This file has been put into the public domain.\n//  You can do whatever you want with this file.\n//\n///////////////////////////////////////////////////////////////////////////////\n\n#ifndef LZMA_LZMA2_DECODER_H\n#define LZMA_LZMA2_DECODER_H\n\n#include \"common.h\"\n\nextern lzma_ret lzma_lzma2_decoder_init(lzma_next_coder *next,\n\t\tconst lzma_allocator *allocator,\n\t\tconst lzma_filter_info *filters);\n\nextern uint64_t lzma_lzma2_decoder_memusage(const void *options);\n\nextern lzma_ret lzma_lzma2_props_decode(\n\t\tvoid **options, const lzma_allocator *allocator,\n\t\tconst uint8_t *props, size_t props_size);\n\n#endif\n"
  },
  {
    "path": "external/xz/liblzma/lzma/lzma2_encoder.c",
    "content": "///////////////////////////////////////////////////////////////////////////////\n//\n/// \\file       lzma2_encoder.c\n/// \\brief      LZMA2 encoder\n///\n//  Authors:    Igor Pavlov\n//              Lasse Collin\n//\n//  This file has been put into the public domain.\n//  You can do whatever you want with this file.\n//\n///////////////////////////////////////////////////////////////////////////////\n\n#include \"lz_encoder.h\"\n#include \"lzma_encoder.h\"\n#include \"fastpos.h\"\n#include \"lzma2_encoder.h\"\n\n\ntypedef struct {\n\tenum {\n\t\tSEQ_INIT,\n\t\tSEQ_LZMA_ENCODE,\n\t\tSEQ_LZMA_COPY,\n\t\tSEQ_UNCOMPRESSED_HEADER,\n\t\tSEQ_UNCOMPRESSED_COPY,\n\t} sequence;\n\n\t/// LZMA encoder\n\tvoid *lzma;\n\n\t/// LZMA options currently in use.\n\tlzma_options_lzma opt_cur;\n\n\tbool need_properties;\n\tbool need_state_reset;\n\tbool need_dictionary_reset;\n\n\t/// Uncompressed size of a chunk\n\tsize_t uncompressed_size;\n\n\t/// Compressed size of a chunk (excluding headers); this is also used\n\t/// to indicate the end of buf[] in SEQ_LZMA_COPY.\n\tsize_t compressed_size;\n\n\t/// Read position in buf[]\n\tsize_t buf_pos;\n\n\t/// Buffer to hold the chunk header and LZMA compressed data\n\tuint8_t buf[LZMA2_HEADER_MAX + LZMA2_CHUNK_MAX];\n} lzma_lzma2_coder;\n\n\nstatic void\nlzma2_header_lzma(lzma_lzma2_coder *coder)\n{\n\tassert(coder->uncompressed_size > 0);\n\tassert(coder->uncompressed_size <= LZMA2_UNCOMPRESSED_MAX);\n\tassert(coder->compressed_size > 0);\n\tassert(coder->compressed_size <= LZMA2_CHUNK_MAX);\n\n\tsize_t pos;\n\n\tif (coder->need_properties) {\n\t\tpos = 0;\n\n\t\tif (coder->need_dictionary_reset)\n\t\t\tcoder->buf[pos] = 0x80 + (3 << 5);\n\t\telse\n\t\t\tcoder->buf[pos] = 0x80 + (2 << 5);\n\t} else {\n\t\tpos = 1;\n\n\t\tif (coder->need_state_reset)\n\t\t\tcoder->buf[pos] = 0x80 + (1 << 5);\n\t\telse\n\t\t\tcoder->buf[pos] = 0x80;\n\t}\n\n\t// Set the start position for copying.\n\tcoder->buf_pos = pos;\n\n\t// Uncompressed size\n\tsize_t size = coder->uncompressed_size - 1;\n\tcoder->buf[pos++] += size >> 16;\n\tcoder->buf[pos++] = (size >> 8) & 0xFF;\n\tcoder->buf[pos++] = size & 0xFF;\n\n\t// Compressed size\n\tsize = coder->compressed_size - 1;\n\tcoder->buf[pos++] = size >> 8;\n\tcoder->buf[pos++] = size & 0xFF;\n\n\t// Properties, if needed\n\tif (coder->need_properties)\n\t\tlzma_lzma_lclppb_encode(&coder->opt_cur, coder->buf + pos);\n\n\tcoder->need_properties = false;\n\tcoder->need_state_reset = false;\n\tcoder->need_dictionary_reset = false;\n\n\t// The copying code uses coder->compressed_size to indicate the end\n\t// of coder->buf[], so we need add the maximum size of the header here.\n\tcoder->compressed_size += LZMA2_HEADER_MAX;\n\n\treturn;\n}\n\n\nstatic void\nlzma2_header_uncompressed(lzma_lzma2_coder *coder)\n{\n\tassert(coder->uncompressed_size > 0);\n\tassert(coder->uncompressed_size <= LZMA2_CHUNK_MAX);\n\n\t// If this is the first chunk, we need to include dictionary\n\t// reset indicator.\n\tif (coder->need_dictionary_reset)\n\t\tcoder->buf[0] = 1;\n\telse\n\t\tcoder->buf[0] = 2;\n\n\tcoder->need_dictionary_reset = false;\n\n\t// \"Compressed\" size\n\tcoder->buf[1] = (coder->uncompressed_size - 1) >> 8;\n\tcoder->buf[2] = (coder->uncompressed_size - 1) & 0xFF;\n\n\t// Set the start position for copying.\n\tcoder->buf_pos = 0;\n\treturn;\n}\n\n\nstatic lzma_ret\nlzma2_encode(void *coder_ptr, lzma_mf *restrict mf,\n\t\tuint8_t *restrict out, size_t *restrict out_pos,\n\t\tsize_t out_size)\n{\n\tlzma_lzma2_coder *restrict coder = coder_ptr;\n\n\twhile (*out_pos < out_size)\n\tswitch (coder->sequence) {\n\tcase SEQ_INIT:\n\t\t// If there's no input left and we are flushing or finishing,\n\t\t// don't start a new chunk.\n\t\tif (mf_unencoded(mf) == 0) {\n\t\t\t// Write end of payload marker if finishing.\n\t\t\tif (mf->action == LZMA_FINISH)\n\t\t\t\tout[(*out_pos)++] = 0;\n\n\t\t\treturn mf->action == LZMA_RUN\n\t\t\t\t\t? LZMA_OK : LZMA_STREAM_END;\n\t\t}\n\n\t\tif (coder->need_state_reset)\n\t\t\treturn_if_error(lzma_lzma_encoder_reset(\n\t\t\t\t\tcoder->lzma, &coder->opt_cur));\n\n\t\tcoder->uncompressed_size = 0;\n\t\tcoder->compressed_size = 0;\n\t\tcoder->sequence = SEQ_LZMA_ENCODE;\n\n\t// Fall through\n\n\tcase SEQ_LZMA_ENCODE: {\n\t\t// Calculate how much more uncompressed data this chunk\n\t\t// could accept.\n\t\tconst uint32_t left = LZMA2_UNCOMPRESSED_MAX\n\t\t\t\t- coder->uncompressed_size;\n\t\tuint32_t limit;\n\n\t\tif (left < mf->match_len_max) {\n\t\t\t// Must flush immediately since the next LZMA symbol\n\t\t\t// could make the uncompressed size of the chunk too\n\t\t\t// big.\n\t\t\tlimit = 0;\n\t\t} else {\n\t\t\t// Calculate maximum read_limit that is OK from point\n\t\t\t// of view of LZMA2 chunk size.\n\t\t\tlimit = mf->read_pos - mf->read_ahead\n\t\t\t\t\t+ left - mf->match_len_max;\n\t\t}\n\n\t\t// Save the start position so that we can update\n\t\t// coder->uncompressed_size.\n\t\tconst uint32_t read_start = mf->read_pos - mf->read_ahead;\n\n\t\t// Call the LZMA encoder until the chunk is finished.\n\t\tconst lzma_ret ret = lzma_lzma_encode(coder->lzma, mf,\n\t\t\t\tcoder->buf + LZMA2_HEADER_MAX,\n\t\t\t\t&coder->compressed_size,\n\t\t\t\tLZMA2_CHUNK_MAX, limit);\n\n\t\tcoder->uncompressed_size += mf->read_pos - mf->read_ahead\n\t\t\t\t- read_start;\n\n\t\tassert(coder->compressed_size <= LZMA2_CHUNK_MAX);\n\t\tassert(coder->uncompressed_size <= LZMA2_UNCOMPRESSED_MAX);\n\n\t\tif (ret != LZMA_STREAM_END)\n\t\t\treturn LZMA_OK;\n\n\t\t// See if the chunk compressed. If it didn't, we encode it\n\t\t// as uncompressed chunk. This saves a few bytes of space\n\t\t// and makes decoding faster.\n\t\tif (coder->compressed_size >= coder->uncompressed_size) {\n\t\t\tcoder->uncompressed_size += mf->read_ahead;\n\t\t\tassert(coder->uncompressed_size\n\t\t\t\t\t<= LZMA2_UNCOMPRESSED_MAX);\n\t\t\tmf->read_ahead = 0;\n\t\t\tlzma2_header_uncompressed(coder);\n\t\t\tcoder->need_state_reset = true;\n\t\t\tcoder->sequence = SEQ_UNCOMPRESSED_HEADER;\n\t\t\tbreak;\n\t\t}\n\n\t\t// The chunk did compress at least by one byte, so we store\n\t\t// the chunk as LZMA.\n\t\tlzma2_header_lzma(coder);\n\n\t\tcoder->sequence = SEQ_LZMA_COPY;\n\t}\n\n\t// Fall through\n\n\tcase SEQ_LZMA_COPY:\n\t\t// Copy the compressed chunk along its headers to the\n\t\t// output buffer.\n\t\tlzma_bufcpy(coder->buf, &coder->buf_pos,\n\t\t\t\tcoder->compressed_size,\n\t\t\t\tout, out_pos, out_size);\n\t\tif (coder->buf_pos != coder->compressed_size)\n\t\t\treturn LZMA_OK;\n\n\t\tcoder->sequence = SEQ_INIT;\n\t\tbreak;\n\n\tcase SEQ_UNCOMPRESSED_HEADER:\n\t\t// Copy the three-byte header to indicate uncompressed chunk.\n\t\tlzma_bufcpy(coder->buf, &coder->buf_pos,\n\t\t\t\tLZMA2_HEADER_UNCOMPRESSED,\n\t\t\t\tout, out_pos, out_size);\n\t\tif (coder->buf_pos != LZMA2_HEADER_UNCOMPRESSED)\n\t\t\treturn LZMA_OK;\n\n\t\tcoder->sequence = SEQ_UNCOMPRESSED_COPY;\n\n\t// Fall through\n\n\tcase SEQ_UNCOMPRESSED_COPY:\n\t\t// Copy the uncompressed data as is from the dictionary\n\t\t// to the output buffer.\n\t\tmf_read(mf, out, out_pos, out_size, &coder->uncompressed_size);\n\t\tif (coder->uncompressed_size != 0)\n\t\t\treturn LZMA_OK;\n\n\t\tcoder->sequence = SEQ_INIT;\n\t\tbreak;\n\t}\n\n\treturn LZMA_OK;\n}\n\n\nstatic void\nlzma2_encoder_end(void *coder_ptr, const lzma_allocator *allocator)\n{\n\tlzma_lzma2_coder *coder = coder_ptr;\n\tlzma_free(coder->lzma, allocator);\n\tlzma_free(coder, allocator);\n\treturn;\n}\n\n\nstatic lzma_ret\nlzma2_encoder_options_update(void *coder_ptr, const lzma_filter *filter)\n{\n\tlzma_lzma2_coder *coder = coder_ptr;\n\n\t// New options can be set only when there is no incomplete chunk.\n\t// This is the case at the beginning of the raw stream and right\n\t// after LZMA_SYNC_FLUSH.\n\tif (filter->options == NULL || coder->sequence != SEQ_INIT)\n\t\treturn LZMA_PROG_ERROR;\n\n\t// Look if there are new options. At least for now,\n\t// only lc/lp/pb can be changed.\n\tconst lzma_options_lzma *opt = filter->options;\n\tif (coder->opt_cur.lc != opt->lc || coder->opt_cur.lp != opt->lp\n\t\t\t|| coder->opt_cur.pb != opt->pb) {\n\t\t// Validate the options.\n\t\tif (opt->lc > LZMA_LCLP_MAX || opt->lp > LZMA_LCLP_MAX\n\t\t\t\t|| opt->lc + opt->lp > LZMA_LCLP_MAX\n\t\t\t\t|| opt->pb > LZMA_PB_MAX)\n\t\t\treturn LZMA_OPTIONS_ERROR;\n\n\t\t// The new options will be used when the encoder starts\n\t\t// a new LZMA2 chunk.\n\t\tcoder->opt_cur.lc = opt->lc;\n\t\tcoder->opt_cur.lp = opt->lp;\n\t\tcoder->opt_cur.pb = opt->pb;\n\t\tcoder->need_properties = true;\n\t\tcoder->need_state_reset = true;\n\t}\n\n\treturn LZMA_OK;\n}\n\n\nstatic lzma_ret\nlzma2_encoder_init(lzma_lz_encoder *lz, const lzma_allocator *allocator,\n\t\tconst void *options, lzma_lz_options *lz_options)\n{\n\tif (options == NULL)\n\t\treturn LZMA_PROG_ERROR;\n\n\tlzma_lzma2_coder *coder = lz->coder;\n\tif (coder == NULL) {\n\t\tcoder = lzma_alloc(sizeof(lzma_lzma2_coder), allocator);\n\t\tif (coder == NULL)\n\t\t\treturn LZMA_MEM_ERROR;\n\n\t\tlz->coder = coder;\n\t\tlz->code = &lzma2_encode;\n\t\tlz->end = &lzma2_encoder_end;\n\t\tlz->options_update = &lzma2_encoder_options_update;\n\n\t\tcoder->lzma = NULL;\n\t}\n\n\tcoder->opt_cur = *(const lzma_options_lzma *)(options);\n\n\tcoder->sequence = SEQ_INIT;\n\tcoder->need_properties = true;\n\tcoder->need_state_reset = false;\n\tcoder->need_dictionary_reset\n\t\t\t= coder->opt_cur.preset_dict == NULL\n\t\t\t|| coder->opt_cur.preset_dict_size == 0;\n\n\t// Initialize LZMA encoder\n\treturn_if_error(lzma_lzma_encoder_create(&coder->lzma, allocator,\n\t\t\t&coder->opt_cur, lz_options));\n\n\t// Make sure that we will always have enough history available in\n\t// case we need to use uncompressed chunks. They are used when the\n\t// compressed size of a chunk is not smaller than the uncompressed\n\t// size, so we need to have at least LZMA2_COMPRESSED_MAX bytes\n\t// history available.\n\tif (lz_options->before_size + lz_options->dict_size < LZMA2_CHUNK_MAX)\n\t\tlz_options->before_size\n\t\t\t\t= LZMA2_CHUNK_MAX - lz_options->dict_size;\n\n\treturn LZMA_OK;\n}\n\n\nextern lzma_ret\nlzma_lzma2_encoder_init(lzma_next_coder *next, const lzma_allocator *allocator,\n\t\tconst lzma_filter_info *filters)\n{\n\treturn lzma_lz_encoder_init(\n\t\t\tnext, allocator, filters, &lzma2_encoder_init);\n}\n\n\nextern uint64_t\nlzma_lzma2_encoder_memusage(const void *options)\n{\n\tconst uint64_t lzma_mem = lzma_lzma_encoder_memusage(options);\n\tif (lzma_mem == UINT64_MAX)\n\t\treturn UINT64_MAX;\n\n\treturn sizeof(lzma_lzma2_coder) + lzma_mem;\n}\n\n\nextern lzma_ret\nlzma_lzma2_props_encode(const void *options, uint8_t *out)\n{\n\tconst lzma_options_lzma *const opt = options;\n\tuint32_t d = my_max(opt->dict_size, LZMA_DICT_SIZE_MIN);\n\n\t// Round up to the next 2^n - 1 or 2^n + 2^(n - 1) - 1 depending\n\t// on which one is the next:\n\t--d;\n\td |= d >> 2;\n\td |= d >> 3;\n\td |= d >> 4;\n\td |= d >> 8;\n\td |= d >> 16;\n\n\t// Get the highest two bits using the proper encoding:\n\tif (d == UINT32_MAX)\n\t\tout[0] = 40;\n\telse\n\t\tout[0] = get_dist_slot(d + 1) - 24;\n\n\treturn LZMA_OK;\n}\n\n\nextern uint64_t\nlzma_lzma2_block_size(const void *options)\n{\n\tconst lzma_options_lzma *const opt = options;\n\n\t// Use at least 1 MiB to keep compression ratio better.\n\treturn my_max((uint64_t)(opt->dict_size) * 3, UINT64_C(1) << 20);\n}\n"
  },
  {
    "path": "external/xz/liblzma/lzma/lzma2_encoder.h",
    "content": "///////////////////////////////////////////////////////////////////////////////\n//\n/// \\file       lzma2_encoder.h\n/// \\brief      LZMA2 encoder\n///\n//  Authors:    Igor Pavlov\n//              Lasse Collin\n//\n//  This file has been put into the public domain.\n//  You can do whatever you want with this file.\n//\n///////////////////////////////////////////////////////////////////////////////\n\n#ifndef LZMA_LZMA2_ENCODER_H\n#define LZMA_LZMA2_ENCODER_H\n\n#include \"common.h\"\n\n\n/// Maximum number of bytes of actual data per chunk (no headers)\n#define LZMA2_CHUNK_MAX (UINT32_C(1) << 16)\n\n/// Maximum uncompressed size of LZMA chunk (no headers)\n#define LZMA2_UNCOMPRESSED_MAX (UINT32_C(1) << 21)\n\n/// Maximum size of LZMA2 headers\n#define LZMA2_HEADER_MAX 6\n\n/// Size of a header for uncompressed chunk\n#define LZMA2_HEADER_UNCOMPRESSED 3\n\n\nextern lzma_ret lzma_lzma2_encoder_init(\n\t\tlzma_next_coder *next, const lzma_allocator *allocator,\n\t\tconst lzma_filter_info *filters);\n\nextern uint64_t lzma_lzma2_encoder_memusage(const void *options);\n\nextern lzma_ret lzma_lzma2_props_encode(const void *options, uint8_t *out);\n\nextern uint64_t lzma_lzma2_block_size(const void *options);\n\n#endif\n"
  },
  {
    "path": "external/xz/liblzma/lzma/lzma_common.h",
    "content": "///////////////////////////////////////////////////////////////////////////////\n//\n/// \\file       lzma_common.h\n/// \\brief      Private definitions common to LZMA encoder and decoder\n///\n//  Authors:    Igor Pavlov\n//              Lasse Collin\n//\n//  This file has been put into the public domain.\n//  You can do whatever you want with this file.\n//\n///////////////////////////////////////////////////////////////////////////////\n\n#ifndef LZMA_LZMA_COMMON_H\n#define LZMA_LZMA_COMMON_H\n\n#include \"common.h\"\n#include \"range_common.h\"\n\n\n///////////////////\n// Miscellaneous //\n///////////////////\n\n/// Maximum number of position states. A position state is the lowest pos bits\n/// number of bits of the current uncompressed offset. In some places there\n/// are different sets of probabilities for different pos states.\n#define POS_STATES_MAX (1 << LZMA_PB_MAX)\n\n\n/// Validates lc, lp, and pb.\nstatic inline bool\nis_lclppb_valid(const lzma_options_lzma *options)\n{\n\treturn options->lc <= LZMA_LCLP_MAX && options->lp <= LZMA_LCLP_MAX\n\t\t\t&& options->lc + options->lp <= LZMA_LCLP_MAX\n\t\t\t&& options->pb <= LZMA_PB_MAX;\n}\n\n\n///////////\n// State //\n///////////\n\n/// This enum is used to track which events have occurred most recently and\n/// in which order. This information is used to predict the next event.\n///\n/// Events:\n///  - Literal: One 8-bit byte\n///  - Match: Repeat a chunk of data at some distance\n///  - Long repeat: Multi-byte match at a recently seen distance\n///  - Short repeat: One-byte repeat at a recently seen distance\n///\n/// The event names are in from STATE_oldest_older_previous. REP means\n/// either short or long repeated match, and NONLIT means any non-literal.\ntypedef enum {\n\tSTATE_LIT_LIT,\n\tSTATE_MATCH_LIT_LIT,\n\tSTATE_REP_LIT_LIT,\n\tSTATE_SHORTREP_LIT_LIT,\n\tSTATE_MATCH_LIT,\n\tSTATE_REP_LIT,\n\tSTATE_SHORTREP_LIT,\n\tSTATE_LIT_MATCH,\n\tSTATE_LIT_LONGREP,\n\tSTATE_LIT_SHORTREP,\n\tSTATE_NONLIT_MATCH,\n\tSTATE_NONLIT_REP,\n} lzma_lzma_state;\n\n\n/// Total number of states\n#define STATES 12\n\n/// The lowest 7 states indicate that the previous state was a literal.\n#define LIT_STATES 7\n\n\n/// Indicate that the latest state was a literal.\n#define update_literal(state) \\\n\tstate = ((state) <= STATE_SHORTREP_LIT_LIT \\\n\t\t\t? STATE_LIT_LIT \\\n\t\t\t: ((state) <= STATE_LIT_SHORTREP \\\n\t\t\t\t? (state) - 3 \\\n\t\t\t\t: (state) - 6))\n\n/// Indicate that the latest state was a match.\n#define update_match(state) \\\n\tstate = ((state) < LIT_STATES ? STATE_LIT_MATCH : STATE_NONLIT_MATCH)\n\n/// Indicate that the latest state was a long repeated match.\n#define update_long_rep(state) \\\n\tstate = ((state) < LIT_STATES ? STATE_LIT_LONGREP : STATE_NONLIT_REP)\n\n/// Indicate that the latest state was a short match.\n#define update_short_rep(state) \\\n\tstate = ((state) < LIT_STATES ? STATE_LIT_SHORTREP : STATE_NONLIT_REP)\n\n/// Test if the previous state was a literal.\n#define is_literal_state(state) \\\n\t((state) < LIT_STATES)\n\n\n/////////////\n// Literal //\n/////////////\n\n/// Each literal coder is divided in three sections:\n///   - 0x001-0x0FF: Without match byte\n///   - 0x101-0x1FF: With match byte; match bit is 0\n///   - 0x201-0x2FF: With match byte; match bit is 1\n///\n/// Match byte is used when the previous LZMA symbol was something else than\n/// a literal (that is, it was some kind of match).\n#define LITERAL_CODER_SIZE 0x300\n\n/// Maximum number of literal coders\n#define LITERAL_CODERS_MAX (1 << LZMA_LCLP_MAX)\n\n/// Locate the literal coder for the next literal byte. The choice depends on\n///   - the lowest literal_pos_bits bits of the position of the current\n///     byte; and\n///   - the highest literal_context_bits bits of the previous byte.\n#define literal_subcoder(probs, lc, lp_mask, pos, prev_byte) \\\n\t((probs)[(((pos) & (lp_mask)) << (lc)) \\\n\t\t\t+ ((uint32_t)(prev_byte) >> (8U - (lc)))])\n\n\nstatic inline void\nliteral_init(probability (*probs)[LITERAL_CODER_SIZE],\n\t\tuint32_t lc, uint32_t lp)\n{\n\tassert(lc + lp <= LZMA_LCLP_MAX);\n\n\tconst uint32_t coders = 1U << (lc + lp);\n\n\tfor (uint32_t i = 0; i < coders; ++i)\n\t\tfor (uint32_t j = 0; j < LITERAL_CODER_SIZE; ++j)\n\t\t\tbit_reset(probs[i][j]);\n\n\treturn;\n}\n\n\n//////////////////\n// Match length //\n//////////////////\n\n// Minimum length of a match is two bytes.\n#define MATCH_LEN_MIN 2\n\n// Match length is encoded with 4, 5, or 10 bits.\n//\n// Length   Bits\n//  2-9      4 = Choice=0 + 3 bits\n// 10-17     5 = Choice=1 + Choice2=0 + 3 bits\n// 18-273   10 = Choice=1 + Choice2=1 + 8 bits\n#define LEN_LOW_BITS 3\n#define LEN_LOW_SYMBOLS (1 << LEN_LOW_BITS)\n#define LEN_MID_BITS 3\n#define LEN_MID_SYMBOLS (1 << LEN_MID_BITS)\n#define LEN_HIGH_BITS 8\n#define LEN_HIGH_SYMBOLS (1 << LEN_HIGH_BITS)\n#define LEN_SYMBOLS (LEN_LOW_SYMBOLS + LEN_MID_SYMBOLS + LEN_HIGH_SYMBOLS)\n\n// Maximum length of a match is 273 which is a result of the encoding\n// described above.\n#define MATCH_LEN_MAX (MATCH_LEN_MIN + LEN_SYMBOLS - 1)\n\n\n////////////////////\n// Match distance //\n////////////////////\n\n// Different sets of probabilities are used for match distances that have very\n// short match length: Lengths of 2, 3, and 4 bytes have a separate set of\n// probabilities for each length. The matches with longer length use a shared\n// set of probabilities.\n#define DIST_STATES 4\n\n// Macro to get the index of the appropriate probability array.\n#define get_dist_state(len) \\\n\t((len) < DIST_STATES + MATCH_LEN_MIN \\\n\t\t? (len) - MATCH_LEN_MIN \\\n\t\t: DIST_STATES - 1)\n\n// The highest two bits of a match distance (distance slot) are encoded\n// using six bits. See fastpos.h for more explanation.\n#define DIST_SLOT_BITS 6\n#define DIST_SLOTS (1 << DIST_SLOT_BITS)\n\n// Match distances up to 127 are fully encoded using probabilities. Since\n// the highest two bits (distance slot) are always encoded using six bits,\n// the distances 0-3 don't need any additional bits to encode, since the\n// distance slot itself is the same as the actual distance. DIST_MODEL_START\n// indicates the first distance slot where at least one additional bit is\n// needed.\n#define DIST_MODEL_START 4\n\n// Match distances greater than 127 are encoded in three pieces:\n//   - distance slot: the highest two bits\n//   - direct bits: 2-26 bits below the highest two bits\n//   - alignment bits: four lowest bits\n//\n// Direct bits don't use any probabilities.\n//\n// The distance slot value of 14 is for distances 128-191 (see the table in\n// fastpos.h to understand why).\n#define DIST_MODEL_END 14\n\n// Distance slots that indicate a distance <= 127.\n#define FULL_DISTANCES_BITS (DIST_MODEL_END / 2)\n#define FULL_DISTANCES (1 << FULL_DISTANCES_BITS)\n\n// For match distances greater than 127, only the highest two bits and the\n// lowest four bits (alignment) is encoded using probabilities.\n#define ALIGN_BITS 4\n#define ALIGN_SIZE (1 << ALIGN_BITS)\n#define ALIGN_MASK (ALIGN_SIZE - 1)\n\n// LZMA remembers the four most recent match distances. Reusing these distances\n// tends to take less space than re-encoding the actual distance value.\n#define REPS 4\n\n#endif\n"
  },
  {
    "path": "external/xz/liblzma/lzma/lzma_decoder.c",
    "content": "///////////////////////////////////////////////////////////////////////////////\n//\n/// \\file       lzma_decoder.c\n/// \\brief      LZMA decoder\n///\n//  Authors:    Igor Pavlov\n//              Lasse Collin\n//\n//  This file has been put into the public domain.\n//  You can do whatever you want with this file.\n//\n///////////////////////////////////////////////////////////////////////////////\n\n#include \"lz_decoder.h\"\n#include \"lzma_common.h\"\n#include \"lzma_decoder.h\"\n#include \"range_decoder.h\"\n\n// The macros unroll loops with switch statements.\n// Silence warnings about missing fall-through comments.\n#if TUKLIB_GNUC_REQ(7, 0)\n#\tpragma GCC diagnostic ignored \"-Wimplicit-fallthrough\"\n#endif\n\n\n#ifdef HAVE_SMALL\n\n// Macros for (somewhat) size-optimized code.\n#define seq_4(seq) seq\n\n#define seq_6(seq) seq\n\n#define seq_8(seq) seq\n\n#define seq_len(seq) \\\n\tseq ## _CHOICE, \\\n\tseq ## _CHOICE2, \\\n\tseq ## _BITTREE\n\n#define len_decode(target, ld, pos_state, seq) \\\ndo { \\\ncase seq ## _CHOICE: \\\n\trc_if_0(ld.choice, seq ## _CHOICE) { \\\n\t\trc_update_0(ld.choice); \\\n\t\tprobs = ld.low[pos_state];\\\n\t\tlimit = LEN_LOW_SYMBOLS; \\\n\t\ttarget = MATCH_LEN_MIN; \\\n\t} else { \\\n\t\trc_update_1(ld.choice); \\\ncase seq ## _CHOICE2: \\\n\t\trc_if_0(ld.choice2, seq ## _CHOICE2) { \\\n\t\t\trc_update_0(ld.choice2); \\\n\t\t\tprobs = ld.mid[pos_state]; \\\n\t\t\tlimit = LEN_MID_SYMBOLS; \\\n\t\t\ttarget = MATCH_LEN_MIN + LEN_LOW_SYMBOLS; \\\n\t\t} else { \\\n\t\t\trc_update_1(ld.choice2); \\\n\t\t\tprobs = ld.high; \\\n\t\t\tlimit = LEN_HIGH_SYMBOLS; \\\n\t\t\ttarget = MATCH_LEN_MIN + LEN_LOW_SYMBOLS \\\n\t\t\t\t\t+ LEN_MID_SYMBOLS; \\\n\t\t} \\\n\t} \\\n\tsymbol = 1; \\\ncase seq ## _BITTREE: \\\n\tdo { \\\n\t\trc_bit(probs[symbol], , , seq ## _BITTREE); \\\n\t} while (symbol < limit); \\\n\ttarget += symbol - limit; \\\n} while (0)\n\n#else // HAVE_SMALL\n\n// Unrolled versions\n#define seq_4(seq) \\\n\tseq ## 0, \\\n\tseq ## 1, \\\n\tseq ## 2, \\\n\tseq ## 3\n\n#define seq_6(seq) \\\n\tseq ## 0, \\\n\tseq ## 1, \\\n\tseq ## 2, \\\n\tseq ## 3, \\\n\tseq ## 4, \\\n\tseq ## 5\n\n#define seq_8(seq) \\\n\tseq ## 0, \\\n\tseq ## 1, \\\n\tseq ## 2, \\\n\tseq ## 3, \\\n\tseq ## 4, \\\n\tseq ## 5, \\\n\tseq ## 6, \\\n\tseq ## 7\n\n#define seq_len(seq) \\\n\tseq ## _CHOICE, \\\n\tseq ## _LOW0, \\\n\tseq ## _LOW1, \\\n\tseq ## _LOW2, \\\n\tseq ## _CHOICE2, \\\n\tseq ## _MID0, \\\n\tseq ## _MID1, \\\n\tseq ## _MID2, \\\n\tseq ## _HIGH0, \\\n\tseq ## _HIGH1, \\\n\tseq ## _HIGH2, \\\n\tseq ## _HIGH3, \\\n\tseq ## _HIGH4, \\\n\tseq ## _HIGH5, \\\n\tseq ## _HIGH6, \\\n\tseq ## _HIGH7\n\n#define len_decode(target, ld, pos_state, seq) \\\ndo { \\\n\tsymbol = 1; \\\ncase seq ## _CHOICE: \\\n\trc_if_0(ld.choice, seq ## _CHOICE) { \\\n\t\trc_update_0(ld.choice); \\\n\t\trc_bit_case(ld.low[pos_state][symbol], , , seq ## _LOW0); \\\n\t\trc_bit_case(ld.low[pos_state][symbol], , , seq ## _LOW1); \\\n\t\trc_bit_case(ld.low[pos_state][symbol], , , seq ## _LOW2); \\\n\t\ttarget = symbol - LEN_LOW_SYMBOLS + MATCH_LEN_MIN; \\\n\t} else { \\\n\t\trc_update_1(ld.choice); \\\ncase seq ## _CHOICE2: \\\n\t\trc_if_0(ld.choice2, seq ## _CHOICE2) { \\\n\t\t\trc_update_0(ld.choice2); \\\n\t\t\trc_bit_case(ld.mid[pos_state][symbol], , , \\\n\t\t\t\t\tseq ## _MID0); \\\n\t\t\trc_bit_case(ld.mid[pos_state][symbol], , , \\\n\t\t\t\t\tseq ## _MID1); \\\n\t\t\trc_bit_case(ld.mid[pos_state][symbol], , , \\\n\t\t\t\t\tseq ## _MID2); \\\n\t\t\ttarget = symbol - LEN_MID_SYMBOLS \\\n\t\t\t\t\t+ MATCH_LEN_MIN + LEN_LOW_SYMBOLS; \\\n\t\t} else { \\\n\t\t\trc_update_1(ld.choice2); \\\n\t\t\trc_bit_case(ld.high[symbol], , , seq ## _HIGH0); \\\n\t\t\trc_bit_case(ld.high[symbol], , , seq ## _HIGH1); \\\n\t\t\trc_bit_case(ld.high[symbol], , , seq ## _HIGH2); \\\n\t\t\trc_bit_case(ld.high[symbol], , , seq ## _HIGH3); \\\n\t\t\trc_bit_case(ld.high[symbol], , , seq ## _HIGH4); \\\n\t\t\trc_bit_case(ld.high[symbol], , , seq ## _HIGH5); \\\n\t\t\trc_bit_case(ld.high[symbol], , , seq ## _HIGH6); \\\n\t\t\trc_bit_case(ld.high[symbol], , , seq ## _HIGH7); \\\n\t\t\ttarget = symbol - LEN_HIGH_SYMBOLS \\\n\t\t\t\t\t+ MATCH_LEN_MIN \\\n\t\t\t\t\t+ LEN_LOW_SYMBOLS + LEN_MID_SYMBOLS; \\\n\t\t} \\\n\t} \\\n} while (0)\n\n#endif // HAVE_SMALL\n\n\n/// Length decoder probabilities; see comments in lzma_common.h.\ntypedef struct {\n\tprobability choice;\n\tprobability choice2;\n\tprobability low[POS_STATES_MAX][LEN_LOW_SYMBOLS];\n\tprobability mid[POS_STATES_MAX][LEN_MID_SYMBOLS];\n\tprobability high[LEN_HIGH_SYMBOLS];\n} lzma_length_decoder;\n\n\ntypedef struct {\n\t///////////////////\n\t// Probabilities //\n\t///////////////////\n\n\t/// Literals; see comments in lzma_common.h.\n\tprobability literal[LITERAL_CODERS_MAX][LITERAL_CODER_SIZE];\n\n\t/// If 1, it's a match. Otherwise it's a single 8-bit literal.\n\tprobability is_match[STATES][POS_STATES_MAX];\n\n\t/// If 1, it's a repeated match. The distance is one of rep0 .. rep3.\n\tprobability is_rep[STATES];\n\n\t/// If 0, distance of a repeated match is rep0.\n\t/// Otherwise check is_rep1.\n\tprobability is_rep0[STATES];\n\n\t/// If 0, distance of a repeated match is rep1.\n\t/// Otherwise check is_rep2.\n\tprobability is_rep1[STATES];\n\n\t/// If 0, distance of a repeated match is rep2. Otherwise it is rep3.\n\tprobability is_rep2[STATES];\n\n\t/// If 1, the repeated match has length of one byte. Otherwise\n\t/// the length is decoded from rep_len_decoder.\n\tprobability is_rep0_long[STATES][POS_STATES_MAX];\n\n\t/// Probability tree for the highest two bits of the match distance.\n\t/// There is a separate probability tree for match lengths of\n\t/// 2 (i.e. MATCH_LEN_MIN), 3, 4, and [5, 273].\n\tprobability dist_slot[DIST_STATES][DIST_SLOTS];\n\n\t/// Probability trees for additional bits for match distance when the\n\t/// distance is in the range [4, 127].\n\tprobability pos_special[FULL_DISTANCES - DIST_MODEL_END];\n\n\t/// Probability tree for the lowest four bits of a match distance\n\t/// that is equal to or greater than 128.\n\tprobability pos_align[ALIGN_SIZE];\n\n\t/// Length of a normal match\n\tlzma_length_decoder match_len_decoder;\n\n\t/// Length of a repeated match\n\tlzma_length_decoder rep_len_decoder;\n\n\t///////////////////\n\t// Decoder state //\n\t///////////////////\n\n\t// Range coder\n\tlzma_range_decoder rc;\n\n\t// Types of the most recently seen LZMA symbols\n\tlzma_lzma_state state;\n\n\tuint32_t rep0;      ///< Distance of the latest match\n\tuint32_t rep1;      ///< Distance of second latest match\n\tuint32_t rep2;      ///< Distance of third latest match\n\tuint32_t rep3;      ///< Distance of fourth latest match\n\n\tuint32_t pos_mask; // (1U << pb) - 1\n\tuint32_t literal_context_bits;\n\tuint32_t literal_pos_mask;\n\n\t/// Uncompressed size as bytes, or LZMA_VLI_UNKNOWN if end of\n\t/// payload marker is expected.\n\tlzma_vli uncompressed_size;\n\n\t////////////////////////////////\n\t// State of incomplete symbol //\n\t////////////////////////////////\n\n\t/// Position where to continue the decoder loop\n\tenum {\n\t\tSEQ_NORMALIZE,\n\t\tSEQ_IS_MATCH,\n\t\tseq_8(SEQ_LITERAL),\n\t\tseq_8(SEQ_LITERAL_MATCHED),\n\t\tSEQ_LITERAL_WRITE,\n\t\tSEQ_IS_REP,\n\t\tseq_len(SEQ_MATCH_LEN),\n\t\tseq_6(SEQ_DIST_SLOT),\n\t\tSEQ_DIST_MODEL,\n\t\tSEQ_DIRECT,\n\t\tseq_4(SEQ_ALIGN),\n\t\tSEQ_EOPM,\n\t\tSEQ_IS_REP0,\n\t\tSEQ_SHORTREP,\n\t\tSEQ_IS_REP0_LONG,\n\t\tSEQ_IS_REP1,\n\t\tSEQ_IS_REP2,\n\t\tseq_len(SEQ_REP_LEN),\n\t\tSEQ_COPY,\n\t} sequence;\n\n\t/// Base of the current probability tree\n\tprobability *probs;\n\n\t/// Symbol being decoded. This is also used as an index variable in\n\t/// bittree decoders: probs[symbol]\n\tuint32_t symbol;\n\n\t/// Used as a loop termination condition on bittree decoders and\n\t/// direct bits decoder.\n\tuint32_t limit;\n\n\t/// Matched literal decoder: 0x100 or 0 to help avoiding branches.\n\t/// Bittree reverse decoders: Offset of the next bit: 1 << offset\n\tuint32_t offset;\n\n\t/// If decoding a literal: match byte.\n\t/// If decoding a match: length of the match.\n\tuint32_t len;\n} lzma_lzma1_decoder;\n\n\nstatic lzma_ret\nlzma_decode(void *coder_ptr, lzma_dict *restrict dictptr,\n\t\tconst uint8_t *restrict in,\n\t\tsize_t *restrict in_pos, size_t in_size)\n{\n\tlzma_lzma1_decoder *restrict coder = coder_ptr;\n\n\t////////////////////\n\t// Initialization //\n\t////////////////////\n\n\t{\n\t\tconst lzma_ret ret = rc_read_init(\n\t\t\t\t&coder->rc, in, in_pos, in_size);\n\t\tif (ret != LZMA_STREAM_END)\n\t\t\treturn ret;\n\t}\n\n\t///////////////\n\t// Variables //\n\t///////////////\n\n\t// Making local copies of often-used variables improves both\n\t// speed and readability.\n\n\tlzma_dict dict = *dictptr;\n\n\tconst size_t dict_start = dict.pos;\n\n\t// Range decoder\n\trc_to_local(coder->rc, *in_pos);\n\n\t// State\n\tuint32_t state = coder->state;\n\tuint32_t rep0 = coder->rep0;\n\tuint32_t rep1 = coder->rep1;\n\tuint32_t rep2 = coder->rep2;\n\tuint32_t rep3 = coder->rep3;\n\n\tconst uint32_t pos_mask = coder->pos_mask;\n\n\t// These variables are actually needed only if we last time ran\n\t// out of input in the middle of the decoder loop.\n\tprobability *probs = coder->probs;\n\tuint32_t symbol = coder->symbol;\n\tuint32_t limit = coder->limit;\n\tuint32_t offset = coder->offset;\n\tuint32_t len = coder->len;\n\n\tconst uint32_t literal_pos_mask = coder->literal_pos_mask;\n\tconst uint32_t literal_context_bits = coder->literal_context_bits;\n\n\t// Temporary variables\n\tuint32_t pos_state = dict.pos & pos_mask;\n\n\tlzma_ret ret = LZMA_OK;\n\n\t// If uncompressed size is known, there must be no end of payload\n\t// marker.\n\tconst bool no_eopm = coder->uncompressed_size\n\t\t\t!= LZMA_VLI_UNKNOWN;\n\tif (no_eopm && coder->uncompressed_size < dict.limit - dict.pos)\n\t\tdict.limit = dict.pos + (size_t)(coder->uncompressed_size);\n\n\t// The main decoder loop. The \"switch\" is used to restart the decoder at\n\t// correct location. Once restarted, the \"switch\" is no longer used.\n\tswitch (coder->sequence)\n\twhile (true) {\n\t\t// Calculate new pos_state. This is skipped on the first loop\n\t\t// since we already calculated it when setting up the local\n\t\t// variables.\n\t\tpos_state = dict.pos & pos_mask;\n\n\tcase SEQ_NORMALIZE:\n\tcase SEQ_IS_MATCH:\n\t\tif (unlikely(no_eopm && dict.pos == dict.limit))\n\t\t\tbreak;\n\n\t\trc_if_0(coder->is_match[state][pos_state], SEQ_IS_MATCH) {\n\t\t\trc_update_0(coder->is_match[state][pos_state]);\n\n\t\t\t// It's a literal i.e. a single 8-bit byte.\n\n\t\t\tprobs = literal_subcoder(coder->literal,\n\t\t\t\t\tliteral_context_bits, literal_pos_mask,\n\t\t\t\t\tdict.pos, dict_get(&dict, 0));\n\t\t\tsymbol = 1;\n\n\t\t\tif (is_literal_state(state)) {\n\t\t\t\t// Decode literal without match byte.\n#ifdef HAVE_SMALL\n\tcase SEQ_LITERAL:\n\t\t\t\tdo {\n\t\t\t\t\trc_bit(probs[symbol], , , SEQ_LITERAL);\n\t\t\t\t} while (symbol < (1 << 8));\n#else\n\t\t\t\trc_bit_case(probs[symbol], , , SEQ_LITERAL0);\n\t\t\t\trc_bit_case(probs[symbol], , , SEQ_LITERAL1);\n\t\t\t\trc_bit_case(probs[symbol], , , SEQ_LITERAL2);\n\t\t\t\trc_bit_case(probs[symbol], , , SEQ_LITERAL3);\n\t\t\t\trc_bit_case(probs[symbol], , , SEQ_LITERAL4);\n\t\t\t\trc_bit_case(probs[symbol], , , SEQ_LITERAL5);\n\t\t\t\trc_bit_case(probs[symbol], , , SEQ_LITERAL6);\n\t\t\t\trc_bit_case(probs[symbol], , , SEQ_LITERAL7);\n#endif\n\t\t\t} else {\n\t\t\t\t// Decode literal with match byte.\n\t\t\t\t//\n\t\t\t\t// We store the byte we compare against\n\t\t\t\t// (\"match byte\") to \"len\" to minimize the\n\t\t\t\t// number of variables we need to store\n\t\t\t\t// between decoder calls.\n\t\t\t\tlen = (uint32_t)(dict_get(&dict, rep0)) << 1;\n\n\t\t\t\t// The usage of \"offset\" allows omitting some\n\t\t\t\t// branches, which should give tiny speed\n\t\t\t\t// improvement on some CPUs. \"offset\" gets\n\t\t\t\t// set to zero if match_bit didn't match.\n\t\t\t\toffset = 0x100;\n\n#ifdef HAVE_SMALL\n\tcase SEQ_LITERAL_MATCHED:\n\t\t\t\tdo {\n\t\t\t\t\tconst uint32_t match_bit\n\t\t\t\t\t\t\t= len & offset;\n\t\t\t\t\tconst uint32_t subcoder_index\n\t\t\t\t\t\t\t= offset + match_bit\n\t\t\t\t\t\t\t+ symbol;\n\n\t\t\t\t\trc_bit(probs[subcoder_index],\n\t\t\t\t\t\t\toffset &= ~match_bit,\n\t\t\t\t\t\t\toffset &= match_bit,\n\t\t\t\t\t\t\tSEQ_LITERAL_MATCHED);\n\n\t\t\t\t\t// It seems to be faster to do this\n\t\t\t\t\t// here instead of putting it to the\n\t\t\t\t\t// beginning of the loop and then\n\t\t\t\t\t// putting the \"case\" in the middle\n\t\t\t\t\t// of the loop.\n\t\t\t\t\tlen <<= 1;\n\n\t\t\t\t} while (symbol < (1 << 8));\n#else\n\t\t\t\t// Unroll the loop.\n\t\t\t\tuint32_t match_bit;\n\t\t\t\tuint32_t subcoder_index;\n\n#\tdefine d(seq) \\\n\t\tcase seq: \\\n\t\t\tmatch_bit = len & offset; \\\n\t\t\tsubcoder_index = offset + match_bit + symbol; \\\n\t\t\trc_bit(probs[subcoder_index], \\\n\t\t\t\t\toffset &= ~match_bit, \\\n\t\t\t\t\toffset &= match_bit, \\\n\t\t\t\t\tseq)\n\n\t\t\t\td(SEQ_LITERAL_MATCHED0);\n\t\t\t\tlen <<= 1;\n\t\t\t\td(SEQ_LITERAL_MATCHED1);\n\t\t\t\tlen <<= 1;\n\t\t\t\td(SEQ_LITERAL_MATCHED2);\n\t\t\t\tlen <<= 1;\n\t\t\t\td(SEQ_LITERAL_MATCHED3);\n\t\t\t\tlen <<= 1;\n\t\t\t\td(SEQ_LITERAL_MATCHED4);\n\t\t\t\tlen <<= 1;\n\t\t\t\td(SEQ_LITERAL_MATCHED5);\n\t\t\t\tlen <<= 1;\n\t\t\t\td(SEQ_LITERAL_MATCHED6);\n\t\t\t\tlen <<= 1;\n\t\t\t\td(SEQ_LITERAL_MATCHED7);\n#\tundef d\n#endif\n\t\t\t}\n\n\t\t\t//update_literal(state);\n\t\t\t// Use a lookup table to update to literal state,\n\t\t\t// since compared to other state updates, this would\n\t\t\t// need two branches.\n\t\t\tstatic const lzma_lzma_state next_state[] = {\n\t\t\t\tSTATE_LIT_LIT,\n\t\t\t\tSTATE_LIT_LIT,\n\t\t\t\tSTATE_LIT_LIT,\n\t\t\t\tSTATE_LIT_LIT,\n\t\t\t\tSTATE_MATCH_LIT_LIT,\n\t\t\t\tSTATE_REP_LIT_LIT,\n\t\t\t\tSTATE_SHORTREP_LIT_LIT,\n\t\t\t\tSTATE_MATCH_LIT,\n\t\t\t\tSTATE_REP_LIT,\n\t\t\t\tSTATE_SHORTREP_LIT,\n\t\t\t\tSTATE_MATCH_LIT,\n\t\t\t\tSTATE_REP_LIT\n\t\t\t};\n\t\t\tstate = next_state[state];\n\n\tcase SEQ_LITERAL_WRITE:\n\t\t\tif (unlikely(dict_put(&dict, symbol))) {\n\t\t\t\tcoder->sequence = SEQ_LITERAL_WRITE;\n\t\t\t\tgoto out;\n\t\t\t}\n\n\t\t\tcontinue;\n\t\t}\n\n\t\t// Instead of a new byte we are going to get a byte range\n\t\t// (distance and length) which will be repeated from our\n\t\t// output history.\n\n\t\trc_update_1(coder->is_match[state][pos_state]);\n\n\tcase SEQ_IS_REP:\n\t\trc_if_0(coder->is_rep[state], SEQ_IS_REP) {\n\t\t\t// Not a repeated match\n\t\t\trc_update_0(coder->is_rep[state]);\n\t\t\tupdate_match(state);\n\n\t\t\t// The latest three match distances are kept in\n\t\t\t// memory in case there are repeated matches.\n\t\t\trep3 = rep2;\n\t\t\trep2 = rep1;\n\t\t\trep1 = rep0;\n\n\t\t\t// Decode the length of the match.\n\t\t\tlen_decode(len, coder->match_len_decoder,\n\t\t\t\t\tpos_state, SEQ_MATCH_LEN);\n\n\t\t\t// Prepare to decode the highest two bits of the\n\t\t\t// match distance.\n\t\t\tprobs = coder->dist_slot[get_dist_state(len)];\n\t\t\tsymbol = 1;\n\n#ifdef HAVE_SMALL\n\tcase SEQ_DIST_SLOT:\n\t\t\tdo {\n\t\t\t\trc_bit(probs[symbol], , , SEQ_DIST_SLOT);\n\t\t\t} while (symbol < DIST_SLOTS);\n#else\n\t\t\trc_bit_case(probs[symbol], , , SEQ_DIST_SLOT0);\n\t\t\trc_bit_case(probs[symbol], , , SEQ_DIST_SLOT1);\n\t\t\trc_bit_case(probs[symbol], , , SEQ_DIST_SLOT2);\n\t\t\trc_bit_case(probs[symbol], , , SEQ_DIST_SLOT3);\n\t\t\trc_bit_case(probs[symbol], , , SEQ_DIST_SLOT4);\n\t\t\trc_bit_case(probs[symbol], , , SEQ_DIST_SLOT5);\n#endif\n\t\t\t// Get rid of the highest bit that was needed for\n\t\t\t// indexing of the probability array.\n\t\t\tsymbol -= DIST_SLOTS;\n\t\t\tassert(symbol <= 63);\n\n\t\t\tif (symbol < DIST_MODEL_START) {\n\t\t\t\t// Match distances [0, 3] have only two bits.\n\t\t\t\trep0 = symbol;\n\t\t\t} else {\n\t\t\t\t// Decode the lowest [1, 29] bits of\n\t\t\t\t// the match distance.\n\t\t\t\tlimit = (symbol >> 1) - 1;\n\t\t\t\tassert(limit >= 1 && limit <= 30);\n\t\t\t\trep0 = 2 + (symbol & 1);\n\n\t\t\t\tif (symbol < DIST_MODEL_END) {\n\t\t\t\t\t// Prepare to decode the low bits for\n\t\t\t\t\t// a distance of [4, 127].\n\t\t\t\t\tassert(limit <= 5);\n\t\t\t\t\trep0 <<= limit;\n\t\t\t\t\tassert(rep0 <= 96);\n\t\t\t\t\t// -1 is fine, because we start\n\t\t\t\t\t// decoding at probs[1], not probs[0].\n\t\t\t\t\t// NOTE: This violates the C standard,\n\t\t\t\t\t// since we are doing pointer\n\t\t\t\t\t// arithmetic past the beginning of\n\t\t\t\t\t// the array.\n\t\t\t\t\tassert((int32_t)(rep0 - symbol - 1)\n\t\t\t\t\t\t\t>= -1);\n\t\t\t\t\tassert((int32_t)(rep0 - symbol - 1)\n\t\t\t\t\t\t\t<= 82);\n\t\t\t\t\tprobs = coder->pos_special + rep0\n\t\t\t\t\t\t\t- symbol - 1;\n\t\t\t\t\tsymbol = 1;\n\t\t\t\t\toffset = 0;\n\tcase SEQ_DIST_MODEL:\n#ifdef HAVE_SMALL\n\t\t\t\t\tdo {\n\t\t\t\t\t\trc_bit(probs[symbol], ,\n\t\t\t\t\t\t\trep0 += 1U << offset,\n\t\t\t\t\t\t\tSEQ_DIST_MODEL);\n\t\t\t\t\t} while (++offset < limit);\n#else\n\t\t\t\t\tswitch (limit) {\n\t\t\t\t\tcase 5:\n\t\t\t\t\t\tassert(offset == 0);\n\t\t\t\t\t\trc_bit(probs[symbol], ,\n\t\t\t\t\t\t\trep0 += 1U,\n\t\t\t\t\t\t\tSEQ_DIST_MODEL);\n\t\t\t\t\t\t++offset;\n\t\t\t\t\t\t--limit;\n\t\t\t\t\tcase 4:\n\t\t\t\t\t\trc_bit(probs[symbol], ,\n\t\t\t\t\t\t\trep0 += 1U << offset,\n\t\t\t\t\t\t\tSEQ_DIST_MODEL);\n\t\t\t\t\t\t++offset;\n\t\t\t\t\t\t--limit;\n\t\t\t\t\tcase 3:\n\t\t\t\t\t\trc_bit(probs[symbol], ,\n\t\t\t\t\t\t\trep0 += 1U << offset,\n\t\t\t\t\t\t\tSEQ_DIST_MODEL);\n\t\t\t\t\t\t++offset;\n\t\t\t\t\t\t--limit;\n\t\t\t\t\tcase 2:\n\t\t\t\t\t\trc_bit(probs[symbol], ,\n\t\t\t\t\t\t\trep0 += 1U << offset,\n\t\t\t\t\t\t\tSEQ_DIST_MODEL);\n\t\t\t\t\t\t++offset;\n\t\t\t\t\t\t--limit;\n\t\t\t\t\tcase 1:\n\t\t\t\t\t\t// We need \"symbol\" only for\n\t\t\t\t\t\t// indexing the probability\n\t\t\t\t\t\t// array, thus we can use\n\t\t\t\t\t\t// rc_bit_last() here to omit\n\t\t\t\t\t\t// the unneeded updating of\n\t\t\t\t\t\t// \"symbol\".\n\t\t\t\t\t\trc_bit_last(probs[symbol], ,\n\t\t\t\t\t\t\trep0 += 1U << offset,\n\t\t\t\t\t\t\tSEQ_DIST_MODEL);\n\t\t\t\t\t}\n#endif\n\t\t\t\t} else {\n\t\t\t\t\t// The distance is >= 128. Decode the\n\t\t\t\t\t// lower bits without probabilities\n\t\t\t\t\t// except the lowest four bits.\n\t\t\t\t\tassert(symbol >= 14);\n\t\t\t\t\tassert(limit >= 6);\n\t\t\t\t\tlimit -= ALIGN_BITS;\n\t\t\t\t\tassert(limit >= 2);\n\tcase SEQ_DIRECT:\n\t\t\t\t\t// Not worth manual unrolling\n\t\t\t\t\tdo {\n\t\t\t\t\t\trc_direct(rep0, SEQ_DIRECT);\n\t\t\t\t\t} while (--limit > 0);\n\n\t\t\t\t\t// Decode the lowest four bits using\n\t\t\t\t\t// probabilities.\n\t\t\t\t\trep0 <<= ALIGN_BITS;\n\t\t\t\t\tsymbol = 1;\n#ifdef HAVE_SMALL\n\t\t\t\t\toffset = 0;\n\tcase SEQ_ALIGN:\n\t\t\t\t\tdo {\n\t\t\t\t\t\trc_bit(coder->pos_align[\n\t\t\t\t\t\t\t\tsymbol], ,\n\t\t\t\t\t\t\trep0 += 1U << offset,\n\t\t\t\t\t\t\tSEQ_ALIGN);\n\t\t\t\t\t} while (++offset < ALIGN_BITS);\n#else\n\tcase SEQ_ALIGN0:\n\t\t\t\t\trc_bit(coder->pos_align[symbol], ,\n\t\t\t\t\t\t\trep0 += 1, SEQ_ALIGN0);\n\tcase SEQ_ALIGN1:\n\t\t\t\t\trc_bit(coder->pos_align[symbol], ,\n\t\t\t\t\t\t\trep0 += 2, SEQ_ALIGN1);\n\tcase SEQ_ALIGN2:\n\t\t\t\t\trc_bit(coder->pos_align[symbol], ,\n\t\t\t\t\t\t\trep0 += 4, SEQ_ALIGN2);\n\tcase SEQ_ALIGN3:\n\t\t\t\t\t// Like in SEQ_DIST_MODEL, we don't\n\t\t\t\t\t// need \"symbol\" for anything else\n\t\t\t\t\t// than indexing the probability array.\n\t\t\t\t\trc_bit_last(coder->pos_align[symbol], ,\n\t\t\t\t\t\t\trep0 += 8, SEQ_ALIGN3);\n#endif\n\n\t\t\t\t\tif (rep0 == UINT32_MAX) {\n\t\t\t\t\t\t// End of payload marker was\n\t\t\t\t\t\t// found. It must not be\n\t\t\t\t\t\t// present if uncompressed\n\t\t\t\t\t\t// size is known.\n\t\t\t\t\t\tif (coder->uncompressed_size\n\t\t\t\t\t\t!= LZMA_VLI_UNKNOWN) {\n\t\t\t\t\t\t\tret = LZMA_DATA_ERROR;\n\t\t\t\t\t\t\tgoto out;\n\t\t\t\t\t\t}\n\n\tcase SEQ_EOPM:\n\t\t\t\t\t\t// LZMA1 stream with\n\t\t\t\t\t\t// end-of-payload marker.\n\t\t\t\t\t\trc_normalize(SEQ_EOPM);\n\t\t\t\t\t\tret = LZMA_STREAM_END;\n\t\t\t\t\t\tgoto out;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\n\t\t\t// Validate the distance we just decoded.\n\t\t\tif (unlikely(!dict_is_distance_valid(&dict, rep0))) {\n\t\t\t\tret = LZMA_DATA_ERROR;\n\t\t\t\tgoto out;\n\t\t\t}\n\n\t\t} else {\n\t\t\trc_update_1(coder->is_rep[state]);\n\n\t\t\t// Repeated match\n\t\t\t//\n\t\t\t// The match distance is a value that we have had\n\t\t\t// earlier. The latest four match distances are\n\t\t\t// available as rep0, rep1, rep2 and rep3. We will\n\t\t\t// now decode which of them is the new distance.\n\t\t\t//\n\t\t\t// There cannot be a match if we haven't produced\n\t\t\t// any output, so check that first.\n\t\t\tif (unlikely(!dict_is_distance_valid(&dict, 0))) {\n\t\t\t\tret = LZMA_DATA_ERROR;\n\t\t\t\tgoto out;\n\t\t\t}\n\n\tcase SEQ_IS_REP0:\n\t\t\trc_if_0(coder->is_rep0[state], SEQ_IS_REP0) {\n\t\t\t\trc_update_0(coder->is_rep0[state]);\n\t\t\t\t// The distance is rep0.\n\n\tcase SEQ_IS_REP0_LONG:\n\t\t\t\trc_if_0(coder->is_rep0_long[state][pos_state],\n\t\t\t\t\t\tSEQ_IS_REP0_LONG) {\n\t\t\t\t\trc_update_0(coder->is_rep0_long[\n\t\t\t\t\t\t\tstate][pos_state]);\n\n\t\t\t\t\tupdate_short_rep(state);\n\n\tcase SEQ_SHORTREP:\n\t\t\t\t\tif (unlikely(dict_put(&dict, dict_get(\n\t\t\t\t\t\t\t&dict, rep0)))) {\n\t\t\t\t\t\tcoder->sequence = SEQ_SHORTREP;\n\t\t\t\t\t\tgoto out;\n\t\t\t\t\t}\n\n\t\t\t\t\tcontinue;\n\t\t\t\t}\n\n\t\t\t\t// Repeating more than one byte at\n\t\t\t\t// distance of rep0.\n\t\t\t\trc_update_1(coder->is_rep0_long[\n\t\t\t\t\t\tstate][pos_state]);\n\n\t\t\t} else {\n\t\t\t\trc_update_1(coder->is_rep0[state]);\n\n\tcase SEQ_IS_REP1:\n\t\t\t\t// The distance is rep1, rep2 or rep3. Once\n\t\t\t\t// we find out which one of these three, it\n\t\t\t\t// is stored to rep0 and rep1, rep2 and rep3\n\t\t\t\t// are updated accordingly.\n\t\t\t\trc_if_0(coder->is_rep1[state], SEQ_IS_REP1) {\n\t\t\t\t\trc_update_0(coder->is_rep1[state]);\n\n\t\t\t\t\tconst uint32_t distance = rep1;\n\t\t\t\t\trep1 = rep0;\n\t\t\t\t\trep0 = distance;\n\n\t\t\t\t} else {\n\t\t\t\t\trc_update_1(coder->is_rep1[state]);\n\tcase SEQ_IS_REP2:\n\t\t\t\t\trc_if_0(coder->is_rep2[state],\n\t\t\t\t\t\t\tSEQ_IS_REP2) {\n\t\t\t\t\t\trc_update_0(coder->is_rep2[\n\t\t\t\t\t\t\t\tstate]);\n\n\t\t\t\t\t\tconst uint32_t distance = rep2;\n\t\t\t\t\t\trep2 = rep1;\n\t\t\t\t\t\trep1 = rep0;\n\t\t\t\t\t\trep0 = distance;\n\n\t\t\t\t\t} else {\n\t\t\t\t\t\trc_update_1(coder->is_rep2[\n\t\t\t\t\t\t\t\tstate]);\n\n\t\t\t\t\t\tconst uint32_t distance = rep3;\n\t\t\t\t\t\trep3 = rep2;\n\t\t\t\t\t\trep2 = rep1;\n\t\t\t\t\t\trep1 = rep0;\n\t\t\t\t\t\trep0 = distance;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tupdate_long_rep(state);\n\n\t\t\t// Decode the length of the repeated match.\n\t\t\tlen_decode(len, coder->rep_len_decoder,\n\t\t\t\t\tpos_state, SEQ_REP_LEN);\n\t\t}\n\n\t\t/////////////////////////////////\n\t\t// Repeat from history buffer. //\n\t\t/////////////////////////////////\n\n\t\t// The length is always between these limits. There is no way\n\t\t// to trigger the algorithm to set len outside this range.\n\t\tassert(len >= MATCH_LEN_MIN);\n\t\tassert(len <= MATCH_LEN_MAX);\n\n\tcase SEQ_COPY:\n\t\t// Repeat len bytes from distance of rep0.\n\t\tif (unlikely(dict_repeat(&dict, rep0, &len))) {\n\t\t\tcoder->sequence = SEQ_COPY;\n\t\t\tgoto out;\n\t\t}\n\t}\n\n\trc_normalize(SEQ_NORMALIZE);\n\tcoder->sequence = SEQ_IS_MATCH;\n\nout:\n\t// Save state\n\n\t// NOTE: Must not copy dict.limit.\n\tdictptr->pos = dict.pos;\n\tdictptr->full = dict.full;\n\n\trc_from_local(coder->rc, *in_pos);\n\n\tcoder->state = state;\n\tcoder->rep0 = rep0;\n\tcoder->rep1 = rep1;\n\tcoder->rep2 = rep2;\n\tcoder->rep3 = rep3;\n\n\tcoder->probs = probs;\n\tcoder->symbol = symbol;\n\tcoder->limit = limit;\n\tcoder->offset = offset;\n\tcoder->len = len;\n\n\t// Update the remaining amount of uncompressed data if uncompressed\n\t// size was known.\n\tif (coder->uncompressed_size != LZMA_VLI_UNKNOWN) {\n\t\tcoder->uncompressed_size -= dict.pos - dict_start;\n\n\t\t// Since there cannot be end of payload marker if the\n\t\t// uncompressed size was known, we check here if we\n\t\t// finished decoding.\n\t\tif (coder->uncompressed_size == 0 && ret == LZMA_OK\n\t\t\t\t&& coder->sequence != SEQ_NORMALIZE)\n\t\t\tret = coder->sequence == SEQ_IS_MATCH\n\t\t\t\t\t? LZMA_STREAM_END : LZMA_DATA_ERROR;\n\t}\n\n\t// We can do an additional check in the range decoder to catch some\n\t// corrupted files.\n\tif (ret == LZMA_STREAM_END) {\n\t\tif (!rc_is_finished(coder->rc))\n\t\t\tret = LZMA_DATA_ERROR;\n\n\t\t// Reset the range decoder so that it is ready to reinitialize\n\t\t// for a new LZMA2 chunk.\n\t\trc_reset(coder->rc);\n\t}\n\n\treturn ret;\n}\n\n\n\nstatic void\nlzma_decoder_uncompressed(void *coder_ptr, lzma_vli uncompressed_size)\n{\n\tlzma_lzma1_decoder *coder = coder_ptr;\n\tcoder->uncompressed_size = uncompressed_size;\n}\n\n\nstatic void\nlzma_decoder_reset(void *coder_ptr, const void *opt)\n{\n\tlzma_lzma1_decoder *coder = coder_ptr;\n\tconst lzma_options_lzma *options = opt;\n\n\t// NOTE: We assume that lc/lp/pb are valid since they were\n\t// successfully decoded with lzma_lzma_decode_properties().\n\n\t// Calculate pos_mask. We don't need pos_bits as is for anything.\n\tcoder->pos_mask = (1U << options->pb) - 1;\n\n\t// Initialize the literal decoder.\n\tliteral_init(coder->literal, options->lc, options->lp);\n\n\tcoder->literal_context_bits = options->lc;\n\tcoder->literal_pos_mask = (1U << options->lp) - 1;\n\n\t// State\n\tcoder->state = STATE_LIT_LIT;\n\tcoder->rep0 = 0;\n\tcoder->rep1 = 0;\n\tcoder->rep2 = 0;\n\tcoder->rep3 = 0;\n\tcoder->pos_mask = (1U << options->pb) - 1;\n\n\t// Range decoder\n\trc_reset(coder->rc);\n\n\t// Bit and bittree decoders\n\tfor (uint32_t i = 0; i < STATES; ++i) {\n\t\tfor (uint32_t j = 0; j <= coder->pos_mask; ++j) {\n\t\t\tbit_reset(coder->is_match[i][j]);\n\t\t\tbit_reset(coder->is_rep0_long[i][j]);\n\t\t}\n\n\t\tbit_reset(coder->is_rep[i]);\n\t\tbit_reset(coder->is_rep0[i]);\n\t\tbit_reset(coder->is_rep1[i]);\n\t\tbit_reset(coder->is_rep2[i]);\n\t}\n\n\tfor (uint32_t i = 0; i < DIST_STATES; ++i)\n\t\tbittree_reset(coder->dist_slot[i], DIST_SLOT_BITS);\n\n\tfor (uint32_t i = 0; i < FULL_DISTANCES - DIST_MODEL_END; ++i)\n\t\tbit_reset(coder->pos_special[i]);\n\n\tbittree_reset(coder->pos_align, ALIGN_BITS);\n\n\t// Len decoders (also bit/bittree)\n\tconst uint32_t num_pos_states = 1U << options->pb;\n\tbit_reset(coder->match_len_decoder.choice);\n\tbit_reset(coder->match_len_decoder.choice2);\n\tbit_reset(coder->rep_len_decoder.choice);\n\tbit_reset(coder->rep_len_decoder.choice2);\n\n\tfor (uint32_t pos_state = 0; pos_state < num_pos_states; ++pos_state) {\n\t\tbittree_reset(coder->match_len_decoder.low[pos_state],\n\t\t\t\tLEN_LOW_BITS);\n\t\tbittree_reset(coder->match_len_decoder.mid[pos_state],\n\t\t\t\tLEN_MID_BITS);\n\n\t\tbittree_reset(coder->rep_len_decoder.low[pos_state],\n\t\t\t\tLEN_LOW_BITS);\n\t\tbittree_reset(coder->rep_len_decoder.mid[pos_state],\n\t\t\t\tLEN_MID_BITS);\n\t}\n\n\tbittree_reset(coder->match_len_decoder.high, LEN_HIGH_BITS);\n\tbittree_reset(coder->rep_len_decoder.high, LEN_HIGH_BITS);\n\n\tcoder->sequence = SEQ_IS_MATCH;\n\tcoder->probs = NULL;\n\tcoder->symbol = 0;\n\tcoder->limit = 0;\n\tcoder->offset = 0;\n\tcoder->len = 0;\n\n\treturn;\n}\n\n\nextern lzma_ret\nlzma_lzma_decoder_create(lzma_lz_decoder *lz, const lzma_allocator *allocator,\n\t\tconst void *opt, lzma_lz_options *lz_options)\n{\n\tif (lz->coder == NULL) {\n\t\tlz->coder = lzma_alloc(sizeof(lzma_lzma1_decoder), allocator);\n\t\tif (lz->coder == NULL)\n\t\t\treturn LZMA_MEM_ERROR;\n\n\t\tlz->code = &lzma_decode;\n\t\tlz->reset = &lzma_decoder_reset;\n\t\tlz->set_uncompressed = &lzma_decoder_uncompressed;\n\t}\n\n\t// All dictionary sizes are OK here. LZ decoder will take care of\n\t// the special cases.\n\tconst lzma_options_lzma *options = opt;\n\tlz_options->dict_size = options->dict_size;\n\tlz_options->preset_dict = options->preset_dict;\n\tlz_options->preset_dict_size = options->preset_dict_size;\n\n\treturn LZMA_OK;\n}\n\n\n/// Allocate and initialize LZMA decoder. This is used only via LZ\n/// initialization (lzma_lzma_decoder_init() passes function pointer to\n/// the LZ initialization).\nstatic lzma_ret\nlzma_decoder_init(lzma_lz_decoder *lz, const lzma_allocator *allocator,\n\t\tconst void *options, lzma_lz_options *lz_options)\n{\n\tif (!is_lclppb_valid(options))\n\t\treturn LZMA_PROG_ERROR;\n\n\treturn_if_error(lzma_lzma_decoder_create(\n\t\t\tlz, allocator, options, lz_options));\n\n\tlzma_decoder_reset(lz->coder, options);\n\tlzma_decoder_uncompressed(lz->coder, LZMA_VLI_UNKNOWN);\n\n\treturn LZMA_OK;\n}\n\n\nextern lzma_ret\nlzma_lzma_decoder_init(lzma_next_coder *next, const lzma_allocator *allocator,\n\t\tconst lzma_filter_info *filters)\n{\n\t// LZMA can only be the last filter in the chain. This is enforced\n\t// by the raw_decoder initialization.\n\tassert(filters[1].init == NULL);\n\n\treturn lzma_lz_decoder_init(next, allocator, filters,\n\t\t\t&lzma_decoder_init);\n}\n\n\nextern bool\nlzma_lzma_lclppb_decode(lzma_options_lzma *options, uint8_t byte)\n{\n\tif (byte > (4 * 5 + 4) * 9 + 8)\n\t\treturn true;\n\n\t// See the file format specification to understand this.\n\toptions->pb = byte / (9 * 5);\n\tbyte -= options->pb * 9 * 5;\n\toptions->lp = byte / 9;\n\toptions->lc = byte - options->lp * 9;\n\n\treturn options->lc + options->lp > LZMA_LCLP_MAX;\n}\n\n\nextern uint64_t\nlzma_lzma_decoder_memusage_nocheck(const void *options)\n{\n\tconst lzma_options_lzma *const opt = options;\n\treturn sizeof(lzma_lzma1_decoder)\n\t\t\t+ lzma_lz_decoder_memusage(opt->dict_size);\n}\n\n\nextern uint64_t\nlzma_lzma_decoder_memusage(const void *options)\n{\n\tif (!is_lclppb_valid(options))\n\t\treturn UINT64_MAX;\n\n\treturn lzma_lzma_decoder_memusage_nocheck(options);\n}\n\n\nextern lzma_ret\nlzma_lzma_props_decode(void **options, const lzma_allocator *allocator,\n\t\tconst uint8_t *props, size_t props_size)\n{\n\tif (props_size != 5)\n\t\treturn LZMA_OPTIONS_ERROR;\n\n\tlzma_options_lzma *opt\n\t\t\t= lzma_alloc(sizeof(lzma_options_lzma), allocator);\n\tif (opt == NULL)\n\t\treturn LZMA_MEM_ERROR;\n\n\tif (lzma_lzma_lclppb_decode(opt, props[0]))\n\t\tgoto error;\n\n\t// All dictionary sizes are accepted, including zero. LZ decoder\n\t// will automatically use a dictionary at least a few KiB even if\n\t// a smaller dictionary is requested.\n\topt->dict_size = read32le(props + 1);\n\n\topt->preset_dict = NULL;\n\topt->preset_dict_size = 0;\n\n\t*options = opt;\n\n\treturn LZMA_OK;\n\nerror:\n\tlzma_free(opt, allocator);\n\treturn LZMA_OPTIONS_ERROR;\n}\n"
  },
  {
    "path": "external/xz/liblzma/lzma/lzma_decoder.h",
    "content": "///////////////////////////////////////////////////////////////////////////////\n//\n/// \\file       lzma_decoder.h\n/// \\brief      LZMA decoder API\n///\n//  Authors:    Igor Pavlov\n//              Lasse Collin\n//\n//  This file has been put into the public domain.\n//  You can do whatever you want with this file.\n//\n///////////////////////////////////////////////////////////////////////////////\n\n#ifndef LZMA_LZMA_DECODER_H\n#define LZMA_LZMA_DECODER_H\n\n#include \"common.h\"\n\n\n/// Allocates and initializes LZMA decoder\nextern lzma_ret lzma_lzma_decoder_init(lzma_next_coder *next,\n\t\tconst lzma_allocator *allocator,\n\t\tconst lzma_filter_info *filters);\n\nextern uint64_t lzma_lzma_decoder_memusage(const void *options);\n\nextern lzma_ret lzma_lzma_props_decode(\n\t\tvoid **options, const lzma_allocator *allocator,\n\t\tconst uint8_t *props, size_t props_size);\n\n\n/// \\brief      Decodes the LZMA Properties byte (lc/lp/pb)\n///\n/// \\return     true if error occurred, false on success\n///\nextern bool lzma_lzma_lclppb_decode(\n\t\tlzma_options_lzma *options, uint8_t byte);\n\n\n#ifdef LZMA_LZ_DECODER_H\n/// Allocate and setup function pointers only. This is used by LZMA1 and\n/// LZMA2 decoders.\nextern lzma_ret lzma_lzma_decoder_create(\n\t\tlzma_lz_decoder *lz, const lzma_allocator *allocator,\n\t\tconst void *opt, lzma_lz_options *lz_options);\n\n/// Gets memory usage without validating lc/lp/pb. This is used by LZMA2\n/// decoder, because raw LZMA2 decoding doesn't need lc/lp/pb.\nextern uint64_t lzma_lzma_decoder_memusage_nocheck(const void *options);\n\n#endif\n\n#endif\n"
  },
  {
    "path": "external/xz/liblzma/lzma/lzma_encoder.c",
    "content": "///////////////////////////////////////////////////////////////////////////////\n//\n/// \\file       lzma_encoder.c\n/// \\brief      LZMA encoder\n///\n//  Authors:    Igor Pavlov\n//              Lasse Collin\n//\n//  This file has been put into the public domain.\n//  You can do whatever you want with this file.\n//\n///////////////////////////////////////////////////////////////////////////////\n\n#include \"lzma2_encoder.h\"\n#include \"lzma_encoder_private.h\"\n#include \"fastpos.h\"\n\n\n/////////////\n// Literal //\n/////////////\n\nstatic inline void\nliteral_matched(lzma_range_encoder *rc, probability *subcoder,\n\t\tuint32_t match_byte, uint32_t symbol)\n{\n\tuint32_t offset = 0x100;\n\tsymbol += UINT32_C(1) << 8;\n\n\tdo {\n\t\tmatch_byte <<= 1;\n\t\tconst uint32_t match_bit = match_byte & offset;\n\t\tconst uint32_t subcoder_index\n\t\t\t\t= offset + match_bit + (symbol >> 8);\n\t\tconst uint32_t bit = (symbol >> 7) & 1;\n\t\trc_bit(rc, &subcoder[subcoder_index], bit);\n\n\t\tsymbol <<= 1;\n\t\toffset &= ~(match_byte ^ symbol);\n\n\t} while (symbol < (UINT32_C(1) << 16));\n}\n\n\nstatic inline void\nliteral(lzma_lzma1_encoder *coder, lzma_mf *mf, uint32_t position)\n{\n\t// Locate the literal byte to be encoded and the subcoder.\n\tconst uint8_t cur_byte = mf->buffer[\n\t\t\tmf->read_pos - mf->read_ahead];\n\tprobability *subcoder = literal_subcoder(coder->literal,\n\t\t\tcoder->literal_context_bits, coder->literal_pos_mask,\n\t\t\tposition, mf->buffer[mf->read_pos - mf->read_ahead - 1]);\n\n\tif (is_literal_state(coder->state)) {\n\t\t// Previous LZMA-symbol was a literal. Encode a normal\n\t\t// literal without a match byte.\n\t\trc_bittree(&coder->rc, subcoder, 8, cur_byte);\n\t} else {\n\t\t// Previous LZMA-symbol was a match. Use the last byte of\n\t\t// the match as a \"match byte\". That is, compare the bits\n\t\t// of the current literal and the match byte.\n\t\tconst uint8_t match_byte = mf->buffer[\n\t\t\t\tmf->read_pos - coder->reps[0] - 1\n\t\t\t\t- mf->read_ahead];\n\t\tliteral_matched(&coder->rc, subcoder, match_byte, cur_byte);\n\t}\n\n\tupdate_literal(coder->state);\n}\n\n\n//////////////////\n// Match length //\n//////////////////\n\nstatic void\nlength_update_prices(lzma_length_encoder *lc, const uint32_t pos_state)\n{\n\tconst uint32_t table_size = lc->table_size;\n\tlc->counters[pos_state] = table_size;\n\n\tconst uint32_t a0 = rc_bit_0_price(lc->choice);\n\tconst uint32_t a1 = rc_bit_1_price(lc->choice);\n\tconst uint32_t b0 = a1 + rc_bit_0_price(lc->choice2);\n\tconst uint32_t b1 = a1 + rc_bit_1_price(lc->choice2);\n\tuint32_t *const prices = lc->prices[pos_state];\n\n\tuint32_t i;\n\tfor (i = 0; i < table_size && i < LEN_LOW_SYMBOLS; ++i)\n\t\tprices[i] = a0 + rc_bittree_price(lc->low[pos_state],\n\t\t\t\tLEN_LOW_BITS, i);\n\n\tfor (; i < table_size && i < LEN_LOW_SYMBOLS + LEN_MID_SYMBOLS; ++i)\n\t\tprices[i] = b0 + rc_bittree_price(lc->mid[pos_state],\n\t\t\t\tLEN_MID_BITS, i - LEN_LOW_SYMBOLS);\n\n\tfor (; i < table_size; ++i)\n\t\tprices[i] = b1 + rc_bittree_price(lc->high, LEN_HIGH_BITS,\n\t\t\t\ti - LEN_LOW_SYMBOLS - LEN_MID_SYMBOLS);\n\n\treturn;\n}\n\n\nstatic inline void\nlength(lzma_range_encoder *rc, lzma_length_encoder *lc,\n\t\tconst uint32_t pos_state, uint32_t len, const bool fast_mode)\n{\n\tassert(len <= MATCH_LEN_MAX);\n\tlen -= MATCH_LEN_MIN;\n\n\tif (len < LEN_LOW_SYMBOLS) {\n\t\trc_bit(rc, &lc->choice, 0);\n\t\trc_bittree(rc, lc->low[pos_state], LEN_LOW_BITS, len);\n\t} else {\n\t\trc_bit(rc, &lc->choice, 1);\n\t\tlen -= LEN_LOW_SYMBOLS;\n\n\t\tif (len < LEN_MID_SYMBOLS) {\n\t\t\trc_bit(rc, &lc->choice2, 0);\n\t\t\trc_bittree(rc, lc->mid[pos_state], LEN_MID_BITS, len);\n\t\t} else {\n\t\t\trc_bit(rc, &lc->choice2, 1);\n\t\t\tlen -= LEN_MID_SYMBOLS;\n\t\t\trc_bittree(rc, lc->high, LEN_HIGH_BITS, len);\n\t\t}\n\t}\n\n\t// Only getoptimum uses the prices so don't update the table when\n\t// in fast mode.\n\tif (!fast_mode)\n\t\tif (--lc->counters[pos_state] == 0)\n\t\t\tlength_update_prices(lc, pos_state);\n}\n\n\n///////////\n// Match //\n///////////\n\nstatic inline void\nmatch(lzma_lzma1_encoder *coder, const uint32_t pos_state,\n\t\tconst uint32_t distance, const uint32_t len)\n{\n\tupdate_match(coder->state);\n\n\tlength(&coder->rc, &coder->match_len_encoder, pos_state, len,\n\t\t\tcoder->fast_mode);\n\n\tconst uint32_t dist_slot = get_dist_slot(distance);\n\tconst uint32_t dist_state = get_dist_state(len);\n\trc_bittree(&coder->rc, coder->dist_slot[dist_state],\n\t\t\tDIST_SLOT_BITS, dist_slot);\n\n\tif (dist_slot >= DIST_MODEL_START) {\n\t\tconst uint32_t footer_bits = (dist_slot >> 1) - 1;\n\t\tconst uint32_t base = (2 | (dist_slot & 1)) << footer_bits;\n\t\tconst uint32_t dist_reduced = distance - base;\n\n\t\tif (dist_slot < DIST_MODEL_END) {\n\t\t\t// Careful here: base - dist_slot - 1 can be -1, but\n\t\t\t// rc_bittree_reverse starts at probs[1], not probs[0].\n\t\t\trc_bittree_reverse(&coder->rc,\n\t\t\t\tcoder->dist_special + base - dist_slot - 1,\n\t\t\t\tfooter_bits, dist_reduced);\n\t\t} else {\n\t\t\trc_direct(&coder->rc, dist_reduced >> ALIGN_BITS,\n\t\t\t\t\tfooter_bits - ALIGN_BITS);\n\t\t\trc_bittree_reverse(\n\t\t\t\t\t&coder->rc, coder->dist_align,\n\t\t\t\t\tALIGN_BITS, dist_reduced & ALIGN_MASK);\n\t\t\t++coder->align_price_count;\n\t\t}\n\t}\n\n\tcoder->reps[3] = coder->reps[2];\n\tcoder->reps[2] = coder->reps[1];\n\tcoder->reps[1] = coder->reps[0];\n\tcoder->reps[0] = distance;\n\t++coder->match_price_count;\n}\n\n\n////////////////////\n// Repeated match //\n////////////////////\n\nstatic inline void\nrep_match(lzma_lzma1_encoder *coder, const uint32_t pos_state,\n\t\tconst uint32_t rep, const uint32_t len)\n{\n\tif (rep == 0) {\n\t\trc_bit(&coder->rc, &coder->is_rep0[coder->state], 0);\n\t\trc_bit(&coder->rc,\n\t\t\t\t&coder->is_rep0_long[coder->state][pos_state],\n\t\t\t\tlen != 1);\n\t} else {\n\t\tconst uint32_t distance = coder->reps[rep];\n\t\trc_bit(&coder->rc, &coder->is_rep0[coder->state], 1);\n\n\t\tif (rep == 1) {\n\t\t\trc_bit(&coder->rc, &coder->is_rep1[coder->state], 0);\n\t\t} else {\n\t\t\trc_bit(&coder->rc, &coder->is_rep1[coder->state], 1);\n\t\t\trc_bit(&coder->rc, &coder->is_rep2[coder->state],\n\t\t\t\t\trep - 2);\n\n\t\t\tif (rep == 3)\n\t\t\t\tcoder->reps[3] = coder->reps[2];\n\n\t\t\tcoder->reps[2] = coder->reps[1];\n\t\t}\n\n\t\tcoder->reps[1] = coder->reps[0];\n\t\tcoder->reps[0] = distance;\n\t}\n\n\tif (len == 1) {\n\t\tupdate_short_rep(coder->state);\n\t} else {\n\t\tlength(&coder->rc, &coder->rep_len_encoder, pos_state, len,\n\t\t\t\tcoder->fast_mode);\n\t\tupdate_long_rep(coder->state);\n\t}\n}\n\n\n//////////\n// Main //\n//////////\n\nstatic void\nencode_symbol(lzma_lzma1_encoder *coder, lzma_mf *mf,\n\t\tuint32_t back, uint32_t len, uint32_t position)\n{\n\tconst uint32_t pos_state = position & coder->pos_mask;\n\n\tif (back == UINT32_MAX) {\n\t\t// Literal i.e. eight-bit byte\n\t\tassert(len == 1);\n\t\trc_bit(&coder->rc,\n\t\t\t\t&coder->is_match[coder->state][pos_state], 0);\n\t\tliteral(coder, mf, position);\n\t} else {\n\t\t// Some type of match\n\t\trc_bit(&coder->rc,\n\t\t\t&coder->is_match[coder->state][pos_state], 1);\n\n\t\tif (back < REPS) {\n\t\t\t// It's a repeated match i.e. the same distance\n\t\t\t// has been used earlier.\n\t\t\trc_bit(&coder->rc, &coder->is_rep[coder->state], 1);\n\t\t\trep_match(coder, pos_state, back, len);\n\t\t} else {\n\t\t\t// Normal match\n\t\t\trc_bit(&coder->rc, &coder->is_rep[coder->state], 0);\n\t\t\tmatch(coder, pos_state, back - REPS, len);\n\t\t}\n\t}\n\n\tassert(mf->read_ahead >= len);\n\tmf->read_ahead -= len;\n}\n\n\nstatic bool\nencode_init(lzma_lzma1_encoder *coder, lzma_mf *mf)\n{\n\tassert(mf_position(mf) == 0);\n\n\tif (mf->read_pos == mf->read_limit) {\n\t\tif (mf->action == LZMA_RUN)\n\t\t\treturn false; // We cannot do anything.\n\n\t\t// We are finishing (we cannot get here when flushing).\n\t\tassert(mf->write_pos == mf->read_pos);\n\t\tassert(mf->action == LZMA_FINISH);\n\t} else {\n\t\t// Do the actual initialization. The first LZMA symbol must\n\t\t// always be a literal.\n\t\tmf_skip(mf, 1);\n\t\tmf->read_ahead = 0;\n\t\trc_bit(&coder->rc, &coder->is_match[0][0], 0);\n\t\trc_bittree(&coder->rc, coder->literal[0], 8, mf->buffer[0]);\n\t}\n\n\t// Initialization is done (except if empty file).\n\tcoder->is_initialized = true;\n\n\treturn true;\n}\n\n\nstatic void\nencode_eopm(lzma_lzma1_encoder *coder, uint32_t position)\n{\n\tconst uint32_t pos_state = position & coder->pos_mask;\n\trc_bit(&coder->rc, &coder->is_match[coder->state][pos_state], 1);\n\trc_bit(&coder->rc, &coder->is_rep[coder->state], 0);\n\tmatch(coder, pos_state, UINT32_MAX, MATCH_LEN_MIN);\n}\n\n\n/// Number of bytes that a single encoding loop in lzma_lzma_encode() can\n/// consume from the dictionary. This limit comes from lzma_lzma_optimum()\n/// and may need to be updated if that function is significantly modified.\n#define LOOP_INPUT_MAX (OPTS + 1)\n\n\nextern lzma_ret\nlzma_lzma_encode(lzma_lzma1_encoder *restrict coder, lzma_mf *restrict mf,\n\t\tuint8_t *restrict out, size_t *restrict out_pos,\n\t\tsize_t out_size, uint32_t limit)\n{\n\t// Initialize the stream if no data has been encoded yet.\n\tif (!coder->is_initialized && !encode_init(coder, mf))\n\t\treturn LZMA_OK;\n\n\t// Get the lowest bits of the uncompressed offset from the LZ layer.\n\tuint32_t position = mf_position(mf);\n\n\twhile (true) {\n\t\t// Encode pending bits, if any. Calling this before encoding\n\t\t// the next symbol is needed only with plain LZMA, since\n\t\t// LZMA2 always provides big enough buffer to flush\n\t\t// everything out from the range encoder. For the same reason,\n\t\t// rc_encode() never returns true when this function is used\n\t\t// as part of LZMA2 encoder.\n\t\tif (rc_encode(&coder->rc, out, out_pos, out_size)) {\n\t\t\tassert(limit == UINT32_MAX);\n\t\t\treturn LZMA_OK;\n\t\t}\n\n\t\t// With LZMA2 we need to take care that compressed size of\n\t\t// a chunk doesn't get too big.\n\t\t// FIXME? Check if this could be improved.\n\t\tif (limit != UINT32_MAX\n\t\t\t\t&& (mf->read_pos - mf->read_ahead >= limit\n\t\t\t\t\t|| *out_pos + rc_pending(&coder->rc)\n\t\t\t\t\t\t>= LZMA2_CHUNK_MAX\n\t\t\t\t\t\t\t- LOOP_INPUT_MAX))\n\t\t\tbreak;\n\n\t\t// Check that there is some input to process.\n\t\tif (mf->read_pos >= mf->read_limit) {\n\t\t\tif (mf->action == LZMA_RUN)\n\t\t\t\treturn LZMA_OK;\n\n\t\t\tif (mf->read_ahead == 0)\n\t\t\t\tbreak;\n\t\t}\n\n\t\t// Get optimal match (repeat position and length).\n\t\t// Value ranges for pos:\n\t\t//   - [0, REPS): repeated match\n\t\t//   - [REPS, UINT32_MAX):\n\t\t//     match at (pos - REPS)\n\t\t//   - UINT32_MAX: not a match but a literal\n\t\t// Value ranges for len:\n\t\t//   - [MATCH_LEN_MIN, MATCH_LEN_MAX]\n\t\tuint32_t len;\n\t\tuint32_t back;\n\n\t\tif (coder->fast_mode)\n\t\t\tlzma_lzma_optimum_fast(coder, mf, &back, &len);\n\t\telse\n\t\t\tlzma_lzma_optimum_normal(\n\t\t\t\t\tcoder, mf, &back, &len, position);\n\n\t\tencode_symbol(coder, mf, back, len, position);\n\n\t\tposition += len;\n\t}\n\n\tif (!coder->is_flushed) {\n\t\tcoder->is_flushed = true;\n\n\t\t// We don't support encoding plain LZMA streams without EOPM,\n\t\t// and LZMA2 doesn't use EOPM at LZMA level.\n\t\tif (limit == UINT32_MAX)\n\t\t\tencode_eopm(coder, position);\n\n\t\t// Flush the remaining bytes from the range encoder.\n\t\trc_flush(&coder->rc);\n\n\t\t// Copy the remaining bytes to the output buffer. If there\n\t\t// isn't enough output space, we will copy out the remaining\n\t\t// bytes on the next call to this function by using\n\t\t// the rc_encode() call in the encoding loop above.\n\t\tif (rc_encode(&coder->rc, out, out_pos, out_size)) {\n\t\t\tassert(limit == UINT32_MAX);\n\t\t\treturn LZMA_OK;\n\t\t}\n\t}\n\n\t// Make it ready for the next LZMA2 chunk.\n\tcoder->is_flushed = false;\n\n\treturn LZMA_STREAM_END;\n}\n\n\nstatic lzma_ret\nlzma_encode(void *coder, lzma_mf *restrict mf,\n\t\tuint8_t *restrict out, size_t *restrict out_pos,\n\t\tsize_t out_size)\n{\n\t// Plain LZMA has no support for sync-flushing.\n\tif (unlikely(mf->action == LZMA_SYNC_FLUSH))\n\t\treturn LZMA_OPTIONS_ERROR;\n\n\treturn lzma_lzma_encode(coder, mf, out, out_pos, out_size, UINT32_MAX);\n}\n\n\n////////////////////\n// Initialization //\n////////////////////\n\nstatic bool\nis_options_valid(const lzma_options_lzma *options)\n{\n\t// Validate some of the options. LZ encoder validates nice_len too\n\t// but we need a valid value here earlier.\n\treturn is_lclppb_valid(options)\n\t\t\t&& options->nice_len >= MATCH_LEN_MIN\n\t\t\t&& options->nice_len <= MATCH_LEN_MAX\n\t\t\t&& (options->mode == LZMA_MODE_FAST\n\t\t\t\t|| options->mode == LZMA_MODE_NORMAL);\n}\n\n\nstatic void\nset_lz_options(lzma_lz_options *lz_options, const lzma_options_lzma *options)\n{\n\t// LZ encoder initialization does the validation for these so we\n\t// don't need to validate here.\n\tlz_options->before_size = OPTS;\n\tlz_options->dict_size = options->dict_size;\n\tlz_options->after_size = LOOP_INPUT_MAX;\n\tlz_options->match_len_max = MATCH_LEN_MAX;\n\tlz_options->nice_len = options->nice_len;\n\tlz_options->match_finder = options->mf;\n\tlz_options->depth = options->depth;\n\tlz_options->preset_dict = options->preset_dict;\n\tlz_options->preset_dict_size = options->preset_dict_size;\n\treturn;\n}\n\n\nstatic void\nlength_encoder_reset(lzma_length_encoder *lencoder,\n\t\tconst uint32_t num_pos_states, const bool fast_mode)\n{\n\tbit_reset(lencoder->choice);\n\tbit_reset(lencoder->choice2);\n\n\tfor (size_t pos_state = 0; pos_state < num_pos_states; ++pos_state) {\n\t\tbittree_reset(lencoder->low[pos_state], LEN_LOW_BITS);\n\t\tbittree_reset(lencoder->mid[pos_state], LEN_MID_BITS);\n\t}\n\n\tbittree_reset(lencoder->high, LEN_HIGH_BITS);\n\n\tif (!fast_mode)\n\t\tfor (uint32_t pos_state = 0; pos_state < num_pos_states;\n\t\t\t\t++pos_state)\n\t\t\tlength_update_prices(lencoder, pos_state);\n\n\treturn;\n}\n\n\nextern lzma_ret\nlzma_lzma_encoder_reset(lzma_lzma1_encoder *coder,\n\t\tconst lzma_options_lzma *options)\n{\n\tif (!is_options_valid(options))\n\t\treturn LZMA_OPTIONS_ERROR;\n\n\tcoder->pos_mask = (1U << options->pb) - 1;\n\tcoder->literal_context_bits = options->lc;\n\tcoder->literal_pos_mask = (1U << options->lp) - 1;\n\n\t// Range coder\n\trc_reset(&coder->rc);\n\n\t// State\n\tcoder->state = STATE_LIT_LIT;\n\tfor (size_t i = 0; i < REPS; ++i)\n\t\tcoder->reps[i] = 0;\n\n\tliteral_init(coder->literal, options->lc, options->lp);\n\n\t// Bit encoders\n\tfor (size_t i = 0; i < STATES; ++i) {\n\t\tfor (size_t j = 0; j <= coder->pos_mask; ++j) {\n\t\t\tbit_reset(coder->is_match[i][j]);\n\t\t\tbit_reset(coder->is_rep0_long[i][j]);\n\t\t}\n\n\t\tbit_reset(coder->is_rep[i]);\n\t\tbit_reset(coder->is_rep0[i]);\n\t\tbit_reset(coder->is_rep1[i]);\n\t\tbit_reset(coder->is_rep2[i]);\n\t}\n\n\tfor (size_t i = 0; i < FULL_DISTANCES - DIST_MODEL_END; ++i)\n\t\tbit_reset(coder->dist_special[i]);\n\n\t// Bit tree encoders\n\tfor (size_t i = 0; i < DIST_STATES; ++i)\n\t\tbittree_reset(coder->dist_slot[i], DIST_SLOT_BITS);\n\n\tbittree_reset(coder->dist_align, ALIGN_BITS);\n\n\t// Length encoders\n\tlength_encoder_reset(&coder->match_len_encoder,\n\t\t\t1U << options->pb, coder->fast_mode);\n\n\tlength_encoder_reset(&coder->rep_len_encoder,\n\t\t\t1U << options->pb, coder->fast_mode);\n\n\t// Price counts are incremented every time appropriate probabilities\n\t// are changed. price counts are set to zero when the price tables\n\t// are updated, which is done when the appropriate price counts have\n\t// big enough value, and lzma_mf.read_ahead == 0 which happens at\n\t// least every OPTS (a few thousand) possible price count increments.\n\t//\n\t// By resetting price counts to UINT32_MAX / 2, we make sure that the\n\t// price tables will be initialized before they will be used (since\n\t// the value is definitely big enough), and that it is OK to increment\n\t// price counts without risk of integer overflow (since UINT32_MAX / 2\n\t// is small enough). The current code doesn't increment price counts\n\t// before initializing price tables, but it maybe done in future if\n\t// we add support for saving the state between LZMA2 chunks.\n\tcoder->match_price_count = UINT32_MAX / 2;\n\tcoder->align_price_count = UINT32_MAX / 2;\n\n\tcoder->opts_end_index = 0;\n\tcoder->opts_current_index = 0;\n\n\treturn LZMA_OK;\n}\n\n\nextern lzma_ret\nlzma_lzma_encoder_create(void **coder_ptr,\n\t\tconst lzma_allocator *allocator,\n\t\tconst lzma_options_lzma *options, lzma_lz_options *lz_options)\n{\n\t// Allocate lzma_lzma1_encoder if it wasn't already allocated.\n\tif (*coder_ptr == NULL) {\n\t\t*coder_ptr = lzma_alloc(sizeof(lzma_lzma1_encoder), allocator);\n\t\tif (*coder_ptr == NULL)\n\t\t\treturn LZMA_MEM_ERROR;\n\t}\n\n\tlzma_lzma1_encoder *coder = *coder_ptr;\n\n\t// Set compression mode. We haven't validates the options yet,\n\t// but it's OK here, since nothing bad happens with invalid\n\t// options in the code below, and they will get rejected by\n\t// lzma_lzma_encoder_reset() call at the end of this function.\n\tswitch (options->mode) {\n\t\tcase LZMA_MODE_FAST:\n\t\t\tcoder->fast_mode = true;\n\t\t\tbreak;\n\n\t\tcase LZMA_MODE_NORMAL: {\n\t\t\tcoder->fast_mode = false;\n\n\t\t\t// Set dist_table_size.\n\t\t\t// Round the dictionary size up to next 2^n.\n\t\t\tuint32_t log_size = 0;\n\t\t\twhile ((UINT32_C(1) << log_size) < options->dict_size)\n\t\t\t\t++log_size;\n\n\t\t\tcoder->dist_table_size = log_size * 2;\n\n\t\t\t// Length encoders' price table size\n\t\t\tcoder->match_len_encoder.table_size\n\t\t\t\t= options->nice_len + 1 - MATCH_LEN_MIN;\n\t\t\tcoder->rep_len_encoder.table_size\n\t\t\t\t= options->nice_len + 1 - MATCH_LEN_MIN;\n\t\t\tbreak;\n\t\t}\n\n\t\tdefault:\n\t\t\treturn LZMA_OPTIONS_ERROR;\n\t}\n\n\t// We don't need to write the first byte as literal if there is\n\t// a non-empty preset dictionary. encode_init() wouldn't even work\n\t// if there is a non-empty preset dictionary, because encode_init()\n\t// assumes that position is zero and previous byte is also zero.\n\tcoder->is_initialized = options->preset_dict != NULL\n\t\t\t&& options->preset_dict_size > 0;\n\tcoder->is_flushed = false;\n\n\tset_lz_options(lz_options, options);\n\n\treturn lzma_lzma_encoder_reset(coder, options);\n}\n\n\nstatic lzma_ret\nlzma_encoder_init(lzma_lz_encoder *lz, const lzma_allocator *allocator,\n\t\tconst void *options, lzma_lz_options *lz_options)\n{\n\tlz->code = &lzma_encode;\n\treturn lzma_lzma_encoder_create(\n\t\t\t&lz->coder, allocator, options, lz_options);\n}\n\n\nextern lzma_ret\nlzma_lzma_encoder_init(lzma_next_coder *next, const lzma_allocator *allocator,\n\t\tconst lzma_filter_info *filters)\n{\n\treturn lzma_lz_encoder_init(\n\t\t\tnext, allocator, filters, &lzma_encoder_init);\n}\n\n\nextern uint64_t\nlzma_lzma_encoder_memusage(const void *options)\n{\n\tif (!is_options_valid(options))\n\t\treturn UINT64_MAX;\n\n\tlzma_lz_options lz_options;\n\tset_lz_options(&lz_options, options);\n\n\tconst uint64_t lz_memusage = lzma_lz_encoder_memusage(&lz_options);\n\tif (lz_memusage == UINT64_MAX)\n\t\treturn UINT64_MAX;\n\n\treturn (uint64_t)(sizeof(lzma_lzma1_encoder)) + lz_memusage;\n}\n\n\nextern bool\nlzma_lzma_lclppb_encode(const lzma_options_lzma *options, uint8_t *byte)\n{\n\tif (!is_lclppb_valid(options))\n\t\treturn true;\n\n\t*byte = (options->pb * 5 + options->lp) * 9 + options->lc;\n\tassert(*byte <= (4 * 5 + 4) * 9 + 8);\n\n\treturn false;\n}\n\n\n#ifdef HAVE_ENCODER_LZMA1\nextern lzma_ret\nlzma_lzma_props_encode(const void *options, uint8_t *out)\n{\n\tconst lzma_options_lzma *const opt = options;\n\n\tif (lzma_lzma_lclppb_encode(opt, out))\n\t\treturn LZMA_PROG_ERROR;\n\n\twrite32le(out + 1, opt->dict_size);\n\n\treturn LZMA_OK;\n}\n#endif\n\n\nextern LZMA_API(lzma_bool)\nlzma_mode_is_supported(lzma_mode mode)\n{\n\treturn mode == LZMA_MODE_FAST || mode == LZMA_MODE_NORMAL;\n}\n"
  },
  {
    "path": "external/xz/liblzma/lzma/lzma_encoder.h",
    "content": "///////////////////////////////////////////////////////////////////////////////\n//\n/// \\file       lzma_encoder.h\n/// \\brief      LZMA encoder API\n///\n//  Authors:    Igor Pavlov\n//              Lasse Collin\n//\n//  This file has been put into the public domain.\n//  You can do whatever you want with this file.\n//\n///////////////////////////////////////////////////////////////////////////////\n\n#ifndef LZMA_LZMA_ENCODER_H\n#define LZMA_LZMA_ENCODER_H\n\n#include \"common.h\"\n\n\ntypedef struct lzma_lzma1_encoder_s lzma_lzma1_encoder;\n\n\nextern lzma_ret lzma_lzma_encoder_init(lzma_next_coder *next,\n\t\tconst lzma_allocator *allocator,\n\t\tconst lzma_filter_info *filters);\n\n\nextern uint64_t lzma_lzma_encoder_memusage(const void *options);\n\nextern lzma_ret lzma_lzma_props_encode(const void *options, uint8_t *out);\n\n\n/// Encodes lc/lp/pb into one byte. Returns false on success and true on error.\nextern bool lzma_lzma_lclppb_encode(\n\t\tconst lzma_options_lzma *options, uint8_t *byte);\n\n\n#ifdef LZMA_LZ_ENCODER_H\n\n/// Initializes raw LZMA encoder; this is used by LZMA2.\nextern lzma_ret lzma_lzma_encoder_create(\n\t\tvoid **coder_ptr, const lzma_allocator *allocator,\n\t\tconst lzma_options_lzma *options, lzma_lz_options *lz_options);\n\n\n/// Resets an already initialized LZMA encoder; this is used by LZMA2.\nextern lzma_ret lzma_lzma_encoder_reset(\n\t\tlzma_lzma1_encoder *coder, const lzma_options_lzma *options);\n\n\nextern lzma_ret lzma_lzma_encode(lzma_lzma1_encoder *restrict coder,\n\t\tlzma_mf *restrict mf, uint8_t *restrict out,\n\t\tsize_t *restrict out_pos, size_t out_size,\n\t\tuint32_t read_limit);\n\n#endif\n\n#endif\n"
  },
  {
    "path": "external/xz/liblzma/lzma/lzma_encoder_optimum_fast.c",
    "content": "///////////////////////////////////////////////////////////////////////////////\n//\n/// \\file       lzma_encoder_optimum_fast.c\n//\n//  Author:     Igor Pavlov\n//\n//  This file has been put into the public domain.\n//  You can do whatever you want with this file.\n//\n///////////////////////////////////////////////////////////////////////////////\n\n#include \"lzma_encoder_private.h\"\n#include \"memcmplen.h\"\n\n\n#define change_pair(small_dist, big_dist) \\\n\t(((big_dist) >> 7) > (small_dist))\n\n\nextern void\nlzma_lzma_optimum_fast(lzma_lzma1_encoder *restrict coder,\n\t\tlzma_mf *restrict mf,\n\t\tuint32_t *restrict back_res, uint32_t *restrict len_res)\n{\n\tconst uint32_t nice_len = mf->nice_len;\n\n\tuint32_t len_main;\n\tuint32_t matches_count;\n\tif (mf->read_ahead == 0) {\n\t\tlen_main = mf_find(mf, &matches_count, coder->matches);\n\t} else {\n\t\tassert(mf->read_ahead == 1);\n\t\tlen_main = coder->longest_match_length;\n\t\tmatches_count = coder->matches_count;\n\t}\n\n\tconst uint8_t *buf = mf_ptr(mf) - 1;\n\tconst uint32_t buf_avail = my_min(mf_avail(mf) + 1, MATCH_LEN_MAX);\n\n\tif (buf_avail < 2) {\n\t\t// There's not enough input left to encode a match.\n\t\t*back_res = UINT32_MAX;\n\t\t*len_res = 1;\n\t\treturn;\n\t}\n\n\t// Look for repeated matches; scan the previous four match distances\n\tuint32_t rep_len = 0;\n\tuint32_t rep_index = 0;\n\n\tfor (uint32_t i = 0; i < REPS; ++i) {\n\t\t// Pointer to the beginning of the match candidate\n\t\tconst uint8_t *const buf_back = buf - coder->reps[i] - 1;\n\n\t\t// If the first two bytes (2 == MATCH_LEN_MIN) do not match,\n\t\t// this rep is not useful.\n\t\tif (not_equal_16(buf, buf_back))\n\t\t\tcontinue;\n\n\t\t// The first two bytes matched.\n\t\t// Calculate the length of the match.\n\t\tconst uint32_t len = lzma_memcmplen(\n\t\t\t\tbuf, buf_back, 2, buf_avail);\n\n\t\t// If we have found a repeated match that is at least\n\t\t// nice_len long, return it immediately.\n\t\tif (len >= nice_len) {\n\t\t\t*back_res = i;\n\t\t\t*len_res = len;\n\t\t\tmf_skip(mf, len - 1);\n\t\t\treturn;\n\t\t}\n\n\t\tif (len > rep_len) {\n\t\t\trep_index = i;\n\t\t\trep_len = len;\n\t\t}\n\t}\n\n\t// We didn't find a long enough repeated match. Encode it as a normal\n\t// match if the match length is at least nice_len.\n\tif (len_main >= nice_len) {\n\t\t*back_res = coder->matches[matches_count - 1].dist + REPS;\n\t\t*len_res = len_main;\n\t\tmf_skip(mf, len_main - 1);\n\t\treturn;\n\t}\n\n\tuint32_t back_main = 0;\n\tif (len_main >= 2) {\n\t\tback_main = coder->matches[matches_count - 1].dist;\n\n\t\twhile (matches_count > 1 && len_main ==\n\t\t\t\tcoder->matches[matches_count - 2].len + 1) {\n\t\t\tif (!change_pair(coder->matches[\n\t\t\t\t\t\tmatches_count - 2].dist,\n\t\t\t\t\tback_main))\n\t\t\t\tbreak;\n\n\t\t\t--matches_count;\n\t\t\tlen_main = coder->matches[matches_count - 1].len;\n\t\t\tback_main = coder->matches[matches_count - 1].dist;\n\t\t}\n\n\t\tif (len_main == 2 && back_main >= 0x80)\n\t\t\tlen_main = 1;\n\t}\n\n\tif (rep_len >= 2) {\n\t\tif (rep_len + 1 >= len_main\n\t\t\t\t|| (rep_len + 2 >= len_main\n\t\t\t\t\t&& back_main > (UINT32_C(1) << 9))\n\t\t\t\t|| (rep_len + 3 >= len_main\n\t\t\t\t\t&& back_main > (UINT32_C(1) << 15))) {\n\t\t\t*back_res = rep_index;\n\t\t\t*len_res = rep_len;\n\t\t\tmf_skip(mf, rep_len - 1);\n\t\t\treturn;\n\t\t}\n\t}\n\n\tif (len_main < 2 || buf_avail <= 2) {\n\t\t*back_res = UINT32_MAX;\n\t\t*len_res = 1;\n\t\treturn;\n\t}\n\n\t// Get the matches for the next byte. If we find a better match,\n\t// the current byte is encoded as a literal.\n\tcoder->longest_match_length = mf_find(mf,\n\t\t\t&coder->matches_count, coder->matches);\n\n\tif (coder->longest_match_length >= 2) {\n\t\tconst uint32_t new_dist = coder->matches[\n\t\t\t\tcoder->matches_count - 1].dist;\n\n\t\tif ((coder->longest_match_length >= len_main\n\t\t\t\t\t&& new_dist < back_main)\n\t\t\t\t|| (coder->longest_match_length == len_main + 1\n\t\t\t\t\t&& !change_pair(back_main, new_dist))\n\t\t\t\t|| (coder->longest_match_length > len_main + 1)\n\t\t\t\t|| (coder->longest_match_length + 1 >= len_main\n\t\t\t\t\t&& len_main >= 3\n\t\t\t\t\t&& change_pair(new_dist, back_main))) {\n\t\t\t*back_res = UINT32_MAX;\n\t\t\t*len_res = 1;\n\t\t\treturn;\n\t\t}\n\t}\n\n\t// In contrast to LZMA SDK, dictionary could not have been moved\n\t// between mf_find() calls, thus it is safe to just increment\n\t// the old buf pointer instead of recalculating it with mf_ptr().\n\t++buf;\n\n\tconst uint32_t limit = my_max(2, len_main - 1);\n\n\tfor (uint32_t i = 0; i < REPS; ++i) {\n\t\tif (memcmp(buf, buf - coder->reps[i] - 1, limit) == 0) {\n\t\t\t*back_res = UINT32_MAX;\n\t\t\t*len_res = 1;\n\t\t\treturn;\n\t\t}\n\t}\n\n\t*back_res = back_main + REPS;\n\t*len_res = len_main;\n\tmf_skip(mf, len_main - 2);\n\treturn;\n}\n"
  },
  {
    "path": "external/xz/liblzma/lzma/lzma_encoder_optimum_normal.c",
    "content": "///////////////////////////////////////////////////////////////////////////////\n//\n/// \\file       lzma_encoder_optimum_normal.c\n//\n//  Author:     Igor Pavlov\n//\n//  This file has been put into the public domain.\n//  You can do whatever you want with this file.\n//\n///////////////////////////////////////////////////////////////////////////////\n\n#include \"lzma_encoder_private.h\"\n#include \"fastpos.h\"\n#include \"memcmplen.h\"\n\n\n////////////\n// Prices //\n////////////\n\nstatic uint32_t\nget_literal_price(const lzma_lzma1_encoder *const coder, const uint32_t pos,\n\t\tconst uint32_t prev_byte, const bool match_mode,\n\t\tuint32_t match_byte, uint32_t symbol)\n{\n\tconst probability *const subcoder = literal_subcoder(coder->literal,\n\t\t\tcoder->literal_context_bits, coder->literal_pos_mask,\n\t\t\tpos, prev_byte);\n\n\tuint32_t price = 0;\n\n\tif (!match_mode) {\n\t\tprice = rc_bittree_price(subcoder, 8, symbol);\n\t} else {\n\t\tuint32_t offset = 0x100;\n\t\tsymbol += UINT32_C(1) << 8;\n\n\t\tdo {\n\t\t\tmatch_byte <<= 1;\n\n\t\t\tconst uint32_t match_bit = match_byte & offset;\n\t\t\tconst uint32_t subcoder_index\n\t\t\t\t\t= offset + match_bit + (symbol >> 8);\n\t\t\tconst uint32_t bit = (symbol >> 7) & 1;\n\t\t\tprice += rc_bit_price(subcoder[subcoder_index], bit);\n\n\t\t\tsymbol <<= 1;\n\t\t\toffset &= ~(match_byte ^ symbol);\n\n\t\t} while (symbol < (UINT32_C(1) << 16));\n\t}\n\n\treturn price;\n}\n\n\nstatic inline uint32_t\nget_len_price(const lzma_length_encoder *const lencoder,\n\t\tconst uint32_t len, const uint32_t pos_state)\n{\n\t// NOTE: Unlike the other price tables, length prices are updated\n\t// in lzma_encoder.c\n\treturn lencoder->prices[pos_state][len - MATCH_LEN_MIN];\n}\n\n\nstatic inline uint32_t\nget_short_rep_price(const lzma_lzma1_encoder *const coder,\n\t\tconst lzma_lzma_state state, const uint32_t pos_state)\n{\n\treturn rc_bit_0_price(coder->is_rep0[state])\n\t\t+ rc_bit_0_price(coder->is_rep0_long[state][pos_state]);\n}\n\n\nstatic inline uint32_t\nget_pure_rep_price(const lzma_lzma1_encoder *const coder, const uint32_t rep_index,\n\t\tconst lzma_lzma_state state, uint32_t pos_state)\n{\n\tuint32_t price;\n\n\tif (rep_index == 0) {\n\t\tprice = rc_bit_0_price(coder->is_rep0[state]);\n\t\tprice += rc_bit_1_price(coder->is_rep0_long[state][pos_state]);\n\t} else {\n\t\tprice = rc_bit_1_price(coder->is_rep0[state]);\n\n\t\tif (rep_index == 1) {\n\t\t\tprice += rc_bit_0_price(coder->is_rep1[state]);\n\t\t} else {\n\t\t\tprice += rc_bit_1_price(coder->is_rep1[state]);\n\t\t\tprice += rc_bit_price(coder->is_rep2[state],\n\t\t\t\t\trep_index - 2);\n\t\t}\n\t}\n\n\treturn price;\n}\n\n\nstatic inline uint32_t\nget_rep_price(const lzma_lzma1_encoder *const coder, const uint32_t rep_index,\n\t\tconst uint32_t len, const lzma_lzma_state state,\n\t\tconst uint32_t pos_state)\n{\n\treturn get_len_price(&coder->rep_len_encoder, len, pos_state)\n\t\t+ get_pure_rep_price(coder, rep_index, state, pos_state);\n}\n\n\nstatic inline uint32_t\nget_dist_len_price(const lzma_lzma1_encoder *const coder, const uint32_t dist,\n\t\tconst uint32_t len, const uint32_t pos_state)\n{\n\tconst uint32_t dist_state = get_dist_state(len);\n\tuint32_t price;\n\n\tif (dist < FULL_DISTANCES) {\n\t\tprice = coder->dist_prices[dist_state][dist];\n\t} else {\n\t\tconst uint32_t dist_slot = get_dist_slot_2(dist);\n\t\tprice = coder->dist_slot_prices[dist_state][dist_slot]\n\t\t\t\t+ coder->align_prices[dist & ALIGN_MASK];\n\t}\n\n\tprice += get_len_price(&coder->match_len_encoder, len, pos_state);\n\n\treturn price;\n}\n\n\nstatic void\nfill_dist_prices(lzma_lzma1_encoder *coder)\n{\n\tfor (uint32_t dist_state = 0; dist_state < DIST_STATES; ++dist_state) {\n\n\t\tuint32_t *const dist_slot_prices\n\t\t\t\t= coder->dist_slot_prices[dist_state];\n\n\t\t// Price to encode the dist_slot.\n\t\tfor (uint32_t dist_slot = 0;\n\t\t\t\tdist_slot < coder->dist_table_size; ++dist_slot)\n\t\t\tdist_slot_prices[dist_slot] = rc_bittree_price(\n\t\t\t\t\tcoder->dist_slot[dist_state],\n\t\t\t\t\tDIST_SLOT_BITS, dist_slot);\n\n\t\t// For matches with distance >= FULL_DISTANCES, add the price\n\t\t// of the direct bits part of the match distance. (Align bits\n\t\t// are handled by fill_align_prices()).\n\t\tfor (uint32_t dist_slot = DIST_MODEL_END;\n\t\t\t\tdist_slot < coder->dist_table_size;\n\t\t\t\t++dist_slot)\n\t\t\tdist_slot_prices[dist_slot] += rc_direct_price(\n\t\t\t\t\t((dist_slot >> 1) - 1) - ALIGN_BITS);\n\n\t\t// Distances in the range [0, 3] are fully encoded with\n\t\t// dist_slot, so they are used for coder->dist_prices\n\t\t// as is.\n\t\tfor (uint32_t i = 0; i < DIST_MODEL_START; ++i)\n\t\t\tcoder->dist_prices[dist_state][i]\n\t\t\t\t\t= dist_slot_prices[i];\n\t}\n\n\t// Distances in the range [4, 127] depend on dist_slot and\n\t// dist_special. We do this in a loop separate from the above\n\t// loop to avoid redundant calls to get_dist_slot().\n\tfor (uint32_t i = DIST_MODEL_START; i < FULL_DISTANCES; ++i) {\n\t\tconst uint32_t dist_slot = get_dist_slot(i);\n\t\tconst uint32_t footer_bits = ((dist_slot >> 1) - 1);\n\t\tconst uint32_t base = (2 | (dist_slot & 1)) << footer_bits;\n\t\tconst uint32_t price = rc_bittree_reverse_price(\n\t\t\t\tcoder->dist_special + base - dist_slot - 1,\n\t\t\t\tfooter_bits, i - base);\n\n\t\tfor (uint32_t dist_state = 0; dist_state < DIST_STATES;\n\t\t\t\t++dist_state)\n\t\t\tcoder->dist_prices[dist_state][i]\n\t\t\t\t\t= price + coder->dist_slot_prices[\n\t\t\t\t\t\tdist_state][dist_slot];\n\t}\n\n\tcoder->match_price_count = 0;\n\treturn;\n}\n\n\nstatic void\nfill_align_prices(lzma_lzma1_encoder *coder)\n{\n\tfor (uint32_t i = 0; i < ALIGN_SIZE; ++i)\n\t\tcoder->align_prices[i] = rc_bittree_reverse_price(\n\t\t\t\tcoder->dist_align, ALIGN_BITS, i);\n\n\tcoder->align_price_count = 0;\n\treturn;\n}\n\n\n/////////////\n// Optimal //\n/////////////\n\nstatic inline void\nmake_literal(lzma_optimal *optimal)\n{\n\toptimal->back_prev = UINT32_MAX;\n\toptimal->prev_1_is_literal = false;\n}\n\n\nstatic inline void\nmake_short_rep(lzma_optimal *optimal)\n{\n\toptimal->back_prev = 0;\n\toptimal->prev_1_is_literal = false;\n}\n\n\n#define is_short_rep(optimal) \\\n\t((optimal).back_prev == 0)\n\n\nstatic void\nbackward(lzma_lzma1_encoder *restrict coder, uint32_t *restrict len_res,\n\t\tuint32_t *restrict back_res, uint32_t cur)\n{\n\tcoder->opts_end_index = cur;\n\n\tuint32_t pos_mem = coder->opts[cur].pos_prev;\n\tuint32_t back_mem = coder->opts[cur].back_prev;\n\n\tdo {\n\t\tif (coder->opts[cur].prev_1_is_literal) {\n\t\t\tmake_literal(&coder->opts[pos_mem]);\n\t\t\tcoder->opts[pos_mem].pos_prev = pos_mem - 1;\n\n\t\t\tif (coder->opts[cur].prev_2) {\n\t\t\t\tcoder->opts[pos_mem - 1].prev_1_is_literal\n\t\t\t\t\t\t= false;\n\t\t\t\tcoder->opts[pos_mem - 1].pos_prev\n\t\t\t\t\t\t= coder->opts[cur].pos_prev_2;\n\t\t\t\tcoder->opts[pos_mem - 1].back_prev\n\t\t\t\t\t\t= coder->opts[cur].back_prev_2;\n\t\t\t}\n\t\t}\n\n\t\tconst uint32_t pos_prev = pos_mem;\n\t\tconst uint32_t back_cur = back_mem;\n\n\t\tback_mem = coder->opts[pos_prev].back_prev;\n\t\tpos_mem = coder->opts[pos_prev].pos_prev;\n\n\t\tcoder->opts[pos_prev].back_prev = back_cur;\n\t\tcoder->opts[pos_prev].pos_prev = cur;\n\t\tcur = pos_prev;\n\n\t} while (cur != 0);\n\n\tcoder->opts_current_index = coder->opts[0].pos_prev;\n\t*len_res = coder->opts[0].pos_prev;\n\t*back_res = coder->opts[0].back_prev;\n\n\treturn;\n}\n\n\n//////////\n// Main //\n//////////\n\nstatic inline uint32_t\nhelper1(lzma_lzma1_encoder *restrict coder, lzma_mf *restrict mf,\n\t\tuint32_t *restrict back_res, uint32_t *restrict len_res,\n\t\tuint32_t position)\n{\n\tconst uint32_t nice_len = mf->nice_len;\n\n\tuint32_t len_main;\n\tuint32_t matches_count;\n\n\tif (mf->read_ahead == 0) {\n\t\tlen_main = mf_find(mf, &matches_count, coder->matches);\n\t} else {\n\t\tassert(mf->read_ahead == 1);\n\t\tlen_main = coder->longest_match_length;\n\t\tmatches_count = coder->matches_count;\n\t}\n\n\tconst uint32_t buf_avail = my_min(mf_avail(mf) + 1, MATCH_LEN_MAX);\n\tif (buf_avail < 2) {\n\t\t*back_res = UINT32_MAX;\n\t\t*len_res = 1;\n\t\treturn UINT32_MAX;\n\t}\n\n\tconst uint8_t *const buf = mf_ptr(mf) - 1;\n\n\tuint32_t rep_lens[REPS];\n\tuint32_t rep_max_index = 0;\n\n\tfor (uint32_t i = 0; i < REPS; ++i) {\n\t\tconst uint8_t *const buf_back = buf - coder->reps[i] - 1;\n\n\t\tif (not_equal_16(buf, buf_back)) {\n\t\t\trep_lens[i] = 0;\n\t\t\tcontinue;\n\t\t}\n\n\t\trep_lens[i] = lzma_memcmplen(buf, buf_back, 2, buf_avail);\n\n\t\tif (rep_lens[i] > rep_lens[rep_max_index])\n\t\t\trep_max_index = i;\n\t}\n\n\tif (rep_lens[rep_max_index] >= nice_len) {\n\t\t*back_res = rep_max_index;\n\t\t*len_res = rep_lens[rep_max_index];\n\t\tmf_skip(mf, *len_res - 1);\n\t\treturn UINT32_MAX;\n\t}\n\n\n\tif (len_main >= nice_len) {\n\t\t*back_res = coder->matches[matches_count - 1].dist + REPS;\n\t\t*len_res = len_main;\n\t\tmf_skip(mf, len_main - 1);\n\t\treturn UINT32_MAX;\n\t}\n\n\tconst uint8_t current_byte = *buf;\n\tconst uint8_t match_byte = *(buf - coder->reps[0] - 1);\n\n\tif (len_main < 2 && current_byte != match_byte\n\t\t\t&& rep_lens[rep_max_index] < 2) {\n\t\t*back_res = UINT32_MAX;\n\t\t*len_res = 1;\n\t\treturn UINT32_MAX;\n\t}\n\n\tcoder->opts[0].state = coder->state;\n\n\tconst uint32_t pos_state = position & coder->pos_mask;\n\n\tcoder->opts[1].price = rc_bit_0_price(\n\t\t\t\tcoder->is_match[coder->state][pos_state])\n\t\t\t+ get_literal_price(coder, position, buf[-1],\n\t\t\t\t!is_literal_state(coder->state),\n\t\t\t\tmatch_byte, current_byte);\n\n\tmake_literal(&coder->opts[1]);\n\n\tconst uint32_t match_price = rc_bit_1_price(\n\t\t\tcoder->is_match[coder->state][pos_state]);\n\tconst uint32_t rep_match_price = match_price\n\t\t\t+ rc_bit_1_price(coder->is_rep[coder->state]);\n\n\tif (match_byte == current_byte) {\n\t\tconst uint32_t short_rep_price = rep_match_price\n\t\t\t\t+ get_short_rep_price(\n\t\t\t\t\tcoder, coder->state, pos_state);\n\n\t\tif (short_rep_price < coder->opts[1].price) {\n\t\t\tcoder->opts[1].price = short_rep_price;\n\t\t\tmake_short_rep(&coder->opts[1]);\n\t\t}\n\t}\n\n\tconst uint32_t len_end = my_max(len_main, rep_lens[rep_max_index]);\n\n\tif (len_end < 2) {\n\t\t*back_res = coder->opts[1].back_prev;\n\t\t*len_res = 1;\n\t\treturn UINT32_MAX;\n\t}\n\n\tcoder->opts[1].pos_prev = 0;\n\n\tfor (uint32_t i = 0; i < REPS; ++i)\n\t\tcoder->opts[0].backs[i] = coder->reps[i];\n\n\tuint32_t len = len_end;\n\tdo {\n\t\tcoder->opts[len].price = RC_INFINITY_PRICE;\n\t} while (--len >= 2);\n\n\n\tfor (uint32_t i = 0; i < REPS; ++i) {\n\t\tuint32_t rep_len = rep_lens[i];\n\t\tif (rep_len < 2)\n\t\t\tcontinue;\n\n\t\tconst uint32_t price = rep_match_price + get_pure_rep_price(\n\t\t\t\tcoder, i, coder->state, pos_state);\n\n\t\tdo {\n\t\t\tconst uint32_t cur_and_len_price = price\n\t\t\t\t\t+ get_len_price(\n\t\t\t\t\t\t&coder->rep_len_encoder,\n\t\t\t\t\t\trep_len, pos_state);\n\n\t\t\tif (cur_and_len_price < coder->opts[rep_len].price) {\n\t\t\t\tcoder->opts[rep_len].price = cur_and_len_price;\n\t\t\t\tcoder->opts[rep_len].pos_prev = 0;\n\t\t\t\tcoder->opts[rep_len].back_prev = i;\n\t\t\t\tcoder->opts[rep_len].prev_1_is_literal = false;\n\t\t\t}\n\t\t} while (--rep_len >= 2);\n\t}\n\n\n\tconst uint32_t normal_match_price = match_price\n\t\t\t+ rc_bit_0_price(coder->is_rep[coder->state]);\n\n\tlen = rep_lens[0] >= 2 ? rep_lens[0] + 1 : 2;\n\tif (len <= len_main) {\n\t\tuint32_t i = 0;\n\t\twhile (len > coder->matches[i].len)\n\t\t\t++i;\n\n\t\tfor(; ; ++len) {\n\t\t\tconst uint32_t dist = coder->matches[i].dist;\n\t\t\tconst uint32_t cur_and_len_price = normal_match_price\n\t\t\t\t\t+ get_dist_len_price(coder,\n\t\t\t\t\t\tdist, len, pos_state);\n\n\t\t\tif (cur_and_len_price < coder->opts[len].price) {\n\t\t\t\tcoder->opts[len].price = cur_and_len_price;\n\t\t\t\tcoder->opts[len].pos_prev = 0;\n\t\t\t\tcoder->opts[len].back_prev = dist + REPS;\n\t\t\t\tcoder->opts[len].prev_1_is_literal = false;\n\t\t\t}\n\n\t\t\tif (len == coder->matches[i].len)\n\t\t\t\tif (++i == matches_count)\n\t\t\t\t\tbreak;\n\t\t}\n\t}\n\n\treturn len_end;\n}\n\n\nstatic inline uint32_t\nhelper2(lzma_lzma1_encoder *coder, uint32_t *reps, const uint8_t *buf,\n\t\tuint32_t len_end, uint32_t position, const uint32_t cur,\n\t\tconst uint32_t nice_len, const uint32_t buf_avail_full)\n{\n\tuint32_t matches_count = coder->matches_count;\n\tuint32_t new_len = coder->longest_match_length;\n\tuint32_t pos_prev = coder->opts[cur].pos_prev;\n\tlzma_lzma_state state;\n\n\tif (coder->opts[cur].prev_1_is_literal) {\n\t\t--pos_prev;\n\n\t\tif (coder->opts[cur].prev_2) {\n\t\t\tstate = coder->opts[coder->opts[cur].pos_prev_2].state;\n\n\t\t\tif (coder->opts[cur].back_prev_2 < REPS)\n\t\t\t\tupdate_long_rep(state);\n\t\t\telse\n\t\t\t\tupdate_match(state);\n\n\t\t} else {\n\t\t\tstate = coder->opts[pos_prev].state;\n\t\t}\n\n\t\tupdate_literal(state);\n\n\t} else {\n\t\tstate = coder->opts[pos_prev].state;\n\t}\n\n\tif (pos_prev == cur - 1) {\n\t\tif (is_short_rep(coder->opts[cur]))\n\t\t\tupdate_short_rep(state);\n\t\telse\n\t\t\tupdate_literal(state);\n\t} else {\n\t\tuint32_t pos;\n\t\tif (coder->opts[cur].prev_1_is_literal\n\t\t\t\t&& coder->opts[cur].prev_2) {\n\t\t\tpos_prev = coder->opts[cur].pos_prev_2;\n\t\t\tpos = coder->opts[cur].back_prev_2;\n\t\t\tupdate_long_rep(state);\n\t\t} else {\n\t\t\tpos = coder->opts[cur].back_prev;\n\t\t\tif (pos < REPS)\n\t\t\t\tupdate_long_rep(state);\n\t\t\telse\n\t\t\t\tupdate_match(state);\n\t\t}\n\n\t\tif (pos < REPS) {\n\t\t\treps[0] = coder->opts[pos_prev].backs[pos];\n\n\t\t\tuint32_t i;\n\t\t\tfor (i = 1; i <= pos; ++i)\n\t\t\t\treps[i] = coder->opts[pos_prev].backs[i - 1];\n\n\t\t\tfor (; i < REPS; ++i)\n\t\t\t\treps[i] = coder->opts[pos_prev].backs[i];\n\n\t\t} else {\n\t\t\treps[0] = pos - REPS;\n\n\t\t\tfor (uint32_t i = 1; i < REPS; ++i)\n\t\t\t\treps[i] = coder->opts[pos_prev].backs[i - 1];\n\t\t}\n\t}\n\n\tcoder->opts[cur].state = state;\n\n\tfor (uint32_t i = 0; i < REPS; ++i)\n\t\tcoder->opts[cur].backs[i] = reps[i];\n\n\tconst uint32_t cur_price = coder->opts[cur].price;\n\n\tconst uint8_t current_byte = *buf;\n\tconst uint8_t match_byte = *(buf - reps[0] - 1);\n\n\tconst uint32_t pos_state = position & coder->pos_mask;\n\n\tconst uint32_t cur_and_1_price = cur_price\n\t\t\t+ rc_bit_0_price(coder->is_match[state][pos_state])\n\t\t\t+ get_literal_price(coder, position, buf[-1],\n\t\t\t!is_literal_state(state), match_byte, current_byte);\n\n\tbool next_is_literal = false;\n\n\tif (cur_and_1_price < coder->opts[cur + 1].price) {\n\t\tcoder->opts[cur + 1].price = cur_and_1_price;\n\t\tcoder->opts[cur + 1].pos_prev = cur;\n\t\tmake_literal(&coder->opts[cur + 1]);\n\t\tnext_is_literal = true;\n\t}\n\n\tconst uint32_t match_price = cur_price\n\t\t\t+ rc_bit_1_price(coder->is_match[state][pos_state]);\n\tconst uint32_t rep_match_price = match_price\n\t\t\t+ rc_bit_1_price(coder->is_rep[state]);\n\n\tif (match_byte == current_byte\n\t\t\t&& !(coder->opts[cur + 1].pos_prev < cur\n\t\t\t\t&& coder->opts[cur + 1].back_prev == 0)) {\n\n\t\tconst uint32_t short_rep_price = rep_match_price\n\t\t\t\t+ get_short_rep_price(coder, state, pos_state);\n\n\t\tif (short_rep_price <= coder->opts[cur + 1].price) {\n\t\t\tcoder->opts[cur + 1].price = short_rep_price;\n\t\t\tcoder->opts[cur + 1].pos_prev = cur;\n\t\t\tmake_short_rep(&coder->opts[cur + 1]);\n\t\t\tnext_is_literal = true;\n\t\t}\n\t}\n\n\tif (buf_avail_full < 2)\n\t\treturn len_end;\n\n\tconst uint32_t buf_avail = my_min(buf_avail_full, nice_len);\n\n\tif (!next_is_literal && match_byte != current_byte) { // speed optimization\n\t\t// try literal + rep0\n\t\tconst uint8_t *const buf_back = buf - reps[0] - 1;\n\t\tconst uint32_t limit = my_min(buf_avail_full, nice_len + 1);\n\n\t\tconst uint32_t len_test = lzma_memcmplen(buf, buf_back, 1, limit) - 1;\n\n\t\tif (len_test >= 2) {\n\t\t\tlzma_lzma_state state_2 = state;\n\t\t\tupdate_literal(state_2);\n\n\t\t\tconst uint32_t pos_state_next = (position + 1) & coder->pos_mask;\n\t\t\tconst uint32_t next_rep_match_price = cur_and_1_price\n\t\t\t\t\t+ rc_bit_1_price(coder->is_match[state_2][pos_state_next])\n\t\t\t\t\t+ rc_bit_1_price(coder->is_rep[state_2]);\n\n\t\t\t//for (; len_test >= 2; --len_test) {\n\t\t\tconst uint32_t offset = cur + 1 + len_test;\n\n\t\t\twhile (len_end < offset)\n\t\t\t\tcoder->opts[++len_end].price = RC_INFINITY_PRICE;\n\n\t\t\tconst uint32_t cur_and_len_price = next_rep_match_price\n\t\t\t\t\t+ get_rep_price(coder, 0, len_test,\n\t\t\t\t\t\tstate_2, pos_state_next);\n\n\t\t\tif (cur_and_len_price < coder->opts[offset].price) {\n\t\t\t\tcoder->opts[offset].price = cur_and_len_price;\n\t\t\t\tcoder->opts[offset].pos_prev = cur + 1;\n\t\t\t\tcoder->opts[offset].back_prev = 0;\n\t\t\t\tcoder->opts[offset].prev_1_is_literal = true;\n\t\t\t\tcoder->opts[offset].prev_2 = false;\n\t\t\t}\n\t\t\t//}\n\t\t}\n\t}\n\n\n\tuint32_t start_len = 2; // speed optimization\n\n\tfor (uint32_t rep_index = 0; rep_index < REPS; ++rep_index) {\n\t\tconst uint8_t *const buf_back = buf - reps[rep_index] - 1;\n\t\tif (not_equal_16(buf, buf_back))\n\t\t\tcontinue;\n\n\t\tuint32_t len_test = lzma_memcmplen(buf, buf_back, 2, buf_avail);\n\n\t\twhile (len_end < cur + len_test)\n\t\t\tcoder->opts[++len_end].price = RC_INFINITY_PRICE;\n\n\t\tconst uint32_t len_test_temp = len_test;\n\t\tconst uint32_t price = rep_match_price + get_pure_rep_price(\n\t\t\t\tcoder, rep_index, state, pos_state);\n\n\t\tdo {\n\t\t\tconst uint32_t cur_and_len_price = price\n\t\t\t\t\t+ get_len_price(&coder->rep_len_encoder,\n\t\t\t\t\t\t\tlen_test, pos_state);\n\n\t\t\tif (cur_and_len_price < coder->opts[cur + len_test].price) {\n\t\t\t\tcoder->opts[cur + len_test].price = cur_and_len_price;\n\t\t\t\tcoder->opts[cur + len_test].pos_prev = cur;\n\t\t\t\tcoder->opts[cur + len_test].back_prev = rep_index;\n\t\t\t\tcoder->opts[cur + len_test].prev_1_is_literal = false;\n\t\t\t}\n\t\t} while (--len_test >= 2);\n\n\t\tlen_test = len_test_temp;\n\n\t\tif (rep_index == 0)\n\t\t\tstart_len = len_test + 1;\n\n\n\t\tuint32_t len_test_2 = len_test + 1;\n\t\tconst uint32_t limit = my_min(buf_avail_full,\n\t\t\t\tlen_test_2 + nice_len);\n\t\t// NOTE: len_test_2 may be greater than limit so the call to\n\t\t// lzma_memcmplen() must be done conditionally.\n\t\tif (len_test_2 < limit)\n\t\t\tlen_test_2 = lzma_memcmplen(buf, buf_back, len_test_2, limit);\n\n\t\tlen_test_2 -= len_test + 1;\n\n\t\tif (len_test_2 >= 2) {\n\t\t\tlzma_lzma_state state_2 = state;\n\t\t\tupdate_long_rep(state_2);\n\n\t\t\tuint32_t pos_state_next = (position + len_test) & coder->pos_mask;\n\n\t\t\tconst uint32_t cur_and_len_literal_price = price\n\t\t\t\t\t+ get_len_price(&coder->rep_len_encoder,\n\t\t\t\t\t\tlen_test, pos_state)\n\t\t\t\t\t+ rc_bit_0_price(coder->is_match[state_2][pos_state_next])\n\t\t\t\t\t+ get_literal_price(coder, position + len_test,\n\t\t\t\t\t\tbuf[len_test - 1], true,\n\t\t\t\t\t\tbuf_back[len_test], buf[len_test]);\n\n\t\t\tupdate_literal(state_2);\n\n\t\t\tpos_state_next = (position + len_test + 1) & coder->pos_mask;\n\n\t\t\tconst uint32_t next_rep_match_price = cur_and_len_literal_price\n\t\t\t\t\t+ rc_bit_1_price(coder->is_match[state_2][pos_state_next])\n\t\t\t\t\t+ rc_bit_1_price(coder->is_rep[state_2]);\n\n\t\t\t//for(; len_test_2 >= 2; len_test_2--) {\n\t\t\tconst uint32_t offset = cur + len_test + 1 + len_test_2;\n\n\t\t\twhile (len_end < offset)\n\t\t\t\tcoder->opts[++len_end].price = RC_INFINITY_PRICE;\n\n\t\t\tconst uint32_t cur_and_len_price = next_rep_match_price\n\t\t\t\t\t+ get_rep_price(coder, 0, len_test_2,\n\t\t\t\t\t\tstate_2, pos_state_next);\n\n\t\t\tif (cur_and_len_price < coder->opts[offset].price) {\n\t\t\t\tcoder->opts[offset].price = cur_and_len_price;\n\t\t\t\tcoder->opts[offset].pos_prev = cur + len_test + 1;\n\t\t\t\tcoder->opts[offset].back_prev = 0;\n\t\t\t\tcoder->opts[offset].prev_1_is_literal = true;\n\t\t\t\tcoder->opts[offset].prev_2 = true;\n\t\t\t\tcoder->opts[offset].pos_prev_2 = cur;\n\t\t\t\tcoder->opts[offset].back_prev_2 = rep_index;\n\t\t\t}\n\t\t\t//}\n\t\t}\n\t}\n\n\n\t//for (uint32_t len_test = 2; len_test <= new_len; ++len_test)\n\tif (new_len > buf_avail) {\n\t\tnew_len = buf_avail;\n\n\t\tmatches_count = 0;\n\t\twhile (new_len > coder->matches[matches_count].len)\n\t\t\t++matches_count;\n\n\t\tcoder->matches[matches_count++].len = new_len;\n\t}\n\n\n\tif (new_len >= start_len) {\n\t\tconst uint32_t normal_match_price = match_price\n\t\t\t\t+ rc_bit_0_price(coder->is_rep[state]);\n\n\t\twhile (len_end < cur + new_len)\n\t\t\tcoder->opts[++len_end].price = RC_INFINITY_PRICE;\n\n\t\tuint32_t i = 0;\n\t\twhile (start_len > coder->matches[i].len)\n\t\t\t++i;\n\n\t\tfor (uint32_t len_test = start_len; ; ++len_test) {\n\t\t\tconst uint32_t cur_back = coder->matches[i].dist;\n\t\t\tuint32_t cur_and_len_price = normal_match_price\n\t\t\t\t\t+ get_dist_len_price(coder,\n\t\t\t\t\t\tcur_back, len_test, pos_state);\n\n\t\t\tif (cur_and_len_price < coder->opts[cur + len_test].price) {\n\t\t\t\tcoder->opts[cur + len_test].price = cur_and_len_price;\n\t\t\t\tcoder->opts[cur + len_test].pos_prev = cur;\n\t\t\t\tcoder->opts[cur + len_test].back_prev\n\t\t\t\t\t\t= cur_back + REPS;\n\t\t\t\tcoder->opts[cur + len_test].prev_1_is_literal = false;\n\t\t\t}\n\n\t\t\tif (len_test == coder->matches[i].len) {\n\t\t\t\t// Try Match + Literal + Rep0\n\t\t\t\tconst uint8_t *const buf_back = buf - cur_back - 1;\n\t\t\t\tuint32_t len_test_2 = len_test + 1;\n\t\t\t\tconst uint32_t limit = my_min(buf_avail_full,\n\t\t\t\t\t\tlen_test_2 + nice_len);\n\n\t\t\t\t// NOTE: len_test_2 may be greater than limit\n\t\t\t\t// so the call to lzma_memcmplen() must be\n\t\t\t\t// done conditionally.\n\t\t\t\tif (len_test_2 < limit)\n\t\t\t\t\tlen_test_2 = lzma_memcmplen(buf, buf_back,\n\t\t\t\t\t\t\tlen_test_2, limit);\n\n\t\t\t\tlen_test_2 -= len_test + 1;\n\n\t\t\t\tif (len_test_2 >= 2) {\n\t\t\t\t\tlzma_lzma_state state_2 = state;\n\t\t\t\t\tupdate_match(state_2);\n\t\t\t\t\tuint32_t pos_state_next\n\t\t\t\t\t\t\t= (position + len_test) & coder->pos_mask;\n\n\t\t\t\t\tconst uint32_t cur_and_len_literal_price = cur_and_len_price\n\t\t\t\t\t\t\t+ rc_bit_0_price(\n\t\t\t\t\t\t\t\tcoder->is_match[state_2][pos_state_next])\n\t\t\t\t\t\t\t+ get_literal_price(coder,\n\t\t\t\t\t\t\t\tposition + len_test,\n\t\t\t\t\t\t\t\tbuf[len_test - 1],\n\t\t\t\t\t\t\t\ttrue,\n\t\t\t\t\t\t\t\tbuf_back[len_test],\n\t\t\t\t\t\t\t\tbuf[len_test]);\n\n\t\t\t\t\tupdate_literal(state_2);\n\t\t\t\t\tpos_state_next = (pos_state_next + 1) & coder->pos_mask;\n\n\t\t\t\t\tconst uint32_t next_rep_match_price\n\t\t\t\t\t\t\t= cur_and_len_literal_price\n\t\t\t\t\t\t\t+ rc_bit_1_price(\n\t\t\t\t\t\t\t\tcoder->is_match[state_2][pos_state_next])\n\t\t\t\t\t\t\t+ rc_bit_1_price(coder->is_rep[state_2]);\n\n\t\t\t\t\t// for(; len_test_2 >= 2; --len_test_2) {\n\t\t\t\t\tconst uint32_t offset = cur + len_test + 1 + len_test_2;\n\n\t\t\t\t\twhile (len_end < offset)\n\t\t\t\t\t\tcoder->opts[++len_end].price = RC_INFINITY_PRICE;\n\n\t\t\t\t\tcur_and_len_price = next_rep_match_price\n\t\t\t\t\t\t\t+ get_rep_price(coder, 0, len_test_2,\n\t\t\t\t\t\t\t\tstate_2, pos_state_next);\n\n\t\t\t\t\tif (cur_and_len_price < coder->opts[offset].price) {\n\t\t\t\t\t\tcoder->opts[offset].price = cur_and_len_price;\n\t\t\t\t\t\tcoder->opts[offset].pos_prev = cur + len_test + 1;\n\t\t\t\t\t\tcoder->opts[offset].back_prev = 0;\n\t\t\t\t\t\tcoder->opts[offset].prev_1_is_literal = true;\n\t\t\t\t\t\tcoder->opts[offset].prev_2 = true;\n\t\t\t\t\t\tcoder->opts[offset].pos_prev_2 = cur;\n\t\t\t\t\t\tcoder->opts[offset].back_prev_2\n\t\t\t\t\t\t\t\t= cur_back + REPS;\n\t\t\t\t\t}\n\t\t\t\t\t//}\n\t\t\t\t}\n\n\t\t\t\tif (++i == matches_count)\n\t\t\t\t\tbreak;\n\t\t\t}\n\t\t}\n\t}\n\n\treturn len_end;\n}\n\n\nextern void\nlzma_lzma_optimum_normal(lzma_lzma1_encoder *restrict coder,\n\t\tlzma_mf *restrict mf,\n\t\tuint32_t *restrict back_res, uint32_t *restrict len_res,\n\t\tuint32_t position)\n{\n\t// If we have symbols pending, return the next pending symbol.\n\tif (coder->opts_end_index != coder->opts_current_index) {\n\t\tassert(mf->read_ahead > 0);\n\t\t*len_res = coder->opts[coder->opts_current_index].pos_prev\n\t\t\t\t- coder->opts_current_index;\n\t\t*back_res = coder->opts[coder->opts_current_index].back_prev;\n\t\tcoder->opts_current_index = coder->opts[\n\t\t\t\tcoder->opts_current_index].pos_prev;\n\t\treturn;\n\t}\n\n\t// Update the price tables. In LZMA SDK <= 4.60 (and possibly later)\n\t// this was done in both initialization function and in the main loop.\n\t// In liblzma they were moved into this single place.\n\tif (mf->read_ahead == 0) {\n\t\tif (coder->match_price_count >= (1 << 7))\n\t\t\tfill_dist_prices(coder);\n\n\t\tif (coder->align_price_count >= ALIGN_SIZE)\n\t\t\tfill_align_prices(coder);\n\t}\n\n\t// TODO: This needs quite a bit of cleaning still. But splitting\n\t// the original function into two pieces makes it at least a little\n\t// more readable, since those two parts don't share many variables.\n\n\tuint32_t len_end = helper1(coder, mf, back_res, len_res, position);\n\tif (len_end == UINT32_MAX)\n\t\treturn;\n\n\tuint32_t reps[REPS];\n\tmemcpy(reps, coder->reps, sizeof(reps));\n\n\tuint32_t cur;\n\tfor (cur = 1; cur < len_end; ++cur) {\n\t\tassert(cur < OPTS);\n\n\t\tcoder->longest_match_length = mf_find(\n\t\t\t\tmf, &coder->matches_count, coder->matches);\n\n\t\tif (coder->longest_match_length >= mf->nice_len)\n\t\t\tbreak;\n\n\t\tlen_end = helper2(coder, reps, mf_ptr(mf) - 1, len_end,\n\t\t\t\tposition + cur, cur, mf->nice_len,\n\t\t\t\tmy_min(mf_avail(mf) + 1, OPTS - 1 - cur));\n\t}\n\n\tbackward(coder, len_res, back_res, cur);\n\treturn;\n}\n"
  },
  {
    "path": "external/xz/liblzma/lzma/lzma_encoder_presets.c",
    "content": "///////////////////////////////////////////////////////////////////////////////\n//\n/// \\file       lzma_encoder_presets.c\n/// \\brief      Encoder presets\n/// \\note       xz needs this even when only decoding is enabled.\n//\n//  Author:     Lasse Collin\n//\n//  This file has been put into the public domain.\n//  You can do whatever you want with this file.\n//\n///////////////////////////////////////////////////////////////////////////////\n\n#include \"common.h\"\n\n\nextern LZMA_API(lzma_bool)\nlzma_lzma_preset(lzma_options_lzma *options, uint32_t preset)\n{\n\tconst uint32_t level = preset & LZMA_PRESET_LEVEL_MASK;\n\tconst uint32_t flags = preset & ~LZMA_PRESET_LEVEL_MASK;\n\tconst uint32_t supported_flags = LZMA_PRESET_EXTREME;\n\n\tif (level > 9 || (flags & ~supported_flags))\n\t\treturn true;\n\n\toptions->preset_dict = NULL;\n\toptions->preset_dict_size = 0;\n\n\toptions->lc = LZMA_LC_DEFAULT;\n\toptions->lp = LZMA_LP_DEFAULT;\n\toptions->pb = LZMA_PB_DEFAULT;\n\n\tstatic const uint8_t dict_pow2[]\n\t\t\t= { 18, 20, 21, 22, 22, 23, 23, 24, 25, 26 };\n\toptions->dict_size = UINT32_C(1) << dict_pow2[level];\n\n\tif (level <= 3) {\n\t\toptions->mode = LZMA_MODE_FAST;\n\t\toptions->mf = level == 0 ? LZMA_MF_HC3 : LZMA_MF_HC4;\n\t\toptions->nice_len = level <= 1 ? 128 : 273;\n\t\tstatic const uint8_t depths[] = { 4, 8, 24, 48 };\n\t\toptions->depth = depths[level];\n\t} else {\n\t\toptions->mode = LZMA_MODE_NORMAL;\n\t\toptions->mf = LZMA_MF_BT4;\n\t\toptions->nice_len = level == 4 ? 16 : level == 5 ? 32 : 64;\n\t\toptions->depth = 0;\n\t}\n\n\tif (flags & LZMA_PRESET_EXTREME) {\n\t\toptions->mode = LZMA_MODE_NORMAL;\n\t\toptions->mf = LZMA_MF_BT4;\n\t\tif (level == 3 || level == 5) {\n\t\t\toptions->nice_len = 192;\n\t\t\toptions->depth = 0;\n\t\t} else {\n\t\t\toptions->nice_len = 273;\n\t\t\toptions->depth = 512;\n\t\t}\n\t}\n\n\treturn false;\n}\n"
  },
  {
    "path": "external/xz/liblzma/lzma/lzma_encoder_private.h",
    "content": "///////////////////////////////////////////////////////////////////////////////\n//\n/// \\file       lzma_encoder_private.h\n/// \\brief      Private definitions for LZMA encoder\n///\n//  Authors:    Igor Pavlov\n//              Lasse Collin\n//\n//  This file has been put into the public domain.\n//  You can do whatever you want with this file.\n//\n///////////////////////////////////////////////////////////////////////////////\n\n#ifndef LZMA_LZMA_ENCODER_PRIVATE_H\n#define LZMA_LZMA_ENCODER_PRIVATE_H\n\n#include \"lz_encoder.h\"\n#include \"range_encoder.h\"\n#include \"lzma_common.h\"\n#include \"lzma_encoder.h\"\n\n\n// Macro to compare if the first two bytes in two buffers differ. This is\n// needed in lzma_lzma_optimum_*() to test if the match is at least\n// MATCH_LEN_MIN bytes. Unaligned access gives tiny gain so there's no\n// reason to not use it when it is supported.\n#ifdef TUKLIB_FAST_UNALIGNED_ACCESS\n#\tdefine not_equal_16(a, b) (read16ne(a) != read16ne(b))\n#else\n#\tdefine not_equal_16(a, b) \\\n\t\t((a)[0] != (b)[0] || (a)[1] != (b)[1])\n#endif\n\n\n// Optimal - Number of entries in the optimum array.\n#define OPTS (1 << 12)\n\n\ntypedef struct {\n\tprobability choice;\n\tprobability choice2;\n\tprobability low[POS_STATES_MAX][LEN_LOW_SYMBOLS];\n\tprobability mid[POS_STATES_MAX][LEN_MID_SYMBOLS];\n\tprobability high[LEN_HIGH_SYMBOLS];\n\n\tuint32_t prices[POS_STATES_MAX][LEN_SYMBOLS];\n\tuint32_t table_size;\n\tuint32_t counters[POS_STATES_MAX];\n\n} lzma_length_encoder;\n\n\ntypedef struct {\n\tlzma_lzma_state state;\n\n\tbool prev_1_is_literal;\n\tbool prev_2;\n\n\tuint32_t pos_prev_2;\n\tuint32_t back_prev_2;\n\n\tuint32_t price;\n\tuint32_t pos_prev;  // pos_next;\n\tuint32_t back_prev;\n\n\tuint32_t backs[REPS];\n\n} lzma_optimal;\n\n\nstruct lzma_lzma1_encoder_s {\n\t/// Range encoder\n\tlzma_range_encoder rc;\n\n\t/// State\n\tlzma_lzma_state state;\n\n\t/// The four most recent match distances\n\tuint32_t reps[REPS];\n\n\t/// Array of match candidates\n\tlzma_match matches[MATCH_LEN_MAX + 1];\n\n\t/// Number of match candidates in matches[]\n\tuint32_t matches_count;\n\n\t/// Variable to hold the length of the longest match between calls\n\t/// to lzma_lzma_optimum_*().\n\tuint32_t longest_match_length;\n\n\t/// True if using getoptimumfast\n\tbool fast_mode;\n\n\t/// True if the encoder has been initialized by encoding the first\n\t/// byte as a literal.\n\tbool is_initialized;\n\n\t/// True if the range encoder has been flushed, but not all bytes\n\t/// have been written to the output buffer yet.\n\tbool is_flushed;\n\n\tuint32_t pos_mask;         ///< (1 << pos_bits) - 1\n\tuint32_t literal_context_bits;\n\tuint32_t literal_pos_mask;\n\n\t// These are the same as in lzma_decoder.c. See comments there.\n\tprobability literal[LITERAL_CODERS_MAX][LITERAL_CODER_SIZE];\n\tprobability is_match[STATES][POS_STATES_MAX];\n\tprobability is_rep[STATES];\n\tprobability is_rep0[STATES];\n\tprobability is_rep1[STATES];\n\tprobability is_rep2[STATES];\n\tprobability is_rep0_long[STATES][POS_STATES_MAX];\n\tprobability dist_slot[DIST_STATES][DIST_SLOTS];\n\tprobability dist_special[FULL_DISTANCES - DIST_MODEL_END];\n\tprobability dist_align[ALIGN_SIZE];\n\n\t// These are the same as in lzma_decoder.c except that the encoders\n\t// include also price tables.\n\tlzma_length_encoder match_len_encoder;\n\tlzma_length_encoder rep_len_encoder;\n\n\t// Price tables\n\tuint32_t dist_slot_prices[DIST_STATES][DIST_SLOTS];\n\tuint32_t dist_prices[DIST_STATES][FULL_DISTANCES];\n\tuint32_t dist_table_size;\n\tuint32_t match_price_count;\n\n\tuint32_t align_prices[ALIGN_SIZE];\n\tuint32_t align_price_count;\n\n\t// Optimal\n\tuint32_t opts_end_index;\n\tuint32_t opts_current_index;\n\tlzma_optimal opts[OPTS];\n};\n\n\nextern void lzma_lzma_optimum_fast(\n\t\tlzma_lzma1_encoder *restrict coder, lzma_mf *restrict mf,\n\t\tuint32_t *restrict back_res, uint32_t *restrict len_res);\n\nextern void lzma_lzma_optimum_normal(lzma_lzma1_encoder *restrict coder,\n\t\tlzma_mf *restrict mf, uint32_t *restrict back_res,\n\t\tuint32_t *restrict len_res, uint32_t position);\n\n#endif\n"
  },
  {
    "path": "external/xz/liblzma/rangecoder/price.h",
    "content": "///////////////////////////////////////////////////////////////////////////////\n//\n/// \\file       price.h\n/// \\brief      Probability price calculation\n//\n//  Author:     Igor Pavlov\n//\n//  This file has been put into the public domain.\n//  You can do whatever you want with this file.\n//\n///////////////////////////////////////////////////////////////////////////////\n\n#ifndef LZMA_PRICE_H\n#define LZMA_PRICE_H\n\n\n#define RC_MOVE_REDUCING_BITS 4\n#define RC_BIT_PRICE_SHIFT_BITS 4\n#define RC_PRICE_TABLE_SIZE (RC_BIT_MODEL_TOTAL >> RC_MOVE_REDUCING_BITS)\n\n#define RC_INFINITY_PRICE (UINT32_C(1) << 30)\n\n\n/// Lookup table for the inline functions defined in this file.\nextern const uint8_t lzma_rc_prices[RC_PRICE_TABLE_SIZE];\n\n\nstatic inline uint32_t\nrc_bit_price(const probability prob, const uint32_t bit)\n{\n\treturn lzma_rc_prices[(prob ^ ((UINT32_C(0) - bit)\n\t\t\t& (RC_BIT_MODEL_TOTAL - 1))) >> RC_MOVE_REDUCING_BITS];\n}\n\n\nstatic inline uint32_t\nrc_bit_0_price(const probability prob)\n{\n\treturn lzma_rc_prices[prob >> RC_MOVE_REDUCING_BITS];\n}\n\n\nstatic inline uint32_t\nrc_bit_1_price(const probability prob)\n{\n\treturn lzma_rc_prices[(prob ^ (RC_BIT_MODEL_TOTAL - 1))\n\t\t\t>> RC_MOVE_REDUCING_BITS];\n}\n\n\nstatic inline uint32_t\nrc_bittree_price(const probability *const probs,\n\t\tconst uint32_t bit_levels, uint32_t symbol)\n{\n\tuint32_t price = 0;\n\tsymbol += UINT32_C(1) << bit_levels;\n\n\tdo {\n\t\tconst uint32_t bit = symbol & 1;\n\t\tsymbol >>= 1;\n\t\tprice += rc_bit_price(probs[symbol], bit);\n\t} while (symbol != 1);\n\n\treturn price;\n}\n\n\nstatic inline uint32_t\nrc_bittree_reverse_price(const probability *const probs,\n\t\tuint32_t bit_levels, uint32_t symbol)\n{\n\tuint32_t price = 0;\n\tuint32_t model_index = 1;\n\n\tdo {\n\t\tconst uint32_t bit = symbol & 1;\n\t\tsymbol >>= 1;\n\t\tprice += rc_bit_price(probs[model_index], bit);\n\t\tmodel_index = (model_index << 1) + bit;\n\t} while (--bit_levels != 0);\n\n\treturn price;\n}\n\n\nstatic inline uint32_t\nrc_direct_price(const uint32_t bits)\n{\n\t return bits << RC_BIT_PRICE_SHIFT_BITS;\n}\n\n#endif\n"
  },
  {
    "path": "external/xz/liblzma/rangecoder/price_table.c",
    "content": "/* This file has been automatically generated by price_tablegen.c. */\n\n#include \"range_encoder.h\"\n\nconst uint8_t lzma_rc_prices[RC_PRICE_TABLE_SIZE] = {\n\t 128, 103,  91,  84,  78,  73,  69,  66,\n\t  63,  61,  58,  56,  54,  52,  51,  49,\n\t  48,  46,  45,  44,  43,  42,  41,  40,\n\t  39,  38,  37,  36,  35,  34,  34,  33,\n\t  32,  31,  31,  30,  29,  29,  28,  28,\n\t  27,  26,  26,  25,  25,  24,  24,  23,\n\t  23,  22,  22,  22,  21,  21,  20,  20,\n\t  19,  19,  19,  18,  18,  17,  17,  17,\n\t  16,  16,  16,  15,  15,  15,  14,  14,\n\t  14,  13,  13,  13,  12,  12,  12,  11,\n\t  11,  11,  11,  10,  10,  10,  10,   9,\n\t   9,   9,   9,   8,   8,   8,   8,   7,\n\t   7,   7,   7,   6,   6,   6,   6,   5,\n\t   5,   5,   5,   5,   4,   4,   4,   4,\n\t   3,   3,   3,   3,   3,   2,   2,   2,\n\t   2,   2,   2,   1,   1,   1,   1,   1\n};\n"
  },
  {
    "path": "external/xz/liblzma/rangecoder/range_common.h",
    "content": "///////////////////////////////////////////////////////////////////////////////\n//\n/// \\file       range_common.h\n/// \\brief      Common things for range encoder and decoder\n///\n//  Authors:    Igor Pavlov\n//              Lasse Collin\n//\n//  This file has been put into the public domain.\n//  You can do whatever you want with this file.\n//\n///////////////////////////////////////////////////////////////////////////////\n\n#ifndef LZMA_RANGE_COMMON_H\n#define LZMA_RANGE_COMMON_H\n\n#include \"common.h\"\n\n\n///////////////\n// Constants //\n///////////////\n\n#define RC_SHIFT_BITS 8\n#define RC_TOP_BITS 24\n#define RC_TOP_VALUE (UINT32_C(1) << RC_TOP_BITS)\n#define RC_BIT_MODEL_TOTAL_BITS 11\n#define RC_BIT_MODEL_TOTAL (UINT32_C(1) << RC_BIT_MODEL_TOTAL_BITS)\n#define RC_MOVE_BITS 5\n\n\n////////////\n// Macros //\n////////////\n\n// Resets the probability so that both 0 and 1 have probability of 50 %\n#define bit_reset(prob) \\\n\tprob = RC_BIT_MODEL_TOTAL >> 1\n\n// This does the same for a complete bit tree.\n// (A tree represented as an array.)\n#define bittree_reset(probs, bit_levels) \\\n\tfor (uint32_t bt_i = 0; bt_i < (1 << (bit_levels)); ++bt_i) \\\n\t\tbit_reset((probs)[bt_i])\n\n\n//////////////////////\n// Type definitions //\n//////////////////////\n\n/// \\brief      Type of probabilities used with range coder\n///\n/// This needs to be at least 12-bit integer, so uint16_t is a logical choice.\n/// However, on some architecture and compiler combinations, a bigger type\n/// may give better speed, because the probability variables are accessed\n/// a lot. On the other hand, bigger probability type increases cache\n/// footprint, since there are 2 to 14 thousand probability variables in\n/// LZMA (assuming the limit of lc + lp <= 4; with lc + lp <= 12 there\n/// would be about 1.5 million variables).\n///\n/// With malicious files, the initialization speed of the LZMA decoder can\n/// become important. In that case, smaller probability variables mean that\n/// there is less bytes to write to RAM, which makes initialization faster.\n/// With big probability type, the initialization can become so slow that it\n/// can be a problem e.g. for email servers doing virus scanning.\n///\n/// I will be sticking to uint16_t unless some specific architectures\n/// are *much* faster (20-50 %) with uint32_t.\ntypedef uint16_t probability;\n\n#endif\n"
  },
  {
    "path": "external/xz/liblzma/rangecoder/range_decoder.h",
    "content": "///////////////////////////////////////////////////////////////////////////////\n//\n/// \\file       range_decoder.h\n/// \\brief      Range Decoder\n///\n//  Authors:    Igor Pavlov\n//              Lasse Collin\n//\n//  This file has been put into the public domain.\n//  You can do whatever you want with this file.\n//\n///////////////////////////////////////////////////////////////////////////////\n\n#ifndef LZMA_RANGE_DECODER_H\n#define LZMA_RANGE_DECODER_H\n\n#include \"range_common.h\"\n\n\ntypedef struct {\n\tuint32_t range;\n\tuint32_t code;\n\tuint32_t init_bytes_left;\n} lzma_range_decoder;\n\n\n/// Reads the first five bytes to initialize the range decoder.\nstatic inline lzma_ret\nrc_read_init(lzma_range_decoder *rc, const uint8_t *restrict in,\n\t\tsize_t *restrict in_pos, size_t in_size)\n{\n\twhile (rc->init_bytes_left > 0) {\n\t\tif (*in_pos == in_size)\n\t\t\treturn LZMA_OK;\n\n\t\t// The first byte is always 0x00. It could have been omitted\n\t\t// in LZMA2 but it wasn't, so one byte is wasted in every\n\t\t// LZMA2 chunk.\n\t\tif (rc->init_bytes_left == 5 && in[*in_pos] != 0x00)\n\t\t\treturn LZMA_DATA_ERROR;\n\n\t\trc->code = (rc->code << 8) | in[*in_pos];\n\t\t++*in_pos;\n\t\t--rc->init_bytes_left;\n\t}\n\n\treturn LZMA_STREAM_END;\n}\n\n\n/// Makes local copies of range decoder and *in_pos variables. Doing this\n/// improves speed significantly. The range decoder macros expect also\n/// variables `in' and `in_size' to be defined.\n#define rc_to_local(range_decoder, in_pos) \\\n\tlzma_range_decoder rc = range_decoder; \\\n\tsize_t rc_in_pos = (in_pos); \\\n\tuint32_t rc_bound\n\n\n/// Stores the local copes back to the range decoder structure.\n#define rc_from_local(range_decoder, in_pos) \\\ndo { \\\n\trange_decoder = rc; \\\n\tin_pos = rc_in_pos; \\\n} while (0)\n\n\n/// Resets the range decoder structure.\n#define rc_reset(range_decoder) \\\ndo { \\\n\t(range_decoder).range = UINT32_MAX; \\\n\t(range_decoder).code = 0; \\\n\t(range_decoder).init_bytes_left = 5; \\\n} while (0)\n\n\n/// When decoding has been properly finished, rc.code is always zero unless\n/// the input stream is corrupt. So checking this can catch some corrupt\n/// files especially if they don't have any other integrity check.\n#define rc_is_finished(range_decoder) \\\n\t((range_decoder).code == 0)\n\n\n/// Read the next input byte if needed. If more input is needed but there is\n/// no more input available, \"goto out\" is used to jump out of the main\n/// decoder loop.\n#define rc_normalize(seq) \\\ndo { \\\n\tif (rc.range < RC_TOP_VALUE) { \\\n\t\tif (unlikely(rc_in_pos == in_size)) { \\\n\t\t\tcoder->sequence = seq; \\\n\t\t\tgoto out; \\\n\t\t} \\\n\t\trc.range <<= RC_SHIFT_BITS; \\\n\t\trc.code = (rc.code << RC_SHIFT_BITS) | in[rc_in_pos++]; \\\n\t} \\\n} while (0)\n\n\n/// Start decoding a bit. This must be used together with rc_update_0()\n/// and rc_update_1():\n///\n///     rc_if_0(prob, seq) {\n///         rc_update_0(prob);\n///         // Do something\n///     } else {\n///         rc_update_1(prob);\n///         // Do something else\n///     }\n///\n#define rc_if_0(prob, seq) \\\n\trc_normalize(seq); \\\n\trc_bound = (rc.range >> RC_BIT_MODEL_TOTAL_BITS) * (prob); \\\n\tif (rc.code < rc_bound)\n\n\n/// Update the range decoder state and the used probability variable to\n/// match a decoded bit of 0.\n#define rc_update_0(prob) \\\ndo { \\\n\trc.range = rc_bound; \\\n\tprob += (RC_BIT_MODEL_TOTAL - (prob)) >> RC_MOVE_BITS; \\\n} while (0)\n\n\n/// Update the range decoder state and the used probability variable to\n/// match a decoded bit of 1.\n#define rc_update_1(prob) \\\ndo { \\\n\trc.range -= rc_bound; \\\n\trc.code -= rc_bound; \\\n\tprob -= (prob) >> RC_MOVE_BITS; \\\n} while (0)\n\n\n/// Decodes one bit and runs action0 or action1 depending on the decoded bit.\n/// This macro is used as the last step in bittree reverse decoders since\n/// those don't use \"symbol\" for anything else than indexing the probability\n/// arrays.\n#define rc_bit_last(prob, action0, action1, seq) \\\ndo { \\\n\trc_if_0(prob, seq) { \\\n\t\trc_update_0(prob); \\\n\t\taction0; \\\n\t} else { \\\n\t\trc_update_1(prob); \\\n\t\taction1; \\\n\t} \\\n} while (0)\n\n\n/// Decodes one bit, updates \"symbol\", and runs action0 or action1 depending\n/// on the decoded bit.\n#define rc_bit(prob, action0, action1, seq) \\\n\trc_bit_last(prob, \\\n\t\tsymbol <<= 1; action0, \\\n\t\tsymbol = (symbol << 1) + 1; action1, \\\n\t\tseq);\n\n\n/// Like rc_bit() but add \"case seq:\" as a prefix. This makes the unrolled\n/// loops more readable because the code isn't littered with \"case\"\n/// statements. On the other hand this also makes it less readable, since\n/// spotting the places where the decoder loop may be restarted is less\n/// obvious.\n#define rc_bit_case(prob, action0, action1, seq) \\\n\tcase seq: rc_bit(prob, action0, action1, seq)\n\n\n/// Decode a bit without using a probability.\n#define rc_direct(dest, seq) \\\ndo { \\\n\trc_normalize(seq); \\\n\trc.range >>= 1; \\\n\trc.code -= rc.range; \\\n\trc_bound = UINT32_C(0) - (rc.code >> 31); \\\n\trc.code += rc.range & rc_bound; \\\n\tdest = (dest << 1) + (rc_bound + 1); \\\n} while (0)\n\n\n// NOTE: No macros are provided for bittree decoding. It seems to be simpler\n// to just write them open in the code.\n\n#endif\n"
  },
  {
    "path": "external/xz/liblzma/rangecoder/range_encoder.h",
    "content": "///////////////////////////////////////////////////////////////////////////////\n//\n/// \\file       range_encoder.h\n/// \\brief      Range Encoder\n///\n//  Authors:    Igor Pavlov\n//              Lasse Collin\n//\n//  This file has been put into the public domain.\n//  You can do whatever you want with this file.\n//\n///////////////////////////////////////////////////////////////////////////////\n\n#ifndef LZMA_RANGE_ENCODER_H\n#define LZMA_RANGE_ENCODER_H\n\n#include \"range_common.h\"\n#include \"price.h\"\n\n\n/// Maximum number of symbols that can be put pending into lzma_range_encoder\n/// structure between calls to lzma_rc_encode(). For LZMA, 52+5 is enough\n/// (match with big distance and length followed by range encoder flush).\n#define RC_SYMBOLS_MAX 58\n\n\ntypedef struct {\n\tuint64_t low;\n\tuint64_t cache_size;\n\tuint32_t range;\n\tuint8_t cache;\n\n\t/// Number of symbols in the tables\n\tsize_t count;\n\n\t/// rc_encode()'s position in the tables\n\tsize_t pos;\n\n\t/// Symbols to encode\n\tenum {\n\t\tRC_BIT_0,\n\t\tRC_BIT_1,\n\t\tRC_DIRECT_0,\n\t\tRC_DIRECT_1,\n\t\tRC_FLUSH,\n\t} symbols[RC_SYMBOLS_MAX];\n\n\t/// Probabilities associated with RC_BIT_0 or RC_BIT_1\n\tprobability *probs[RC_SYMBOLS_MAX];\n\n} lzma_range_encoder;\n\n\nstatic inline void\nrc_reset(lzma_range_encoder *rc)\n{\n\trc->low = 0;\n\trc->cache_size = 1;\n\trc->range = UINT32_MAX;\n\trc->cache = 0;\n\trc->count = 0;\n\trc->pos = 0;\n}\n\n\nstatic inline void\nrc_bit(lzma_range_encoder *rc, probability *prob, uint32_t bit)\n{\n\trc->symbols[rc->count] = bit;\n\trc->probs[rc->count] = prob;\n\t++rc->count;\n}\n\n\nstatic inline void\nrc_bittree(lzma_range_encoder *rc, probability *probs,\n\t\tuint32_t bit_count, uint32_t symbol)\n{\n\tuint32_t model_index = 1;\n\n\tdo {\n\t\tconst uint32_t bit = (symbol >> --bit_count) & 1;\n\t\trc_bit(rc, &probs[model_index], bit);\n\t\tmodel_index = (model_index << 1) + bit;\n\t} while (bit_count != 0);\n}\n\n\nstatic inline void\nrc_bittree_reverse(lzma_range_encoder *rc, probability *probs,\n\t\tuint32_t bit_count, uint32_t symbol)\n{\n\tuint32_t model_index = 1;\n\n\tdo {\n\t\tconst uint32_t bit = symbol & 1;\n\t\tsymbol >>= 1;\n\t\trc_bit(rc, &probs[model_index], bit);\n\t\tmodel_index = (model_index << 1) + bit;\n\t} while (--bit_count != 0);\n}\n\n\nstatic inline void\nrc_direct(lzma_range_encoder *rc,\n\t\tuint32_t value, uint32_t bit_count)\n{\n\tdo {\n\t\trc->symbols[rc->count++]\n\t\t\t\t= RC_DIRECT_0 + ((value >> --bit_count) & 1);\n\t} while (bit_count != 0);\n}\n\n\nstatic inline void\nrc_flush(lzma_range_encoder *rc)\n{\n\tfor (size_t i = 0; i < 5; ++i)\n\t\trc->symbols[rc->count++] = RC_FLUSH;\n}\n\n\nstatic inline bool\nrc_shift_low(lzma_range_encoder *rc,\n\t\tuint8_t *out, size_t *out_pos, size_t out_size)\n{\n\tif ((uint32_t)(rc->low) < (uint32_t)(0xFF000000)\n\t\t\t|| (uint32_t)(rc->low >> 32) != 0) {\n\t\tdo {\n\t\t\tif (*out_pos == out_size)\n\t\t\t\treturn true;\n\n\t\t\tout[*out_pos] = rc->cache + (uint8_t)(rc->low >> 32);\n\t\t\t++*out_pos;\n\t\t\trc->cache = 0xFF;\n\n\t\t} while (--rc->cache_size != 0);\n\n\t\trc->cache = (rc->low >> 24) & 0xFF;\n\t}\n\n\t++rc->cache_size;\n\trc->low = (rc->low & 0x00FFFFFF) << RC_SHIFT_BITS;\n\n\treturn false;\n}\n\n\nstatic inline bool\nrc_encode(lzma_range_encoder *rc,\n\t\tuint8_t *out, size_t *out_pos, size_t out_size)\n{\n\tassert(rc->count <= RC_SYMBOLS_MAX);\n\n\twhile (rc->pos < rc->count) {\n\t\t// Normalize\n\t\tif (rc->range < RC_TOP_VALUE) {\n\t\t\tif (rc_shift_low(rc, out, out_pos, out_size))\n\t\t\t\treturn true;\n\n\t\t\trc->range <<= RC_SHIFT_BITS;\n\t\t}\n\n\t\t// Encode a bit\n\t\tswitch (rc->symbols[rc->pos]) {\n\t\tcase RC_BIT_0: {\n\t\t\tprobability prob = *rc->probs[rc->pos];\n\t\t\trc->range = (rc->range >> RC_BIT_MODEL_TOTAL_BITS)\n\t\t\t\t\t* prob;\n\t\t\tprob += (RC_BIT_MODEL_TOTAL - prob) >> RC_MOVE_BITS;\n\t\t\t*rc->probs[rc->pos] = prob;\n\t\t\tbreak;\n\t\t}\n\n\t\tcase RC_BIT_1: {\n\t\t\tprobability prob = *rc->probs[rc->pos];\n\t\t\tconst uint32_t bound = prob * (rc->range\n\t\t\t\t\t>> RC_BIT_MODEL_TOTAL_BITS);\n\t\t\trc->low += bound;\n\t\t\trc->range -= bound;\n\t\t\tprob -= prob >> RC_MOVE_BITS;\n\t\t\t*rc->probs[rc->pos] = prob;\n\t\t\tbreak;\n\t\t}\n\n\t\tcase RC_DIRECT_0:\n\t\t\trc->range >>= 1;\n\t\t\tbreak;\n\n\t\tcase RC_DIRECT_1:\n\t\t\trc->range >>= 1;\n\t\t\trc->low += rc->range;\n\t\t\tbreak;\n\n\t\tcase RC_FLUSH:\n\t\t\t// Prevent further normalizations.\n\t\t\trc->range = UINT32_MAX;\n\n\t\t\t// Flush the last five bytes (see rc_flush()).\n\t\t\tdo {\n\t\t\t\tif (rc_shift_low(rc, out, out_pos, out_size))\n\t\t\t\t\treturn true;\n\t\t\t} while (++rc->pos < rc->count);\n\n\t\t\t// Reset the range encoder so we are ready to continue\n\t\t\t// encoding if we weren't finishing the stream.\n\t\t\trc_reset(rc);\n\t\t\treturn false;\n\n\t\tdefault:\n\t\t\tassert(0);\n\t\t\tbreak;\n\t\t}\n\n\t\t++rc->pos;\n\t}\n\n\trc->count = 0;\n\trc->pos = 0;\n\n\treturn false;\n}\n\n\nstatic inline uint64_t\nrc_pending(const lzma_range_encoder *rc)\n{\n\treturn rc->cache_size + 5 - 1;\n}\n\n#endif\n"
  },
  {
    "path": "external/xz/liblzma/simple/arm.c",
    "content": "///////////////////////////////////////////////////////////////////////////////\n//\n/// \\file       arm.c\n/// \\brief      Filter for ARM binaries\n///\n//  Authors:    Igor Pavlov\n//              Lasse Collin\n//\n//  This file has been put into the public domain.\n//  You can do whatever you want with this file.\n//\n///////////////////////////////////////////////////////////////////////////////\n\n#include \"simple_private.h\"\n\n\nstatic size_t\narm_code(void *simple lzma_attribute((__unused__)),\n\t\tuint32_t now_pos, bool is_encoder,\n\t\tuint8_t *buffer, size_t size)\n{\n\tsize_t i;\n\tfor (i = 0; i + 4 <= size; i += 4) {\n\t\tif (buffer[i + 3] == 0xEB) {\n\t\t\tuint32_t src = ((uint32_t)(buffer[i + 2]) << 16)\n\t\t\t\t\t| ((uint32_t)(buffer[i + 1]) << 8)\n\t\t\t\t\t| (uint32_t)(buffer[i + 0]);\n\t\t\tsrc <<= 2;\n\n\t\t\tuint32_t dest;\n\t\t\tif (is_encoder)\n\t\t\t\tdest = now_pos + (uint32_t)(i) + 8 + src;\n\t\t\telse\n\t\t\t\tdest = src - (now_pos + (uint32_t)(i) + 8);\n\n\t\t\tdest >>= 2;\n\t\t\tbuffer[i + 2] = (dest >> 16);\n\t\t\tbuffer[i + 1] = (dest >> 8);\n\t\t\tbuffer[i + 0] = dest;\n\t\t}\n\t}\n\n\treturn i;\n}\n\n\nstatic lzma_ret\narm_coder_init(lzma_next_coder *next, const lzma_allocator *allocator,\n\t\tconst lzma_filter_info *filters, bool is_encoder)\n{\n\treturn lzma_simple_coder_init(next, allocator, filters,\n\t\t\t&arm_code, 0, 4, 4, is_encoder);\n}\n\n\nextern lzma_ret\nlzma_simple_arm_encoder_init(lzma_next_coder *next,\n\t\tconst lzma_allocator *allocator,\n\t\tconst lzma_filter_info *filters)\n{\n\treturn arm_coder_init(next, allocator, filters, true);\n}\n\n\nextern lzma_ret\nlzma_simple_arm_decoder_init(lzma_next_coder *next,\n\t\tconst lzma_allocator *allocator,\n\t\tconst lzma_filter_info *filters)\n{\n\treturn arm_coder_init(next, allocator, filters, false);\n}\n"
  },
  {
    "path": "external/xz/liblzma/simple/armthumb.c",
    "content": "///////////////////////////////////////////////////////////////////////////////\n//\n/// \\file       armthumb.c\n/// \\brief      Filter for ARM-Thumb binaries\n///\n//  Authors:    Igor Pavlov\n//              Lasse Collin\n//\n//  This file has been put into the public domain.\n//  You can do whatever you want with this file.\n//\n///////////////////////////////////////////////////////////////////////////////\n\n#include \"simple_private.h\"\n\n\nstatic size_t\narmthumb_code(void *simple lzma_attribute((__unused__)),\n\t\tuint32_t now_pos, bool is_encoder,\n\t\tuint8_t *buffer, size_t size)\n{\n\tsize_t i;\n\tfor (i = 0; i + 4 <= size; i += 2) {\n\t\tif ((buffer[i + 1] & 0xF8) == 0xF0\n\t\t\t\t&& (buffer[i + 3] & 0xF8) == 0xF8) {\n\t\t\tuint32_t src = (((uint32_t)(buffer[i + 1]) & 7) << 19)\n\t\t\t\t| ((uint32_t)(buffer[i + 0]) << 11)\n\t\t\t\t| (((uint32_t)(buffer[i + 3]) & 7) << 8)\n\t\t\t\t| (uint32_t)(buffer[i + 2]);\n\n\t\t\tsrc <<= 1;\n\n\t\t\tuint32_t dest;\n\t\t\tif (is_encoder)\n\t\t\t\tdest = now_pos + (uint32_t)(i) + 4 + src;\n\t\t\telse\n\t\t\t\tdest = src - (now_pos + (uint32_t)(i) + 4);\n\n\t\t\tdest >>= 1;\n\t\t\tbuffer[i + 1] = 0xF0 | ((dest >> 19) & 0x7);\n\t\t\tbuffer[i + 0] = (dest >> 11);\n\t\t\tbuffer[i + 3] = 0xF8 | ((dest >> 8) & 0x7);\n\t\t\tbuffer[i + 2] = (dest);\n\t\t\ti += 2;\n\t\t}\n\t}\n\n\treturn i;\n}\n\n\nstatic lzma_ret\narmthumb_coder_init(lzma_next_coder *next, const lzma_allocator *allocator,\n\t\tconst lzma_filter_info *filters, bool is_encoder)\n{\n\treturn lzma_simple_coder_init(next, allocator, filters,\n\t\t\t&armthumb_code, 0, 4, 2, is_encoder);\n}\n\n\nextern lzma_ret\nlzma_simple_armthumb_encoder_init(lzma_next_coder *next,\n\t\tconst lzma_allocator *allocator,\n\t\tconst lzma_filter_info *filters)\n{\n\treturn armthumb_coder_init(next, allocator, filters, true);\n}\n\n\nextern lzma_ret\nlzma_simple_armthumb_decoder_init(lzma_next_coder *next,\n\t\tconst lzma_allocator *allocator,\n\t\tconst lzma_filter_info *filters)\n{\n\treturn armthumb_coder_init(next, allocator, filters, false);\n}\n"
  },
  {
    "path": "external/xz/liblzma/simple/ia64.c",
    "content": "///////////////////////////////////////////////////////////////////////////////\n//\n/// \\file       ia64.c\n/// \\brief      Filter for IA64 (Itanium) binaries\n///\n//  Authors:    Igor Pavlov\n//              Lasse Collin\n//\n//  This file has been put into the public domain.\n//  You can do whatever you want with this file.\n//\n///////////////////////////////////////////////////////////////////////////////\n\n#include \"simple_private.h\"\n\n\nstatic size_t\nia64_code(void *simple lzma_attribute((__unused__)),\n\t\tuint32_t now_pos, bool is_encoder,\n\t\tuint8_t *buffer, size_t size)\n{\n\tstatic const uint32_t BRANCH_TABLE[32] = {\n\t\t0, 0, 0, 0, 0, 0, 0, 0,\n\t\t0, 0, 0, 0, 0, 0, 0, 0,\n\t\t4, 4, 6, 6, 0, 0, 7, 7,\n\t\t4, 4, 0, 0, 4, 4, 0, 0\n\t};\n\n\tsize_t i;\n\tfor (i = 0; i + 16 <= size; i += 16) {\n\t\tconst uint32_t instr_template = buffer[i] & 0x1F;\n\t\tconst uint32_t mask = BRANCH_TABLE[instr_template];\n\t\tuint32_t bit_pos = 5;\n\n\t\tfor (size_t slot = 0; slot < 3; ++slot, bit_pos += 41) {\n\t\t\tif (((mask >> slot) & 1) == 0)\n\t\t\t\tcontinue;\n\n\t\t\tconst size_t byte_pos = (bit_pos >> 3);\n\t\t\tconst uint32_t bit_res = bit_pos & 0x7;\n\t\t\tuint64_t instruction = 0;\n\n\t\t\tfor (size_t j = 0; j < 6; ++j)\n\t\t\t\tinstruction += (uint64_t)(\n\t\t\t\t\t\tbuffer[i + j + byte_pos])\n\t\t\t\t\t\t<< (8 * j);\n\n\t\t\tuint64_t inst_norm = instruction >> bit_res;\n\n\t\t\tif (((inst_norm >> 37) & 0xF) == 0x5\n\t\t\t\t\t&& ((inst_norm >> 9) & 0x7) == 0\n\t\t\t\t\t/* &&  (inst_norm & 0x3F)== 0 */\n\t\t\t\t\t) {\n\t\t\t\tuint32_t src = (uint32_t)(\n\t\t\t\t\t\t(inst_norm >> 13) & 0xFFFFF);\n\t\t\t\tsrc |= ((inst_norm >> 36) & 1) << 20;\n\n\t\t\t\tsrc <<= 4;\n\n\t\t\t\tuint32_t dest;\n\t\t\t\tif (is_encoder)\n\t\t\t\t\tdest = now_pos + (uint32_t)(i) + src;\n\t\t\t\telse\n\t\t\t\t\tdest = src - (now_pos + (uint32_t)(i));\n\n\t\t\t\tdest >>= 4;\n\n\t\t\t\tinst_norm &= ~((uint64_t)(0x8FFFFF) << 13);\n\t\t\t\tinst_norm |= (uint64_t)(dest & 0xFFFFF) << 13;\n\t\t\t\tinst_norm |= (uint64_t)(dest & 0x100000)\n\t\t\t\t\t\t<< (36 - 20);\n\n\t\t\t\tinstruction &= (1U << bit_res) - 1;\n\t\t\t\tinstruction |= (inst_norm << bit_res);\n\n\t\t\t\tfor (size_t j = 0; j < 6; j++)\n\t\t\t\t\tbuffer[i + j + byte_pos] = (uint8_t)(\n\t\t\t\t\t\t\tinstruction\n\t\t\t\t\t\t\t>> (8 * j));\n\t\t\t}\n\t\t}\n\t}\n\n\treturn i;\n}\n\n\nstatic lzma_ret\nia64_coder_init(lzma_next_coder *next, const lzma_allocator *allocator,\n\t\tconst lzma_filter_info *filters, bool is_encoder)\n{\n\treturn lzma_simple_coder_init(next, allocator, filters,\n\t\t\t&ia64_code, 0, 16, 16, is_encoder);\n}\n\n\nextern lzma_ret\nlzma_simple_ia64_encoder_init(lzma_next_coder *next,\n\t\tconst lzma_allocator *allocator,\n\t\tconst lzma_filter_info *filters)\n{\n\treturn ia64_coder_init(next, allocator, filters, true);\n}\n\n\nextern lzma_ret\nlzma_simple_ia64_decoder_init(lzma_next_coder *next,\n\t\tconst lzma_allocator *allocator,\n\t\tconst lzma_filter_info *filters)\n{\n\treturn ia64_coder_init(next, allocator, filters, false);\n}\n"
  },
  {
    "path": "external/xz/liblzma/simple/powerpc.c",
    "content": "///////////////////////////////////////////////////////////////////////////////\n//\n/// \\file       powerpc.c\n/// \\brief      Filter for PowerPC (big endian) binaries\n///\n//  Authors:    Igor Pavlov\n//              Lasse Collin\n//\n//  This file has been put into the public domain.\n//  You can do whatever you want with this file.\n//\n///////////////////////////////////////////////////////////////////////////////\n\n#include \"simple_private.h\"\n\n\nstatic size_t\npowerpc_code(void *simple lzma_attribute((__unused__)),\n\t\tuint32_t now_pos, bool is_encoder,\n\t\tuint8_t *buffer, size_t size)\n{\n\tsize_t i;\n\tfor (i = 0; i + 4 <= size; i += 4) {\n\t\t// PowerPC branch 6(48) 24(Offset) 1(Abs) 1(Link)\n\t\tif ((buffer[i] >> 2) == 0x12\n\t\t\t\t&& ((buffer[i + 3] & 3) == 1)) {\n\n\t\t\tconst uint32_t src\n\t\t\t\t= (((uint32_t)(buffer[i + 0]) & 3) << 24)\n\t\t\t\t| ((uint32_t)(buffer[i + 1]) << 16)\n\t\t\t\t| ((uint32_t)(buffer[i + 2]) << 8)\n\t\t\t\t| ((uint32_t)(buffer[i + 3]) & ~UINT32_C(3));\n\n\t\t\tuint32_t dest;\n\t\t\tif (is_encoder)\n\t\t\t\tdest = now_pos + (uint32_t)(i) + src;\n\t\t\telse\n\t\t\t\tdest = src - (now_pos + (uint32_t)(i));\n\n\t\t\tbuffer[i + 0] = 0x48 | ((dest >> 24) &  0x03);\n\t\t\tbuffer[i + 1] = (dest >> 16);\n\t\t\tbuffer[i + 2] = (dest >> 8);\n\t\t\tbuffer[i + 3] &= 0x03;\n\t\t\tbuffer[i + 3] |= dest;\n\t\t}\n\t}\n\n\treturn i;\n}\n\n\nstatic lzma_ret\npowerpc_coder_init(lzma_next_coder *next, const lzma_allocator *allocator,\n\t\tconst lzma_filter_info *filters, bool is_encoder)\n{\n\treturn lzma_simple_coder_init(next, allocator, filters,\n\t\t\t&powerpc_code, 0, 4, 4, is_encoder);\n}\n\n\nextern lzma_ret\nlzma_simple_powerpc_encoder_init(lzma_next_coder *next,\n\t\tconst lzma_allocator *allocator,\n\t\tconst lzma_filter_info *filters)\n{\n\treturn powerpc_coder_init(next, allocator, filters, true);\n}\n\n\nextern lzma_ret\nlzma_simple_powerpc_decoder_init(lzma_next_coder *next,\n\t\tconst lzma_allocator *allocator,\n\t\tconst lzma_filter_info *filters)\n{\n\treturn powerpc_coder_init(next, allocator, filters, false);\n}\n"
  },
  {
    "path": "external/xz/liblzma/simple/simple_coder.c",
    "content": "///////////////////////////////////////////////////////////////////////////////\n//\n/// \\file       simple_coder.c\n/// \\brief      Wrapper for simple filters\n///\n/// Simple filters don't change the size of the data i.e. number of bytes\n/// in equals the number of bytes out.\n//\n//  Author:     Lasse Collin\n//\n//  This file has been put into the public domain.\n//  You can do whatever you want with this file.\n//\n///////////////////////////////////////////////////////////////////////////////\n\n#include \"simple_private.h\"\n\n\n/// Copied or encodes/decodes more data to out[].\nstatic lzma_ret\ncopy_or_code(lzma_simple_coder *coder, const lzma_allocator *allocator,\n\t\tconst uint8_t *restrict in, size_t *restrict in_pos,\n\t\tsize_t in_size, uint8_t *restrict out,\n\t\tsize_t *restrict out_pos, size_t out_size, lzma_action action)\n{\n\tassert(!coder->end_was_reached);\n\n\tif (coder->next.code == NULL) {\n\t\tlzma_bufcpy(in, in_pos, in_size, out, out_pos, out_size);\n\n\t\t// Check if end of stream was reached.\n\t\tif (coder->is_encoder && action == LZMA_FINISH\n\t\t\t\t&& *in_pos == in_size)\n\t\t\tcoder->end_was_reached = true;\n\n\t} else {\n\t\t// Call the next coder in the chain to provide us some data.\n\t\tconst lzma_ret ret = coder->next.code(\n\t\t\t\tcoder->next.coder, allocator,\n\t\t\t\tin, in_pos, in_size,\n\t\t\t\tout, out_pos, out_size, action);\n\n\t\tif (ret == LZMA_STREAM_END) {\n\t\t\tassert(!coder->is_encoder\n\t\t\t\t\t|| action == LZMA_FINISH);\n\t\t\tcoder->end_was_reached = true;\n\n\t\t} else if (ret != LZMA_OK) {\n\t\t\treturn ret;\n\t\t}\n\t}\n\n\treturn LZMA_OK;\n}\n\n\nstatic size_t\ncall_filter(lzma_simple_coder *coder, uint8_t *buffer, size_t size)\n{\n\tconst size_t filtered = coder->filter(coder->simple,\n\t\t\tcoder->now_pos, coder->is_encoder,\n\t\t\tbuffer, size);\n\tcoder->now_pos += filtered;\n\treturn filtered;\n}\n\n\nstatic lzma_ret\nsimple_code(void *coder_ptr, const lzma_allocator *allocator,\n\t\tconst uint8_t *restrict in, size_t *restrict in_pos,\n\t\tsize_t in_size, uint8_t *restrict out,\n\t\tsize_t *restrict out_pos, size_t out_size, lzma_action action)\n{\n\tlzma_simple_coder *coder = coder_ptr;\n\n\t// TODO: Add partial support for LZMA_SYNC_FLUSH. We can support it\n\t// in cases when the filter is able to filter everything. With most\n\t// simple filters it can be done at offset that is a multiple of 2,\n\t// 4, or 16. With x86 filter, it needs good luck, and thus cannot\n\t// be made to work predictably.\n\tif (action == LZMA_SYNC_FLUSH)\n\t\treturn LZMA_OPTIONS_ERROR;\n\n\t// Flush already filtered data from coder->buffer[] to out[].\n\tif (coder->pos < coder->filtered) {\n\t\tlzma_bufcpy(coder->buffer, &coder->pos, coder->filtered,\n\t\t\t\tout, out_pos, out_size);\n\n\t\t// If we couldn't flush all the filtered data, return to\n\t\t// application immediately.\n\t\tif (coder->pos < coder->filtered)\n\t\t\treturn LZMA_OK;\n\n\t\tif (coder->end_was_reached) {\n\t\t\tassert(coder->filtered == coder->size);\n\t\t\treturn LZMA_STREAM_END;\n\t\t}\n\t}\n\n\t// If we get here, there is no filtered data left in the buffer.\n\tcoder->filtered = 0;\n\n\tassert(!coder->end_was_reached);\n\n\t// If there is more output space left than there is unfiltered data\n\t// in coder->buffer[], flush coder->buffer[] to out[], and copy/code\n\t// more data to out[] hopefully filling it completely. Then filter\n\t// the data in out[]. This step is where most of the data gets\n\t// filtered if the buffer sizes used by the application are reasonable.\n\tconst size_t out_avail = out_size - *out_pos;\n\tconst size_t buf_avail = coder->size - coder->pos;\n\tif (out_avail > buf_avail || buf_avail == 0) {\n\t\t// Store the old position so that we know from which byte\n\t\t// to start filtering.\n\t\tconst size_t out_start = *out_pos;\n\n\t\t// Flush data from coder->buffer[] to out[], but don't reset\n\t\t// coder->pos and coder->size yet. This way the coder can be\n\t\t// restarted if the next filter in the chain returns e.g.\n\t\t// LZMA_MEM_ERROR.\n\t\t//\n\t\t// Do the memcpy() conditionally because out can be NULL\n\t\t// (in which case buf_avail is always 0). Calling memcpy()\n\t\t// with a null-pointer is undefined even if the third\n\t\t// argument is 0.\n\t\tif (buf_avail > 0)\n\t\t\tmemcpy(out + *out_pos, coder->buffer + coder->pos,\n\t\t\t\t\tbuf_avail);\n\n\t\t*out_pos += buf_avail;\n\n\t\t// Copy/Encode/Decode more data to out[].\n\t\t{\n\t\t\tconst lzma_ret ret = copy_or_code(coder, allocator,\n\t\t\t\t\tin, in_pos, in_size,\n\t\t\t\t\tout, out_pos, out_size, action);\n\t\t\tassert(ret != LZMA_STREAM_END);\n\t\t\tif (ret != LZMA_OK)\n\t\t\t\treturn ret;\n\t\t}\n\n\t\t// Filter out[].\n\t\tconst size_t size = *out_pos - out_start;\n\t\tconst size_t filtered = call_filter(\n\t\t\t\tcoder, out + out_start, size);\n\n\t\tconst size_t unfiltered = size - filtered;\n\t\tassert(unfiltered <= coder->allocated / 2);\n\n\t\t// Now we can update coder->pos and coder->size, because\n\t\t// the next coder in the chain (if any) was successful.\n\t\tcoder->pos = 0;\n\t\tcoder->size = unfiltered;\n\n\t\tif (coder->end_was_reached) {\n\t\t\t// The last byte has been copied to out[] already.\n\t\t\t// They are left as is.\n\t\t\tcoder->size = 0;\n\n\t\t} else if (unfiltered > 0) {\n\t\t\t// There is unfiltered data left in out[]. Copy it to\n\t\t\t// coder->buffer[] and rewind *out_pos appropriately.\n\t\t\t*out_pos -= unfiltered;\n\t\t\tmemcpy(coder->buffer, out + *out_pos, unfiltered);\n\t\t}\n\t} else if (coder->pos > 0) {\n\t\tmemmove(coder->buffer, coder->buffer + coder->pos, buf_avail);\n\t\tcoder->size -= coder->pos;\n\t\tcoder->pos = 0;\n\t}\n\n\tassert(coder->pos == 0);\n\n\t// If coder->buffer[] isn't empty, try to fill it by copying/decoding\n\t// more data. Then filter coder->buffer[] and copy the successfully\n\t// filtered data to out[]. It is probable, that some filtered and\n\t// unfiltered data will be left to coder->buffer[].\n\tif (coder->size > 0) {\n\t\t{\n\t\t\tconst lzma_ret ret = copy_or_code(coder, allocator,\n\t\t\t\t\tin, in_pos, in_size,\n\t\t\t\t\tcoder->buffer, &coder->size,\n\t\t\t\t\tcoder->allocated, action);\n\t\t\tassert(ret != LZMA_STREAM_END);\n\t\t\tif (ret != LZMA_OK)\n\t\t\t\treturn ret;\n\t\t}\n\n\t\tcoder->filtered = call_filter(\n\t\t\t\tcoder, coder->buffer, coder->size);\n\n\t\t// Everything is considered to be filtered if coder->buffer[]\n\t\t// contains the last bytes of the data.\n\t\tif (coder->end_was_reached)\n\t\t\tcoder->filtered = coder->size;\n\n\t\t// Flush as much as possible.\n\t\tlzma_bufcpy(coder->buffer, &coder->pos, coder->filtered,\n\t\t\t\tout, out_pos, out_size);\n\t}\n\n\t// Check if we got everything done.\n\tif (coder->end_was_reached && coder->pos == coder->size)\n\t\treturn LZMA_STREAM_END;\n\n\treturn LZMA_OK;\n}\n\n\nstatic void\nsimple_coder_end(void *coder_ptr, const lzma_allocator *allocator)\n{\n\tlzma_simple_coder *coder = coder_ptr;\n\tlzma_next_end(&coder->next, allocator);\n\tlzma_free(coder->simple, allocator);\n\tlzma_free(coder, allocator);\n\treturn;\n}\n\n\nstatic lzma_ret\nsimple_coder_update(void *coder_ptr, const lzma_allocator *allocator,\n\t\tconst lzma_filter *filters_null lzma_attribute((__unused__)),\n\t\tconst lzma_filter *reversed_filters)\n{\n\tlzma_simple_coder *coder = coder_ptr;\n\n\t// No update support, just call the next filter in the chain.\n\treturn lzma_next_filter_update(\n\t\t\t&coder->next, allocator, reversed_filters + 1);\n}\n\n\nextern lzma_ret\nlzma_simple_coder_init(lzma_next_coder *next, const lzma_allocator *allocator,\n\t\tconst lzma_filter_info *filters,\n\t\tsize_t (*filter)(void *simple, uint32_t now_pos,\n\t\t\tbool is_encoder, uint8_t *buffer, size_t size),\n\t\tsize_t simple_size, size_t unfiltered_max,\n\t\tuint32_t alignment, bool is_encoder)\n{\n\t// Allocate memory for the lzma_simple_coder structure if needed.\n\tlzma_simple_coder *coder = next->coder;\n\tif (coder == NULL) {\n\t\t// Here we allocate space also for the temporary buffer. We\n\t\t// need twice the size of unfiltered_max, because then it\n\t\t// is always possible to filter at least unfiltered_max bytes\n\t\t// more data in coder->buffer[] if it can be filled completely.\n\t\tcoder = lzma_alloc(sizeof(lzma_simple_coder)\n\t\t\t\t+ 2 * unfiltered_max, allocator);\n\t\tif (coder == NULL)\n\t\t\treturn LZMA_MEM_ERROR;\n\n\t\tnext->coder = coder;\n\t\tnext->code = &simple_code;\n\t\tnext->end = &simple_coder_end;\n\t\tnext->update = &simple_coder_update;\n\n\t\tcoder->next = LZMA_NEXT_CODER_INIT;\n\t\tcoder->filter = filter;\n\t\tcoder->allocated = 2 * unfiltered_max;\n\n\t\t// Allocate memory for filter-specific data structure.\n\t\tif (simple_size > 0) {\n\t\t\tcoder->simple = lzma_alloc(simple_size, allocator);\n\t\t\tif (coder->simple == NULL)\n\t\t\t\treturn LZMA_MEM_ERROR;\n\t\t} else {\n\t\t\tcoder->simple = NULL;\n\t\t}\n\t}\n\n\tif (filters[0].options != NULL) {\n\t\tconst lzma_options_bcj *simple = filters[0].options;\n\t\tcoder->now_pos = simple->start_offset;\n\t\tif (coder->now_pos & (alignment - 1))\n\t\t\treturn LZMA_OPTIONS_ERROR;\n\t} else {\n\t\tcoder->now_pos = 0;\n\t}\n\n\t// Reset variables.\n\tcoder->is_encoder = is_encoder;\n\tcoder->end_was_reached = false;\n\tcoder->pos = 0;\n\tcoder->filtered = 0;\n\tcoder->size = 0;\n\n\treturn lzma_next_filter_init(&coder->next, allocator, filters + 1);\n}\n"
  },
  {
    "path": "external/xz/liblzma/simple/simple_coder.h",
    "content": "///////////////////////////////////////////////////////////////////////////////\n//\n/// \\file       simple_coder.h\n/// \\brief      Wrapper for simple filters\n//\n//  Author:     Lasse Collin\n//\n//  This file has been put into the public domain.\n//  You can do whatever you want with this file.\n//\n///////////////////////////////////////////////////////////////////////////////\n\n#ifndef LZMA_SIMPLE_CODER_H\n#define LZMA_SIMPLE_CODER_H\n\n#include \"common.h\"\n\n\nextern lzma_ret lzma_simple_x86_encoder_init(lzma_next_coder *next,\n\t\tconst lzma_allocator *allocator,\n\t\tconst lzma_filter_info *filters);\n\nextern lzma_ret lzma_simple_x86_decoder_init(lzma_next_coder *next,\n\t\tconst lzma_allocator *allocator,\n\t\tconst lzma_filter_info *filters);\n\n\nextern lzma_ret lzma_simple_powerpc_encoder_init(lzma_next_coder *next,\n\t\tconst lzma_allocator *allocator,\n\t\tconst lzma_filter_info *filters);\n\nextern lzma_ret lzma_simple_powerpc_decoder_init(lzma_next_coder *next,\n\t\tconst lzma_allocator *allocator,\n\t\tconst lzma_filter_info *filters);\n\n\nextern lzma_ret lzma_simple_ia64_encoder_init(lzma_next_coder *next,\n\t\tconst lzma_allocator *allocator,\n\t\tconst lzma_filter_info *filters);\n\nextern lzma_ret lzma_simple_ia64_decoder_init(lzma_next_coder *next,\n\t\tconst lzma_allocator *allocator,\n\t\tconst lzma_filter_info *filters);\n\n\nextern lzma_ret lzma_simple_arm_encoder_init(lzma_next_coder *next,\n\t\tconst lzma_allocator *allocator,\n\t\tconst lzma_filter_info *filters);\n\nextern lzma_ret lzma_simple_arm_decoder_init(lzma_next_coder *next,\n\t\tconst lzma_allocator *allocator,\n\t\tconst lzma_filter_info *filters);\n\n\nextern lzma_ret lzma_simple_armthumb_encoder_init(lzma_next_coder *next,\n\t\tconst lzma_allocator *allocator,\n\t\tconst lzma_filter_info *filters);\n\nextern lzma_ret lzma_simple_armthumb_decoder_init(lzma_next_coder *next,\n\t\tconst lzma_allocator *allocator,\n\t\tconst lzma_filter_info *filters);\n\n\nextern lzma_ret lzma_simple_sparc_encoder_init(lzma_next_coder *next,\n\t\tconst lzma_allocator *allocator,\n\t\tconst lzma_filter_info *filters);\n\nextern lzma_ret lzma_simple_sparc_decoder_init(lzma_next_coder *next,\n\t\tconst lzma_allocator *allocator,\n\t\tconst lzma_filter_info *filters);\n\n#endif\n"
  },
  {
    "path": "external/xz/liblzma/simple/simple_decoder.c",
    "content": "///////////////////////////////////////////////////////////////////////////////\n//\n/// \\file       simple_decoder.c\n/// \\brief      Properties decoder for simple filters\n//\n//  Author:     Lasse Collin\n//\n//  This file has been put into the public domain.\n//  You can do whatever you want with this file.\n//\n///////////////////////////////////////////////////////////////////////////////\n\n#include \"simple_decoder.h\"\n\n\nextern lzma_ret\nlzma_simple_props_decode(void **options, const lzma_allocator *allocator,\n\t\tconst uint8_t *props, size_t props_size)\n{\n\tif (props_size == 0)\n\t\treturn LZMA_OK;\n\n\tif (props_size != 4)\n\t\treturn LZMA_OPTIONS_ERROR;\n\n\tlzma_options_bcj *opt = lzma_alloc(\n\t\t\tsizeof(lzma_options_bcj), allocator);\n\tif (opt == NULL)\n\t\treturn LZMA_MEM_ERROR;\n\n\topt->start_offset = read32le(props);\n\n\t// Don't leave an options structure allocated if start_offset is zero.\n\tif (opt->start_offset == 0)\n\t\tlzma_free(opt, allocator);\n\telse\n\t\t*options = opt;\n\n\treturn LZMA_OK;\n}\n"
  },
  {
    "path": "external/xz/liblzma/simple/simple_decoder.h",
    "content": "///////////////////////////////////////////////////////////////////////////////\n//\n/// \\file       simple_decoder.h\n/// \\brief      Properties decoder for simple filters\n//\n//  Author:     Lasse Collin\n//\n//  This file has been put into the public domain.\n//  You can do whatever you want with this file.\n//\n///////////////////////////////////////////////////////////////////////////////\n\n#ifndef LZMA_SIMPLE_DECODER_H\n#define LZMA_SIMPLE_DECODER_H\n\n#include \"simple_coder.h\"\n\nextern lzma_ret lzma_simple_props_decode(\n\t\tvoid **options, const lzma_allocator *allocator,\n\t\tconst uint8_t *props, size_t props_size);\n\n#endif\n"
  },
  {
    "path": "external/xz/liblzma/simple/simple_encoder.c",
    "content": "///////////////////////////////////////////////////////////////////////////////\n//\n/// \\file       simple_encoder.c\n/// \\brief      Properties encoder for simple filters\n//\n//  Author:     Lasse Collin\n//\n//  This file has been put into the public domain.\n//  You can do whatever you want with this file.\n//\n///////////////////////////////////////////////////////////////////////////////\n\n#include \"simple_encoder.h\"\n\n\nextern lzma_ret\nlzma_simple_props_size(uint32_t *size, const void *options)\n{\n\tconst lzma_options_bcj *const opt = options;\n\t*size = (opt == NULL || opt->start_offset == 0) ? 0 : 4;\n\treturn LZMA_OK;\n}\n\n\nextern lzma_ret\nlzma_simple_props_encode(const void *options, uint8_t *out)\n{\n\tconst lzma_options_bcj *const opt = options;\n\n\t// The default start offset is zero, so we don't need to store any\n\t// options unless the start offset is non-zero.\n\tif (opt == NULL || opt->start_offset == 0)\n\t\treturn LZMA_OK;\n\n\twrite32le(out, opt->start_offset);\n\n\treturn LZMA_OK;\n}\n"
  },
  {
    "path": "external/xz/liblzma/simple/simple_encoder.h",
    "content": "///////////////////////////////////////////////////////////////////////////////\n//\n/// \\file       simple_encoder.c\n/// \\brief      Properties encoder for simple filters\n//\n//  Author:     Lasse Collin\n//\n//  This file has been put into the public domain.\n//  You can do whatever you want with this file.\n//\n///////////////////////////////////////////////////////////////////////////////\n\n#ifndef LZMA_SIMPLE_ENCODER_H\n#define LZMA_SIMPLE_ENCODER_H\n\n#include \"simple_coder.h\"\n\n\nextern lzma_ret lzma_simple_props_size(uint32_t *size, const void *options);\n\nextern lzma_ret lzma_simple_props_encode(const void *options, uint8_t *out);\n\n#endif\n"
  },
  {
    "path": "external/xz/liblzma/simple/simple_private.h",
    "content": "///////////////////////////////////////////////////////////////////////////////\n//\n/// \\file       simple_private.h\n/// \\brief      Private definitions for so called simple filters\n//\n//  Author:     Lasse Collin\n//\n//  This file has been put into the public domain.\n//  You can do whatever you want with this file.\n//\n///////////////////////////////////////////////////////////////////////////////\n\n#ifndef LZMA_SIMPLE_PRIVATE_H\n#define LZMA_SIMPLE_PRIVATE_H\n\n#include \"simple_coder.h\"\n\n\ntypedef struct {\n\t/// Next filter in the chain\n\tlzma_next_coder next;\n\n\t/// True if the next coder in the chain has returned LZMA_STREAM_END.\n\tbool end_was_reached;\n\n\t/// True if filter() should encode the data; false to decode.\n\t/// Currently all simple filters use the same function for encoding\n\t/// and decoding, because the difference between encoders and decoders\n\t/// is very small.\n\tbool is_encoder;\n\n\t/// Pointer to filter-specific function, which does\n\t/// the actual filtering.\n\tsize_t (*filter)(void *simple, uint32_t now_pos,\n\t\t\tbool is_encoder, uint8_t *buffer, size_t size);\n\n\t/// Pointer to filter-specific data, or NULL if filter doesn't need\n\t/// any extra data.\n\tvoid *simple;\n\n\t/// The lowest 32 bits of the current position in the data. Most\n\t/// filters need this to do conversions between absolute and relative\n\t/// addresses.\n\tuint32_t now_pos;\n\n\t/// Size of the memory allocated for the buffer.\n\tsize_t allocated;\n\n\t/// Flushing position in the temporary buffer. buffer[pos] is the\n\t/// next byte to be copied to out[].\n\tsize_t pos;\n\n\t/// buffer[filtered] is the first unfiltered byte. When pos is smaller\n\t/// than filtered, there is unflushed filtered data in the buffer.\n\tsize_t filtered;\n\n\t/// Total number of bytes (both filtered and unfiltered) currently\n\t/// in the temporary buffer.\n\tsize_t size;\n\n\t/// Temporary buffer\n\tuint8_t buffer[];\n} lzma_simple_coder;\n\n\nextern lzma_ret lzma_simple_coder_init(lzma_next_coder *next,\n\t\tconst lzma_allocator *allocator,\n\t\tconst lzma_filter_info *filters,\n\t\tsize_t (*filter)(void *simple, uint32_t now_pos,\n\t\t\tbool is_encoder, uint8_t *buffer, size_t size),\n\t\tsize_t simple_size, size_t unfiltered_max,\n\t\tuint32_t alignment, bool is_encoder);\n\n#endif\n"
  },
  {
    "path": "external/xz/liblzma/simple/sparc.c",
    "content": "///////////////////////////////////////////////////////////////////////////////\n//\n/// \\file       sparc.c\n/// \\brief      Filter for SPARC binaries\n///\n//  Authors:    Igor Pavlov\n//              Lasse Collin\n//\n//  This file has been put into the public domain.\n//  You can do whatever you want with this file.\n//\n///////////////////////////////////////////////////////////////////////////////\n\n#include \"simple_private.h\"\n\n\nstatic size_t\nsparc_code(void *simple lzma_attribute((__unused__)),\n\t\tuint32_t now_pos, bool is_encoder,\n\t\tuint8_t *buffer, size_t size)\n{\n\tsize_t i;\n\tfor (i = 0; i + 4 <= size; i += 4) {\n\n\t\tif ((buffer[i] == 0x40 && (buffer[i + 1] & 0xC0) == 0x00)\n\t\t\t\t|| (buffer[i] == 0x7F\n\t\t\t\t&& (buffer[i + 1] & 0xC0) == 0xC0)) {\n\n\t\t\tuint32_t src = ((uint32_t)buffer[i + 0] << 24)\n\t\t\t\t\t| ((uint32_t)buffer[i + 1] << 16)\n\t\t\t\t\t| ((uint32_t)buffer[i + 2] << 8)\n\t\t\t\t\t| ((uint32_t)buffer[i + 3]);\n\n\t\t\tsrc <<= 2;\n\n\t\t\tuint32_t dest;\n\t\t\tif (is_encoder)\n\t\t\t\tdest = now_pos + (uint32_t)(i) + src;\n\t\t\telse\n\t\t\t\tdest = src - (now_pos + (uint32_t)(i));\n\n\t\t\tdest >>= 2;\n\n\t\t\tdest = (((0 - ((dest >> 22) & 1)) << 22) & 0x3FFFFFFF)\n\t\t\t\t\t| (dest & 0x3FFFFF)\n\t\t\t\t\t| 0x40000000;\n\n\t\t\tbuffer[i + 0] = (uint8_t)(dest >> 24);\n\t\t\tbuffer[i + 1] = (uint8_t)(dest >> 16);\n\t\t\tbuffer[i + 2] = (uint8_t)(dest >> 8);\n\t\t\tbuffer[i + 3] = (uint8_t)(dest);\n\t\t}\n\t}\n\n\treturn i;\n}\n\n\nstatic lzma_ret\nsparc_coder_init(lzma_next_coder *next, const lzma_allocator *allocator,\n\t\tconst lzma_filter_info *filters, bool is_encoder)\n{\n\treturn lzma_simple_coder_init(next, allocator, filters,\n\t\t\t&sparc_code, 0, 4, 4, is_encoder);\n}\n\n\nextern lzma_ret\nlzma_simple_sparc_encoder_init(lzma_next_coder *next,\n\t\tconst lzma_allocator *allocator,\n\t\tconst lzma_filter_info *filters)\n{\n\treturn sparc_coder_init(next, allocator, filters, true);\n}\n\n\nextern lzma_ret\nlzma_simple_sparc_decoder_init(lzma_next_coder *next,\n\t\tconst lzma_allocator *allocator,\n\t\tconst lzma_filter_info *filters)\n{\n\treturn sparc_coder_init(next, allocator, filters, false);\n}\n"
  },
  {
    "path": "external/xz/liblzma/simple/x86.c",
    "content": "///////////////////////////////////////////////////////////////////////////////\n//\n/// \\file       x86.c\n/// \\brief      Filter for x86 binaries (BCJ filter)\n///\n//  Authors:    Igor Pavlov\n//              Lasse Collin\n//\n//  This file has been put into the public domain.\n//  You can do whatever you want with this file.\n//\n///////////////////////////////////////////////////////////////////////////////\n\n#include \"simple_private.h\"\n\n\n#define Test86MSByte(b) ((b) == 0 || (b) == 0xFF)\n\n\ntypedef struct {\n\tuint32_t prev_mask;\n\tuint32_t prev_pos;\n} lzma_simple_x86;\n\n\nstatic size_t\nx86_code(void *simple_ptr, uint32_t now_pos, bool is_encoder,\n\t\tuint8_t *buffer, size_t size)\n{\n\tstatic const bool MASK_TO_ALLOWED_STATUS[8]\n\t\t= { true, true, true, false, true, false, false, false };\n\n\tstatic const uint32_t MASK_TO_BIT_NUMBER[8]\n\t\t\t= { 0, 1, 2, 2, 3, 3, 3, 3 };\n\n\tlzma_simple_x86 *simple = simple_ptr;\n\tuint32_t prev_mask = simple->prev_mask;\n\tuint32_t prev_pos = simple->prev_pos;\n\n\tif (size < 5)\n\t\treturn 0;\n\n\tif (now_pos - prev_pos > 5)\n\t\tprev_pos = now_pos - 5;\n\n\tconst size_t limit = size - 5;\n\tsize_t buffer_pos = 0;\n\n\twhile (buffer_pos <= limit) {\n\t\tuint8_t b = buffer[buffer_pos];\n\t\tif (b != 0xE8 && b != 0xE9) {\n\t\t\t++buffer_pos;\n\t\t\tcontinue;\n\t\t}\n\n\t\tconst uint32_t offset = now_pos + (uint32_t)(buffer_pos)\n\t\t\t\t- prev_pos;\n\t\tprev_pos = now_pos + (uint32_t)(buffer_pos);\n\n\t\tif (offset > 5) {\n\t\t\tprev_mask = 0;\n\t\t} else {\n\t\t\tfor (uint32_t i = 0; i < offset; ++i) {\n\t\t\t\tprev_mask &= 0x77;\n\t\t\t\tprev_mask <<= 1;\n\t\t\t}\n\t\t}\n\n\t\tb = buffer[buffer_pos + 4];\n\n\t\tif (Test86MSByte(b)\n\t\t\t&& MASK_TO_ALLOWED_STATUS[(prev_mask >> 1) & 0x7]\n\t\t\t\t&& (prev_mask >> 1) < 0x10) {\n\n\t\t\tuint32_t src = ((uint32_t)(b) << 24)\n\t\t\t\t| ((uint32_t)(buffer[buffer_pos + 3]) << 16)\n\t\t\t\t| ((uint32_t)(buffer[buffer_pos + 2]) << 8)\n\t\t\t\t| (buffer[buffer_pos + 1]);\n\n\t\t\tuint32_t dest;\n\t\t\twhile (true) {\n\t\t\t\tif (is_encoder)\n\t\t\t\t\tdest = src + (now_pos + (uint32_t)(\n\t\t\t\t\t\t\tbuffer_pos) + 5);\n\t\t\t\telse\n\t\t\t\t\tdest = src - (now_pos + (uint32_t)(\n\t\t\t\t\t\t\tbuffer_pos) + 5);\n\n\t\t\t\tif (prev_mask == 0)\n\t\t\t\t\tbreak;\n\n\t\t\t\tconst uint32_t i = MASK_TO_BIT_NUMBER[\n\t\t\t\t\t\tprev_mask >> 1];\n\n\t\t\t\tb = (uint8_t)(dest >> (24 - i * 8));\n\n\t\t\t\tif (!Test86MSByte(b))\n\t\t\t\t\tbreak;\n\n\t\t\t\tsrc = dest ^ ((1U << (32 - i * 8)) - 1);\n\t\t\t}\n\n\t\t\tbuffer[buffer_pos + 4]\n\t\t\t\t\t= (uint8_t)(~(((dest >> 24) & 1) - 1));\n\t\t\tbuffer[buffer_pos + 3] = (uint8_t)(dest >> 16);\n\t\t\tbuffer[buffer_pos + 2] = (uint8_t)(dest >> 8);\n\t\t\tbuffer[buffer_pos + 1] = (uint8_t)(dest);\n\t\t\tbuffer_pos += 5;\n\t\t\tprev_mask = 0;\n\n\t\t} else {\n\t\t\t++buffer_pos;\n\t\t\tprev_mask |= 1;\n\t\t\tif (Test86MSByte(b))\n\t\t\t\tprev_mask |= 0x10;\n\t\t}\n\t}\n\n\tsimple->prev_mask = prev_mask;\n\tsimple->prev_pos = prev_pos;\n\n\treturn buffer_pos;\n}\n\n\nstatic lzma_ret\nx86_coder_init(lzma_next_coder *next, const lzma_allocator *allocator,\n\t\tconst lzma_filter_info *filters, bool is_encoder)\n{\n\tconst lzma_ret ret = lzma_simple_coder_init(next, allocator, filters,\n\t\t\t&x86_code, sizeof(lzma_simple_x86), 5, 1, is_encoder);\n\n\tif (ret == LZMA_OK) {\n\t\tlzma_simple_coder *coder = next->coder;\n\t\tlzma_simple_x86 *simple = coder->simple;\n\t\tsimple->prev_mask = 0;\n\t\tsimple->prev_pos = (uint32_t)(-5);\n\t}\n\n\treturn ret;\n}\n\n\nextern lzma_ret\nlzma_simple_x86_encoder_init(lzma_next_coder *next,\n\t\tconst lzma_allocator *allocator,\n\t\tconst lzma_filter_info *filters)\n{\n\treturn x86_coder_init(next, allocator, filters, true);\n}\n\n\nextern lzma_ret\nlzma_simple_x86_decoder_init(lzma_next_coder *next,\n\t\tconst lzma_allocator *allocator,\n\t\tconst lzma_filter_info *filters)\n{\n\treturn x86_coder_init(next, allocator, filters, false);\n}\n"
  },
  {
    "path": "external/xz_config/config.h",
    "content": "/* config.h.  Generated from config.h.in by configure.  */\n/* config.h.in.  Generated from configure.ac by autoheader.  */\n\n/* Define if building universal (internal helper macro) */\n/* #undef AC_APPLE_UNIVERSAL_BUILD */\n\n/* How many MiB of RAM to assume if the real amount cannot be determined. */\n#define ASSUME_RAM 128\n#ifdef SVB_MINGW  \ntypedef unsigned long long sigset_t;\n#else\n/* Define to 1 if translation of program messages to the user's native\n   language is requested. */\n/* #undef ENABLE_NLS */\n\n/* Define to 1 if bswap_16 is available. */\n#define HAVE_BSWAP_16 1\n\n/* Define to 1 if bswap_32 is available. */\n#define HAVE_BSWAP_32 1\n\n/* Define to 1 if bswap_64 is available. */\n#define HAVE_BSWAP_64 1\n\n/* Define to 1 if you have the <byteswap.h> header file. */\n#define HAVE_BYTESWAP_H 1\n#endif\n/* Define to 1 if Capsicum is available. */\n/* #undef HAVE_CAPSICUM */\n\n/* Define to 1 if the system has the type `CC_SHA256_CTX'. */\n/* #undef HAVE_CC_SHA256_CTX */\n\n/* Define to 1 if you have the `CC_SHA256_Init' function. */\n/* #undef HAVE_CC_SHA256_INIT */\n\n/* Define to 1 if you have the MacOS X function CFLocaleCopyCurrent in the\n   CoreFoundation framework. */\n/* #undef HAVE_CFLOCALECOPYCURRENT */\n\n/* Define to 1 if you have the MacOS X function CFPreferencesCopyAppValue in\n   the CoreFoundation framework. */\n/* #undef HAVE_CFPREFERENCESCOPYAPPVALUE */\n\n/* Define to 1 if crc32 integrity check is enabled. */\n#define HAVE_CHECK_CRC32 1\n\n/* Define to 1 if crc64 integrity check is enabled. */\n#define HAVE_CHECK_CRC64 1\n\n/* Define to 1 if sha256 integrity check is enabled. */\n#define HAVE_CHECK_SHA256 1\n\n/* Define to 1 if you have the `clock_gettime' function. */\n#define HAVE_CLOCK_GETTIME 1\n\n/* Define to 1 if you have the <CommonCrypto/CommonDigest.h> header file. */\n/* #undef HAVE_COMMONCRYPTO_COMMONDIGEST_H */\n\n/* Define if the GNU dcgettext() function is already present or preinstalled.\n   */\n/* #undef HAVE_DCGETTEXT */\n\n/* Define to 1 if you have the declaration of `CLOCK_MONOTONIC', and to 0 if\n   you don't. */\n#define HAVE_DECL_CLOCK_MONOTONIC 1\n\n/* Define to 1 if you have the declaration of `program_invocation_name', and\n   to 0 if you don't. */\n#define HAVE_DECL_PROGRAM_INVOCATION_NAME 0\n\n/* Define to 1 if any of HAVE_DECODER_foo have been defined. */\n#define HAVE_DECODERS 1\n\n/* Define to 1 if arm decoder is enabled. */\n#define HAVE_DECODER_ARM 1\n\n/* Define to 1 if armthumb decoder is enabled. */\n#define HAVE_DECODER_ARMTHUMB 1\n\n/* Define to 1 if delta decoder is enabled. */\n#define HAVE_DECODER_DELTA 1\n\n/* Define to 1 if ia64 decoder is enabled. */\n#define HAVE_DECODER_IA64 1\n\n/* Define to 1 if lzma1 decoder is enabled. */\n#define HAVE_DECODER_LZMA1 1\n\n/* Define to 1 if lzma2 decoder is enabled. */\n#define HAVE_DECODER_LZMA2 1\n\n/* Define to 1 if powerpc decoder is enabled. */\n#define HAVE_DECODER_POWERPC 1\n\n/* Define to 1 if sparc decoder is enabled. */\n#define HAVE_DECODER_SPARC 1\n\n/* Define to 1 if x86 decoder is enabled. */\n#define HAVE_DECODER_X86 1\n\n/* Define to 1 if you have the <dlfcn.h> header file. */\n#define HAVE_DLFCN_H 1\n\n/* Define to 1 if any of HAVE_ENCODER_foo have been defined. */\n#define HAVE_ENCODERS 1\n\n/* Define to 1 if arm encoder is enabled. */\n#define HAVE_ENCODER_ARM 1\n\n/* Define to 1 if armthumb encoder is enabled. */\n#define HAVE_ENCODER_ARMTHUMB 1\n\n/* Define to 1 if delta encoder is enabled. */\n#define HAVE_ENCODER_DELTA 1\n\n/* Define to 1 if ia64 encoder is enabled. */\n#define HAVE_ENCODER_IA64 1\n\n/* Define to 1 if lzma1 encoder is enabled. */\n#define HAVE_ENCODER_LZMA1 1\n\n/* Define to 1 if lzma2 encoder is enabled. */\n#define HAVE_ENCODER_LZMA2 1\n\n/* Define to 1 if powerpc encoder is enabled. */\n#define HAVE_ENCODER_POWERPC 1\n\n/* Define to 1 if sparc encoder is enabled. */\n#define HAVE_ENCODER_SPARC 1\n\n/* Define to 1 if x86 encoder is enabled. */\n#define HAVE_ENCODER_X86 1\n\n/* Define to 1 if you have the <fcntl.h> header file. */\n#define HAVE_FCNTL_H 1\n\n/* Define to 1 if you have the `futimens' function. */\n#define HAVE_FUTIMENS 1\n\n/* Define to 1 if you have the `futimes' function. */\n/* #undef HAVE_FUTIMES */\n\n/* Define to 1 if you have the `futimesat' function. */\n/* #undef HAVE_FUTIMESAT */\n\n/* Define to 1 if you have the <getopt.h> header file. */\n#define HAVE_GETOPT_H 1\n\n/* Define to 1 if you have the `getopt_long' function. */\n#define HAVE_GETOPT_LONG 1\n\n/* Define if the GNU gettext() function is already present or preinstalled. */\n/* #undef HAVE_GETTEXT */\n\n/* Define if you have the iconv() function and it works. */\n/* #undef HAVE_ICONV */\n\n/* Define to 1 if you have the <immintrin.h> header file. */\n/* #undef HAVE_IMMINTRIN_H */\n\n/* Define to 1 if you have the <inttypes.h> header file. */\n#define HAVE_INTTYPES_H 1\n\n/* Define to 1 if you have the <limits.h> header file. */\n#define HAVE_LIMITS_H 1\n\n/* Define to 1 if mbrtowc and mbstate_t are properly declared. */\n#define HAVE_MBRTOWC 1\n\n/* Define to 1 if you have the <memory.h> header file. */\n#define HAVE_MEMORY_H 1\n\n/* Define to 1 to enable bt2 match finder. */\n#define HAVE_MF_BT2 1\n\n/* Define to 1 to enable bt3 match finder. */\n#define HAVE_MF_BT3 1\n\n/* Define to 1 to enable bt4 match finder. */\n#define HAVE_MF_BT4 1\n\n/* Define to 1 to enable hc3 match finder. */\n#define HAVE_MF_HC3 1\n\n/* Define to 1 to enable hc4 match finder. */\n#define HAVE_MF_HC4 1\n\n/* Define to 1 if you have the <minix/sha2.h> header file. */\n/* #undef HAVE_MINIX_SHA2_H */\n\n/* Define to 1 if getopt.h declares extern int optreset. */\n#define HAVE_OPTRESET 1\n\n/* Define to 1 if you have the `posix_fadvise' function. */\n#define HAVE_POSIX_FADVISE 1\n\n/* Define to 1 if you have the `pthread_condattr_setclock' function. */\n#define HAVE_PTHREAD_CONDATTR_SETCLOCK 1\n\n/* Have PTHREAD_PRIO_INHERIT. */\n/* #undef HAVE_PTHREAD_PRIO_INHERIT */\n\n/* Define to 1 if you have the `SHA256Init' function. */\n/* #undef HAVE_SHA256INIT */\n\n/* Define to 1 if the system has the type `SHA256_CTX'. */\n/* #undef HAVE_SHA256_CTX */\n\n/* Define to 1 if you have the <sha256.h> header file. */\n/* #undef HAVE_SHA256_H */\n\n/* Define to 1 if you have the `SHA256_Init' function. */\n/* #undef HAVE_SHA256_INIT */\n\n/* Define to 1 if the system has the type `SHA2_CTX'. */\n/* #undef HAVE_SHA2_CTX */\n\n/* Define to 1 if you have the <sha2.h> header file. */\n/* #undef HAVE_SHA2_H */\n\n/* Define to 1 if optimizing for size. */\n/* #undef HAVE_SMALL */\n\n/* Define to 1 if stdbool.h conforms to C99. */\n#define HAVE_STDBOOL_H 1\n\n/* Define to 1 if you have the <stdint.h> header file. */\n#define HAVE_STDINT_H 1\n\n/* Define to 1 if you have the <stdlib.h> header file. */\n#define HAVE_STDLIB_H 1\n\n/* Define to 1 if you have the <strings.h> header file. */\n#define HAVE_STRINGS_H 1\n\n/* Define to 1 if you have the <string.h> header file. */\n#define HAVE_STRING_H 1\n\n/* Define to 1 if `st_atimensec' is a member of `struct stat'. */\n#define HAVE_STRUCT_STAT_ST_ATIMENSEC 1\n\n/* Define to 1 if `st_atimespec.tv_nsec' is a member of `struct stat'. */\n/* #undef HAVE_STRUCT_STAT_ST_ATIMESPEC_TV_NSEC */\n\n/* Define to 1 if `st_atim.st__tim.tv_nsec' is a member of `struct stat'. */\n/* #undef HAVE_STRUCT_STAT_ST_ATIM_ST__TIM_TV_NSEC */\n\n/* Define to 1 if `st_atim.tv_nsec' is a member of `struct stat'. */\n/* #undef HAVE_STRUCT_STAT_ST_ATIM_TV_NSEC */\n\n/* Define to 1 if `st_uatime' is a member of `struct stat'. */\n/* #undef HAVE_STRUCT_STAT_ST_UATIME */\n\n/* Define to 1 if you have the <sys/byteorder.h> header file. */\n/* #undef HAVE_SYS_BYTEORDER_H */\n\n/* Define to 1 if you have the <sys/capsicum.h> header file. */\n/* #undef HAVE_SYS_CAPSICUM_H */\n\n/* Define to 1 if you have the <sys/endian.h> header file. */\n/* #undef HAVE_SYS_ENDIAN_H */\n\n/* Define to 1 if you have the <sys/param.h> header file. */\n#define HAVE_SYS_PARAM_H 1\n\n/* Define to 1 if you have the <sys/stat.h> header file. */\n#define HAVE_SYS_STAT_H 1\n\n/* Define to 1 if you have the <sys/time.h> header file. */\n#define HAVE_SYS_TIME_H 1\n\n/* Define to 1 if you have the <sys/types.h> header file. */\n#define HAVE_SYS_TYPES_H 1\n\n/* Define to 1 if the system has the type `uintptr_t'. */\n#define HAVE_UINTPTR_T 1\n\n/* Define to 1 if you have the <unistd.h> header file. */\n#define HAVE_UNISTD_H 1\n\n/* Define to 1 if you have the `utime' function. */\n/* #undef HAVE_UTIME */\n\n/* Define to 1 if you have the `utimes' function. */\n/* #undef HAVE_UTIMES */\n\n/* Define to 1 or 0, depending whether the compiler supports simple visibility\n   declarations. */\n#define HAVE_VISIBILITY 1\n\n/* Define to 1 if you have the `wcwidth' function. */\n#ifndef SVB_MINGW\n#define HAVE_WCWIDTH 1\n#endif\n\n/* Define to 1 if the system has the type `_Bool'. */\n#define HAVE__BOOL 1\n\n/* Define to 1 if _mm_movemask_epi8 is available. */\n/* #undef HAVE__MM_MOVEMASK_EPI8 */\n\n/* Define to the sub-directory where libtool stores uninstalled libraries. */\n#define LT_OBJDIR \".libs/\"\n\n/* Define to 1 when using POSIX threads (pthreads). */\n#define MYTHREAD_POSIX 1\n\n/* Define to 1 when using Windows Vista compatible threads. This uses features\n   that are not available on Windows XP. */\n/* #undef MYTHREAD_VISTA */\n\n/* Define to 1 when using Windows 95 (and thus XP) compatible threads. This\n   avoids use of features that were added in Windows Vista. */\n/* #undef MYTHREAD_WIN95 */\n\n/* Define to 1 to disable debugging code. */\n#define NDEBUG 1\n\n/* Name of package */\n#define PACKAGE \"xz\"\n\n/* Define to the address where bug reports for this package should be sent. */\n#define PACKAGE_BUGREPORT \"lasse.collin@tukaani.org\"\n\n/* Define to the full name of this package. */\n#define PACKAGE_NAME \"XZ Utils\"\n\n/* Define to the full name and version of this package. */\n#define PACKAGE_STRING \"XZ Utils 5.3.0alpha\"\n\n/* Define to the one symbol short name of this package. */\n#define PACKAGE_TARNAME \"xz\"\n\n/* Define to the home page for this package. */\n#define PACKAGE_URL \"http://tukaani.org/xz/\"\n\n/* Define to the version of this package. */\n#define PACKAGE_VERSION \"5.3.0alpha\"\n\n/* Define to necessary symbol if this constant uses a non-standard name on\n   your system. */\n/* #undef PTHREAD_CREATE_JOINABLE */\n\n/* The size of `size_t', as computed by sizeof. */\n#define SIZEOF_SIZE_T 4\n\n/* Define to 1 if you have the ANSI C header files. */\n#define STDC_HEADERS 1\n\n/* Define to 1 if the number of available CPU cores can be detected with\n   cpuset(2). */\n/* #undef TUKLIB_CPUCORES_CPUSET */\n\n/* Define to 1 if the number of available CPU cores can be detected with\n   pstat_getdynamic(). */\n/* #undef TUKLIB_CPUCORES_PSTAT_GETDYNAMIC */\n\n/* Define to 1 if the number of available CPU cores can be detected with\n   sysconf(_SC_NPROCESSORS_ONLN) or sysconf(_SC_NPROC_ONLN). */\n#define TUKLIB_CPUCORES_SYSCONF 1\n\n/* Define to 1 if the number of available CPU cores can be detected with\n   sysctl(). */\n/* #undef TUKLIB_CPUCORES_SYSCTL */\n\n/* Define to 1 if the system supports fast unaligned access to 16-bit and\n   32-bit integers. */\n/* #undef TUKLIB_FAST_UNALIGNED_ACCESS */\n\n/* Define to 1 if the amount of physical memory can be detected with\n   _system_configuration.physmem. */\n/* #undef TUKLIB_PHYSMEM_AIX */\n\n/* Define to 1 if the amount of physical memory can be detected with\n   getinvent_r(). */\n/* #undef TUKLIB_PHYSMEM_GETINVENT_R */\n\n/* Define to 1 if the amount of physical memory can be detected with\n   getsysinfo(). */\n/* #undef TUKLIB_PHYSMEM_GETSYSINFO */\n\n/* Define to 1 if the amount of physical memory can be detected with\n   pstat_getstatic(). */\n/* #undef TUKLIB_PHYSMEM_PSTAT_GETSTATIC */\n\n/* Define to 1 if the amount of physical memory can be detected with\n   sysconf(_SC_PAGESIZE) and sysconf(_SC_PHYS_PAGES). */\n#define TUKLIB_PHYSMEM_SYSCONF 1\n\n/* Define to 1 if the amount of physical memory can be detected with sysctl().\n   */\n/* #undef TUKLIB_PHYSMEM_SYSCTL */\n\n/* Define to 1 if the amount of physical memory can be detected with Linux\n   sysinfo(). */\n/* #undef TUKLIB_PHYSMEM_SYSINFO */\n\n/* Enable extensions on AIX 3, Interix.  */\n#ifndef _ALL_SOURCE\n# define _ALL_SOURCE 1\n#endif\n/* Enable GNU extensions on systems that have them.  */\n#ifndef _GNU_SOURCE\n# define _GNU_SOURCE 1\n#endif\n/* Enable threading extensions on Solaris.  */\n#ifndef _POSIX_PTHREAD_SEMANTICS\n# define _POSIX_PTHREAD_SEMANTICS 1\n#endif\n/* Enable extensions on HP NonStop.  */\n#ifndef _TANDEM_SOURCE\n# define _TANDEM_SOURCE 1\n#endif\n/* Enable general extensions on Solaris.  */\n#ifndef __EXTENSIONS__\n# define __EXTENSIONS__ 1\n#endif\n\n\n/* Version number of package */\n#define VERSION \"5.3.0alpha\"\n\n/* Define WORDS_BIGENDIAN to 1 if your processor stores words with the most\n   significant byte first (like Motorola and SPARC, unlike Intel). */\n#if defined AC_APPLE_UNIVERSAL_BUILD\n# if defined __BIG_ENDIAN__\n#  define WORDS_BIGENDIAN 1\n# endif\n#else\n# ifndef WORDS_BIGENDIAN\n/* #  undef WORDS_BIGENDIAN */\n# endif\n#endif\n\n/* Enable large inode numbers on Mac OS X 10.5.  */\n#ifndef _DARWIN_USE_64_BIT_INODE\n# define _DARWIN_USE_64_BIT_INODE 1\n#endif\n\n/* Number of bits in a file offset, on hosts where this is settable. */\n/* #undef _FILE_OFFSET_BITS */\n\n/* Define for large files, on AIX-style hosts. */\n/* #undef _LARGE_FILES */\n\n/* Define to 1 if on MINIX. */\n/* #undef _MINIX */\n\n/* Define to 2 if the system does not provide POSIX.1 features except with\n   this defined. */\n/* #undef _POSIX_1_SOURCE */\n\n/* Define to 1 if you need to in order for `stat' and other things to work. */\n/* #undef _POSIX_SOURCE */\n\n/* Define for Solaris 2.5.1 so the uint32_t typedef from <sys/synch.h>,\n   <pthread.h>, or <semaphore.h> is not used. If the typedef were allowed, the\n   #define below would cause a syntax error. */\n/* #undef _UINT32_T */\n\n/* Define for Solaris 2.5.1 so the uint64_t typedef from <sys/synch.h>,\n   <pthread.h>, or <semaphore.h> is not used. If the typedef were allowed, the\n   #define below would cause a syntax error. */\n/* #undef _UINT64_T */\n\n/* Define for Solaris 2.5.1 so the uint8_t typedef from <sys/synch.h>,\n   <pthread.h>, or <semaphore.h> is not used. If the typedef were allowed, the\n   #define below would cause a syntax error. */\n/* #undef _UINT8_T */\n\n/* Define to rpl_ if the getopt replacement functions and variables should be\n   used. */\n/* #undef __GETOPT_PREFIX */\n\n/* Define to the type of a signed integer type of width exactly 32 bits if\n   such a type exists and the standard includes do not define it. */\n/* #undef int32_t */\n\n/* Define to the type of a signed integer type of width exactly 64 bits if\n   such a type exists and the standard includes do not define it. */\n/* #undef int64_t */\n\n/* Define to the type of an unsigned integer type of width exactly 16 bits if\n   such a type exists and the standard includes do not define it. */\n/* #undef uint16_t */\n\n/* Define to the type of an unsigned integer type of width exactly 32 bits if\n   such a type exists and the standard includes do not define it. */\n/* #undef uint32_t */\n\n/* Define to the type of an unsigned integer type of width exactly 64 bits if\n   such a type exists and the standard includes do not define it. */\n/* #undef uint64_t */\n\n/* Define to the type of an unsigned integer type of width exactly 8 bits if\n   such a type exists and the standard includes do not define it. */\n/* #undef uint8_t */\n\n/* Define to the type of an unsigned integer type wide enough to hold a\n   pointer, if such a type exists, and if the system does not define it. */\n/* #undef uintptr_t */\n"
  },
  {
    "path": "external/zlib/adler32.c",
    "content": "/* adler32.c -- compute the Adler-32 checksum of a data stream\n * Copyright (C) 1995-2011 Mark Adler\n * For conditions of distribution and use, see copyright notice in zlib.h\n */\n\n/* @(#) $Id$ */\n\n#include \"zutil.h\"\n\n#define local static\n\nlocal uLong adler32_combine_ OF((uLong adler1, uLong adler2, z_off64_t len2));\n\n#define BASE 65521      /* largest prime smaller than 65536 */\n#define NMAX 5552\n/* NMAX is the largest n such that 255n(n+1)/2 + (n+1)(BASE-1) <= 2^32-1 */\n\n#define DO1(buf,i)  {adler += (buf)[i]; sum2 += adler;}\n#define DO2(buf,i)  DO1(buf,i); DO1(buf,i+1);\n#define DO4(buf,i)  DO2(buf,i); DO2(buf,i+2);\n#define DO8(buf,i)  DO4(buf,i); DO4(buf,i+4);\n#define DO16(buf)   DO8(buf,0); DO8(buf,8);\n\n/* use NO_DIVIDE if your processor does not do division in hardware --\n   try it both ways to see which is faster */\n#ifdef NO_DIVIDE\n/* note that this assumes BASE is 65521, where 65536 % 65521 == 15\n   (thank you to John Reiser for pointing this out) */\n#  define CHOP(a) \\\n    do { \\\n        unsigned long tmp = a >> 16; \\\n        a &= 0xffffUL; \\\n        a += (tmp << 4) - tmp; \\\n    } while (0)\n#  define MOD28(a) \\\n    do { \\\n        CHOP(a); \\\n        if (a >= BASE) a -= BASE; \\\n    } while (0)\n#  define MOD(a) \\\n    do { \\\n        CHOP(a); \\\n        MOD28(a); \\\n    } while (0)\n#  define MOD63(a) \\\n    do { /* this assumes a is not negative */ \\\n        z_off64_t tmp = a >> 32; \\\n        a &= 0xffffffffL; \\\n        a += (tmp << 8) - (tmp << 5) + tmp; \\\n        tmp = a >> 16; \\\n        a &= 0xffffL; \\\n        a += (tmp << 4) - tmp; \\\n        tmp = a >> 16; \\\n        a &= 0xffffL; \\\n        a += (tmp << 4) - tmp; \\\n        if (a >= BASE) a -= BASE; \\\n    } while (0)\n#else\n#  define MOD(a) a %= BASE\n#  define MOD28(a) a %= BASE\n#  define MOD63(a) a %= BASE\n#endif\n\n/* ========================================================================= */\nuLong ZEXPORT adler32(adler, buf, len)\n    uLong adler;\n    const Bytef *buf;\n    uInt len;\n{\n    unsigned long sum2;\n    unsigned n;\n\n    /* split Adler-32 into component sums */\n    sum2 = (adler >> 16) & 0xffff;\n    adler &= 0xffff;\n\n    /* in case user likes doing a byte at a time, keep it fast */\n    if (len == 1) {\n        adler += buf[0];\n        if (adler >= BASE)\n            adler -= BASE;\n        sum2 += adler;\n        if (sum2 >= BASE)\n            sum2 -= BASE;\n        return adler | (sum2 << 16);\n    }\n\n    /* initial Adler-32 value (deferred check for len == 1 speed) */\n    if (buf == Z_NULL)\n        return 1L;\n\n    /* in case short lengths are provided, keep it somewhat fast */\n    if (len < 16) {\n        while (len--) {\n            adler += *buf++;\n            sum2 += adler;\n        }\n        if (adler >= BASE)\n            adler -= BASE;\n        MOD28(sum2);            /* only added so many BASE's */\n        return adler | (sum2 << 16);\n    }\n\n    /* do length NMAX blocks -- requires just one modulo operation */\n    while (len >= NMAX) {\n        len -= NMAX;\n        n = NMAX / 16;          /* NMAX is divisible by 16 */\n        do {\n            DO16(buf);          /* 16 sums unrolled */\n            buf += 16;\n        } while (--n);\n        MOD(adler);\n        MOD(sum2);\n    }\n\n    /* do remaining bytes (less than NMAX, still just one modulo) */\n    if (len) {                  /* avoid modulos if none remaining */\n        while (len >= 16) {\n            len -= 16;\n            DO16(buf);\n            buf += 16;\n        }\n        while (len--) {\n            adler += *buf++;\n            sum2 += adler;\n        }\n        MOD(adler);\n        MOD(sum2);\n    }\n\n    /* return recombined sums */\n    return adler | (sum2 << 16);\n}\n\n/* ========================================================================= */\nlocal uLong adler32_combine_(adler1, adler2, len2)\n    uLong adler1;\n    uLong adler2;\n    z_off64_t len2;\n{\n    unsigned long sum1;\n    unsigned long sum2;\n    unsigned rem;\n\n    /* for negative len, return invalid adler32 as a clue for debugging */\n    if (len2 < 0)\n        return 0xffffffffUL;\n\n    /* the derivation of this formula is left as an exercise for the reader */\n    MOD63(len2);                /* assumes len2 >= 0 */\n    rem = (unsigned)len2;\n    sum1 = adler1 & 0xffff;\n    sum2 = rem * sum1;\n    MOD(sum2);\n    sum1 += (adler2 & 0xffff) + BASE - 1;\n    sum2 += ((adler1 >> 16) & 0xffff) + ((adler2 >> 16) & 0xffff) + BASE - rem;\n    if (sum1 >= BASE) sum1 -= BASE;\n    if (sum1 >= BASE) sum1 -= BASE;\n    if (sum2 >= (BASE << 1)) sum2 -= (BASE << 1);\n    if (sum2 >= BASE) sum2 -= BASE;\n    return sum1 | (sum2 << 16);\n}\n\n/* ========================================================================= */\nuLong ZEXPORT adler32_combine(adler1, adler2, len2)\n    uLong adler1;\n    uLong adler2;\n    z_off_t len2;\n{\n    return adler32_combine_(adler1, adler2, len2);\n}\n\nuLong ZEXPORT adler32_combine64(adler1, adler2, len2)\n    uLong adler1;\n    uLong adler2;\n    z_off64_t len2;\n{\n    return adler32_combine_(adler1, adler2, len2);\n}\n"
  },
  {
    "path": "external/zlib/compress.c",
    "content": "/* compress.c -- compress a memory buffer\n * Copyright (C) 1995-2005 Jean-loup Gailly.\n * For conditions of distribution and use, see copyright notice in zlib.h\n */\n\n/* @(#) $Id$ */\n\n#define ZLIB_INTERNAL\n#include \"zlib.h\"\n\n/* ===========================================================================\n     Compresses the source buffer into the destination buffer. The level\n   parameter has the same meaning as in deflateInit.  sourceLen is the byte\n   length of the source buffer. Upon entry, destLen is the total size of the\n   destination buffer, which must be at least 0.1% larger than sourceLen plus\n   12 bytes. Upon exit, destLen is the actual size of the compressed buffer.\n\n     compress2 returns Z_OK if success, Z_MEM_ERROR if there was not enough\n   memory, Z_BUF_ERROR if there was not enough room in the output buffer,\n   Z_STREAM_ERROR if the level parameter is invalid.\n*/\nint ZEXPORT compress2 (dest, destLen, source, sourceLen, level)\n    Bytef *dest;\n    uLongf *destLen;\n    const Bytef *source;\n    uLong sourceLen;\n    int level;\n{\n    z_stream stream;\n    int err;\n\n    stream.next_in = (z_const Bytef *)source;\n    stream.avail_in = (uInt)sourceLen;\n#ifdef MAXSEG_64K\n    /* Check for source > 64K on 16-bit machine: */\n    if ((uLong)stream.avail_in != sourceLen) return Z_BUF_ERROR;\n#endif\n    stream.next_out = dest;\n    stream.avail_out = (uInt)*destLen;\n    if ((uLong)stream.avail_out != *destLen) return Z_BUF_ERROR;\n\n    stream.zalloc = (alloc_func)0;\n    stream.zfree = (free_func)0;\n    stream.opaque = (voidpf)0;\n\n    err = deflateInit(&stream, level);\n    if (err != Z_OK) return err;\n\n    err = deflate(&stream, Z_FINISH);\n    if (err != Z_STREAM_END) {\n        deflateEnd(&stream);\n        return err == Z_OK ? Z_BUF_ERROR : err;\n    }\n    *destLen = stream.total_out;\n\n    err = deflateEnd(&stream);\n    return err;\n}\n\n/* ===========================================================================\n */\nint ZEXPORT compress (dest, destLen, source, sourceLen)\n    Bytef *dest;\n    uLongf *destLen;\n    const Bytef *source;\n    uLong sourceLen;\n{\n    return compress2(dest, destLen, source, sourceLen, Z_DEFAULT_COMPRESSION);\n}\n\n/* ===========================================================================\n     If the default memLevel or windowBits for deflateInit() is changed, then\n   this function needs to be updated.\n */\nuLong ZEXPORT compressBound (sourceLen)\n    uLong sourceLen;\n{\n    return sourceLen + (sourceLen >> 12) + (sourceLen >> 14) +\n           (sourceLen >> 25) + 13;\n}\n"
  },
  {
    "path": "external/zlib/crc32.c",
    "content": "/* crc32.c -- compute the CRC-32 of a data stream\n * Copyright (C) 1995-2006, 2010, 2011, 2012 Mark Adler\n * For conditions of distribution and use, see copyright notice in zlib.h\n *\n * Thanks to Rodney Brown <rbrown64@csc.com.au> for his contribution of faster\n * CRC methods: exclusive-oring 32 bits of data at a time, and pre-computing\n * tables for updating the shift register in one step with three exclusive-ors\n * instead of four steps with four exclusive-ors.  This results in about a\n * factor of two increase in speed on a Power PC G4 (PPC7455) using gcc -O3.\n */\n\n/* @(#) $Id$ */\n\n/*\n  Note on the use of DYNAMIC_CRC_TABLE: there is no mutex or semaphore\n  protection on the static variables used to control the first-use generation\n  of the crc tables.  Therefore, if you #define DYNAMIC_CRC_TABLE, you should\n  first call get_crc_table() to initialize the tables before allowing more than\n  one thread to use crc32().\n\n  DYNAMIC_CRC_TABLE and MAKECRCH can be #defined to write out crc32.h.\n */\n\n#ifdef MAKECRCH\n#  include <stdio.h>\n#  ifndef DYNAMIC_CRC_TABLE\n#    define DYNAMIC_CRC_TABLE\n#  endif /* !DYNAMIC_CRC_TABLE */\n#endif /* MAKECRCH */\n\n#include \"zutil.h\"      /* for STDC and FAR definitions */\n\n#define local static\n\n/* Definitions for doing the crc four data bytes at a time. */\n#if !defined(NOBYFOUR) && defined(Z_U4)\n#  define BYFOUR\n#endif\n#ifdef BYFOUR\n   local unsigned long crc32_little OF((unsigned long,\n                        const unsigned char FAR *, unsigned));\n   local unsigned long crc32_big OF((unsigned long,\n                        const unsigned char FAR *, unsigned));\n#  define TBLS 8\n#else\n#  define TBLS 1\n#endif /* BYFOUR */\n\n/* Local functions for crc concatenation */\nlocal unsigned long gf2_matrix_times OF((unsigned long *mat,\n                                         unsigned long vec));\nlocal void gf2_matrix_square OF((unsigned long *square, unsigned long *mat));\nlocal uLong crc32_combine_ OF((uLong crc1, uLong crc2, z_off64_t len2));\n\n\n#ifdef DYNAMIC_CRC_TABLE\n\nlocal volatile int crc_table_empty = 1;\nlocal z_crc_t FAR crc_table[TBLS][256];\nlocal void make_crc_table OF((void));\n#ifdef MAKECRCH\n   local void write_table OF((FILE *, const z_crc_t FAR *));\n#endif /* MAKECRCH */\n/*\n  Generate tables for a byte-wise 32-bit CRC calculation on the polynomial:\n  x^32+x^26+x^23+x^22+x^16+x^12+x^11+x^10+x^8+x^7+x^5+x^4+x^2+x+1.\n\n  Polynomials over GF(2) are represented in binary, one bit per coefficient,\n  with the lowest powers in the most significant bit.  Then adding polynomials\n  is just exclusive-or, and multiplying a polynomial by x is a right shift by\n  one.  If we call the above polynomial p, and represent a byte as the\n  polynomial q, also with the lowest power in the most significant bit (so the\n  byte 0xb1 is the polynomial x^7+x^3+x+1), then the CRC is (q*x^32) mod p,\n  where a mod b means the remainder after dividing a by b.\n\n  This calculation is done using the shift-register method of multiplying and\n  taking the remainder.  The register is initialized to zero, and for each\n  incoming bit, x^32 is added mod p to the register if the bit is a one (where\n  x^32 mod p is p+x^32 = x^26+...+1), and the register is multiplied mod p by\n  x (which is shifting right by one and adding x^32 mod p if the bit shifted\n  out is a one).  We start with the highest power (least significant bit) of\n  q and repeat for all eight bits of q.\n\n  The first table is simply the CRC of all possible eight bit values.  This is\n  all the information needed to generate CRCs on data a byte at a time for all\n  combinations of CRC register values and incoming bytes.  The remaining tables\n  allow for word-at-a-time CRC calculation for both big-endian and little-\n  endian machines, where a word is four bytes.\n*/\nlocal void make_crc_table()\n{\n    z_crc_t c;\n    int n, k;\n    z_crc_t poly;                       /* polynomial exclusive-or pattern */\n    /* terms of polynomial defining this crc (except x^32): */\n    static volatile int first = 1;      /* flag to limit concurrent making */\n    static const unsigned char p[] = {0,1,2,4,5,7,8,10,11,12,16,22,23,26};\n\n    /* See if another task is already doing this (not thread-safe, but better\n       than nothing -- significantly reduces duration of vulnerability in\n       case the advice about DYNAMIC_CRC_TABLE is ignored) */\n    if (first) {\n        first = 0;\n\n        /* make exclusive-or pattern from polynomial (0xedb88320UL) */\n        poly = 0;\n        for (n = 0; n < (int)(sizeof(p)/sizeof(unsigned char)); n++)\n            poly |= (z_crc_t)1 << (31 - p[n]);\n\n        /* generate a crc for every 8-bit value */\n        for (n = 0; n < 256; n++) {\n            c = (z_crc_t)n;\n            for (k = 0; k < 8; k++)\n                c = c & 1 ? poly ^ (c >> 1) : c >> 1;\n            crc_table[0][n] = c;\n        }\n\n#ifdef BYFOUR\n        /* generate crc for each value followed by one, two, and three zeros,\n           and then the byte reversal of those as well as the first table */\n        for (n = 0; n < 256; n++) {\n            c = crc_table[0][n];\n            crc_table[4][n] = ZSWAP32(c);\n            for (k = 1; k < 4; k++) {\n                c = crc_table[0][c & 0xff] ^ (c >> 8);\n                crc_table[k][n] = c;\n                crc_table[k + 4][n] = ZSWAP32(c);\n            }\n        }\n#endif /* BYFOUR */\n\n        crc_table_empty = 0;\n    }\n    else {      /* not first */\n        /* wait for the other guy to finish (not efficient, but rare) */\n        while (crc_table_empty)\n            ;\n    }\n\n#ifdef MAKECRCH\n    /* write out CRC tables to crc32.h */\n    {\n        FILE *out;\n\n        out = fopen(\"crc32.h\", \"w\");\n        if (out == NULL) return;\n        fprintf(out, \"/* crc32.h -- tables for rapid CRC calculation\\n\");\n        fprintf(out, \" * Generated automatically by crc32.c\\n */\\n\\n\");\n        fprintf(out, \"local const z_crc_t FAR \");\n        fprintf(out, \"crc_table[TBLS][256] =\\n{\\n  {\\n\");\n        write_table(out, crc_table[0]);\n#  ifdef BYFOUR\n        fprintf(out, \"#ifdef BYFOUR\\n\");\n        for (k = 1; k < 8; k++) {\n            fprintf(out, \"  },\\n  {\\n\");\n            write_table(out, crc_table[k]);\n        }\n        fprintf(out, \"#endif\\n\");\n#  endif /* BYFOUR */\n        fprintf(out, \"  }\\n};\\n\");\n        fclose(out);\n    }\n#endif /* MAKECRCH */\n}\n\n#ifdef MAKECRCH\nlocal void write_table(out, table)\n    FILE *out;\n    const z_crc_t FAR *table;\n{\n    int n;\n\n    for (n = 0; n < 256; n++)\n        fprintf(out, \"%s0x%08lxUL%s\", n % 5 ? \"\" : \"    \",\n                (unsigned long)(table[n]),\n                n == 255 ? \"\\n\" : (n % 5 == 4 ? \",\\n\" : \", \"));\n}\n#endif /* MAKECRCH */\n\n#else /* !DYNAMIC_CRC_TABLE */\n/* ========================================================================\n * Tables of CRC-32s of all single-byte values, made by make_crc_table().\n */\n#include \"crc32.h\"\n#endif /* DYNAMIC_CRC_TABLE */\n\n/* =========================================================================\n * This function can be used by asm versions of crc32()\n */\nconst z_crc_t FAR * ZEXPORT get_crc_table()\n{\n#ifdef DYNAMIC_CRC_TABLE\n    if (crc_table_empty)\n        make_crc_table();\n#endif /* DYNAMIC_CRC_TABLE */\n    return (const z_crc_t FAR *)crc_table;\n}\n\n/* ========================================================================= */\n#define DO1 crc = crc_table[0][((int)crc ^ (*buf++)) & 0xff] ^ (crc >> 8)\n#define DO8 DO1; DO1; DO1; DO1; DO1; DO1; DO1; DO1\n\n/* ========================================================================= */\nunsigned long ZEXPORT crc32(crc, buf, len)\n    unsigned long crc;\n    const unsigned char FAR *buf;\n    uInt len;\n{\n    if (buf == Z_NULL) return 0UL;\n\n#ifdef DYNAMIC_CRC_TABLE\n    if (crc_table_empty)\n        make_crc_table();\n#endif /* DYNAMIC_CRC_TABLE */\n\n#ifdef BYFOUR\n    if (sizeof(void *) == sizeof(ptrdiff_t)) {\n        z_crc_t endian;\n\n        endian = 1;\n        if (*((unsigned char *)(&endian)))\n            return crc32_little(crc, buf, len);\n        else\n            return crc32_big(crc, buf, len);\n    }\n#endif /* BYFOUR */\n    crc = crc ^ 0xffffffffUL;\n    while (len >= 8) {\n        DO8;\n        len -= 8;\n    }\n    if (len) do {\n        DO1;\n    } while (--len);\n    return crc ^ 0xffffffffUL;\n}\n\n#ifdef BYFOUR\n\n/* ========================================================================= */\n#define DOLIT4 c ^= *buf4++; \\\n        c = crc_table[3][c & 0xff] ^ crc_table[2][(c >> 8) & 0xff] ^ \\\n            crc_table[1][(c >> 16) & 0xff] ^ crc_table[0][c >> 24]\n#define DOLIT32 DOLIT4; DOLIT4; DOLIT4; DOLIT4; DOLIT4; DOLIT4; DOLIT4; DOLIT4\n\n/* ========================================================================= */\nlocal unsigned long crc32_little(crc, buf, len)\n    unsigned long crc;\n    const unsigned char FAR *buf;\n    unsigned len;\n{\n    register z_crc_t c;\n    register const z_crc_t FAR *buf4;\n\n    c = (z_crc_t)crc;\n    c = ~c;\n    while (len && ((ptrdiff_t)buf & 3)) {\n        c = crc_table[0][(c ^ *buf++) & 0xff] ^ (c >> 8);\n        len--;\n    }\n\n    buf4 = (const z_crc_t FAR *)(const void FAR *)buf;\n    while (len >= 32) {\n        DOLIT32;\n        len -= 32;\n    }\n    while (len >= 4) {\n        DOLIT4;\n        len -= 4;\n    }\n    buf = (const unsigned char FAR *)buf4;\n\n    if (len) do {\n        c = crc_table[0][(c ^ *buf++) & 0xff] ^ (c >> 8);\n    } while (--len);\n    c = ~c;\n    return (unsigned long)c;\n}\n\n/* ========================================================================= */\n#define DOBIG4 c ^= *++buf4; \\\n        c = crc_table[4][c & 0xff] ^ crc_table[5][(c >> 8) & 0xff] ^ \\\n            crc_table[6][(c >> 16) & 0xff] ^ crc_table[7][c >> 24]\n#define DOBIG32 DOBIG4; DOBIG4; DOBIG4; DOBIG4; DOBIG4; DOBIG4; DOBIG4; DOBIG4\n\n/* ========================================================================= */\nlocal unsigned long crc32_big(crc, buf, len)\n    unsigned long crc;\n    const unsigned char FAR *buf;\n    unsigned len;\n{\n    register z_crc_t c;\n    register const z_crc_t FAR *buf4;\n\n    c = ZSWAP32((z_crc_t)crc);\n    c = ~c;\n    while (len && ((ptrdiff_t)buf & 3)) {\n        c = crc_table[4][(c >> 24) ^ *buf++] ^ (c << 8);\n        len--;\n    }\n\n    buf4 = (const z_crc_t FAR *)(const void FAR *)buf;\n    buf4--;\n    while (len >= 32) {\n        DOBIG32;\n        len -= 32;\n    }\n    while (len >= 4) {\n        DOBIG4;\n        len -= 4;\n    }\n    buf4++;\n    buf = (const unsigned char FAR *)buf4;\n\n    if (len) do {\n        c = crc_table[4][(c >> 24) ^ *buf++] ^ (c << 8);\n    } while (--len);\n    c = ~c;\n    return (unsigned long)(ZSWAP32(c));\n}\n\n#endif /* BYFOUR */\n\n#define GF2_DIM 32      /* dimension of GF(2) vectors (length of CRC) */\n\n/* ========================================================================= */\nlocal unsigned long gf2_matrix_times(mat, vec)\n    unsigned long *mat;\n    unsigned long vec;\n{\n    unsigned long sum;\n\n    sum = 0;\n    while (vec) {\n        if (vec & 1)\n            sum ^= *mat;\n        vec >>= 1;\n        mat++;\n    }\n    return sum;\n}\n\n/* ========================================================================= */\nlocal void gf2_matrix_square(square, mat)\n    unsigned long *square;\n    unsigned long *mat;\n{\n    int n;\n\n    for (n = 0; n < GF2_DIM; n++)\n        square[n] = gf2_matrix_times(mat, mat[n]);\n}\n\n/* ========================================================================= */\nlocal uLong crc32_combine_(crc1, crc2, len2)\n    uLong crc1;\n    uLong crc2;\n    z_off64_t len2;\n{\n    int n;\n    unsigned long row;\n    unsigned long even[GF2_DIM];    /* even-power-of-two zeros operator */\n    unsigned long odd[GF2_DIM];     /* odd-power-of-two zeros operator */\n\n    /* degenerate case (also disallow negative lengths) */\n    if (len2 <= 0)\n        return crc1;\n\n    /* put operator for one zero bit in odd */\n    odd[0] = 0xedb88320UL;          /* CRC-32 polynomial */\n    row = 1;\n    for (n = 1; n < GF2_DIM; n++) {\n        odd[n] = row;\n        row <<= 1;\n    }\n\n    /* put operator for two zero bits in even */\n    gf2_matrix_square(even, odd);\n\n    /* put operator for four zero bits in odd */\n    gf2_matrix_square(odd, even);\n\n    /* apply len2 zeros to crc1 (first square will put the operator for one\n       zero byte, eight zero bits, in even) */\n    do {\n        /* apply zeros operator for this bit of len2 */\n        gf2_matrix_square(even, odd);\n        if (len2 & 1)\n            crc1 = gf2_matrix_times(even, crc1);\n        len2 >>= 1;\n\n        /* if no more bits set, then done */\n        if (len2 == 0)\n            break;\n\n        /* another iteration of the loop with odd and even swapped */\n        gf2_matrix_square(odd, even);\n        if (len2 & 1)\n            crc1 = gf2_matrix_times(odd, crc1);\n        len2 >>= 1;\n\n        /* if no more bits set, then done */\n    } while (len2 != 0);\n\n    /* return combined crc */\n    crc1 ^= crc2;\n    return crc1;\n}\n\n/* ========================================================================= */\nuLong ZEXPORT crc32_combine(crc1, crc2, len2)\n    uLong crc1;\n    uLong crc2;\n    z_off_t len2;\n{\n    return crc32_combine_(crc1, crc2, len2);\n}\n\nuLong ZEXPORT crc32_combine64(crc1, crc2, len2)\n    uLong crc1;\n    uLong crc2;\n    z_off64_t len2;\n{\n    return crc32_combine_(crc1, crc2, len2);\n}\n"
  },
  {
    "path": "external/zlib/crc32.h",
    "content": "/* crc32.h -- tables for rapid CRC calculation\n * Generated automatically by crc32.c\n */\n\nlocal const z_crc_t FAR crc_table[TBLS][256] =\n{\n  {\n    0x00000000UL, 0x77073096UL, 0xee0e612cUL, 0x990951baUL, 0x076dc419UL,\n    0x706af48fUL, 0xe963a535UL, 0x9e6495a3UL, 0x0edb8832UL, 0x79dcb8a4UL,\n    0xe0d5e91eUL, 0x97d2d988UL, 0x09b64c2bUL, 0x7eb17cbdUL, 0xe7b82d07UL,\n    0x90bf1d91UL, 0x1db71064UL, 0x6ab020f2UL, 0xf3b97148UL, 0x84be41deUL,\n    0x1adad47dUL, 0x6ddde4ebUL, 0xf4d4b551UL, 0x83d385c7UL, 0x136c9856UL,\n    0x646ba8c0UL, 0xfd62f97aUL, 0x8a65c9ecUL, 0x14015c4fUL, 0x63066cd9UL,\n    0xfa0f3d63UL, 0x8d080df5UL, 0x3b6e20c8UL, 0x4c69105eUL, 0xd56041e4UL,\n    0xa2677172UL, 0x3c03e4d1UL, 0x4b04d447UL, 0xd20d85fdUL, 0xa50ab56bUL,\n    0x35b5a8faUL, 0x42b2986cUL, 0xdbbbc9d6UL, 0xacbcf940UL, 0x32d86ce3UL,\n    0x45df5c75UL, 0xdcd60dcfUL, 0xabd13d59UL, 0x26d930acUL, 0x51de003aUL,\n    0xc8d75180UL, 0xbfd06116UL, 0x21b4f4b5UL, 0x56b3c423UL, 0xcfba9599UL,\n    0xb8bda50fUL, 0x2802b89eUL, 0x5f058808UL, 0xc60cd9b2UL, 0xb10be924UL,\n    0x2f6f7c87UL, 0x58684c11UL, 0xc1611dabUL, 0xb6662d3dUL, 0x76dc4190UL,\n    0x01db7106UL, 0x98d220bcUL, 0xefd5102aUL, 0x71b18589UL, 0x06b6b51fUL,\n    0x9fbfe4a5UL, 0xe8b8d433UL, 0x7807c9a2UL, 0x0f00f934UL, 0x9609a88eUL,\n    0xe10e9818UL, 0x7f6a0dbbUL, 0x086d3d2dUL, 0x91646c97UL, 0xe6635c01UL,\n    0x6b6b51f4UL, 0x1c6c6162UL, 0x856530d8UL, 0xf262004eUL, 0x6c0695edUL,\n    0x1b01a57bUL, 0x8208f4c1UL, 0xf50fc457UL, 0x65b0d9c6UL, 0x12b7e950UL,\n    0x8bbeb8eaUL, 0xfcb9887cUL, 0x62dd1ddfUL, 0x15da2d49UL, 0x8cd37cf3UL,\n    0xfbd44c65UL, 0x4db26158UL, 0x3ab551ceUL, 0xa3bc0074UL, 0xd4bb30e2UL,\n    0x4adfa541UL, 0x3dd895d7UL, 0xa4d1c46dUL, 0xd3d6f4fbUL, 0x4369e96aUL,\n    0x346ed9fcUL, 0xad678846UL, 0xda60b8d0UL, 0x44042d73UL, 0x33031de5UL,\n    0xaa0a4c5fUL, 0xdd0d7cc9UL, 0x5005713cUL, 0x270241aaUL, 0xbe0b1010UL,\n    0xc90c2086UL, 0x5768b525UL, 0x206f85b3UL, 0xb966d409UL, 0xce61e49fUL,\n    0x5edef90eUL, 0x29d9c998UL, 0xb0d09822UL, 0xc7d7a8b4UL, 0x59b33d17UL,\n    0x2eb40d81UL, 0xb7bd5c3bUL, 0xc0ba6cadUL, 0xedb88320UL, 0x9abfb3b6UL,\n    0x03b6e20cUL, 0x74b1d29aUL, 0xead54739UL, 0x9dd277afUL, 0x04db2615UL,\n    0x73dc1683UL, 0xe3630b12UL, 0x94643b84UL, 0x0d6d6a3eUL, 0x7a6a5aa8UL,\n    0xe40ecf0bUL, 0x9309ff9dUL, 0x0a00ae27UL, 0x7d079eb1UL, 0xf00f9344UL,\n    0x8708a3d2UL, 0x1e01f268UL, 0x6906c2feUL, 0xf762575dUL, 0x806567cbUL,\n    0x196c3671UL, 0x6e6b06e7UL, 0xfed41b76UL, 0x89d32be0UL, 0x10da7a5aUL,\n    0x67dd4accUL, 0xf9b9df6fUL, 0x8ebeeff9UL, 0x17b7be43UL, 0x60b08ed5UL,\n    0xd6d6a3e8UL, 0xa1d1937eUL, 0x38d8c2c4UL, 0x4fdff252UL, 0xd1bb67f1UL,\n    0xa6bc5767UL, 0x3fb506ddUL, 0x48b2364bUL, 0xd80d2bdaUL, 0xaf0a1b4cUL,\n    0x36034af6UL, 0x41047a60UL, 0xdf60efc3UL, 0xa867df55UL, 0x316e8eefUL,\n    0x4669be79UL, 0xcb61b38cUL, 0xbc66831aUL, 0x256fd2a0UL, 0x5268e236UL,\n    0xcc0c7795UL, 0xbb0b4703UL, 0x220216b9UL, 0x5505262fUL, 0xc5ba3bbeUL,\n    0xb2bd0b28UL, 0x2bb45a92UL, 0x5cb36a04UL, 0xc2d7ffa7UL, 0xb5d0cf31UL,\n    0x2cd99e8bUL, 0x5bdeae1dUL, 0x9b64c2b0UL, 0xec63f226UL, 0x756aa39cUL,\n    0x026d930aUL, 0x9c0906a9UL, 0xeb0e363fUL, 0x72076785UL, 0x05005713UL,\n    0x95bf4a82UL, 0xe2b87a14UL, 0x7bb12baeUL, 0x0cb61b38UL, 0x92d28e9bUL,\n    0xe5d5be0dUL, 0x7cdcefb7UL, 0x0bdbdf21UL, 0x86d3d2d4UL, 0xf1d4e242UL,\n    0x68ddb3f8UL, 0x1fda836eUL, 0x81be16cdUL, 0xf6b9265bUL, 0x6fb077e1UL,\n    0x18b74777UL, 0x88085ae6UL, 0xff0f6a70UL, 0x66063bcaUL, 0x11010b5cUL,\n    0x8f659effUL, 0xf862ae69UL, 0x616bffd3UL, 0x166ccf45UL, 0xa00ae278UL,\n    0xd70dd2eeUL, 0x4e048354UL, 0x3903b3c2UL, 0xa7672661UL, 0xd06016f7UL,\n    0x4969474dUL, 0x3e6e77dbUL, 0xaed16a4aUL, 0xd9d65adcUL, 0x40df0b66UL,\n    0x37d83bf0UL, 0xa9bcae53UL, 0xdebb9ec5UL, 0x47b2cf7fUL, 0x30b5ffe9UL,\n    0xbdbdf21cUL, 0xcabac28aUL, 0x53b39330UL, 0x24b4a3a6UL, 0xbad03605UL,\n    0xcdd70693UL, 0x54de5729UL, 0x23d967bfUL, 0xb3667a2eUL, 0xc4614ab8UL,\n    0x5d681b02UL, 0x2a6f2b94UL, 0xb40bbe37UL, 0xc30c8ea1UL, 0x5a05df1bUL,\n    0x2d02ef8dUL\n#ifdef BYFOUR\n  },\n  {\n    0x00000000UL, 0x191b3141UL, 0x32366282UL, 0x2b2d53c3UL, 0x646cc504UL,\n    0x7d77f445UL, 0x565aa786UL, 0x4f4196c7UL, 0xc8d98a08UL, 0xd1c2bb49UL,\n    0xfaefe88aUL, 0xe3f4d9cbUL, 0xacb54f0cUL, 0xb5ae7e4dUL, 0x9e832d8eUL,\n    0x87981ccfUL, 0x4ac21251UL, 0x53d92310UL, 0x78f470d3UL, 0x61ef4192UL,\n    0x2eaed755UL, 0x37b5e614UL, 0x1c98b5d7UL, 0x05838496UL, 0x821b9859UL,\n    0x9b00a918UL, 0xb02dfadbUL, 0xa936cb9aUL, 0xe6775d5dUL, 0xff6c6c1cUL,\n    0xd4413fdfUL, 0xcd5a0e9eUL, 0x958424a2UL, 0x8c9f15e3UL, 0xa7b24620UL,\n    0xbea97761UL, 0xf1e8e1a6UL, 0xe8f3d0e7UL, 0xc3de8324UL, 0xdac5b265UL,\n    0x5d5daeaaUL, 0x44469febUL, 0x6f6bcc28UL, 0x7670fd69UL, 0x39316baeUL,\n    0x202a5aefUL, 0x0b07092cUL, 0x121c386dUL, 0xdf4636f3UL, 0xc65d07b2UL,\n    0xed705471UL, 0xf46b6530UL, 0xbb2af3f7UL, 0xa231c2b6UL, 0x891c9175UL,\n    0x9007a034UL, 0x179fbcfbUL, 0x0e848dbaUL, 0x25a9de79UL, 0x3cb2ef38UL,\n    0x73f379ffUL, 0x6ae848beUL, 0x41c51b7dUL, 0x58de2a3cUL, 0xf0794f05UL,\n    0xe9627e44UL, 0xc24f2d87UL, 0xdb541cc6UL, 0x94158a01UL, 0x8d0ebb40UL,\n    0xa623e883UL, 0xbf38d9c2UL, 0x38a0c50dUL, 0x21bbf44cUL, 0x0a96a78fUL,\n    0x138d96ceUL, 0x5ccc0009UL, 0x45d73148UL, 0x6efa628bUL, 0x77e153caUL,\n    0xbabb5d54UL, 0xa3a06c15UL, 0x888d3fd6UL, 0x91960e97UL, 0xded79850UL,\n    0xc7cca911UL, 0xece1fad2UL, 0xf5facb93UL, 0x7262d75cUL, 0x6b79e61dUL,\n    0x4054b5deUL, 0x594f849fUL, 0x160e1258UL, 0x0f152319UL, 0x243870daUL,\n    0x3d23419bUL, 0x65fd6ba7UL, 0x7ce65ae6UL, 0x57cb0925UL, 0x4ed03864UL,\n    0x0191aea3UL, 0x188a9fe2UL, 0x33a7cc21UL, 0x2abcfd60UL, 0xad24e1afUL,\n    0xb43fd0eeUL, 0x9f12832dUL, 0x8609b26cUL, 0xc94824abUL, 0xd05315eaUL,\n    0xfb7e4629UL, 0xe2657768UL, 0x2f3f79f6UL, 0x362448b7UL, 0x1d091b74UL,\n    0x04122a35UL, 0x4b53bcf2UL, 0x52488db3UL, 0x7965de70UL, 0x607eef31UL,\n    0xe7e6f3feUL, 0xfefdc2bfUL, 0xd5d0917cUL, 0xcccba03dUL, 0x838a36faUL,\n    0x9a9107bbUL, 0xb1bc5478UL, 0xa8a76539UL, 0x3b83984bUL, 0x2298a90aUL,\n    0x09b5fac9UL, 0x10aecb88UL, 0x5fef5d4fUL, 0x46f46c0eUL, 0x6dd93fcdUL,\n    0x74c20e8cUL, 0xf35a1243UL, 0xea412302UL, 0xc16c70c1UL, 0xd8774180UL,\n    0x9736d747UL, 0x8e2de606UL, 0xa500b5c5UL, 0xbc1b8484UL, 0x71418a1aUL,\n    0x685abb5bUL, 0x4377e898UL, 0x5a6cd9d9UL, 0x152d4f1eUL, 0x0c367e5fUL,\n    0x271b2d9cUL, 0x3e001cddUL, 0xb9980012UL, 0xa0833153UL, 0x8bae6290UL,\n    0x92b553d1UL, 0xddf4c516UL, 0xc4eff457UL, 0xefc2a794UL, 0xf6d996d5UL,\n    0xae07bce9UL, 0xb71c8da8UL, 0x9c31de6bUL, 0x852aef2aUL, 0xca6b79edUL,\n    0xd37048acUL, 0xf85d1b6fUL, 0xe1462a2eUL, 0x66de36e1UL, 0x7fc507a0UL,\n    0x54e85463UL, 0x4df36522UL, 0x02b2f3e5UL, 0x1ba9c2a4UL, 0x30849167UL,\n    0x299fa026UL, 0xe4c5aeb8UL, 0xfdde9ff9UL, 0xd6f3cc3aUL, 0xcfe8fd7bUL,\n    0x80a96bbcUL, 0x99b25afdUL, 0xb29f093eUL, 0xab84387fUL, 0x2c1c24b0UL,\n    0x350715f1UL, 0x1e2a4632UL, 0x07317773UL, 0x4870e1b4UL, 0x516bd0f5UL,\n    0x7a468336UL, 0x635db277UL, 0xcbfad74eUL, 0xd2e1e60fUL, 0xf9ccb5ccUL,\n    0xe0d7848dUL, 0xaf96124aUL, 0xb68d230bUL, 0x9da070c8UL, 0x84bb4189UL,\n    0x03235d46UL, 0x1a386c07UL, 0x31153fc4UL, 0x280e0e85UL, 0x674f9842UL,\n    0x7e54a903UL, 0x5579fac0UL, 0x4c62cb81UL, 0x8138c51fUL, 0x9823f45eUL,\n    0xb30ea79dUL, 0xaa1596dcUL, 0xe554001bUL, 0xfc4f315aUL, 0xd7626299UL,\n    0xce7953d8UL, 0x49e14f17UL, 0x50fa7e56UL, 0x7bd72d95UL, 0x62cc1cd4UL,\n    0x2d8d8a13UL, 0x3496bb52UL, 0x1fbbe891UL, 0x06a0d9d0UL, 0x5e7ef3ecUL,\n    0x4765c2adUL, 0x6c48916eUL, 0x7553a02fUL, 0x3a1236e8UL, 0x230907a9UL,\n    0x0824546aUL, 0x113f652bUL, 0x96a779e4UL, 0x8fbc48a5UL, 0xa4911b66UL,\n    0xbd8a2a27UL, 0xf2cbbce0UL, 0xebd08da1UL, 0xc0fdde62UL, 0xd9e6ef23UL,\n    0x14bce1bdUL, 0x0da7d0fcUL, 0x268a833fUL, 0x3f91b27eUL, 0x70d024b9UL,\n    0x69cb15f8UL, 0x42e6463bUL, 0x5bfd777aUL, 0xdc656bb5UL, 0xc57e5af4UL,\n    0xee530937UL, 0xf7483876UL, 0xb809aeb1UL, 0xa1129ff0UL, 0x8a3fcc33UL,\n    0x9324fd72UL\n  },\n  {\n    0x00000000UL, 0x01c26a37UL, 0x0384d46eUL, 0x0246be59UL, 0x0709a8dcUL,\n    0x06cbc2ebUL, 0x048d7cb2UL, 0x054f1685UL, 0x0e1351b8UL, 0x0fd13b8fUL,\n    0x0d9785d6UL, 0x0c55efe1UL, 0x091af964UL, 0x08d89353UL, 0x0a9e2d0aUL,\n    0x0b5c473dUL, 0x1c26a370UL, 0x1de4c947UL, 0x1fa2771eUL, 0x1e601d29UL,\n    0x1b2f0bacUL, 0x1aed619bUL, 0x18abdfc2UL, 0x1969b5f5UL, 0x1235f2c8UL,\n    0x13f798ffUL, 0x11b126a6UL, 0x10734c91UL, 0x153c5a14UL, 0x14fe3023UL,\n    0x16b88e7aUL, 0x177ae44dUL, 0x384d46e0UL, 0x398f2cd7UL, 0x3bc9928eUL,\n    0x3a0bf8b9UL, 0x3f44ee3cUL, 0x3e86840bUL, 0x3cc03a52UL, 0x3d025065UL,\n    0x365e1758UL, 0x379c7d6fUL, 0x35dac336UL, 0x3418a901UL, 0x3157bf84UL,\n    0x3095d5b3UL, 0x32d36beaUL, 0x331101ddUL, 0x246be590UL, 0x25a98fa7UL,\n    0x27ef31feUL, 0x262d5bc9UL, 0x23624d4cUL, 0x22a0277bUL, 0x20e69922UL,\n    0x2124f315UL, 0x2a78b428UL, 0x2bbade1fUL, 0x29fc6046UL, 0x283e0a71UL,\n    0x2d711cf4UL, 0x2cb376c3UL, 0x2ef5c89aUL, 0x2f37a2adUL, 0x709a8dc0UL,\n    0x7158e7f7UL, 0x731e59aeUL, 0x72dc3399UL, 0x7793251cUL, 0x76514f2bUL,\n    0x7417f172UL, 0x75d59b45UL, 0x7e89dc78UL, 0x7f4bb64fUL, 0x7d0d0816UL,\n    0x7ccf6221UL, 0x798074a4UL, 0x78421e93UL, 0x7a04a0caUL, 0x7bc6cafdUL,\n    0x6cbc2eb0UL, 0x6d7e4487UL, 0x6f38fadeUL, 0x6efa90e9UL, 0x6bb5866cUL,\n    0x6a77ec5bUL, 0x68315202UL, 0x69f33835UL, 0x62af7f08UL, 0x636d153fUL,\n    0x612bab66UL, 0x60e9c151UL, 0x65a6d7d4UL, 0x6464bde3UL, 0x662203baUL,\n    0x67e0698dUL, 0x48d7cb20UL, 0x4915a117UL, 0x4b531f4eUL, 0x4a917579UL,\n    0x4fde63fcUL, 0x4e1c09cbUL, 0x4c5ab792UL, 0x4d98dda5UL, 0x46c49a98UL,\n    0x4706f0afUL, 0x45404ef6UL, 0x448224c1UL, 0x41cd3244UL, 0x400f5873UL,\n    0x4249e62aUL, 0x438b8c1dUL, 0x54f16850UL, 0x55330267UL, 0x5775bc3eUL,\n    0x56b7d609UL, 0x53f8c08cUL, 0x523aaabbUL, 0x507c14e2UL, 0x51be7ed5UL,\n    0x5ae239e8UL, 0x5b2053dfUL, 0x5966ed86UL, 0x58a487b1UL, 0x5deb9134UL,\n    0x5c29fb03UL, 0x5e6f455aUL, 0x5fad2f6dUL, 0xe1351b80UL, 0xe0f771b7UL,\n    0xe2b1cfeeUL, 0xe373a5d9UL, 0xe63cb35cUL, 0xe7fed96bUL, 0xe5b86732UL,\n    0xe47a0d05UL, 0xef264a38UL, 0xeee4200fUL, 0xeca29e56UL, 0xed60f461UL,\n    0xe82fe2e4UL, 0xe9ed88d3UL, 0xebab368aUL, 0xea695cbdUL, 0xfd13b8f0UL,\n    0xfcd1d2c7UL, 0xfe976c9eUL, 0xff5506a9UL, 0xfa1a102cUL, 0xfbd87a1bUL,\n    0xf99ec442UL, 0xf85cae75UL, 0xf300e948UL, 0xf2c2837fUL, 0xf0843d26UL,\n    0xf1465711UL, 0xf4094194UL, 0xf5cb2ba3UL, 0xf78d95faUL, 0xf64fffcdUL,\n    0xd9785d60UL, 0xd8ba3757UL, 0xdafc890eUL, 0xdb3ee339UL, 0xde71f5bcUL,\n    0xdfb39f8bUL, 0xddf521d2UL, 0xdc374be5UL, 0xd76b0cd8UL, 0xd6a966efUL,\n    0xd4efd8b6UL, 0xd52db281UL, 0xd062a404UL, 0xd1a0ce33UL, 0xd3e6706aUL,\n    0xd2241a5dUL, 0xc55efe10UL, 0xc49c9427UL, 0xc6da2a7eUL, 0xc7184049UL,\n    0xc25756ccUL, 0xc3953cfbUL, 0xc1d382a2UL, 0xc011e895UL, 0xcb4dafa8UL,\n    0xca8fc59fUL, 0xc8c97bc6UL, 0xc90b11f1UL, 0xcc440774UL, 0xcd866d43UL,\n    0xcfc0d31aUL, 0xce02b92dUL, 0x91af9640UL, 0x906dfc77UL, 0x922b422eUL,\n    0x93e92819UL, 0x96a63e9cUL, 0x976454abUL, 0x9522eaf2UL, 0x94e080c5UL,\n    0x9fbcc7f8UL, 0x9e7eadcfUL, 0x9c381396UL, 0x9dfa79a1UL, 0x98b56f24UL,\n    0x99770513UL, 0x9b31bb4aUL, 0x9af3d17dUL, 0x8d893530UL, 0x8c4b5f07UL,\n    0x8e0de15eUL, 0x8fcf8b69UL, 0x8a809decUL, 0x8b42f7dbUL, 0x89044982UL,\n    0x88c623b5UL, 0x839a6488UL, 0x82580ebfUL, 0x801eb0e6UL, 0x81dcdad1UL,\n    0x8493cc54UL, 0x8551a663UL, 0x8717183aUL, 0x86d5720dUL, 0xa9e2d0a0UL,\n    0xa820ba97UL, 0xaa6604ceUL, 0xaba46ef9UL, 0xaeeb787cUL, 0xaf29124bUL,\n    0xad6fac12UL, 0xacadc625UL, 0xa7f18118UL, 0xa633eb2fUL, 0xa4755576UL,\n    0xa5b73f41UL, 0xa0f829c4UL, 0xa13a43f3UL, 0xa37cfdaaUL, 0xa2be979dUL,\n    0xb5c473d0UL, 0xb40619e7UL, 0xb640a7beUL, 0xb782cd89UL, 0xb2cddb0cUL,\n    0xb30fb13bUL, 0xb1490f62UL, 0xb08b6555UL, 0xbbd72268UL, 0xba15485fUL,\n    0xb853f606UL, 0xb9919c31UL, 0xbcde8ab4UL, 0xbd1ce083UL, 0xbf5a5edaUL,\n    0xbe9834edUL\n  },\n  {\n    0x00000000UL, 0xb8bc6765UL, 0xaa09c88bUL, 0x12b5afeeUL, 0x8f629757UL,\n    0x37def032UL, 0x256b5fdcUL, 0x9dd738b9UL, 0xc5b428efUL, 0x7d084f8aUL,\n    0x6fbde064UL, 0xd7018701UL, 0x4ad6bfb8UL, 0xf26ad8ddUL, 0xe0df7733UL,\n    0x58631056UL, 0x5019579fUL, 0xe8a530faUL, 0xfa109f14UL, 0x42acf871UL,\n    0xdf7bc0c8UL, 0x67c7a7adUL, 0x75720843UL, 0xcdce6f26UL, 0x95ad7f70UL,\n    0x2d111815UL, 0x3fa4b7fbUL, 0x8718d09eUL, 0x1acfe827UL, 0xa2738f42UL,\n    0xb0c620acUL, 0x087a47c9UL, 0xa032af3eUL, 0x188ec85bUL, 0x0a3b67b5UL,\n    0xb28700d0UL, 0x2f503869UL, 0x97ec5f0cUL, 0x8559f0e2UL, 0x3de59787UL,\n    0x658687d1UL, 0xdd3ae0b4UL, 0xcf8f4f5aUL, 0x7733283fUL, 0xeae41086UL,\n    0x525877e3UL, 0x40edd80dUL, 0xf851bf68UL, 0xf02bf8a1UL, 0x48979fc4UL,\n    0x5a22302aUL, 0xe29e574fUL, 0x7f496ff6UL, 0xc7f50893UL, 0xd540a77dUL,\n    0x6dfcc018UL, 0x359fd04eUL, 0x8d23b72bUL, 0x9f9618c5UL, 0x272a7fa0UL,\n    0xbafd4719UL, 0x0241207cUL, 0x10f48f92UL, 0xa848e8f7UL, 0x9b14583dUL,\n    0x23a83f58UL, 0x311d90b6UL, 0x89a1f7d3UL, 0x1476cf6aUL, 0xaccaa80fUL,\n    0xbe7f07e1UL, 0x06c36084UL, 0x5ea070d2UL, 0xe61c17b7UL, 0xf4a9b859UL,\n    0x4c15df3cUL, 0xd1c2e785UL, 0x697e80e0UL, 0x7bcb2f0eUL, 0xc377486bUL,\n    0xcb0d0fa2UL, 0x73b168c7UL, 0x6104c729UL, 0xd9b8a04cUL, 0x446f98f5UL,\n    0xfcd3ff90UL, 0xee66507eUL, 0x56da371bUL, 0x0eb9274dUL, 0xb6054028UL,\n    0xa4b0efc6UL, 0x1c0c88a3UL, 0x81dbb01aUL, 0x3967d77fUL, 0x2bd27891UL,\n    0x936e1ff4UL, 0x3b26f703UL, 0x839a9066UL, 0x912f3f88UL, 0x299358edUL,\n    0xb4446054UL, 0x0cf80731UL, 0x1e4da8dfUL, 0xa6f1cfbaUL, 0xfe92dfecUL,\n    0x462eb889UL, 0x549b1767UL, 0xec277002UL, 0x71f048bbUL, 0xc94c2fdeUL,\n    0xdbf98030UL, 0x6345e755UL, 0x6b3fa09cUL, 0xd383c7f9UL, 0xc1366817UL,\n    0x798a0f72UL, 0xe45d37cbUL, 0x5ce150aeUL, 0x4e54ff40UL, 0xf6e89825UL,\n    0xae8b8873UL, 0x1637ef16UL, 0x048240f8UL, 0xbc3e279dUL, 0x21e91f24UL,\n    0x99557841UL, 0x8be0d7afUL, 0x335cb0caUL, 0xed59b63bUL, 0x55e5d15eUL,\n    0x47507eb0UL, 0xffec19d5UL, 0x623b216cUL, 0xda874609UL, 0xc832e9e7UL,\n    0x708e8e82UL, 0x28ed9ed4UL, 0x9051f9b1UL, 0x82e4565fUL, 0x3a58313aUL,\n    0xa78f0983UL, 0x1f336ee6UL, 0x0d86c108UL, 0xb53aa66dUL, 0xbd40e1a4UL,\n    0x05fc86c1UL, 0x1749292fUL, 0xaff54e4aUL, 0x322276f3UL, 0x8a9e1196UL,\n    0x982bbe78UL, 0x2097d91dUL, 0x78f4c94bUL, 0xc048ae2eUL, 0xd2fd01c0UL,\n    0x6a4166a5UL, 0xf7965e1cUL, 0x4f2a3979UL, 0x5d9f9697UL, 0xe523f1f2UL,\n    0x4d6b1905UL, 0xf5d77e60UL, 0xe762d18eUL, 0x5fdeb6ebUL, 0xc2098e52UL,\n    0x7ab5e937UL, 0x680046d9UL, 0xd0bc21bcUL, 0x88df31eaUL, 0x3063568fUL,\n    0x22d6f961UL, 0x9a6a9e04UL, 0x07bda6bdUL, 0xbf01c1d8UL, 0xadb46e36UL,\n    0x15080953UL, 0x1d724e9aUL, 0xa5ce29ffUL, 0xb77b8611UL, 0x0fc7e174UL,\n    0x9210d9cdUL, 0x2aacbea8UL, 0x38191146UL, 0x80a57623UL, 0xd8c66675UL,\n    0x607a0110UL, 0x72cfaefeUL, 0xca73c99bUL, 0x57a4f122UL, 0xef189647UL,\n    0xfdad39a9UL, 0x45115eccUL, 0x764dee06UL, 0xcef18963UL, 0xdc44268dUL,\n    0x64f841e8UL, 0xf92f7951UL, 0x41931e34UL, 0x5326b1daUL, 0xeb9ad6bfUL,\n    0xb3f9c6e9UL, 0x0b45a18cUL, 0x19f00e62UL, 0xa14c6907UL, 0x3c9b51beUL,\n    0x842736dbUL, 0x96929935UL, 0x2e2efe50UL, 0x2654b999UL, 0x9ee8defcUL,\n    0x8c5d7112UL, 0x34e11677UL, 0xa9362eceUL, 0x118a49abUL, 0x033fe645UL,\n    0xbb838120UL, 0xe3e09176UL, 0x5b5cf613UL, 0x49e959fdUL, 0xf1553e98UL,\n    0x6c820621UL, 0xd43e6144UL, 0xc68bceaaUL, 0x7e37a9cfUL, 0xd67f4138UL,\n    0x6ec3265dUL, 0x7c7689b3UL, 0xc4caeed6UL, 0x591dd66fUL, 0xe1a1b10aUL,\n    0xf3141ee4UL, 0x4ba87981UL, 0x13cb69d7UL, 0xab770eb2UL, 0xb9c2a15cUL,\n    0x017ec639UL, 0x9ca9fe80UL, 0x241599e5UL, 0x36a0360bUL, 0x8e1c516eUL,\n    0x866616a7UL, 0x3eda71c2UL, 0x2c6fde2cUL, 0x94d3b949UL, 0x090481f0UL,\n    0xb1b8e695UL, 0xa30d497bUL, 0x1bb12e1eUL, 0x43d23e48UL, 0xfb6e592dUL,\n    0xe9dbf6c3UL, 0x516791a6UL, 0xccb0a91fUL, 0x740cce7aUL, 0x66b96194UL,\n    0xde0506f1UL\n  },\n  {\n    0x00000000UL, 0x96300777UL, 0x2c610eeeUL, 0xba510999UL, 0x19c46d07UL,\n    0x8ff46a70UL, 0x35a563e9UL, 0xa395649eUL, 0x3288db0eUL, 0xa4b8dc79UL,\n    0x1ee9d5e0UL, 0x88d9d297UL, 0x2b4cb609UL, 0xbd7cb17eUL, 0x072db8e7UL,\n    0x911dbf90UL, 0x6410b71dUL, 0xf220b06aUL, 0x4871b9f3UL, 0xde41be84UL,\n    0x7dd4da1aUL, 0xebe4dd6dUL, 0x51b5d4f4UL, 0xc785d383UL, 0x56986c13UL,\n    0xc0a86b64UL, 0x7af962fdUL, 0xecc9658aUL, 0x4f5c0114UL, 0xd96c0663UL,\n    0x633d0ffaUL, 0xf50d088dUL, 0xc8206e3bUL, 0x5e10694cUL, 0xe44160d5UL,\n    0x727167a2UL, 0xd1e4033cUL, 0x47d4044bUL, 0xfd850dd2UL, 0x6bb50aa5UL,\n    0xfaa8b535UL, 0x6c98b242UL, 0xd6c9bbdbUL, 0x40f9bcacUL, 0xe36cd832UL,\n    0x755cdf45UL, 0xcf0dd6dcUL, 0x593dd1abUL, 0xac30d926UL, 0x3a00de51UL,\n    0x8051d7c8UL, 0x1661d0bfUL, 0xb5f4b421UL, 0x23c4b356UL, 0x9995bacfUL,\n    0x0fa5bdb8UL, 0x9eb80228UL, 0x0888055fUL, 0xb2d90cc6UL, 0x24e90bb1UL,\n    0x877c6f2fUL, 0x114c6858UL, 0xab1d61c1UL, 0x3d2d66b6UL, 0x9041dc76UL,\n    0x0671db01UL, 0xbc20d298UL, 0x2a10d5efUL, 0x8985b171UL, 0x1fb5b606UL,\n    0xa5e4bf9fUL, 0x33d4b8e8UL, 0xa2c90778UL, 0x34f9000fUL, 0x8ea80996UL,\n    0x18980ee1UL, 0xbb0d6a7fUL, 0x2d3d6d08UL, 0x976c6491UL, 0x015c63e6UL,\n    0xf4516b6bUL, 0x62616c1cUL, 0xd8306585UL, 0x4e0062f2UL, 0xed95066cUL,\n    0x7ba5011bUL, 0xc1f40882UL, 0x57c40ff5UL, 0xc6d9b065UL, 0x50e9b712UL,\n    0xeab8be8bUL, 0x7c88b9fcUL, 0xdf1ddd62UL, 0x492dda15UL, 0xf37cd38cUL,\n    0x654cd4fbUL, 0x5861b24dUL, 0xce51b53aUL, 0x7400bca3UL, 0xe230bbd4UL,\n    0x41a5df4aUL, 0xd795d83dUL, 0x6dc4d1a4UL, 0xfbf4d6d3UL, 0x6ae96943UL,\n    0xfcd96e34UL, 0x468867adUL, 0xd0b860daUL, 0x732d0444UL, 0xe51d0333UL,\n    0x5f4c0aaaUL, 0xc97c0dddUL, 0x3c710550UL, 0xaa410227UL, 0x10100bbeUL,\n    0x86200cc9UL, 0x25b56857UL, 0xb3856f20UL, 0x09d466b9UL, 0x9fe461ceUL,\n    0x0ef9de5eUL, 0x98c9d929UL, 0x2298d0b0UL, 0xb4a8d7c7UL, 0x173db359UL,\n    0x810db42eUL, 0x3b5cbdb7UL, 0xad6cbac0UL, 0x2083b8edUL, 0xb6b3bf9aUL,\n    0x0ce2b603UL, 0x9ad2b174UL, 0x3947d5eaUL, 0xaf77d29dUL, 0x1526db04UL,\n    0x8316dc73UL, 0x120b63e3UL, 0x843b6494UL, 0x3e6a6d0dUL, 0xa85a6a7aUL,\n    0x0bcf0ee4UL, 0x9dff0993UL, 0x27ae000aUL, 0xb19e077dUL, 0x44930ff0UL,\n    0xd2a30887UL, 0x68f2011eUL, 0xfec20669UL, 0x5d5762f7UL, 0xcb676580UL,\n    0x71366c19UL, 0xe7066b6eUL, 0x761bd4feUL, 0xe02bd389UL, 0x5a7ada10UL,\n    0xcc4add67UL, 0x6fdfb9f9UL, 0xf9efbe8eUL, 0x43beb717UL, 0xd58eb060UL,\n    0xe8a3d6d6UL, 0x7e93d1a1UL, 0xc4c2d838UL, 0x52f2df4fUL, 0xf167bbd1UL,\n    0x6757bca6UL, 0xdd06b53fUL, 0x4b36b248UL, 0xda2b0dd8UL, 0x4c1b0aafUL,\n    0xf64a0336UL, 0x607a0441UL, 0xc3ef60dfUL, 0x55df67a8UL, 0xef8e6e31UL,\n    0x79be6946UL, 0x8cb361cbUL, 0x1a8366bcUL, 0xa0d26f25UL, 0x36e26852UL,\n    0x95770cccUL, 0x03470bbbUL, 0xb9160222UL, 0x2f260555UL, 0xbe3bbac5UL,\n    0x280bbdb2UL, 0x925ab42bUL, 0x046ab35cUL, 0xa7ffd7c2UL, 0x31cfd0b5UL,\n    0x8b9ed92cUL, 0x1daede5bUL, 0xb0c2649bUL, 0x26f263ecUL, 0x9ca36a75UL,\n    0x0a936d02UL, 0xa906099cUL, 0x3f360eebUL, 0x85670772UL, 0x13570005UL,\n    0x824abf95UL, 0x147ab8e2UL, 0xae2bb17bUL, 0x381bb60cUL, 0x9b8ed292UL,\n    0x0dbed5e5UL, 0xb7efdc7cUL, 0x21dfdb0bUL, 0xd4d2d386UL, 0x42e2d4f1UL,\n    0xf8b3dd68UL, 0x6e83da1fUL, 0xcd16be81UL, 0x5b26b9f6UL, 0xe177b06fUL,\n    0x7747b718UL, 0xe65a0888UL, 0x706a0fffUL, 0xca3b0666UL, 0x5c0b0111UL,\n    0xff9e658fUL, 0x69ae62f8UL, 0xd3ff6b61UL, 0x45cf6c16UL, 0x78e20aa0UL,\n    0xeed20dd7UL, 0x5483044eUL, 0xc2b30339UL, 0x612667a7UL, 0xf71660d0UL,\n    0x4d476949UL, 0xdb776e3eUL, 0x4a6ad1aeUL, 0xdc5ad6d9UL, 0x660bdf40UL,\n    0xf03bd837UL, 0x53aebca9UL, 0xc59ebbdeUL, 0x7fcfb247UL, 0xe9ffb530UL,\n    0x1cf2bdbdUL, 0x8ac2bacaUL, 0x3093b353UL, 0xa6a3b424UL, 0x0536d0baUL,\n    0x9306d7cdUL, 0x2957de54UL, 0xbf67d923UL, 0x2e7a66b3UL, 0xb84a61c4UL,\n    0x021b685dUL, 0x942b6f2aUL, 0x37be0bb4UL, 0xa18e0cc3UL, 0x1bdf055aUL,\n    0x8def022dUL\n  },\n  {\n    0x00000000UL, 0x41311b19UL, 0x82623632UL, 0xc3532d2bUL, 0x04c56c64UL,\n    0x45f4777dUL, 0x86a75a56UL, 0xc796414fUL, 0x088ad9c8UL, 0x49bbc2d1UL,\n    0x8ae8effaUL, 0xcbd9f4e3UL, 0x0c4fb5acUL, 0x4d7eaeb5UL, 0x8e2d839eUL,\n    0xcf1c9887UL, 0x5112c24aUL, 0x1023d953UL, 0xd370f478UL, 0x9241ef61UL,\n    0x55d7ae2eUL, 0x14e6b537UL, 0xd7b5981cUL, 0x96848305UL, 0x59981b82UL,\n    0x18a9009bUL, 0xdbfa2db0UL, 0x9acb36a9UL, 0x5d5d77e6UL, 0x1c6c6cffUL,\n    0xdf3f41d4UL, 0x9e0e5acdUL, 0xa2248495UL, 0xe3159f8cUL, 0x2046b2a7UL,\n    0x6177a9beUL, 0xa6e1e8f1UL, 0xe7d0f3e8UL, 0x2483dec3UL, 0x65b2c5daUL,\n    0xaaae5d5dUL, 0xeb9f4644UL, 0x28cc6b6fUL, 0x69fd7076UL, 0xae6b3139UL,\n    0xef5a2a20UL, 0x2c09070bUL, 0x6d381c12UL, 0xf33646dfUL, 0xb2075dc6UL,\n    0x715470edUL, 0x30656bf4UL, 0xf7f32abbUL, 0xb6c231a2UL, 0x75911c89UL,\n    0x34a00790UL, 0xfbbc9f17UL, 0xba8d840eUL, 0x79dea925UL, 0x38efb23cUL,\n    0xff79f373UL, 0xbe48e86aUL, 0x7d1bc541UL, 0x3c2ade58UL, 0x054f79f0UL,\n    0x447e62e9UL, 0x872d4fc2UL, 0xc61c54dbUL, 0x018a1594UL, 0x40bb0e8dUL,\n    0x83e823a6UL, 0xc2d938bfUL, 0x0dc5a038UL, 0x4cf4bb21UL, 0x8fa7960aUL,\n    0xce968d13UL, 0x0900cc5cUL, 0x4831d745UL, 0x8b62fa6eUL, 0xca53e177UL,\n    0x545dbbbaUL, 0x156ca0a3UL, 0xd63f8d88UL, 0x970e9691UL, 0x5098d7deUL,\n    0x11a9ccc7UL, 0xd2fae1ecUL, 0x93cbfaf5UL, 0x5cd76272UL, 0x1de6796bUL,\n    0xdeb55440UL, 0x9f844f59UL, 0x58120e16UL, 0x1923150fUL, 0xda703824UL,\n    0x9b41233dUL, 0xa76bfd65UL, 0xe65ae67cUL, 0x2509cb57UL, 0x6438d04eUL,\n    0xa3ae9101UL, 0xe29f8a18UL, 0x21cca733UL, 0x60fdbc2aUL, 0xafe124adUL,\n    0xeed03fb4UL, 0x2d83129fUL, 0x6cb20986UL, 0xab2448c9UL, 0xea1553d0UL,\n    0x29467efbUL, 0x687765e2UL, 0xf6793f2fUL, 0xb7482436UL, 0x741b091dUL,\n    0x352a1204UL, 0xf2bc534bUL, 0xb38d4852UL, 0x70de6579UL, 0x31ef7e60UL,\n    0xfef3e6e7UL, 0xbfc2fdfeUL, 0x7c91d0d5UL, 0x3da0cbccUL, 0xfa368a83UL,\n    0xbb07919aUL, 0x7854bcb1UL, 0x3965a7a8UL, 0x4b98833bUL, 0x0aa99822UL,\n    0xc9fab509UL, 0x88cbae10UL, 0x4f5def5fUL, 0x0e6cf446UL, 0xcd3fd96dUL,\n    0x8c0ec274UL, 0x43125af3UL, 0x022341eaUL, 0xc1706cc1UL, 0x804177d8UL,\n    0x47d73697UL, 0x06e62d8eUL, 0xc5b500a5UL, 0x84841bbcUL, 0x1a8a4171UL,\n    0x5bbb5a68UL, 0x98e87743UL, 0xd9d96c5aUL, 0x1e4f2d15UL, 0x5f7e360cUL,\n    0x9c2d1b27UL, 0xdd1c003eUL, 0x120098b9UL, 0x533183a0UL, 0x9062ae8bUL,\n    0xd153b592UL, 0x16c5f4ddUL, 0x57f4efc4UL, 0x94a7c2efUL, 0xd596d9f6UL,\n    0xe9bc07aeUL, 0xa88d1cb7UL, 0x6bde319cUL, 0x2aef2a85UL, 0xed796bcaUL,\n    0xac4870d3UL, 0x6f1b5df8UL, 0x2e2a46e1UL, 0xe136de66UL, 0xa007c57fUL,\n    0x6354e854UL, 0x2265f34dUL, 0xe5f3b202UL, 0xa4c2a91bUL, 0x67918430UL,\n    0x26a09f29UL, 0xb8aec5e4UL, 0xf99fdefdUL, 0x3accf3d6UL, 0x7bfde8cfUL,\n    0xbc6ba980UL, 0xfd5ab299UL, 0x3e099fb2UL, 0x7f3884abUL, 0xb0241c2cUL,\n    0xf1150735UL, 0x32462a1eUL, 0x73773107UL, 0xb4e17048UL, 0xf5d06b51UL,\n    0x3683467aUL, 0x77b25d63UL, 0x4ed7facbUL, 0x0fe6e1d2UL, 0xccb5ccf9UL,\n    0x8d84d7e0UL, 0x4a1296afUL, 0x0b238db6UL, 0xc870a09dUL, 0x8941bb84UL,\n    0x465d2303UL, 0x076c381aUL, 0xc43f1531UL, 0x850e0e28UL, 0x42984f67UL,\n    0x03a9547eUL, 0xc0fa7955UL, 0x81cb624cUL, 0x1fc53881UL, 0x5ef42398UL,\n    0x9da70eb3UL, 0xdc9615aaUL, 0x1b0054e5UL, 0x5a314ffcUL, 0x996262d7UL,\n    0xd85379ceUL, 0x174fe149UL, 0x567efa50UL, 0x952dd77bUL, 0xd41ccc62UL,\n    0x138a8d2dUL, 0x52bb9634UL, 0x91e8bb1fUL, 0xd0d9a006UL, 0xecf37e5eUL,\n    0xadc26547UL, 0x6e91486cUL, 0x2fa05375UL, 0xe836123aUL, 0xa9070923UL,\n    0x6a542408UL, 0x2b653f11UL, 0xe479a796UL, 0xa548bc8fUL, 0x661b91a4UL,\n    0x272a8abdUL, 0xe0bccbf2UL, 0xa18dd0ebUL, 0x62defdc0UL, 0x23efe6d9UL,\n    0xbde1bc14UL, 0xfcd0a70dUL, 0x3f838a26UL, 0x7eb2913fUL, 0xb924d070UL,\n    0xf815cb69UL, 0x3b46e642UL, 0x7a77fd5bUL, 0xb56b65dcUL, 0xf45a7ec5UL,\n    0x370953eeUL, 0x763848f7UL, 0xb1ae09b8UL, 0xf09f12a1UL, 0x33cc3f8aUL,\n    0x72fd2493UL\n  },\n  {\n    0x00000000UL, 0x376ac201UL, 0x6ed48403UL, 0x59be4602UL, 0xdca80907UL,\n    0xebc2cb06UL, 0xb27c8d04UL, 0x85164f05UL, 0xb851130eUL, 0x8f3bd10fUL,\n    0xd685970dUL, 0xe1ef550cUL, 0x64f91a09UL, 0x5393d808UL, 0x0a2d9e0aUL,\n    0x3d475c0bUL, 0x70a3261cUL, 0x47c9e41dUL, 0x1e77a21fUL, 0x291d601eUL,\n    0xac0b2f1bUL, 0x9b61ed1aUL, 0xc2dfab18UL, 0xf5b56919UL, 0xc8f23512UL,\n    0xff98f713UL, 0xa626b111UL, 0x914c7310UL, 0x145a3c15UL, 0x2330fe14UL,\n    0x7a8eb816UL, 0x4de47a17UL, 0xe0464d38UL, 0xd72c8f39UL, 0x8e92c93bUL,\n    0xb9f80b3aUL, 0x3cee443fUL, 0x0b84863eUL, 0x523ac03cUL, 0x6550023dUL,\n    0x58175e36UL, 0x6f7d9c37UL, 0x36c3da35UL, 0x01a91834UL, 0x84bf5731UL,\n    0xb3d59530UL, 0xea6bd332UL, 0xdd011133UL, 0x90e56b24UL, 0xa78fa925UL,\n    0xfe31ef27UL, 0xc95b2d26UL, 0x4c4d6223UL, 0x7b27a022UL, 0x2299e620UL,\n    0x15f32421UL, 0x28b4782aUL, 0x1fdeba2bUL, 0x4660fc29UL, 0x710a3e28UL,\n    0xf41c712dUL, 0xc376b32cUL, 0x9ac8f52eUL, 0xada2372fUL, 0xc08d9a70UL,\n    0xf7e75871UL, 0xae591e73UL, 0x9933dc72UL, 0x1c259377UL, 0x2b4f5176UL,\n    0x72f11774UL, 0x459bd575UL, 0x78dc897eUL, 0x4fb64b7fUL, 0x16080d7dUL,\n    0x2162cf7cUL, 0xa4748079UL, 0x931e4278UL, 0xcaa0047aUL, 0xfdcac67bUL,\n    0xb02ebc6cUL, 0x87447e6dUL, 0xdefa386fUL, 0xe990fa6eUL, 0x6c86b56bUL,\n    0x5bec776aUL, 0x02523168UL, 0x3538f369UL, 0x087faf62UL, 0x3f156d63UL,\n    0x66ab2b61UL, 0x51c1e960UL, 0xd4d7a665UL, 0xe3bd6464UL, 0xba032266UL,\n    0x8d69e067UL, 0x20cbd748UL, 0x17a11549UL, 0x4e1f534bUL, 0x7975914aUL,\n    0xfc63de4fUL, 0xcb091c4eUL, 0x92b75a4cUL, 0xa5dd984dUL, 0x989ac446UL,\n    0xaff00647UL, 0xf64e4045UL, 0xc1248244UL, 0x4432cd41UL, 0x73580f40UL,\n    0x2ae64942UL, 0x1d8c8b43UL, 0x5068f154UL, 0x67023355UL, 0x3ebc7557UL,\n    0x09d6b756UL, 0x8cc0f853UL, 0xbbaa3a52UL, 0xe2147c50UL, 0xd57ebe51UL,\n    0xe839e25aUL, 0xdf53205bUL, 0x86ed6659UL, 0xb187a458UL, 0x3491eb5dUL,\n    0x03fb295cUL, 0x5a456f5eUL, 0x6d2fad5fUL, 0x801b35e1UL, 0xb771f7e0UL,\n    0xeecfb1e2UL, 0xd9a573e3UL, 0x5cb33ce6UL, 0x6bd9fee7UL, 0x3267b8e5UL,\n    0x050d7ae4UL, 0x384a26efUL, 0x0f20e4eeUL, 0x569ea2ecUL, 0x61f460edUL,\n    0xe4e22fe8UL, 0xd388ede9UL, 0x8a36abebUL, 0xbd5c69eaUL, 0xf0b813fdUL,\n    0xc7d2d1fcUL, 0x9e6c97feUL, 0xa90655ffUL, 0x2c101afaUL, 0x1b7ad8fbUL,\n    0x42c49ef9UL, 0x75ae5cf8UL, 0x48e900f3UL, 0x7f83c2f2UL, 0x263d84f0UL,\n    0x115746f1UL, 0x944109f4UL, 0xa32bcbf5UL, 0xfa958df7UL, 0xcdff4ff6UL,\n    0x605d78d9UL, 0x5737bad8UL, 0x0e89fcdaUL, 0x39e33edbUL, 0xbcf571deUL,\n    0x8b9fb3dfUL, 0xd221f5ddUL, 0xe54b37dcUL, 0xd80c6bd7UL, 0xef66a9d6UL,\n    0xb6d8efd4UL, 0x81b22dd5UL, 0x04a462d0UL, 0x33cea0d1UL, 0x6a70e6d3UL,\n    0x5d1a24d2UL, 0x10fe5ec5UL, 0x27949cc4UL, 0x7e2adac6UL, 0x494018c7UL,\n    0xcc5657c2UL, 0xfb3c95c3UL, 0xa282d3c1UL, 0x95e811c0UL, 0xa8af4dcbUL,\n    0x9fc58fcaUL, 0xc67bc9c8UL, 0xf1110bc9UL, 0x740744ccUL, 0x436d86cdUL,\n    0x1ad3c0cfUL, 0x2db902ceUL, 0x4096af91UL, 0x77fc6d90UL, 0x2e422b92UL,\n    0x1928e993UL, 0x9c3ea696UL, 0xab546497UL, 0xf2ea2295UL, 0xc580e094UL,\n    0xf8c7bc9fUL, 0xcfad7e9eUL, 0x9613389cUL, 0xa179fa9dUL, 0x246fb598UL,\n    0x13057799UL, 0x4abb319bUL, 0x7dd1f39aUL, 0x3035898dUL, 0x075f4b8cUL,\n    0x5ee10d8eUL, 0x698bcf8fUL, 0xec9d808aUL, 0xdbf7428bUL, 0x82490489UL,\n    0xb523c688UL, 0x88649a83UL, 0xbf0e5882UL, 0xe6b01e80UL, 0xd1dadc81UL,\n    0x54cc9384UL, 0x63a65185UL, 0x3a181787UL, 0x0d72d586UL, 0xa0d0e2a9UL,\n    0x97ba20a8UL, 0xce0466aaUL, 0xf96ea4abUL, 0x7c78ebaeUL, 0x4b1229afUL,\n    0x12ac6fadUL, 0x25c6adacUL, 0x1881f1a7UL, 0x2feb33a6UL, 0x765575a4UL,\n    0x413fb7a5UL, 0xc429f8a0UL, 0xf3433aa1UL, 0xaafd7ca3UL, 0x9d97bea2UL,\n    0xd073c4b5UL, 0xe71906b4UL, 0xbea740b6UL, 0x89cd82b7UL, 0x0cdbcdb2UL,\n    0x3bb10fb3UL, 0x620f49b1UL, 0x55658bb0UL, 0x6822d7bbUL, 0x5f4815baUL,\n    0x06f653b8UL, 0x319c91b9UL, 0xb48adebcUL, 0x83e01cbdUL, 0xda5e5abfUL,\n    0xed3498beUL\n  },\n  {\n    0x00000000UL, 0x6567bcb8UL, 0x8bc809aaUL, 0xeeafb512UL, 0x5797628fUL,\n    0x32f0de37UL, 0xdc5f6b25UL, 0xb938d79dUL, 0xef28b4c5UL, 0x8a4f087dUL,\n    0x64e0bd6fUL, 0x018701d7UL, 0xb8bfd64aUL, 0xddd86af2UL, 0x3377dfe0UL,\n    0x56106358UL, 0x9f571950UL, 0xfa30a5e8UL, 0x149f10faUL, 0x71f8ac42UL,\n    0xc8c07bdfUL, 0xada7c767UL, 0x43087275UL, 0x266fcecdUL, 0x707fad95UL,\n    0x1518112dUL, 0xfbb7a43fUL, 0x9ed01887UL, 0x27e8cf1aUL, 0x428f73a2UL,\n    0xac20c6b0UL, 0xc9477a08UL, 0x3eaf32a0UL, 0x5bc88e18UL, 0xb5673b0aUL,\n    0xd00087b2UL, 0x6938502fUL, 0x0c5fec97UL, 0xe2f05985UL, 0x8797e53dUL,\n    0xd1878665UL, 0xb4e03addUL, 0x5a4f8fcfUL, 0x3f283377UL, 0x8610e4eaUL,\n    0xe3775852UL, 0x0dd8ed40UL, 0x68bf51f8UL, 0xa1f82bf0UL, 0xc49f9748UL,\n    0x2a30225aUL, 0x4f579ee2UL, 0xf66f497fUL, 0x9308f5c7UL, 0x7da740d5UL,\n    0x18c0fc6dUL, 0x4ed09f35UL, 0x2bb7238dUL, 0xc518969fUL, 0xa07f2a27UL,\n    0x1947fdbaUL, 0x7c204102UL, 0x928ff410UL, 0xf7e848a8UL, 0x3d58149bUL,\n    0x583fa823UL, 0xb6901d31UL, 0xd3f7a189UL, 0x6acf7614UL, 0x0fa8caacUL,\n    0xe1077fbeUL, 0x8460c306UL, 0xd270a05eUL, 0xb7171ce6UL, 0x59b8a9f4UL,\n    0x3cdf154cUL, 0x85e7c2d1UL, 0xe0807e69UL, 0x0e2fcb7bUL, 0x6b4877c3UL,\n    0xa20f0dcbUL, 0xc768b173UL, 0x29c70461UL, 0x4ca0b8d9UL, 0xf5986f44UL,\n    0x90ffd3fcUL, 0x7e5066eeUL, 0x1b37da56UL, 0x4d27b90eUL, 0x284005b6UL,\n    0xc6efb0a4UL, 0xa3880c1cUL, 0x1ab0db81UL, 0x7fd76739UL, 0x9178d22bUL,\n    0xf41f6e93UL, 0x03f7263bUL, 0x66909a83UL, 0x883f2f91UL, 0xed589329UL,\n    0x546044b4UL, 0x3107f80cUL, 0xdfa84d1eUL, 0xbacff1a6UL, 0xecdf92feUL,\n    0x89b82e46UL, 0x67179b54UL, 0x027027ecUL, 0xbb48f071UL, 0xde2f4cc9UL,\n    0x3080f9dbUL, 0x55e74563UL, 0x9ca03f6bUL, 0xf9c783d3UL, 0x176836c1UL,\n    0x720f8a79UL, 0xcb375de4UL, 0xae50e15cUL, 0x40ff544eUL, 0x2598e8f6UL,\n    0x73888baeUL, 0x16ef3716UL, 0xf8408204UL, 0x9d273ebcUL, 0x241fe921UL,\n    0x41785599UL, 0xafd7e08bUL, 0xcab05c33UL, 0x3bb659edUL, 0x5ed1e555UL,\n    0xb07e5047UL, 0xd519ecffUL, 0x6c213b62UL, 0x094687daUL, 0xe7e932c8UL,\n    0x828e8e70UL, 0xd49eed28UL, 0xb1f95190UL, 0x5f56e482UL, 0x3a31583aUL,\n    0x83098fa7UL, 0xe66e331fUL, 0x08c1860dUL, 0x6da63ab5UL, 0xa4e140bdUL,\n    0xc186fc05UL, 0x2f294917UL, 0x4a4ef5afUL, 0xf3762232UL, 0x96119e8aUL,\n    0x78be2b98UL, 0x1dd99720UL, 0x4bc9f478UL, 0x2eae48c0UL, 0xc001fdd2UL,\n    0xa566416aUL, 0x1c5e96f7UL, 0x79392a4fUL, 0x97969f5dUL, 0xf2f123e5UL,\n    0x05196b4dUL, 0x607ed7f5UL, 0x8ed162e7UL, 0xebb6de5fUL, 0x528e09c2UL,\n    0x37e9b57aUL, 0xd9460068UL, 0xbc21bcd0UL, 0xea31df88UL, 0x8f566330UL,\n    0x61f9d622UL, 0x049e6a9aUL, 0xbda6bd07UL, 0xd8c101bfUL, 0x366eb4adUL,\n    0x53090815UL, 0x9a4e721dUL, 0xff29cea5UL, 0x11867bb7UL, 0x74e1c70fUL,\n    0xcdd91092UL, 0xa8beac2aUL, 0x46111938UL, 0x2376a580UL, 0x7566c6d8UL,\n    0x10017a60UL, 0xfeaecf72UL, 0x9bc973caUL, 0x22f1a457UL, 0x479618efUL,\n    0xa939adfdUL, 0xcc5e1145UL, 0x06ee4d76UL, 0x6389f1ceUL, 0x8d2644dcUL,\n    0xe841f864UL, 0x51792ff9UL, 0x341e9341UL, 0xdab12653UL, 0xbfd69aebUL,\n    0xe9c6f9b3UL, 0x8ca1450bUL, 0x620ef019UL, 0x07694ca1UL, 0xbe519b3cUL,\n    0xdb362784UL, 0x35999296UL, 0x50fe2e2eUL, 0x99b95426UL, 0xfcdee89eUL,\n    0x12715d8cUL, 0x7716e134UL, 0xce2e36a9UL, 0xab498a11UL, 0x45e63f03UL,\n    0x208183bbUL, 0x7691e0e3UL, 0x13f65c5bUL, 0xfd59e949UL, 0x983e55f1UL,\n    0x2106826cUL, 0x44613ed4UL, 0xaace8bc6UL, 0xcfa9377eUL, 0x38417fd6UL,\n    0x5d26c36eUL, 0xb389767cUL, 0xd6eecac4UL, 0x6fd61d59UL, 0x0ab1a1e1UL,\n    0xe41e14f3UL, 0x8179a84bUL, 0xd769cb13UL, 0xb20e77abUL, 0x5ca1c2b9UL,\n    0x39c67e01UL, 0x80fea99cUL, 0xe5991524UL, 0x0b36a036UL, 0x6e511c8eUL,\n    0xa7166686UL, 0xc271da3eUL, 0x2cde6f2cUL, 0x49b9d394UL, 0xf0810409UL,\n    0x95e6b8b1UL, 0x7b490da3UL, 0x1e2eb11bUL, 0x483ed243UL, 0x2d596efbUL,\n    0xc3f6dbe9UL, 0xa6916751UL, 0x1fa9b0ccUL, 0x7ace0c74UL, 0x9461b966UL,\n    0xf10605deUL\n#endif\n  }\n};\n"
  },
  {
    "path": "external/zlib/deflate.c",
    "content": "/* deflate.c -- compress data using the deflation algorithm\n * Copyright (C) 1995-2013 Jean-loup Gailly and Mark Adler\n * For conditions of distribution and use, see copyright notice in zlib.h\n */\n\n/*\n *  ALGORITHM\n *\n *      The \"deflation\" process depends on being able to identify portions\n *      of the input text which are identical to earlier input (within a\n *      sliding window trailing behind the input currently being processed).\n *\n *      The most straightforward technique turns out to be the fastest for\n *      most input files: try all possible matches and select the longest.\n *      The key feature of this algorithm is that insertions into the string\n *      dictionary are very simple and thus fast, and deletions are avoided\n *      completely. Insertions are performed at each input character, whereas\n *      string matches are performed only when the previous match ends. So it\n *      is preferable to spend more time in matches to allow very fast string\n *      insertions and avoid deletions. The matching algorithm for small\n *      strings is inspired from that of Rabin & Karp. A brute force approach\n *      is used to find longer strings when a small match has been found.\n *      A similar algorithm is used in comic (by Jan-Mark Wams) and freeze\n *      (by Leonid Broukhis).\n *         A previous version of this file used a more sophisticated algorithm\n *      (by Fiala and Greene) which is guaranteed to run in linear amortized\n *      time, but has a larger average cost, uses more memory and is patented.\n *      However the F&G algorithm may be faster for some highly redundant\n *      files if the parameter max_chain_length (described below) is too large.\n *\n *  ACKNOWLEDGEMENTS\n *\n *      The idea of lazy evaluation of matches is due to Jan-Mark Wams, and\n *      I found it in 'freeze' written by Leonid Broukhis.\n *      Thanks to many people for bug reports and testing.\n *\n *  REFERENCES\n *\n *      Deutsch, L.P.,\"DEFLATE Compressed Data Format Specification\".\n *      Available in http://tools.ietf.org/html/rfc1951\n *\n *      A description of the Rabin and Karp algorithm is given in the book\n *         \"Algorithms\" by R. Sedgewick, Addison-Wesley, p252.\n *\n *      Fiala,E.R., and Greene,D.H.\n *         Data Compression with Finite Windows, Comm.ACM, 32,4 (1989) 490-595\n *\n */\n\n/* @(#) $Id$ */\n\n#include \"deflate.h\"\n\nconst char deflate_copyright[] =\n   \" deflate 1.2.8 Copyright 1995-2013 Jean-loup Gailly and Mark Adler \";\n/*\n  If you use the zlib library in a product, an acknowledgment is welcome\n  in the documentation of your product. If for some reason you cannot\n  include such an acknowledgment, I would appreciate that you keep this\n  copyright string in the executable of your product.\n */\n\n/* ===========================================================================\n *  Function prototypes.\n */\ntypedef enum {\n    need_more,      /* block not completed, need more input or more output */\n    block_done,     /* block flush performed */\n    finish_started, /* finish started, need only more output at next deflate */\n    finish_done     /* finish done, accept no more input or output */\n} block_state;\n\ntypedef block_state (*compress_func) OF((deflate_state *s, int flush));\n/* Compression function. Returns the block state after the call. */\n\nlocal void fill_window    OF((deflate_state *s));\nlocal block_state deflate_stored OF((deflate_state *s, int flush));\nlocal block_state deflate_fast   OF((deflate_state *s, int flush));\n#ifndef FASTEST\nlocal block_state deflate_slow   OF((deflate_state *s, int flush));\n#endif\nlocal block_state deflate_rle    OF((deflate_state *s, int flush));\nlocal block_state deflate_huff   OF((deflate_state *s, int flush));\nlocal void lm_init        OF((deflate_state *s));\nlocal void putShortMSB    OF((deflate_state *s, uInt b));\nlocal void flush_pending  OF((z_streamp strm));\nlocal int read_buf        OF((z_streamp strm, Bytef *buf, unsigned size));\n#ifdef ASMV\n      void match_init OF((void)); /* asm code initialization */\n      uInt longest_match  OF((deflate_state *s, IPos cur_match));\n#else\nlocal uInt longest_match  OF((deflate_state *s, IPos cur_match));\n#endif\n\n#ifdef DEBUG\nlocal  void check_match OF((deflate_state *s, IPos start, IPos match,\n                            int length));\n#endif\n\n/* ===========================================================================\n * Local data\n */\n\n#define NIL 0\n/* Tail of hash chains */\n\n#ifndef TOO_FAR\n#  define TOO_FAR 4096\n#endif\n/* Matches of length 3 are discarded if their distance exceeds TOO_FAR */\n\n/* Values for max_lazy_match, good_match and max_chain_length, depending on\n * the desired pack level (0..9). The values given below have been tuned to\n * exclude worst case performance for pathological files. Better values may be\n * found for specific files.\n */\ntypedef struct config_s {\n   ush good_length; /* reduce lazy search above this match length */\n   ush max_lazy;    /* do not perform lazy search above this match length */\n   ush nice_length; /* quit search above this match length */\n   ush max_chain;\n   compress_func func;\n} config;\n\n#ifdef FASTEST\nlocal const config configuration_table[2] = {\n/*      good lazy nice chain */\n/* 0 */ {0,    0,  0,    0, deflate_stored},  /* store only */\n/* 1 */ {4,    4,  8,    4, deflate_fast}}; /* max speed, no lazy matches */\n#else\nlocal const config configuration_table[10] = {\n/*      good lazy nice chain */\n/* 0 */ {0,    0,  0,    0, deflate_stored},  /* store only */\n/* 1 */ {4,    4,  8,    4, deflate_fast}, /* max speed, no lazy matches */\n/* 2 */ {4,    5, 16,    8, deflate_fast},\n/* 3 */ {4,    6, 32,   32, deflate_fast},\n\n/* 4 */ {4,    4, 16,   16, deflate_slow},  /* lazy matches */\n/* 5 */ {8,   16, 32,   32, deflate_slow},\n/* 6 */ {8,   16, 128, 128, deflate_slow},\n/* 7 */ {8,   32, 128, 256, deflate_slow},\n/* 8 */ {32, 128, 258, 1024, deflate_slow},\n/* 9 */ {32, 258, 258, 4096, deflate_slow}}; /* max compression */\n#endif\n\n/* Note: the deflate() code requires max_lazy >= MIN_MATCH and max_chain >= 4\n * For deflate_fast() (levels <= 3) good is ignored and lazy has a different\n * meaning.\n */\n\n#define EQUAL 0\n/* result of memcmp for equal strings */\n\n#ifndef NO_DUMMY_DECL\nstruct static_tree_desc_s {int dummy;}; /* for buggy compilers */\n#endif\n\n/* rank Z_BLOCK between Z_NO_FLUSH and Z_PARTIAL_FLUSH */\n#define RANK(f) (((f) << 1) - ((f) > 4 ? 9 : 0))\n\n/* ===========================================================================\n * Update a hash value with the given input byte\n * IN  assertion: all calls to to UPDATE_HASH are made with consecutive\n *    input characters, so that a running hash key can be computed from the\n *    previous key instead of complete recalculation each time.\n */\n#define UPDATE_HASH(s,h,c) (h = (((h)<<s->hash_shift) ^ (c)) & s->hash_mask)\n\n\n/* ===========================================================================\n * Insert string str in the dictionary and set match_head to the previous head\n * of the hash chain (the most recent string with same hash key). Return\n * the previous length of the hash chain.\n * If this file is compiled with -DFASTEST, the compression level is forced\n * to 1, and no hash chains are maintained.\n * IN  assertion: all calls to to INSERT_STRING are made with consecutive\n *    input characters and the first MIN_MATCH bytes of str are valid\n *    (except for the last MIN_MATCH-1 bytes of the input file).\n */\n#ifdef FASTEST\n#define INSERT_STRING(s, str, match_head) \\\n   (UPDATE_HASH(s, s->ins_h, s->window[(str) + (MIN_MATCH-1)]), \\\n    match_head = s->head[s->ins_h], \\\n    s->head[s->ins_h] = (Pos)(str))\n#else\n#define INSERT_STRING(s, str, match_head) \\\n   (UPDATE_HASH(s, s->ins_h, s->window[(str) + (MIN_MATCH-1)]), \\\n    match_head = s->prev[(str) & s->w_mask] = s->head[s->ins_h], \\\n    s->head[s->ins_h] = (Pos)(str))\n#endif\n\n/* ===========================================================================\n * Initialize the hash table (avoiding 64K overflow for 16 bit systems).\n * prev[] will be initialized on the fly.\n */\n#define CLEAR_HASH(s) \\\n    s->head[s->hash_size-1] = NIL; \\\n    zmemzero((Bytef *)s->head, (unsigned)(s->hash_size-1)*sizeof(*s->head));\n\n/* ========================================================================= */\nint ZEXPORT deflateInit_(strm, level, version, stream_size)\n    z_streamp strm;\n    int level;\n    const char *version;\n    int stream_size;\n{\n    return deflateInit2_(strm, level, Z_DEFLATED, MAX_WBITS, DEF_MEM_LEVEL,\n                         Z_DEFAULT_STRATEGY, version, stream_size);\n    /* To do: ignore strm->next_in if we use it as window */\n}\n\n/* ========================================================================= */\nint ZEXPORT deflateInit2_(strm, level, method, windowBits, memLevel, strategy,\n                  version, stream_size)\n    z_streamp strm;\n    int  level;\n    int  method;\n    int  windowBits;\n    int  memLevel;\n    int  strategy;\n    const char *version;\n    int stream_size;\n{\n    deflate_state *s;\n    int wrap = 1;\n    static const char my_version[] = ZLIB_VERSION;\n\n    ushf *overlay;\n    /* We overlay pending_buf and d_buf+l_buf. This works since the average\n     * output size for (length,distance) codes is <= 24 bits.\n     */\n\n    if (version == Z_NULL || version[0] != my_version[0] ||\n        stream_size != sizeof(z_stream)) {\n        return Z_VERSION_ERROR;\n    }\n    if (strm == Z_NULL) return Z_STREAM_ERROR;\n\n    strm->msg = Z_NULL;\n    if (strm->zalloc == (alloc_func)0) {\n#ifdef Z_SOLO\n        return Z_STREAM_ERROR;\n#else\n        strm->zalloc = zcalloc;\n        strm->opaque = (voidpf)0;\n#endif\n    }\n    if (strm->zfree == (free_func)0)\n#ifdef Z_SOLO\n        return Z_STREAM_ERROR;\n#else\n        strm->zfree = zcfree;\n#endif\n\n#ifdef FASTEST\n    if (level != 0) level = 1;\n#else\n    if (level == Z_DEFAULT_COMPRESSION) level = 6;\n#endif\n\n    if (windowBits < 0) { /* suppress zlib wrapper */\n        wrap = 0;\n        windowBits = -windowBits;\n    }\n#ifdef GZIP\n    else if (windowBits > 15) {\n        wrap = 2;       /* write gzip wrapper instead */\n        windowBits -= 16;\n    }\n#endif\n    if (memLevel < 1 || memLevel > MAX_MEM_LEVEL || method != Z_DEFLATED ||\n        windowBits < 8 || windowBits > 15 || level < 0 || level > 9 ||\n        strategy < 0 || strategy > Z_FIXED) {\n        return Z_STREAM_ERROR;\n    }\n    if (windowBits == 8) windowBits = 9;  /* until 256-byte window bug fixed */\n    s = (deflate_state *) ZALLOC(strm, 1, sizeof(deflate_state));\n    if (s == Z_NULL) return Z_MEM_ERROR;\n    strm->state = (struct internal_state FAR *)s;\n    s->strm = strm;\n\n    s->wrap = wrap;\n    s->gzhead = Z_NULL;\n    s->w_bits = windowBits;\n    s->w_size = 1 << s->w_bits;\n    s->w_mask = s->w_size - 1;\n\n    s->hash_bits = memLevel + 7;\n    s->hash_size = 1 << s->hash_bits;\n    s->hash_mask = s->hash_size - 1;\n    s->hash_shift =  ((s->hash_bits+MIN_MATCH-1)/MIN_MATCH);\n\n    s->window = (Bytef *) ZALLOC(strm, s->w_size, 2*sizeof(Byte));\n    s->prev   = (Posf *)  ZALLOC(strm, s->w_size, sizeof(Pos));\n    s->head   = (Posf *)  ZALLOC(strm, s->hash_size, sizeof(Pos));\n\n    s->high_water = 0;      /* nothing written to s->window yet */\n\n    s->lit_bufsize = 1 << (memLevel + 6); /* 16K elements by default */\n\n    overlay = (ushf *) ZALLOC(strm, s->lit_bufsize, sizeof(ush)+2);\n    s->pending_buf = (uchf *) overlay;\n    s->pending_buf_size = (ulg)s->lit_bufsize * (sizeof(ush)+2L);\n\n    if (s->window == Z_NULL || s->prev == Z_NULL || s->head == Z_NULL ||\n        s->pending_buf == Z_NULL) {\n        s->status = FINISH_STATE;\n        strm->msg = ERR_MSG(Z_MEM_ERROR);\n        deflateEnd (strm);\n        return Z_MEM_ERROR;\n    }\n    s->d_buf = overlay + s->lit_bufsize/sizeof(ush);\n    s->l_buf = s->pending_buf + (1+sizeof(ush))*s->lit_bufsize;\n\n    s->level = level;\n    s->strategy = strategy;\n    s->method = (Byte)method;\n\n    return deflateReset(strm);\n}\n\n/* ========================================================================= */\nint ZEXPORT deflateSetDictionary (strm, dictionary, dictLength)\n    z_streamp strm;\n    const Bytef *dictionary;\n    uInt  dictLength;\n{\n    deflate_state *s;\n    uInt str, n;\n    int wrap;\n    unsigned avail;\n    z_const unsigned char *next;\n\n    if (strm == Z_NULL || strm->state == Z_NULL || dictionary == Z_NULL)\n        return Z_STREAM_ERROR;\n    s = strm->state;\n    wrap = s->wrap;\n    if (wrap == 2 || (wrap == 1 && s->status != INIT_STATE) || s->lookahead)\n        return Z_STREAM_ERROR;\n\n    /* when using zlib wrappers, compute Adler-32 for provided dictionary */\n    if (wrap == 1)\n        strm->adler = adler32(strm->adler, dictionary, dictLength);\n    s->wrap = 0;                    /* avoid computing Adler-32 in read_buf */\n\n    /* if dictionary would fill window, just replace the history */\n    if (dictLength >= s->w_size) {\n        if (wrap == 0) {            /* already empty otherwise */\n            CLEAR_HASH(s);\n            s->strstart = 0;\n            s->block_start = 0L;\n            s->insert = 0;\n        }\n        dictionary += dictLength - s->w_size;  /* use the tail */\n        dictLength = s->w_size;\n    }\n\n    /* insert dictionary into window and hash */\n    avail = strm->avail_in;\n    next = strm->next_in;\n    strm->avail_in = dictLength;\n    strm->next_in = (z_const Bytef *)dictionary;\n    fill_window(s);\n    while (s->lookahead >= MIN_MATCH) {\n        str = s->strstart;\n        n = s->lookahead - (MIN_MATCH-1);\n        do {\n            UPDATE_HASH(s, s->ins_h, s->window[str + MIN_MATCH-1]);\n#ifndef FASTEST\n            s->prev[str & s->w_mask] = s->head[s->ins_h];\n#endif\n            s->head[s->ins_h] = (Pos)str;\n            str++;\n        } while (--n);\n        s->strstart = str;\n        s->lookahead = MIN_MATCH-1;\n        fill_window(s);\n    }\n    s->strstart += s->lookahead;\n    s->block_start = (long)s->strstart;\n    s->insert = s->lookahead;\n    s->lookahead = 0;\n    s->match_length = s->prev_length = MIN_MATCH-1;\n    s->match_available = 0;\n    strm->next_in = next;\n    strm->avail_in = avail;\n    s->wrap = wrap;\n    return Z_OK;\n}\n\n/* ========================================================================= */\nint ZEXPORT deflateResetKeep (strm)\n    z_streamp strm;\n{\n    deflate_state *s;\n\n    if (strm == Z_NULL || strm->state == Z_NULL ||\n        strm->zalloc == (alloc_func)0 || strm->zfree == (free_func)0) {\n        return Z_STREAM_ERROR;\n    }\n\n    strm->total_in = strm->total_out = 0;\n    strm->msg = Z_NULL; /* use zfree if we ever allocate msg dynamically */\n    strm->data_type = Z_UNKNOWN;\n\n    s = (deflate_state *)strm->state;\n    s->pending = 0;\n    s->pending_out = s->pending_buf;\n\n    if (s->wrap < 0) {\n        s->wrap = -s->wrap; /* was made negative by deflate(..., Z_FINISH); */\n    }\n    s->status = s->wrap ? INIT_STATE : BUSY_STATE;\n    strm->adler =\n#ifdef GZIP\n        s->wrap == 2 ? crc32(0L, Z_NULL, 0) :\n#endif\n        adler32(0L, Z_NULL, 0);\n    s->last_flush = Z_NO_FLUSH;\n\n    _tr_init(s);\n\n    return Z_OK;\n}\n\n/* ========================================================================= */\nint ZEXPORT deflateReset (strm)\n    z_streamp strm;\n{\n    int ret;\n\n    ret = deflateResetKeep(strm);\n    if (ret == Z_OK)\n        lm_init(strm->state);\n    return ret;\n}\n\n/* ========================================================================= */\nint ZEXPORT deflateSetHeader (strm, head)\n    z_streamp strm;\n    gz_headerp head;\n{\n    if (strm == Z_NULL || strm->state == Z_NULL) return Z_STREAM_ERROR;\n    if (strm->state->wrap != 2) return Z_STREAM_ERROR;\n    strm->state->gzhead = head;\n    return Z_OK;\n}\n\n/* ========================================================================= */\nint ZEXPORT deflatePending (strm, pending, bits)\n    unsigned *pending;\n    int *bits;\n    z_streamp strm;\n{\n    if (strm == Z_NULL || strm->state == Z_NULL) return Z_STREAM_ERROR;\n    if (pending != Z_NULL)\n        *pending = strm->state->pending;\n    if (bits != Z_NULL)\n        *bits = strm->state->bi_valid;\n    return Z_OK;\n}\n\n/* ========================================================================= */\nint ZEXPORT deflatePrime (strm, bits, value)\n    z_streamp strm;\n    int bits;\n    int value;\n{\n    deflate_state *s;\n    int put;\n\n    if (strm == Z_NULL || strm->state == Z_NULL) return Z_STREAM_ERROR;\n    s = strm->state;\n    if ((Bytef *)(s->d_buf) < s->pending_out + ((Buf_size + 7) >> 3))\n        return Z_BUF_ERROR;\n    do {\n        put = Buf_size - s->bi_valid;\n        if (put > bits)\n            put = bits;\n        s->bi_buf |= (ush)((value & ((1 << put) - 1)) << s->bi_valid);\n        s->bi_valid += put;\n        _tr_flush_bits(s);\n        value >>= put;\n        bits -= put;\n    } while (bits);\n    return Z_OK;\n}\n\n/* ========================================================================= */\nint ZEXPORT deflateParams(strm, level, strategy)\n    z_streamp strm;\n    int level;\n    int strategy;\n{\n    deflate_state *s;\n    compress_func func;\n    int err = Z_OK;\n\n    if (strm == Z_NULL || strm->state == Z_NULL) return Z_STREAM_ERROR;\n    s = strm->state;\n\n#ifdef FASTEST\n    if (level != 0) level = 1;\n#else\n    if (level == Z_DEFAULT_COMPRESSION) level = 6;\n#endif\n    if (level < 0 || level > 9 || strategy < 0 || strategy > Z_FIXED) {\n        return Z_STREAM_ERROR;\n    }\n    func = configuration_table[s->level].func;\n\n    if ((strategy != s->strategy || func != configuration_table[level].func) &&\n        strm->total_in != 0) {\n        /* Flush the last buffer: */\n        err = deflate(strm, Z_BLOCK);\n        if (err == Z_BUF_ERROR && s->pending == 0)\n            err = Z_OK;\n    }\n    if (s->level != level) {\n        s->level = level;\n        s->max_lazy_match   = configuration_table[level].max_lazy;\n        s->good_match       = configuration_table[level].good_length;\n        s->nice_match       = configuration_table[level].nice_length;\n        s->max_chain_length = configuration_table[level].max_chain;\n    }\n    s->strategy = strategy;\n    return err;\n}\n\n/* ========================================================================= */\nint ZEXPORT deflateTune(strm, good_length, max_lazy, nice_length, max_chain)\n    z_streamp strm;\n    int good_length;\n    int max_lazy;\n    int nice_length;\n    int max_chain;\n{\n    deflate_state *s;\n\n    if (strm == Z_NULL || strm->state == Z_NULL) return Z_STREAM_ERROR;\n    s = strm->state;\n    s->good_match = good_length;\n    s->max_lazy_match = max_lazy;\n    s->nice_match = nice_length;\n    s->max_chain_length = max_chain;\n    return Z_OK;\n}\n\n/* =========================================================================\n * For the default windowBits of 15 and memLevel of 8, this function returns\n * a close to exact, as well as small, upper bound on the compressed size.\n * They are coded as constants here for a reason--if the #define's are\n * changed, then this function needs to be changed as well.  The return\n * value for 15 and 8 only works for those exact settings.\n *\n * For any setting other than those defaults for windowBits and memLevel,\n * the value returned is a conservative worst case for the maximum expansion\n * resulting from using fixed blocks instead of stored blocks, which deflate\n * can emit on compressed data for some combinations of the parameters.\n *\n * This function could be more sophisticated to provide closer upper bounds for\n * every combination of windowBits and memLevel.  But even the conservative\n * upper bound of about 14% expansion does not seem onerous for output buffer\n * allocation.\n */\nuLong ZEXPORT deflateBound(strm, sourceLen)\n    z_streamp strm;\n    uLong sourceLen;\n{\n    deflate_state *s;\n    uLong complen, wraplen;\n    Bytef *str;\n\n    /* conservative upper bound for compressed data */\n    complen = sourceLen +\n              ((sourceLen + 7) >> 3) + ((sourceLen + 63) >> 6) + 5;\n\n    /* if can't get parameters, return conservative bound plus zlib wrapper */\n    if (strm == Z_NULL || strm->state == Z_NULL)\n        return complen + 6;\n\n    /* compute wrapper length */\n    s = strm->state;\n    switch (s->wrap) {\n    case 0:                                 /* raw deflate */\n        wraplen = 0;\n        break;\n    case 1:                                 /* zlib wrapper */\n        wraplen = 6 + (s->strstart ? 4 : 0);\n        break;\n    case 2:                                 /* gzip wrapper */\n        wraplen = 18;\n        if (s->gzhead != Z_NULL) {          /* user-supplied gzip header */\n            if (s->gzhead->extra != Z_NULL)\n                wraplen += 2 + s->gzhead->extra_len;\n            str = s->gzhead->name;\n            if (str != Z_NULL)\n                do {\n                    wraplen++;\n                } while (*str++);\n            str = s->gzhead->comment;\n            if (str != Z_NULL)\n                do {\n                    wraplen++;\n                } while (*str++);\n            if (s->gzhead->hcrc)\n                wraplen += 2;\n        }\n        break;\n    default:                                /* for compiler happiness */\n        wraplen = 6;\n    }\n\n    /* if not default parameters, return conservative bound */\n    if (s->w_bits != 15 || s->hash_bits != 8 + 7)\n        return complen + wraplen;\n\n    /* default settings: return tight bound for that case */\n    return sourceLen + (sourceLen >> 12) + (sourceLen >> 14) +\n           (sourceLen >> 25) + 13 - 6 + wraplen;\n}\n\n/* =========================================================================\n * Put a short in the pending buffer. The 16-bit value is put in MSB order.\n * IN assertion: the stream state is correct and there is enough room in\n * pending_buf.\n */\nlocal void putShortMSB (s, b)\n    deflate_state *s;\n    uInt b;\n{\n    put_byte(s, (Byte)(b >> 8));\n    put_byte(s, (Byte)(b & 0xff));\n}\n\n/* =========================================================================\n * Flush as much pending output as possible. All deflate() output goes\n * through this function so some applications may wish to modify it\n * to avoid allocating a large strm->next_out buffer and copying into it.\n * (See also read_buf()).\n */\nlocal void flush_pending(strm)\n    z_streamp strm;\n{\n    unsigned len;\n    deflate_state *s = strm->state;\n\n    _tr_flush_bits(s);\n    len = s->pending;\n    if (len > strm->avail_out) len = strm->avail_out;\n    if (len == 0) return;\n\n    zmemcpy(strm->next_out, s->pending_out, len);\n    strm->next_out  += len;\n    s->pending_out  += len;\n    strm->total_out += len;\n    strm->avail_out  -= len;\n    s->pending -= len;\n    if (s->pending == 0) {\n        s->pending_out = s->pending_buf;\n    }\n}\n\n/* ========================================================================= */\nint ZEXPORT deflate (strm, flush)\n    z_streamp strm;\n    int flush;\n{\n    int old_flush; /* value of flush param for previous deflate call */\n    deflate_state *s;\n\n    if (strm == Z_NULL || strm->state == Z_NULL ||\n        flush > Z_BLOCK || flush < 0) {\n        return Z_STREAM_ERROR;\n    }\n    s = strm->state;\n\n    if (strm->next_out == Z_NULL ||\n        (strm->next_in == Z_NULL && strm->avail_in != 0) ||\n        (s->status == FINISH_STATE && flush != Z_FINISH)) {\n        ERR_RETURN(strm, Z_STREAM_ERROR);\n    }\n    if (strm->avail_out == 0) ERR_RETURN(strm, Z_BUF_ERROR);\n\n    s->strm = strm; /* just in case */\n    old_flush = s->last_flush;\n    s->last_flush = flush;\n\n    /* Write the header */\n    if (s->status == INIT_STATE) {\n#ifdef GZIP\n        if (s->wrap == 2) {\n            strm->adler = crc32(0L, Z_NULL, 0);\n            put_byte(s, 31);\n            put_byte(s, 139);\n            put_byte(s, 8);\n            if (s->gzhead == Z_NULL) {\n                put_byte(s, 0);\n                put_byte(s, 0);\n                put_byte(s, 0);\n                put_byte(s, 0);\n                put_byte(s, 0);\n                put_byte(s, s->level == 9 ? 2 :\n                            (s->strategy >= Z_HUFFMAN_ONLY || s->level < 2 ?\n                             4 : 0));\n                put_byte(s, OS_CODE);\n                s->status = BUSY_STATE;\n            }\n            else {\n                put_byte(s, (s->gzhead->text ? 1 : 0) +\n                            (s->gzhead->hcrc ? 2 : 0) +\n                            (s->gzhead->extra == Z_NULL ? 0 : 4) +\n                            (s->gzhead->name == Z_NULL ? 0 : 8) +\n                            (s->gzhead->comment == Z_NULL ? 0 : 16)\n                        );\n                put_byte(s, (Byte)(s->gzhead->time & 0xff));\n                put_byte(s, (Byte)((s->gzhead->time >> 8) & 0xff));\n                put_byte(s, (Byte)((s->gzhead->time >> 16) & 0xff));\n                put_byte(s, (Byte)((s->gzhead->time >> 24) & 0xff));\n                put_byte(s, s->level == 9 ? 2 :\n                            (s->strategy >= Z_HUFFMAN_ONLY || s->level < 2 ?\n                             4 : 0));\n                put_byte(s, s->gzhead->os & 0xff);\n                if (s->gzhead->extra != Z_NULL) {\n                    put_byte(s, s->gzhead->extra_len & 0xff);\n                    put_byte(s, (s->gzhead->extra_len >> 8) & 0xff);\n                }\n                if (s->gzhead->hcrc)\n                    strm->adler = crc32(strm->adler, s->pending_buf,\n                                        s->pending);\n                s->gzindex = 0;\n                s->status = EXTRA_STATE;\n            }\n        }\n        else\n#endif\n        {\n            uInt header = (Z_DEFLATED + ((s->w_bits-8)<<4)) << 8;\n            uInt level_flags;\n\n            if (s->strategy >= Z_HUFFMAN_ONLY || s->level < 2)\n                level_flags = 0;\n            else if (s->level < 6)\n                level_flags = 1;\n            else if (s->level == 6)\n                level_flags = 2;\n            else\n                level_flags = 3;\n            header |= (level_flags << 6);\n            if (s->strstart != 0) header |= PRESET_DICT;\n            header += 31 - (header % 31);\n\n            s->status = BUSY_STATE;\n            putShortMSB(s, header);\n\n            /* Save the adler32 of the preset dictionary: */\n            if (s->strstart != 0) {\n                putShortMSB(s, (uInt)(strm->adler >> 16));\n                putShortMSB(s, (uInt)(strm->adler & 0xffff));\n            }\n            strm->adler = adler32(0L, Z_NULL, 0);\n        }\n    }\n#ifdef GZIP\n    if (s->status == EXTRA_STATE) {\n        if (s->gzhead->extra != Z_NULL) {\n            uInt beg = s->pending;  /* start of bytes to update crc */\n\n            while (s->gzindex < (s->gzhead->extra_len & 0xffff)) {\n                if (s->pending == s->pending_buf_size) {\n                    if (s->gzhead->hcrc && s->pending > beg)\n                        strm->adler = crc32(strm->adler, s->pending_buf + beg,\n                                            s->pending - beg);\n                    flush_pending(strm);\n                    beg = s->pending;\n                    if (s->pending == s->pending_buf_size)\n                        break;\n                }\n                put_byte(s, s->gzhead->extra[s->gzindex]);\n                s->gzindex++;\n            }\n            if (s->gzhead->hcrc && s->pending > beg)\n                strm->adler = crc32(strm->adler, s->pending_buf + beg,\n                                    s->pending - beg);\n            if (s->gzindex == s->gzhead->extra_len) {\n                s->gzindex = 0;\n                s->status = NAME_STATE;\n            }\n        }\n        else\n            s->status = NAME_STATE;\n    }\n    if (s->status == NAME_STATE) {\n        if (s->gzhead->name != Z_NULL) {\n            uInt beg = s->pending;  /* start of bytes to update crc */\n            int val;\n\n            do {\n                if (s->pending == s->pending_buf_size) {\n                    if (s->gzhead->hcrc && s->pending > beg)\n                        strm->adler = crc32(strm->adler, s->pending_buf + beg,\n                                            s->pending - beg);\n                    flush_pending(strm);\n                    beg = s->pending;\n                    if (s->pending == s->pending_buf_size) {\n                        val = 1;\n                        break;\n                    }\n                }\n                val = s->gzhead->name[s->gzindex++];\n                put_byte(s, val);\n            } while (val != 0);\n            if (s->gzhead->hcrc && s->pending > beg)\n                strm->adler = crc32(strm->adler, s->pending_buf + beg,\n                                    s->pending - beg);\n            if (val == 0) {\n                s->gzindex = 0;\n                s->status = COMMENT_STATE;\n            }\n        }\n        else\n            s->status = COMMENT_STATE;\n    }\n    if (s->status == COMMENT_STATE) {\n        if (s->gzhead->comment != Z_NULL) {\n            uInt beg = s->pending;  /* start of bytes to update crc */\n            int val;\n\n            do {\n                if (s->pending == s->pending_buf_size) {\n                    if (s->gzhead->hcrc && s->pending > beg)\n                        strm->adler = crc32(strm->adler, s->pending_buf + beg,\n                                            s->pending - beg);\n                    flush_pending(strm);\n                    beg = s->pending;\n                    if (s->pending == s->pending_buf_size) {\n                        val = 1;\n                        break;\n                    }\n                }\n                val = s->gzhead->comment[s->gzindex++];\n                put_byte(s, val);\n            } while (val != 0);\n            if (s->gzhead->hcrc && s->pending > beg)\n                strm->adler = crc32(strm->adler, s->pending_buf + beg,\n                                    s->pending - beg);\n            if (val == 0)\n                s->status = HCRC_STATE;\n        }\n        else\n            s->status = HCRC_STATE;\n    }\n    if (s->status == HCRC_STATE) {\n        if (s->gzhead->hcrc) {\n            if (s->pending + 2 > s->pending_buf_size)\n                flush_pending(strm);\n            if (s->pending + 2 <= s->pending_buf_size) {\n                put_byte(s, (Byte)(strm->adler & 0xff));\n                put_byte(s, (Byte)((strm->adler >> 8) & 0xff));\n                strm->adler = crc32(0L, Z_NULL, 0);\n                s->status = BUSY_STATE;\n            }\n        }\n        else\n            s->status = BUSY_STATE;\n    }\n#endif\n\n    /* Flush as much pending output as possible */\n    if (s->pending != 0) {\n        flush_pending(strm);\n        if (strm->avail_out == 0) {\n            /* Since avail_out is 0, deflate will be called again with\n             * more output space, but possibly with both pending and\n             * avail_in equal to zero. There won't be anything to do,\n             * but this is not an error situation so make sure we\n             * return OK instead of BUF_ERROR at next call of deflate:\n             */\n            s->last_flush = -1;\n            return Z_OK;\n        }\n\n    /* Make sure there is something to do and avoid duplicate consecutive\n     * flushes. For repeated and useless calls with Z_FINISH, we keep\n     * returning Z_STREAM_END instead of Z_BUF_ERROR.\n     */\n    } else if (strm->avail_in == 0 && RANK(flush) <= RANK(old_flush) &&\n               flush != Z_FINISH) {\n        ERR_RETURN(strm, Z_BUF_ERROR);\n    }\n\n    /* User must not provide more input after the first FINISH: */\n    if (s->status == FINISH_STATE && strm->avail_in != 0) {\n        ERR_RETURN(strm, Z_BUF_ERROR);\n    }\n\n    /* Start a new block or continue the current one.\n     */\n    if (strm->avail_in != 0 || s->lookahead != 0 ||\n        (flush != Z_NO_FLUSH && s->status != FINISH_STATE)) {\n        block_state bstate;\n\n        bstate = s->strategy == Z_HUFFMAN_ONLY ? deflate_huff(s, flush) :\n                    (s->strategy == Z_RLE ? deflate_rle(s, flush) :\n                        (*(configuration_table[s->level].func))(s, flush));\n\n        if (bstate == finish_started || bstate == finish_done) {\n            s->status = FINISH_STATE;\n        }\n        if (bstate == need_more || bstate == finish_started) {\n            if (strm->avail_out == 0) {\n                s->last_flush = -1; /* avoid BUF_ERROR next call, see above */\n            }\n            return Z_OK;\n            /* If flush != Z_NO_FLUSH && avail_out == 0, the next call\n             * of deflate should use the same flush parameter to make sure\n             * that the flush is complete. So we don't have to output an\n             * empty block here, this will be done at next call. This also\n             * ensures that for a very small output buffer, we emit at most\n             * one empty block.\n             */\n        }\n        if (bstate == block_done) {\n            if (flush == Z_PARTIAL_FLUSH) {\n                _tr_align(s);\n            } else if (flush != Z_BLOCK) { /* FULL_FLUSH or SYNC_FLUSH */\n                _tr_stored_block(s, (char*)0, 0L, 0);\n                /* For a full flush, this empty block will be recognized\n                 * as a special marker by inflate_sync().\n                 */\n                if (flush == Z_FULL_FLUSH) {\n                    CLEAR_HASH(s);             /* forget history */\n                    if (s->lookahead == 0) {\n                        s->strstart = 0;\n                        s->block_start = 0L;\n                        s->insert = 0;\n                    }\n                }\n            }\n            flush_pending(strm);\n            if (strm->avail_out == 0) {\n              s->last_flush = -1; /* avoid BUF_ERROR at next call, see above */\n              return Z_OK;\n            }\n        }\n    }\n    Assert(strm->avail_out > 0, \"bug2\");\n\n    if (flush != Z_FINISH) return Z_OK;\n    if (s->wrap <= 0) return Z_STREAM_END;\n\n    /* Write the trailer */\n#ifdef GZIP\n    if (s->wrap == 2) {\n        put_byte(s, (Byte)(strm->adler & 0xff));\n        put_byte(s, (Byte)((strm->adler >> 8) & 0xff));\n        put_byte(s, (Byte)((strm->adler >> 16) & 0xff));\n        put_byte(s, (Byte)((strm->adler >> 24) & 0xff));\n        put_byte(s, (Byte)(strm->total_in & 0xff));\n        put_byte(s, (Byte)((strm->total_in >> 8) & 0xff));\n        put_byte(s, (Byte)((strm->total_in >> 16) & 0xff));\n        put_byte(s, (Byte)((strm->total_in >> 24) & 0xff));\n    }\n    else\n#endif\n    {\n        putShortMSB(s, (uInt)(strm->adler >> 16));\n        putShortMSB(s, (uInt)(strm->adler & 0xffff));\n    }\n    flush_pending(strm);\n    /* If avail_out is zero, the application will call deflate again\n     * to flush the rest.\n     */\n    if (s->wrap > 0) s->wrap = -s->wrap; /* write the trailer only once! */\n    return s->pending != 0 ? Z_OK : Z_STREAM_END;\n}\n\n/* ========================================================================= */\nint ZEXPORT deflateEnd (strm)\n    z_streamp strm;\n{\n    int status;\n\n    if (strm == Z_NULL || strm->state == Z_NULL) return Z_STREAM_ERROR;\n\n    status = strm->state->status;\n    if (status != INIT_STATE &&\n        status != EXTRA_STATE &&\n        status != NAME_STATE &&\n        status != COMMENT_STATE &&\n        status != HCRC_STATE &&\n        status != BUSY_STATE &&\n        status != FINISH_STATE) {\n      return Z_STREAM_ERROR;\n    }\n\n    /* Deallocate in reverse order of allocations: */\n    TRY_FREE(strm, strm->state->pending_buf);\n    TRY_FREE(strm, strm->state->head);\n    TRY_FREE(strm, strm->state->prev);\n    TRY_FREE(strm, strm->state->window);\n\n    ZFREE(strm, strm->state);\n    strm->state = Z_NULL;\n\n    return status == BUSY_STATE ? Z_DATA_ERROR : Z_OK;\n}\n\n/* =========================================================================\n * Copy the source state to the destination state.\n * To simplify the source, this is not supported for 16-bit MSDOS (which\n * doesn't have enough memory anyway to duplicate compression states).\n */\nint ZEXPORT deflateCopy (dest, source)\n    z_streamp dest;\n    z_streamp source;\n{\n#ifdef MAXSEG_64K\n    return Z_STREAM_ERROR;\n#else\n    deflate_state *ds;\n    deflate_state *ss;\n    ushf *overlay;\n\n\n    if (source == Z_NULL || dest == Z_NULL || source->state == Z_NULL) {\n        return Z_STREAM_ERROR;\n    }\n\n    ss = source->state;\n\n    zmemcpy((voidpf)dest, (voidpf)source, sizeof(z_stream));\n\n    ds = (deflate_state *) ZALLOC(dest, 1, sizeof(deflate_state));\n    if (ds == Z_NULL) return Z_MEM_ERROR;\n    dest->state = (struct internal_state FAR *) ds;\n    zmemcpy((voidpf)ds, (voidpf)ss, sizeof(deflate_state));\n    ds->strm = dest;\n\n    ds->window = (Bytef *) ZALLOC(dest, ds->w_size, 2*sizeof(Byte));\n    ds->prev   = (Posf *)  ZALLOC(dest, ds->w_size, sizeof(Pos));\n    ds->head   = (Posf *)  ZALLOC(dest, ds->hash_size, sizeof(Pos));\n    overlay = (ushf *) ZALLOC(dest, ds->lit_bufsize, sizeof(ush)+2);\n    ds->pending_buf = (uchf *) overlay;\n\n    if (ds->window == Z_NULL || ds->prev == Z_NULL || ds->head == Z_NULL ||\n        ds->pending_buf == Z_NULL) {\n        deflateEnd (dest);\n        return Z_MEM_ERROR;\n    }\n    /* following zmemcpy do not work for 16-bit MSDOS */\n    zmemcpy(ds->window, ss->window, ds->w_size * 2 * sizeof(Byte));\n    zmemcpy((voidpf)ds->prev, (voidpf)ss->prev, ds->w_size * sizeof(Pos));\n    zmemcpy((voidpf)ds->head, (voidpf)ss->head, ds->hash_size * sizeof(Pos));\n    zmemcpy(ds->pending_buf, ss->pending_buf, (uInt)ds->pending_buf_size);\n\n    ds->pending_out = ds->pending_buf + (ss->pending_out - ss->pending_buf);\n    ds->d_buf = overlay + ds->lit_bufsize/sizeof(ush);\n    ds->l_buf = ds->pending_buf + (1+sizeof(ush))*ds->lit_bufsize;\n\n    ds->l_desc.dyn_tree = ds->dyn_ltree;\n    ds->d_desc.dyn_tree = ds->dyn_dtree;\n    ds->bl_desc.dyn_tree = ds->bl_tree;\n\n    return Z_OK;\n#endif /* MAXSEG_64K */\n}\n\n/* ===========================================================================\n * Read a new buffer from the current input stream, update the adler32\n * and total number of bytes read.  All deflate() input goes through\n * this function so some applications may wish to modify it to avoid\n * allocating a large strm->next_in buffer and copying from it.\n * (See also flush_pending()).\n */\nlocal int read_buf(strm, buf, size)\n    z_streamp strm;\n    Bytef *buf;\n    unsigned size;\n{\n    unsigned len = strm->avail_in;\n\n    if (len > size) len = size;\n    if (len == 0) return 0;\n\n    strm->avail_in  -= len;\n\n    zmemcpy(buf, strm->next_in, len);\n    if (strm->state->wrap == 1) {\n        strm->adler = adler32(strm->adler, buf, len);\n    }\n#ifdef GZIP\n    else if (strm->state->wrap == 2) {\n        strm->adler = crc32(strm->adler, buf, len);\n    }\n#endif\n    strm->next_in  += len;\n    strm->total_in += len;\n\n    return (int)len;\n}\n\n/* ===========================================================================\n * Initialize the \"longest match\" routines for a new zlib stream\n */\nlocal void lm_init (s)\n    deflate_state *s;\n{\n    s->window_size = (ulg)2L*s->w_size;\n\n    CLEAR_HASH(s);\n\n    /* Set the default configuration parameters:\n     */\n    s->max_lazy_match   = configuration_table[s->level].max_lazy;\n    s->good_match       = configuration_table[s->level].good_length;\n    s->nice_match       = configuration_table[s->level].nice_length;\n    s->max_chain_length = configuration_table[s->level].max_chain;\n\n    s->strstart = 0;\n    s->block_start = 0L;\n    s->lookahead = 0;\n    s->insert = 0;\n    s->match_length = s->prev_length = MIN_MATCH-1;\n    s->match_available = 0;\n    s->ins_h = 0;\n#ifndef FASTEST\n#ifdef ASMV\n    match_init(); /* initialize the asm code */\n#endif\n#endif\n}\n\n#ifndef FASTEST\n/* ===========================================================================\n * Set match_start to the longest match starting at the given string and\n * return its length. Matches shorter or equal to prev_length are discarded,\n * in which case the result is equal to prev_length and match_start is\n * garbage.\n * IN assertions: cur_match is the head of the hash chain for the current\n *   string (strstart) and its distance is <= MAX_DIST, and prev_length >= 1\n * OUT assertion: the match length is not greater than s->lookahead.\n */\n#ifndef ASMV\n/* For 80x86 and 680x0, an optimized version will be provided in match.asm or\n * match.S. The code will be functionally equivalent.\n */\nlocal uInt longest_match(s, cur_match)\n    deflate_state *s;\n    IPos cur_match;                             /* current match */\n{\n    unsigned chain_length = s->max_chain_length;/* max hash chain length */\n    register Bytef *scan = s->window + s->strstart; /* current string */\n    register Bytef *match;                       /* matched string */\n    register int len;                           /* length of current match */\n    int best_len = s->prev_length;              /* best match length so far */\n    int nice_match = s->nice_match;             /* stop if match long enough */\n    IPos limit = s->strstart > (IPos)MAX_DIST(s) ?\n        s->strstart - (IPos)MAX_DIST(s) : NIL;\n    /* Stop when cur_match becomes <= limit. To simplify the code,\n     * we prevent matches with the string of window index 0.\n     */\n    Posf *prev = s->prev;\n    uInt wmask = s->w_mask;\n\n#ifdef UNALIGNED_OK\n    /* Compare two bytes at a time. Note: this is not always beneficial.\n     * Try with and without -DUNALIGNED_OK to check.\n     */\n    register Bytef *strend = s->window + s->strstart + MAX_MATCH - 1;\n    register ush scan_start = *(ushf*)scan;\n    register ush scan_end   = *(ushf*)(scan+best_len-1);\n#else\n    register Bytef *strend = s->window + s->strstart + MAX_MATCH;\n    register Byte scan_end1  = scan[best_len-1];\n    register Byte scan_end   = scan[best_len];\n#endif\n\n    /* The code is optimized for HASH_BITS >= 8 and MAX_MATCH-2 multiple of 16.\n     * It is easy to get rid of this optimization if necessary.\n     */\n    Assert(s->hash_bits >= 8 && MAX_MATCH == 258, \"Code too clever\");\n\n    /* Do not waste too much time if we already have a good match: */\n    if (s->prev_length >= s->good_match) {\n        chain_length >>= 2;\n    }\n    /* Do not look for matches beyond the end of the input. This is necessary\n     * to make deflate deterministic.\n     */\n    if ((uInt)nice_match > s->lookahead) nice_match = s->lookahead;\n\n    Assert((ulg)s->strstart <= s->window_size-MIN_LOOKAHEAD, \"need lookahead\");\n\n    do {\n        Assert(cur_match < s->strstart, \"no future\");\n        match = s->window + cur_match;\n\n        /* Skip to next match if the match length cannot increase\n         * or if the match length is less than 2.  Note that the checks below\n         * for insufficient lookahead only occur occasionally for performance\n         * reasons.  Therefore uninitialized memory will be accessed, and\n         * conditional jumps will be made that depend on those values.\n         * However the length of the match is limited to the lookahead, so\n         * the output of deflate is not affected by the uninitialized values.\n         */\n#if (defined(UNALIGNED_OK) && MAX_MATCH == 258)\n        /* This code assumes sizeof(unsigned short) == 2. Do not use\n         * UNALIGNED_OK if your compiler uses a different size.\n         */\n        if (*(ushf*)(match+best_len-1) != scan_end ||\n            *(ushf*)match != scan_start) continue;\n\n        /* It is not necessary to compare scan[2] and match[2] since they are\n         * always equal when the other bytes match, given that the hash keys\n         * are equal and that HASH_BITS >= 8. Compare 2 bytes at a time at\n         * strstart+3, +5, ... up to strstart+257. We check for insufficient\n         * lookahead only every 4th comparison; the 128th check will be made\n         * at strstart+257. If MAX_MATCH-2 is not a multiple of 8, it is\n         * necessary to put more guard bytes at the end of the window, or\n         * to check more often for insufficient lookahead.\n         */\n        Assert(scan[2] == match[2], \"scan[2]?\");\n        scan++, match++;\n        do {\n        } while (*(ushf*)(scan+=2) == *(ushf*)(match+=2) &&\n                 *(ushf*)(scan+=2) == *(ushf*)(match+=2) &&\n                 *(ushf*)(scan+=2) == *(ushf*)(match+=2) &&\n                 *(ushf*)(scan+=2) == *(ushf*)(match+=2) &&\n                 scan < strend);\n        /* The funny \"do {}\" generates better code on most compilers */\n\n        /* Here, scan <= window+strstart+257 */\n        Assert(scan <= s->window+(unsigned)(s->window_size-1), \"wild scan\");\n        if (*scan == *match) scan++;\n\n        len = (MAX_MATCH - 1) - (int)(strend-scan);\n        scan = strend - (MAX_MATCH-1);\n\n#else /* UNALIGNED_OK */\n\n        if (match[best_len]   != scan_end  ||\n            match[best_len-1] != scan_end1 ||\n            *match            != *scan     ||\n            *++match          != scan[1])      continue;\n\n        /* The check at best_len-1 can be removed because it will be made\n         * again later. (This heuristic is not always a win.)\n         * It is not necessary to compare scan[2] and match[2] since they\n         * are always equal when the other bytes match, given that\n         * the hash keys are equal and that HASH_BITS >= 8.\n         */\n        scan += 2, match++;\n        Assert(*scan == *match, \"match[2]?\");\n\n        /* We check for insufficient lookahead only every 8th comparison;\n         * the 256th check will be made at strstart+258.\n         */\n        do {\n        } while (*++scan == *++match && *++scan == *++match &&\n                 *++scan == *++match && *++scan == *++match &&\n                 *++scan == *++match && *++scan == *++match &&\n                 *++scan == *++match && *++scan == *++match &&\n                 scan < strend);\n\n        Assert(scan <= s->window+(unsigned)(s->window_size-1), \"wild scan\");\n\n        len = MAX_MATCH - (int)(strend - scan);\n        scan = strend - MAX_MATCH;\n\n#endif /* UNALIGNED_OK */\n\n        if (len > best_len) {\n            s->match_start = cur_match;\n            best_len = len;\n            if (len >= nice_match) break;\n#ifdef UNALIGNED_OK\n            scan_end = *(ushf*)(scan+best_len-1);\n#else\n            scan_end1  = scan[best_len-1];\n            scan_end   = scan[best_len];\n#endif\n        }\n    } while ((cur_match = prev[cur_match & wmask]) > limit\n             && --chain_length != 0);\n\n    if ((uInt)best_len <= s->lookahead) return (uInt)best_len;\n    return s->lookahead;\n}\n#endif /* ASMV */\n\n#else /* FASTEST */\n\n/* ---------------------------------------------------------------------------\n * Optimized version for FASTEST only\n */\nlocal uInt longest_match(s, cur_match)\n    deflate_state *s;\n    IPos cur_match;                             /* current match */\n{\n    register Bytef *scan = s->window + s->strstart; /* current string */\n    register Bytef *match;                       /* matched string */\n    register int len;                           /* length of current match */\n    register Bytef *strend = s->window + s->strstart + MAX_MATCH;\n\n    /* The code is optimized for HASH_BITS >= 8 and MAX_MATCH-2 multiple of 16.\n     * It is easy to get rid of this optimization if necessary.\n     */\n    Assert(s->hash_bits >= 8 && MAX_MATCH == 258, \"Code too clever\");\n\n    Assert((ulg)s->strstart <= s->window_size-MIN_LOOKAHEAD, \"need lookahead\");\n\n    Assert(cur_match < s->strstart, \"no future\");\n\n    match = s->window + cur_match;\n\n    /* Return failure if the match length is less than 2:\n     */\n    if (match[0] != scan[0] || match[1] != scan[1]) return MIN_MATCH-1;\n\n    /* The check at best_len-1 can be removed because it will be made\n     * again later. (This heuristic is not always a win.)\n     * It is not necessary to compare scan[2] and match[2] since they\n     * are always equal when the other bytes match, given that\n     * the hash keys are equal and that HASH_BITS >= 8.\n     */\n    scan += 2, match += 2;\n    Assert(*scan == *match, \"match[2]?\");\n\n    /* We check for insufficient lookahead only every 8th comparison;\n     * the 256th check will be made at strstart+258.\n     */\n    do {\n    } while (*++scan == *++match && *++scan == *++match &&\n             *++scan == *++match && *++scan == *++match &&\n             *++scan == *++match && *++scan == *++match &&\n             *++scan == *++match && *++scan == *++match &&\n             scan < strend);\n\n    Assert(scan <= s->window+(unsigned)(s->window_size-1), \"wild scan\");\n\n    len = MAX_MATCH - (int)(strend - scan);\n\n    if (len < MIN_MATCH) return MIN_MATCH - 1;\n\n    s->match_start = cur_match;\n    return (uInt)len <= s->lookahead ? (uInt)len : s->lookahead;\n}\n\n#endif /* FASTEST */\n\n#ifdef DEBUG\n/* ===========================================================================\n * Check that the match at match_start is indeed a match.\n */\nlocal void check_match(s, start, match, length)\n    deflate_state *s;\n    IPos start, match;\n    int length;\n{\n    /* check that the match is indeed a match */\n    if (zmemcmp(s->window + match,\n                s->window + start, length) != EQUAL) {\n        fprintf(stderr, \" start %u, match %u, length %d\\n\",\n                start, match, length);\n        do {\n            fprintf(stderr, \"%c%c\", s->window[match++], s->window[start++]);\n        } while (--length != 0);\n        z_error(\"invalid match\");\n    }\n    if (z_verbose > 1) {\n        fprintf(stderr,\"\\\\[%d,%d]\", start-match, length);\n        do { putc(s->window[start++], stderr); } while (--length != 0);\n    }\n}\n#else\n#  define check_match(s, start, match, length)\n#endif /* DEBUG */\n\n/* ===========================================================================\n * Fill the window when the lookahead becomes insufficient.\n * Updates strstart and lookahead.\n *\n * IN assertion: lookahead < MIN_LOOKAHEAD\n * OUT assertions: strstart <= window_size-MIN_LOOKAHEAD\n *    At least one byte has been read, or avail_in == 0; reads are\n *    performed for at least two bytes (required for the zip translate_eol\n *    option -- not supported here).\n */\nlocal void fill_window(s)\n    deflate_state *s;\n{\n    register unsigned n, m;\n    register Posf *p;\n    unsigned more;    /* Amount of free space at the end of the window. */\n    uInt wsize = s->w_size;\n\n    Assert(s->lookahead < MIN_LOOKAHEAD, \"already enough lookahead\");\n\n    do {\n        more = (unsigned)(s->window_size -(ulg)s->lookahead -(ulg)s->strstart);\n\n        /* Deal with !@#$% 64K limit: */\n        if (sizeof(int) <= 2) {\n            if (more == 0 && s->strstart == 0 && s->lookahead == 0) {\n                more = wsize;\n\n            } else if (more == (unsigned)(-1)) {\n                /* Very unlikely, but possible on 16 bit machine if\n                 * strstart == 0 && lookahead == 1 (input done a byte at time)\n                 */\n                more--;\n            }\n        }\n\n        /* If the window is almost full and there is insufficient lookahead,\n         * move the upper half to the lower one to make room in the upper half.\n         */\n        if (s->strstart >= wsize+MAX_DIST(s)) {\n\n            zmemcpy(s->window, s->window+wsize, (unsigned)wsize);\n            s->match_start -= wsize;\n            s->strstart    -= wsize; /* we now have strstart >= MAX_DIST */\n            s->block_start -= (long) wsize;\n\n            /* Slide the hash table (could be avoided with 32 bit values\n               at the expense of memory usage). We slide even when level == 0\n               to keep the hash table consistent if we switch back to level > 0\n               later. (Using level 0 permanently is not an optimal usage of\n               zlib, so we don't care about this pathological case.)\n             */\n            n = s->hash_size;\n            p = &s->head[n];\n            do {\n                m = *--p;\n                *p = (Pos)(m >= wsize ? m-wsize : NIL);\n            } while (--n);\n\n            n = wsize;\n#ifndef FASTEST\n            p = &s->prev[n];\n            do {\n                m = *--p;\n                *p = (Pos)(m >= wsize ? m-wsize : NIL);\n                /* If n is not on any hash chain, prev[n] is garbage but\n                 * its value will never be used.\n                 */\n            } while (--n);\n#endif\n            more += wsize;\n        }\n        if (s->strm->avail_in == 0) break;\n\n        /* If there was no sliding:\n         *    strstart <= WSIZE+MAX_DIST-1 && lookahead <= MIN_LOOKAHEAD - 1 &&\n         *    more == window_size - lookahead - strstart\n         * => more >= window_size - (MIN_LOOKAHEAD-1 + WSIZE + MAX_DIST-1)\n         * => more >= window_size - 2*WSIZE + 2\n         * In the BIG_MEM or MMAP case (not yet supported),\n         *   window_size == input_size + MIN_LOOKAHEAD  &&\n         *   strstart + s->lookahead <= input_size => more >= MIN_LOOKAHEAD.\n         * Otherwise, window_size == 2*WSIZE so more >= 2.\n         * If there was sliding, more >= WSIZE. So in all cases, more >= 2.\n         */\n        Assert(more >= 2, \"more < 2\");\n\n        n = read_buf(s->strm, s->window + s->strstart + s->lookahead, more);\n        s->lookahead += n;\n\n        /* Initialize the hash value now that we have some input: */\n        if (s->lookahead + s->insert >= MIN_MATCH) {\n            uInt str = s->strstart - s->insert;\n            s->ins_h = s->window[str];\n            UPDATE_HASH(s, s->ins_h, s->window[str + 1]);\n#if MIN_MATCH != 3\n            Call UPDATE_HASH() MIN_MATCH-3 more times\n#endif\n            while (s->insert) {\n                UPDATE_HASH(s, s->ins_h, s->window[str + MIN_MATCH-1]);\n#ifndef FASTEST\n                s->prev[str & s->w_mask] = s->head[s->ins_h];\n#endif\n                s->head[s->ins_h] = (Pos)str;\n                str++;\n                s->insert--;\n                if (s->lookahead + s->insert < MIN_MATCH)\n                    break;\n            }\n        }\n        /* If the whole input has less than MIN_MATCH bytes, ins_h is garbage,\n         * but this is not important since only literal bytes will be emitted.\n         */\n\n    } while (s->lookahead < MIN_LOOKAHEAD && s->strm->avail_in != 0);\n\n    /* If the WIN_INIT bytes after the end of the current data have never been\n     * written, then zero those bytes in order to avoid memory check reports of\n     * the use of uninitialized (or uninitialised as Julian writes) bytes by\n     * the longest match routines.  Update the high water mark for the next\n     * time through here.  WIN_INIT is set to MAX_MATCH since the longest match\n     * routines allow scanning to strstart + MAX_MATCH, ignoring lookahead.\n     */\n    if (s->high_water < s->window_size) {\n        ulg curr = s->strstart + (ulg)(s->lookahead);\n        ulg init;\n\n        if (s->high_water < curr) {\n            /* Previous high water mark below current data -- zero WIN_INIT\n             * bytes or up to end of window, whichever is less.\n             */\n            init = s->window_size - curr;\n            if (init > WIN_INIT)\n                init = WIN_INIT;\n            zmemzero(s->window + curr, (unsigned)init);\n            s->high_water = curr + init;\n        }\n        else if (s->high_water < (ulg)curr + WIN_INIT) {\n            /* High water mark at or above current data, but below current data\n             * plus WIN_INIT -- zero out to current data plus WIN_INIT, or up\n             * to end of window, whichever is less.\n             */\n            init = (ulg)curr + WIN_INIT - s->high_water;\n            if (init > s->window_size - s->high_water)\n                init = s->window_size - s->high_water;\n            zmemzero(s->window + s->high_water, (unsigned)init);\n            s->high_water += init;\n        }\n    }\n\n    Assert((ulg)s->strstart <= s->window_size - MIN_LOOKAHEAD,\n           \"not enough room for search\");\n}\n\n/* ===========================================================================\n * Flush the current block, with given end-of-file flag.\n * IN assertion: strstart is set to the end of the current match.\n */\n#define FLUSH_BLOCK_ONLY(s, last) { \\\n   _tr_flush_block(s, (s->block_start >= 0L ? \\\n                   (charf *)&s->window[(unsigned)s->block_start] : \\\n                   (charf *)Z_NULL), \\\n                (ulg)((long)s->strstart - s->block_start), \\\n                (last)); \\\n   s->block_start = s->strstart; \\\n   flush_pending(s->strm); \\\n   Tracev((stderr,\"[FLUSH]\")); \\\n}\n\n/* Same but force premature exit if necessary. */\n#define FLUSH_BLOCK(s, last) { \\\n   FLUSH_BLOCK_ONLY(s, last); \\\n   if (s->strm->avail_out == 0) return (last) ? finish_started : need_more; \\\n}\n\n/* ===========================================================================\n * Copy without compression as much as possible from the input stream, return\n * the current block state.\n * This function does not insert new strings in the dictionary since\n * uncompressible data is probably not useful. This function is used\n * only for the level=0 compression option.\n * NOTE: this function should be optimized to avoid extra copying from\n * window to pending_buf.\n */\nlocal block_state deflate_stored(s, flush)\n    deflate_state *s;\n    int flush;\n{\n    /* Stored blocks are limited to 0xffff bytes, pending_buf is limited\n     * to pending_buf_size, and each stored block has a 5 byte header:\n     */\n    ulg max_block_size = 0xffff;\n    ulg max_start;\n\n    if (max_block_size > s->pending_buf_size - 5) {\n        max_block_size = s->pending_buf_size - 5;\n    }\n\n    /* Copy as much as possible from input to output: */\n    for (;;) {\n        /* Fill the window as much as possible: */\n        if (s->lookahead <= 1) {\n\n            Assert(s->strstart < s->w_size+MAX_DIST(s) ||\n                   s->block_start >= (long)s->w_size, \"slide too late\");\n\n            fill_window(s);\n            if (s->lookahead == 0 && flush == Z_NO_FLUSH) return need_more;\n\n            if (s->lookahead == 0) break; /* flush the current block */\n        }\n        Assert(s->block_start >= 0L, \"block gone\");\n\n        s->strstart += s->lookahead;\n        s->lookahead = 0;\n\n        /* Emit a stored block if pending_buf will be full: */\n        max_start = s->block_start + max_block_size;\n        if (s->strstart == 0 || (ulg)s->strstart >= max_start) {\n            /* strstart == 0 is possible when wraparound on 16-bit machine */\n            s->lookahead = (uInt)(s->strstart - max_start);\n            s->strstart = (uInt)max_start;\n            FLUSH_BLOCK(s, 0);\n        }\n        /* Flush if we may have to slide, otherwise block_start may become\n         * negative and the data will be gone:\n         */\n        if (s->strstart - (uInt)s->block_start >= MAX_DIST(s)) {\n            FLUSH_BLOCK(s, 0);\n        }\n    }\n    s->insert = 0;\n    if (flush == Z_FINISH) {\n        FLUSH_BLOCK(s, 1);\n        return finish_done;\n    }\n    if ((long)s->strstart > s->block_start)\n        FLUSH_BLOCK(s, 0);\n    return block_done;\n}\n\n/* ===========================================================================\n * Compress as much as possible from the input stream, return the current\n * block state.\n * This function does not perform lazy evaluation of matches and inserts\n * new strings in the dictionary only for unmatched strings or for short\n * matches. It is used only for the fast compression options.\n */\nlocal block_state deflate_fast(s, flush)\n    deflate_state *s;\n    int flush;\n{\n    IPos hash_head;       /* head of the hash chain */\n    int bflush;           /* set if current block must be flushed */\n\n    for (;;) {\n        /* Make sure that we always have enough lookahead, except\n         * at the end of the input file. We need MAX_MATCH bytes\n         * for the next match, plus MIN_MATCH bytes to insert the\n         * string following the next match.\n         */\n        if (s->lookahead < MIN_LOOKAHEAD) {\n            fill_window(s);\n            if (s->lookahead < MIN_LOOKAHEAD && flush == Z_NO_FLUSH) {\n                return need_more;\n            }\n            if (s->lookahead == 0) break; /* flush the current block */\n        }\n\n        /* Insert the string window[strstart .. strstart+2] in the\n         * dictionary, and set hash_head to the head of the hash chain:\n         */\n        hash_head = NIL;\n        if (s->lookahead >= MIN_MATCH) {\n            INSERT_STRING(s, s->strstart, hash_head);\n        }\n\n        /* Find the longest match, discarding those <= prev_length.\n         * At this point we have always match_length < MIN_MATCH\n         */\n        if (hash_head != NIL && s->strstart - hash_head <= MAX_DIST(s)) {\n            /* To simplify the code, we prevent matches with the string\n             * of window index 0 (in particular we have to avoid a match\n             * of the string with itself at the start of the input file).\n             */\n            s->match_length = longest_match (s, hash_head);\n            /* longest_match() sets match_start */\n        }\n        if (s->match_length >= MIN_MATCH) {\n            check_match(s, s->strstart, s->match_start, s->match_length);\n\n            _tr_tally_dist(s, s->strstart - s->match_start,\n                           s->match_length - MIN_MATCH, bflush);\n\n            s->lookahead -= s->match_length;\n\n            /* Insert new strings in the hash table only if the match length\n             * is not too large. This saves time but degrades compression.\n             */\n#ifndef FASTEST\n            if (s->match_length <= s->max_insert_length &&\n                s->lookahead >= MIN_MATCH) {\n                s->match_length--; /* string at strstart already in table */\n                do {\n                    s->strstart++;\n                    INSERT_STRING(s, s->strstart, hash_head);\n                    /* strstart never exceeds WSIZE-MAX_MATCH, so there are\n                     * always MIN_MATCH bytes ahead.\n                     */\n                } while (--s->match_length != 0);\n                s->strstart++;\n            } else\n#endif\n            {\n                s->strstart += s->match_length;\n                s->match_length = 0;\n                s->ins_h = s->window[s->strstart];\n                UPDATE_HASH(s, s->ins_h, s->window[s->strstart+1]);\n#if MIN_MATCH != 3\n                Call UPDATE_HASH() MIN_MATCH-3 more times\n#endif\n                /* If lookahead < MIN_MATCH, ins_h is garbage, but it does not\n                 * matter since it will be recomputed at next deflate call.\n                 */\n            }\n        } else {\n            /* No match, output a literal byte */\n            Tracevv((stderr,\"%c\", s->window[s->strstart]));\n            _tr_tally_lit (s, s->window[s->strstart], bflush);\n            s->lookahead--;\n            s->strstart++;\n        }\n        if (bflush) FLUSH_BLOCK(s, 0);\n    }\n    s->insert = s->strstart < MIN_MATCH-1 ? s->strstart : MIN_MATCH-1;\n    if (flush == Z_FINISH) {\n        FLUSH_BLOCK(s, 1);\n        return finish_done;\n    }\n    if (s->last_lit)\n        FLUSH_BLOCK(s, 0);\n    return block_done;\n}\n\n#ifndef FASTEST\n/* ===========================================================================\n * Same as above, but achieves better compression. We use a lazy\n * evaluation for matches: a match is finally adopted only if there is\n * no better match at the next window position.\n */\nlocal block_state deflate_slow(s, flush)\n    deflate_state *s;\n    int flush;\n{\n    IPos hash_head;          /* head of hash chain */\n    int bflush;              /* set if current block must be flushed */\n\n    /* Process the input block. */\n    for (;;) {\n        /* Make sure that we always have enough lookahead, except\n         * at the end of the input file. We need MAX_MATCH bytes\n         * for the next match, plus MIN_MATCH bytes to insert the\n         * string following the next match.\n         */\n        if (s->lookahead < MIN_LOOKAHEAD) {\n            fill_window(s);\n            if (s->lookahead < MIN_LOOKAHEAD && flush == Z_NO_FLUSH) {\n                return need_more;\n            }\n            if (s->lookahead == 0) break; /* flush the current block */\n        }\n\n        /* Insert the string window[strstart .. strstart+2] in the\n         * dictionary, and set hash_head to the head of the hash chain:\n         */\n        hash_head = NIL;\n        if (s->lookahead >= MIN_MATCH) {\n            INSERT_STRING(s, s->strstart, hash_head);\n        }\n\n        /* Find the longest match, discarding those <= prev_length.\n         */\n        s->prev_length = s->match_length, s->prev_match = s->match_start;\n        s->match_length = MIN_MATCH-1;\n\n        if (hash_head != NIL && s->prev_length < s->max_lazy_match &&\n            s->strstart - hash_head <= MAX_DIST(s)) {\n            /* To simplify the code, we prevent matches with the string\n             * of window index 0 (in particular we have to avoid a match\n             * of the string with itself at the start of the input file).\n             */\n            s->match_length = longest_match (s, hash_head);\n            /* longest_match() sets match_start */\n\n            if (s->match_length <= 5 && (s->strategy == Z_FILTERED\n#if TOO_FAR <= 32767\n                || (s->match_length == MIN_MATCH &&\n                    s->strstart - s->match_start > TOO_FAR)\n#endif\n                )) {\n\n                /* If prev_match is also MIN_MATCH, match_start is garbage\n                 * but we will ignore the current match anyway.\n                 */\n                s->match_length = MIN_MATCH-1;\n            }\n        }\n        /* If there was a match at the previous step and the current\n         * match is not better, output the previous match:\n         */\n        if (s->prev_length >= MIN_MATCH && s->match_length <= s->prev_length) {\n            uInt max_insert = s->strstart + s->lookahead - MIN_MATCH;\n            /* Do not insert strings in hash table beyond this. */\n\n            check_match(s, s->strstart-1, s->prev_match, s->prev_length);\n\n            _tr_tally_dist(s, s->strstart -1 - s->prev_match,\n                           s->prev_length - MIN_MATCH, bflush);\n\n            /* Insert in hash table all strings up to the end of the match.\n             * strstart-1 and strstart are already inserted. If there is not\n             * enough lookahead, the last two strings are not inserted in\n             * the hash table.\n             */\n            s->lookahead -= s->prev_length-1;\n            s->prev_length -= 2;\n            do {\n                if (++s->strstart <= max_insert) {\n                    INSERT_STRING(s, s->strstart, hash_head);\n                }\n            } while (--s->prev_length != 0);\n            s->match_available = 0;\n            s->match_length = MIN_MATCH-1;\n            s->strstart++;\n\n            if (bflush) FLUSH_BLOCK(s, 0);\n\n        } else if (s->match_available) {\n            /* If there was no match at the previous position, output a\n             * single literal. If there was a match but the current match\n             * is longer, truncate the previous match to a single literal.\n             */\n            Tracevv((stderr,\"%c\", s->window[s->strstart-1]));\n            _tr_tally_lit(s, s->window[s->strstart-1], bflush);\n            if (bflush) {\n                FLUSH_BLOCK_ONLY(s, 0);\n            }\n            s->strstart++;\n            s->lookahead--;\n            if (s->strm->avail_out == 0) return need_more;\n        } else {\n            /* There is no previous match to compare with, wait for\n             * the next step to decide.\n             */\n            s->match_available = 1;\n            s->strstart++;\n            s->lookahead--;\n        }\n    }\n    Assert (flush != Z_NO_FLUSH, \"no flush?\");\n    if (s->match_available) {\n        Tracevv((stderr,\"%c\", s->window[s->strstart-1]));\n        _tr_tally_lit(s, s->window[s->strstart-1], bflush);\n        s->match_available = 0;\n    }\n    s->insert = s->strstart < MIN_MATCH-1 ? s->strstart : MIN_MATCH-1;\n    if (flush == Z_FINISH) {\n        FLUSH_BLOCK(s, 1);\n        return finish_done;\n    }\n    if (s->last_lit)\n        FLUSH_BLOCK(s, 0);\n    return block_done;\n}\n#endif /* FASTEST */\n\n/* ===========================================================================\n * For Z_RLE, simply look for runs of bytes, generate matches only of distance\n * one.  Do not maintain a hash table.  (It will be regenerated if this run of\n * deflate switches away from Z_RLE.)\n */\nlocal block_state deflate_rle(s, flush)\n    deflate_state *s;\n    int flush;\n{\n    int bflush;             /* set if current block must be flushed */\n    uInt prev;              /* byte at distance one to match */\n    Bytef *scan, *strend;   /* scan goes up to strend for length of run */\n\n    for (;;) {\n        /* Make sure that we always have enough lookahead, except\n         * at the end of the input file. We need MAX_MATCH bytes\n         * for the longest run, plus one for the unrolled loop.\n         */\n        if (s->lookahead <= MAX_MATCH) {\n            fill_window(s);\n            if (s->lookahead <= MAX_MATCH && flush == Z_NO_FLUSH) {\n                return need_more;\n            }\n            if (s->lookahead == 0) break; /* flush the current block */\n        }\n\n        /* See how many times the previous byte repeats */\n        s->match_length = 0;\n        if (s->lookahead >= MIN_MATCH && s->strstart > 0) {\n            scan = s->window + s->strstart - 1;\n            prev = *scan;\n            if (prev == *++scan && prev == *++scan && prev == *++scan) {\n                strend = s->window + s->strstart + MAX_MATCH;\n                do {\n                } while (prev == *++scan && prev == *++scan &&\n                         prev == *++scan && prev == *++scan &&\n                         prev == *++scan && prev == *++scan &&\n                         prev == *++scan && prev == *++scan &&\n                         scan < strend);\n                s->match_length = MAX_MATCH - (int)(strend - scan);\n                if (s->match_length > s->lookahead)\n                    s->match_length = s->lookahead;\n            }\n            Assert(scan <= s->window+(uInt)(s->window_size-1), \"wild scan\");\n        }\n\n        /* Emit match if have run of MIN_MATCH or longer, else emit literal */\n        if (s->match_length >= MIN_MATCH) {\n            check_match(s, s->strstart, s->strstart - 1, s->match_length);\n\n            _tr_tally_dist(s, 1, s->match_length - MIN_MATCH, bflush);\n\n            s->lookahead -= s->match_length;\n            s->strstart += s->match_length;\n            s->match_length = 0;\n        } else {\n            /* No match, output a literal byte */\n            Tracevv((stderr,\"%c\", s->window[s->strstart]));\n            _tr_tally_lit (s, s->window[s->strstart], bflush);\n            s->lookahead--;\n            s->strstart++;\n        }\n        if (bflush) FLUSH_BLOCK(s, 0);\n    }\n    s->insert = 0;\n    if (flush == Z_FINISH) {\n        FLUSH_BLOCK(s, 1);\n        return finish_done;\n    }\n    if (s->last_lit)\n        FLUSH_BLOCK(s, 0);\n    return block_done;\n}\n\n/* ===========================================================================\n * For Z_HUFFMAN_ONLY, do not look for matches.  Do not maintain a hash table.\n * (It will be regenerated if this run of deflate switches away from Huffman.)\n */\nlocal block_state deflate_huff(s, flush)\n    deflate_state *s;\n    int flush;\n{\n    int bflush;             /* set if current block must be flushed */\n\n    for (;;) {\n        /* Make sure that we have a literal to write. */\n        if (s->lookahead == 0) {\n            fill_window(s);\n            if (s->lookahead == 0) {\n                if (flush == Z_NO_FLUSH)\n                    return need_more;\n                break;      /* flush the current block */\n            }\n        }\n\n        /* Output a literal byte */\n        s->match_length = 0;\n        Tracevv((stderr,\"%c\", s->window[s->strstart]));\n        _tr_tally_lit (s, s->window[s->strstart], bflush);\n        s->lookahead--;\n        s->strstart++;\n        if (bflush) FLUSH_BLOCK(s, 0);\n    }\n    s->insert = 0;\n    if (flush == Z_FINISH) {\n        FLUSH_BLOCK(s, 1);\n        return finish_done;\n    }\n    if (s->last_lit)\n        FLUSH_BLOCK(s, 0);\n    return block_done;\n}\n"
  },
  {
    "path": "external/zlib/deflate.h",
    "content": "/* deflate.h -- internal compression state\n * Copyright (C) 1995-2012 Jean-loup Gailly\n * For conditions of distribution and use, see copyright notice in zlib.h\n */\n\n/* WARNING: this file should *not* be used by applications. It is\n   part of the implementation of the compression library and is\n   subject to change. Applications should only use zlib.h.\n */\n\n/* @(#) $Id$ */\n\n#ifndef DEFLATE_H\n#define DEFLATE_H\n\n#include \"zutil.h\"\n\n/* define NO_GZIP when compiling if you want to disable gzip header and\n   trailer creation by deflate().  NO_GZIP would be used to avoid linking in\n   the crc code when it is not needed.  For shared libraries, gzip encoding\n   should be left enabled. */\n#ifndef NO_GZIP\n#  define GZIP\n#endif\n\n/* ===========================================================================\n * Internal compression state.\n */\n\n#define LENGTH_CODES 29\n/* number of length codes, not counting the special END_BLOCK code */\n\n#define LITERALS  256\n/* number of literal bytes 0..255 */\n\n#define L_CODES (LITERALS+1+LENGTH_CODES)\n/* number of Literal or Length codes, including the END_BLOCK code */\n\n#define D_CODES   30\n/* number of distance codes */\n\n#define BL_CODES  19\n/* number of codes used to transfer the bit lengths */\n\n#define HEAP_SIZE (2*L_CODES+1)\n/* maximum heap size */\n\n#define MAX_BITS 15\n/* All codes must not exceed MAX_BITS bits */\n\n#define Buf_size 16\n/* size of bit buffer in bi_buf */\n\n#define INIT_STATE    42\n#define EXTRA_STATE   69\n#define NAME_STATE    73\n#define COMMENT_STATE 91\n#define HCRC_STATE   103\n#define BUSY_STATE   113\n#define FINISH_STATE 666\n/* Stream status */\n\n\n/* Data structure describing a single value and its code string. */\ntypedef struct ct_data_s {\n    union {\n        ush  freq;       /* frequency count */\n        ush  code;       /* bit string */\n    } fc;\n    union {\n        ush  dad;        /* father node in Huffman tree */\n        ush  len;        /* length of bit string */\n    } dl;\n} FAR ct_data;\n\n#define Freq fc.freq\n#define Code fc.code\n#define Dad  dl.dad\n#define Len  dl.len\n\ntypedef struct static_tree_desc_s  static_tree_desc;\n\ntypedef struct tree_desc_s {\n    ct_data *dyn_tree;           /* the dynamic tree */\n    int     max_code;            /* largest code with non zero frequency */\n    static_tree_desc *stat_desc; /* the corresponding static tree */\n} FAR tree_desc;\n\ntypedef ush Pos;\ntypedef Pos FAR Posf;\ntypedef unsigned IPos;\n\n/* A Pos is an index in the character window. We use short instead of int to\n * save space in the various tables. IPos is used only for parameter passing.\n */\n\ntypedef struct internal_state {\n    z_streamp strm;      /* pointer back to this zlib stream */\n    int   status;        /* as the name implies */\n    Bytef *pending_buf;  /* output still pending */\n    ulg   pending_buf_size; /* size of pending_buf */\n    Bytef *pending_out;  /* next pending byte to output to the stream */\n    uInt   pending;      /* nb of bytes in the pending buffer */\n    int   wrap;          /* bit 0 true for zlib, bit 1 true for gzip */\n    gz_headerp  gzhead;  /* gzip header information to write */\n    uInt   gzindex;      /* where in extra, name, or comment */\n    Byte  method;        /* can only be DEFLATED */\n    int   last_flush;    /* value of flush param for previous deflate call */\n\n                /* used by deflate.c: */\n\n    uInt  w_size;        /* LZ77 window size (32K by default) */\n    uInt  w_bits;        /* log2(w_size)  (8..16) */\n    uInt  w_mask;        /* w_size - 1 */\n\n    Bytef *window;\n    /* Sliding window. Input bytes are read into the second half of the window,\n     * and move to the first half later to keep a dictionary of at least wSize\n     * bytes. With this organization, matches are limited to a distance of\n     * wSize-MAX_MATCH bytes, but this ensures that IO is always\n     * performed with a length multiple of the block size. Also, it limits\n     * the window size to 64K, which is quite useful on MSDOS.\n     * To do: use the user input buffer as sliding window.\n     */\n\n    ulg window_size;\n    /* Actual size of window: 2*wSize, except when the user input buffer\n     * is directly used as sliding window.\n     */\n\n    Posf *prev;\n    /* Link to older string with same hash index. To limit the size of this\n     * array to 64K, this link is maintained only for the last 32K strings.\n     * An index in this array is thus a window index modulo 32K.\n     */\n\n    Posf *head; /* Heads of the hash chains or NIL. */\n\n    uInt  ins_h;          /* hash index of string to be inserted */\n    uInt  hash_size;      /* number of elements in hash table */\n    uInt  hash_bits;      /* log2(hash_size) */\n    uInt  hash_mask;      /* hash_size-1 */\n\n    uInt  hash_shift;\n    /* Number of bits by which ins_h must be shifted at each input\n     * step. It must be such that after MIN_MATCH steps, the oldest\n     * byte no longer takes part in the hash key, that is:\n     *   hash_shift * MIN_MATCH >= hash_bits\n     */\n\n    long block_start;\n    /* Window position at the beginning of the current output block. Gets\n     * negative when the window is moved backwards.\n     */\n\n    uInt match_length;           /* length of best match */\n    IPos prev_match;             /* previous match */\n    int match_available;         /* set if previous match exists */\n    uInt strstart;               /* start of string to insert */\n    uInt match_start;            /* start of matching string */\n    uInt lookahead;              /* number of valid bytes ahead in window */\n\n    uInt prev_length;\n    /* Length of the best match at previous step. Matches not greater than this\n     * are discarded. This is used in the lazy match evaluation.\n     */\n\n    uInt max_chain_length;\n    /* To speed up deflation, hash chains are never searched beyond this\n     * length.  A higher limit improves compression ratio but degrades the\n     * speed.\n     */\n\n    uInt max_lazy_match;\n    /* Attempt to find a better match only when the current match is strictly\n     * smaller than this value. This mechanism is used only for compression\n     * levels >= 4.\n     */\n#   define max_insert_length  max_lazy_match\n    /* Insert new strings in the hash table only if the match length is not\n     * greater than this length. This saves time but degrades compression.\n     * max_insert_length is used only for compression levels <= 3.\n     */\n\n    int level;    /* compression level (1..9) */\n    int strategy; /* favor or force Huffman coding*/\n\n    uInt good_match;\n    /* Use a faster search when the previous match is longer than this */\n\n    int nice_match; /* Stop searching when current match exceeds this */\n\n                /* used by trees.c: */\n    /* Didn't use ct_data typedef below to suppress compiler warning */\n    struct ct_data_s dyn_ltree[HEAP_SIZE];   /* literal and length tree */\n    struct ct_data_s dyn_dtree[2*D_CODES+1]; /* distance tree */\n    struct ct_data_s bl_tree[2*BL_CODES+1];  /* Huffman tree for bit lengths */\n\n    struct tree_desc_s l_desc;               /* desc. for literal tree */\n    struct tree_desc_s d_desc;               /* desc. for distance tree */\n    struct tree_desc_s bl_desc;              /* desc. for bit length tree */\n\n    ush bl_count[MAX_BITS+1];\n    /* number of codes at each bit length for an optimal tree */\n\n    int heap[2*L_CODES+1];      /* heap used to build the Huffman trees */\n    int heap_len;               /* number of elements in the heap */\n    int heap_max;               /* element of largest frequency */\n    /* The sons of heap[n] are heap[2*n] and heap[2*n+1]. heap[0] is not used.\n     * The same heap array is used to build all trees.\n     */\n\n    uch depth[2*L_CODES+1];\n    /* Depth of each subtree used as tie breaker for trees of equal frequency\n     */\n\n    uchf *l_buf;          /* buffer for literals or lengths */\n\n    uInt  lit_bufsize;\n    /* Size of match buffer for literals/lengths.  There are 4 reasons for\n     * limiting lit_bufsize to 64K:\n     *   - frequencies can be kept in 16 bit counters\n     *   - if compression is not successful for the first block, all input\n     *     data is still in the window so we can still emit a stored block even\n     *     when input comes from standard input.  (This can also be done for\n     *     all blocks if lit_bufsize is not greater than 32K.)\n     *   - if compression is not successful for a file smaller than 64K, we can\n     *     even emit a stored file instead of a stored block (saving 5 bytes).\n     *     This is applicable only for zip (not gzip or zlib).\n     *   - creating new Huffman trees less frequently may not provide fast\n     *     adaptation to changes in the input data statistics. (Take for\n     *     example a binary file with poorly compressible code followed by\n     *     a highly compressible string table.) Smaller buffer sizes give\n     *     fast adaptation but have of course the overhead of transmitting\n     *     trees more frequently.\n     *   - I can't count above 4\n     */\n\n    uInt last_lit;      /* running index in l_buf */\n\n    ushf *d_buf;\n    /* Buffer for distances. To simplify the code, d_buf and l_buf have\n     * the same number of elements. To use different lengths, an extra flag\n     * array would be necessary.\n     */\n\n    ulg opt_len;        /* bit length of current block with optimal trees */\n    ulg static_len;     /* bit length of current block with static trees */\n    uInt matches;       /* number of string matches in current block */\n    uInt insert;        /* bytes at end of window left to insert */\n\n#ifdef DEBUG\n    ulg compressed_len; /* total bit length of compressed file mod 2^32 */\n    ulg bits_sent;      /* bit length of compressed data sent mod 2^32 */\n#endif\n\n    ush bi_buf;\n    /* Output buffer. bits are inserted starting at the bottom (least\n     * significant bits).\n     */\n    int bi_valid;\n    /* Number of valid bits in bi_buf.  All bits above the last valid bit\n     * are always zero.\n     */\n\n    ulg high_water;\n    /* High water mark offset in window for initialized bytes -- bytes above\n     * this are set to zero in order to avoid memory check warnings when\n     * longest match routines access bytes past the input.  This is then\n     * updated to the new high water mark.\n     */\n\n} FAR deflate_state;\n\n/* Output a byte on the stream.\n * IN assertion: there is enough room in pending_buf.\n */\n#define put_byte(s, c) {s->pending_buf[s->pending++] = (c);}\n\n\n#define MIN_LOOKAHEAD (MAX_MATCH+MIN_MATCH+1)\n/* Minimum amount of lookahead, except at the end of the input file.\n * See deflate.c for comments about the MIN_MATCH+1.\n */\n\n#define MAX_DIST(s)  ((s)->w_size-MIN_LOOKAHEAD)\n/* In order to simplify the code, particularly on 16 bit machines, match\n * distances are limited to MAX_DIST instead of WSIZE.\n */\n\n#define WIN_INIT MAX_MATCH\n/* Number of bytes after end of data in window to initialize in order to avoid\n   memory checker errors from longest match routines */\n\n        /* in trees.c */\nvoid ZLIB_INTERNAL _tr_init OF((deflate_state *s));\nint ZLIB_INTERNAL _tr_tally OF((deflate_state *s, unsigned dist, unsigned lc));\nvoid ZLIB_INTERNAL _tr_flush_block OF((deflate_state *s, charf *buf,\n                        ulg stored_len, int last));\nvoid ZLIB_INTERNAL _tr_flush_bits OF((deflate_state *s));\nvoid ZLIB_INTERNAL _tr_align OF((deflate_state *s));\nvoid ZLIB_INTERNAL _tr_stored_block OF((deflate_state *s, charf *buf,\n                        ulg stored_len, int last));\n\n#define d_code(dist) \\\n   ((dist) < 256 ? _dist_code[dist] : _dist_code[256+((dist)>>7)])\n/* Mapping from a distance to a distance code. dist is the distance - 1 and\n * must not have side effects. _dist_code[256] and _dist_code[257] are never\n * used.\n */\n\n#ifndef DEBUG\n/* Inline versions of _tr_tally for speed: */\n\n#if defined(GEN_TREES_H) || !defined(STDC)\n  extern uch ZLIB_INTERNAL _length_code[];\n  extern uch ZLIB_INTERNAL _dist_code[];\n#else\n  extern const uch ZLIB_INTERNAL _length_code[];\n  extern const uch ZLIB_INTERNAL _dist_code[];\n#endif\n\n# define _tr_tally_lit(s, c, flush) \\\n  { uch cc = (c); \\\n    s->d_buf[s->last_lit] = 0; \\\n    s->l_buf[s->last_lit++] = cc; \\\n    s->dyn_ltree[cc].Freq++; \\\n    flush = (s->last_lit == s->lit_bufsize-1); \\\n   }\n# define _tr_tally_dist(s, distance, length, flush) \\\n  { uch len = (length); \\\n    ush dist = (distance); \\\n    s->d_buf[s->last_lit] = dist; \\\n    s->l_buf[s->last_lit++] = len; \\\n    dist--; \\\n    s->dyn_ltree[_length_code[len]+LITERALS+1].Freq++; \\\n    s->dyn_dtree[d_code(dist)].Freq++; \\\n    flush = (s->last_lit == s->lit_bufsize-1); \\\n  }\n#else\n# define _tr_tally_lit(s, c, flush) flush = _tr_tally(s, 0, c)\n# define _tr_tally_dist(s, distance, length, flush) \\\n              flush = _tr_tally(s, distance, length)\n#endif\n\n#endif /* DEFLATE_H */\n"
  },
  {
    "path": "external/zlib/gzclose.c",
    "content": "/* gzclose.c -- zlib gzclose() function\n * Copyright (C) 2004, 2010 Mark Adler\n * For conditions of distribution and use, see copyright notice in zlib.h\n */\n\n#include \"gzguts.h\"\n\n/* gzclose() is in a separate file so that it is linked in only if it is used.\n   That way the other gzclose functions can be used instead to avoid linking in\n   unneeded compression or decompression routines. */\nint ZEXPORT gzclose(file)\n    gzFile file;\n{\n#ifndef NO_GZCOMPRESS\n    gz_statep state;\n\n    if (file == NULL)\n        return Z_STREAM_ERROR;\n    state = (gz_statep)file;\n\n    return state->mode == GZ_READ ? gzclose_r(file) : gzclose_w(file);\n#else\n    return gzclose_r(file);\n#endif\n}\n"
  },
  {
    "path": "external/zlib/gzguts.h",
    "content": "/* gzguts.h -- zlib internal header definitions for gz* operations\n * Copyright (C) 2004, 2005, 2010, 2011, 2012, 2013 Mark Adler\n * For conditions of distribution and use, see copyright notice in zlib.h\n */\n\n#ifdef _LARGEFILE64_SOURCE\n#  ifndef _LARGEFILE_SOURCE\n#    define _LARGEFILE_SOURCE 1\n#  endif\n#  ifdef _FILE_OFFSET_BITS\n#    undef _FILE_OFFSET_BITS\n#  endif\n#endif\n\n#ifdef HAVE_HIDDEN\n#  define ZLIB_INTERNAL __attribute__((visibility (\"hidden\")))\n#else\n#  define ZLIB_INTERNAL\n#endif\n\n#include <stdio.h>\n#include \"zlib.h\"\n#ifdef STDC\n#  include <string.h>\n#  include <stdlib.h>\n#  include <limits.h>\n#endif\n#include <fcntl.h>\n\n#ifdef _WIN32\n#  include <stddef.h>\n#endif\n\n#if defined(__TURBOC__) || defined(_MSC_VER) || defined(_WIN32)\n#  include <io.h>\n#endif\n\n#ifdef WINAPI_FAMILY\n#  define open _open\n#  define read _read\n#  define write _write\n#  define close _close\n#endif\n\n#ifdef NO_DEFLATE       /* for compatibility with old definition */\n#  define NO_GZCOMPRESS\n#endif\n\n#if defined(STDC99) || (defined(__TURBOC__) && __TURBOC__ >= 0x550)\n#  ifndef HAVE_VSNPRINTF\n#    define HAVE_VSNPRINTF\n#  endif\n#endif\n\n#if defined(__CYGWIN__)\n#  ifndef HAVE_VSNPRINTF\n#    define HAVE_VSNPRINTF\n#  endif\n#endif\n\n#if defined(MSDOS) && defined(__BORLANDC__) && (BORLANDC > 0x410)\n#  ifndef HAVE_VSNPRINTF\n#    define HAVE_VSNPRINTF\n#  endif\n#endif\n\n#ifndef HAVE_VSNPRINTF\n#  ifdef MSDOS\n/* vsnprintf may exist on some MS-DOS compilers (DJGPP?),\n   but for now we just assume it doesn't. */\n#    define NO_vsnprintf\n#  endif\n#  ifdef __TURBOC__\n#    define NO_vsnprintf\n#  endif\n#  ifdef WIN32\n/* In Win32, vsnprintf is available as the \"non-ANSI\" _vsnprintf. */\n#    if !defined(vsnprintf) && !defined(NO_vsnprintf)\n#      if !defined(_MSC_VER) || ( defined(_MSC_VER) && _MSC_VER < 1500 )\n#         define vsnprintf _vsnprintf\n#      endif\n#    endif\n#  endif\n#  ifdef __SASC\n#    define NO_vsnprintf\n#  endif\n#  ifdef VMS\n#    define NO_vsnprintf\n#  endif\n#  ifdef __OS400__\n#    define NO_vsnprintf\n#  endif\n#  ifdef __MVS__\n#    define NO_vsnprintf\n#  endif\n#endif\n\n/* unlike snprintf (which is required in C99, yet still not supported by\n   Microsoft more than a decade later!), _snprintf does not guarantee null\n   termination of the result -- however this is only used in gzlib.c where\n   the result is assured to fit in the space provided */\n#ifdef _MSC_VER\n#  define snprintf _snprintf\n#endif\n\n#ifndef local\n#  define local static\n#endif\n/* compile with -Dlocal if your debugger can't find static symbols */\n\n/* gz* functions always use library allocation functions */\n#ifndef STDC\n  extern voidp  malloc OF((uInt size));\n  extern void   free   OF((voidpf ptr));\n#endif\n\n/* get errno and strerror definition */\n#if defined UNDER_CE\n#  include <windows.h>\n#  define zstrerror() gz_strwinerror((DWORD)GetLastError())\n#else\n#  ifndef NO_STRERROR\n#    include <errno.h>\n#    define zstrerror() strerror(errno)\n#  else\n#    define zstrerror() \"stdio error (consult errno)\"\n#  endif\n#endif\n\n/* provide prototypes for these when building zlib without LFS */\n#if !defined(_LARGEFILE64_SOURCE) || _LFS64_LARGEFILE-0 == 0\n    ZEXTERN gzFile ZEXPORT gzopen64 OF((const char *, const char *));\n    ZEXTERN z_off64_t ZEXPORT gzseek64 OF((gzFile, z_off64_t, int));\n    ZEXTERN z_off64_t ZEXPORT gztell64 OF((gzFile));\n    ZEXTERN z_off64_t ZEXPORT gzoffset64 OF((gzFile));\n#endif\n\n/* default memLevel */\n#if MAX_MEM_LEVEL >= 8\n#  define DEF_MEM_LEVEL 8\n#else\n#  define DEF_MEM_LEVEL  MAX_MEM_LEVEL\n#endif\n\n/* default i/o buffer size -- double this for output when reading (this and\n   twice this must be able to fit in an unsigned type) */\n#define GZBUFSIZE 8192\n\n/* gzip modes, also provide a little integrity check on the passed structure */\n#define GZ_NONE 0\n#define GZ_READ 7247\n#define GZ_WRITE 31153\n#define GZ_APPEND 1     /* mode set to GZ_WRITE after the file is opened */\n\n/* values for gz_state how */\n#define LOOK 0      /* look for a gzip header */\n#define COPY 1      /* copy input directly */\n#define GZIP 2      /* decompress a gzip stream */\n\n/* internal gzip file state data structure */\ntypedef struct {\n        /* exposed contents for gzgetc() macro */\n    struct gzFile_s x;      /* \"x\" for exposed */\n                            /* x.have: number of bytes available at x.next */\n                            /* x.next: next output data to deliver or write */\n                            /* x.pos: current position in uncompressed data */\n        /* used for both reading and writing */\n    int mode;               /* see gzip modes above */\n    int fd;                 /* file descriptor */\n    char *path;             /* path or fd for error messages */\n    unsigned size;          /* buffer size, zero if not allocated yet */\n    unsigned want;          /* requested buffer size, default is GZBUFSIZE */\n    unsigned char *in;      /* input buffer */\n    unsigned char *out;     /* output buffer (double-sized when reading) */\n    int direct;             /* 0 if processing gzip, 1 if transparent */\n        /* just for reading */\n    int how;                /* 0: get header, 1: copy, 2: decompress */\n    z_off64_t start;        /* where the gzip data started, for rewinding */\n    int eof;                /* true if end of input file reached */\n    int past;               /* true if read requested past end */\n        /* just for writing */\n    int level;              /* compression level */\n    int strategy;           /* compression strategy */\n        /* seek request */\n    z_off64_t skip;         /* amount to skip (already rewound if backwards) */\n    int seek;               /* true if seek request pending */\n        /* error information */\n    int err;                /* error code */\n    char *msg;              /* error message */\n        /* zlib inflate or deflate stream */\n    z_stream strm;          /* stream structure in-place (not a pointer) */\n} gz_state;\ntypedef gz_state FAR *gz_statep;\n\n/* shared functions */\nvoid ZLIB_INTERNAL gz_error OF((gz_statep, int, const char *));\n#if defined UNDER_CE\nchar ZLIB_INTERNAL *gz_strwinerror OF((DWORD error));\n#endif\n\n/* GT_OFF(x), where x is an unsigned value, is true if x > maximum z_off64_t\n   value -- needed when comparing unsigned to z_off64_t, which is signed\n   (possible z_off64_t types off_t, off64_t, and long are all signed) */\n#ifdef INT_MAX\n#  define GT_OFF(x) (sizeof(int) == sizeof(z_off64_t) && (x) > INT_MAX)\n#else\nunsigned ZLIB_INTERNAL gz_intmax OF((void));\n#  define GT_OFF(x) (sizeof(int) == sizeof(z_off64_t) && (x) > gz_intmax())\n#endif\n"
  },
  {
    "path": "external/zlib/gzlib.c",
    "content": "/* gzlib.c -- zlib functions common to reading and writing gzip files\n * Copyright (C) 2004, 2010, 2011, 2012, 2013 Mark Adler\n * For conditions of distribution and use, see copyright notice in zlib.h\n */\n\n#include \"gzguts.h\"\n\n#if defined(_WIN32) && !defined(__BORLANDC__)\n#  define LSEEK _lseeki64\n#else\n#if defined(_LARGEFILE64_SOURCE) && _LFS64_LARGEFILE-0\n#  define LSEEK lseek64\n#else\n#  define LSEEK lseek\n#endif\n#endif\n\n/* Local functions */\nlocal void gz_reset OF((gz_statep));\nlocal gzFile gz_open OF((const void *, int, const char *));\n\n#if defined UNDER_CE\n\n/* Map the Windows error number in ERROR to a locale-dependent error message\n   string and return a pointer to it.  Typically, the values for ERROR come\n   from GetLastError.\n\n   The string pointed to shall not be modified by the application, but may be\n   overwritten by a subsequent call to gz_strwinerror\n\n   The gz_strwinerror function does not change the current setting of\n   GetLastError. */\nchar ZLIB_INTERNAL *gz_strwinerror (error)\n     DWORD error;\n{\n    static char buf[1024];\n\n    wchar_t *msgbuf;\n    DWORD lasterr = GetLastError();\n    DWORD chars = FormatMessage(FORMAT_MESSAGE_FROM_SYSTEM\n        | FORMAT_MESSAGE_ALLOCATE_BUFFER,\n        NULL,\n        error,\n        0, /* Default language */\n        (LPVOID)&msgbuf,\n        0,\n        NULL);\n    if (chars != 0) {\n        /* If there is an \\r\\n appended, zap it.  */\n        if (chars >= 2\n            && msgbuf[chars - 2] == '\\r' && msgbuf[chars - 1] == '\\n') {\n            chars -= 2;\n            msgbuf[chars] = 0;\n        }\n\n        if (chars > sizeof (buf) - 1) {\n            chars = sizeof (buf) - 1;\n            msgbuf[chars] = 0;\n        }\n\n        wcstombs(buf, msgbuf, chars + 1);\n        LocalFree(msgbuf);\n    }\n    else {\n        sprintf(buf, \"unknown win32 error (%ld)\", error);\n    }\n\n    SetLastError(lasterr);\n    return buf;\n}\n\n#endif /* UNDER_CE */\n\n/* Reset gzip file state */\nlocal void gz_reset(state)\n    gz_statep state;\n{\n    state->x.have = 0;              /* no output data available */\n    if (state->mode == GZ_READ) {   /* for reading ... */\n        state->eof = 0;             /* not at end of file */\n        state->past = 0;            /* have not read past end yet */\n        state->how = LOOK;          /* look for gzip header */\n    }\n    state->seek = 0;                /* no seek request pending */\n    gz_error(state, Z_OK, NULL);    /* clear error */\n    state->x.pos = 0;               /* no uncompressed data yet */\n    state->strm.avail_in = 0;       /* no input data yet */\n}\n\n/* Open a gzip file either by name or file descriptor. */\nlocal gzFile gz_open(path, fd, mode)\n    const void *path;\n    int fd;\n    const char *mode;\n{\n    gz_statep state;\n    size_t len;\n    int oflag;\n#ifdef O_CLOEXEC\n    int cloexec = 0;\n#endif\n#ifdef O_EXCL\n    int exclusive = 0;\n#endif\n\n    /* check input */\n    if (path == NULL)\n        return NULL;\n\n    /* allocate gzFile structure to return */\n    state = (gz_statep)malloc(sizeof(gz_state));\n    if (state == NULL)\n        return NULL;\n    state->size = 0;            /* no buffers allocated yet */\n    state->want = GZBUFSIZE;    /* requested buffer size */\n    state->msg = NULL;          /* no error message yet */\n\n    /* interpret mode */\n    state->mode = GZ_NONE;\n    state->level = Z_DEFAULT_COMPRESSION;\n    state->strategy = Z_DEFAULT_STRATEGY;\n    state->direct = 0;\n    while (*mode) {\n        if (*mode >= '0' && *mode <= '9')\n            state->level = *mode - '0';\n        else\n            switch (*mode) {\n            case 'r':\n                state->mode = GZ_READ;\n                break;\n#ifndef NO_GZCOMPRESS\n            case 'w':\n                state->mode = GZ_WRITE;\n                break;\n            case 'a':\n                state->mode = GZ_APPEND;\n                break;\n#endif\n            case '+':       /* can't read and write at the same time */\n                free(state);\n                return NULL;\n            case 'b':       /* ignore -- will request binary anyway */\n                break;\n#ifdef O_CLOEXEC\n            case 'e':\n                cloexec = 1;\n                break;\n#endif\n#ifdef O_EXCL\n            case 'x':\n                exclusive = 1;\n                break;\n#endif\n            case 'f':\n                state->strategy = Z_FILTERED;\n                break;\n            case 'h':\n                state->strategy = Z_HUFFMAN_ONLY;\n                break;\n            case 'R':\n                state->strategy = Z_RLE;\n                break;\n            case 'F':\n                state->strategy = Z_FIXED;\n                break;\n            case 'T':\n                state->direct = 1;\n                break;\n            default:        /* could consider as an error, but just ignore */\n                ;\n            }\n        mode++;\n    }\n\n    /* must provide an \"r\", \"w\", or \"a\" */\n    if (state->mode == GZ_NONE) {\n        free(state);\n        return NULL;\n    }\n\n    /* can't force transparent read */\n    if (state->mode == GZ_READ) {\n        if (state->direct) {\n            free(state);\n            return NULL;\n        }\n        state->direct = 1;      /* for empty file */\n    }\n\n    /* save the path name for error messages */\n#ifdef _WIN32\n    if (fd == -2) {\n        len = wcstombs(NULL, path, 0);\n        if (len == (size_t)-1)\n            len = 0;\n    }\n    else\n#endif\n        len = strlen((const char *)path);\n    state->path = (char *)malloc(len + 1);\n    if (state->path == NULL) {\n        free(state);\n        return NULL;\n    }\n#ifdef _WIN32\n    if (fd == -2)\n        if (len)\n            wcstombs(state->path, path, len + 1);\n        else\n            *(state->path) = 0;\n    else\n#endif\n#if !defined(NO_snprintf) && !defined(NO_vsnprintf)\n        snprintf(state->path, len + 1, \"%s\", (const char *)path);\n#else\n        strcpy(state->path, path);\n#endif\n\n    /* compute the flags for open() */\n    oflag =\n#ifdef O_LARGEFILE\n        O_LARGEFILE |\n#endif\n#ifdef O_BINARY\n        O_BINARY |\n#endif\n#ifdef O_CLOEXEC\n        (cloexec ? O_CLOEXEC : 0) |\n#endif\n        (state->mode == GZ_READ ?\n         O_RDONLY :\n         (O_WRONLY | O_CREAT |\n#ifdef O_EXCL\n          (exclusive ? O_EXCL : 0) |\n#endif\n          (state->mode == GZ_WRITE ?\n           O_TRUNC :\n           O_APPEND)));\n\n    /* open the file with the appropriate flags (or just use fd) */\n    state->fd = fd > -1 ? fd : (\n#ifdef _WIN32\n        fd == -2 ? _wopen(path, oflag, 0666) :\n#endif\n        open((const char *)path, oflag, 0666));\n    if (state->fd == -1) {\n        free(state->path);\n        free(state);\n        return NULL;\n    }\n    if (state->mode == GZ_APPEND)\n        state->mode = GZ_WRITE;         /* simplify later checks */\n\n    /* save the current position for rewinding (only if reading) */\n    if (state->mode == GZ_READ) {\n        state->start = LSEEK(state->fd, 0, SEEK_CUR);\n        if (state->start == -1) state->start = 0;\n    }\n\n    /* initialize stream */\n    gz_reset(state);\n\n    /* return stream */\n    return (gzFile)state;\n}\n\n/* -- see zlib.h -- */\ngzFile ZEXPORT gzopen(path, mode)\n    const char *path;\n    const char *mode;\n{\n    return gz_open(path, -1, mode);\n}\n\n/* -- see zlib.h -- */\ngzFile ZEXPORT gzopen64(path, mode)\n    const char *path;\n    const char *mode;\n{\n    return gz_open(path, -1, mode);\n}\n\n/* -- see zlib.h -- */\ngzFile ZEXPORT gzdopen(fd, mode)\n    int fd;\n    const char *mode;\n{\n    char *path;         /* identifier for error messages */\n    gzFile gz;\n\n    if (fd == -1 || (path = (char *)malloc(7 + 3 * sizeof(int))) == NULL)\n        return NULL;\n#if !defined(NO_snprintf) && !defined(NO_vsnprintf)\n    snprintf(path, 7 + 3 * sizeof(int), \"<fd:%d>\", fd); /* for debugging */\n#else\n    sprintf(path, \"<fd:%d>\", fd);   /* for debugging */\n#endif\n    gz = gz_open(path, fd, mode);\n    free(path);\n    return gz;\n}\n\n/* -- see zlib.h -- */\n#ifdef _WIN32\ngzFile ZEXPORT gzopen_w(path, mode)\n    const wchar_t *path;\n    const char *mode;\n{\n    return gz_open(path, -2, mode);\n}\n#endif\n\n/* -- see zlib.h -- */\nint ZEXPORT gzbuffer(file, size)\n    gzFile file;\n    unsigned size;\n{\n    gz_statep state;\n\n    /* get internal structure and check integrity */\n    if (file == NULL)\n        return -1;\n    state = (gz_statep)file;\n    if (state->mode != GZ_READ && state->mode != GZ_WRITE)\n        return -1;\n\n    /* make sure we haven't already allocated memory */\n    if (state->size != 0)\n        return -1;\n\n    /* check and set requested size */\n    if (size < 2)\n        size = 2;               /* need two bytes to check magic header */\n    state->want = size;\n    return 0;\n}\n\n/* -- see zlib.h -- */\nint ZEXPORT gzrewind(file)\n    gzFile file;\n{\n    gz_statep state;\n\n    /* get internal structure */\n    if (file == NULL)\n        return -1;\n    state = (gz_statep)file;\n\n    /* check that we're reading and that there's no error */\n    if (state->mode != GZ_READ ||\n            (state->err != Z_OK && state->err != Z_BUF_ERROR))\n        return -1;\n\n    /* back up and start over */\n    if (LSEEK(state->fd, state->start, SEEK_SET) == -1)\n        return -1;\n    gz_reset(state);\n    return 0;\n}\n\n/* -- see zlib.h -- */\nz_off64_t ZEXPORT gzseek64(file, offset, whence)\n    gzFile file;\n    z_off64_t offset;\n    int whence;\n{\n    unsigned n;\n    z_off64_t ret;\n    gz_statep state;\n\n    /* get internal structure and check integrity */\n    if (file == NULL)\n        return -1;\n    state = (gz_statep)file;\n    if (state->mode != GZ_READ && state->mode != GZ_WRITE)\n        return -1;\n\n    /* check that there's no error */\n    if (state->err != Z_OK && state->err != Z_BUF_ERROR)\n        return -1;\n\n    /* can only seek from start or relative to current position */\n    if (whence != SEEK_SET && whence != SEEK_CUR)\n        return -1;\n\n    /* normalize offset to a SEEK_CUR specification */\n    if (whence == SEEK_SET)\n        offset -= state->x.pos;\n    else if (state->seek)\n        offset += state->skip;\n    state->seek = 0;\n\n    /* if within raw area while reading, just go there */\n    if (state->mode == GZ_READ && state->how == COPY &&\n            state->x.pos + offset >= 0) {\n        ret = LSEEK(state->fd, offset - state->x.have, SEEK_CUR);\n        if (ret == -1)\n            return -1;\n        state->x.have = 0;\n        state->eof = 0;\n        state->past = 0;\n        state->seek = 0;\n        gz_error(state, Z_OK, NULL);\n        state->strm.avail_in = 0;\n        state->x.pos += offset;\n        return state->x.pos;\n    }\n\n    /* calculate skip amount, rewinding if needed for back seek when reading */\n    if (offset < 0) {\n        if (state->mode != GZ_READ)         /* writing -- can't go backwards */\n            return -1;\n        offset += state->x.pos;\n        if (offset < 0)                     /* before start of file! */\n            return -1;\n        if (gzrewind(file) == -1)           /* rewind, then skip to offset */\n            return -1;\n    }\n\n    /* if reading, skip what's in output buffer (one less gzgetc() check) */\n    if (state->mode == GZ_READ) {\n        n = GT_OFF(state->x.have) || (z_off64_t)state->x.have > offset ?\n            (unsigned)offset : state->x.have;\n        state->x.have -= n;\n        state->x.next += n;\n        state->x.pos += n;\n        offset -= n;\n    }\n\n    /* request skip (if not zero) */\n    if (offset) {\n        state->seek = 1;\n        state->skip = offset;\n    }\n    return state->x.pos + offset;\n}\n\n/* -- see zlib.h -- */\nz_off_t ZEXPORT gzseek(file, offset, whence)\n    gzFile file;\n    z_off_t offset;\n    int whence;\n{\n    z_off64_t ret;\n\n    ret = gzseek64(file, (z_off64_t)offset, whence);\n    return ret == (z_off_t)ret ? (z_off_t)ret : -1;\n}\n\n/* -- see zlib.h -- */\nz_off64_t ZEXPORT gztell64(file)\n    gzFile file;\n{\n    gz_statep state;\n\n    /* get internal structure and check integrity */\n    if (file == NULL)\n        return -1;\n    state = (gz_statep)file;\n    if (state->mode != GZ_READ && state->mode != GZ_WRITE)\n        return -1;\n\n    /* return position */\n    return state->x.pos + (state->seek ? state->skip : 0);\n}\n\n/* -- see zlib.h -- */\nz_off_t ZEXPORT gztell(file)\n    gzFile file;\n{\n    z_off64_t ret;\n\n    ret = gztell64(file);\n    return ret == (z_off_t)ret ? (z_off_t)ret : -1;\n}\n\n/* -- see zlib.h -- */\nz_off64_t ZEXPORT gzoffset64(file)\n    gzFile file;\n{\n    z_off64_t offset;\n    gz_statep state;\n\n    /* get internal structure and check integrity */\n    if (file == NULL)\n        return -1;\n    state = (gz_statep)file;\n    if (state->mode != GZ_READ && state->mode != GZ_WRITE)\n        return -1;\n\n    /* compute and return effective offset in file */\n    offset = LSEEK(state->fd, 0, SEEK_CUR);\n    if (offset == -1)\n        return -1;\n    if (state->mode == GZ_READ)             /* reading */\n        offset -= state->strm.avail_in;     /* don't count buffered input */\n    return offset;\n}\n\n/* -- see zlib.h -- */\nz_off_t ZEXPORT gzoffset(file)\n    gzFile file;\n{\n    z_off64_t ret;\n\n    ret = gzoffset64(file);\n    return ret == (z_off_t)ret ? (z_off_t)ret : -1;\n}\n\n/* -- see zlib.h -- */\nint ZEXPORT gzeof(file)\n    gzFile file;\n{\n    gz_statep state;\n\n    /* get internal structure and check integrity */\n    if (file == NULL)\n        return 0;\n    state = (gz_statep)file;\n    if (state->mode != GZ_READ && state->mode != GZ_WRITE)\n        return 0;\n\n    /* return end-of-file state */\n    return state->mode == GZ_READ ? state->past : 0;\n}\n\n/* -- see zlib.h -- */\nconst char * ZEXPORT gzerror(file, errnum)\n    gzFile file;\n    int *errnum;\n{\n    gz_statep state;\n\n    /* get internal structure and check integrity */\n    if (file == NULL)\n        return NULL;\n    state = (gz_statep)file;\n    if (state->mode != GZ_READ && state->mode != GZ_WRITE)\n        return NULL;\n\n    /* return error information */\n    if (errnum != NULL)\n        *errnum = state->err;\n    return state->err == Z_MEM_ERROR ? \"out of memory\" :\n                                       (state->msg == NULL ? \"\" : state->msg);\n}\n\n/* -- see zlib.h -- */\nvoid ZEXPORT gzclearerr(file)\n    gzFile file;\n{\n    gz_statep state;\n\n    /* get internal structure and check integrity */\n    if (file == NULL)\n        return;\n    state = (gz_statep)file;\n    if (state->mode != GZ_READ && state->mode != GZ_WRITE)\n        return;\n\n    /* clear error and end-of-file */\n    if (state->mode == GZ_READ) {\n        state->eof = 0;\n        state->past = 0;\n    }\n    gz_error(state, Z_OK, NULL);\n}\n\n/* Create an error message in allocated memory and set state->err and\n   state->msg accordingly.  Free any previous error message already there.  Do\n   not try to free or allocate space if the error is Z_MEM_ERROR (out of\n   memory).  Simply save the error message as a static string.  If there is an\n   allocation failure constructing the error message, then convert the error to\n   out of memory. */\nvoid ZLIB_INTERNAL gz_error(state, err, msg)\n    gz_statep state;\n    int err;\n    const char *msg;\n{\n    /* free previously allocated message and clear */\n    if (state->msg != NULL) {\n        if (state->err != Z_MEM_ERROR)\n            free(state->msg);\n        state->msg = NULL;\n    }\n\n    /* if fatal, set state->x.have to 0 so that the gzgetc() macro fails */\n    if (err != Z_OK && err != Z_BUF_ERROR)\n        state->x.have = 0;\n\n    /* set error code, and if no message, then done */\n    state->err = err;\n    if (msg == NULL)\n        return;\n\n    /* for an out of memory error, return literal string when requested */\n    if (err == Z_MEM_ERROR)\n        return;\n\n    /* construct error message with path */\n    if ((state->msg = (char *)malloc(strlen(state->path) + strlen(msg) + 3)) ==\n            NULL) {\n        state->err = Z_MEM_ERROR;\n        return;\n    }\n#if !defined(NO_snprintf) && !defined(NO_vsnprintf)\n    snprintf(state->msg, strlen(state->path) + strlen(msg) + 3,\n             \"%s%s%s\", state->path, \": \", msg);\n#else\n    strcpy(state->msg, state->path);\n    strcat(state->msg, \": \");\n    strcat(state->msg, msg);\n#endif\n    return;\n}\n\n#ifndef INT_MAX\n/* portably return maximum value for an int (when limits.h presumed not\n   available) -- we need to do this to cover cases where 2's complement not\n   used, since C standard permits 1's complement and sign-bit representations,\n   otherwise we could just use ((unsigned)-1) >> 1 */\nunsigned ZLIB_INTERNAL gz_intmax()\n{\n    unsigned p, q;\n\n    p = 1;\n    do {\n        q = p;\n        p <<= 1;\n        p++;\n    } while (p > q);\n    return q >> 1;\n}\n#endif\n"
  },
  {
    "path": "external/zlib/gzread.c",
    "content": "/* gzread.c -- zlib functions for reading gzip files\n * Copyright (C) 2004, 2005, 2010, 2011, 2012, 2013 Mark Adler\n * For conditions of distribution and use, see copyright notice in zlib.h\n */\n\n#include \"gzguts.h\"\n\n/* Local functions */\nlocal int gz_load OF((gz_statep, unsigned char *, unsigned, unsigned *));\nlocal int gz_avail OF((gz_statep));\nlocal int gz_look OF((gz_statep));\nlocal int gz_decomp OF((gz_statep));\nlocal int gz_fetch OF((gz_statep));\nlocal int gz_skip OF((gz_statep, z_off64_t));\n\n/* Use read() to load a buffer -- return -1 on error, otherwise 0.  Read from\n   state->fd, and update state->eof, state->err, and state->msg as appropriate.\n   This function needs to loop on read(), since read() is not guaranteed to\n   read the number of bytes requested, depending on the type of descriptor. */\nlocal int gz_load(state, buf, len, have)\n    gz_statep state;\n    unsigned char *buf;\n    unsigned len;\n    unsigned *have;\n{\n    int ret;\n\n    *have = 0;\n    do {\n        ret = read(state->fd, buf + *have, len - *have);\n        if (ret <= 0)\n            break;\n        *have += ret;\n    } while (*have < len);\n    if (ret < 0) {\n        gz_error(state, Z_ERRNO, zstrerror());\n        return -1;\n    }\n    if (ret == 0)\n        state->eof = 1;\n    return 0;\n}\n\n/* Load up input buffer and set eof flag if last data loaded -- return -1 on\n   error, 0 otherwise.  Note that the eof flag is set when the end of the input\n   file is reached, even though there may be unused data in the buffer.  Once\n   that data has been used, no more attempts will be made to read the file.\n   If strm->avail_in != 0, then the current data is moved to the beginning of\n   the input buffer, and then the remainder of the buffer is loaded with the\n   available data from the input file. */\nlocal int gz_avail(state)\n    gz_statep state;\n{\n    unsigned got;\n    z_streamp strm = &(state->strm);\n\n    if (state->err != Z_OK && state->err != Z_BUF_ERROR)\n        return -1;\n    if (state->eof == 0) {\n        if (strm->avail_in) {       /* copy what's there to the start */\n            unsigned char *p = state->in;\n            unsigned const char *q = strm->next_in;\n            unsigned n = strm->avail_in;\n            do {\n                *p++ = *q++;\n            } while (--n);\n        }\n        if (gz_load(state, state->in + strm->avail_in,\n                    state->size - strm->avail_in, &got) == -1)\n            return -1;\n        strm->avail_in += got;\n        strm->next_in = state->in;\n    }\n    return 0;\n}\n\n/* Look for gzip header, set up for inflate or copy.  state->x.have must be 0.\n   If this is the first time in, allocate required memory.  state->how will be\n   left unchanged if there is no more input data available, will be set to COPY\n   if there is no gzip header and direct copying will be performed, or it will\n   be set to GZIP for decompression.  If direct copying, then leftover input\n   data from the input buffer will be copied to the output buffer.  In that\n   case, all further file reads will be directly to either the output buffer or\n   a user buffer.  If decompressing, the inflate state will be initialized.\n   gz_look() will return 0 on success or -1 on failure. */\nlocal int gz_look(state)\n    gz_statep state;\n{\n    z_streamp strm = &(state->strm);\n\n    /* allocate read buffers and inflate memory */\n    if (state->size == 0) {\n        /* allocate buffers */\n        state->in = (unsigned char *)malloc(state->want);\n        state->out = (unsigned char *)malloc(state->want << 1);\n        if (state->in == NULL || state->out == NULL) {\n            if (state->out != NULL)\n                free(state->out);\n            if (state->in != NULL)\n                free(state->in);\n            gz_error(state, Z_MEM_ERROR, \"out of memory\");\n            return -1;\n        }\n        state->size = state->want;\n\n        /* allocate inflate memory */\n        state->strm.zalloc = Z_NULL;\n        state->strm.zfree = Z_NULL;\n        state->strm.opaque = Z_NULL;\n        state->strm.avail_in = 0;\n        state->strm.next_in = Z_NULL;\n        if (inflateInit2(&(state->strm), 15 + 16) != Z_OK) {    /* gunzip */\n            free(state->out);\n            free(state->in);\n            state->size = 0;\n            gz_error(state, Z_MEM_ERROR, \"out of memory\");\n            return -1;\n        }\n    }\n\n    /* get at least the magic bytes in the input buffer */\n    if (strm->avail_in < 2) {\n        if (gz_avail(state) == -1)\n            return -1;\n        if (strm->avail_in == 0)\n            return 0;\n    }\n\n    /* look for gzip magic bytes -- if there, do gzip decoding (note: there is\n       a logical dilemma here when considering the case of a partially written\n       gzip file, to wit, if a single 31 byte is written, then we cannot tell\n       whether this is a single-byte file, or just a partially written gzip\n       file -- for here we assume that if a gzip file is being written, then\n       the header will be written in a single operation, so that reading a\n       single byte is sufficient indication that it is not a gzip file) */\n    if (strm->avail_in > 1 &&\n            strm->next_in[0] == 31 && strm->next_in[1] == 139) {\n        inflateReset(strm);\n        state->how = GZIP;\n        state->direct = 0;\n        return 0;\n    }\n\n    /* no gzip header -- if we were decoding gzip before, then this is trailing\n       garbage.  Ignore the trailing garbage and finish. */\n    if (state->direct == 0) {\n        strm->avail_in = 0;\n        state->eof = 1;\n        state->x.have = 0;\n        return 0;\n    }\n\n    /* doing raw i/o, copy any leftover input to output -- this assumes that\n       the output buffer is larger than the input buffer, which also assures\n       space for gzungetc() */\n    state->x.next = state->out;\n    if (strm->avail_in) {\n        memcpy(state->x.next, strm->next_in, strm->avail_in);\n        state->x.have = strm->avail_in;\n        strm->avail_in = 0;\n    }\n    state->how = COPY;\n    state->direct = 1;\n    return 0;\n}\n\n/* Decompress from input to the provided next_out and avail_out in the state.\n   On return, state->x.have and state->x.next point to the just decompressed\n   data.  If the gzip stream completes, state->how is reset to LOOK to look for\n   the next gzip stream or raw data, once state->x.have is depleted.  Returns 0\n   on success, -1 on failure. */\nlocal int gz_decomp(state)\n    gz_statep state;\n{\n    int ret = Z_OK;\n    unsigned had;\n    z_streamp strm = &(state->strm);\n\n    /* fill output buffer up to end of deflate stream */\n    had = strm->avail_out;\n    do {\n        /* get more input for inflate() */\n        if (strm->avail_in == 0 && gz_avail(state) == -1)\n            return -1;\n        if (strm->avail_in == 0) {\n            gz_error(state, Z_BUF_ERROR, \"unexpected end of file\");\n            break;\n        }\n\n        /* decompress and handle errors */\n        ret = inflate(strm, Z_NO_FLUSH);\n        if (ret == Z_STREAM_ERROR || ret == Z_NEED_DICT) {\n            gz_error(state, Z_STREAM_ERROR,\n                     \"internal error: inflate stream corrupt\");\n            return -1;\n        }\n        if (ret == Z_MEM_ERROR) {\n            gz_error(state, Z_MEM_ERROR, \"out of memory\");\n            return -1;\n        }\n        if (ret == Z_DATA_ERROR) {              /* deflate stream invalid */\n            gz_error(state, Z_DATA_ERROR,\n                     strm->msg == NULL ? \"compressed data error\" : strm->msg);\n            return -1;\n        }\n    } while (strm->avail_out && ret != Z_STREAM_END);\n\n    /* update available output */\n    state->x.have = had - strm->avail_out;\n    state->x.next = strm->next_out - state->x.have;\n\n    /* if the gzip stream completed successfully, look for another */\n    if (ret == Z_STREAM_END)\n        state->how = LOOK;\n\n    /* good decompression */\n    return 0;\n}\n\n/* Fetch data and put it in the output buffer.  Assumes state->x.have is 0.\n   Data is either copied from the input file or decompressed from the input\n   file depending on state->how.  If state->how is LOOK, then a gzip header is\n   looked for to determine whether to copy or decompress.  Returns -1 on error,\n   otherwise 0.  gz_fetch() will leave state->how as COPY or GZIP unless the\n   end of the input file has been reached and all data has been processed.  */\nlocal int gz_fetch(state)\n    gz_statep state;\n{\n    z_streamp strm = &(state->strm);\n\n    do {\n        switch(state->how) {\n        case LOOK:      /* -> LOOK, COPY (only if never GZIP), or GZIP */\n            if (gz_look(state) == -1)\n                return -1;\n            if (state->how == LOOK)\n                return 0;\n            break;\n        case COPY:      /* -> COPY */\n            if (gz_load(state, state->out, state->size << 1, &(state->x.have))\n                    == -1)\n                return -1;\n            state->x.next = state->out;\n            return 0;\n        case GZIP:      /* -> GZIP or LOOK (if end of gzip stream) */\n            strm->avail_out = state->size << 1;\n            strm->next_out = state->out;\n            if (gz_decomp(state) == -1)\n                return -1;\n        }\n    } while (state->x.have == 0 && (!state->eof || strm->avail_in));\n    return 0;\n}\n\n/* Skip len uncompressed bytes of output.  Return -1 on error, 0 on success. */\nlocal int gz_skip(state, len)\n    gz_statep state;\n    z_off64_t len;\n{\n    unsigned n;\n\n    /* skip over len bytes or reach end-of-file, whichever comes first */\n    while (len)\n        /* skip over whatever is in output buffer */\n        if (state->x.have) {\n            n = GT_OFF(state->x.have) || (z_off64_t)state->x.have > len ?\n                (unsigned)len : state->x.have;\n            state->x.have -= n;\n            state->x.next += n;\n            state->x.pos += n;\n            len -= n;\n        }\n\n        /* output buffer empty -- return if we're at the end of the input */\n        else if (state->eof && state->strm.avail_in == 0)\n            break;\n\n        /* need more data to skip -- load up output buffer */\n        else {\n            /* get more output, looking for header if required */\n            if (gz_fetch(state) == -1)\n                return -1;\n        }\n    return 0;\n}\n\n/* -- see zlib.h -- */\nint ZEXPORT gzread(file, buf, len)\n    gzFile file;\n    voidp buf;\n    unsigned len;\n{\n    unsigned got, n;\n    gz_statep state;\n    z_streamp strm;\n\n    /* get internal structure */\n    if (file == NULL)\n        return -1;\n    state = (gz_statep)file;\n    strm = &(state->strm);\n\n    /* check that we're reading and that there's no (serious) error */\n    if (state->mode != GZ_READ ||\n            (state->err != Z_OK && state->err != Z_BUF_ERROR))\n        return -1;\n\n    /* since an int is returned, make sure len fits in one, otherwise return\n       with an error (this avoids the flaw in the interface) */\n    if ((int)len < 0) {\n        gz_error(state, Z_DATA_ERROR, \"requested length does not fit in int\");\n        return -1;\n    }\n\n    /* if len is zero, avoid unnecessary operations */\n    if (len == 0)\n        return 0;\n\n    /* process a skip request */\n    if (state->seek) {\n        state->seek = 0;\n        if (gz_skip(state, state->skip) == -1)\n            return -1;\n    }\n\n    /* get len bytes to buf, or less than len if at the end */\n    got = 0;\n    do {\n        /* first just try copying data from the output buffer */\n        if (state->x.have) {\n            n = state->x.have > len ? len : state->x.have;\n            memcpy(buf, state->x.next, n);\n            state->x.next += n;\n            state->x.have -= n;\n        }\n\n        /* output buffer empty -- return if we're at the end of the input */\n        else if (state->eof && strm->avail_in == 0) {\n            state->past = 1;        /* tried to read past end */\n            break;\n        }\n\n        /* need output data -- for small len or new stream load up our output\n           buffer */\n        else if (state->how == LOOK || len < (state->size << 1)) {\n            /* get more output, looking for header if required */\n            if (gz_fetch(state) == -1)\n                return -1;\n            continue;       /* no progress yet -- go back to copy above */\n            /* the copy above assures that we will leave with space in the\n               output buffer, allowing at least one gzungetc() to succeed */\n        }\n\n        /* large len -- read directly into user buffer */\n        else if (state->how == COPY) {      /* read directly */\n            if (gz_load(state, (unsigned char *)buf, len, &n) == -1)\n                return -1;\n        }\n\n        /* large len -- decompress directly into user buffer */\n        else {  /* state->how == GZIP */\n            strm->avail_out = len;\n            strm->next_out = (unsigned char *)buf;\n            if (gz_decomp(state) == -1)\n                return -1;\n            n = state->x.have;\n            state->x.have = 0;\n        }\n\n        /* update progress */\n        len -= n;\n        buf = (char *)buf + n;\n        got += n;\n        state->x.pos += n;\n    } while (len);\n\n    /* return number of bytes read into user buffer (will fit in int) */\n    return (int)got;\n}\n\n/* -- see zlib.h -- */\n#ifdef Z_PREFIX_SET\n#  undef z_gzgetc\n#else\n#  undef gzgetc\n#endif\nint ZEXPORT gzgetc(file)\n    gzFile file;\n{\n    int ret;\n    unsigned char buf[1];\n    gz_statep state;\n\n    /* get internal structure */\n    if (file == NULL)\n        return -1;\n    state = (gz_statep)file;\n\n    /* check that we're reading and that there's no (serious) error */\n    if (state->mode != GZ_READ ||\n        (state->err != Z_OK && state->err != Z_BUF_ERROR))\n        return -1;\n\n    /* try output buffer (no need to check for skip request) */\n    if (state->x.have) {\n        state->x.have--;\n        state->x.pos++;\n        return *(state->x.next)++;\n    }\n\n    /* nothing there -- try gzread() */\n    ret = gzread(file, buf, 1);\n    return ret < 1 ? -1 : buf[0];\n}\n\nint ZEXPORT gzgetc_(file)\ngzFile file;\n{\n    return gzgetc(file);\n}\n\n/* -- see zlib.h -- */\nint ZEXPORT gzungetc(c, file)\n    int c;\n    gzFile file;\n{\n    gz_statep state;\n\n    /* get internal structure */\n    if (file == NULL)\n        return -1;\n    state = (gz_statep)file;\n\n    /* check that we're reading and that there's no (serious) error */\n    if (state->mode != GZ_READ ||\n        (state->err != Z_OK && state->err != Z_BUF_ERROR))\n        return -1;\n\n    /* process a skip request */\n    if (state->seek) {\n        state->seek = 0;\n        if (gz_skip(state, state->skip) == -1)\n            return -1;\n    }\n\n    /* can't push EOF */\n    if (c < 0)\n        return -1;\n\n    /* if output buffer empty, put byte at end (allows more pushing) */\n    if (state->x.have == 0) {\n        state->x.have = 1;\n        state->x.next = state->out + (state->size << 1) - 1;\n        state->x.next[0] = c;\n        state->x.pos--;\n        state->past = 0;\n        return c;\n    }\n\n    /* if no room, give up (must have already done a gzungetc()) */\n    if (state->x.have == (state->size << 1)) {\n        gz_error(state, Z_DATA_ERROR, \"out of room to push characters\");\n        return -1;\n    }\n\n    /* slide output data if needed and insert byte before existing data */\n    if (state->x.next == state->out) {\n        unsigned char *src = state->out + state->x.have;\n        unsigned char *dest = state->out + (state->size << 1);\n        while (src > state->out)\n            *--dest = *--src;\n        state->x.next = dest;\n    }\n    state->x.have++;\n    state->x.next--;\n    state->x.next[0] = c;\n    state->x.pos--;\n    state->past = 0;\n    return c;\n}\n\n/* -- see zlib.h -- */\nchar * ZEXPORT gzgets(file, buf, len)\n    gzFile file;\n    char *buf;\n    int len;\n{\n    unsigned left, n;\n    char *str;\n    unsigned char *eol;\n    gz_statep state;\n\n    /* check parameters and get internal structure */\n    if (file == NULL || buf == NULL || len < 1)\n        return NULL;\n    state = (gz_statep)file;\n\n    /* check that we're reading and that there's no (serious) error */\n    if (state->mode != GZ_READ ||\n        (state->err != Z_OK && state->err != Z_BUF_ERROR))\n        return NULL;\n\n    /* process a skip request */\n    if (state->seek) {\n        state->seek = 0;\n        if (gz_skip(state, state->skip) == -1)\n            return NULL;\n    }\n\n    /* copy output bytes up to new line or len - 1, whichever comes first --\n       append a terminating zero to the string (we don't check for a zero in\n       the contents, let the user worry about that) */\n    str = buf;\n    left = (unsigned)len - 1;\n    if (left) do {\n        /* assure that something is in the output buffer */\n        if (state->x.have == 0 && gz_fetch(state) == -1)\n            return NULL;                /* error */\n        if (state->x.have == 0) {       /* end of file */\n            state->past = 1;            /* read past end */\n            break;                      /* return what we have */\n        }\n\n        /* look for end-of-line in current output buffer */\n        n = state->x.have > left ? left : state->x.have;\n        eol = (unsigned char *)memchr(state->x.next, '\\n', n);\n        if (eol != NULL)\n            n = (unsigned)(eol - state->x.next) + 1;\n\n        /* copy through end-of-line, or remainder if not found */\n        memcpy(buf, state->x.next, n);\n        state->x.have -= n;\n        state->x.next += n;\n        state->x.pos += n;\n        left -= n;\n        buf += n;\n    } while (left && eol == NULL);\n\n    /* return terminated string, or if nothing, end of file */\n    if (buf == str)\n        return NULL;\n    buf[0] = 0;\n    return str;\n}\n\n/* -- see zlib.h -- */\nint ZEXPORT gzdirect(file)\n    gzFile file;\n{\n    gz_statep state;\n\n    /* get internal structure */\n    if (file == NULL)\n        return 0;\n    state = (gz_statep)file;\n\n    /* if the state is not known, but we can find out, then do so (this is\n       mainly for right after a gzopen() or gzdopen()) */\n    if (state->mode == GZ_READ && state->how == LOOK && state->x.have == 0)\n        (void)gz_look(state);\n\n    /* return 1 if transparent, 0 if processing a gzip stream */\n    return state->direct;\n}\n\n/* -- see zlib.h -- */\nint ZEXPORT gzclose_r(file)\n    gzFile file;\n{\n    int ret, err;\n    gz_statep state;\n\n    /* get internal structure */\n    if (file == NULL)\n        return Z_STREAM_ERROR;\n    state = (gz_statep)file;\n\n    /* check that we're reading */\n    if (state->mode != GZ_READ)\n        return Z_STREAM_ERROR;\n\n    /* free memory and close file */\n    if (state->size) {\n        inflateEnd(&(state->strm));\n        free(state->out);\n        free(state->in);\n    }\n    err = state->err == Z_BUF_ERROR ? Z_BUF_ERROR : Z_OK;\n    gz_error(state, Z_OK, NULL);\n    free(state->path);\n    ret = close(state->fd);\n    free(state);\n    return ret ? Z_ERRNO : err;\n}\n"
  },
  {
    "path": "external/zlib/gzwrite.c",
    "content": "/* gzwrite.c -- zlib functions for writing gzip files\n * Copyright (C) 2004, 2005, 2010, 2011, 2012, 2013 Mark Adler\n * For conditions of distribution and use, see copyright notice in zlib.h\n */\n\n#include \"gzguts.h\"\n\n/* Local functions */\nlocal int gz_init OF((gz_statep));\nlocal int gz_comp OF((gz_statep, int));\nlocal int gz_zero OF((gz_statep, z_off64_t));\n\n/* Initialize state for writing a gzip file.  Mark initialization by setting\n   state->size to non-zero.  Return -1 on failure or 0 on success. */\nlocal int gz_init(state)\n    gz_statep state;\n{\n    int ret;\n    z_streamp strm = &(state->strm);\n\n    /* allocate input buffer */\n    state->in = (unsigned char *)malloc(state->want);\n    if (state->in == NULL) {\n        gz_error(state, Z_MEM_ERROR, \"out of memory\");\n        return -1;\n    }\n\n    /* only need output buffer and deflate state if compressing */\n    if (!state->direct) {\n        /* allocate output buffer */\n        state->out = (unsigned char *)malloc(state->want);\n        if (state->out == NULL) {\n            free(state->in);\n            gz_error(state, Z_MEM_ERROR, \"out of memory\");\n            return -1;\n        }\n\n        /* allocate deflate memory, set up for gzip compression */\n        strm->zalloc = Z_NULL;\n        strm->zfree = Z_NULL;\n        strm->opaque = Z_NULL;\n        ret = deflateInit2(strm, state->level, Z_DEFLATED,\n                           MAX_WBITS + 16, DEF_MEM_LEVEL, state->strategy);\n        if (ret != Z_OK) {\n            free(state->out);\n            free(state->in);\n            gz_error(state, Z_MEM_ERROR, \"out of memory\");\n            return -1;\n        }\n    }\n\n    /* mark state as initialized */\n    state->size = state->want;\n\n    /* initialize write buffer if compressing */\n    if (!state->direct) {\n        strm->avail_out = state->size;\n        strm->next_out = state->out;\n        state->x.next = strm->next_out;\n    }\n    return 0;\n}\n\n/* Compress whatever is at avail_in and next_in and write to the output file.\n   Return -1 if there is an error writing to the output file, otherwise 0.\n   flush is assumed to be a valid deflate() flush value.  If flush is Z_FINISH,\n   then the deflate() state is reset to start a new gzip stream.  If gz->direct\n   is true, then simply write to the output file without compressing, and\n   ignore flush. */\nlocal int gz_comp(state, flush)\n    gz_statep state;\n    int flush;\n{\n    int ret, got;\n    unsigned have;\n    z_streamp strm = &(state->strm);\n\n    /* allocate memory if this is the first time through */\n    if (state->size == 0 && gz_init(state) == -1)\n        return -1;\n\n    /* write directly if requested */\n    if (state->direct) {\n        got = write(state->fd, strm->next_in, strm->avail_in);\n        if (got < 0 || (unsigned)got != strm->avail_in) {\n            gz_error(state, Z_ERRNO, zstrerror());\n            return -1;\n        }\n        strm->avail_in = 0;\n        return 0;\n    }\n\n    /* run deflate() on provided input until it produces no more output */\n    ret = Z_OK;\n    do {\n        /* write out current buffer contents if full, or if flushing, but if\n           doing Z_FINISH then don't write until we get to Z_STREAM_END */\n        if (strm->avail_out == 0 || (flush != Z_NO_FLUSH &&\n            (flush != Z_FINISH || ret == Z_STREAM_END))) {\n            have = (unsigned)(strm->next_out - state->x.next);\n            if (have && ((got = write(state->fd, state->x.next, have)) < 0 ||\n                         (unsigned)got != have)) {\n                gz_error(state, Z_ERRNO, zstrerror());\n                return -1;\n            }\n            if (strm->avail_out == 0) {\n                strm->avail_out = state->size;\n                strm->next_out = state->out;\n            }\n            state->x.next = strm->next_out;\n        }\n\n        /* compress */\n        have = strm->avail_out;\n        ret = deflate(strm, flush);\n        if (ret == Z_STREAM_ERROR) {\n            gz_error(state, Z_STREAM_ERROR,\n                      \"internal error: deflate stream corrupt\");\n            return -1;\n        }\n        have -= strm->avail_out;\n    } while (have);\n\n    /* if that completed a deflate stream, allow another to start */\n    if (flush == Z_FINISH)\n        deflateReset(strm);\n\n    /* all done, no errors */\n    return 0;\n}\n\n/* Compress len zeros to output.  Return -1 on error, 0 on success. */\nlocal int gz_zero(state, len)\n    gz_statep state;\n    z_off64_t len;\n{\n    int first;\n    unsigned n;\n    z_streamp strm = &(state->strm);\n\n    /* consume whatever's left in the input buffer */\n    if (strm->avail_in && gz_comp(state, Z_NO_FLUSH) == -1)\n        return -1;\n\n    /* compress len zeros (len guaranteed > 0) */\n    first = 1;\n    while (len) {\n        n = GT_OFF(state->size) || (z_off64_t)state->size > len ?\n            (unsigned)len : state->size;\n        if (first) {\n            memset(state->in, 0, n);\n            first = 0;\n        }\n        strm->avail_in = n;\n        strm->next_in = state->in;\n        state->x.pos += n;\n        if (gz_comp(state, Z_NO_FLUSH) == -1)\n            return -1;\n        len -= n;\n    }\n    return 0;\n}\n\n/* -- see zlib.h -- */\nint ZEXPORT gzwrite(file, buf, len)\n    gzFile file;\n    voidpc buf;\n    unsigned len;\n{\n    unsigned put = len;\n    gz_statep state;\n    z_streamp strm;\n\n    /* get internal structure */\n    if (file == NULL)\n        return 0;\n    state = (gz_statep)file;\n    strm = &(state->strm);\n\n    /* check that we're writing and that there's no error */\n    if (state->mode != GZ_WRITE || state->err != Z_OK)\n        return 0;\n\n    /* since an int is returned, make sure len fits in one, otherwise return\n       with an error (this avoids the flaw in the interface) */\n    if ((int)len < 0) {\n        gz_error(state, Z_DATA_ERROR, \"requested length does not fit in int\");\n        return 0;\n    }\n\n    /* if len is zero, avoid unnecessary operations */\n    if (len == 0)\n        return 0;\n\n    /* allocate memory if this is the first time through */\n    if (state->size == 0 && gz_init(state) == -1)\n        return 0;\n\n    /* check for seek request */\n    if (state->seek) {\n        state->seek = 0;\n        if (gz_zero(state, state->skip) == -1)\n            return 0;\n    }\n\n    /* for small len, copy to input buffer, otherwise compress directly */\n    if (len < state->size) {\n        /* copy to input buffer, compress when full */\n        do {\n            unsigned have, copy;\n\n            if (strm->avail_in == 0)\n                strm->next_in = state->in;\n            have = (unsigned)((strm->next_in + strm->avail_in) - state->in);\n            copy = state->size - have;\n            if (copy > len)\n                copy = len;\n            memcpy(state->in + have, buf, copy);\n            strm->avail_in += copy;\n            state->x.pos += copy;\n            buf = (const char *)buf + copy;\n            len -= copy;\n            if (len && gz_comp(state, Z_NO_FLUSH) == -1)\n                return 0;\n        } while (len);\n    }\n    else {\n        /* consume whatever's left in the input buffer */\n        if (strm->avail_in && gz_comp(state, Z_NO_FLUSH) == -1)\n            return 0;\n\n        /* directly compress user buffer to file */\n        strm->avail_in = len;\n        strm->next_in = (z_const Bytef *)buf;\n        state->x.pos += len;\n        if (gz_comp(state, Z_NO_FLUSH) == -1)\n            return 0;\n    }\n\n    /* input was all buffered or compressed (put will fit in int) */\n    return (int)put;\n}\n\n/* -- see zlib.h -- */\nint ZEXPORT gzputc(file, c)\n    gzFile file;\n    int c;\n{\n    unsigned have;\n    unsigned char buf[1];\n    gz_statep state;\n    z_streamp strm;\n\n    /* get internal structure */\n    if (file == NULL)\n        return -1;\n    state = (gz_statep)file;\n    strm = &(state->strm);\n\n    /* check that we're writing and that there's no error */\n    if (state->mode != GZ_WRITE || state->err != Z_OK)\n        return -1;\n\n    /* check for seek request */\n    if (state->seek) {\n        state->seek = 0;\n        if (gz_zero(state, state->skip) == -1)\n            return -1;\n    }\n\n    /* try writing to input buffer for speed (state->size == 0 if buffer not\n       initialized) */\n    if (state->size) {\n        if (strm->avail_in == 0)\n            strm->next_in = state->in;\n        have = (unsigned)((strm->next_in + strm->avail_in) - state->in);\n        if (have < state->size) {\n            state->in[have] = c;\n            strm->avail_in++;\n            state->x.pos++;\n            return c & 0xff;\n        }\n    }\n\n    /* no room in buffer or not initialized, use gz_write() */\n    buf[0] = c;\n    if (gzwrite(file, buf, 1) != 1)\n        return -1;\n    return c & 0xff;\n}\n\n/* -- see zlib.h -- */\nint ZEXPORT gzputs(file, str)\n    gzFile file;\n    const char *str;\n{\n    int ret;\n    unsigned len;\n\n    /* write string */\n    len = (unsigned)strlen(str);\n    ret = gzwrite(file, str, len);\n    return ret == 0 && len != 0 ? -1 : ret;\n}\n\n#if defined(STDC) || defined(Z_HAVE_STDARG_H)\n#include <stdarg.h>\n\n/* -- see zlib.h -- */\nint ZEXPORTVA gzvprintf(gzFile file, const char *format, va_list va)\n{\n    int size, len;\n    gz_statep state;\n    z_streamp strm;\n\n    /* get internal structure */\n    if (file == NULL)\n        return -1;\n    state = (gz_statep)file;\n    strm = &(state->strm);\n\n    /* check that we're writing and that there's no error */\n    if (state->mode != GZ_WRITE || state->err != Z_OK)\n        return 0;\n\n    /* make sure we have some buffer space */\n    if (state->size == 0 && gz_init(state) == -1)\n        return 0;\n\n    /* check for seek request */\n    if (state->seek) {\n        state->seek = 0;\n        if (gz_zero(state, state->skip) == -1)\n            return 0;\n    }\n\n    /* consume whatever's left in the input buffer */\n    if (strm->avail_in && gz_comp(state, Z_NO_FLUSH) == -1)\n        return 0;\n\n    /* do the printf() into the input buffer, put length in len */\n    size = (int)(state->size);\n    state->in[size - 1] = 0;\n#ifdef NO_vsnprintf\n#  ifdef HAS_vsprintf_void\n    (void)vsprintf((char *)(state->in), format, va);\n    for (len = 0; len < size; len++)\n        if (state->in[len] == 0) break;\n#  else\n    len = vsprintf((char *)(state->in), format, va);\n#  endif\n#else\n#  ifdef HAS_vsnprintf_void\n    (void)vsnprintf((char *)(state->in), size, format, va);\n    len = strlen((char *)(state->in));\n#  else\n    len = vsnprintf((char *)(state->in), size, format, va);\n#  endif\n#endif\n\n    /* check that printf() results fit in buffer */\n    if (len <= 0 || len >= (int)size || state->in[size - 1] != 0)\n        return 0;\n\n    /* update buffer and position, defer compression until needed */\n    strm->avail_in = (unsigned)len;\n    strm->next_in = state->in;\n    state->x.pos += len;\n    return len;\n}\n\nint ZEXPORTVA gzprintf(gzFile file, const char *format, ...)\n{\n    va_list va;\n    int ret;\n\n    va_start(va, format);\n    ret = gzvprintf(file, format, va);\n    va_end(va);\n    return ret;\n}\n\n#else /* !STDC && !Z_HAVE_STDARG_H */\n\n/* -- see zlib.h -- */\nint ZEXPORTVA gzprintf (file, format, a1, a2, a3, a4, a5, a6, a7, a8, a9, a10,\n                       a11, a12, a13, a14, a15, a16, a17, a18, a19, a20)\n    gzFile file;\n    const char *format;\n    int a1, a2, a3, a4, a5, a6, a7, a8, a9, a10,\n        a11, a12, a13, a14, a15, a16, a17, a18, a19, a20;\n{\n    int size, len;\n    gz_statep state;\n    z_streamp strm;\n\n    /* get internal structure */\n    if (file == NULL)\n        return -1;\n    state = (gz_statep)file;\n    strm = &(state->strm);\n\n    /* check that can really pass pointer in ints */\n    if (sizeof(int) != sizeof(void *))\n        return 0;\n\n    /* check that we're writing and that there's no error */\n    if (state->mode != GZ_WRITE || state->err != Z_OK)\n        return 0;\n\n    /* make sure we have some buffer space */\n    if (state->size == 0 && gz_init(state) == -1)\n        return 0;\n\n    /* check for seek request */\n    if (state->seek) {\n        state->seek = 0;\n        if (gz_zero(state, state->skip) == -1)\n            return 0;\n    }\n\n    /* consume whatever's left in the input buffer */\n    if (strm->avail_in && gz_comp(state, Z_NO_FLUSH) == -1)\n        return 0;\n\n    /* do the printf() into the input buffer, put length in len */\n    size = (int)(state->size);\n    state->in[size - 1] = 0;\n#ifdef NO_snprintf\n#  ifdef HAS_sprintf_void\n    sprintf((char *)(state->in), format, a1, a2, a3, a4, a5, a6, a7, a8,\n            a9, a10, a11, a12, a13, a14, a15, a16, a17, a18, a19, a20);\n    for (len = 0; len < size; len++)\n        if (state->in[len] == 0) break;\n#  else\n    len = sprintf((char *)(state->in), format, a1, a2, a3, a4, a5, a6, a7, a8,\n                  a9, a10, a11, a12, a13, a14, a15, a16, a17, a18, a19, a20);\n#  endif\n#else\n#  ifdef HAS_snprintf_void\n    snprintf((char *)(state->in), size, format, a1, a2, a3, a4, a5, a6, a7, a8,\n             a9, a10, a11, a12, a13, a14, a15, a16, a17, a18, a19, a20);\n    len = strlen((char *)(state->in));\n#  else\n    len = snprintf((char *)(state->in), size, format, a1, a2, a3, a4, a5, a6,\n                   a7, a8, a9, a10, a11, a12, a13, a14, a15, a16, a17, a18,\n                   a19, a20);\n#  endif\n#endif\n\n    /* check that printf() results fit in buffer */\n    if (len <= 0 || len >= (int)size || state->in[size - 1] != 0)\n        return 0;\n\n    /* update buffer and position, defer compression until needed */\n    strm->avail_in = (unsigned)len;\n    strm->next_in = state->in;\n    state->x.pos += len;\n    return len;\n}\n\n#endif\n\n/* -- see zlib.h -- */\nint ZEXPORT gzflush(file, flush)\n    gzFile file;\n    int flush;\n{\n    gz_statep state;\n\n    /* get internal structure */\n    if (file == NULL)\n        return -1;\n    state = (gz_statep)file;\n\n    /* check that we're writing and that there's no error */\n    if (state->mode != GZ_WRITE || state->err != Z_OK)\n        return Z_STREAM_ERROR;\n\n    /* check flush parameter */\n    if (flush < 0 || flush > Z_FINISH)\n        return Z_STREAM_ERROR;\n\n    /* check for seek request */\n    if (state->seek) {\n        state->seek = 0;\n        if (gz_zero(state, state->skip) == -1)\n            return -1;\n    }\n\n    /* compress remaining data with requested flush */\n    gz_comp(state, flush);\n    return state->err;\n}\n\n/* -- see zlib.h -- */\nint ZEXPORT gzsetparams(file, level, strategy)\n    gzFile file;\n    int level;\n    int strategy;\n{\n    gz_statep state;\n    z_streamp strm;\n\n    /* get internal structure */\n    if (file == NULL)\n        return Z_STREAM_ERROR;\n    state = (gz_statep)file;\n    strm = &(state->strm);\n\n    /* check that we're writing and that there's no error */\n    if (state->mode != GZ_WRITE || state->err != Z_OK)\n        return Z_STREAM_ERROR;\n\n    /* if no change is requested, then do nothing */\n    if (level == state->level && strategy == state->strategy)\n        return Z_OK;\n\n    /* check for seek request */\n    if (state->seek) {\n        state->seek = 0;\n        if (gz_zero(state, state->skip) == -1)\n            return -1;\n    }\n\n    /* change compression parameters for subsequent input */\n    if (state->size) {\n        /* flush previous input with previous parameters before changing */\n        if (strm->avail_in && gz_comp(state, Z_PARTIAL_FLUSH) == -1)\n            return state->err;\n        deflateParams(strm, level, strategy);\n    }\n    state->level = level;\n    state->strategy = strategy;\n    return Z_OK;\n}\n\n/* -- see zlib.h -- */\nint ZEXPORT gzclose_w(file)\n    gzFile file;\n{\n    int ret = Z_OK;\n    gz_statep state;\n\n    /* get internal structure */\n    if (file == NULL)\n        return Z_STREAM_ERROR;\n    state = (gz_statep)file;\n\n    /* check that we're writing */\n    if (state->mode != GZ_WRITE)\n        return Z_STREAM_ERROR;\n\n    /* check for seek request */\n    if (state->seek) {\n        state->seek = 0;\n        if (gz_zero(state, state->skip) == -1)\n            ret = state->err;\n    }\n\n    /* flush, free memory, and close file */\n    if (gz_comp(state, Z_FINISH) == -1)\n        ret = state->err;\n    if (state->size) {\n        if (!state->direct) {\n            (void)deflateEnd(&(state->strm));\n            free(state->out);\n        }\n        free(state->in);\n    }\n    gz_error(state, Z_OK, NULL);\n    free(state->path);\n    if (close(state->fd) == -1)\n        ret = Z_ERRNO;\n    free(state);\n    return ret;\n}\n"
  },
  {
    "path": "external/zlib/infback.c",
    "content": "/* infback.c -- inflate using a call-back interface\n * Copyright (C) 1995-2011 Mark Adler\n * For conditions of distribution and use, see copyright notice in zlib.h\n */\n\n/*\n   This code is largely copied from inflate.c.  Normally either infback.o or\n   inflate.o would be linked into an application--not both.  The interface\n   with inffast.c is retained so that optimized assembler-coded versions of\n   inflate_fast() can be used with either inflate.c or infback.c.\n */\n\n#include \"zutil.h\"\n#include \"inftrees.h\"\n#include \"inflate.h\"\n#include \"inffast.h\"\n\n/* function prototypes */\nlocal void fixedtables OF((struct inflate_state FAR *state));\n\n/*\n   strm provides memory allocation functions in zalloc and zfree, or\n   Z_NULL to use the library memory allocation functions.\n\n   windowBits is in the range 8..15, and window is a user-supplied\n   window and output buffer that is 2**windowBits bytes.\n */\nint ZEXPORT inflateBackInit_(strm, windowBits, window, version, stream_size)\nz_streamp strm;\nint windowBits;\nunsigned char FAR *window;\nconst char *version;\nint stream_size;\n{\n    struct inflate_state FAR *state;\n\n    if (version == Z_NULL || version[0] != ZLIB_VERSION[0] ||\n        stream_size != (int)(sizeof(z_stream)))\n        return Z_VERSION_ERROR;\n    if (strm == Z_NULL || window == Z_NULL ||\n        windowBits < 8 || windowBits > 15)\n        return Z_STREAM_ERROR;\n    strm->msg = Z_NULL;                 /* in case we return an error */\n    if (strm->zalloc == (alloc_func)0) {\n#ifdef Z_SOLO\n        return Z_STREAM_ERROR;\n#else\n        strm->zalloc = zcalloc;\n        strm->opaque = (voidpf)0;\n#endif\n    }\n    if (strm->zfree == (free_func)0)\n#ifdef Z_SOLO\n        return Z_STREAM_ERROR;\n#else\n    strm->zfree = zcfree;\n#endif\n    state = (struct inflate_state FAR *)ZALLOC(strm, 1,\n                                               sizeof(struct inflate_state));\n    if (state == Z_NULL) return Z_MEM_ERROR;\n    Tracev((stderr, \"inflate: allocated\\n\"));\n    strm->state = (struct internal_state FAR *)state;\n    state->dmax = 32768U;\n    state->wbits = windowBits;\n    state->wsize = 1U << windowBits;\n    state->window = window;\n    state->wnext = 0;\n    state->whave = 0;\n    return Z_OK;\n}\n\n/*\n   Return state with length and distance decoding tables and index sizes set to\n   fixed code decoding.  Normally this returns fixed tables from inffixed.h.\n   If BUILDFIXED is defined, then instead this routine builds the tables the\n   first time it's called, and returns those tables the first time and\n   thereafter.  This reduces the size of the code by about 2K bytes, in\n   exchange for a little execution time.  However, BUILDFIXED should not be\n   used for threaded applications, since the rewriting of the tables and virgin\n   may not be thread-safe.\n */\nlocal void fixedtables(state)\nstruct inflate_state FAR *state;\n{\n#ifdef BUILDFIXED\n    static int virgin = 1;\n    static code *lenfix, *distfix;\n    static code fixed[544];\n\n    /* build fixed huffman tables if first call (may not be thread safe) */\n    if (virgin) {\n        unsigned sym, bits;\n        static code *next;\n\n        /* literal/length table */\n        sym = 0;\n        while (sym < 144) state->lens[sym++] = 8;\n        while (sym < 256) state->lens[sym++] = 9;\n        while (sym < 280) state->lens[sym++] = 7;\n        while (sym < 288) state->lens[sym++] = 8;\n        next = fixed;\n        lenfix = next;\n        bits = 9;\n        inflate_table(LENS, state->lens, 288, &(next), &(bits), state->work);\n\n        /* distance table */\n        sym = 0;\n        while (sym < 32) state->lens[sym++] = 5;\n        distfix = next;\n        bits = 5;\n        inflate_table(DISTS, state->lens, 32, &(next), &(bits), state->work);\n\n        /* do this just once */\n        virgin = 0;\n    }\n#else /* !BUILDFIXED */\n#   include \"inffixed.h\"\n#endif /* BUILDFIXED */\n    state->lencode = lenfix;\n    state->lenbits = 9;\n    state->distcode = distfix;\n    state->distbits = 5;\n}\n\n/* Macros for inflateBack(): */\n\n/* Load returned state from inflate_fast() */\n#define LOAD() \\\n    do { \\\n        put = strm->next_out; \\\n        left = strm->avail_out; \\\n        next = strm->next_in; \\\n        have = strm->avail_in; \\\n        hold = state->hold; \\\n        bits = state->bits; \\\n    } while (0)\n\n/* Set state from registers for inflate_fast() */\n#define RESTORE() \\\n    do { \\\n        strm->next_out = put; \\\n        strm->avail_out = left; \\\n        strm->next_in = next; \\\n        strm->avail_in = have; \\\n        state->hold = hold; \\\n        state->bits = bits; \\\n    } while (0)\n\n/* Clear the input bit accumulator */\n#define INITBITS() \\\n    do { \\\n        hold = 0; \\\n        bits = 0; \\\n    } while (0)\n\n/* Assure that some input is available.  If input is requested, but denied,\n   then return a Z_BUF_ERROR from inflateBack(). */\n#define PULL() \\\n    do { \\\n        if (have == 0) { \\\n            have = in(in_desc, &next); \\\n            if (have == 0) { \\\n                next = Z_NULL; \\\n                ret = Z_BUF_ERROR; \\\n                goto inf_leave; \\\n            } \\\n        } \\\n    } while (0)\n\n/* Get a byte of input into the bit accumulator, or return from inflateBack()\n   with an error if there is no input available. */\n#define PULLBYTE() \\\n    do { \\\n        PULL(); \\\n        have--; \\\n        hold += (unsigned long)(*next++) << bits; \\\n        bits += 8; \\\n    } while (0)\n\n/* Assure that there are at least n bits in the bit accumulator.  If there is\n   not enough available input to do that, then return from inflateBack() with\n   an error. */\n#define NEEDBITS(n) \\\n    do { \\\n        while (bits < (unsigned)(n)) \\\n            PULLBYTE(); \\\n    } while (0)\n\n/* Return the low n bits of the bit accumulator (n < 16) */\n#define BITS(n) \\\n    ((unsigned)hold & ((1U << (n)) - 1))\n\n/* Remove n bits from the bit accumulator */\n#define DROPBITS(n) \\\n    do { \\\n        hold >>= (n); \\\n        bits -= (unsigned)(n); \\\n    } while (0)\n\n/* Remove zero to seven bits as needed to go to a byte boundary */\n#define BYTEBITS() \\\n    do { \\\n        hold >>= bits & 7; \\\n        bits -= bits & 7; \\\n    } while (0)\n\n/* Assure that some output space is available, by writing out the window\n   if it's full.  If the write fails, return from inflateBack() with a\n   Z_BUF_ERROR. */\n#define ROOM() \\\n    do { \\\n        if (left == 0) { \\\n            put = state->window; \\\n            left = state->wsize; \\\n            state->whave = left; \\\n            if (out(out_desc, put, left)) { \\\n                ret = Z_BUF_ERROR; \\\n                goto inf_leave; \\\n            } \\\n        } \\\n    } while (0)\n\n/*\n   strm provides the memory allocation functions and window buffer on input,\n   and provides information on the unused input on return.  For Z_DATA_ERROR\n   returns, strm will also provide an error message.\n\n   in() and out() are the call-back input and output functions.  When\n   inflateBack() needs more input, it calls in().  When inflateBack() has\n   filled the window with output, or when it completes with data in the\n   window, it calls out() to write out the data.  The application must not\n   change the provided input until in() is called again or inflateBack()\n   returns.  The application must not change the window/output buffer until\n   inflateBack() returns.\n\n   in() and out() are called with a descriptor parameter provided in the\n   inflateBack() call.  This parameter can be a structure that provides the\n   information required to do the read or write, as well as accumulated\n   information on the input and output such as totals and check values.\n\n   in() should return zero on failure.  out() should return non-zero on\n   failure.  If either in() or out() fails, than inflateBack() returns a\n   Z_BUF_ERROR.  strm->next_in can be checked for Z_NULL to see whether it\n   was in() or out() that caused in the error.  Otherwise,  inflateBack()\n   returns Z_STREAM_END on success, Z_DATA_ERROR for an deflate format\n   error, or Z_MEM_ERROR if it could not allocate memory for the state.\n   inflateBack() can also return Z_STREAM_ERROR if the input parameters\n   are not correct, i.e. strm is Z_NULL or the state was not initialized.\n */\nint ZEXPORT inflateBack(strm, in, in_desc, out, out_desc)\nz_streamp strm;\nin_func in;\nvoid FAR *in_desc;\nout_func out;\nvoid FAR *out_desc;\n{\n    struct inflate_state FAR *state;\n    z_const unsigned char FAR *next;    /* next input */\n    unsigned char FAR *put;     /* next output */\n    unsigned have, left;        /* available input and output */\n    unsigned long hold;         /* bit buffer */\n    unsigned bits;              /* bits in bit buffer */\n    unsigned copy;              /* number of stored or match bytes to copy */\n    unsigned char FAR *from;    /* where to copy match bytes from */\n    code here;                  /* current decoding table entry */\n    code last;                  /* parent table entry */\n    unsigned len;               /* length to copy for repeats, bits to drop */\n    int ret;                    /* return code */\n    static const unsigned short order[19] = /* permutation of code lengths */\n        {16, 17, 18, 0, 8, 7, 9, 6, 10, 5, 11, 4, 12, 3, 13, 2, 14, 1, 15};\n\n    /* Check that the strm exists and that the state was initialized */\n    if (strm == Z_NULL || strm->state == Z_NULL)\n        return Z_STREAM_ERROR;\n    state = (struct inflate_state FAR *)strm->state;\n\n    /* Reset the state */\n    strm->msg = Z_NULL;\n    state->mode = TYPE;\n    state->last = 0;\n    state->whave = 0;\n    next = strm->next_in;\n    have = next != Z_NULL ? strm->avail_in : 0;\n    hold = 0;\n    bits = 0;\n    put = state->window;\n    left = state->wsize;\n\n    /* Inflate until end of block marked as last */\n    for (;;)\n        switch (state->mode) {\n        case TYPE:\n            /* determine and dispatch block type */\n            if (state->last) {\n                BYTEBITS();\n                state->mode = DONE;\n                break;\n            }\n            NEEDBITS(3);\n            state->last = BITS(1);\n            DROPBITS(1);\n            switch (BITS(2)) {\n            case 0:                             /* stored block */\n                Tracev((stderr, \"inflate:     stored block%s\\n\",\n                        state->last ? \" (last)\" : \"\"));\n                state->mode = STORED;\n                break;\n            case 1:                             /* fixed block */\n                fixedtables(state);\n                Tracev((stderr, \"inflate:     fixed codes block%s\\n\",\n                        state->last ? \" (last)\" : \"\"));\n                state->mode = LEN;              /* decode codes */\n                break;\n            case 2:                             /* dynamic block */\n                Tracev((stderr, \"inflate:     dynamic codes block%s\\n\",\n                        state->last ? \" (last)\" : \"\"));\n                state->mode = TABLE;\n                break;\n            case 3:\n                strm->msg = (char *)\"invalid block type\";\n                state->mode = BAD;\n            }\n            DROPBITS(2);\n            break;\n\n        case STORED:\n            /* get and verify stored block length */\n            BYTEBITS();                         /* go to byte boundary */\n            NEEDBITS(32);\n            if ((hold & 0xffff) != ((hold >> 16) ^ 0xffff)) {\n                strm->msg = (char *)\"invalid stored block lengths\";\n                state->mode = BAD;\n                break;\n            }\n            state->length = (unsigned)hold & 0xffff;\n            Tracev((stderr, \"inflate:       stored length %u\\n\",\n                    state->length));\n            INITBITS();\n\n            /* copy stored block from input to output */\n            while (state->length != 0) {\n                copy = state->length;\n                PULL();\n                ROOM();\n                if (copy > have) copy = have;\n                if (copy > left) copy = left;\n                zmemcpy(put, next, copy);\n                have -= copy;\n                next += copy;\n                left -= copy;\n                put += copy;\n                state->length -= copy;\n            }\n            Tracev((stderr, \"inflate:       stored end\\n\"));\n            state->mode = TYPE;\n            break;\n\n        case TABLE:\n            /* get dynamic table entries descriptor */\n            NEEDBITS(14);\n            state->nlen = BITS(5) + 257;\n            DROPBITS(5);\n            state->ndist = BITS(5) + 1;\n            DROPBITS(5);\n            state->ncode = BITS(4) + 4;\n            DROPBITS(4);\n#ifndef PKZIP_BUG_WORKAROUND\n            if (state->nlen > 286 || state->ndist > 30) {\n                strm->msg = (char *)\"too many length or distance symbols\";\n                state->mode = BAD;\n                break;\n            }\n#endif\n            Tracev((stderr, \"inflate:       table sizes ok\\n\"));\n\n            /* get code length code lengths (not a typo) */\n            state->have = 0;\n            while (state->have < state->ncode) {\n                NEEDBITS(3);\n                state->lens[order[state->have++]] = (unsigned short)BITS(3);\n                DROPBITS(3);\n            }\n            while (state->have < 19)\n                state->lens[order[state->have++]] = 0;\n            state->next = state->codes;\n            state->lencode = (code const FAR *)(state->next);\n            state->lenbits = 7;\n            ret = inflate_table(CODES, state->lens, 19, &(state->next),\n                                &(state->lenbits), state->work);\n            if (ret) {\n                strm->msg = (char *)\"invalid code lengths set\";\n                state->mode = BAD;\n                break;\n            }\n            Tracev((stderr, \"inflate:       code lengths ok\\n\"));\n\n            /* get length and distance code code lengths */\n            state->have = 0;\n            while (state->have < state->nlen + state->ndist) {\n                for (;;) {\n                    here = state->lencode[BITS(state->lenbits)];\n                    if ((unsigned)(here.bits) <= bits) break;\n                    PULLBYTE();\n                }\n                if (here.val < 16) {\n                    DROPBITS(here.bits);\n                    state->lens[state->have++] = here.val;\n                }\n                else {\n                    if (here.val == 16) {\n                        NEEDBITS(here.bits + 2);\n                        DROPBITS(here.bits);\n                        if (state->have == 0) {\n                            strm->msg = (char *)\"invalid bit length repeat\";\n                            state->mode = BAD;\n                            break;\n                        }\n                        len = (unsigned)(state->lens[state->have - 1]);\n                        copy = 3 + BITS(2);\n                        DROPBITS(2);\n                    }\n                    else if (here.val == 17) {\n                        NEEDBITS(here.bits + 3);\n                        DROPBITS(here.bits);\n                        len = 0;\n                        copy = 3 + BITS(3);\n                        DROPBITS(3);\n                    }\n                    else {\n                        NEEDBITS(here.bits + 7);\n                        DROPBITS(here.bits);\n                        len = 0;\n                        copy = 11 + BITS(7);\n                        DROPBITS(7);\n                    }\n                    if (state->have + copy > state->nlen + state->ndist) {\n                        strm->msg = (char *)\"invalid bit length repeat\";\n                        state->mode = BAD;\n                        break;\n                    }\n                    while (copy--)\n                        state->lens[state->have++] = (unsigned short)len;\n                }\n            }\n\n            /* handle error breaks in while */\n            if (state->mode == BAD) break;\n\n            /* check for end-of-block code (better have one) */\n            if (state->lens[256] == 0) {\n                strm->msg = (char *)\"invalid code -- missing end-of-block\";\n                state->mode = BAD;\n                break;\n            }\n\n            /* build code tables -- note: do not change the lenbits or distbits\n               values here (9 and 6) without reading the comments in inftrees.h\n               concerning the ENOUGH constants, which depend on those values */\n            state->next = state->codes;\n            state->lencode = (code const FAR *)(state->next);\n            state->lenbits = 9;\n            ret = inflate_table(LENS, state->lens, state->nlen, &(state->next),\n                                &(state->lenbits), state->work);\n            if (ret) {\n                strm->msg = (char *)\"invalid literal/lengths set\";\n                state->mode = BAD;\n                break;\n            }\n            state->distcode = (code const FAR *)(state->next);\n            state->distbits = 6;\n            ret = inflate_table(DISTS, state->lens + state->nlen, state->ndist,\n                            &(state->next), &(state->distbits), state->work);\n            if (ret) {\n                strm->msg = (char *)\"invalid distances set\";\n                state->mode = BAD;\n                break;\n            }\n            Tracev((stderr, \"inflate:       codes ok\\n\"));\n            state->mode = LEN;\n\n        case LEN:\n            /* use inflate_fast() if we have enough input and output */\n            if (have >= 6 && left >= 258) {\n                RESTORE();\n                if (state->whave < state->wsize)\n                    state->whave = state->wsize - left;\n                inflate_fast(strm, state->wsize);\n                LOAD();\n                break;\n            }\n\n            /* get a literal, length, or end-of-block code */\n            for (;;) {\n                here = state->lencode[BITS(state->lenbits)];\n                if ((unsigned)(here.bits) <= bits) break;\n                PULLBYTE();\n            }\n            if (here.op && (here.op & 0xf0) == 0) {\n                last = here;\n                for (;;) {\n                    here = state->lencode[last.val +\n                            (BITS(last.bits + last.op) >> last.bits)];\n                    if ((unsigned)(last.bits + here.bits) <= bits) break;\n                    PULLBYTE();\n                }\n                DROPBITS(last.bits);\n            }\n            DROPBITS(here.bits);\n            state->length = (unsigned)here.val;\n\n            /* process literal */\n            if (here.op == 0) {\n                Tracevv((stderr, here.val >= 0x20 && here.val < 0x7f ?\n                        \"inflate:         literal '%c'\\n\" :\n                        \"inflate:         literal 0x%02x\\n\", here.val));\n                ROOM();\n                *put++ = (unsigned char)(state->length);\n                left--;\n                state->mode = LEN;\n                break;\n            }\n\n            /* process end of block */\n            if (here.op & 32) {\n                Tracevv((stderr, \"inflate:         end of block\\n\"));\n                state->mode = TYPE;\n                break;\n            }\n\n            /* invalid code */\n            if (here.op & 64) {\n                strm->msg = (char *)\"invalid literal/length code\";\n                state->mode = BAD;\n                break;\n            }\n\n            /* length code -- get extra bits, if any */\n            state->extra = (unsigned)(here.op) & 15;\n            if (state->extra != 0) {\n                NEEDBITS(state->extra);\n                state->length += BITS(state->extra);\n                DROPBITS(state->extra);\n            }\n            Tracevv((stderr, \"inflate:         length %u\\n\", state->length));\n\n            /* get distance code */\n            for (;;) {\n                here = state->distcode[BITS(state->distbits)];\n                if ((unsigned)(here.bits) <= bits) break;\n                PULLBYTE();\n            }\n            if ((here.op & 0xf0) == 0) {\n                last = here;\n                for (;;) {\n                    here = state->distcode[last.val +\n                            (BITS(last.bits + last.op) >> last.bits)];\n                    if ((unsigned)(last.bits + here.bits) <= bits) break;\n                    PULLBYTE();\n                }\n                DROPBITS(last.bits);\n            }\n            DROPBITS(here.bits);\n            if (here.op & 64) {\n                strm->msg = (char *)\"invalid distance code\";\n                state->mode = BAD;\n                break;\n            }\n            state->offset = (unsigned)here.val;\n\n            /* get distance extra bits, if any */\n            state->extra = (unsigned)(here.op) & 15;\n            if (state->extra != 0) {\n                NEEDBITS(state->extra);\n                state->offset += BITS(state->extra);\n                DROPBITS(state->extra);\n            }\n            if (state->offset > state->wsize - (state->whave < state->wsize ?\n                                                left : 0)) {\n                strm->msg = (char *)\"invalid distance too far back\";\n                state->mode = BAD;\n                break;\n            }\n            Tracevv((stderr, \"inflate:         distance %u\\n\", state->offset));\n\n            /* copy match from window to output */\n            do {\n                ROOM();\n                copy = state->wsize - state->offset;\n                if (copy < left) {\n                    from = put + copy;\n                    copy = left - copy;\n                }\n                else {\n                    from = put - state->offset;\n                    copy = left;\n                }\n                if (copy > state->length) copy = state->length;\n                state->length -= copy;\n                left -= copy;\n                do {\n                    *put++ = *from++;\n                } while (--copy);\n            } while (state->length != 0);\n            break;\n\n        case DONE:\n            /* inflate stream terminated properly -- write leftover output */\n            ret = Z_STREAM_END;\n            if (left < state->wsize) {\n                if (out(out_desc, state->window, state->wsize - left))\n                    ret = Z_BUF_ERROR;\n            }\n            goto inf_leave;\n\n        case BAD:\n            ret = Z_DATA_ERROR;\n            goto inf_leave;\n\n        default:                /* can't happen, but makes compilers happy */\n            ret = Z_STREAM_ERROR;\n            goto inf_leave;\n        }\n\n    /* Return unused input */\n  inf_leave:\n    strm->next_in = next;\n    strm->avail_in = have;\n    return ret;\n}\n\nint ZEXPORT inflateBackEnd(strm)\nz_streamp strm;\n{\n    if (strm == Z_NULL || strm->state == Z_NULL || strm->zfree == (free_func)0)\n        return Z_STREAM_ERROR;\n    ZFREE(strm, strm->state);\n    strm->state = Z_NULL;\n    Tracev((stderr, \"inflate: end\\n\"));\n    return Z_OK;\n}\n"
  },
  {
    "path": "external/zlib/inffast.c",
    "content": "/* inffast.c -- fast decoding\n * Copyright (C) 1995-2008, 2010, 2013 Mark Adler\n * For conditions of distribution and use, see copyright notice in zlib.h\n */\n\n#include \"zutil.h\"\n#include \"inftrees.h\"\n#include \"inflate.h\"\n#include \"inffast.h\"\n\n#ifndef ASMINF\n\n/* Allow machine dependent optimization for post-increment or pre-increment.\n   Based on testing to date,\n   Pre-increment preferred for:\n   - PowerPC G3 (Adler)\n   - MIPS R5000 (Randers-Pehrson)\n   Post-increment preferred for:\n   - none\n   No measurable difference:\n   - Pentium III (Anderson)\n   - M68060 (Nikl)\n */\n#ifdef POSTINC\n#  define OFF 0\n#  define PUP(a) *(a)++\n#else\n#  define OFF 1\n#  define PUP(a) *++(a)\n#endif\n\n/*\n   Decode literal, length, and distance codes and write out the resulting\n   literal and match bytes until either not enough input or output is\n   available, an end-of-block is encountered, or a data error is encountered.\n   When large enough input and output buffers are supplied to inflate(), for\n   example, a 16K input buffer and a 64K output buffer, more than 95% of the\n   inflate execution time is spent in this routine.\n\n   Entry assumptions:\n\n        state->mode == LEN\n        strm->avail_in >= 6\n        strm->avail_out >= 258\n        start >= strm->avail_out\n        state->bits < 8\n\n   On return, state->mode is one of:\n\n        LEN -- ran out of enough output space or enough available input\n        TYPE -- reached end of block code, inflate() to interpret next block\n        BAD -- error in block data\n\n   Notes:\n\n    - The maximum input bits used by a length/distance pair is 15 bits for the\n      length code, 5 bits for the length extra, 15 bits for the distance code,\n      and 13 bits for the distance extra.  This totals 48 bits, or six bytes.\n      Therefore if strm->avail_in >= 6, then there is enough input to avoid\n      checking for available input while decoding.\n\n    - The maximum bytes that a single length/distance pair can output is 258\n      bytes, which is the maximum length that can be coded.  inflate_fast()\n      requires strm->avail_out >= 258 for each loop to avoid checking for\n      output space.\n */\nvoid ZLIB_INTERNAL inflate_fast(strm, start)\nz_streamp strm;\nunsigned start;         /* inflate()'s starting value for strm->avail_out */\n{\n    struct inflate_state FAR *state;\n    z_const unsigned char FAR *in;      /* local strm->next_in */\n    z_const unsigned char FAR *last;    /* have enough input while in < last */\n    unsigned char FAR *out;     /* local strm->next_out */\n    unsigned char FAR *beg;     /* inflate()'s initial strm->next_out */\n    unsigned char FAR *end;     /* while out < end, enough space available */\n#ifdef INFLATE_STRICT\n    unsigned dmax;              /* maximum distance from zlib header */\n#endif\n    unsigned wsize;             /* window size or zero if not using window */\n    unsigned whave;             /* valid bytes in the window */\n    unsigned wnext;             /* window write index */\n    unsigned char FAR *window;  /* allocated sliding window, if wsize != 0 */\n    unsigned long hold;         /* local strm->hold */\n    unsigned bits;              /* local strm->bits */\n    code const FAR *lcode;      /* local strm->lencode */\n    code const FAR *dcode;      /* local strm->distcode */\n    unsigned lmask;             /* mask for first level of length codes */\n    unsigned dmask;             /* mask for first level of distance codes */\n    code here;                  /* retrieved table entry */\n    unsigned op;                /* code bits, operation, extra bits, or */\n                                /*  window position, window bytes to copy */\n    unsigned len;               /* match length, unused bytes */\n    unsigned dist;              /* match distance */\n    unsigned char FAR *from;    /* where to copy match from */\n\n    /* copy state to local variables */\n    state = (struct inflate_state FAR *)strm->state;\n    in = strm->next_in - OFF;\n    last = in + (strm->avail_in - 5);\n    out = strm->next_out - OFF;\n    beg = out - (start - strm->avail_out);\n    end = out + (strm->avail_out - 257);\n#ifdef INFLATE_STRICT\n    dmax = state->dmax;\n#endif\n    wsize = state->wsize;\n    whave = state->whave;\n    wnext = state->wnext;\n    window = state->window;\n    hold = state->hold;\n    bits = state->bits;\n    lcode = state->lencode;\n    dcode = state->distcode;\n    lmask = (1U << state->lenbits) - 1;\n    dmask = (1U << state->distbits) - 1;\n\n    /* decode literals and length/distances until end-of-block or not enough\n       input data or output space */\n    do {\n        if (bits < 15) {\n            hold += (unsigned long)(PUP(in)) << bits;\n            bits += 8;\n            hold += (unsigned long)(PUP(in)) << bits;\n            bits += 8;\n        }\n        here = lcode[hold & lmask];\n      dolen:\n        op = (unsigned)(here.bits);\n        hold >>= op;\n        bits -= op;\n        op = (unsigned)(here.op);\n        if (op == 0) {                          /* literal */\n            Tracevv((stderr, here.val >= 0x20 && here.val < 0x7f ?\n                    \"inflate:         literal '%c'\\n\" :\n                    \"inflate:         literal 0x%02x\\n\", here.val));\n            PUP(out) = (unsigned char)(here.val);\n        }\n        else if (op & 16) {                     /* length base */\n            len = (unsigned)(here.val);\n            op &= 15;                           /* number of extra bits */\n            if (op) {\n                if (bits < op) {\n                    hold += (unsigned long)(PUP(in)) << bits;\n                    bits += 8;\n                }\n                len += (unsigned)hold & ((1U << op) - 1);\n                hold >>= op;\n                bits -= op;\n            }\n            Tracevv((stderr, \"inflate:         length %u\\n\", len));\n            if (bits < 15) {\n                hold += (unsigned long)(PUP(in)) << bits;\n                bits += 8;\n                hold += (unsigned long)(PUP(in)) << bits;\n                bits += 8;\n            }\n            here = dcode[hold & dmask];\n          dodist:\n            op = (unsigned)(here.bits);\n            hold >>= op;\n            bits -= op;\n            op = (unsigned)(here.op);\n            if (op & 16) {                      /* distance base */\n                dist = (unsigned)(here.val);\n                op &= 15;                       /* number of extra bits */\n                if (bits < op) {\n                    hold += (unsigned long)(PUP(in)) << bits;\n                    bits += 8;\n                    if (bits < op) {\n                        hold += (unsigned long)(PUP(in)) << bits;\n                        bits += 8;\n                    }\n                }\n                dist += (unsigned)hold & ((1U << op) - 1);\n#ifdef INFLATE_STRICT\n                if (dist > dmax) {\n                    strm->msg = (char *)\"invalid distance too far back\";\n                    state->mode = BAD;\n                    break;\n                }\n#endif\n                hold >>= op;\n                bits -= op;\n                Tracevv((stderr, \"inflate:         distance %u\\n\", dist));\n                op = (unsigned)(out - beg);     /* max distance in output */\n                if (dist > op) {                /* see if copy from window */\n                    op = dist - op;             /* distance back in window */\n                    if (op > whave) {\n                        if (state->sane) {\n                            strm->msg =\n                                (char *)\"invalid distance too far back\";\n                            state->mode = BAD;\n                            break;\n                        }\n#ifdef INFLATE_ALLOW_INVALID_DISTANCE_TOOFAR_ARRR\n                        if (len <= op - whave) {\n                            do {\n                                PUP(out) = 0;\n                            } while (--len);\n                            continue;\n                        }\n                        len -= op - whave;\n                        do {\n                            PUP(out) = 0;\n                        } while (--op > whave);\n                        if (op == 0) {\n                            from = out - dist;\n                            do {\n                                PUP(out) = PUP(from);\n                            } while (--len);\n                            continue;\n                        }\n#endif\n                    }\n                    from = window - OFF;\n                    if (wnext == 0) {           /* very common case */\n                        from += wsize - op;\n                        if (op < len) {         /* some from window */\n                            len -= op;\n                            do {\n                                PUP(out) = PUP(from);\n                            } while (--op);\n                            from = out - dist;  /* rest from output */\n                        }\n                    }\n                    else if (wnext < op) {      /* wrap around window */\n                        from += wsize + wnext - op;\n                        op -= wnext;\n                        if (op < len) {         /* some from end of window */\n                            len -= op;\n                            do {\n                                PUP(out) = PUP(from);\n                            } while (--op);\n                            from = window - OFF;\n                            if (wnext < len) {  /* some from start of window */\n                                op = wnext;\n                                len -= op;\n                                do {\n                                    PUP(out) = PUP(from);\n                                } while (--op);\n                                from = out - dist;      /* rest from output */\n                            }\n                        }\n                    }\n                    else {                      /* contiguous in window */\n                        from += wnext - op;\n                        if (op < len) {         /* some from window */\n                            len -= op;\n                            do {\n                                PUP(out) = PUP(from);\n                            } while (--op);\n                            from = out - dist;  /* rest from output */\n                        }\n                    }\n                    while (len > 2) {\n                        PUP(out) = PUP(from);\n                        PUP(out) = PUP(from);\n                        PUP(out) = PUP(from);\n                        len -= 3;\n                    }\n                    if (len) {\n                        PUP(out) = PUP(from);\n                        if (len > 1)\n                            PUP(out) = PUP(from);\n                    }\n                }\n                else {\n                    from = out - dist;          /* copy direct from output */\n                    do {                        /* minimum length is three */\n                        PUP(out) = PUP(from);\n                        PUP(out) = PUP(from);\n                        PUP(out) = PUP(from);\n                        len -= 3;\n                    } while (len > 2);\n                    if (len) {\n                        PUP(out) = PUP(from);\n                        if (len > 1)\n                            PUP(out) = PUP(from);\n                    }\n                }\n            }\n            else if ((op & 64) == 0) {          /* 2nd level distance code */\n                here = dcode[here.val + (hold & ((1U << op) - 1))];\n                goto dodist;\n            }\n            else {\n                strm->msg = (char *)\"invalid distance code\";\n                state->mode = BAD;\n                break;\n            }\n        }\n        else if ((op & 64) == 0) {              /* 2nd level length code */\n            here = lcode[here.val + (hold & ((1U << op) - 1))];\n            goto dolen;\n        }\n        else if (op & 32) {                     /* end-of-block */\n            Tracevv((stderr, \"inflate:         end of block\\n\"));\n            state->mode = TYPE;\n            break;\n        }\n        else {\n            strm->msg = (char *)\"invalid literal/length code\";\n            state->mode = BAD;\n            break;\n        }\n    } while (in < last && out < end);\n\n    /* return unused bytes (on entry, bits < 8, so in won't go too far back) */\n    len = bits >> 3;\n    in -= len;\n    bits -= len << 3;\n    hold &= (1U << bits) - 1;\n\n    /* update state and return */\n    strm->next_in = in + OFF;\n    strm->next_out = out + OFF;\n    strm->avail_in = (unsigned)(in < last ? 5 + (last - in) : 5 - (in - last));\n    strm->avail_out = (unsigned)(out < end ?\n                                 257 + (end - out) : 257 - (out - end));\n    state->hold = hold;\n    state->bits = bits;\n    return;\n}\n\n/*\n   inflate_fast() speedups that turned out slower (on a PowerPC G3 750CXe):\n   - Using bit fields for code structure\n   - Different op definition to avoid & for extra bits (do & for table bits)\n   - Three separate decoding do-loops for direct, window, and wnext == 0\n   - Special case for distance > 1 copies to do overlapped load and store copy\n   - Explicit branch predictions (based on measured branch probabilities)\n   - Deferring match copy and interspersed it with decoding subsequent codes\n   - Swapping literal/length else\n   - Swapping window/direct else\n   - Larger unrolled copy loops (three is about right)\n   - Moving len -= 3 statement into middle of loop\n */\n\n#endif /* !ASMINF */\n"
  },
  {
    "path": "external/zlib/inffast.h",
    "content": "/* inffast.h -- header to use inffast.c\n * Copyright (C) 1995-2003, 2010 Mark Adler\n * For conditions of distribution and use, see copyright notice in zlib.h\n */\n\n/* WARNING: this file should *not* be used by applications. It is\n   part of the implementation of the compression library and is\n   subject to change. Applications should only use zlib.h.\n */\n\nvoid ZLIB_INTERNAL inflate_fast OF((z_streamp strm, unsigned start));\n"
  },
  {
    "path": "external/zlib/inffixed.h",
    "content": "    /* inffixed.h -- table for decoding fixed codes\n     * Generated automatically by makefixed().\n     */\n\n    /* WARNING: this file should *not* be used by applications.\n       It is part of the implementation of this library and is\n       subject to change. Applications should only use zlib.h.\n     */\n\n    static const code lenfix[512] = {\n        {96,7,0},{0,8,80},{0,8,16},{20,8,115},{18,7,31},{0,8,112},{0,8,48},\n        {0,9,192},{16,7,10},{0,8,96},{0,8,32},{0,9,160},{0,8,0},{0,8,128},\n        {0,8,64},{0,9,224},{16,7,6},{0,8,88},{0,8,24},{0,9,144},{19,7,59},\n        {0,8,120},{0,8,56},{0,9,208},{17,7,17},{0,8,104},{0,8,40},{0,9,176},\n        {0,8,8},{0,8,136},{0,8,72},{0,9,240},{16,7,4},{0,8,84},{0,8,20},\n        {21,8,227},{19,7,43},{0,8,116},{0,8,52},{0,9,200},{17,7,13},{0,8,100},\n        {0,8,36},{0,9,168},{0,8,4},{0,8,132},{0,8,68},{0,9,232},{16,7,8},\n        {0,8,92},{0,8,28},{0,9,152},{20,7,83},{0,8,124},{0,8,60},{0,9,216},\n        {18,7,23},{0,8,108},{0,8,44},{0,9,184},{0,8,12},{0,8,140},{0,8,76},\n        {0,9,248},{16,7,3},{0,8,82},{0,8,18},{21,8,163},{19,7,35},{0,8,114},\n        {0,8,50},{0,9,196},{17,7,11},{0,8,98},{0,8,34},{0,9,164},{0,8,2},\n        {0,8,130},{0,8,66},{0,9,228},{16,7,7},{0,8,90},{0,8,26},{0,9,148},\n        {20,7,67},{0,8,122},{0,8,58},{0,9,212},{18,7,19},{0,8,106},{0,8,42},\n        {0,9,180},{0,8,10},{0,8,138},{0,8,74},{0,9,244},{16,7,5},{0,8,86},\n        {0,8,22},{64,8,0},{19,7,51},{0,8,118},{0,8,54},{0,9,204},{17,7,15},\n        {0,8,102},{0,8,38},{0,9,172},{0,8,6},{0,8,134},{0,8,70},{0,9,236},\n        {16,7,9},{0,8,94},{0,8,30},{0,9,156},{20,7,99},{0,8,126},{0,8,62},\n        {0,9,220},{18,7,27},{0,8,110},{0,8,46},{0,9,188},{0,8,14},{0,8,142},\n        {0,8,78},{0,9,252},{96,7,0},{0,8,81},{0,8,17},{21,8,131},{18,7,31},\n        {0,8,113},{0,8,49},{0,9,194},{16,7,10},{0,8,97},{0,8,33},{0,9,162},\n        {0,8,1},{0,8,129},{0,8,65},{0,9,226},{16,7,6},{0,8,89},{0,8,25},\n        {0,9,146},{19,7,59},{0,8,121},{0,8,57},{0,9,210},{17,7,17},{0,8,105},\n        {0,8,41},{0,9,178},{0,8,9},{0,8,137},{0,8,73},{0,9,242},{16,7,4},\n        {0,8,85},{0,8,21},{16,8,258},{19,7,43},{0,8,117},{0,8,53},{0,9,202},\n        {17,7,13},{0,8,101},{0,8,37},{0,9,170},{0,8,5},{0,8,133},{0,8,69},\n        {0,9,234},{16,7,8},{0,8,93},{0,8,29},{0,9,154},{20,7,83},{0,8,125},\n        {0,8,61},{0,9,218},{18,7,23},{0,8,109},{0,8,45},{0,9,186},{0,8,13},\n        {0,8,141},{0,8,77},{0,9,250},{16,7,3},{0,8,83},{0,8,19},{21,8,195},\n        {19,7,35},{0,8,115},{0,8,51},{0,9,198},{17,7,11},{0,8,99},{0,8,35},\n        {0,9,166},{0,8,3},{0,8,131},{0,8,67},{0,9,230},{16,7,7},{0,8,91},\n        {0,8,27},{0,9,150},{20,7,67},{0,8,123},{0,8,59},{0,9,214},{18,7,19},\n        {0,8,107},{0,8,43},{0,9,182},{0,8,11},{0,8,139},{0,8,75},{0,9,246},\n        {16,7,5},{0,8,87},{0,8,23},{64,8,0},{19,7,51},{0,8,119},{0,8,55},\n        {0,9,206},{17,7,15},{0,8,103},{0,8,39},{0,9,174},{0,8,7},{0,8,135},\n        {0,8,71},{0,9,238},{16,7,9},{0,8,95},{0,8,31},{0,9,158},{20,7,99},\n        {0,8,127},{0,8,63},{0,9,222},{18,7,27},{0,8,111},{0,8,47},{0,9,190},\n        {0,8,15},{0,8,143},{0,8,79},{0,9,254},{96,7,0},{0,8,80},{0,8,16},\n        {20,8,115},{18,7,31},{0,8,112},{0,8,48},{0,9,193},{16,7,10},{0,8,96},\n        {0,8,32},{0,9,161},{0,8,0},{0,8,128},{0,8,64},{0,9,225},{16,7,6},\n        {0,8,88},{0,8,24},{0,9,145},{19,7,59},{0,8,120},{0,8,56},{0,9,209},\n        {17,7,17},{0,8,104},{0,8,40},{0,9,177},{0,8,8},{0,8,136},{0,8,72},\n        {0,9,241},{16,7,4},{0,8,84},{0,8,20},{21,8,227},{19,7,43},{0,8,116},\n        {0,8,52},{0,9,201},{17,7,13},{0,8,100},{0,8,36},{0,9,169},{0,8,4},\n        {0,8,132},{0,8,68},{0,9,233},{16,7,8},{0,8,92},{0,8,28},{0,9,153},\n        {20,7,83},{0,8,124},{0,8,60},{0,9,217},{18,7,23},{0,8,108},{0,8,44},\n        {0,9,185},{0,8,12},{0,8,140},{0,8,76},{0,9,249},{16,7,3},{0,8,82},\n        {0,8,18},{21,8,163},{19,7,35},{0,8,114},{0,8,50},{0,9,197},{17,7,11},\n        {0,8,98},{0,8,34},{0,9,165},{0,8,2},{0,8,130},{0,8,66},{0,9,229},\n        {16,7,7},{0,8,90},{0,8,26},{0,9,149},{20,7,67},{0,8,122},{0,8,58},\n        {0,9,213},{18,7,19},{0,8,106},{0,8,42},{0,9,181},{0,8,10},{0,8,138},\n        {0,8,74},{0,9,245},{16,7,5},{0,8,86},{0,8,22},{64,8,0},{19,7,51},\n        {0,8,118},{0,8,54},{0,9,205},{17,7,15},{0,8,102},{0,8,38},{0,9,173},\n        {0,8,6},{0,8,134},{0,8,70},{0,9,237},{16,7,9},{0,8,94},{0,8,30},\n        {0,9,157},{20,7,99},{0,8,126},{0,8,62},{0,9,221},{18,7,27},{0,8,110},\n        {0,8,46},{0,9,189},{0,8,14},{0,8,142},{0,8,78},{0,9,253},{96,7,0},\n        {0,8,81},{0,8,17},{21,8,131},{18,7,31},{0,8,113},{0,8,49},{0,9,195},\n        {16,7,10},{0,8,97},{0,8,33},{0,9,163},{0,8,1},{0,8,129},{0,8,65},\n        {0,9,227},{16,7,6},{0,8,89},{0,8,25},{0,9,147},{19,7,59},{0,8,121},\n        {0,8,57},{0,9,211},{17,7,17},{0,8,105},{0,8,41},{0,9,179},{0,8,9},\n        {0,8,137},{0,8,73},{0,9,243},{16,7,4},{0,8,85},{0,8,21},{16,8,258},\n        {19,7,43},{0,8,117},{0,8,53},{0,9,203},{17,7,13},{0,8,101},{0,8,37},\n        {0,9,171},{0,8,5},{0,8,133},{0,8,69},{0,9,235},{16,7,8},{0,8,93},\n        {0,8,29},{0,9,155},{20,7,83},{0,8,125},{0,8,61},{0,9,219},{18,7,23},\n        {0,8,109},{0,8,45},{0,9,187},{0,8,13},{0,8,141},{0,8,77},{0,9,251},\n        {16,7,3},{0,8,83},{0,8,19},{21,8,195},{19,7,35},{0,8,115},{0,8,51},\n        {0,9,199},{17,7,11},{0,8,99},{0,8,35},{0,9,167},{0,8,3},{0,8,131},\n        {0,8,67},{0,9,231},{16,7,7},{0,8,91},{0,8,27},{0,9,151},{20,7,67},\n        {0,8,123},{0,8,59},{0,9,215},{18,7,19},{0,8,107},{0,8,43},{0,9,183},\n        {0,8,11},{0,8,139},{0,8,75},{0,9,247},{16,7,5},{0,8,87},{0,8,23},\n        {64,8,0},{19,7,51},{0,8,119},{0,8,55},{0,9,207},{17,7,15},{0,8,103},\n        {0,8,39},{0,9,175},{0,8,7},{0,8,135},{0,8,71},{0,9,239},{16,7,9},\n        {0,8,95},{0,8,31},{0,9,159},{20,7,99},{0,8,127},{0,8,63},{0,9,223},\n        {18,7,27},{0,8,111},{0,8,47},{0,9,191},{0,8,15},{0,8,143},{0,8,79},\n        {0,9,255}\n    };\n\n    static const code distfix[32] = {\n        {16,5,1},{23,5,257},{19,5,17},{27,5,4097},{17,5,5},{25,5,1025},\n        {21,5,65},{29,5,16385},{16,5,3},{24,5,513},{20,5,33},{28,5,8193},\n        {18,5,9},{26,5,2049},{22,5,129},{64,5,0},{16,5,2},{23,5,385},\n        {19,5,25},{27,5,6145},{17,5,7},{25,5,1537},{21,5,97},{29,5,24577},\n        {16,5,4},{24,5,769},{20,5,49},{28,5,12289},{18,5,13},{26,5,3073},\n        {22,5,193},{64,5,0}\n    };\n"
  },
  {
    "path": "external/zlib/inflate.c",
    "content": "/* inflate.c -- zlib decompression\n * Copyright (C) 1995-2012 Mark Adler\n * For conditions of distribution and use, see copyright notice in zlib.h\n */\n\n/*\n * Change history:\n *\n * 1.2.beta0    24 Nov 2002\n * - First version -- complete rewrite of inflate to simplify code, avoid\n *   creation of window when not needed, minimize use of window when it is\n *   needed, make inffast.c even faster, implement gzip decoding, and to\n *   improve code readability and style over the previous zlib inflate code\n *\n * 1.2.beta1    25 Nov 2002\n * - Use pointers for available input and output checking in inffast.c\n * - Remove input and output counters in inffast.c\n * - Change inffast.c entry and loop from avail_in >= 7 to >= 6\n * - Remove unnecessary second byte pull from length extra in inffast.c\n * - Unroll direct copy to three copies per loop in inffast.c\n *\n * 1.2.beta2    4 Dec 2002\n * - Change external routine names to reduce potential conflicts\n * - Correct filename to inffixed.h for fixed tables in inflate.c\n * - Make hbuf[] unsigned char to match parameter type in inflate.c\n * - Change strm->next_out[-state->offset] to *(strm->next_out - state->offset)\n *   to avoid negation problem on Alphas (64 bit) in inflate.c\n *\n * 1.2.beta3    22 Dec 2002\n * - Add comments on state->bits assertion in inffast.c\n * - Add comments on op field in inftrees.h\n * - Fix bug in reuse of allocated window after inflateReset()\n * - Remove bit fields--back to byte structure for speed\n * - Remove distance extra == 0 check in inflate_fast()--only helps for lengths\n * - Change post-increments to pre-increments in inflate_fast(), PPC biased?\n * - Add compile time option, POSTINC, to use post-increments instead (Intel?)\n * - Make MATCH copy in inflate() much faster for when inflate_fast() not used\n * - Use local copies of stream next and avail values, as well as local bit\n *   buffer and bit count in inflate()--for speed when inflate_fast() not used\n *\n * 1.2.beta4    1 Jan 2003\n * - Split ptr - 257 statements in inflate_table() to avoid compiler warnings\n * - Move a comment on output buffer sizes from inffast.c to inflate.c\n * - Add comments in inffast.c to introduce the inflate_fast() routine\n * - Rearrange window copies in inflate_fast() for speed and simplification\n * - Unroll last copy for window match in inflate_fast()\n * - Use local copies of window variables in inflate_fast() for speed\n * - Pull out common wnext == 0 case for speed in inflate_fast()\n * - Make op and len in inflate_fast() unsigned for consistency\n * - Add FAR to lcode and dcode declarations in inflate_fast()\n * - Simplified bad distance check in inflate_fast()\n * - Added inflateBackInit(), inflateBack(), and inflateBackEnd() in new\n *   source file infback.c to provide a call-back interface to inflate for\n *   programs like gzip and unzip -- uses window as output buffer to avoid\n *   window copying\n *\n * 1.2.beta5    1 Jan 2003\n * - Improved inflateBack() interface to allow the caller to provide initial\n *   input in strm.\n * - Fixed stored blocks bug in inflateBack()\n *\n * 1.2.beta6    4 Jan 2003\n * - Added comments in inffast.c on effectiveness of POSTINC\n * - Typecasting all around to reduce compiler warnings\n * - Changed loops from while (1) or do {} while (1) to for (;;), again to\n *   make compilers happy\n * - Changed type of window in inflateBackInit() to unsigned char *\n *\n * 1.2.beta7    27 Jan 2003\n * - Changed many types to unsigned or unsigned short to avoid warnings\n * - Added inflateCopy() function\n *\n * 1.2.0        9 Mar 2003\n * - Changed inflateBack() interface to provide separate opaque descriptors\n *   for the in() and out() functions\n * - Changed inflateBack() argument and in_func typedef to swap the length\n *   and buffer address return values for the input function\n * - Check next_in and next_out for Z_NULL on entry to inflate()\n *\n * The history for versions after 1.2.0 are in ChangeLog in zlib distribution.\n */\n\n#include \"zutil.h\"\n#include \"inftrees.h\"\n#include \"inflate.h\"\n#include \"inffast.h\"\n\n#ifdef MAKEFIXED\n#  ifndef BUILDFIXED\n#    define BUILDFIXED\n#  endif\n#endif\n\n/* function prototypes */\nlocal void fixedtables OF((struct inflate_state FAR *state));\nlocal int updatewindow OF((z_streamp strm, const unsigned char FAR *end,\n                           unsigned copy));\n#ifdef BUILDFIXED\n   void makefixed OF((void));\n#endif\nlocal unsigned syncsearch OF((unsigned FAR *have, const unsigned char FAR *buf,\n                              unsigned len));\n\nint ZEXPORT inflateResetKeep(strm)\nz_streamp strm;\n{\n    struct inflate_state FAR *state;\n\n    if (strm == Z_NULL || strm->state == Z_NULL) return Z_STREAM_ERROR;\n    state = (struct inflate_state FAR *)strm->state;\n    strm->total_in = strm->total_out = state->total = 0;\n    strm->msg = Z_NULL;\n    if (state->wrap)        /* to support ill-conceived Java test suite */\n        strm->adler = state->wrap & 1;\n    state->mode = HEAD;\n    state->last = 0;\n    state->havedict = 0;\n    state->dmax = 32768U;\n    state->head = Z_NULL;\n    state->hold = 0;\n    state->bits = 0;\n    state->lencode = state->distcode = state->next = state->codes;\n    state->sane = 1;\n    state->back = -1;\n    Tracev((stderr, \"inflate: reset\\n\"));\n    return Z_OK;\n}\n\nint ZEXPORT inflateReset(strm)\nz_streamp strm;\n{\n    struct inflate_state FAR *state;\n\n    if (strm == Z_NULL || strm->state == Z_NULL) return Z_STREAM_ERROR;\n    state = (struct inflate_state FAR *)strm->state;\n    state->wsize = 0;\n    state->whave = 0;\n    state->wnext = 0;\n    return inflateResetKeep(strm);\n}\n\nint ZEXPORT inflateReset2(strm, windowBits)\nz_streamp strm;\nint windowBits;\n{\n    int wrap;\n    struct inflate_state FAR *state;\n\n    /* get the state */\n    if (strm == Z_NULL || strm->state == Z_NULL) return Z_STREAM_ERROR;\n    state = (struct inflate_state FAR *)strm->state;\n\n    /* extract wrap request from windowBits parameter */\n    if (windowBits < 0) {\n        wrap = 0;\n        windowBits = -windowBits;\n    }\n    else {\n        wrap = (windowBits >> 4) + 1;\n#ifdef GUNZIP\n        if (windowBits < 48)\n            windowBits &= 15;\n#endif\n    }\n\n    /* set number of window bits, free window if different */\n    if (windowBits && (windowBits < 8 || windowBits > 15))\n        return Z_STREAM_ERROR;\n    if (state->window != Z_NULL && state->wbits != (unsigned)windowBits) {\n        ZFREE(strm, state->window);\n        state->window = Z_NULL;\n    }\n\n    /* update state and reset the rest of it */\n    state->wrap = wrap;\n    state->wbits = (unsigned)windowBits;\n    return inflateReset(strm);\n}\n\nint ZEXPORT inflateInit2_(strm, windowBits, version, stream_size)\nz_streamp strm;\nint windowBits;\nconst char *version;\nint stream_size;\n{\n    int ret;\n    struct inflate_state FAR *state;\n\n    if (version == Z_NULL || version[0] != ZLIB_VERSION[0] ||\n        stream_size != (int)(sizeof(z_stream)))\n        return Z_VERSION_ERROR;\n    if (strm == Z_NULL) return Z_STREAM_ERROR;\n    strm->msg = Z_NULL;                 /* in case we return an error */\n    if (strm->zalloc == (alloc_func)0) {\n#ifdef Z_SOLO\n        return Z_STREAM_ERROR;\n#else\n        strm->zalloc = zcalloc;\n        strm->opaque = (voidpf)0;\n#endif\n    }\n    if (strm->zfree == (free_func)0)\n#ifdef Z_SOLO\n        return Z_STREAM_ERROR;\n#else\n        strm->zfree = zcfree;\n#endif\n    state = (struct inflate_state FAR *)\n            ZALLOC(strm, 1, sizeof(struct inflate_state));\n    if (state == Z_NULL) return Z_MEM_ERROR;\n    Tracev((stderr, \"inflate: allocated\\n\"));\n    strm->state = (struct internal_state FAR *)state;\n    state->window = Z_NULL;\n    ret = inflateReset2(strm, windowBits);\n    if (ret != Z_OK) {\n        ZFREE(strm, state);\n        strm->state = Z_NULL;\n    }\n    return ret;\n}\n\nint ZEXPORT inflateInit_(strm, version, stream_size)\nz_streamp strm;\nconst char *version;\nint stream_size;\n{\n    return inflateInit2_(strm, DEF_WBITS, version, stream_size);\n}\n\nint ZEXPORT inflatePrime(strm, bits, value)\nz_streamp strm;\nint bits;\nint value;\n{\n    struct inflate_state FAR *state;\n\n    if (strm == Z_NULL || strm->state == Z_NULL) return Z_STREAM_ERROR;\n    state = (struct inflate_state FAR *)strm->state;\n    if (bits < 0) {\n        state->hold = 0;\n        state->bits = 0;\n        return Z_OK;\n    }\n    if (bits > 16 || state->bits + bits > 32) return Z_STREAM_ERROR;\n    value &= (1L << bits) - 1;\n    state->hold += value << state->bits;\n    state->bits += bits;\n    return Z_OK;\n}\n\n/*\n   Return state with length and distance decoding tables and index sizes set to\n   fixed code decoding.  Normally this returns fixed tables from inffixed.h.\n   If BUILDFIXED is defined, then instead this routine builds the tables the\n   first time it's called, and returns those tables the first time and\n   thereafter.  This reduces the size of the code by about 2K bytes, in\n   exchange for a little execution time.  However, BUILDFIXED should not be\n   used for threaded applications, since the rewriting of the tables and virgin\n   may not be thread-safe.\n */\nlocal void fixedtables(state)\nstruct inflate_state FAR *state;\n{\n#ifdef BUILDFIXED\n    static int virgin = 1;\n    static code *lenfix, *distfix;\n    static code fixed[544];\n\n    /* build fixed huffman tables if first call (may not be thread safe) */\n    if (virgin) {\n        unsigned sym, bits;\n        static code *next;\n\n        /* literal/length table */\n        sym = 0;\n        while (sym < 144) state->lens[sym++] = 8;\n        while (sym < 256) state->lens[sym++] = 9;\n        while (sym < 280) state->lens[sym++] = 7;\n        while (sym < 288) state->lens[sym++] = 8;\n        next = fixed;\n        lenfix = next;\n        bits = 9;\n        inflate_table(LENS, state->lens, 288, &(next), &(bits), state->work);\n\n        /* distance table */\n        sym = 0;\n        while (sym < 32) state->lens[sym++] = 5;\n        distfix = next;\n        bits = 5;\n        inflate_table(DISTS, state->lens, 32, &(next), &(bits), state->work);\n\n        /* do this just once */\n        virgin = 0;\n    }\n#else /* !BUILDFIXED */\n#   include \"inffixed.h\"\n#endif /* BUILDFIXED */\n    state->lencode = lenfix;\n    state->lenbits = 9;\n    state->distcode = distfix;\n    state->distbits = 5;\n}\n\n#ifdef MAKEFIXED\n#include <stdio.h>\n\n/*\n   Write out the inffixed.h that is #include'd above.  Defining MAKEFIXED also\n   defines BUILDFIXED, so the tables are built on the fly.  makefixed() writes\n   those tables to stdout, which would be piped to inffixed.h.  A small program\n   can simply call makefixed to do this:\n\n    void makefixed(void);\n\n    int main(void)\n    {\n        makefixed();\n        return 0;\n    }\n\n   Then that can be linked with zlib built with MAKEFIXED defined and run:\n\n    a.out > inffixed.h\n */\nvoid makefixed()\n{\n    unsigned low, size;\n    struct inflate_state state;\n\n    fixedtables(&state);\n    puts(\"    /* inffixed.h -- table for decoding fixed codes\");\n    puts(\"     * Generated automatically by makefixed().\");\n    puts(\"     */\");\n    puts(\"\");\n    puts(\"    /* WARNING: this file should *not* be used by applications.\");\n    puts(\"       It is part of the implementation of this library and is\");\n    puts(\"       subject to change. Applications should only use zlib.h.\");\n    puts(\"     */\");\n    puts(\"\");\n    size = 1U << 9;\n    printf(\"    static const code lenfix[%u] = {\", size);\n    low = 0;\n    for (;;) {\n        if ((low % 7) == 0) printf(\"\\n        \");\n        printf(\"{%u,%u,%d}\", (low & 127) == 99 ? 64 : state.lencode[low].op,\n               state.lencode[low].bits, state.lencode[low].val);\n        if (++low == size) break;\n        putchar(',');\n    }\n    puts(\"\\n    };\");\n    size = 1U << 5;\n    printf(\"\\n    static const code distfix[%u] = {\", size);\n    low = 0;\n    for (;;) {\n        if ((low % 6) == 0) printf(\"\\n        \");\n        printf(\"{%u,%u,%d}\", state.distcode[low].op, state.distcode[low].bits,\n               state.distcode[low].val);\n        if (++low == size) break;\n        putchar(',');\n    }\n    puts(\"\\n    };\");\n}\n#endif /* MAKEFIXED */\n\n/*\n   Update the window with the last wsize (normally 32K) bytes written before\n   returning.  If window does not exist yet, create it.  This is only called\n   when a window is already in use, or when output has been written during this\n   inflate call, but the end of the deflate stream has not been reached yet.\n   It is also called to create a window for dictionary data when a dictionary\n   is loaded.\n\n   Providing output buffers larger than 32K to inflate() should provide a speed\n   advantage, since only the last 32K of output is copied to the sliding window\n   upon return from inflate(), and since all distances after the first 32K of\n   output will fall in the output data, making match copies simpler and faster.\n   The advantage may be dependent on the size of the processor's data caches.\n */\nlocal int updatewindow(strm, end, copy)\nz_streamp strm;\nconst Bytef *end;\nunsigned copy;\n{\n    struct inflate_state FAR *state;\n    unsigned dist;\n\n    state = (struct inflate_state FAR *)strm->state;\n\n    /* if it hasn't been done already, allocate space for the window */\n    if (state->window == Z_NULL) {\n        state->window = (unsigned char FAR *)\n                        ZALLOC(strm, 1U << state->wbits,\n                               sizeof(unsigned char));\n        if (state->window == Z_NULL) return 1;\n    }\n\n    /* if window not in use yet, initialize */\n    if (state->wsize == 0) {\n        state->wsize = 1U << state->wbits;\n        state->wnext = 0;\n        state->whave = 0;\n    }\n\n    /* copy state->wsize or less output bytes into the circular window */\n    if (copy >= state->wsize) {\n        zmemcpy(state->window, end - state->wsize, state->wsize);\n        state->wnext = 0;\n        state->whave = state->wsize;\n    }\n    else {\n        dist = state->wsize - state->wnext;\n        if (dist > copy) dist = copy;\n        zmemcpy(state->window + state->wnext, end - copy, dist);\n        copy -= dist;\n        if (copy) {\n            zmemcpy(state->window, end - copy, copy);\n            state->wnext = copy;\n            state->whave = state->wsize;\n        }\n        else {\n            state->wnext += dist;\n            if (state->wnext == state->wsize) state->wnext = 0;\n            if (state->whave < state->wsize) state->whave += dist;\n        }\n    }\n    return 0;\n}\n\n/* Macros for inflate(): */\n\n/* check function to use adler32() for zlib or crc32() for gzip */\n#ifdef GUNZIP\n#  define UPDATE(check, buf, len) \\\n    (state->flags ? crc32(check, buf, len) : adler32(check, buf, len))\n#else\n#  define UPDATE(check, buf, len) adler32(check, buf, len)\n#endif\n\n/* check macros for header crc */\n#ifdef GUNZIP\n#  define CRC2(check, word) \\\n    do { \\\n        hbuf[0] = (unsigned char)(word); \\\n        hbuf[1] = (unsigned char)((word) >> 8); \\\n        check = crc32(check, hbuf, 2); \\\n    } while (0)\n\n#  define CRC4(check, word) \\\n    do { \\\n        hbuf[0] = (unsigned char)(word); \\\n        hbuf[1] = (unsigned char)((word) >> 8); \\\n        hbuf[2] = (unsigned char)((word) >> 16); \\\n        hbuf[3] = (unsigned char)((word) >> 24); \\\n        check = crc32(check, hbuf, 4); \\\n    } while (0)\n#endif\n\n/* Load registers with state in inflate() for speed */\n#define LOAD() \\\n    do { \\\n        put = strm->next_out; \\\n        left = strm->avail_out; \\\n        next = strm->next_in; \\\n        have = strm->avail_in; \\\n        hold = state->hold; \\\n        bits = state->bits; \\\n    } while (0)\n\n/* Restore state from registers in inflate() */\n#define RESTORE() \\\n    do { \\\n        strm->next_out = put; \\\n        strm->avail_out = left; \\\n        strm->next_in = next; \\\n        strm->avail_in = have; \\\n        state->hold = hold; \\\n        state->bits = bits; \\\n    } while (0)\n\n/* Clear the input bit accumulator */\n#define INITBITS() \\\n    do { \\\n        hold = 0; \\\n        bits = 0; \\\n    } while (0)\n\n/* Get a byte of input into the bit accumulator, or return from inflate()\n   if there is no input available. */\n#define PULLBYTE() \\\n    do { \\\n        if (have == 0) goto inf_leave; \\\n        have--; \\\n        hold += (unsigned long)(*next++) << bits; \\\n        bits += 8; \\\n    } while (0)\n\n/* Assure that there are at least n bits in the bit accumulator.  If there is\n   not enough available input to do that, then return from inflate(). */\n#define NEEDBITS(n) \\\n    do { \\\n        while (bits < (unsigned)(n)) \\\n            PULLBYTE(); \\\n    } while (0)\n\n/* Return the low n bits of the bit accumulator (n < 16) */\n#define BITS(n) \\\n    ((unsigned)hold & ((1U << (n)) - 1))\n\n/* Remove n bits from the bit accumulator */\n#define DROPBITS(n) \\\n    do { \\\n        hold >>= (n); \\\n        bits -= (unsigned)(n); \\\n    } while (0)\n\n/* Remove zero to seven bits as needed to go to a byte boundary */\n#define BYTEBITS() \\\n    do { \\\n        hold >>= bits & 7; \\\n        bits -= bits & 7; \\\n    } while (0)\n\n/*\n   inflate() uses a state machine to process as much input data and generate as\n   much output data as possible before returning.  The state machine is\n   structured roughly as follows:\n\n    for (;;) switch (state) {\n    ...\n    case STATEn:\n        if (not enough input data or output space to make progress)\n            return;\n        ... make progress ...\n        state = STATEm;\n        break;\n    ...\n    }\n\n   so when inflate() is called again, the same case is attempted again, and\n   if the appropriate resources are provided, the machine proceeds to the\n   next state.  The NEEDBITS() macro is usually the way the state evaluates\n   whether it can proceed or should return.  NEEDBITS() does the return if\n   the requested bits are not available.  The typical use of the BITS macros\n   is:\n\n        NEEDBITS(n);\n        ... do something with BITS(n) ...\n        DROPBITS(n);\n\n   where NEEDBITS(n) either returns from inflate() if there isn't enough\n   input left to load n bits into the accumulator, or it continues.  BITS(n)\n   gives the low n bits in the accumulator.  When done, DROPBITS(n) drops\n   the low n bits off the accumulator.  INITBITS() clears the accumulator\n   and sets the number of available bits to zero.  BYTEBITS() discards just\n   enough bits to put the accumulator on a byte boundary.  After BYTEBITS()\n   and a NEEDBITS(8), then BITS(8) would return the next byte in the stream.\n\n   NEEDBITS(n) uses PULLBYTE() to get an available byte of input, or to return\n   if there is no input available.  The decoding of variable length codes uses\n   PULLBYTE() directly in order to pull just enough bytes to decode the next\n   code, and no more.\n\n   Some states loop until they get enough input, making sure that enough\n   state information is maintained to continue the loop where it left off\n   if NEEDBITS() returns in the loop.  For example, want, need, and keep\n   would all have to actually be part of the saved state in case NEEDBITS()\n   returns:\n\n    case STATEw:\n        while (want < need) {\n            NEEDBITS(n);\n            keep[want++] = BITS(n);\n            DROPBITS(n);\n        }\n        state = STATEx;\n    case STATEx:\n\n   As shown above, if the next state is also the next case, then the break\n   is omitted.\n\n   A state may also return if there is not enough output space available to\n   complete that state.  Those states are copying stored data, writing a\n   literal byte, and copying a matching string.\n\n   When returning, a \"goto inf_leave\" is used to update the total counters,\n   update the check value, and determine whether any progress has been made\n   during that inflate() call in order to return the proper return code.\n   Progress is defined as a change in either strm->avail_in or strm->avail_out.\n   When there is a window, goto inf_leave will update the window with the last\n   output written.  If a goto inf_leave occurs in the middle of decompression\n   and there is no window currently, goto inf_leave will create one and copy\n   output to the window for the next call of inflate().\n\n   In this implementation, the flush parameter of inflate() only affects the\n   return code (per zlib.h).  inflate() always writes as much as possible to\n   strm->next_out, given the space available and the provided input--the effect\n   documented in zlib.h of Z_SYNC_FLUSH.  Furthermore, inflate() always defers\n   the allocation of and copying into a sliding window until necessary, which\n   provides the effect documented in zlib.h for Z_FINISH when the entire input\n   stream available.  So the only thing the flush parameter actually does is:\n   when flush is set to Z_FINISH, inflate() cannot return Z_OK.  Instead it\n   will return Z_BUF_ERROR if it has not reached the end of the stream.\n */\n\nint ZEXPORT inflate(strm, flush)\nz_streamp strm;\nint flush;\n{\n    struct inflate_state FAR *state;\n    z_const unsigned char FAR *next;    /* next input */\n    unsigned char FAR *put;     /* next output */\n    unsigned have, left;        /* available input and output */\n    unsigned long hold;         /* bit buffer */\n    unsigned bits;              /* bits in bit buffer */\n    unsigned in, out;           /* save starting available input and output */\n    unsigned copy;              /* number of stored or match bytes to copy */\n    unsigned char FAR *from;    /* where to copy match bytes from */\n    code here;                  /* current decoding table entry */\n    code last;                  /* parent table entry */\n    unsigned len;               /* length to copy for repeats, bits to drop */\n    int ret;                    /* return code */\n#ifdef GUNZIP\n    unsigned char hbuf[4];      /* buffer for gzip header crc calculation */\n#endif\n    static const unsigned short order[19] = /* permutation of code lengths */\n        {16, 17, 18, 0, 8, 7, 9, 6, 10, 5, 11, 4, 12, 3, 13, 2, 14, 1, 15};\n\n    if (strm == Z_NULL || strm->state == Z_NULL || strm->next_out == Z_NULL ||\n        (strm->next_in == Z_NULL && strm->avail_in != 0))\n        return Z_STREAM_ERROR;\n\n    state = (struct inflate_state FAR *)strm->state;\n    if (state->mode == TYPE) state->mode = TYPEDO;      /* skip check */\n    LOAD();\n    in = have;\n    out = left;\n    ret = Z_OK;\n    for (;;)\n        switch (state->mode) {\n        case HEAD:\n            if (state->wrap == 0) {\n                state->mode = TYPEDO;\n                break;\n            }\n            NEEDBITS(16);\n#ifdef GUNZIP\n            if ((state->wrap & 2) && hold == 0x8b1f) {  /* gzip header */\n                state->check = crc32(0L, Z_NULL, 0);\n                CRC2(state->check, hold);\n                INITBITS();\n                state->mode = FLAGS;\n                break;\n            }\n            state->flags = 0;           /* expect zlib header */\n            if (state->head != Z_NULL)\n                state->head->done = -1;\n            if (!(state->wrap & 1) ||   /* check if zlib header allowed */\n#else\n            if (\n#endif\n                ((BITS(8) << 8) + (hold >> 8)) % 31) {\n                strm->msg = (char *)\"incorrect header check\";\n                state->mode = BAD;\n                break;\n            }\n            if (BITS(4) != Z_DEFLATED) {\n                strm->msg = (char *)\"unknown compression method\";\n                state->mode = BAD;\n                break;\n            }\n            DROPBITS(4);\n            len = BITS(4) + 8;\n            if (state->wbits == 0)\n                state->wbits = len;\n            else if (len > state->wbits) {\n                strm->msg = (char *)\"invalid window size\";\n                state->mode = BAD;\n                break;\n            }\n            state->dmax = 1U << len;\n            Tracev((stderr, \"inflate:   zlib header ok\\n\"));\n            strm->adler = state->check = adler32(0L, Z_NULL, 0);\n            state->mode = hold & 0x200 ? DICTID : TYPE;\n            INITBITS();\n            break;\n#ifdef GUNZIP\n        case FLAGS:\n            NEEDBITS(16);\n            state->flags = (int)(hold);\n            if ((state->flags & 0xff) != Z_DEFLATED) {\n                strm->msg = (char *)\"unknown compression method\";\n                state->mode = BAD;\n                break;\n            }\n            if (state->flags & 0xe000) {\n                strm->msg = (char *)\"unknown header flags set\";\n                state->mode = BAD;\n                break;\n            }\n            if (state->head != Z_NULL)\n                state->head->text = (int)((hold >> 8) & 1);\n            if (state->flags & 0x0200) CRC2(state->check, hold);\n            INITBITS();\n            state->mode = TIME;\n        case TIME:\n            NEEDBITS(32);\n            if (state->head != Z_NULL)\n                state->head->time = hold;\n            if (state->flags & 0x0200) CRC4(state->check, hold);\n            INITBITS();\n            state->mode = OS;\n        case OS:\n            NEEDBITS(16);\n            if (state->head != Z_NULL) {\n                state->head->xflags = (int)(hold & 0xff);\n                state->head->os = (int)(hold >> 8);\n            }\n            if (state->flags & 0x0200) CRC2(state->check, hold);\n            INITBITS();\n            state->mode = EXLEN;\n        case EXLEN:\n            if (state->flags & 0x0400) {\n                NEEDBITS(16);\n                state->length = (unsigned)(hold);\n                if (state->head != Z_NULL)\n                    state->head->extra_len = (unsigned)hold;\n                if (state->flags & 0x0200) CRC2(state->check, hold);\n                INITBITS();\n            }\n            else if (state->head != Z_NULL)\n                state->head->extra = Z_NULL;\n            state->mode = EXTRA;\n        case EXTRA:\n            if (state->flags & 0x0400) {\n                copy = state->length;\n                if (copy > have) copy = have;\n                if (copy) {\n                    if (state->head != Z_NULL &&\n                        state->head->extra != Z_NULL) {\n                        len = state->head->extra_len - state->length;\n                        zmemcpy(state->head->extra + len, next,\n                                len + copy > state->head->extra_max ?\n                                state->head->extra_max - len : copy);\n                    }\n                    if (state->flags & 0x0200)\n                        state->check = crc32(state->check, next, copy);\n                    have -= copy;\n                    next += copy;\n                    state->length -= copy;\n                }\n                if (state->length) goto inf_leave;\n            }\n            state->length = 0;\n            state->mode = NAME;\n        case NAME:\n            if (state->flags & 0x0800) {\n                if (have == 0) goto inf_leave;\n                copy = 0;\n                do {\n                    len = (unsigned)(next[copy++]);\n                    if (state->head != Z_NULL &&\n                            state->head->name != Z_NULL &&\n                            state->length < state->head->name_max)\n                        state->head->name[state->length++] = len;\n                } while (len && copy < have);\n                if (state->flags & 0x0200)\n                    state->check = crc32(state->check, next, copy);\n                have -= copy;\n                next += copy;\n                if (len) goto inf_leave;\n            }\n            else if (state->head != Z_NULL)\n                state->head->name = Z_NULL;\n            state->length = 0;\n            state->mode = COMMENT;\n        case COMMENT:\n            if (state->flags & 0x1000) {\n                if (have == 0) goto inf_leave;\n                copy = 0;\n                do {\n                    len = (unsigned)(next[copy++]);\n                    if (state->head != Z_NULL &&\n                            state->head->comment != Z_NULL &&\n                            state->length < state->head->comm_max)\n                        state->head->comment[state->length++] = len;\n                } while (len && copy < have);\n                if (state->flags & 0x0200)\n                    state->check = crc32(state->check, next, copy);\n                have -= copy;\n                next += copy;\n                if (len) goto inf_leave;\n            }\n            else if (state->head != Z_NULL)\n                state->head->comment = Z_NULL;\n            state->mode = HCRC;\n        case HCRC:\n            if (state->flags & 0x0200) {\n                NEEDBITS(16);\n                if (hold != (state->check & 0xffff)) {\n                    strm->msg = (char *)\"header crc mismatch\";\n                    state->mode = BAD;\n                    break;\n                }\n                INITBITS();\n            }\n            if (state->head != Z_NULL) {\n                state->head->hcrc = (int)((state->flags >> 9) & 1);\n                state->head->done = 1;\n            }\n            strm->adler = state->check = crc32(0L, Z_NULL, 0);\n            state->mode = TYPE;\n            break;\n#endif\n        case DICTID:\n            NEEDBITS(32);\n            strm->adler = state->check = ZSWAP32(hold);\n            INITBITS();\n            state->mode = DICT;\n        case DICT:\n            if (state->havedict == 0) {\n                RESTORE();\n                return Z_NEED_DICT;\n            }\n            strm->adler = state->check = adler32(0L, Z_NULL, 0);\n            state->mode = TYPE;\n        case TYPE:\n            if (flush == Z_BLOCK || flush == Z_TREES) goto inf_leave;\n        case TYPEDO:\n            if (state->last) {\n                BYTEBITS();\n                state->mode = CHECK;\n                break;\n            }\n            NEEDBITS(3);\n            state->last = BITS(1);\n            DROPBITS(1);\n            switch (BITS(2)) {\n            case 0:                             /* stored block */\n                Tracev((stderr, \"inflate:     stored block%s\\n\",\n                        state->last ? \" (last)\" : \"\"));\n                state->mode = STORED;\n                break;\n            case 1:                             /* fixed block */\n                fixedtables(state);\n                Tracev((stderr, \"inflate:     fixed codes block%s\\n\",\n                        state->last ? \" (last)\" : \"\"));\n                state->mode = LEN_;             /* decode codes */\n                if (flush == Z_TREES) {\n                    DROPBITS(2);\n                    goto inf_leave;\n                }\n                break;\n            case 2:                             /* dynamic block */\n                Tracev((stderr, \"inflate:     dynamic codes block%s\\n\",\n                        state->last ? \" (last)\" : \"\"));\n                state->mode = TABLE;\n                break;\n            case 3:\n                strm->msg = (char *)\"invalid block type\";\n                state->mode = BAD;\n            }\n            DROPBITS(2);\n            break;\n        case STORED:\n            BYTEBITS();                         /* go to byte boundary */\n            NEEDBITS(32);\n            if ((hold & 0xffff) != ((hold >> 16) ^ 0xffff)) {\n                strm->msg = (char *)\"invalid stored block lengths\";\n                state->mode = BAD;\n                break;\n            }\n            state->length = (unsigned)hold & 0xffff;\n            Tracev((stderr, \"inflate:       stored length %u\\n\",\n                    state->length));\n            INITBITS();\n            state->mode = COPY_;\n            if (flush == Z_TREES) goto inf_leave;\n        case COPY_:\n            state->mode = COPY;\n        case COPY:\n            copy = state->length;\n            if (copy) {\n                if (copy > have) copy = have;\n                if (copy > left) copy = left;\n                if (copy == 0) goto inf_leave;\n                zmemcpy(put, next, copy);\n                have -= copy;\n                next += copy;\n                left -= copy;\n                put += copy;\n                state->length -= copy;\n                break;\n            }\n            Tracev((stderr, \"inflate:       stored end\\n\"));\n            state->mode = TYPE;\n            break;\n        case TABLE:\n            NEEDBITS(14);\n            state->nlen = BITS(5) + 257;\n            DROPBITS(5);\n            state->ndist = BITS(5) + 1;\n            DROPBITS(5);\n            state->ncode = BITS(4) + 4;\n            DROPBITS(4);\n#ifndef PKZIP_BUG_WORKAROUND\n            if (state->nlen > 286 || state->ndist > 30) {\n                strm->msg = (char *)\"too many length or distance symbols\";\n                state->mode = BAD;\n                break;\n            }\n#endif\n            Tracev((stderr, \"inflate:       table sizes ok\\n\"));\n            state->have = 0;\n            state->mode = LENLENS;\n        case LENLENS:\n            while (state->have < state->ncode) {\n                NEEDBITS(3);\n                state->lens[order[state->have++]] = (unsigned short)BITS(3);\n                DROPBITS(3);\n            }\n            while (state->have < 19)\n                state->lens[order[state->have++]] = 0;\n            state->next = state->codes;\n            state->lencode = (const code FAR *)(state->next);\n            state->lenbits = 7;\n            ret = inflate_table(CODES, state->lens, 19, &(state->next),\n                                &(state->lenbits), state->work);\n            if (ret) {\n                strm->msg = (char *)\"invalid code lengths set\";\n                state->mode = BAD;\n                break;\n            }\n            Tracev((stderr, \"inflate:       code lengths ok\\n\"));\n            state->have = 0;\n            state->mode = CODELENS;\n        case CODELENS:\n            while (state->have < state->nlen + state->ndist) {\n                for (;;) {\n                    here = state->lencode[BITS(state->lenbits)];\n                    if ((unsigned)(here.bits) <= bits) break;\n                    PULLBYTE();\n                }\n                if (here.val < 16) {\n                    DROPBITS(here.bits);\n                    state->lens[state->have++] = here.val;\n                }\n                else {\n                    if (here.val == 16) {\n                        NEEDBITS(here.bits + 2);\n                        DROPBITS(here.bits);\n                        if (state->have == 0) {\n                            strm->msg = (char *)\"invalid bit length repeat\";\n                            state->mode = BAD;\n                            break;\n                        }\n                        len = state->lens[state->have - 1];\n                        copy = 3 + BITS(2);\n                        DROPBITS(2);\n                    }\n                    else if (here.val == 17) {\n                        NEEDBITS(here.bits + 3);\n                        DROPBITS(here.bits);\n                        len = 0;\n                        copy = 3 + BITS(3);\n                        DROPBITS(3);\n                    }\n                    else {\n                        NEEDBITS(here.bits + 7);\n                        DROPBITS(here.bits);\n                        len = 0;\n                        copy = 11 + BITS(7);\n                        DROPBITS(7);\n                    }\n                    if (state->have + copy > state->nlen + state->ndist) {\n                        strm->msg = (char *)\"invalid bit length repeat\";\n                        state->mode = BAD;\n                        break;\n                    }\n                    while (copy--)\n                        state->lens[state->have++] = (unsigned short)len;\n                }\n            }\n\n            /* handle error breaks in while */\n            if (state->mode == BAD) break;\n\n            /* check for end-of-block code (better have one) */\n            if (state->lens[256] == 0) {\n                strm->msg = (char *)\"invalid code -- missing end-of-block\";\n                state->mode = BAD;\n                break;\n            }\n\n            /* build code tables -- note: do not change the lenbits or distbits\n               values here (9 and 6) without reading the comments in inftrees.h\n               concerning the ENOUGH constants, which depend on those values */\n            state->next = state->codes;\n            state->lencode = (const code FAR *)(state->next);\n            state->lenbits = 9;\n            ret = inflate_table(LENS, state->lens, state->nlen, &(state->next),\n                                &(state->lenbits), state->work);\n            if (ret) {\n                strm->msg = (char *)\"invalid literal/lengths set\";\n                state->mode = BAD;\n                break;\n            }\n            state->distcode = (const code FAR *)(state->next);\n            state->distbits = 6;\n            ret = inflate_table(DISTS, state->lens + state->nlen, state->ndist,\n                            &(state->next), &(state->distbits), state->work);\n            if (ret) {\n                strm->msg = (char *)\"invalid distances set\";\n                state->mode = BAD;\n                break;\n            }\n            Tracev((stderr, \"inflate:       codes ok\\n\"));\n            state->mode = LEN_;\n            if (flush == Z_TREES) goto inf_leave;\n        case LEN_:\n            state->mode = LEN;\n        case LEN:\n            if (have >= 6 && left >= 258) {\n                RESTORE();\n                inflate_fast(strm, out);\n                LOAD();\n                if (state->mode == TYPE)\n                    state->back = -1;\n                break;\n            }\n            state->back = 0;\n            for (;;) {\n                here = state->lencode[BITS(state->lenbits)];\n                if ((unsigned)(here.bits) <= bits) break;\n                PULLBYTE();\n            }\n            if (here.op && (here.op & 0xf0) == 0) {\n                last = here;\n                for (;;) {\n                    here = state->lencode[last.val +\n                            (BITS(last.bits + last.op) >> last.bits)];\n                    if ((unsigned)(last.bits + here.bits) <= bits) break;\n                    PULLBYTE();\n                }\n                DROPBITS(last.bits);\n                state->back += last.bits;\n            }\n            DROPBITS(here.bits);\n            state->back += here.bits;\n            state->length = (unsigned)here.val;\n            if ((int)(here.op) == 0) {\n                Tracevv((stderr, here.val >= 0x20 && here.val < 0x7f ?\n                        \"inflate:         literal '%c'\\n\" :\n                        \"inflate:         literal 0x%02x\\n\", here.val));\n                state->mode = LIT;\n                break;\n            }\n            if (here.op & 32) {\n                Tracevv((stderr, \"inflate:         end of block\\n\"));\n                state->back = -1;\n                state->mode = TYPE;\n                break;\n            }\n            if (here.op & 64) {\n                strm->msg = (char *)\"invalid literal/length code\";\n                state->mode = BAD;\n                break;\n            }\n            state->extra = (unsigned)(here.op) & 15;\n            state->mode = LENEXT;\n        case LENEXT:\n            if (state->extra) {\n                NEEDBITS(state->extra);\n                state->length += BITS(state->extra);\n                DROPBITS(state->extra);\n                state->back += state->extra;\n            }\n            Tracevv((stderr, \"inflate:         length %u\\n\", state->length));\n            state->was = state->length;\n            state->mode = DIST;\n        case DIST:\n            for (;;) {\n                here = state->distcode[BITS(state->distbits)];\n                if ((unsigned)(here.bits) <= bits) break;\n                PULLBYTE();\n            }\n            if ((here.op & 0xf0) == 0) {\n                last = here;\n                for (;;) {\n                    here = state->distcode[last.val +\n                            (BITS(last.bits + last.op) >> last.bits)];\n                    if ((unsigned)(last.bits + here.bits) <= bits) break;\n                    PULLBYTE();\n                }\n                DROPBITS(last.bits);\n                state->back += last.bits;\n            }\n            DROPBITS(here.bits);\n            state->back += here.bits;\n            if (here.op & 64) {\n                strm->msg = (char *)\"invalid distance code\";\n                state->mode = BAD;\n                break;\n            }\n            state->offset = (unsigned)here.val;\n            state->extra = (unsigned)(here.op) & 15;\n            state->mode = DISTEXT;\n        case DISTEXT:\n            if (state->extra) {\n                NEEDBITS(state->extra);\n                state->offset += BITS(state->extra);\n                DROPBITS(state->extra);\n                state->back += state->extra;\n            }\n#ifdef INFLATE_STRICT\n            if (state->offset > state->dmax) {\n                strm->msg = (char *)\"invalid distance too far back\";\n                state->mode = BAD;\n                break;\n            }\n#endif\n            Tracevv((stderr, \"inflate:         distance %u\\n\", state->offset));\n            state->mode = MATCH;\n        case MATCH:\n            if (left == 0) goto inf_leave;\n            copy = out - left;\n            if (state->offset > copy) {         /* copy from window */\n                copy = state->offset - copy;\n                if (copy > state->whave) {\n                    if (state->sane) {\n                        strm->msg = (char *)\"invalid distance too far back\";\n                        state->mode = BAD;\n                        break;\n                    }\n#ifdef INFLATE_ALLOW_INVALID_DISTANCE_TOOFAR_ARRR\n                    Trace((stderr, \"inflate.c too far\\n\"));\n                    copy -= state->whave;\n                    if (copy > state->length) copy = state->length;\n                    if (copy > left) copy = left;\n                    left -= copy;\n                    state->length -= copy;\n                    do {\n                        *put++ = 0;\n                    } while (--copy);\n                    if (state->length == 0) state->mode = LEN;\n                    break;\n#endif\n                }\n                if (copy > state->wnext) {\n                    copy -= state->wnext;\n                    from = state->window + (state->wsize - copy);\n                }\n                else\n                    from = state->window + (state->wnext - copy);\n                if (copy > state->length) copy = state->length;\n            }\n            else {                              /* copy from output */\n                from = put - state->offset;\n                copy = state->length;\n            }\n            if (copy > left) copy = left;\n            left -= copy;\n            state->length -= copy;\n            do {\n                *put++ = *from++;\n            } while (--copy);\n            if (state->length == 0) state->mode = LEN;\n            break;\n        case LIT:\n            if (left == 0) goto inf_leave;\n            *put++ = (unsigned char)(state->length);\n            left--;\n            state->mode = LEN;\n            break;\n        case CHECK:\n            if (state->wrap) {\n                NEEDBITS(32);\n                out -= left;\n                strm->total_out += out;\n                state->total += out;\n                if (out)\n                    strm->adler = state->check =\n                        UPDATE(state->check, put - out, out);\n                out = left;\n                if ((\n#ifdef GUNZIP\n                     state->flags ? hold :\n#endif\n                     ZSWAP32(hold)) != state->check) {\n                    strm->msg = (char *)\"incorrect data check\";\n                    state->mode = BAD;\n                    break;\n                }\n                INITBITS();\n                Tracev((stderr, \"inflate:   check matches trailer\\n\"));\n            }\n#ifdef GUNZIP\n            state->mode = LENGTH;\n        case LENGTH:\n            if (state->wrap && state->flags) {\n                NEEDBITS(32);\n                if (hold != (state->total & 0xffffffffUL)) {\n                    strm->msg = (char *)\"incorrect length check\";\n                    state->mode = BAD;\n                    break;\n                }\n                INITBITS();\n                Tracev((stderr, \"inflate:   length matches trailer\\n\"));\n            }\n#endif\n            state->mode = DONE;\n        case DONE:\n            ret = Z_STREAM_END;\n            goto inf_leave;\n        case BAD:\n            ret = Z_DATA_ERROR;\n            goto inf_leave;\n        case MEM:\n            return Z_MEM_ERROR;\n        case SYNC:\n        default:\n            return Z_STREAM_ERROR;\n        }\n\n    /*\n       Return from inflate(), updating the total counts and the check value.\n       If there was no progress during the inflate() call, return a buffer\n       error.  Call updatewindow() to create and/or update the window state.\n       Note: a memory error from inflate() is non-recoverable.\n     */\n  inf_leave:\n    RESTORE();\n    if (state->wsize || (out != strm->avail_out && state->mode < BAD &&\n            (state->mode < CHECK || flush != Z_FINISH)))\n        if (updatewindow(strm, strm->next_out, out - strm->avail_out)) {\n            state->mode = MEM;\n            return Z_MEM_ERROR;\n        }\n    in -= strm->avail_in;\n    out -= strm->avail_out;\n    strm->total_in += in;\n    strm->total_out += out;\n    state->total += out;\n    if (state->wrap && out)\n        strm->adler = state->check =\n            UPDATE(state->check, strm->next_out - out, out);\n    strm->data_type = state->bits + (state->last ? 64 : 0) +\n                      (state->mode == TYPE ? 128 : 0) +\n                      (state->mode == LEN_ || state->mode == COPY_ ? 256 : 0);\n    if (((in == 0 && out == 0) || flush == Z_FINISH) && ret == Z_OK)\n        ret = Z_BUF_ERROR;\n    return ret;\n}\n\nint ZEXPORT inflateEnd(strm)\nz_streamp strm;\n{\n    struct inflate_state FAR *state;\n    if (strm == Z_NULL || strm->state == Z_NULL || strm->zfree == (free_func)0)\n        return Z_STREAM_ERROR;\n    state = (struct inflate_state FAR *)strm->state;\n    if (state->window != Z_NULL) ZFREE(strm, state->window);\n    ZFREE(strm, strm->state);\n    strm->state = Z_NULL;\n    Tracev((stderr, \"inflate: end\\n\"));\n    return Z_OK;\n}\n\nint ZEXPORT inflateGetDictionary(strm, dictionary, dictLength)\nz_streamp strm;\nBytef *dictionary;\nuInt *dictLength;\n{\n    struct inflate_state FAR *state;\n\n    /* check state */\n    if (strm == Z_NULL || strm->state == Z_NULL) return Z_STREAM_ERROR;\n    state = (struct inflate_state FAR *)strm->state;\n\n    /* copy dictionary */\n    if (state->whave && dictionary != Z_NULL) {\n        zmemcpy(dictionary, state->window + state->wnext,\n                state->whave - state->wnext);\n        zmemcpy(dictionary + state->whave - state->wnext,\n                state->window, state->wnext);\n    }\n    if (dictLength != Z_NULL)\n        *dictLength = state->whave;\n    return Z_OK;\n}\n\nint ZEXPORT inflateSetDictionary(strm, dictionary, dictLength)\nz_streamp strm;\nconst Bytef *dictionary;\nuInt dictLength;\n{\n    struct inflate_state FAR *state;\n    unsigned long dictid;\n    int ret;\n\n    /* check state */\n    if (strm == Z_NULL || strm->state == Z_NULL) return Z_STREAM_ERROR;\n    state = (struct inflate_state FAR *)strm->state;\n    if (state->wrap != 0 && state->mode != DICT)\n        return Z_STREAM_ERROR;\n\n    /* check for correct dictionary identifier */\n    if (state->mode == DICT) {\n        dictid = adler32(0L, Z_NULL, 0);\n        dictid = adler32(dictid, dictionary, dictLength);\n        if (dictid != state->check)\n            return Z_DATA_ERROR;\n    }\n\n    /* copy dictionary to window using updatewindow(), which will amend the\n       existing dictionary if appropriate */\n    ret = updatewindow(strm, dictionary + dictLength, dictLength);\n    if (ret) {\n        state->mode = MEM;\n        return Z_MEM_ERROR;\n    }\n    state->havedict = 1;\n    Tracev((stderr, \"inflate:   dictionary set\\n\"));\n    return Z_OK;\n}\n\nint ZEXPORT inflateGetHeader(strm, head)\nz_streamp strm;\ngz_headerp head;\n{\n    struct inflate_state FAR *state;\n\n    /* check state */\n    if (strm == Z_NULL || strm->state == Z_NULL) return Z_STREAM_ERROR;\n    state = (struct inflate_state FAR *)strm->state;\n    if ((state->wrap & 2) == 0) return Z_STREAM_ERROR;\n\n    /* save header structure */\n    state->head = head;\n    head->done = 0;\n    return Z_OK;\n}\n\n/*\n   Search buf[0..len-1] for the pattern: 0, 0, 0xff, 0xff.  Return when found\n   or when out of input.  When called, *have is the number of pattern bytes\n   found in order so far, in 0..3.  On return *have is updated to the new\n   state.  If on return *have equals four, then the pattern was found and the\n   return value is how many bytes were read including the last byte of the\n   pattern.  If *have is less than four, then the pattern has not been found\n   yet and the return value is len.  In the latter case, syncsearch() can be\n   called again with more data and the *have state.  *have is initialized to\n   zero for the first call.\n */\nlocal unsigned syncsearch(have, buf, len)\nunsigned FAR *have;\nconst unsigned char FAR *buf;\nunsigned len;\n{\n    unsigned got;\n    unsigned next;\n\n    got = *have;\n    next = 0;\n    while (next < len && got < 4) {\n        if ((int)(buf[next]) == (got < 2 ? 0 : 0xff))\n            got++;\n        else if (buf[next])\n            got = 0;\n        else\n            got = 4 - got;\n        next++;\n    }\n    *have = got;\n    return next;\n}\n\nint ZEXPORT inflateSync(strm)\nz_streamp strm;\n{\n    unsigned len;               /* number of bytes to look at or looked at */\n    unsigned long in, out;      /* temporary to save total_in and total_out */\n    unsigned char buf[4];       /* to restore bit buffer to byte string */\n    struct inflate_state FAR *state;\n\n    /* check parameters */\n    if (strm == Z_NULL || strm->state == Z_NULL) return Z_STREAM_ERROR;\n    state = (struct inflate_state FAR *)strm->state;\n    if (strm->avail_in == 0 && state->bits < 8) return Z_BUF_ERROR;\n\n    /* if first time, start search in bit buffer */\n    if (state->mode != SYNC) {\n        state->mode = SYNC;\n        state->hold <<= state->bits & 7;\n        state->bits -= state->bits & 7;\n        len = 0;\n        while (state->bits >= 8) {\n            buf[len++] = (unsigned char)(state->hold);\n            state->hold >>= 8;\n            state->bits -= 8;\n        }\n        state->have = 0;\n        syncsearch(&(state->have), buf, len);\n    }\n\n    /* search available input */\n    len = syncsearch(&(state->have), strm->next_in, strm->avail_in);\n    strm->avail_in -= len;\n    strm->next_in += len;\n    strm->total_in += len;\n\n    /* return no joy or set up to restart inflate() on a new block */\n    if (state->have != 4) return Z_DATA_ERROR;\n    in = strm->total_in;  out = strm->total_out;\n    inflateReset(strm);\n    strm->total_in = in;  strm->total_out = out;\n    state->mode = TYPE;\n    return Z_OK;\n}\n\n/*\n   Returns true if inflate is currently at the end of a block generated by\n   Z_SYNC_FLUSH or Z_FULL_FLUSH. This function is used by one PPP\n   implementation to provide an additional safety check. PPP uses\n   Z_SYNC_FLUSH but removes the length bytes of the resulting empty stored\n   block. When decompressing, PPP checks that at the end of input packet,\n   inflate is waiting for these length bytes.\n */\nint ZEXPORT inflateSyncPoint(strm)\nz_streamp strm;\n{\n    struct inflate_state FAR *state;\n\n    if (strm == Z_NULL || strm->state == Z_NULL) return Z_STREAM_ERROR;\n    state = (struct inflate_state FAR *)strm->state;\n    return state->mode == STORED && state->bits == 0;\n}\n\nint ZEXPORT inflateCopy(dest, source)\nz_streamp dest;\nz_streamp source;\n{\n    struct inflate_state FAR *state;\n    struct inflate_state FAR *copy;\n    unsigned char FAR *window;\n    unsigned wsize;\n\n    /* check input */\n    if (dest == Z_NULL || source == Z_NULL || source->state == Z_NULL ||\n        source->zalloc == (alloc_func)0 || source->zfree == (free_func)0)\n        return Z_STREAM_ERROR;\n    state = (struct inflate_state FAR *)source->state;\n\n    /* allocate space */\n    copy = (struct inflate_state FAR *)\n           ZALLOC(source, 1, sizeof(struct inflate_state));\n    if (copy == Z_NULL) return Z_MEM_ERROR;\n    window = Z_NULL;\n    if (state->window != Z_NULL) {\n        window = (unsigned char FAR *)\n                 ZALLOC(source, 1U << state->wbits, sizeof(unsigned char));\n        if (window == Z_NULL) {\n            ZFREE(source, copy);\n            return Z_MEM_ERROR;\n        }\n    }\n\n    /* copy state */\n    zmemcpy((voidpf)dest, (voidpf)source, sizeof(z_stream));\n    zmemcpy((voidpf)copy, (voidpf)state, sizeof(struct inflate_state));\n    if (state->lencode >= state->codes &&\n        state->lencode <= state->codes + ENOUGH - 1) {\n        copy->lencode = copy->codes + (state->lencode - state->codes);\n        copy->distcode = copy->codes + (state->distcode - state->codes);\n    }\n    copy->next = copy->codes + (state->next - state->codes);\n    if (window != Z_NULL) {\n        wsize = 1U << state->wbits;\n        zmemcpy(window, state->window, wsize);\n    }\n    copy->window = window;\n    dest->state = (struct internal_state FAR *)copy;\n    return Z_OK;\n}\n\nint ZEXPORT inflateUndermine(strm, subvert)\nz_streamp strm;\nint subvert;\n{\n    struct inflate_state FAR *state;\n\n    if (strm == Z_NULL || strm->state == Z_NULL) return Z_STREAM_ERROR;\n    state = (struct inflate_state FAR *)strm->state;\n    state->sane = !subvert;\n#ifdef INFLATE_ALLOW_INVALID_DISTANCE_TOOFAR_ARRR\n    return Z_OK;\n#else\n    state->sane = 1;\n    return Z_DATA_ERROR;\n#endif\n}\n\nlong ZEXPORT inflateMark(strm)\nz_streamp strm;\n{\n    struct inflate_state FAR *state;\n\n    if (strm == Z_NULL || strm->state == Z_NULL) return -1L << 16;\n    state = (struct inflate_state FAR *)strm->state;\n    return ((long)(state->back) << 16) +\n        (state->mode == COPY ? state->length :\n            (state->mode == MATCH ? state->was - state->length : 0));\n}\n"
  },
  {
    "path": "external/zlib/inflate.h",
    "content": "/* inflate.h -- internal inflate state definition\n * Copyright (C) 1995-2009 Mark Adler\n * For conditions of distribution and use, see copyright notice in zlib.h\n */\n\n/* WARNING: this file should *not* be used by applications. It is\n   part of the implementation of the compression library and is\n   subject to change. Applications should only use zlib.h.\n */\n\n/* define NO_GZIP when compiling if you want to disable gzip header and\n   trailer decoding by inflate().  NO_GZIP would be used to avoid linking in\n   the crc code when it is not needed.  For shared libraries, gzip decoding\n   should be left enabled. */\n#ifndef NO_GZIP\n#  define GUNZIP\n#endif\n\n/* Possible inflate modes between inflate() calls */\ntypedef enum {\n    HEAD,       /* i: waiting for magic header */\n    FLAGS,      /* i: waiting for method and flags (gzip) */\n    TIME,       /* i: waiting for modification time (gzip) */\n    OS,         /* i: waiting for extra flags and operating system (gzip) */\n    EXLEN,      /* i: waiting for extra length (gzip) */\n    EXTRA,      /* i: waiting for extra bytes (gzip) */\n    NAME,       /* i: waiting for end of file name (gzip) */\n    COMMENT,    /* i: waiting for end of comment (gzip) */\n    HCRC,       /* i: waiting for header crc (gzip) */\n    DICTID,     /* i: waiting for dictionary check value */\n    DICT,       /* waiting for inflateSetDictionary() call */\n        TYPE,       /* i: waiting for type bits, including last-flag bit */\n        TYPEDO,     /* i: same, but skip check to exit inflate on new block */\n        STORED,     /* i: waiting for stored size (length and complement) */\n        COPY_,      /* i/o: same as COPY below, but only first time in */\n        COPY,       /* i/o: waiting for input or output to copy stored block */\n        TABLE,      /* i: waiting for dynamic block table lengths */\n        LENLENS,    /* i: waiting for code length code lengths */\n        CODELENS,   /* i: waiting for length/lit and distance code lengths */\n            LEN_,       /* i: same as LEN below, but only first time in */\n            LEN,        /* i: waiting for length/lit/eob code */\n            LENEXT,     /* i: waiting for length extra bits */\n            DIST,       /* i: waiting for distance code */\n            DISTEXT,    /* i: waiting for distance extra bits */\n            MATCH,      /* o: waiting for output space to copy string */\n            LIT,        /* o: waiting for output space to write literal */\n    CHECK,      /* i: waiting for 32-bit check value */\n    LENGTH,     /* i: waiting for 32-bit length (gzip) */\n    DONE,       /* finished check, done -- remain here until reset */\n    BAD,        /* got a data error -- remain here until reset */\n    MEM,        /* got an inflate() memory error -- remain here until reset */\n    SYNC        /* looking for synchronization bytes to restart inflate() */\n} inflate_mode;\n\n/*\n    State transitions between above modes -\n\n    (most modes can go to BAD or MEM on error -- not shown for clarity)\n\n    Process header:\n        HEAD -> (gzip) or (zlib) or (raw)\n        (gzip) -> FLAGS -> TIME -> OS -> EXLEN -> EXTRA -> NAME -> COMMENT ->\n                  HCRC -> TYPE\n        (zlib) -> DICTID or TYPE\n        DICTID -> DICT -> TYPE\n        (raw) -> TYPEDO\n    Read deflate blocks:\n            TYPE -> TYPEDO -> STORED or TABLE or LEN_ or CHECK\n            STORED -> COPY_ -> COPY -> TYPE\n            TABLE -> LENLENS -> CODELENS -> LEN_\n            LEN_ -> LEN\n    Read deflate codes in fixed or dynamic block:\n                LEN -> LENEXT or LIT or TYPE\n                LENEXT -> DIST -> DISTEXT -> MATCH -> LEN\n                LIT -> LEN\n    Process trailer:\n        CHECK -> LENGTH -> DONE\n */\n\n/* state maintained between inflate() calls.  Approximately 10K bytes. */\nstruct inflate_state {\n    inflate_mode mode;          /* current inflate mode */\n    int last;                   /* true if processing last block */\n    int wrap;                   /* bit 0 true for zlib, bit 1 true for gzip */\n    int havedict;               /* true if dictionary provided */\n    int flags;                  /* gzip header method and flags (0 if zlib) */\n    unsigned dmax;              /* zlib header max distance (INFLATE_STRICT) */\n    unsigned long check;        /* protected copy of check value */\n    unsigned long total;        /* protected copy of output count */\n    gz_headerp head;            /* where to save gzip header information */\n        /* sliding window */\n    unsigned wbits;             /* log base 2 of requested window size */\n    unsigned wsize;             /* window size or zero if not using window */\n    unsigned whave;             /* valid bytes in the window */\n    unsigned wnext;             /* window write index */\n    unsigned char FAR *window;  /* allocated sliding window, if needed */\n        /* bit accumulator */\n    unsigned long hold;         /* input bit accumulator */\n    unsigned bits;              /* number of bits in \"in\" */\n        /* for string and stored block copying */\n    unsigned length;            /* literal or length of data to copy */\n    unsigned offset;            /* distance back to copy string from */\n        /* for table and code decoding */\n    unsigned extra;             /* extra bits needed */\n        /* fixed and dynamic code tables */\n    code const FAR *lencode;    /* starting table for length/literal codes */\n    code const FAR *distcode;   /* starting table for distance codes */\n    unsigned lenbits;           /* index bits for lencode */\n    unsigned distbits;          /* index bits for distcode */\n        /* dynamic table building */\n    unsigned ncode;             /* number of code length code lengths */\n    unsigned nlen;              /* number of length code lengths */\n    unsigned ndist;             /* number of distance code lengths */\n    unsigned have;              /* number of code lengths in lens[] */\n    code FAR *next;             /* next available space in codes[] */\n    unsigned short lens[320];   /* temporary storage for code lengths */\n    unsigned short work[288];   /* work area for code table building */\n    code codes[ENOUGH];         /* space for code tables */\n    int sane;                   /* if false, allow invalid distance too far */\n    int back;                   /* bits back of last unprocessed length/lit */\n    unsigned was;               /* initial length of match */\n};\n"
  },
  {
    "path": "external/zlib/inftrees.c",
    "content": "/* inftrees.c -- generate Huffman trees for efficient decoding\n * Copyright (C) 1995-2013 Mark Adler\n * For conditions of distribution and use, see copyright notice in zlib.h\n */\n\n#include \"zutil.h\"\n#include \"inftrees.h\"\n\n#define MAXBITS 15\n\nconst char inflate_copyright[] =\n   \" inflate 1.2.8 Copyright 1995-2013 Mark Adler \";\n/*\n  If you use the zlib library in a product, an acknowledgment is welcome\n  in the documentation of your product. If for some reason you cannot\n  include such an acknowledgment, I would appreciate that you keep this\n  copyright string in the executable of your product.\n */\n\n/*\n   Build a set of tables to decode the provided canonical Huffman code.\n   The code lengths are lens[0..codes-1].  The result starts at *table,\n   whose indices are 0..2^bits-1.  work is a writable array of at least\n   lens shorts, which is used as a work area.  type is the type of code\n   to be generated, CODES, LENS, or DISTS.  On return, zero is success,\n   -1 is an invalid code, and +1 means that ENOUGH isn't enough.  table\n   on return points to the next available entry's address.  bits is the\n   requested root table index bits, and on return it is the actual root\n   table index bits.  It will differ if the request is greater than the\n   longest code or if it is less than the shortest code.\n */\nint ZLIB_INTERNAL inflate_table(type, lens, codes, table, bits, work)\ncodetype type;\nunsigned short FAR *lens;\nunsigned codes;\ncode FAR * FAR *table;\nunsigned FAR *bits;\nunsigned short FAR *work;\n{\n    unsigned len;               /* a code's length in bits */\n    unsigned sym;               /* index of code symbols */\n    unsigned min, max;          /* minimum and maximum code lengths */\n    unsigned root;              /* number of index bits for root table */\n    unsigned curr;              /* number of index bits for current table */\n    unsigned drop;              /* code bits to drop for sub-table */\n    int left;                   /* number of prefix codes available */\n    unsigned used;              /* code entries in table used */\n    unsigned huff;              /* Huffman code */\n    unsigned incr;              /* for incrementing code, index */\n    unsigned fill;              /* index for replicating entries */\n    unsigned low;               /* low bits for current root entry */\n    unsigned mask;              /* mask for low root bits */\n    code here;                  /* table entry for duplication */\n    code FAR *next;             /* next available space in table */\n    const unsigned short FAR *base;     /* base value table to use */\n    const unsigned short FAR *extra;    /* extra bits table to use */\n    int end;                    /* use base and extra for symbol > end */\n    unsigned short count[MAXBITS+1];    /* number of codes of each length */\n    unsigned short offs[MAXBITS+1];     /* offsets in table for each length */\n    static const unsigned short lbase[31] = { /* Length codes 257..285 base */\n        3, 4, 5, 6, 7, 8, 9, 10, 11, 13, 15, 17, 19, 23, 27, 31,\n        35, 43, 51, 59, 67, 83, 99, 115, 131, 163, 195, 227, 258, 0, 0};\n    static const unsigned short lext[31] = { /* Length codes 257..285 extra */\n        16, 16, 16, 16, 16, 16, 16, 16, 17, 17, 17, 17, 18, 18, 18, 18,\n        19, 19, 19, 19, 20, 20, 20, 20, 21, 21, 21, 21, 16, 72, 78};\n    static const unsigned short dbase[32] = { /* Distance codes 0..29 base */\n        1, 2, 3, 4, 5, 7, 9, 13, 17, 25, 33, 49, 65, 97, 129, 193,\n        257, 385, 513, 769, 1025, 1537, 2049, 3073, 4097, 6145,\n        8193, 12289, 16385, 24577, 0, 0};\n    static const unsigned short dext[32] = { /* Distance codes 0..29 extra */\n        16, 16, 16, 16, 17, 17, 18, 18, 19, 19, 20, 20, 21, 21, 22, 22,\n        23, 23, 24, 24, 25, 25, 26, 26, 27, 27,\n        28, 28, 29, 29, 64, 64};\n\n    /*\n       Process a set of code lengths to create a canonical Huffman code.  The\n       code lengths are lens[0..codes-1].  Each length corresponds to the\n       symbols 0..codes-1.  The Huffman code is generated by first sorting the\n       symbols by length from short to long, and retaining the symbol order\n       for codes with equal lengths.  Then the code starts with all zero bits\n       for the first code of the shortest length, and the codes are integer\n       increments for the same length, and zeros are appended as the length\n       increases.  For the deflate format, these bits are stored backwards\n       from their more natural integer increment ordering, and so when the\n       decoding tables are built in the large loop below, the integer codes\n       are incremented backwards.\n\n       This routine assumes, but does not check, that all of the entries in\n       lens[] are in the range 0..MAXBITS.  The caller must assure this.\n       1..MAXBITS is interpreted as that code length.  zero means that that\n       symbol does not occur in this code.\n\n       The codes are sorted by computing a count of codes for each length,\n       creating from that a table of starting indices for each length in the\n       sorted table, and then entering the symbols in order in the sorted\n       table.  The sorted table is work[], with that space being provided by\n       the caller.\n\n       The length counts are used for other purposes as well, i.e. finding\n       the minimum and maximum length codes, determining if there are any\n       codes at all, checking for a valid set of lengths, and looking ahead\n       at length counts to determine sub-table sizes when building the\n       decoding tables.\n     */\n\n    /* accumulate lengths for codes (assumes lens[] all in 0..MAXBITS) */\n    for (len = 0; len <= MAXBITS; len++)\n        count[len] = 0;\n    for (sym = 0; sym < codes; sym++)\n        count[lens[sym]]++;\n\n    /* bound code lengths, force root to be within code lengths */\n    root = *bits;\n    for (max = MAXBITS; max >= 1; max--)\n        if (count[max] != 0) break;\n    if (root > max) root = max;\n    if (max == 0) {                     /* no symbols to code at all */\n        here.op = (unsigned char)64;    /* invalid code marker */\n        here.bits = (unsigned char)1;\n        here.val = (unsigned short)0;\n        *(*table)++ = here;             /* make a table to force an error */\n        *(*table)++ = here;\n        *bits = 1;\n        return 0;     /* no symbols, but wait for decoding to report error */\n    }\n    for (min = 1; min < max; min++)\n        if (count[min] != 0) break;\n    if (root < min) root = min;\n\n    /* check for an over-subscribed or incomplete set of lengths */\n    left = 1;\n    for (len = 1; len <= MAXBITS; len++) {\n        left <<= 1;\n        left -= count[len];\n        if (left < 0) return -1;        /* over-subscribed */\n    }\n    if (left > 0 && (type == CODES || max != 1))\n        return -1;                      /* incomplete set */\n\n    /* generate offsets into symbol table for each length for sorting */\n    offs[1] = 0;\n    for (len = 1; len < MAXBITS; len++)\n        offs[len + 1] = offs[len] + count[len];\n\n    /* sort symbols by length, by symbol order within each length */\n    for (sym = 0; sym < codes; sym++)\n        if (lens[sym] != 0) work[offs[lens[sym]]++] = (unsigned short)sym;\n\n    /*\n       Create and fill in decoding tables.  In this loop, the table being\n       filled is at next and has curr index bits.  The code being used is huff\n       with length len.  That code is converted to an index by dropping drop\n       bits off of the bottom.  For codes where len is less than drop + curr,\n       those top drop + curr - len bits are incremented through all values to\n       fill the table with replicated entries.\n\n       root is the number of index bits for the root table.  When len exceeds\n       root, sub-tables are created pointed to by the root entry with an index\n       of the low root bits of huff.  This is saved in low to check for when a\n       new sub-table should be started.  drop is zero when the root table is\n       being filled, and drop is root when sub-tables are being filled.\n\n       When a new sub-table is needed, it is necessary to look ahead in the\n       code lengths to determine what size sub-table is needed.  The length\n       counts are used for this, and so count[] is decremented as codes are\n       entered in the tables.\n\n       used keeps track of how many table entries have been allocated from the\n       provided *table space.  It is checked for LENS and DIST tables against\n       the constants ENOUGH_LENS and ENOUGH_DISTS to guard against changes in\n       the initial root table size constants.  See the comments in inftrees.h\n       for more information.\n\n       sym increments through all symbols, and the loop terminates when\n       all codes of length max, i.e. all codes, have been processed.  This\n       routine permits incomplete codes, so another loop after this one fills\n       in the rest of the decoding tables with invalid code markers.\n     */\n\n    /* set up for code type */\n    switch (type) {\n    case CODES:\n        base = extra = work;    /* dummy value--not used */\n        end = 19;\n        break;\n    case LENS:\n        base = lbase;\n        base -= 257;\n        extra = lext;\n        extra -= 257;\n        end = 256;\n        break;\n    default:            /* DISTS */\n        base = dbase;\n        extra = dext;\n        end = -1;\n    }\n\n    /* initialize state for loop */\n    huff = 0;                   /* starting code */\n    sym = 0;                    /* starting code symbol */\n    len = min;                  /* starting code length */\n    next = *table;              /* current table to fill in */\n    curr = root;                /* current table index bits */\n    drop = 0;                   /* current bits to drop from code for index */\n    low = (unsigned)(-1);       /* trigger new sub-table when len > root */\n    used = 1U << root;          /* use root table entries */\n    mask = used - 1;            /* mask for comparing low */\n\n    /* check available table space */\n    if ((type == LENS && used > ENOUGH_LENS) ||\n        (type == DISTS && used > ENOUGH_DISTS))\n        return 1;\n\n    /* process all codes and make table entries */\n    for (;;) {\n        /* create table entry */\n        here.bits = (unsigned char)(len - drop);\n        if ((int)(work[sym]) < end) {\n            here.op = (unsigned char)0;\n            here.val = work[sym];\n        }\n        else if ((int)(work[sym]) > end) {\n            here.op = (unsigned char)(extra[work[sym]]);\n            here.val = base[work[sym]];\n        }\n        else {\n            here.op = (unsigned char)(32 + 64);         /* end of block */\n            here.val = 0;\n        }\n\n        /* replicate for those indices with low len bits equal to huff */\n        incr = 1U << (len - drop);\n        fill = 1U << curr;\n        min = fill;                 /* save offset to next table */\n        do {\n            fill -= incr;\n            next[(huff >> drop) + fill] = here;\n        } while (fill != 0);\n\n        /* backwards increment the len-bit code huff */\n        incr = 1U << (len - 1);\n        while (huff & incr)\n            incr >>= 1;\n        if (incr != 0) {\n            huff &= incr - 1;\n            huff += incr;\n        }\n        else\n            huff = 0;\n\n        /* go to next symbol, update count, len */\n        sym++;\n        if (--(count[len]) == 0) {\n            if (len == max) break;\n            len = lens[work[sym]];\n        }\n\n        /* create new sub-table if needed */\n        if (len > root && (huff & mask) != low) {\n            /* if first time, transition to sub-tables */\n            if (drop == 0)\n                drop = root;\n\n            /* increment past last table */\n            next += min;            /* here min is 1 << curr */\n\n            /* determine length of next table */\n            curr = len - drop;\n            left = (int)(1 << curr);\n            while (curr + drop < max) {\n                left -= count[curr + drop];\n                if (left <= 0) break;\n                curr++;\n                left <<= 1;\n            }\n\n            /* check for enough space */\n            used += 1U << curr;\n            if ((type == LENS && used > ENOUGH_LENS) ||\n                (type == DISTS && used > ENOUGH_DISTS))\n                return 1;\n\n            /* point entry in root table to sub-table */\n            low = huff & mask;\n            (*table)[low].op = (unsigned char)curr;\n            (*table)[low].bits = (unsigned char)root;\n            (*table)[low].val = (unsigned short)(next - *table);\n        }\n    }\n\n    /* fill in remaining table entry if code is incomplete (guaranteed to have\n       at most one remaining entry, since if the code is incomplete, the\n       maximum code length that was allowed to get this far is one bit) */\n    if (huff != 0) {\n        here.op = (unsigned char)64;            /* invalid code marker */\n        here.bits = (unsigned char)(len - drop);\n        here.val = (unsigned short)0;\n        next[huff] = here;\n    }\n\n    /* set return parameters */\n    *table += used;\n    *bits = root;\n    return 0;\n}\n"
  },
  {
    "path": "external/zlib/inftrees.h",
    "content": "/* inftrees.h -- header to use inftrees.c\n * Copyright (C) 1995-2005, 2010 Mark Adler\n * For conditions of distribution and use, see copyright notice in zlib.h\n */\n\n/* WARNING: this file should *not* be used by applications. It is\n   part of the implementation of the compression library and is\n   subject to change. Applications should only use zlib.h.\n */\n\n/* Structure for decoding tables.  Each entry provides either the\n   information needed to do the operation requested by the code that\n   indexed that table entry, or it provides a pointer to another\n   table that indexes more bits of the code.  op indicates whether\n   the entry is a pointer to another table, a literal, a length or\n   distance, an end-of-block, or an invalid code.  For a table\n   pointer, the low four bits of op is the number of index bits of\n   that table.  For a length or distance, the low four bits of op\n   is the number of extra bits to get after the code.  bits is\n   the number of bits in this code or part of the code to drop off\n   of the bit buffer.  val is the actual byte to output in the case\n   of a literal, the base length or distance, or the offset from\n   the current table to the next table.  Each entry is four bytes. */\ntypedef struct {\n    unsigned char op;           /* operation, extra bits, table bits */\n    unsigned char bits;         /* bits in this part of the code */\n    unsigned short val;         /* offset in table or code value */\n} code;\n\n/* op values as set by inflate_table():\n    00000000 - literal\n    0000tttt - table link, tttt != 0 is the number of table index bits\n    0001eeee - length or distance, eeee is the number of extra bits\n    01100000 - end of block\n    01000000 - invalid code\n */\n\n/* Maximum size of the dynamic table.  The maximum number of code structures is\n   1444, which is the sum of 852 for literal/length codes and 592 for distance\n   codes.  These values were found by exhaustive searches using the program\n   examples/enough.c found in the zlib distribtution.  The arguments to that\n   program are the number of symbols, the initial root table size, and the\n   maximum bit length of a code.  \"enough 286 9 15\" for literal/length codes\n   returns returns 852, and \"enough 30 6 15\" for distance codes returns 592.\n   The initial root table size (9 or 6) is found in the fifth argument of the\n   inflate_table() calls in inflate.c and infback.c.  If the root table size is\n   changed, then these maximum sizes would be need to be recalculated and\n   updated. */\n#define ENOUGH_LENS 852\n#define ENOUGH_DISTS 592\n#define ENOUGH (ENOUGH_LENS+ENOUGH_DISTS)\n\n/* Type of code to build for inflate_table() */\ntypedef enum {\n    CODES,\n    LENS,\n    DISTS\n} codetype;\n\nint ZLIB_INTERNAL inflate_table OF((codetype type, unsigned short FAR *lens,\n                             unsigned codes, code FAR * FAR *table,\n                             unsigned FAR *bits, unsigned short FAR *work));\n"
  },
  {
    "path": "external/zlib/trees.c",
    "content": "/* trees.c -- output deflated data using Huffman coding\n * Copyright (C) 1995-2012 Jean-loup Gailly\n * detect_data_type() function provided freely by Cosmin Truta, 2006\n * For conditions of distribution and use, see copyright notice in zlib.h\n */\n\n/*\n *  ALGORITHM\n *\n *      The \"deflation\" process uses several Huffman trees. The more\n *      common source values are represented by shorter bit sequences.\n *\n *      Each code tree is stored in a compressed form which is itself\n * a Huffman encoding of the lengths of all the code strings (in\n * ascending order by source values).  The actual code strings are\n * reconstructed from the lengths in the inflate process, as described\n * in the deflate specification.\n *\n *  REFERENCES\n *\n *      Deutsch, L.P.,\"'Deflate' Compressed Data Format Specification\".\n *      Available in ftp.uu.net:/pub/archiving/zip/doc/deflate-1.1.doc\n *\n *      Storer, James A.\n *          Data Compression:  Methods and Theory, pp. 49-50.\n *          Computer Science Press, 1988.  ISBN 0-7167-8156-5.\n *\n *      Sedgewick, R.\n *          Algorithms, p290.\n *          Addison-Wesley, 1983. ISBN 0-201-06672-6.\n */\n\n/* @(#) $Id$ */\n\n/* #define GEN_TREES_H */\n\n#include \"deflate.h\"\n\n#ifdef DEBUG\n#  include <ctype.h>\n#endif\n\n/* ===========================================================================\n * Constants\n */\n\n#define MAX_BL_BITS 7\n/* Bit length codes must not exceed MAX_BL_BITS bits */\n\n#define END_BLOCK 256\n/* end of block literal code */\n\n#define REP_3_6      16\n/* repeat previous bit length 3-6 times (2 bits of repeat count) */\n\n#define REPZ_3_10    17\n/* repeat a zero length 3-10 times  (3 bits of repeat count) */\n\n#define REPZ_11_138  18\n/* repeat a zero length 11-138 times  (7 bits of repeat count) */\n\nlocal const int extra_lbits[LENGTH_CODES] /* extra bits for each length code */\n   = {0,0,0,0,0,0,0,0,1,1,1,1,2,2,2,2,3,3,3,3,4,4,4,4,5,5,5,5,0};\n\nlocal const int extra_dbits[D_CODES] /* extra bits for each distance code */\n   = {0,0,0,0,1,1,2,2,3,3,4,4,5,5,6,6,7,7,8,8,9,9,10,10,11,11,12,12,13,13};\n\nlocal const int extra_blbits[BL_CODES]/* extra bits for each bit length code */\n   = {0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,2,3,7};\n\nlocal const uch bl_order[BL_CODES]\n   = {16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15};\n/* The lengths of the bit length codes are sent in order of decreasing\n * probability, to avoid transmitting the lengths for unused bit length codes.\n */\n\n/* ===========================================================================\n * Local data. These are initialized only once.\n */\n\n#define DIST_CODE_LEN  512 /* see definition of array dist_code below */\n\n#if defined(GEN_TREES_H) || !defined(STDC)\n/* non ANSI compilers may not accept trees.h */\n\nlocal ct_data static_ltree[L_CODES+2];\n/* The static literal tree. Since the bit lengths are imposed, there is no\n * need for the L_CODES extra codes used during heap construction. However\n * The codes 286 and 287 are needed to build a canonical tree (see _tr_init\n * below).\n */\n\nlocal ct_data static_dtree[D_CODES];\n/* The static distance tree. (Actually a trivial tree since all codes use\n * 5 bits.)\n */\n\nuch _dist_code[DIST_CODE_LEN];\n/* Distance codes. The first 256 values correspond to the distances\n * 3 .. 258, the last 256 values correspond to the top 8 bits of\n * the 15 bit distances.\n */\n\nuch _length_code[MAX_MATCH-MIN_MATCH+1];\n/* length code for each normalized match length (0 == MIN_MATCH) */\n\nlocal int base_length[LENGTH_CODES];\n/* First normalized length for each code (0 = MIN_MATCH) */\n\nlocal int base_dist[D_CODES];\n/* First normalized distance for each code (0 = distance of 1) */\n\n#else\n#  include \"trees.h\"\n#endif /* GEN_TREES_H */\n\nstruct static_tree_desc_s {\n    const ct_data *static_tree;  /* static tree or NULL */\n    const intf *extra_bits;      /* extra bits for each code or NULL */\n    int     extra_base;          /* base index for extra_bits */\n    int     elems;               /* max number of elements in the tree */\n    int     max_length;          /* max bit length for the codes */\n};\n\nlocal static_tree_desc  static_l_desc =\n{static_ltree, extra_lbits, LITERALS+1, L_CODES, MAX_BITS};\n\nlocal static_tree_desc  static_d_desc =\n{static_dtree, extra_dbits, 0,          D_CODES, MAX_BITS};\n\nlocal static_tree_desc  static_bl_desc =\n{(const ct_data *)0, extra_blbits, 0,   BL_CODES, MAX_BL_BITS};\n\n/* ===========================================================================\n * Local (static) routines in this file.\n */\n\nlocal void tr_static_init OF((void));\nlocal void init_block     OF((deflate_state *s));\nlocal void pqdownheap     OF((deflate_state *s, ct_data *tree, int k));\nlocal void gen_bitlen     OF((deflate_state *s, tree_desc *desc));\nlocal void gen_codes      OF((ct_data *tree, int max_code, ushf *bl_count));\nlocal void build_tree     OF((deflate_state *s, tree_desc *desc));\nlocal void scan_tree      OF((deflate_state *s, ct_data *tree, int max_code));\nlocal void send_tree      OF((deflate_state *s, ct_data *tree, int max_code));\nlocal int  build_bl_tree  OF((deflate_state *s));\nlocal void send_all_trees OF((deflate_state *s, int lcodes, int dcodes,\n                              int blcodes));\nlocal void compress_block OF((deflate_state *s, const ct_data *ltree,\n                              const ct_data *dtree));\nlocal int  detect_data_type OF((deflate_state *s));\nlocal unsigned bi_reverse OF((unsigned value, int length));\nlocal void bi_windup      OF((deflate_state *s));\nlocal void bi_flush       OF((deflate_state *s));\nlocal void copy_block     OF((deflate_state *s, charf *buf, unsigned len,\n                              int header));\n\n#ifdef GEN_TREES_H\nlocal void gen_trees_header OF((void));\n#endif\n\n#ifndef DEBUG\n#  define send_code(s, c, tree) send_bits(s, tree[c].Code, tree[c].Len)\n   /* Send a code of the given tree. c and tree must not have side effects */\n\n#else /* DEBUG */\n#  define send_code(s, c, tree) \\\n     { if (z_verbose>2) fprintf(stderr,\"\\ncd %3d \",(c)); \\\n       send_bits(s, tree[c].Code, tree[c].Len); }\n#endif\n\n/* ===========================================================================\n * Output a short LSB first on the stream.\n * IN assertion: there is enough room in pendingBuf.\n */\n#define put_short(s, w) { \\\n    put_byte(s, (uch)((w) & 0xff)); \\\n    put_byte(s, (uch)((ush)(w) >> 8)); \\\n}\n\n/* ===========================================================================\n * Send a value on a given number of bits.\n * IN assertion: length <= 16 and value fits in length bits.\n */\n#ifdef DEBUG\nlocal void send_bits      OF((deflate_state *s, int value, int length));\n\nlocal void send_bits(s, value, length)\n    deflate_state *s;\n    int value;  /* value to send */\n    int length; /* number of bits */\n{\n    Tracevv((stderr,\" l %2d v %4x \", length, value));\n    Assert(length > 0 && length <= 15, \"invalid length\");\n    s->bits_sent += (ulg)length;\n\n    /* If not enough room in bi_buf, use (valid) bits from bi_buf and\n     * (16 - bi_valid) bits from value, leaving (width - (16-bi_valid))\n     * unused bits in value.\n     */\n    if (s->bi_valid > (int)Buf_size - length) {\n        s->bi_buf |= (ush)value << s->bi_valid;\n        put_short(s, s->bi_buf);\n        s->bi_buf = (ush)value >> (Buf_size - s->bi_valid);\n        s->bi_valid += length - Buf_size;\n    } else {\n        s->bi_buf |= (ush)value << s->bi_valid;\n        s->bi_valid += length;\n    }\n}\n#else /* !DEBUG */\n\n#define send_bits(s, value, length) \\\n{ int len = length;\\\n  if (s->bi_valid > (int)Buf_size - len) {\\\n    int val = value;\\\n    s->bi_buf |= (ush)val << s->bi_valid;\\\n    put_short(s, s->bi_buf);\\\n    s->bi_buf = (ush)val >> (Buf_size - s->bi_valid);\\\n    s->bi_valid += len - Buf_size;\\\n  } else {\\\n    s->bi_buf |= (ush)(value) << s->bi_valid;\\\n    s->bi_valid += len;\\\n  }\\\n}\n#endif /* DEBUG */\n\n\n/* the arguments must not have side effects */\n\n/* ===========================================================================\n * Initialize the various 'constant' tables.\n */\nlocal void tr_static_init()\n{\n#if defined(GEN_TREES_H) || !defined(STDC)\n    static int static_init_done = 0;\n    int n;        /* iterates over tree elements */\n    int bits;     /* bit counter */\n    int length;   /* length value */\n    int code;     /* code value */\n    int dist;     /* distance index */\n    ush bl_count[MAX_BITS+1];\n    /* number of codes at each bit length for an optimal tree */\n\n    if (static_init_done) return;\n\n    /* For some embedded targets, global variables are not initialized: */\n#ifdef NO_INIT_GLOBAL_POINTERS\n    static_l_desc.static_tree = static_ltree;\n    static_l_desc.extra_bits = extra_lbits;\n    static_d_desc.static_tree = static_dtree;\n    static_d_desc.extra_bits = extra_dbits;\n    static_bl_desc.extra_bits = extra_blbits;\n#endif\n\n    /* Initialize the mapping length (0..255) -> length code (0..28) */\n    length = 0;\n    for (code = 0; code < LENGTH_CODES-1; code++) {\n        base_length[code] = length;\n        for (n = 0; n < (1<<extra_lbits[code]); n++) {\n            _length_code[length++] = (uch)code;\n        }\n    }\n    Assert (length == 256, \"tr_static_init: length != 256\");\n    /* Note that the length 255 (match length 258) can be represented\n     * in two different ways: code 284 + 5 bits or code 285, so we\n     * overwrite length_code[255] to use the best encoding:\n     */\n    _length_code[length-1] = (uch)code;\n\n    /* Initialize the mapping dist (0..32K) -> dist code (0..29) */\n    dist = 0;\n    for (code = 0 ; code < 16; code++) {\n        base_dist[code] = dist;\n        for (n = 0; n < (1<<extra_dbits[code]); n++) {\n            _dist_code[dist++] = (uch)code;\n        }\n    }\n    Assert (dist == 256, \"tr_static_init: dist != 256\");\n    dist >>= 7; /* from now on, all distances are divided by 128 */\n    for ( ; code < D_CODES; code++) {\n        base_dist[code] = dist << 7;\n        for (n = 0; n < (1<<(extra_dbits[code]-7)); n++) {\n            _dist_code[256 + dist++] = (uch)code;\n        }\n    }\n    Assert (dist == 256, \"tr_static_init: 256+dist != 512\");\n\n    /* Construct the codes of the static literal tree */\n    for (bits = 0; bits <= MAX_BITS; bits++) bl_count[bits] = 0;\n    n = 0;\n    while (n <= 143) static_ltree[n++].Len = 8, bl_count[8]++;\n    while (n <= 255) static_ltree[n++].Len = 9, bl_count[9]++;\n    while (n <= 279) static_ltree[n++].Len = 7, bl_count[7]++;\n    while (n <= 287) static_ltree[n++].Len = 8, bl_count[8]++;\n    /* Codes 286 and 287 do not exist, but we must include them in the\n     * tree construction to get a canonical Huffman tree (longest code\n     * all ones)\n     */\n    gen_codes((ct_data *)static_ltree, L_CODES+1, bl_count);\n\n    /* The static distance tree is trivial: */\n    for (n = 0; n < D_CODES; n++) {\n        static_dtree[n].Len = 5;\n        static_dtree[n].Code = bi_reverse((unsigned)n, 5);\n    }\n    static_init_done = 1;\n\n#  ifdef GEN_TREES_H\n    gen_trees_header();\n#  endif\n#endif /* defined(GEN_TREES_H) || !defined(STDC) */\n}\n\n/* ===========================================================================\n * Genererate the file trees.h describing the static trees.\n */\n#ifdef GEN_TREES_H\n#  ifndef DEBUG\n#    include <stdio.h>\n#  endif\n\n#  define SEPARATOR(i, last, width) \\\n      ((i) == (last)? \"\\n};\\n\\n\" :    \\\n       ((i) % (width) == (width)-1 ? \",\\n\" : \", \"))\n\nvoid gen_trees_header()\n{\n    FILE *header = fopen(\"trees.h\", \"w\");\n    int i;\n\n    Assert (header != NULL, \"Can't open trees.h\");\n    fprintf(header,\n            \"/* header created automatically with -DGEN_TREES_H */\\n\\n\");\n\n    fprintf(header, \"local const ct_data static_ltree[L_CODES+2] = {\\n\");\n    for (i = 0; i < L_CODES+2; i++) {\n        fprintf(header, \"{{%3u},{%3u}}%s\", static_ltree[i].Code,\n                static_ltree[i].Len, SEPARATOR(i, L_CODES+1, 5));\n    }\n\n    fprintf(header, \"local const ct_data static_dtree[D_CODES] = {\\n\");\n    for (i = 0; i < D_CODES; i++) {\n        fprintf(header, \"{{%2u},{%2u}}%s\", static_dtree[i].Code,\n                static_dtree[i].Len, SEPARATOR(i, D_CODES-1, 5));\n    }\n\n    fprintf(header, \"const uch ZLIB_INTERNAL _dist_code[DIST_CODE_LEN] = {\\n\");\n    for (i = 0; i < DIST_CODE_LEN; i++) {\n        fprintf(header, \"%2u%s\", _dist_code[i],\n                SEPARATOR(i, DIST_CODE_LEN-1, 20));\n    }\n\n    fprintf(header,\n        \"const uch ZLIB_INTERNAL _length_code[MAX_MATCH-MIN_MATCH+1]= {\\n\");\n    for (i = 0; i < MAX_MATCH-MIN_MATCH+1; i++) {\n        fprintf(header, \"%2u%s\", _length_code[i],\n                SEPARATOR(i, MAX_MATCH-MIN_MATCH, 20));\n    }\n\n    fprintf(header, \"local const int base_length[LENGTH_CODES] = {\\n\");\n    for (i = 0; i < LENGTH_CODES; i++) {\n        fprintf(header, \"%1u%s\", base_length[i],\n                SEPARATOR(i, LENGTH_CODES-1, 20));\n    }\n\n    fprintf(header, \"local const int base_dist[D_CODES] = {\\n\");\n    for (i = 0; i < D_CODES; i++) {\n        fprintf(header, \"%5u%s\", base_dist[i],\n                SEPARATOR(i, D_CODES-1, 10));\n    }\n\n    fclose(header);\n}\n#endif /* GEN_TREES_H */\n\n/* ===========================================================================\n * Initialize the tree data structures for a new zlib stream.\n */\nvoid ZLIB_INTERNAL _tr_init(s)\n    deflate_state *s;\n{\n    tr_static_init();\n\n    s->l_desc.dyn_tree = s->dyn_ltree;\n    s->l_desc.stat_desc = &static_l_desc;\n\n    s->d_desc.dyn_tree = s->dyn_dtree;\n    s->d_desc.stat_desc = &static_d_desc;\n\n    s->bl_desc.dyn_tree = s->bl_tree;\n    s->bl_desc.stat_desc = &static_bl_desc;\n\n    s->bi_buf = 0;\n    s->bi_valid = 0;\n#ifdef DEBUG\n    s->compressed_len = 0L;\n    s->bits_sent = 0L;\n#endif\n\n    /* Initialize the first block of the first file: */\n    init_block(s);\n}\n\n/* ===========================================================================\n * Initialize a new block.\n */\nlocal void init_block(s)\n    deflate_state *s;\n{\n    int n; /* iterates over tree elements */\n\n    /* Initialize the trees. */\n    for (n = 0; n < L_CODES;  n++) s->dyn_ltree[n].Freq = 0;\n    for (n = 0; n < D_CODES;  n++) s->dyn_dtree[n].Freq = 0;\n    for (n = 0; n < BL_CODES; n++) s->bl_tree[n].Freq = 0;\n\n    s->dyn_ltree[END_BLOCK].Freq = 1;\n    s->opt_len = s->static_len = 0L;\n    s->last_lit = s->matches = 0;\n}\n\n#define SMALLEST 1\n/* Index within the heap array of least frequent node in the Huffman tree */\n\n\n/* ===========================================================================\n * Remove the smallest element from the heap and recreate the heap with\n * one less element. Updates heap and heap_len.\n */\n#define pqremove(s, tree, top) \\\n{\\\n    top = s->heap[SMALLEST]; \\\n    s->heap[SMALLEST] = s->heap[s->heap_len--]; \\\n    pqdownheap(s, tree, SMALLEST); \\\n}\n\n/* ===========================================================================\n * Compares to subtrees, using the tree depth as tie breaker when\n * the subtrees have equal frequency. This minimizes the worst case length.\n */\n#define smaller(tree, n, m, depth) \\\n   (tree[n].Freq < tree[m].Freq || \\\n   (tree[n].Freq == tree[m].Freq && depth[n] <= depth[m]))\n\n/* ===========================================================================\n * Restore the heap property by moving down the tree starting at node k,\n * exchanging a node with the smallest of its two sons if necessary, stopping\n * when the heap property is re-established (each father smaller than its\n * two sons).\n */\nlocal void pqdownheap(s, tree, k)\n    deflate_state *s;\n    ct_data *tree;  /* the tree to restore */\n    int k;               /* node to move down */\n{\n    int v = s->heap[k];\n    int j = k << 1;  /* left son of k */\n    while (j <= s->heap_len) {\n        /* Set j to the smallest of the two sons: */\n        if (j < s->heap_len &&\n            smaller(tree, s->heap[j+1], s->heap[j], s->depth)) {\n            j++;\n        }\n        /* Exit if v is smaller than both sons */\n        if (smaller(tree, v, s->heap[j], s->depth)) break;\n\n        /* Exchange v with the smallest son */\n        s->heap[k] = s->heap[j];  k = j;\n\n        /* And continue down the tree, setting j to the left son of k */\n        j <<= 1;\n    }\n    s->heap[k] = v;\n}\n\n/* ===========================================================================\n * Compute the optimal bit lengths for a tree and update the total bit length\n * for the current block.\n * IN assertion: the fields freq and dad are set, heap[heap_max] and\n *    above are the tree nodes sorted by increasing frequency.\n * OUT assertions: the field len is set to the optimal bit length, the\n *     array bl_count contains the frequencies for each bit length.\n *     The length opt_len is updated; static_len is also updated if stree is\n *     not null.\n */\nlocal void gen_bitlen(s, desc)\n    deflate_state *s;\n    tree_desc *desc;    /* the tree descriptor */\n{\n    ct_data *tree        = desc->dyn_tree;\n    int max_code         = desc->max_code;\n    const ct_data *stree = desc->stat_desc->static_tree;\n    const intf *extra    = desc->stat_desc->extra_bits;\n    int base             = desc->stat_desc->extra_base;\n    int max_length       = desc->stat_desc->max_length;\n    int h;              /* heap index */\n    int n, m;           /* iterate over the tree elements */\n    int bits;           /* bit length */\n    int xbits;          /* extra bits */\n    ush f;              /* frequency */\n    int overflow = 0;   /* number of elements with bit length too large */\n\n    for (bits = 0; bits <= MAX_BITS; bits++) s->bl_count[bits] = 0;\n\n    /* In a first pass, compute the optimal bit lengths (which may\n     * overflow in the case of the bit length tree).\n     */\n    tree[s->heap[s->heap_max]].Len = 0; /* root of the heap */\n\n    for (h = s->heap_max+1; h < HEAP_SIZE; h++) {\n        n = s->heap[h];\n        bits = tree[tree[n].Dad].Len + 1;\n        if (bits > max_length) bits = max_length, overflow++;\n        tree[n].Len = (ush)bits;\n        /* We overwrite tree[n].Dad which is no longer needed */\n\n        if (n > max_code) continue; /* not a leaf node */\n\n        s->bl_count[bits]++;\n        xbits = 0;\n        if (n >= base) xbits = extra[n-base];\n        f = tree[n].Freq;\n        s->opt_len += (ulg)f * (bits + xbits);\n        if (stree) s->static_len += (ulg)f * (stree[n].Len + xbits);\n    }\n    if (overflow == 0) return;\n\n    Trace((stderr,\"\\nbit length overflow\\n\"));\n    /* This happens for example on obj2 and pic of the Calgary corpus */\n\n    /* Find the first bit length which could increase: */\n    do {\n        bits = max_length-1;\n        while (s->bl_count[bits] == 0) bits--;\n        s->bl_count[bits]--;      /* move one leaf down the tree */\n        s->bl_count[bits+1] += 2; /* move one overflow item as its brother */\n        s->bl_count[max_length]--;\n        /* The brother of the overflow item also moves one step up,\n         * but this does not affect bl_count[max_length]\n         */\n        overflow -= 2;\n    } while (overflow > 0);\n\n    /* Now recompute all bit lengths, scanning in increasing frequency.\n     * h is still equal to HEAP_SIZE. (It is simpler to reconstruct all\n     * lengths instead of fixing only the wrong ones. This idea is taken\n     * from 'ar' written by Haruhiko Okumura.)\n     */\n    for (bits = max_length; bits != 0; bits--) {\n        n = s->bl_count[bits];\n        while (n != 0) {\n            m = s->heap[--h];\n            if (m > max_code) continue;\n            if ((unsigned) tree[m].Len != (unsigned) bits) {\n                Trace((stderr,\"code %d bits %d->%d\\n\", m, tree[m].Len, bits));\n                s->opt_len += ((long)bits - (long)tree[m].Len)\n                              *(long)tree[m].Freq;\n                tree[m].Len = (ush)bits;\n            }\n            n--;\n        }\n    }\n}\n\n/* ===========================================================================\n * Generate the codes for a given tree and bit counts (which need not be\n * optimal).\n * IN assertion: the array bl_count contains the bit length statistics for\n * the given tree and the field len is set for all tree elements.\n * OUT assertion: the field code is set for all tree elements of non\n *     zero code length.\n */\nlocal void gen_codes (tree, max_code, bl_count)\n    ct_data *tree;             /* the tree to decorate */\n    int max_code;              /* largest code with non zero frequency */\n    ushf *bl_count;            /* number of codes at each bit length */\n{\n    ush next_code[MAX_BITS+1]; /* next code value for each bit length */\n    ush code = 0;              /* running code value */\n    int bits;                  /* bit index */\n    int n;                     /* code index */\n\n    /* The distribution counts are first used to generate the code values\n     * without bit reversal.\n     */\n    for (bits = 1; bits <= MAX_BITS; bits++) {\n        next_code[bits] = code = (code + bl_count[bits-1]) << 1;\n    }\n    /* Check that the bit counts in bl_count are consistent. The last code\n     * must be all ones.\n     */\n    Assert (code + bl_count[MAX_BITS]-1 == (1<<MAX_BITS)-1,\n            \"inconsistent bit counts\");\n    Tracev((stderr,\"\\ngen_codes: max_code %d \", max_code));\n\n    for (n = 0;  n <= max_code; n++) {\n        int len = tree[n].Len;\n        if (len == 0) continue;\n        /* Now reverse the bits */\n        tree[n].Code = bi_reverse(next_code[len]++, len);\n\n        Tracecv(tree != static_ltree, (stderr,\"\\nn %3d %c l %2d c %4x (%x) \",\n             n, (isgraph(n) ? n : ' '), len, tree[n].Code, next_code[len]-1));\n    }\n}\n\n/* ===========================================================================\n * Construct one Huffman tree and assigns the code bit strings and lengths.\n * Update the total bit length for the current block.\n * IN assertion: the field freq is set for all tree elements.\n * OUT assertions: the fields len and code are set to the optimal bit length\n *     and corresponding code. The length opt_len is updated; static_len is\n *     also updated if stree is not null. The field max_code is set.\n */\nlocal void build_tree(s, desc)\n    deflate_state *s;\n    tree_desc *desc; /* the tree descriptor */\n{\n    ct_data *tree         = desc->dyn_tree;\n    const ct_data *stree  = desc->stat_desc->static_tree;\n    int elems             = desc->stat_desc->elems;\n    int n, m;          /* iterate over heap elements */\n    int max_code = -1; /* largest code with non zero frequency */\n    int node;          /* new node being created */\n\n    /* Construct the initial heap, with least frequent element in\n     * heap[SMALLEST]. The sons of heap[n] are heap[2*n] and heap[2*n+1].\n     * heap[0] is not used.\n     */\n    s->heap_len = 0, s->heap_max = HEAP_SIZE;\n\n    for (n = 0; n < elems; n++) {\n        if (tree[n].Freq != 0) {\n            s->heap[++(s->heap_len)] = max_code = n;\n            s->depth[n] = 0;\n        } else {\n            tree[n].Len = 0;\n        }\n    }\n\n    /* The pkzip format requires that at least one distance code exists,\n     * and that at least one bit should be sent even if there is only one\n     * possible code. So to avoid special checks later on we force at least\n     * two codes of non zero frequency.\n     */\n    while (s->heap_len < 2) {\n        node = s->heap[++(s->heap_len)] = (max_code < 2 ? ++max_code : 0);\n        tree[node].Freq = 1;\n        s->depth[node] = 0;\n        s->opt_len--; if (stree) s->static_len -= stree[node].Len;\n        /* node is 0 or 1 so it does not have extra bits */\n    }\n    desc->max_code = max_code;\n\n    /* The elements heap[heap_len/2+1 .. heap_len] are leaves of the tree,\n     * establish sub-heaps of increasing lengths:\n     */\n    for (n = s->heap_len/2; n >= 1; n--) pqdownheap(s, tree, n);\n\n    /* Construct the Huffman tree by repeatedly combining the least two\n     * frequent nodes.\n     */\n    node = elems;              /* next internal node of the tree */\n    do {\n        pqremove(s, tree, n);  /* n = node of least frequency */\n        m = s->heap[SMALLEST]; /* m = node of next least frequency */\n\n        s->heap[--(s->heap_max)] = n; /* keep the nodes sorted by frequency */\n        s->heap[--(s->heap_max)] = m;\n\n        /* Create a new node father of n and m */\n        tree[node].Freq = tree[n].Freq + tree[m].Freq;\n        s->depth[node] = (uch)((s->depth[n] >= s->depth[m] ?\n                                s->depth[n] : s->depth[m]) + 1);\n        tree[n].Dad = tree[m].Dad = (ush)node;\n#ifdef DUMP_BL_TREE\n        if (tree == s->bl_tree) {\n            fprintf(stderr,\"\\nnode %d(%d), sons %d(%d) %d(%d)\",\n                    node, tree[node].Freq, n, tree[n].Freq, m, tree[m].Freq);\n        }\n#endif\n        /* and insert the new node in the heap */\n        s->heap[SMALLEST] = node++;\n        pqdownheap(s, tree, SMALLEST);\n\n    } while (s->heap_len >= 2);\n\n    s->heap[--(s->heap_max)] = s->heap[SMALLEST];\n\n    /* At this point, the fields freq and dad are set. We can now\n     * generate the bit lengths.\n     */\n    gen_bitlen(s, (tree_desc *)desc);\n\n    /* The field len is now set, we can generate the bit codes */\n    gen_codes ((ct_data *)tree, max_code, s->bl_count);\n}\n\n/* ===========================================================================\n * Scan a literal or distance tree to determine the frequencies of the codes\n * in the bit length tree.\n */\nlocal void scan_tree (s, tree, max_code)\n    deflate_state *s;\n    ct_data *tree;   /* the tree to be scanned */\n    int max_code;    /* and its largest code of non zero frequency */\n{\n    int n;                     /* iterates over all tree elements */\n    int prevlen = -1;          /* last emitted length */\n    int curlen;                /* length of current code */\n    int nextlen = tree[0].Len; /* length of next code */\n    int count = 0;             /* repeat count of the current code */\n    int max_count = 7;         /* max repeat count */\n    int min_count = 4;         /* min repeat count */\n\n    if (nextlen == 0) max_count = 138, min_count = 3;\n    tree[max_code+1].Len = (ush)0xffff; /* guard */\n\n    for (n = 0; n <= max_code; n++) {\n        curlen = nextlen; nextlen = tree[n+1].Len;\n        if (++count < max_count && curlen == nextlen) {\n            continue;\n        } else if (count < min_count) {\n            s->bl_tree[curlen].Freq += count;\n        } else if (curlen != 0) {\n            if (curlen != prevlen) s->bl_tree[curlen].Freq++;\n            s->bl_tree[REP_3_6].Freq++;\n        } else if (count <= 10) {\n            s->bl_tree[REPZ_3_10].Freq++;\n        } else {\n            s->bl_tree[REPZ_11_138].Freq++;\n        }\n        count = 0; prevlen = curlen;\n        if (nextlen == 0) {\n            max_count = 138, min_count = 3;\n        } else if (curlen == nextlen) {\n            max_count = 6, min_count = 3;\n        } else {\n            max_count = 7, min_count = 4;\n        }\n    }\n}\n\n/* ===========================================================================\n * Send a literal or distance tree in compressed form, using the codes in\n * bl_tree.\n */\nlocal void send_tree (s, tree, max_code)\n    deflate_state *s;\n    ct_data *tree; /* the tree to be scanned */\n    int max_code;       /* and its largest code of non zero frequency */\n{\n    int n;                     /* iterates over all tree elements */\n    int prevlen = -1;          /* last emitted length */\n    int curlen;                /* length of current code */\n    int nextlen = tree[0].Len; /* length of next code */\n    int count = 0;             /* repeat count of the current code */\n    int max_count = 7;         /* max repeat count */\n    int min_count = 4;         /* min repeat count */\n\n    /* tree[max_code+1].Len = -1; */  /* guard already set */\n    if (nextlen == 0) max_count = 138, min_count = 3;\n\n    for (n = 0; n <= max_code; n++) {\n        curlen = nextlen; nextlen = tree[n+1].Len;\n        if (++count < max_count && curlen == nextlen) {\n            continue;\n        } else if (count < min_count) {\n            do { send_code(s, curlen, s->bl_tree); } while (--count != 0);\n\n        } else if (curlen != 0) {\n            if (curlen != prevlen) {\n                send_code(s, curlen, s->bl_tree); count--;\n            }\n            Assert(count >= 3 && count <= 6, \" 3_6?\");\n            send_code(s, REP_3_6, s->bl_tree); send_bits(s, count-3, 2);\n\n        } else if (count <= 10) {\n            send_code(s, REPZ_3_10, s->bl_tree); send_bits(s, count-3, 3);\n\n        } else {\n            send_code(s, REPZ_11_138, s->bl_tree); send_bits(s, count-11, 7);\n        }\n        count = 0; prevlen = curlen;\n        if (nextlen == 0) {\n            max_count = 138, min_count = 3;\n        } else if (curlen == nextlen) {\n            max_count = 6, min_count = 3;\n        } else {\n            max_count = 7, min_count = 4;\n        }\n    }\n}\n\n/* ===========================================================================\n * Construct the Huffman tree for the bit lengths and return the index in\n * bl_order of the last bit length code to send.\n */\nlocal int build_bl_tree(s)\n    deflate_state *s;\n{\n    int max_blindex;  /* index of last bit length code of non zero freq */\n\n    /* Determine the bit length frequencies for literal and distance trees */\n    scan_tree(s, (ct_data *)s->dyn_ltree, s->l_desc.max_code);\n    scan_tree(s, (ct_data *)s->dyn_dtree, s->d_desc.max_code);\n\n    /* Build the bit length tree: */\n    build_tree(s, (tree_desc *)(&(s->bl_desc)));\n    /* opt_len now includes the length of the tree representations, except\n     * the lengths of the bit lengths codes and the 5+5+4 bits for the counts.\n     */\n\n    /* Determine the number of bit length codes to send. The pkzip format\n     * requires that at least 4 bit length codes be sent. (appnote.txt says\n     * 3 but the actual value used is 4.)\n     */\n    for (max_blindex = BL_CODES-1; max_blindex >= 3; max_blindex--) {\n        if (s->bl_tree[bl_order[max_blindex]].Len != 0) break;\n    }\n    /* Update opt_len to include the bit length tree and counts */\n    s->opt_len += 3*(max_blindex+1) + 5+5+4;\n    Tracev((stderr, \"\\ndyn trees: dyn %ld, stat %ld\",\n            s->opt_len, s->static_len));\n\n    return max_blindex;\n}\n\n/* ===========================================================================\n * Send the header for a block using dynamic Huffman trees: the counts, the\n * lengths of the bit length codes, the literal tree and the distance tree.\n * IN assertion: lcodes >= 257, dcodes >= 1, blcodes >= 4.\n */\nlocal void send_all_trees(s, lcodes, dcodes, blcodes)\n    deflate_state *s;\n    int lcodes, dcodes, blcodes; /* number of codes for each tree */\n{\n    int rank;                    /* index in bl_order */\n\n    Assert (lcodes >= 257 && dcodes >= 1 && blcodes >= 4, \"not enough codes\");\n    Assert (lcodes <= L_CODES && dcodes <= D_CODES && blcodes <= BL_CODES,\n            \"too many codes\");\n    Tracev((stderr, \"\\nbl counts: \"));\n    send_bits(s, lcodes-257, 5); /* not +255 as stated in appnote.txt */\n    send_bits(s, dcodes-1,   5);\n    send_bits(s, blcodes-4,  4); /* not -3 as stated in appnote.txt */\n    for (rank = 0; rank < blcodes; rank++) {\n        Tracev((stderr, \"\\nbl code %2d \", bl_order[rank]));\n        send_bits(s, s->bl_tree[bl_order[rank]].Len, 3);\n    }\n    Tracev((stderr, \"\\nbl tree: sent %ld\", s->bits_sent));\n\n    send_tree(s, (ct_data *)s->dyn_ltree, lcodes-1); /* literal tree */\n    Tracev((stderr, \"\\nlit tree: sent %ld\", s->bits_sent));\n\n    send_tree(s, (ct_data *)s->dyn_dtree, dcodes-1); /* distance tree */\n    Tracev((stderr, \"\\ndist tree: sent %ld\", s->bits_sent));\n}\n\n/* ===========================================================================\n * Send a stored block\n */\nvoid ZLIB_INTERNAL _tr_stored_block(s, buf, stored_len, last)\n    deflate_state *s;\n    charf *buf;       /* input block */\n    ulg stored_len;   /* length of input block */\n    int last;         /* one if this is the last block for a file */\n{\n    send_bits(s, (STORED_BLOCK<<1)+last, 3);    /* send block type */\n#ifdef DEBUG\n    s->compressed_len = (s->compressed_len + 3 + 7) & (ulg)~7L;\n    s->compressed_len += (stored_len + 4) << 3;\n#endif\n    copy_block(s, buf, (unsigned)stored_len, 1); /* with header */\n}\n\n/* ===========================================================================\n * Flush the bits in the bit buffer to pending output (leaves at most 7 bits)\n */\nvoid ZLIB_INTERNAL _tr_flush_bits(s)\n    deflate_state *s;\n{\n    bi_flush(s);\n}\n\n/* ===========================================================================\n * Send one empty static block to give enough lookahead for inflate.\n * This takes 10 bits, of which 7 may remain in the bit buffer.\n */\nvoid ZLIB_INTERNAL _tr_align(s)\n    deflate_state *s;\n{\n    send_bits(s, STATIC_TREES<<1, 3);\n    send_code(s, END_BLOCK, static_ltree);\n#ifdef DEBUG\n    s->compressed_len += 10L; /* 3 for block type, 7 for EOB */\n#endif\n    bi_flush(s);\n}\n\n/* ===========================================================================\n * Determine the best encoding for the current block: dynamic trees, static\n * trees or store, and output the encoded block to the zip file.\n */\nvoid ZLIB_INTERNAL _tr_flush_block(s, buf, stored_len, last)\n    deflate_state *s;\n    charf *buf;       /* input block, or NULL if too old */\n    ulg stored_len;   /* length of input block */\n    int last;         /* one if this is the last block for a file */\n{\n    ulg opt_lenb, static_lenb; /* opt_len and static_len in bytes */\n    int max_blindex = 0;  /* index of last bit length code of non zero freq */\n\n    /* Build the Huffman trees unless a stored block is forced */\n    if (s->level > 0) {\n\n        /* Check if the file is binary or text */\n        if (s->strm->data_type == Z_UNKNOWN)\n            s->strm->data_type = detect_data_type(s);\n\n        /* Construct the literal and distance trees */\n        build_tree(s, (tree_desc *)(&(s->l_desc)));\n        Tracev((stderr, \"\\nlit data: dyn %ld, stat %ld\", s->opt_len,\n                s->static_len));\n\n        build_tree(s, (tree_desc *)(&(s->d_desc)));\n        Tracev((stderr, \"\\ndist data: dyn %ld, stat %ld\", s->opt_len,\n                s->static_len));\n        /* At this point, opt_len and static_len are the total bit lengths of\n         * the compressed block data, excluding the tree representations.\n         */\n\n        /* Build the bit length tree for the above two trees, and get the index\n         * in bl_order of the last bit length code to send.\n         */\n        max_blindex = build_bl_tree(s);\n\n        /* Determine the best encoding. Compute the block lengths in bytes. */\n        opt_lenb = (s->opt_len+3+7)>>3;\n        static_lenb = (s->static_len+3+7)>>3;\n\n        Tracev((stderr, \"\\nopt %lu(%lu) stat %lu(%lu) stored %lu lit %u \",\n                opt_lenb, s->opt_len, static_lenb, s->static_len, stored_len,\n                s->last_lit));\n\n        if (static_lenb <= opt_lenb) opt_lenb = static_lenb;\n\n    } else {\n        Assert(buf != (char*)0, \"lost buf\");\n        opt_lenb = static_lenb = stored_len + 5; /* force a stored block */\n    }\n\n#ifdef FORCE_STORED\n    if (buf != (char*)0) { /* force stored block */\n#else\n    if (stored_len+4 <= opt_lenb && buf != (char*)0) {\n                       /* 4: two words for the lengths */\n#endif\n        /* The test buf != NULL is only necessary if LIT_BUFSIZE > WSIZE.\n         * Otherwise we can't have processed more than WSIZE input bytes since\n         * the last block flush, because compression would have been\n         * successful. If LIT_BUFSIZE <= WSIZE, it is never too late to\n         * transform a block into a stored block.\n         */\n        _tr_stored_block(s, buf, stored_len, last);\n\n#ifdef FORCE_STATIC\n    } else if (static_lenb >= 0) { /* force static trees */\n#else\n    } else if (s->strategy == Z_FIXED || static_lenb == opt_lenb) {\n#endif\n        send_bits(s, (STATIC_TREES<<1)+last, 3);\n        compress_block(s, (const ct_data *)static_ltree,\n                       (const ct_data *)static_dtree);\n#ifdef DEBUG\n        s->compressed_len += 3 + s->static_len;\n#endif\n    } else {\n        send_bits(s, (DYN_TREES<<1)+last, 3);\n        send_all_trees(s, s->l_desc.max_code+1, s->d_desc.max_code+1,\n                       max_blindex+1);\n        compress_block(s, (const ct_data *)s->dyn_ltree,\n                       (const ct_data *)s->dyn_dtree);\n#ifdef DEBUG\n        s->compressed_len += 3 + s->opt_len;\n#endif\n    }\n    Assert (s->compressed_len == s->bits_sent, \"bad compressed size\");\n    /* The above check is made mod 2^32, for files larger than 512 MB\n     * and uLong implemented on 32 bits.\n     */\n    init_block(s);\n\n    if (last) {\n        bi_windup(s);\n#ifdef DEBUG\n        s->compressed_len += 7;  /* align on byte boundary */\n#endif\n    }\n    Tracev((stderr,\"\\ncomprlen %lu(%lu) \", s->compressed_len>>3,\n           s->compressed_len-7*last));\n}\n\n/* ===========================================================================\n * Save the match info and tally the frequency counts. Return true if\n * the current block must be flushed.\n */\nint ZLIB_INTERNAL _tr_tally (s, dist, lc)\n    deflate_state *s;\n    unsigned dist;  /* distance of matched string */\n    unsigned lc;    /* match length-MIN_MATCH or unmatched char (if dist==0) */\n{\n    s->d_buf[s->last_lit] = (ush)dist;\n    s->l_buf[s->last_lit++] = (uch)lc;\n    if (dist == 0) {\n        /* lc is the unmatched char */\n        s->dyn_ltree[lc].Freq++;\n    } else {\n        s->matches++;\n        /* Here, lc is the match length - MIN_MATCH */\n        dist--;             /* dist = match distance - 1 */\n        Assert((ush)dist < (ush)MAX_DIST(s) &&\n               (ush)lc <= (ush)(MAX_MATCH-MIN_MATCH) &&\n               (ush)d_code(dist) < (ush)D_CODES,  \"_tr_tally: bad match\");\n\n        s->dyn_ltree[_length_code[lc]+LITERALS+1].Freq++;\n        s->dyn_dtree[d_code(dist)].Freq++;\n    }\n\n#ifdef TRUNCATE_BLOCK\n    /* Try to guess if it is profitable to stop the current block here */\n    if ((s->last_lit & 0x1fff) == 0 && s->level > 2) {\n        /* Compute an upper bound for the compressed length */\n        ulg out_length = (ulg)s->last_lit*8L;\n        ulg in_length = (ulg)((long)s->strstart - s->block_start);\n        int dcode;\n        for (dcode = 0; dcode < D_CODES; dcode++) {\n            out_length += (ulg)s->dyn_dtree[dcode].Freq *\n                (5L+extra_dbits[dcode]);\n        }\n        out_length >>= 3;\n        Tracev((stderr,\"\\nlast_lit %u, in %ld, out ~%ld(%ld%%) \",\n               s->last_lit, in_length, out_length,\n               100L - out_length*100L/in_length));\n        if (s->matches < s->last_lit/2 && out_length < in_length/2) return 1;\n    }\n#endif\n    return (s->last_lit == s->lit_bufsize-1);\n    /* We avoid equality with lit_bufsize because of wraparound at 64K\n     * on 16 bit machines and because stored blocks are restricted to\n     * 64K-1 bytes.\n     */\n}\n\n/* ===========================================================================\n * Send the block data compressed using the given Huffman trees\n */\nlocal void compress_block(s, ltree, dtree)\n    deflate_state *s;\n    const ct_data *ltree; /* literal tree */\n    const ct_data *dtree; /* distance tree */\n{\n    unsigned dist;      /* distance of matched string */\n    int lc;             /* match length or unmatched char (if dist == 0) */\n    unsigned lx = 0;    /* running index in l_buf */\n    unsigned code;      /* the code to send */\n    int extra;          /* number of extra bits to send */\n\n    if (s->last_lit != 0) do {\n        dist = s->d_buf[lx];\n        lc = s->l_buf[lx++];\n        if (dist == 0) {\n            send_code(s, lc, ltree); /* send a literal byte */\n            Tracecv(isgraph(lc), (stderr,\" '%c' \", lc));\n        } else {\n            /* Here, lc is the match length - MIN_MATCH */\n            code = _length_code[lc];\n            send_code(s, code+LITERALS+1, ltree); /* send the length code */\n            extra = extra_lbits[code];\n            if (extra != 0) {\n                lc -= base_length[code];\n                send_bits(s, lc, extra);       /* send the extra length bits */\n            }\n            dist--; /* dist is now the match distance - 1 */\n            code = d_code(dist);\n            Assert (code < D_CODES, \"bad d_code\");\n\n            send_code(s, code, dtree);       /* send the distance code */\n            extra = extra_dbits[code];\n            if (extra != 0) {\n                dist -= base_dist[code];\n                send_bits(s, dist, extra);   /* send the extra distance bits */\n            }\n        } /* literal or match pair ? */\n\n        /* Check that the overlay between pending_buf and d_buf+l_buf is ok: */\n        Assert((uInt)(s->pending) < s->lit_bufsize + 2*lx,\n               \"pendingBuf overflow\");\n\n    } while (lx < s->last_lit);\n\n    send_code(s, END_BLOCK, ltree);\n}\n\n/* ===========================================================================\n * Check if the data type is TEXT or BINARY, using the following algorithm:\n * - TEXT if the two conditions below are satisfied:\n *    a) There are no non-portable control characters belonging to the\n *       \"black list\" (0..6, 14..25, 28..31).\n *    b) There is at least one printable character belonging to the\n *       \"white list\" (9 {TAB}, 10 {LF}, 13 {CR}, 32..255).\n * - BINARY otherwise.\n * - The following partially-portable control characters form a\n *   \"gray list\" that is ignored in this detection algorithm:\n *   (7 {BEL}, 8 {BS}, 11 {VT}, 12 {FF}, 26 {SUB}, 27 {ESC}).\n * IN assertion: the fields Freq of dyn_ltree are set.\n */\nlocal int detect_data_type(s)\n    deflate_state *s;\n{\n    /* black_mask is the bit mask of black-listed bytes\n     * set bits 0..6, 14..25, and 28..31\n     * 0xf3ffc07f = binary 11110011111111111100000001111111\n     */\n    unsigned long black_mask = 0xf3ffc07fUL;\n    int n;\n\n    /* Check for non-textual (\"black-listed\") bytes. */\n    for (n = 0; n <= 31; n++, black_mask >>= 1)\n        if ((black_mask & 1) && (s->dyn_ltree[n].Freq != 0))\n            return Z_BINARY;\n\n    /* Check for textual (\"white-listed\") bytes. */\n    if (s->dyn_ltree[9].Freq != 0 || s->dyn_ltree[10].Freq != 0\n            || s->dyn_ltree[13].Freq != 0)\n        return Z_TEXT;\n    for (n = 32; n < LITERALS; n++)\n        if (s->dyn_ltree[n].Freq != 0)\n            return Z_TEXT;\n\n    /* There are no \"black-listed\" or \"white-listed\" bytes:\n     * this stream either is empty or has tolerated (\"gray-listed\") bytes only.\n     */\n    return Z_BINARY;\n}\n\n/* ===========================================================================\n * Reverse the first len bits of a code, using straightforward code (a faster\n * method would use a table)\n * IN assertion: 1 <= len <= 15\n */\nlocal unsigned bi_reverse(code, len)\n    unsigned code; /* the value to invert */\n    int len;       /* its bit length */\n{\n    register unsigned res = 0;\n    do {\n        res |= code & 1;\n        code >>= 1, res <<= 1;\n    } while (--len > 0);\n    return res >> 1;\n}\n\n/* ===========================================================================\n * Flush the bit buffer, keeping at most 7 bits in it.\n */\nlocal void bi_flush(s)\n    deflate_state *s;\n{\n    if (s->bi_valid == 16) {\n        put_short(s, s->bi_buf);\n        s->bi_buf = 0;\n        s->bi_valid = 0;\n    } else if (s->bi_valid >= 8) {\n        put_byte(s, (Byte)s->bi_buf);\n        s->bi_buf >>= 8;\n        s->bi_valid -= 8;\n    }\n}\n\n/* ===========================================================================\n * Flush the bit buffer and align the output on a byte boundary\n */\nlocal void bi_windup(s)\n    deflate_state *s;\n{\n    if (s->bi_valid > 8) {\n        put_short(s, s->bi_buf);\n    } else if (s->bi_valid > 0) {\n        put_byte(s, (Byte)s->bi_buf);\n    }\n    s->bi_buf = 0;\n    s->bi_valid = 0;\n#ifdef DEBUG\n    s->bits_sent = (s->bits_sent+7) & ~7;\n#endif\n}\n\n/* ===========================================================================\n * Copy a stored block, storing first the length and its\n * one's complement if requested.\n */\nlocal void copy_block(s, buf, len, header)\n    deflate_state *s;\n    charf    *buf;    /* the input data */\n    unsigned len;     /* its length */\n    int      header;  /* true if block header must be written */\n{\n    bi_windup(s);        /* align on byte boundary */\n\n    if (header) {\n        put_short(s, (ush)len);\n        put_short(s, (ush)~len);\n#ifdef DEBUG\n        s->bits_sent += 2*16;\n#endif\n    }\n#ifdef DEBUG\n    s->bits_sent += (ulg)len<<3;\n#endif\n    while (len--) {\n        put_byte(s, *buf++);\n    }\n}\n"
  },
  {
    "path": "external/zlib/trees.h",
    "content": "/* header created automatically with -DGEN_TREES_H */\n\nlocal const ct_data static_ltree[L_CODES+2] = {\n{{ 12},{  8}}, {{140},{  8}}, {{ 76},{  8}}, {{204},{  8}}, {{ 44},{  8}},\n{{172},{  8}}, {{108},{  8}}, {{236},{  8}}, {{ 28},{  8}}, {{156},{  8}},\n{{ 92},{  8}}, {{220},{  8}}, {{ 60},{  8}}, {{188},{  8}}, {{124},{  8}},\n{{252},{  8}}, {{  2},{  8}}, {{130},{  8}}, {{ 66},{  8}}, {{194},{  8}},\n{{ 34},{  8}}, {{162},{  8}}, {{ 98},{  8}}, {{226},{  8}}, {{ 18},{  8}},\n{{146},{  8}}, {{ 82},{  8}}, {{210},{  8}}, {{ 50},{  8}}, {{178},{  8}},\n{{114},{  8}}, {{242},{  8}}, {{ 10},{  8}}, {{138},{  8}}, {{ 74},{  8}},\n{{202},{  8}}, {{ 42},{  8}}, {{170},{  8}}, {{106},{  8}}, {{234},{  8}},\n{{ 26},{  8}}, {{154},{  8}}, {{ 90},{  8}}, {{218},{  8}}, {{ 58},{  8}},\n{{186},{  8}}, {{122},{  8}}, {{250},{  8}}, {{  6},{  8}}, {{134},{  8}},\n{{ 70},{  8}}, {{198},{  8}}, {{ 38},{  8}}, {{166},{  8}}, {{102},{  8}},\n{{230},{  8}}, {{ 22},{  8}}, {{150},{  8}}, {{ 86},{  8}}, {{214},{  8}},\n{{ 54},{  8}}, {{182},{  8}}, {{118},{  8}}, {{246},{  8}}, {{ 14},{  8}},\n{{142},{  8}}, {{ 78},{  8}}, {{206},{  8}}, {{ 46},{  8}}, {{174},{  8}},\n{{110},{  8}}, {{238},{  8}}, {{ 30},{  8}}, {{158},{  8}}, {{ 94},{  8}},\n{{222},{  8}}, {{ 62},{  8}}, {{190},{  8}}, {{126},{  8}}, {{254},{  8}},\n{{  1},{  8}}, {{129},{  8}}, {{ 65},{  8}}, {{193},{  8}}, {{ 33},{  8}},\n{{161},{  8}}, {{ 97},{  8}}, {{225},{  8}}, {{ 17},{  8}}, {{145},{  8}},\n{{ 81},{  8}}, {{209},{  8}}, {{ 49},{  8}}, {{177},{  8}}, {{113},{  8}},\n{{241},{  8}}, {{  9},{  8}}, {{137},{  8}}, {{ 73},{  8}}, {{201},{  8}},\n{{ 41},{  8}}, {{169},{  8}}, {{105},{  8}}, {{233},{  8}}, {{ 25},{  8}},\n{{153},{  8}}, {{ 89},{  8}}, {{217},{  8}}, {{ 57},{  8}}, {{185},{  8}},\n{{121},{  8}}, {{249},{  8}}, {{  5},{  8}}, {{133},{  8}}, {{ 69},{  8}},\n{{197},{  8}}, {{ 37},{  8}}, {{165},{  8}}, {{101},{  8}}, {{229},{  8}},\n{{ 21},{  8}}, {{149},{  8}}, {{ 85},{  8}}, {{213},{  8}}, {{ 53},{  8}},\n{{181},{  8}}, {{117},{  8}}, {{245},{  8}}, {{ 13},{  8}}, {{141},{  8}},\n{{ 77},{  8}}, {{205},{  8}}, {{ 45},{  8}}, {{173},{  8}}, {{109},{  8}},\n{{237},{  8}}, {{ 29},{  8}}, {{157},{  8}}, {{ 93},{  8}}, {{221},{  8}},\n{{ 61},{  8}}, {{189},{  8}}, {{125},{  8}}, {{253},{  8}}, {{ 19},{  9}},\n{{275},{  9}}, {{147},{  9}}, {{403},{  9}}, {{ 83},{  9}}, {{339},{  9}},\n{{211},{  9}}, {{467},{  9}}, {{ 51},{  9}}, {{307},{  9}}, {{179},{  9}},\n{{435},{  9}}, {{115},{  9}}, {{371},{  9}}, {{243},{  9}}, {{499},{  9}},\n{{ 11},{  9}}, {{267},{  9}}, {{139},{  9}}, {{395},{  9}}, {{ 75},{  9}},\n{{331},{  9}}, {{203},{  9}}, {{459},{  9}}, {{ 43},{  9}}, {{299},{  9}},\n{{171},{  9}}, {{427},{  9}}, {{107},{  9}}, {{363},{  9}}, {{235},{  9}},\n{{491},{  9}}, {{ 27},{  9}}, {{283},{  9}}, {{155},{  9}}, {{411},{  9}},\n{{ 91},{  9}}, {{347},{  9}}, {{219},{  9}}, {{475},{  9}}, {{ 59},{  9}},\n{{315},{  9}}, {{187},{  9}}, {{443},{  9}}, {{123},{  9}}, {{379},{  9}},\n{{251},{  9}}, {{507},{  9}}, {{  7},{  9}}, {{263},{  9}}, {{135},{  9}},\n{{391},{  9}}, {{ 71},{  9}}, {{327},{  9}}, {{199},{  9}}, {{455},{  9}},\n{{ 39},{  9}}, {{295},{  9}}, {{167},{  9}}, {{423},{  9}}, {{103},{  9}},\n{{359},{  9}}, {{231},{  9}}, {{487},{  9}}, {{ 23},{  9}}, {{279},{  9}},\n{{151},{  9}}, {{407},{  9}}, {{ 87},{  9}}, {{343},{  9}}, {{215},{  9}},\n{{471},{  9}}, {{ 55},{  9}}, {{311},{  9}}, {{183},{  9}}, {{439},{  9}},\n{{119},{  9}}, {{375},{  9}}, {{247},{  9}}, {{503},{  9}}, {{ 15},{  9}},\n{{271},{  9}}, {{143},{  9}}, {{399},{  9}}, {{ 79},{  9}}, {{335},{  9}},\n{{207},{  9}}, {{463},{  9}}, {{ 47},{  9}}, {{303},{  9}}, {{175},{  9}},\n{{431},{  9}}, {{111},{  9}}, {{367},{  9}}, {{239},{  9}}, {{495},{  9}},\n{{ 31},{  9}}, {{287},{  9}}, {{159},{  9}}, {{415},{  9}}, {{ 95},{  9}},\n{{351},{  9}}, {{223},{  9}}, {{479},{  9}}, {{ 63},{  9}}, {{319},{  9}},\n{{191},{  9}}, {{447},{  9}}, {{127},{  9}}, {{383},{  9}}, {{255},{  9}},\n{{511},{  9}}, {{  0},{  7}}, {{ 64},{  7}}, {{ 32},{  7}}, {{ 96},{  7}},\n{{ 16},{  7}}, {{ 80},{  7}}, {{ 48},{  7}}, {{112},{  7}}, {{  8},{  7}},\n{{ 72},{  7}}, {{ 40},{  7}}, {{104},{  7}}, {{ 24},{  7}}, {{ 88},{  7}},\n{{ 56},{  7}}, {{120},{  7}}, {{  4},{  7}}, {{ 68},{  7}}, {{ 36},{  7}},\n{{100},{  7}}, {{ 20},{  7}}, {{ 84},{  7}}, {{ 52},{  7}}, {{116},{  7}},\n{{  3},{  8}}, {{131},{  8}}, {{ 67},{  8}}, {{195},{  8}}, {{ 35},{  8}},\n{{163},{  8}}, {{ 99},{  8}}, {{227},{  8}}\n};\n\nlocal const ct_data static_dtree[D_CODES] = {\n{{ 0},{ 5}}, {{16},{ 5}}, {{ 8},{ 5}}, {{24},{ 5}}, {{ 4},{ 5}},\n{{20},{ 5}}, {{12},{ 5}}, {{28},{ 5}}, {{ 2},{ 5}}, {{18},{ 5}},\n{{10},{ 5}}, {{26},{ 5}}, {{ 6},{ 5}}, {{22},{ 5}}, {{14},{ 5}},\n{{30},{ 5}}, {{ 1},{ 5}}, {{17},{ 5}}, {{ 9},{ 5}}, {{25},{ 5}},\n{{ 5},{ 5}}, {{21},{ 5}}, {{13},{ 5}}, {{29},{ 5}}, {{ 3},{ 5}},\n{{19},{ 5}}, {{11},{ 5}}, {{27},{ 5}}, {{ 7},{ 5}}, {{23},{ 5}}\n};\n\nconst uch ZLIB_INTERNAL _dist_code[DIST_CODE_LEN] = {\n 0,  1,  2,  3,  4,  4,  5,  5,  6,  6,  6,  6,  7,  7,  7,  7,  8,  8,  8,  8,\n 8,  8,  8,  8,  9,  9,  9,  9,  9,  9,  9,  9, 10, 10, 10, 10, 10, 10, 10, 10,\n10, 10, 10, 10, 10, 10, 10, 10, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11,\n11, 11, 11, 11, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12,\n12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 13, 13, 13, 13,\n13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13,\n13, 13, 13, 13, 13, 13, 13, 13, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14,\n14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14,\n14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14,\n14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 15, 15, 15, 15, 15, 15, 15, 15,\n15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15,\n15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15,\n15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15,  0,  0, 16, 17,\n18, 18, 19, 19, 20, 20, 20, 20, 21, 21, 21, 21, 22, 22, 22, 22, 22, 22, 22, 22,\n23, 23, 23, 23, 23, 23, 23, 23, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24,\n24, 24, 24, 24, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25,\n26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26,\n26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 27, 27, 27, 27, 27, 27, 27, 27,\n27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27,\n27, 27, 27, 27, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28,\n28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28,\n28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28,\n28, 28, 28, 28, 28, 28, 28, 28, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29,\n29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29,\n29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29,\n29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29\n};\n\nconst uch ZLIB_INTERNAL _length_code[MAX_MATCH-MIN_MATCH+1]= {\n 0,  1,  2,  3,  4,  5,  6,  7,  8,  8,  9,  9, 10, 10, 11, 11, 12, 12, 12, 12,\n13, 13, 13, 13, 14, 14, 14, 14, 15, 15, 15, 15, 16, 16, 16, 16, 16, 16, 16, 16,\n17, 17, 17, 17, 17, 17, 17, 17, 18, 18, 18, 18, 18, 18, 18, 18, 19, 19, 19, 19,\n19, 19, 19, 19, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20,\n21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 22, 22, 22, 22,\n22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 23, 23, 23, 23, 23, 23, 23, 23,\n23, 23, 23, 23, 23, 23, 23, 23, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24,\n24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24,\n25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25,\n25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 26, 26, 26, 26, 26, 26, 26, 26,\n26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26,\n26, 26, 26, 26, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27,\n27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 28\n};\n\nlocal const int base_length[LENGTH_CODES] = {\n0, 1, 2, 3, 4, 5, 6, 7, 8, 10, 12, 14, 16, 20, 24, 28, 32, 40, 48, 56,\n64, 80, 96, 112, 128, 160, 192, 224, 0\n};\n\nlocal const int base_dist[D_CODES] = {\n    0,     1,     2,     3,     4,     6,     8,    12,    16,    24,\n   32,    48,    64,    96,   128,   192,   256,   384,   512,   768,\n 1024,  1536,  2048,  3072,  4096,  6144,  8192, 12288, 16384, 24576\n};\n\n"
  },
  {
    "path": "external/zlib/uncompr.c",
    "content": "/* uncompr.c -- decompress a memory buffer\n * Copyright (C) 1995-2003, 2010 Jean-loup Gailly.\n * For conditions of distribution and use, see copyright notice in zlib.h\n */\n\n/* @(#) $Id$ */\n\n#define ZLIB_INTERNAL\n#include \"zlib.h\"\n\n/* ===========================================================================\n     Decompresses the source buffer into the destination buffer.  sourceLen is\n   the byte length of the source buffer. Upon entry, destLen is the total\n   size of the destination buffer, which must be large enough to hold the\n   entire uncompressed data. (The size of the uncompressed data must have\n   been saved previously by the compressor and transmitted to the decompressor\n   by some mechanism outside the scope of this compression library.)\n   Upon exit, destLen is the actual size of the compressed buffer.\n\n     uncompress returns Z_OK if success, Z_MEM_ERROR if there was not\n   enough memory, Z_BUF_ERROR if there was not enough room in the output\n   buffer, or Z_DATA_ERROR if the input data was corrupted.\n*/\nint ZEXPORT uncompress (dest, destLen, source, sourceLen)\n    Bytef *dest;\n    uLongf *destLen;\n    const Bytef *source;\n    uLong sourceLen;\n{\n    z_stream stream;\n    int err;\n\n    stream.next_in = (z_const Bytef *)source;\n    stream.avail_in = (uInt)sourceLen;\n    /* Check for source > 64K on 16-bit machine: */\n    if ((uLong)stream.avail_in != sourceLen) return Z_BUF_ERROR;\n\n    stream.next_out = dest;\n    stream.avail_out = (uInt)*destLen;\n    if ((uLong)stream.avail_out != *destLen) return Z_BUF_ERROR;\n\n    stream.zalloc = (alloc_func)0;\n    stream.zfree = (free_func)0;\n\n    err = inflateInit(&stream);\n    if (err != Z_OK) return err;\n\n    err = inflate(&stream, Z_FINISH);\n    if (err != Z_STREAM_END) {\n        inflateEnd(&stream);\n        if (err == Z_NEED_DICT || (err == Z_BUF_ERROR && stream.avail_in == 0))\n            return Z_DATA_ERROR;\n        return err;\n    }\n    *destLen = stream.total_out;\n\n    err = inflateEnd(&stream);\n    return err;\n}\n"
  },
  {
    "path": "external/zlib/zconf.h",
    "content": "/* zconf.h -- configuration of the zlib compression library\n * Copyright (C) 1995-2013 Jean-loup Gailly.\n * For conditions of distribution and use, see copyright notice in zlib.h\n */\n\n/* @(#) $Id$ */\n\n#ifndef ZCONF_H\n#define ZCONF_H\n\n/*\n * If you *really* need a unique prefix for all types and library functions,\n * compile with -DZ_PREFIX. The \"standard\" zlib should be compiled without it.\n * Even better than compiling with -DZ_PREFIX would be to use configure to set\n * this permanently in zconf.h using \"./configure --zprefix\".\n */\n#ifdef Z_PREFIX     /* may be set to #if 1 by ./configure */\n#  define Z_PREFIX_SET\n\n/* all linked symbols */\n#  define _dist_code            z__dist_code\n#  define _length_code          z__length_code\n#  define _tr_align             z__tr_align\n#  define _tr_flush_bits        z__tr_flush_bits\n#  define _tr_flush_block       z__tr_flush_block\n#  define _tr_init              z__tr_init\n#  define _tr_stored_block      z__tr_stored_block\n#  define _tr_tally             z__tr_tally\n#  define adler32               z_adler32\n#  define adler32_combine       z_adler32_combine\n#  define adler32_combine64     z_adler32_combine64\n#  ifndef Z_SOLO\n#    define compress              z_compress\n#    define compress2             z_compress2\n#    define compressBound         z_compressBound\n#  endif\n#  define crc32                 z_crc32\n#  define crc32_combine         z_crc32_combine\n#  define crc32_combine64       z_crc32_combine64\n#  define deflate               z_deflate\n#  define deflateBound          z_deflateBound\n#  define deflateCopy           z_deflateCopy\n#  define deflateEnd            z_deflateEnd\n#  define deflateInit2_         z_deflateInit2_\n#  define deflateInit_          z_deflateInit_\n#  define deflateParams         z_deflateParams\n#  define deflatePending        z_deflatePending\n#  define deflatePrime          z_deflatePrime\n#  define deflateReset          z_deflateReset\n#  define deflateResetKeep      z_deflateResetKeep\n#  define deflateSetDictionary  z_deflateSetDictionary\n#  define deflateSetHeader      z_deflateSetHeader\n#  define deflateTune           z_deflateTune\n#  define deflate_copyright     z_deflate_copyright\n#  define get_crc_table         z_get_crc_table\n#  ifndef Z_SOLO\n#    define gz_error              z_gz_error\n#    define gz_intmax             z_gz_intmax\n#    define gz_strwinerror        z_gz_strwinerror\n#    define gzbuffer              z_gzbuffer\n#    define gzclearerr            z_gzclearerr\n#    define gzclose               z_gzclose\n#    define gzclose_r             z_gzclose_r\n#    define gzclose_w             z_gzclose_w\n#    define gzdirect              z_gzdirect\n#    define gzdopen               z_gzdopen\n#    define gzeof                 z_gzeof\n#    define gzerror               z_gzerror\n#    define gzflush               z_gzflush\n#    define gzgetc                z_gzgetc\n#    define gzgetc_               z_gzgetc_\n#    define gzgets                z_gzgets\n#    define gzoffset              z_gzoffset\n#    define gzoffset64            z_gzoffset64\n#    define gzopen                z_gzopen\n#    define gzopen64              z_gzopen64\n#    ifdef _WIN32\n#      define gzopen_w              z_gzopen_w\n#    endif\n#    define gzprintf              z_gzprintf\n#    define gzvprintf             z_gzvprintf\n#    define gzputc                z_gzputc\n#    define gzputs                z_gzputs\n#    define gzread                z_gzread\n#    define gzrewind              z_gzrewind\n#    define gzseek                z_gzseek\n#    define gzseek64              z_gzseek64\n#    define gzsetparams           z_gzsetparams\n#    define gztell                z_gztell\n#    define gztell64              z_gztell64\n#    define gzungetc              z_gzungetc\n#    define gzwrite               z_gzwrite\n#  endif\n#  define inflate               z_inflate\n#  define inflateBack           z_inflateBack\n#  define inflateBackEnd        z_inflateBackEnd\n#  define inflateBackInit_      z_inflateBackInit_\n#  define inflateCopy           z_inflateCopy\n#  define inflateEnd            z_inflateEnd\n#  define inflateGetHeader      z_inflateGetHeader\n#  define inflateInit2_         z_inflateInit2_\n#  define inflateInit_          z_inflateInit_\n#  define inflateMark           z_inflateMark\n#  define inflatePrime          z_inflatePrime\n#  define inflateReset          z_inflateReset\n#  define inflateReset2         z_inflateReset2\n#  define inflateSetDictionary  z_inflateSetDictionary\n#  define inflateGetDictionary  z_inflateGetDictionary\n#  define inflateSync           z_inflateSync\n#  define inflateSyncPoint      z_inflateSyncPoint\n#  define inflateUndermine      z_inflateUndermine\n#  define inflateResetKeep      z_inflateResetKeep\n#  define inflate_copyright     z_inflate_copyright\n#  define inflate_fast          z_inflate_fast\n#  define inflate_table         z_inflate_table\n#  ifndef Z_SOLO\n#    define uncompress            z_uncompress\n#  endif\n#  define zError                z_zError\n#  ifndef Z_SOLO\n#    define zcalloc               z_zcalloc\n#    define zcfree                z_zcfree\n#  endif\n#  define zlibCompileFlags      z_zlibCompileFlags\n#  define zlibVersion           z_zlibVersion\n\n/* all zlib typedefs in zlib.h and zconf.h */\n#  define Byte                  z_Byte\n#  define Bytef                 z_Bytef\n#  define alloc_func            z_alloc_func\n#  define charf                 z_charf\n#  define free_func             z_free_func\n#  ifndef Z_SOLO\n#    define gzFile                z_gzFile\n#  endif\n#  define gz_header             z_gz_header\n#  define gz_headerp            z_gz_headerp\n#  define in_func               z_in_func\n#  define intf                  z_intf\n#  define out_func              z_out_func\n#  define uInt                  z_uInt\n#  define uIntf                 z_uIntf\n#  define uLong                 z_uLong\n#  define uLongf                z_uLongf\n#  define voidp                 z_voidp\n#  define voidpc                z_voidpc\n#  define voidpf                z_voidpf\n\n/* all zlib structs in zlib.h and zconf.h */\n#  define gz_header_s           z_gz_header_s\n#  define internal_state        z_internal_state\n\n#endif\n\n#if defined(__MSDOS__) && !defined(MSDOS)\n#  define MSDOS\n#endif\n#if (defined(OS_2) || defined(__OS2__)) && !defined(OS2)\n#  define OS2\n#endif\n#if defined(_WINDOWS) && !defined(WINDOWS)\n#  define WINDOWS\n#endif\n#if defined(_WIN32) || defined(_WIN32_WCE) || defined(__WIN32__)\n#  ifndef WIN32\n#    define WIN32\n#  endif\n#endif\n#if (defined(MSDOS) || defined(OS2) || defined(WINDOWS)) && !defined(WIN32)\n#  if !defined(__GNUC__) && !defined(__FLAT__) && !defined(__386__)\n#    ifndef SYS16BIT\n#      define SYS16BIT\n#    endif\n#  endif\n#endif\n\n/*\n * Compile with -DMAXSEG_64K if the alloc function cannot allocate more\n * than 64k bytes at a time (needed on systems with 16-bit int).\n */\n#ifdef SYS16BIT\n#  define MAXSEG_64K\n#endif\n#ifdef MSDOS\n#  define UNALIGNED_OK\n#endif\n\n#ifdef __STDC_VERSION__\n#  ifndef STDC\n#    define STDC\n#  endif\n#  if __STDC_VERSION__ >= 199901L\n#    ifndef STDC99\n#      define STDC99\n#    endif\n#  endif\n#endif\n#if !defined(STDC) && (defined(__STDC__) || defined(__cplusplus))\n#  define STDC\n#endif\n#if !defined(STDC) && (defined(__GNUC__) || defined(__BORLANDC__))\n#  define STDC\n#endif\n#if !defined(STDC) && (defined(MSDOS) || defined(WINDOWS) || defined(WIN32))\n#  define STDC\n#endif\n#if !defined(STDC) && (defined(OS2) || defined(__HOS_AIX__))\n#  define STDC\n#endif\n\n#if defined(__OS400__) && !defined(STDC)    /* iSeries (formerly AS/400). */\n#  define STDC\n#endif\n\n#ifndef STDC\n#  ifndef const /* cannot use !defined(STDC) && !defined(const) on Mac */\n#    define const       /* note: need a more gentle solution here */\n#  endif\n#endif\n\n#if defined(ZLIB_CONST) && !defined(z_const)\n#  define z_const const\n#else\n#  define z_const\n#endif\n\n/* Some Mac compilers merge all .h files incorrectly: */\n#if defined(__MWERKS__)||defined(applec)||defined(THINK_C)||defined(__SC__)\n#  define NO_DUMMY_DECL\n#endif\n\n/* Maximum value for memLevel in deflateInit2 */\n#ifndef MAX_MEM_LEVEL\n#  ifdef MAXSEG_64K\n#    define MAX_MEM_LEVEL 8\n#  else\n#    define MAX_MEM_LEVEL 9\n#  endif\n#endif\n\n/* Maximum value for windowBits in deflateInit2 and inflateInit2.\n * WARNING: reducing MAX_WBITS makes minigzip unable to extract .gz files\n * created by gzip. (Files created by minigzip can still be extracted by\n * gzip.)\n */\n#ifndef MAX_WBITS\n#  define MAX_WBITS   15 /* 32K LZ77 window */\n#endif\n\n/* The memory requirements for deflate are (in bytes):\n            (1 << (windowBits+2)) +  (1 << (memLevel+9))\n that is: 128K for windowBits=15  +  128K for memLevel = 8  (default values)\n plus a few kilobytes for small objects. For example, if you want to reduce\n the default memory requirements from 256K to 128K, compile with\n     make CFLAGS=\"-O -DMAX_WBITS=14 -DMAX_MEM_LEVEL=7\"\n Of course this will generally degrade compression (there's no free lunch).\n\n   The memory requirements for inflate are (in bytes) 1 << windowBits\n that is, 32K for windowBits=15 (default value) plus a few kilobytes\n for small objects.\n*/\n\n                        /* Type declarations */\n\n#ifndef OF /* function prototypes */\n#  ifdef STDC\n#    define OF(args)  args\n#  else\n#    define OF(args)  ()\n#  endif\n#endif\n\n#ifndef Z_ARG /* function prototypes for stdarg */\n#  if defined(STDC) || defined(Z_HAVE_STDARG_H)\n#    define Z_ARG(args)  args\n#  else\n#    define Z_ARG(args)  ()\n#  endif\n#endif\n\n/* The following definitions for FAR are needed only for MSDOS mixed\n * model programming (small or medium model with some far allocations).\n * This was tested only with MSC; for other MSDOS compilers you may have\n * to define NO_MEMCPY in zutil.h.  If you don't need the mixed model,\n * just define FAR to be empty.\n */\n#ifdef SYS16BIT\n#  if defined(M_I86SM) || defined(M_I86MM)\n     /* MSC small or medium model */\n#    define SMALL_MEDIUM\n#    ifdef _MSC_VER\n#      define FAR _far\n#    else\n#      define FAR far\n#    endif\n#  endif\n#  if (defined(__SMALL__) || defined(__MEDIUM__))\n     /* Turbo C small or medium model */\n#    define SMALL_MEDIUM\n#    ifdef __BORLANDC__\n#      define FAR _far\n#    else\n#      define FAR far\n#    endif\n#  endif\n#endif\n\n#if defined(WINDOWS) || defined(WIN32)\n   /* If building or using zlib as a DLL, define ZLIB_DLL.\n    * This is not mandatory, but it offers a little performance increase.\n    */\n#  ifdef ZLIB_DLL\n#    if defined(WIN32) && (!defined(__BORLANDC__) || (__BORLANDC__ >= 0x500))\n#      ifdef ZLIB_INTERNAL\n#        define ZEXTERN extern __declspec(dllexport)\n#      else\n#        define ZEXTERN extern __declspec(dllimport)\n#      endif\n#    endif\n#  endif  /* ZLIB_DLL */\n   /* If building or using zlib with the WINAPI/WINAPIV calling convention,\n    * define ZLIB_WINAPI.\n    * Caution: the standard ZLIB1.DLL is NOT compiled using ZLIB_WINAPI.\n    */\n#  ifdef ZLIB_WINAPI\n#    ifdef FAR\n#      undef FAR\n#    endif\n#    include <windows.h>\n     /* No need for _export, use ZLIB.DEF instead. */\n     /* For complete Windows compatibility, use WINAPI, not __stdcall. */\n#    define ZEXPORT WINAPI\n#    ifdef WIN32\n#      define ZEXPORTVA WINAPIV\n#    else\n#      define ZEXPORTVA FAR CDECL\n#    endif\n#  endif\n#endif\n\n#if defined (__BEOS__)\n#  ifdef ZLIB_DLL\n#    ifdef ZLIB_INTERNAL\n#      define ZEXPORT   __declspec(dllexport)\n#      define ZEXPORTVA __declspec(dllexport)\n#    else\n#      define ZEXPORT   __declspec(dllimport)\n#      define ZEXPORTVA __declspec(dllimport)\n#    endif\n#  endif\n#endif\n\n#ifndef ZEXTERN\n#  define ZEXTERN extern\n#endif\n#ifndef ZEXPORT\n#  define ZEXPORT\n#endif\n#ifndef ZEXPORTVA\n#  define ZEXPORTVA\n#endif\n\n#ifndef FAR\n#  define FAR\n#endif\n\n#if !defined(__MACTYPES__)\ntypedef unsigned char  Byte;  /* 8 bits */\n#endif\ntypedef unsigned int   uInt;  /* 16 bits or more */\ntypedef unsigned long  uLong; /* 32 bits or more */\n\n#ifdef SMALL_MEDIUM\n   /* Borland C/C++ and some old MSC versions ignore FAR inside typedef */\n#  define Bytef Byte FAR\n#else\n   typedef Byte  FAR Bytef;\n#endif\ntypedef char  FAR charf;\ntypedef int   FAR intf;\ntypedef uInt  FAR uIntf;\ntypedef uLong FAR uLongf;\n\n#ifdef STDC\n   typedef void const *voidpc;\n   typedef void FAR   *voidpf;\n   typedef void       *voidp;\n#else\n   typedef Byte const *voidpc;\n   typedef Byte FAR   *voidpf;\n   typedef Byte       *voidp;\n#endif\n\n#if !defined(Z_U4) && !defined(Z_SOLO) && defined(STDC)\n#  include <limits.h>\n#  if (UINT_MAX == 0xffffffffUL)\n#    define Z_U4 unsigned\n#  elif (ULONG_MAX == 0xffffffffUL)\n#    define Z_U4 unsigned long\n#  elif (USHRT_MAX == 0xffffffffUL)\n#    define Z_U4 unsigned short\n#  endif\n#endif\n\n#ifdef Z_U4\n   typedef Z_U4 z_crc_t;\n#else\n   typedef unsigned long z_crc_t;\n#endif\n\n#if 1    /* was set to #if 1 by ./configure */\n#  define Z_HAVE_UNISTD_H\n#endif\n\n#if 1    /* was set to #if 1 by ./configure */\n#  define Z_HAVE_STDARG_H\n#endif\n\n#ifdef STDC\n#  ifndef Z_SOLO\n#    include <sys/types.h>      /* for off_t */\n#  endif\n#endif\n\n#if defined(STDC) || defined(Z_HAVE_STDARG_H)\n#  ifndef Z_SOLO\n#    include <stdarg.h>         /* for va_list */\n#  endif\n#endif\n\n#ifdef _WIN32\n#  ifndef Z_SOLO\n#    include <stddef.h>         /* for wchar_t */\n#  endif\n#endif\n\n/* a little trick to accommodate both \"#define _LARGEFILE64_SOURCE\" and\n * \"#define _LARGEFILE64_SOURCE 1\" as requesting 64-bit operations, (even\n * though the former does not conform to the LFS document), but considering\n * both \"#undef _LARGEFILE64_SOURCE\" and \"#define _LARGEFILE64_SOURCE 0\" as\n * equivalently requesting no 64-bit operations\n */\n#if defined(_LARGEFILE64_SOURCE) && -_LARGEFILE64_SOURCE - -1 == 1\n#  undef _LARGEFILE64_SOURCE\n#endif\n\n#if defined(__WATCOMC__) && !defined(Z_HAVE_UNISTD_H)\n#  define Z_HAVE_UNISTD_H\n#endif\n#ifndef Z_SOLO\n#  if defined(Z_HAVE_UNISTD_H) || defined(_LARGEFILE64_SOURCE)\n#    include <unistd.h>         /* for SEEK_*, off_t, and _LFS64_LARGEFILE */\n#    ifdef VMS\n#      include <unixio.h>       /* for off_t */\n#    endif\n#    ifndef z_off_t\n#      define z_off_t off_t\n#    endif\n#  endif\n#endif\n\n#if defined(_LFS64_LARGEFILE) && _LFS64_LARGEFILE-0\n#  define Z_LFS64\n#endif\n\n#if defined(_LARGEFILE64_SOURCE) && defined(Z_LFS64)\n#  define Z_LARGE64\n#endif\n\n#if defined(_FILE_OFFSET_BITS) && _FILE_OFFSET_BITS-0 == 64 && defined(Z_LFS64)\n#  define Z_WANT64\n#endif\n\n#if !defined(SEEK_SET) && !defined(Z_SOLO)\n#  define SEEK_SET        0       /* Seek from beginning of file.  */\n#  define SEEK_CUR        1       /* Seek from current position.  */\n#  define SEEK_END        2       /* Set file pointer to EOF plus \"offset\" */\n#endif\n\n#ifndef z_off_t\n#  define z_off_t long\n#endif\n\n#if !defined(_WIN32) && defined(Z_LARGE64)\n#  define z_off64_t off64_t\n#else\n#  if defined(_WIN32) && !defined(__GNUC__) && !defined(Z_SOLO)\n#    define z_off64_t __int64\n#  else\n#    define z_off64_t z_off_t\n#  endif\n#endif\n\n/* MVS linker does not support external names larger than 8 bytes */\n#if defined(__MVS__)\n  #pragma map(deflateInit_,\"DEIN\")\n  #pragma map(deflateInit2_,\"DEIN2\")\n  #pragma map(deflateEnd,\"DEEND\")\n  #pragma map(deflateBound,\"DEBND\")\n  #pragma map(inflateInit_,\"ININ\")\n  #pragma map(inflateInit2_,\"ININ2\")\n  #pragma map(inflateEnd,\"INEND\")\n  #pragma map(inflateSync,\"INSY\")\n  #pragma map(inflateSetDictionary,\"INSEDI\")\n  #pragma map(compressBound,\"CMBND\")\n  #pragma map(inflate_table,\"INTABL\")\n  #pragma map(inflate_fast,\"INFA\")\n  #pragma map(inflate_copyright,\"INCOPY\")\n#endif\n\n#endif /* ZCONF_H */\n"
  },
  {
    "path": "external/zlib/zlib.h",
    "content": "/* zlib.h -- interface of the 'zlib' general purpose compression library\n  version 1.2.8, April 28th, 2013\n\n  Copyright (C) 1995-2013 Jean-loup Gailly and Mark Adler\n\n  This software is provided 'as-is', without any express or implied\n  warranty.  In no event will the authors be held liable for any damages\n  arising from the use of this software.\n\n  Permission is granted to anyone to use this software for any purpose,\n  including commercial applications, and to alter it and redistribute it\n  freely, subject to the following restrictions:\n\n  1. The origin of this software must not be misrepresented; you must not\n     claim that you wrote the original software. If you use this software\n     in a product, an acknowledgment in the product documentation would be\n     appreciated but is not required.\n  2. Altered source versions must be plainly marked as such, and must not be\n     misrepresented as being the original software.\n  3. This notice may not be removed or altered from any source distribution.\n\n  Jean-loup Gailly        Mark Adler\n  jloup@gzip.org          madler@alumni.caltech.edu\n\n\n  The data format used by the zlib library is described by RFCs (Request for\n  Comments) 1950 to 1952 in the files http://tools.ietf.org/html/rfc1950\n  (zlib format), rfc1951 (deflate format) and rfc1952 (gzip format).\n*/\n\n#ifndef ZLIB_H\n#define ZLIB_H\n\n#include \"zconf.h\"\n\n#ifdef __cplusplus\nextern \"C\" {\n#endif\n\n#define ZLIB_VERSION \"1.2.8\"\n#define ZLIB_VERNUM 0x1280\n#define ZLIB_VER_MAJOR 1\n#define ZLIB_VER_MINOR 2\n#define ZLIB_VER_REVISION 8\n#define ZLIB_VER_SUBREVISION 0\n\n/*\n    The 'zlib' compression library provides in-memory compression and\n  decompression functions, including integrity checks of the uncompressed data.\n  This version of the library supports only one compression method (deflation)\n  but other algorithms will be added later and will have the same stream\n  interface.\n\n    Compression can be done in a single step if the buffers are large enough,\n  or can be done by repeated calls of the compression function.  In the latter\n  case, the application must provide more input and/or consume the output\n  (providing more output space) before each call.\n\n    The compressed data format used by default by the in-memory functions is\n  the zlib format, which is a zlib wrapper documented in RFC 1950, wrapped\n  around a deflate stream, which is itself documented in RFC 1951.\n\n    The library also supports reading and writing files in gzip (.gz) format\n  with an interface similar to that of stdio using the functions that start\n  with \"gz\".  The gzip format is different from the zlib format.  gzip is a\n  gzip wrapper, documented in RFC 1952, wrapped around a deflate stream.\n\n    This library can optionally read and write gzip streams in memory as well.\n\n    The zlib format was designed to be compact and fast for use in memory\n  and on communications channels.  The gzip format was designed for single-\n  file compression on file systems, has a larger header than zlib to maintain\n  directory information, and uses a different, slower check method than zlib.\n\n    The library does not install any signal handler.  The decoder checks\n  the consistency of the compressed data, so the library should never crash\n  even in case of corrupted input.\n*/\n\ntypedef voidpf (*alloc_func) OF((voidpf opaque, uInt items, uInt size));\ntypedef void   (*free_func)  OF((voidpf opaque, voidpf address));\n\nstruct internal_state;\n\ntypedef struct z_stream_s {\n    z_const Bytef *next_in;     /* next input byte */\n    uInt     avail_in;  /* number of bytes available at next_in */\n    uLong    total_in;  /* total number of input bytes read so far */\n\n    Bytef    *next_out; /* next output byte should be put there */\n    uInt     avail_out; /* remaining free space at next_out */\n    uLong    total_out; /* total number of bytes output so far */\n\n    z_const char *msg;  /* last error message, NULL if no error */\n    struct internal_state FAR *state; /* not visible by applications */\n\n    alloc_func zalloc;  /* used to allocate the internal state */\n    free_func  zfree;   /* used to free the internal state */\n    voidpf     opaque;  /* private data object passed to zalloc and zfree */\n\n    int     data_type;  /* best guess about the data type: binary or text */\n    uLong   adler;      /* adler32 value of the uncompressed data */\n    uLong   reserved;   /* reserved for future use */\n} z_stream;\n\ntypedef z_stream FAR *z_streamp;\n\n/*\n     gzip header information passed to and from zlib routines.  See RFC 1952\n  for more details on the meanings of these fields.\n*/\ntypedef struct gz_header_s {\n    int     text;       /* true if compressed data believed to be text */\n    uLong   time;       /* modification time */\n    int     xflags;     /* extra flags (not used when writing a gzip file) */\n    int     os;         /* operating system */\n    Bytef   *extra;     /* pointer to extra field or Z_NULL if none */\n    uInt    extra_len;  /* extra field length (valid if extra != Z_NULL) */\n    uInt    extra_max;  /* space at extra (only when reading header) */\n    Bytef   *name;      /* pointer to zero-terminated file name or Z_NULL */\n    uInt    name_max;   /* space at name (only when reading header) */\n    Bytef   *comment;   /* pointer to zero-terminated comment or Z_NULL */\n    uInt    comm_max;   /* space at comment (only when reading header) */\n    int     hcrc;       /* true if there was or will be a header crc */\n    int     done;       /* true when done reading gzip header (not used\n                           when writing a gzip file) */\n} gz_header;\n\ntypedef gz_header FAR *gz_headerp;\n\n/*\n     The application must update next_in and avail_in when avail_in has dropped\n   to zero.  It must update next_out and avail_out when avail_out has dropped\n   to zero.  The application must initialize zalloc, zfree and opaque before\n   calling the init function.  All other fields are set by the compression\n   library and must not be updated by the application.\n\n     The opaque value provided by the application will be passed as the first\n   parameter for calls of zalloc and zfree.  This can be useful for custom\n   memory management.  The compression library attaches no meaning to the\n   opaque value.\n\n     zalloc must return Z_NULL if there is not enough memory for the object.\n   If zlib is used in a multi-threaded application, zalloc and zfree must be\n   thread safe.\n\n     On 16-bit systems, the functions zalloc and zfree must be able to allocate\n   exactly 65536 bytes, but will not be required to allocate more than this if\n   the symbol MAXSEG_64K is defined (see zconf.h).  WARNING: On MSDOS, pointers\n   returned by zalloc for objects of exactly 65536 bytes *must* have their\n   offset normalized to zero.  The default allocation function provided by this\n   library ensures this (see zutil.c).  To reduce memory requirements and avoid\n   any allocation of 64K objects, at the expense of compression ratio, compile\n   the library with -DMAX_WBITS=14 (see zconf.h).\n\n     The fields total_in and total_out can be used for statistics or progress\n   reports.  After compression, total_in holds the total size of the\n   uncompressed data and may be saved for use in the decompressor (particularly\n   if the decompressor wants to decompress everything in a single step).\n*/\n\n                        /* constants */\n\n#define Z_NO_FLUSH      0\n#define Z_PARTIAL_FLUSH 1\n#define Z_SYNC_FLUSH    2\n#define Z_FULL_FLUSH    3\n#define Z_FINISH        4\n#define Z_BLOCK         5\n#define Z_TREES         6\n/* Allowed flush values; see deflate() and inflate() below for details */\n\n#define Z_OK            0\n#define Z_STREAM_END    1\n#define Z_NEED_DICT     2\n#define Z_ERRNO        (-1)\n#define Z_STREAM_ERROR (-2)\n#define Z_DATA_ERROR   (-3)\n#define Z_MEM_ERROR    (-4)\n#define Z_BUF_ERROR    (-5)\n#define Z_VERSION_ERROR (-6)\n/* Return codes for the compression/decompression functions. Negative values\n * are errors, positive values are used for special but normal events.\n */\n\n#define Z_NO_COMPRESSION         0\n#define Z_BEST_SPEED             1\n#define Z_BEST_COMPRESSION       9\n#define Z_DEFAULT_COMPRESSION  (-1)\n/* compression levels */\n\n#define Z_FILTERED            1\n#define Z_HUFFMAN_ONLY        2\n#define Z_RLE                 3\n#define Z_FIXED               4\n#define Z_DEFAULT_STRATEGY    0\n/* compression strategy; see deflateInit2() below for details */\n\n#define Z_BINARY   0\n#define Z_TEXT     1\n#define Z_ASCII    Z_TEXT   /* for compatibility with 1.2.2 and earlier */\n#define Z_UNKNOWN  2\n/* Possible values of the data_type field (though see inflate()) */\n\n#define Z_DEFLATED   8\n/* The deflate compression method (the only one supported in this version) */\n\n#define Z_NULL  0  /* for initializing zalloc, zfree, opaque */\n\n#define zlib_version zlibVersion()\n/* for compatibility with versions < 1.0.2 */\n\n\n                        /* basic functions */\n\nZEXTERN const char * ZEXPORT zlibVersion OF((void));\n/* The application can compare zlibVersion and ZLIB_VERSION for consistency.\n   If the first character differs, the library code actually used is not\n   compatible with the zlib.h header file used by the application.  This check\n   is automatically made by deflateInit and inflateInit.\n */\n\n/*\nZEXTERN int ZEXPORT deflateInit OF((z_streamp strm, int level));\n\n     Initializes the internal stream state for compression.  The fields\n   zalloc, zfree and opaque must be initialized before by the caller.  If\n   zalloc and zfree are set to Z_NULL, deflateInit updates them to use default\n   allocation functions.\n\n     The compression level must be Z_DEFAULT_COMPRESSION, or between 0 and 9:\n   1 gives best speed, 9 gives best compression, 0 gives no compression at all\n   (the input data is simply copied a block at a time).  Z_DEFAULT_COMPRESSION\n   requests a default compromise between speed and compression (currently\n   equivalent to level 6).\n\n     deflateInit returns Z_OK if success, Z_MEM_ERROR if there was not enough\n   memory, Z_STREAM_ERROR if level is not a valid compression level, or\n   Z_VERSION_ERROR if the zlib library version (zlib_version) is incompatible\n   with the version assumed by the caller (ZLIB_VERSION).  msg is set to null\n   if there is no error message.  deflateInit does not perform any compression:\n   this will be done by deflate().\n*/\n\n\nZEXTERN int ZEXPORT deflate OF((z_streamp strm, int flush));\n/*\n    deflate compresses as much data as possible, and stops when the input\n  buffer becomes empty or the output buffer becomes full.  It may introduce\n  some output latency (reading input without producing any output) except when\n  forced to flush.\n\n    The detailed semantics are as follows.  deflate performs one or both of the\n  following actions:\n\n  - Compress more input starting at next_in and update next_in and avail_in\n    accordingly.  If not all input can be processed (because there is not\n    enough room in the output buffer), next_in and avail_in are updated and\n    processing will resume at this point for the next call of deflate().\n\n  - Provide more output starting at next_out and update next_out and avail_out\n    accordingly.  This action is forced if the parameter flush is non zero.\n    Forcing flush frequently degrades the compression ratio, so this parameter\n    should be set only when necessary (in interactive applications).  Some\n    output may be provided even if flush is not set.\n\n    Before the call of deflate(), the application should ensure that at least\n  one of the actions is possible, by providing more input and/or consuming more\n  output, and updating avail_in or avail_out accordingly; avail_out should\n  never be zero before the call.  The application can consume the compressed\n  output when it wants, for example when the output buffer is full (avail_out\n  == 0), or after each call of deflate().  If deflate returns Z_OK and with\n  zero avail_out, it must be called again after making room in the output\n  buffer because there might be more output pending.\n\n    Normally the parameter flush is set to Z_NO_FLUSH, which allows deflate to\n  decide how much data to accumulate before producing output, in order to\n  maximize compression.\n\n    If the parameter flush is set to Z_SYNC_FLUSH, all pending output is\n  flushed to the output buffer and the output is aligned on a byte boundary, so\n  that the decompressor can get all input data available so far.  (In\n  particular avail_in is zero after the call if enough output space has been\n  provided before the call.) Flushing may degrade compression for some\n  compression algorithms and so it should be used only when necessary.  This\n  completes the current deflate block and follows it with an empty stored block\n  that is three bits plus filler bits to the next byte, followed by four bytes\n  (00 00 ff ff).\n\n    If flush is set to Z_PARTIAL_FLUSH, all pending output is flushed to the\n  output buffer, but the output is not aligned to a byte boundary.  All of the\n  input data so far will be available to the decompressor, as for Z_SYNC_FLUSH.\n  This completes the current deflate block and follows it with an empty fixed\n  codes block that is 10 bits long.  This assures that enough bytes are output\n  in order for the decompressor to finish the block before the empty fixed code\n  block.\n\n    If flush is set to Z_BLOCK, a deflate block is completed and emitted, as\n  for Z_SYNC_FLUSH, but the output is not aligned on a byte boundary, and up to\n  seven bits of the current block are held to be written as the next byte after\n  the next deflate block is completed.  In this case, the decompressor may not\n  be provided enough bits at this point in order to complete decompression of\n  the data provided so far to the compressor.  It may need to wait for the next\n  block to be emitted.  This is for advanced applications that need to control\n  the emission of deflate blocks.\n\n    If flush is set to Z_FULL_FLUSH, all output is flushed as with\n  Z_SYNC_FLUSH, and the compression state is reset so that decompression can\n  restart from this point if previous compressed data has been damaged or if\n  random access is desired.  Using Z_FULL_FLUSH too often can seriously degrade\n  compression.\n\n    If deflate returns with avail_out == 0, this function must be called again\n  with the same value of the flush parameter and more output space (updated\n  avail_out), until the flush is complete (deflate returns with non-zero\n  avail_out).  In the case of a Z_FULL_FLUSH or Z_SYNC_FLUSH, make sure that\n  avail_out is greater than six to avoid repeated flush markers due to\n  avail_out == 0 on return.\n\n    If the parameter flush is set to Z_FINISH, pending input is processed,\n  pending output is flushed and deflate returns with Z_STREAM_END if there was\n  enough output space; if deflate returns with Z_OK, this function must be\n  called again with Z_FINISH and more output space (updated avail_out) but no\n  more input data, until it returns with Z_STREAM_END or an error.  After\n  deflate has returned Z_STREAM_END, the only possible operations on the stream\n  are deflateReset or deflateEnd.\n\n    Z_FINISH can be used immediately after deflateInit if all the compression\n  is to be done in a single step.  In this case, avail_out must be at least the\n  value returned by deflateBound (see below).  Then deflate is guaranteed to\n  return Z_STREAM_END.  If not enough output space is provided, deflate will\n  not return Z_STREAM_END, and it must be called again as described above.\n\n    deflate() sets strm->adler to the adler32 checksum of all input read\n  so far (that is, total_in bytes).\n\n    deflate() may update strm->data_type if it can make a good guess about\n  the input data type (Z_BINARY or Z_TEXT).  In doubt, the data is considered\n  binary.  This field is only for information purposes and does not affect the\n  compression algorithm in any manner.\n\n    deflate() returns Z_OK if some progress has been made (more input\n  processed or more output produced), Z_STREAM_END if all input has been\n  consumed and all output has been produced (only when flush is set to\n  Z_FINISH), Z_STREAM_ERROR if the stream state was inconsistent (for example\n  if next_in or next_out was Z_NULL), Z_BUF_ERROR if no progress is possible\n  (for example avail_in or avail_out was zero).  Note that Z_BUF_ERROR is not\n  fatal, and deflate() can be called again with more input and more output\n  space to continue compressing.\n*/\n\n\nZEXTERN int ZEXPORT deflateEnd OF((z_streamp strm));\n/*\n     All dynamically allocated data structures for this stream are freed.\n   This function discards any unprocessed input and does not flush any pending\n   output.\n\n     deflateEnd returns Z_OK if success, Z_STREAM_ERROR if the\n   stream state was inconsistent, Z_DATA_ERROR if the stream was freed\n   prematurely (some input or output was discarded).  In the error case, msg\n   may be set but then points to a static string (which must not be\n   deallocated).\n*/\n\n\n/*\nZEXTERN int ZEXPORT inflateInit OF((z_streamp strm));\n\n     Initializes the internal stream state for decompression.  The fields\n   next_in, avail_in, zalloc, zfree and opaque must be initialized before by\n   the caller.  If next_in is not Z_NULL and avail_in is large enough (the\n   exact value depends on the compression method), inflateInit determines the\n   compression method from the zlib header and allocates all data structures\n   accordingly; otherwise the allocation will be deferred to the first call of\n   inflate.  If zalloc and zfree are set to Z_NULL, inflateInit updates them to\n   use default allocation functions.\n\n     inflateInit returns Z_OK if success, Z_MEM_ERROR if there was not enough\n   memory, Z_VERSION_ERROR if the zlib library version is incompatible with the\n   version assumed by the caller, or Z_STREAM_ERROR if the parameters are\n   invalid, such as a null pointer to the structure.  msg is set to null if\n   there is no error message.  inflateInit does not perform any decompression\n   apart from possibly reading the zlib header if present: actual decompression\n   will be done by inflate().  (So next_in and avail_in may be modified, but\n   next_out and avail_out are unused and unchanged.) The current implementation\n   of inflateInit() does not process any header information -- that is deferred\n   until inflate() is called.\n*/\n\n\nZEXTERN int ZEXPORT inflate OF((z_streamp strm, int flush));\n/*\n    inflate decompresses as much data as possible, and stops when the input\n  buffer becomes empty or the output buffer becomes full.  It may introduce\n  some output latency (reading input without producing any output) except when\n  forced to flush.\n\n  The detailed semantics are as follows.  inflate performs one or both of the\n  following actions:\n\n  - Decompress more input starting at next_in and update next_in and avail_in\n    accordingly.  If not all input can be processed (because there is not\n    enough room in the output buffer), next_in is updated and processing will\n    resume at this point for the next call of inflate().\n\n  - Provide more output starting at next_out and update next_out and avail_out\n    accordingly.  inflate() provides as much output as possible, until there is\n    no more input data or no more space in the output buffer (see below about\n    the flush parameter).\n\n    Before the call of inflate(), the application should ensure that at least\n  one of the actions is possible, by providing more input and/or consuming more\n  output, and updating the next_* and avail_* values accordingly.  The\n  application can consume the uncompressed output when it wants, for example\n  when the output buffer is full (avail_out == 0), or after each call of\n  inflate().  If inflate returns Z_OK and with zero avail_out, it must be\n  called again after making room in the output buffer because there might be\n  more output pending.\n\n    The flush parameter of inflate() can be Z_NO_FLUSH, Z_SYNC_FLUSH, Z_FINISH,\n  Z_BLOCK, or Z_TREES.  Z_SYNC_FLUSH requests that inflate() flush as much\n  output as possible to the output buffer.  Z_BLOCK requests that inflate()\n  stop if and when it gets to the next deflate block boundary.  When decoding\n  the zlib or gzip format, this will cause inflate() to return immediately\n  after the header and before the first block.  When doing a raw inflate,\n  inflate() will go ahead and process the first block, and will return when it\n  gets to the end of that block, or when it runs out of data.\n\n    The Z_BLOCK option assists in appending to or combining deflate streams.\n  Also to assist in this, on return inflate() will set strm->data_type to the\n  number of unused bits in the last byte taken from strm->next_in, plus 64 if\n  inflate() is currently decoding the last block in the deflate stream, plus\n  128 if inflate() returned immediately after decoding an end-of-block code or\n  decoding the complete header up to just before the first byte of the deflate\n  stream.  The end-of-block will not be indicated until all of the uncompressed\n  data from that block has been written to strm->next_out.  The number of\n  unused bits may in general be greater than seven, except when bit 7 of\n  data_type is set, in which case the number of unused bits will be less than\n  eight.  data_type is set as noted here every time inflate() returns for all\n  flush options, and so can be used to determine the amount of currently\n  consumed input in bits.\n\n    The Z_TREES option behaves as Z_BLOCK does, but it also returns when the\n  end of each deflate block header is reached, before any actual data in that\n  block is decoded.  This allows the caller to determine the length of the\n  deflate block header for later use in random access within a deflate block.\n  256 is added to the value of strm->data_type when inflate() returns\n  immediately after reaching the end of the deflate block header.\n\n    inflate() should normally be called until it returns Z_STREAM_END or an\n  error.  However if all decompression is to be performed in a single step (a\n  single call of inflate), the parameter flush should be set to Z_FINISH.  In\n  this case all pending input is processed and all pending output is flushed;\n  avail_out must be large enough to hold all of the uncompressed data for the\n  operation to complete.  (The size of the uncompressed data may have been\n  saved by the compressor for this purpose.) The use of Z_FINISH is not\n  required to perform an inflation in one step.  However it may be used to\n  inform inflate that a faster approach can be used for the single inflate()\n  call.  Z_FINISH also informs inflate to not maintain a sliding window if the\n  stream completes, which reduces inflate's memory footprint.  If the stream\n  does not complete, either because not all of the stream is provided or not\n  enough output space is provided, then a sliding window will be allocated and\n  inflate() can be called again to continue the operation as if Z_NO_FLUSH had\n  been used.\n\n     In this implementation, inflate() always flushes as much output as\n  possible to the output buffer, and always uses the faster approach on the\n  first call.  So the effects of the flush parameter in this implementation are\n  on the return value of inflate() as noted below, when inflate() returns early\n  when Z_BLOCK or Z_TREES is used, and when inflate() avoids the allocation of\n  memory for a sliding window when Z_FINISH is used.\n\n     If a preset dictionary is needed after this call (see inflateSetDictionary\n  below), inflate sets strm->adler to the Adler-32 checksum of the dictionary\n  chosen by the compressor and returns Z_NEED_DICT; otherwise it sets\n  strm->adler to the Adler-32 checksum of all output produced so far (that is,\n  total_out bytes) and returns Z_OK, Z_STREAM_END or an error code as described\n  below.  At the end of the stream, inflate() checks that its computed adler32\n  checksum is equal to that saved by the compressor and returns Z_STREAM_END\n  only if the checksum is correct.\n\n    inflate() can decompress and check either zlib-wrapped or gzip-wrapped\n  deflate data.  The header type is detected automatically, if requested when\n  initializing with inflateInit2().  Any information contained in the gzip\n  header is not retained, so applications that need that information should\n  instead use raw inflate, see inflateInit2() below, or inflateBack() and\n  perform their own processing of the gzip header and trailer.  When processing\n  gzip-wrapped deflate data, strm->adler32 is set to the CRC-32 of the output\n  producted so far.  The CRC-32 is checked against the gzip trailer.\n\n    inflate() returns Z_OK if some progress has been made (more input processed\n  or more output produced), Z_STREAM_END if the end of the compressed data has\n  been reached and all uncompressed output has been produced, Z_NEED_DICT if a\n  preset dictionary is needed at this point, Z_DATA_ERROR if the input data was\n  corrupted (input stream not conforming to the zlib format or incorrect check\n  value), Z_STREAM_ERROR if the stream structure was inconsistent (for example\n  next_in or next_out was Z_NULL), Z_MEM_ERROR if there was not enough memory,\n  Z_BUF_ERROR if no progress is possible or if there was not enough room in the\n  output buffer when Z_FINISH is used.  Note that Z_BUF_ERROR is not fatal, and\n  inflate() can be called again with more input and more output space to\n  continue decompressing.  If Z_DATA_ERROR is returned, the application may\n  then call inflateSync() to look for a good compression block if a partial\n  recovery of the data is desired.\n*/\n\n\nZEXTERN int ZEXPORT inflateEnd OF((z_streamp strm));\n/*\n     All dynamically allocated data structures for this stream are freed.\n   This function discards any unprocessed input and does not flush any pending\n   output.\n\n     inflateEnd returns Z_OK if success, Z_STREAM_ERROR if the stream state\n   was inconsistent.  In the error case, msg may be set but then points to a\n   static string (which must not be deallocated).\n*/\n\n\n                        /* Advanced functions */\n\n/*\n    The following functions are needed only in some special applications.\n*/\n\n/*\nZEXTERN int ZEXPORT deflateInit2 OF((z_streamp strm,\n                                     int  level,\n                                     int  method,\n                                     int  windowBits,\n                                     int  memLevel,\n                                     int  strategy));\n\n     This is another version of deflateInit with more compression options.  The\n   fields next_in, zalloc, zfree and opaque must be initialized before by the\n   caller.\n\n     The method parameter is the compression method.  It must be Z_DEFLATED in\n   this version of the library.\n\n     The windowBits parameter is the base two logarithm of the window size\n   (the size of the history buffer).  It should be in the range 8..15 for this\n   version of the library.  Larger values of this parameter result in better\n   compression at the expense of memory usage.  The default value is 15 if\n   deflateInit is used instead.\n\n     windowBits can also be -8..-15 for raw deflate.  In this case, -windowBits\n   determines the window size.  deflate() will then generate raw deflate data\n   with no zlib header or trailer, and will not compute an adler32 check value.\n\n     windowBits can also be greater than 15 for optional gzip encoding.  Add\n   16 to windowBits to write a simple gzip header and trailer around the\n   compressed data instead of a zlib wrapper.  The gzip header will have no\n   file name, no extra data, no comment, no modification time (set to zero), no\n   header crc, and the operating system will be set to 255 (unknown).  If a\n   gzip stream is being written, strm->adler is a crc32 instead of an adler32.\n\n     The memLevel parameter specifies how much memory should be allocated\n   for the internal compression state.  memLevel=1 uses minimum memory but is\n   slow and reduces compression ratio; memLevel=9 uses maximum memory for\n   optimal speed.  The default value is 8.  See zconf.h for total memory usage\n   as a function of windowBits and memLevel.\n\n     The strategy parameter is used to tune the compression algorithm.  Use the\n   value Z_DEFAULT_STRATEGY for normal data, Z_FILTERED for data produced by a\n   filter (or predictor), Z_HUFFMAN_ONLY to force Huffman encoding only (no\n   string match), or Z_RLE to limit match distances to one (run-length\n   encoding).  Filtered data consists mostly of small values with a somewhat\n   random distribution.  In this case, the compression algorithm is tuned to\n   compress them better.  The effect of Z_FILTERED is to force more Huffman\n   coding and less string matching; it is somewhat intermediate between\n   Z_DEFAULT_STRATEGY and Z_HUFFMAN_ONLY.  Z_RLE is designed to be almost as\n   fast as Z_HUFFMAN_ONLY, but give better compression for PNG image data.  The\n   strategy parameter only affects the compression ratio but not the\n   correctness of the compressed output even if it is not set appropriately.\n   Z_FIXED prevents the use of dynamic Huffman codes, allowing for a simpler\n   decoder for special applications.\n\n     deflateInit2 returns Z_OK if success, Z_MEM_ERROR if there was not enough\n   memory, Z_STREAM_ERROR if any parameter is invalid (such as an invalid\n   method), or Z_VERSION_ERROR if the zlib library version (zlib_version) is\n   incompatible with the version assumed by the caller (ZLIB_VERSION).  msg is\n   set to null if there is no error message.  deflateInit2 does not perform any\n   compression: this will be done by deflate().\n*/\n\nZEXTERN int ZEXPORT deflateSetDictionary OF((z_streamp strm,\n                                             const Bytef *dictionary,\n                                             uInt  dictLength));\n/*\n     Initializes the compression dictionary from the given byte sequence\n   without producing any compressed output.  When using the zlib format, this\n   function must be called immediately after deflateInit, deflateInit2 or\n   deflateReset, and before any call of deflate.  When doing raw deflate, this\n   function must be called either before any call of deflate, or immediately\n   after the completion of a deflate block, i.e. after all input has been\n   consumed and all output has been delivered when using any of the flush\n   options Z_BLOCK, Z_PARTIAL_FLUSH, Z_SYNC_FLUSH, or Z_FULL_FLUSH.  The\n   compressor and decompressor must use exactly the same dictionary (see\n   inflateSetDictionary).\n\n     The dictionary should consist of strings (byte sequences) that are likely\n   to be encountered later in the data to be compressed, with the most commonly\n   used strings preferably put towards the end of the dictionary.  Using a\n   dictionary is most useful when the data to be compressed is short and can be\n   predicted with good accuracy; the data can then be compressed better than\n   with the default empty dictionary.\n\n     Depending on the size of the compression data structures selected by\n   deflateInit or deflateInit2, a part of the dictionary may in effect be\n   discarded, for example if the dictionary is larger than the window size\n   provided in deflateInit or deflateInit2.  Thus the strings most likely to be\n   useful should be put at the end of the dictionary, not at the front.  In\n   addition, the current implementation of deflate will use at most the window\n   size minus 262 bytes of the provided dictionary.\n\n     Upon return of this function, strm->adler is set to the adler32 value\n   of the dictionary; the decompressor may later use this value to determine\n   which dictionary has been used by the compressor.  (The adler32 value\n   applies to the whole dictionary even if only a subset of the dictionary is\n   actually used by the compressor.) If a raw deflate was requested, then the\n   adler32 value is not computed and strm->adler is not set.\n\n     deflateSetDictionary returns Z_OK if success, or Z_STREAM_ERROR if a\n   parameter is invalid (e.g.  dictionary being Z_NULL) or the stream state is\n   inconsistent (for example if deflate has already been called for this stream\n   or if not at a block boundary for raw deflate).  deflateSetDictionary does\n   not perform any compression: this will be done by deflate().\n*/\n\nZEXTERN int ZEXPORT deflateCopy OF((z_streamp dest,\n                                    z_streamp source));\n/*\n     Sets the destination stream as a complete copy of the source stream.\n\n     This function can be useful when several compression strategies will be\n   tried, for example when there are several ways of pre-processing the input\n   data with a filter.  The streams that will be discarded should then be freed\n   by calling deflateEnd.  Note that deflateCopy duplicates the internal\n   compression state which can be quite large, so this strategy is slow and can\n   consume lots of memory.\n\n     deflateCopy returns Z_OK if success, Z_MEM_ERROR if there was not\n   enough memory, Z_STREAM_ERROR if the source stream state was inconsistent\n   (such as zalloc being Z_NULL).  msg is left unchanged in both source and\n   destination.\n*/\n\nZEXTERN int ZEXPORT deflateReset OF((z_streamp strm));\n/*\n     This function is equivalent to deflateEnd followed by deflateInit,\n   but does not free and reallocate all the internal compression state.  The\n   stream will keep the same compression level and any other attributes that\n   may have been set by deflateInit2.\n\n     deflateReset returns Z_OK if success, or Z_STREAM_ERROR if the source\n   stream state was inconsistent (such as zalloc or state being Z_NULL).\n*/\n\nZEXTERN int ZEXPORT deflateParams OF((z_streamp strm,\n                                      int level,\n                                      int strategy));\n/*\n     Dynamically update the compression level and compression strategy.  The\n   interpretation of level and strategy is as in deflateInit2.  This can be\n   used to switch between compression and straight copy of the input data, or\n   to switch to a different kind of input data requiring a different strategy.\n   If the compression level is changed, the input available so far is\n   compressed with the old level (and may be flushed); the new level will take\n   effect only at the next call of deflate().\n\n     Before the call of deflateParams, the stream state must be set as for\n   a call of deflate(), since the currently available input may have to be\n   compressed and flushed.  In particular, strm->avail_out must be non-zero.\n\n     deflateParams returns Z_OK if success, Z_STREAM_ERROR if the source\n   stream state was inconsistent or if a parameter was invalid, Z_BUF_ERROR if\n   strm->avail_out was zero.\n*/\n\nZEXTERN int ZEXPORT deflateTune OF((z_streamp strm,\n                                    int good_length,\n                                    int max_lazy,\n                                    int nice_length,\n                                    int max_chain));\n/*\n     Fine tune deflate's internal compression parameters.  This should only be\n   used by someone who understands the algorithm used by zlib's deflate for\n   searching for the best matching string, and even then only by the most\n   fanatic optimizer trying to squeeze out the last compressed bit for their\n   specific input data.  Read the deflate.c source code for the meaning of the\n   max_lazy, good_length, nice_length, and max_chain parameters.\n\n     deflateTune() can be called after deflateInit() or deflateInit2(), and\n   returns Z_OK on success, or Z_STREAM_ERROR for an invalid deflate stream.\n */\n\nZEXTERN uLong ZEXPORT deflateBound OF((z_streamp strm,\n                                       uLong sourceLen));\n/*\n     deflateBound() returns an upper bound on the compressed size after\n   deflation of sourceLen bytes.  It must be called after deflateInit() or\n   deflateInit2(), and after deflateSetHeader(), if used.  This would be used\n   to allocate an output buffer for deflation in a single pass, and so would be\n   called before deflate().  If that first deflate() call is provided the\n   sourceLen input bytes, an output buffer allocated to the size returned by\n   deflateBound(), and the flush value Z_FINISH, then deflate() is guaranteed\n   to return Z_STREAM_END.  Note that it is possible for the compressed size to\n   be larger than the value returned by deflateBound() if flush options other\n   than Z_FINISH or Z_NO_FLUSH are used.\n*/\n\nZEXTERN int ZEXPORT deflatePending OF((z_streamp strm,\n                                       unsigned *pending,\n                                       int *bits));\n/*\n     deflatePending() returns the number of bytes and bits of output that have\n   been generated, but not yet provided in the available output.  The bytes not\n   provided would be due to the available output space having being consumed.\n   The number of bits of output not provided are between 0 and 7, where they\n   await more bits to join them in order to fill out a full byte.  If pending\n   or bits are Z_NULL, then those values are not set.\n\n     deflatePending returns Z_OK if success, or Z_STREAM_ERROR if the source\n   stream state was inconsistent.\n */\n\nZEXTERN int ZEXPORT deflatePrime OF((z_streamp strm,\n                                     int bits,\n                                     int value));\n/*\n     deflatePrime() inserts bits in the deflate output stream.  The intent\n   is that this function is used to start off the deflate output with the bits\n   leftover from a previous deflate stream when appending to it.  As such, this\n   function can only be used for raw deflate, and must be used before the first\n   deflate() call after a deflateInit2() or deflateReset().  bits must be less\n   than or equal to 16, and that many of the least significant bits of value\n   will be inserted in the output.\n\n     deflatePrime returns Z_OK if success, Z_BUF_ERROR if there was not enough\n   room in the internal buffer to insert the bits, or Z_STREAM_ERROR if the\n   source stream state was inconsistent.\n*/\n\nZEXTERN int ZEXPORT deflateSetHeader OF((z_streamp strm,\n                                         gz_headerp head));\n/*\n     deflateSetHeader() provides gzip header information for when a gzip\n   stream is requested by deflateInit2().  deflateSetHeader() may be called\n   after deflateInit2() or deflateReset() and before the first call of\n   deflate().  The text, time, os, extra field, name, and comment information\n   in the provided gz_header structure are written to the gzip header (xflag is\n   ignored -- the extra flags are set according to the compression level).  The\n   caller must assure that, if not Z_NULL, name and comment are terminated with\n   a zero byte, and that if extra is not Z_NULL, that extra_len bytes are\n   available there.  If hcrc is true, a gzip header crc is included.  Note that\n   the current versions of the command-line version of gzip (up through version\n   1.3.x) do not support header crc's, and will report that it is a \"multi-part\n   gzip file\" and give up.\n\n     If deflateSetHeader is not used, the default gzip header has text false,\n   the time set to zero, and os set to 255, with no extra, name, or comment\n   fields.  The gzip header is returned to the default state by deflateReset().\n\n     deflateSetHeader returns Z_OK if success, or Z_STREAM_ERROR if the source\n   stream state was inconsistent.\n*/\n\n/*\nZEXTERN int ZEXPORT inflateInit2 OF((z_streamp strm,\n                                     int  windowBits));\n\n     This is another version of inflateInit with an extra parameter.  The\n   fields next_in, avail_in, zalloc, zfree and opaque must be initialized\n   before by the caller.\n\n     The windowBits parameter is the base two logarithm of the maximum window\n   size (the size of the history buffer).  It should be in the range 8..15 for\n   this version of the library.  The default value is 15 if inflateInit is used\n   instead.  windowBits must be greater than or equal to the windowBits value\n   provided to deflateInit2() while compressing, or it must be equal to 15 if\n   deflateInit2() was not used.  If a compressed stream with a larger window\n   size is given as input, inflate() will return with the error code\n   Z_DATA_ERROR instead of trying to allocate a larger window.\n\n     windowBits can also be zero to request that inflate use the window size in\n   the zlib header of the compressed stream.\n\n     windowBits can also be -8..-15 for raw inflate.  In this case, -windowBits\n   determines the window size.  inflate() will then process raw deflate data,\n   not looking for a zlib or gzip header, not generating a check value, and not\n   looking for any check values for comparison at the end of the stream.  This\n   is for use with other formats that use the deflate compressed data format\n   such as zip.  Those formats provide their own check values.  If a custom\n   format is developed using the raw deflate format for compressed data, it is\n   recommended that a check value such as an adler32 or a crc32 be applied to\n   the uncompressed data as is done in the zlib, gzip, and zip formats.  For\n   most applications, the zlib format should be used as is.  Note that comments\n   above on the use in deflateInit2() applies to the magnitude of windowBits.\n\n     windowBits can also be greater than 15 for optional gzip decoding.  Add\n   32 to windowBits to enable zlib and gzip decoding with automatic header\n   detection, or add 16 to decode only the gzip format (the zlib format will\n   return a Z_DATA_ERROR).  If a gzip stream is being decoded, strm->adler is a\n   crc32 instead of an adler32.\n\n     inflateInit2 returns Z_OK if success, Z_MEM_ERROR if there was not enough\n   memory, Z_VERSION_ERROR if the zlib library version is incompatible with the\n   version assumed by the caller, or Z_STREAM_ERROR if the parameters are\n   invalid, such as a null pointer to the structure.  msg is set to null if\n   there is no error message.  inflateInit2 does not perform any decompression\n   apart from possibly reading the zlib header if present: actual decompression\n   will be done by inflate().  (So next_in and avail_in may be modified, but\n   next_out and avail_out are unused and unchanged.) The current implementation\n   of inflateInit2() does not process any header information -- that is\n   deferred until inflate() is called.\n*/\n\nZEXTERN int ZEXPORT inflateSetDictionary OF((z_streamp strm,\n                                             const Bytef *dictionary,\n                                             uInt  dictLength));\n/*\n     Initializes the decompression dictionary from the given uncompressed byte\n   sequence.  This function must be called immediately after a call of inflate,\n   if that call returned Z_NEED_DICT.  The dictionary chosen by the compressor\n   can be determined from the adler32 value returned by that call of inflate.\n   The compressor and decompressor must use exactly the same dictionary (see\n   deflateSetDictionary).  For raw inflate, this function can be called at any\n   time to set the dictionary.  If the provided dictionary is smaller than the\n   window and there is already data in the window, then the provided dictionary\n   will amend what's there.  The application must insure that the dictionary\n   that was used for compression is provided.\n\n     inflateSetDictionary returns Z_OK if success, Z_STREAM_ERROR if a\n   parameter is invalid (e.g.  dictionary being Z_NULL) or the stream state is\n   inconsistent, Z_DATA_ERROR if the given dictionary doesn't match the\n   expected one (incorrect adler32 value).  inflateSetDictionary does not\n   perform any decompression: this will be done by subsequent calls of\n   inflate().\n*/\n\nZEXTERN int ZEXPORT inflateGetDictionary OF((z_streamp strm,\n                                             Bytef *dictionary,\n                                             uInt  *dictLength));\n/*\n     Returns the sliding dictionary being maintained by inflate.  dictLength is\n   set to the number of bytes in the dictionary, and that many bytes are copied\n   to dictionary.  dictionary must have enough space, where 32768 bytes is\n   always enough.  If inflateGetDictionary() is called with dictionary equal to\n   Z_NULL, then only the dictionary length is returned, and nothing is copied.\n   Similary, if dictLength is Z_NULL, then it is not set.\n\n     inflateGetDictionary returns Z_OK on success, or Z_STREAM_ERROR if the\n   stream state is inconsistent.\n*/\n\nZEXTERN int ZEXPORT inflateSync OF((z_streamp strm));\n/*\n     Skips invalid compressed data until a possible full flush point (see above\n   for the description of deflate with Z_FULL_FLUSH) can be found, or until all\n   available input is skipped.  No output is provided.\n\n     inflateSync searches for a 00 00 FF FF pattern in the compressed data.\n   All full flush points have this pattern, but not all occurrences of this\n   pattern are full flush points.\n\n     inflateSync returns Z_OK if a possible full flush point has been found,\n   Z_BUF_ERROR if no more input was provided, Z_DATA_ERROR if no flush point\n   has been found, or Z_STREAM_ERROR if the stream structure was inconsistent.\n   In the success case, the application may save the current current value of\n   total_in which indicates where valid compressed data was found.  In the\n   error case, the application may repeatedly call inflateSync, providing more\n   input each time, until success or end of the input data.\n*/\n\nZEXTERN int ZEXPORT inflateCopy OF((z_streamp dest,\n                                    z_streamp source));\n/*\n     Sets the destination stream as a complete copy of the source stream.\n\n     This function can be useful when randomly accessing a large stream.  The\n   first pass through the stream can periodically record the inflate state,\n   allowing restarting inflate at those points when randomly accessing the\n   stream.\n\n     inflateCopy returns Z_OK if success, Z_MEM_ERROR if there was not\n   enough memory, Z_STREAM_ERROR if the source stream state was inconsistent\n   (such as zalloc being Z_NULL).  msg is left unchanged in both source and\n   destination.\n*/\n\nZEXTERN int ZEXPORT inflateReset OF((z_streamp strm));\n/*\n     This function is equivalent to inflateEnd followed by inflateInit,\n   but does not free and reallocate all the internal decompression state.  The\n   stream will keep attributes that may have been set by inflateInit2.\n\n     inflateReset returns Z_OK if success, or Z_STREAM_ERROR if the source\n   stream state was inconsistent (such as zalloc or state being Z_NULL).\n*/\n\nZEXTERN int ZEXPORT inflateReset2 OF((z_streamp strm,\n                                      int windowBits));\n/*\n     This function is the same as inflateReset, but it also permits changing\n   the wrap and window size requests.  The windowBits parameter is interpreted\n   the same as it is for inflateInit2.\n\n     inflateReset2 returns Z_OK if success, or Z_STREAM_ERROR if the source\n   stream state was inconsistent (such as zalloc or state being Z_NULL), or if\n   the windowBits parameter is invalid.\n*/\n\nZEXTERN int ZEXPORT inflatePrime OF((z_streamp strm,\n                                     int bits,\n                                     int value));\n/*\n     This function inserts bits in the inflate input stream.  The intent is\n   that this function is used to start inflating at a bit position in the\n   middle of a byte.  The provided bits will be used before any bytes are used\n   from next_in.  This function should only be used with raw inflate, and\n   should be used before the first inflate() call after inflateInit2() or\n   inflateReset().  bits must be less than or equal to 16, and that many of the\n   least significant bits of value will be inserted in the input.\n\n     If bits is negative, then the input stream bit buffer is emptied.  Then\n   inflatePrime() can be called again to put bits in the buffer.  This is used\n   to clear out bits leftover after feeding inflate a block description prior\n   to feeding inflate codes.\n\n     inflatePrime returns Z_OK if success, or Z_STREAM_ERROR if the source\n   stream state was inconsistent.\n*/\n\nZEXTERN long ZEXPORT inflateMark OF((z_streamp strm));\n/*\n     This function returns two values, one in the lower 16 bits of the return\n   value, and the other in the remaining upper bits, obtained by shifting the\n   return value down 16 bits.  If the upper value is -1 and the lower value is\n   zero, then inflate() is currently decoding information outside of a block.\n   If the upper value is -1 and the lower value is non-zero, then inflate is in\n   the middle of a stored block, with the lower value equaling the number of\n   bytes from the input remaining to copy.  If the upper value is not -1, then\n   it is the number of bits back from the current bit position in the input of\n   the code (literal or length/distance pair) currently being processed.  In\n   that case the lower value is the number of bytes already emitted for that\n   code.\n\n     A code is being processed if inflate is waiting for more input to complete\n   decoding of the code, or if it has completed decoding but is waiting for\n   more output space to write the literal or match data.\n\n     inflateMark() is used to mark locations in the input data for random\n   access, which may be at bit positions, and to note those cases where the\n   output of a code may span boundaries of random access blocks.  The current\n   location in the input stream can be determined from avail_in and data_type\n   as noted in the description for the Z_BLOCK flush parameter for inflate.\n\n     inflateMark returns the value noted above or -1 << 16 if the provided\n   source stream state was inconsistent.\n*/\n\nZEXTERN int ZEXPORT inflateGetHeader OF((z_streamp strm,\n                                         gz_headerp head));\n/*\n     inflateGetHeader() requests that gzip header information be stored in the\n   provided gz_header structure.  inflateGetHeader() may be called after\n   inflateInit2() or inflateReset(), and before the first call of inflate().\n   As inflate() processes the gzip stream, head->done is zero until the header\n   is completed, at which time head->done is set to one.  If a zlib stream is\n   being decoded, then head->done is set to -1 to indicate that there will be\n   no gzip header information forthcoming.  Note that Z_BLOCK or Z_TREES can be\n   used to force inflate() to return immediately after header processing is\n   complete and before any actual data is decompressed.\n\n     The text, time, xflags, and os fields are filled in with the gzip header\n   contents.  hcrc is set to true if there is a header CRC.  (The header CRC\n   was valid if done is set to one.) If extra is not Z_NULL, then extra_max\n   contains the maximum number of bytes to write to extra.  Once done is true,\n   extra_len contains the actual extra field length, and extra contains the\n   extra field, or that field truncated if extra_max is less than extra_len.\n   If name is not Z_NULL, then up to name_max characters are written there,\n   terminated with a zero unless the length is greater than name_max.  If\n   comment is not Z_NULL, then up to comm_max characters are written there,\n   terminated with a zero unless the length is greater than comm_max.  When any\n   of extra, name, or comment are not Z_NULL and the respective field is not\n   present in the header, then that field is set to Z_NULL to signal its\n   absence.  This allows the use of deflateSetHeader() with the returned\n   structure to duplicate the header.  However if those fields are set to\n   allocated memory, then the application will need to save those pointers\n   elsewhere so that they can be eventually freed.\n\n     If inflateGetHeader is not used, then the header information is simply\n   discarded.  The header is always checked for validity, including the header\n   CRC if present.  inflateReset() will reset the process to discard the header\n   information.  The application would need to call inflateGetHeader() again to\n   retrieve the header from the next gzip stream.\n\n     inflateGetHeader returns Z_OK if success, or Z_STREAM_ERROR if the source\n   stream state was inconsistent.\n*/\n\n/*\nZEXTERN int ZEXPORT inflateBackInit OF((z_streamp strm, int windowBits,\n                                        unsigned char FAR *window));\n\n     Initialize the internal stream state for decompression using inflateBack()\n   calls.  The fields zalloc, zfree and opaque in strm must be initialized\n   before the call.  If zalloc and zfree are Z_NULL, then the default library-\n   derived memory allocation routines are used.  windowBits is the base two\n   logarithm of the window size, in the range 8..15.  window is a caller\n   supplied buffer of that size.  Except for special applications where it is\n   assured that deflate was used with small window sizes, windowBits must be 15\n   and a 32K byte window must be supplied to be able to decompress general\n   deflate streams.\n\n     See inflateBack() for the usage of these routines.\n\n     inflateBackInit will return Z_OK on success, Z_STREAM_ERROR if any of\n   the parameters are invalid, Z_MEM_ERROR if the internal state could not be\n   allocated, or Z_VERSION_ERROR if the version of the library does not match\n   the version of the header file.\n*/\n\ntypedef unsigned (*in_func) OF((void FAR *,\n                                z_const unsigned char FAR * FAR *));\ntypedef int (*out_func) OF((void FAR *, unsigned char FAR *, unsigned));\n\nZEXTERN int ZEXPORT inflateBack OF((z_streamp strm,\n                                    in_func in, void FAR *in_desc,\n                                    out_func out, void FAR *out_desc));\n/*\n     inflateBack() does a raw inflate with a single call using a call-back\n   interface for input and output.  This is potentially more efficient than\n   inflate() for file i/o applications, in that it avoids copying between the\n   output and the sliding window by simply making the window itself the output\n   buffer.  inflate() can be faster on modern CPUs when used with large\n   buffers.  inflateBack() trusts the application to not change the output\n   buffer passed by the output function, at least until inflateBack() returns.\n\n     inflateBackInit() must be called first to allocate the internal state\n   and to initialize the state with the user-provided window buffer.\n   inflateBack() may then be used multiple times to inflate a complete, raw\n   deflate stream with each call.  inflateBackEnd() is then called to free the\n   allocated state.\n\n     A raw deflate stream is one with no zlib or gzip header or trailer.\n   This routine would normally be used in a utility that reads zip or gzip\n   files and writes out uncompressed files.  The utility would decode the\n   header and process the trailer on its own, hence this routine expects only\n   the raw deflate stream to decompress.  This is different from the normal\n   behavior of inflate(), which expects either a zlib or gzip header and\n   trailer around the deflate stream.\n\n     inflateBack() uses two subroutines supplied by the caller that are then\n   called by inflateBack() for input and output.  inflateBack() calls those\n   routines until it reads a complete deflate stream and writes out all of the\n   uncompressed data, or until it encounters an error.  The function's\n   parameters and return types are defined above in the in_func and out_func\n   typedefs.  inflateBack() will call in(in_desc, &buf) which should return the\n   number of bytes of provided input, and a pointer to that input in buf.  If\n   there is no input available, in() must return zero--buf is ignored in that\n   case--and inflateBack() will return a buffer error.  inflateBack() will call\n   out(out_desc, buf, len) to write the uncompressed data buf[0..len-1].  out()\n   should return zero on success, or non-zero on failure.  If out() returns\n   non-zero, inflateBack() will return with an error.  Neither in() nor out()\n   are permitted to change the contents of the window provided to\n   inflateBackInit(), which is also the buffer that out() uses to write from.\n   The length written by out() will be at most the window size.  Any non-zero\n   amount of input may be provided by in().\n\n     For convenience, inflateBack() can be provided input on the first call by\n   setting strm->next_in and strm->avail_in.  If that input is exhausted, then\n   in() will be called.  Therefore strm->next_in must be initialized before\n   calling inflateBack().  If strm->next_in is Z_NULL, then in() will be called\n   immediately for input.  If strm->next_in is not Z_NULL, then strm->avail_in\n   must also be initialized, and then if strm->avail_in is not zero, input will\n   initially be taken from strm->next_in[0 ..  strm->avail_in - 1].\n\n     The in_desc and out_desc parameters of inflateBack() is passed as the\n   first parameter of in() and out() respectively when they are called.  These\n   descriptors can be optionally used to pass any information that the caller-\n   supplied in() and out() functions need to do their job.\n\n     On return, inflateBack() will set strm->next_in and strm->avail_in to\n   pass back any unused input that was provided by the last in() call.  The\n   return values of inflateBack() can be Z_STREAM_END on success, Z_BUF_ERROR\n   if in() or out() returned an error, Z_DATA_ERROR if there was a format error\n   in the deflate stream (in which case strm->msg is set to indicate the nature\n   of the error), or Z_STREAM_ERROR if the stream was not properly initialized.\n   In the case of Z_BUF_ERROR, an input or output error can be distinguished\n   using strm->next_in which will be Z_NULL only if in() returned an error.  If\n   strm->next_in is not Z_NULL, then the Z_BUF_ERROR was due to out() returning\n   non-zero.  (in() will always be called before out(), so strm->next_in is\n   assured to be defined if out() returns non-zero.) Note that inflateBack()\n   cannot return Z_OK.\n*/\n\nZEXTERN int ZEXPORT inflateBackEnd OF((z_streamp strm));\n/*\n     All memory allocated by inflateBackInit() is freed.\n\n     inflateBackEnd() returns Z_OK on success, or Z_STREAM_ERROR if the stream\n   state was inconsistent.\n*/\n\nZEXTERN uLong ZEXPORT zlibCompileFlags OF((void));\n/* Return flags indicating compile-time options.\n\n    Type sizes, two bits each, 00 = 16 bits, 01 = 32, 10 = 64, 11 = other:\n     1.0: size of uInt\n     3.2: size of uLong\n     5.4: size of voidpf (pointer)\n     7.6: size of z_off_t\n\n    Compiler, assembler, and debug options:\n     8: DEBUG\n     9: ASMV or ASMINF -- use ASM code\n     10: ZLIB_WINAPI -- exported functions use the WINAPI calling convention\n     11: 0 (reserved)\n\n    One-time table building (smaller code, but not thread-safe if true):\n     12: BUILDFIXED -- build static block decoding tables when needed\n     13: DYNAMIC_CRC_TABLE -- build CRC calculation tables when needed\n     14,15: 0 (reserved)\n\n    Library content (indicates missing functionality):\n     16: NO_GZCOMPRESS -- gz* functions cannot compress (to avoid linking\n                          deflate code when not needed)\n     17: NO_GZIP -- deflate can't write gzip streams, and inflate can't detect\n                    and decode gzip streams (to avoid linking crc code)\n     18-19: 0 (reserved)\n\n    Operation variations (changes in library functionality):\n     20: PKZIP_BUG_WORKAROUND -- slightly more permissive inflate\n     21: FASTEST -- deflate algorithm with only one, lowest compression level\n     22,23: 0 (reserved)\n\n    The sprintf variant used by gzprintf (zero is best):\n     24: 0 = vs*, 1 = s* -- 1 means limited to 20 arguments after the format\n     25: 0 = *nprintf, 1 = *printf -- 1 means gzprintf() not secure!\n     26: 0 = returns value, 1 = void -- 1 means inferred string length returned\n\n    Remainder:\n     27-31: 0 (reserved)\n */\n\n#ifndef Z_SOLO\n\n                        /* utility functions */\n\n/*\n     The following utility functions are implemented on top of the basic\n   stream-oriented functions.  To simplify the interface, some default options\n   are assumed (compression level and memory usage, standard memory allocation\n   functions).  The source code of these utility functions can be modified if\n   you need special options.\n*/\n\nZEXTERN int ZEXPORT compress OF((Bytef *dest,   uLongf *destLen,\n                                 const Bytef *source, uLong sourceLen));\n/*\n     Compresses the source buffer into the destination buffer.  sourceLen is\n   the byte length of the source buffer.  Upon entry, destLen is the total size\n   of the destination buffer, which must be at least the value returned by\n   compressBound(sourceLen).  Upon exit, destLen is the actual size of the\n   compressed buffer.\n\n     compress returns Z_OK if success, Z_MEM_ERROR if there was not\n   enough memory, Z_BUF_ERROR if there was not enough room in the output\n   buffer.\n*/\n\nZEXTERN int ZEXPORT compress2 OF((Bytef *dest,   uLongf *destLen,\n                                  const Bytef *source, uLong sourceLen,\n                                  int level));\n/*\n     Compresses the source buffer into the destination buffer.  The level\n   parameter has the same meaning as in deflateInit.  sourceLen is the byte\n   length of the source buffer.  Upon entry, destLen is the total size of the\n   destination buffer, which must be at least the value returned by\n   compressBound(sourceLen).  Upon exit, destLen is the actual size of the\n   compressed buffer.\n\n     compress2 returns Z_OK if success, Z_MEM_ERROR if there was not enough\n   memory, Z_BUF_ERROR if there was not enough room in the output buffer,\n   Z_STREAM_ERROR if the level parameter is invalid.\n*/\n\nZEXTERN uLong ZEXPORT compressBound OF((uLong sourceLen));\n/*\n     compressBound() returns an upper bound on the compressed size after\n   compress() or compress2() on sourceLen bytes.  It would be used before a\n   compress() or compress2() call to allocate the destination buffer.\n*/\n\nZEXTERN int ZEXPORT uncompress OF((Bytef *dest,   uLongf *destLen,\n                                   const Bytef *source, uLong sourceLen));\n/*\n     Decompresses the source buffer into the destination buffer.  sourceLen is\n   the byte length of the source buffer.  Upon entry, destLen is the total size\n   of the destination buffer, which must be large enough to hold the entire\n   uncompressed data.  (The size of the uncompressed data must have been saved\n   previously by the compressor and transmitted to the decompressor by some\n   mechanism outside the scope of this compression library.) Upon exit, destLen\n   is the actual size of the uncompressed buffer.\n\n     uncompress returns Z_OK if success, Z_MEM_ERROR if there was not\n   enough memory, Z_BUF_ERROR if there was not enough room in the output\n   buffer, or Z_DATA_ERROR if the input data was corrupted or incomplete.  In\n   the case where there is not enough room, uncompress() will fill the output\n   buffer with the uncompressed data up to that point.\n*/\n\n                        /* gzip file access functions */\n\n/*\n     This library supports reading and writing files in gzip (.gz) format with\n   an interface similar to that of stdio, using the functions that start with\n   \"gz\".  The gzip format is different from the zlib format.  gzip is a gzip\n   wrapper, documented in RFC 1952, wrapped around a deflate stream.\n*/\n\ntypedef struct gzFile_s *gzFile;    /* semi-opaque gzip file descriptor */\n\n/*\nZEXTERN gzFile ZEXPORT gzopen OF((const char *path, const char *mode));\n\n     Opens a gzip (.gz) file for reading or writing.  The mode parameter is as\n   in fopen (\"rb\" or \"wb\") but can also include a compression level (\"wb9\") or\n   a strategy: 'f' for filtered data as in \"wb6f\", 'h' for Huffman-only\n   compression as in \"wb1h\", 'R' for run-length encoding as in \"wb1R\", or 'F'\n   for fixed code compression as in \"wb9F\".  (See the description of\n   deflateInit2 for more information about the strategy parameter.)  'T' will\n   request transparent writing or appending with no compression and not using\n   the gzip format.\n\n     \"a\" can be used instead of \"w\" to request that the gzip stream that will\n   be written be appended to the file.  \"+\" will result in an error, since\n   reading and writing to the same gzip file is not supported.  The addition of\n   \"x\" when writing will create the file exclusively, which fails if the file\n   already exists.  On systems that support it, the addition of \"e\" when\n   reading or writing will set the flag to close the file on an execve() call.\n\n     These functions, as well as gzip, will read and decode a sequence of gzip\n   streams in a file.  The append function of gzopen() can be used to create\n   such a file.  (Also see gzflush() for another way to do this.)  When\n   appending, gzopen does not test whether the file begins with a gzip stream,\n   nor does it look for the end of the gzip streams to begin appending.  gzopen\n   will simply append a gzip stream to the existing file.\n\n     gzopen can be used to read a file which is not in gzip format; in this\n   case gzread will directly read from the file without decompression.  When\n   reading, this will be detected automatically by looking for the magic two-\n   byte gzip header.\n\n     gzopen returns NULL if the file could not be opened, if there was\n   insufficient memory to allocate the gzFile state, or if an invalid mode was\n   specified (an 'r', 'w', or 'a' was not provided, or '+' was provided).\n   errno can be checked to determine if the reason gzopen failed was that the\n   file could not be opened.\n*/\n\nZEXTERN gzFile ZEXPORT gzdopen OF((int fd, const char *mode));\n/*\n     gzdopen associates a gzFile with the file descriptor fd.  File descriptors\n   are obtained from calls like open, dup, creat, pipe or fileno (if the file\n   has been previously opened with fopen).  The mode parameter is as in gzopen.\n\n     The next call of gzclose on the returned gzFile will also close the file\n   descriptor fd, just like fclose(fdopen(fd, mode)) closes the file descriptor\n   fd.  If you want to keep fd open, use fd = dup(fd_keep); gz = gzdopen(fd,\n   mode);.  The duplicated descriptor should be saved to avoid a leak, since\n   gzdopen does not close fd if it fails.  If you are using fileno() to get the\n   file descriptor from a FILE *, then you will have to use dup() to avoid\n   double-close()ing the file descriptor.  Both gzclose() and fclose() will\n   close the associated file descriptor, so they need to have different file\n   descriptors.\n\n     gzdopen returns NULL if there was insufficient memory to allocate the\n   gzFile state, if an invalid mode was specified (an 'r', 'w', or 'a' was not\n   provided, or '+' was provided), or if fd is -1.  The file descriptor is not\n   used until the next gz* read, write, seek, or close operation, so gzdopen\n   will not detect if fd is invalid (unless fd is -1).\n*/\n\nZEXTERN int ZEXPORT gzbuffer OF((gzFile file, unsigned size));\n/*\n     Set the internal buffer size used by this library's functions.  The\n   default buffer size is 8192 bytes.  This function must be called after\n   gzopen() or gzdopen(), and before any other calls that read or write the\n   file.  The buffer memory allocation is always deferred to the first read or\n   write.  Two buffers are allocated, either both of the specified size when\n   writing, or one of the specified size and the other twice that size when\n   reading.  A larger buffer size of, for example, 64K or 128K bytes will\n   noticeably increase the speed of decompression (reading).\n\n     The new buffer size also affects the maximum length for gzprintf().\n\n     gzbuffer() returns 0 on success, or -1 on failure, such as being called\n   too late.\n*/\n\nZEXTERN int ZEXPORT gzsetparams OF((gzFile file, int level, int strategy));\n/*\n     Dynamically update the compression level or strategy.  See the description\n   of deflateInit2 for the meaning of these parameters.\n\n     gzsetparams returns Z_OK if success, or Z_STREAM_ERROR if the file was not\n   opened for writing.\n*/\n\nZEXTERN int ZEXPORT gzread OF((gzFile file, voidp buf, unsigned len));\n/*\n     Reads the given number of uncompressed bytes from the compressed file.  If\n   the input file is not in gzip format, gzread copies the given number of\n   bytes into the buffer directly from the file.\n\n     After reaching the end of a gzip stream in the input, gzread will continue\n   to read, looking for another gzip stream.  Any number of gzip streams may be\n   concatenated in the input file, and will all be decompressed by gzread().\n   If something other than a gzip stream is encountered after a gzip stream,\n   that remaining trailing garbage is ignored (and no error is returned).\n\n     gzread can be used to read a gzip file that is being concurrently written.\n   Upon reaching the end of the input, gzread will return with the available\n   data.  If the error code returned by gzerror is Z_OK or Z_BUF_ERROR, then\n   gzclearerr can be used to clear the end of file indicator in order to permit\n   gzread to be tried again.  Z_OK indicates that a gzip stream was completed\n   on the last gzread.  Z_BUF_ERROR indicates that the input file ended in the\n   middle of a gzip stream.  Note that gzread does not return -1 in the event\n   of an incomplete gzip stream.  This error is deferred until gzclose(), which\n   will return Z_BUF_ERROR if the last gzread ended in the middle of a gzip\n   stream.  Alternatively, gzerror can be used before gzclose to detect this\n   case.\n\n     gzread returns the number of uncompressed bytes actually read, less than\n   len for end of file, or -1 for error.\n*/\n\nZEXTERN int ZEXPORT gzwrite OF((gzFile file,\n                                voidpc buf, unsigned len));\n/*\n     Writes the given number of uncompressed bytes into the compressed file.\n   gzwrite returns the number of uncompressed bytes written or 0 in case of\n   error.\n*/\n\nZEXTERN int ZEXPORTVA gzprintf Z_ARG((gzFile file, const char *format, ...));\n/*\n     Converts, formats, and writes the arguments to the compressed file under\n   control of the format string, as in fprintf.  gzprintf returns the number of\n   uncompressed bytes actually written, or 0 in case of error.  The number of\n   uncompressed bytes written is limited to 8191, or one less than the buffer\n   size given to gzbuffer().  The caller should assure that this limit is not\n   exceeded.  If it is exceeded, then gzprintf() will return an error (0) with\n   nothing written.  In this case, there may also be a buffer overflow with\n   unpredictable consequences, which is possible only if zlib was compiled with\n   the insecure functions sprintf() or vsprintf() because the secure snprintf()\n   or vsnprintf() functions were not available.  This can be determined using\n   zlibCompileFlags().\n*/\n\nZEXTERN int ZEXPORT gzputs OF((gzFile file, const char *s));\n/*\n     Writes the given null-terminated string to the compressed file, excluding\n   the terminating null character.\n\n     gzputs returns the number of characters written, or -1 in case of error.\n*/\n\nZEXTERN char * ZEXPORT gzgets OF((gzFile file, char *buf, int len));\n/*\n     Reads bytes from the compressed file until len-1 characters are read, or a\n   newline character is read and transferred to buf, or an end-of-file\n   condition is encountered.  If any characters are read or if len == 1, the\n   string is terminated with a null character.  If no characters are read due\n   to an end-of-file or len < 1, then the buffer is left untouched.\n\n     gzgets returns buf which is a null-terminated string, or it returns NULL\n   for end-of-file or in case of error.  If there was an error, the contents at\n   buf are indeterminate.\n*/\n\nZEXTERN int ZEXPORT gzputc OF((gzFile file, int c));\n/*\n     Writes c, converted to an unsigned char, into the compressed file.  gzputc\n   returns the value that was written, or -1 in case of error.\n*/\n\nZEXTERN int ZEXPORT gzgetc OF((gzFile file));\n/*\n     Reads one byte from the compressed file.  gzgetc returns this byte or -1\n   in case of end of file or error.  This is implemented as a macro for speed.\n   As such, it does not do all of the checking the other functions do.  I.e.\n   it does not check to see if file is NULL, nor whether the structure file\n   points to has been clobbered or not.\n*/\n\nZEXTERN int ZEXPORT gzungetc OF((int c, gzFile file));\n/*\n     Push one character back onto the stream to be read as the first character\n   on the next read.  At least one character of push-back is allowed.\n   gzungetc() returns the character pushed, or -1 on failure.  gzungetc() will\n   fail if c is -1, and may fail if a character has been pushed but not read\n   yet.  If gzungetc is used immediately after gzopen or gzdopen, at least the\n   output buffer size of pushed characters is allowed.  (See gzbuffer above.)\n   The pushed character will be discarded if the stream is repositioned with\n   gzseek() or gzrewind().\n*/\n\nZEXTERN int ZEXPORT gzflush OF((gzFile file, int flush));\n/*\n     Flushes all pending output into the compressed file.  The parameter flush\n   is as in the deflate() function.  The return value is the zlib error number\n   (see function gzerror below).  gzflush is only permitted when writing.\n\n     If the flush parameter is Z_FINISH, the remaining data is written and the\n   gzip stream is completed in the output.  If gzwrite() is called again, a new\n   gzip stream will be started in the output.  gzread() is able to read such\n   concatented gzip streams.\n\n     gzflush should be called only when strictly necessary because it will\n   degrade compression if called too often.\n*/\n\n/*\nZEXTERN z_off_t ZEXPORT gzseek OF((gzFile file,\n                                   z_off_t offset, int whence));\n\n     Sets the starting position for the next gzread or gzwrite on the given\n   compressed file.  The offset represents a number of bytes in the\n   uncompressed data stream.  The whence parameter is defined as in lseek(2);\n   the value SEEK_END is not supported.\n\n     If the file is opened for reading, this function is emulated but can be\n   extremely slow.  If the file is opened for writing, only forward seeks are\n   supported; gzseek then compresses a sequence of zeroes up to the new\n   starting position.\n\n     gzseek returns the resulting offset location as measured in bytes from\n   the beginning of the uncompressed stream, or -1 in case of error, in\n   particular if the file is opened for writing and the new starting position\n   would be before the current position.\n*/\n\nZEXTERN int ZEXPORT    gzrewind OF((gzFile file));\n/*\n     Rewinds the given file. This function is supported only for reading.\n\n     gzrewind(file) is equivalent to (int)gzseek(file, 0L, SEEK_SET)\n*/\n\n/*\nZEXTERN z_off_t ZEXPORT    gztell OF((gzFile file));\n\n     Returns the starting position for the next gzread or gzwrite on the given\n   compressed file.  This position represents a number of bytes in the\n   uncompressed data stream, and is zero when starting, even if appending or\n   reading a gzip stream from the middle of a file using gzdopen().\n\n     gztell(file) is equivalent to gzseek(file, 0L, SEEK_CUR)\n*/\n\n/*\nZEXTERN z_off_t ZEXPORT gzoffset OF((gzFile file));\n\n     Returns the current offset in the file being read or written.  This offset\n   includes the count of bytes that precede the gzip stream, for example when\n   appending or when using gzdopen() for reading.  When reading, the offset\n   does not include as yet unused buffered input.  This information can be used\n   for a progress indicator.  On error, gzoffset() returns -1.\n*/\n\nZEXTERN int ZEXPORT gzeof OF((gzFile file));\n/*\n     Returns true (1) if the end-of-file indicator has been set while reading,\n   false (0) otherwise.  Note that the end-of-file indicator is set only if the\n   read tried to go past the end of the input, but came up short.  Therefore,\n   just like feof(), gzeof() may return false even if there is no more data to\n   read, in the event that the last read request was for the exact number of\n   bytes remaining in the input file.  This will happen if the input file size\n   is an exact multiple of the buffer size.\n\n     If gzeof() returns true, then the read functions will return no more data,\n   unless the end-of-file indicator is reset by gzclearerr() and the input file\n   has grown since the previous end of file was detected.\n*/\n\nZEXTERN int ZEXPORT gzdirect OF((gzFile file));\n/*\n     Returns true (1) if file is being copied directly while reading, or false\n   (0) if file is a gzip stream being decompressed.\n\n     If the input file is empty, gzdirect() will return true, since the input\n   does not contain a gzip stream.\n\n     If gzdirect() is used immediately after gzopen() or gzdopen() it will\n   cause buffers to be allocated to allow reading the file to determine if it\n   is a gzip file.  Therefore if gzbuffer() is used, it should be called before\n   gzdirect().\n\n     When writing, gzdirect() returns true (1) if transparent writing was\n   requested (\"wT\" for the gzopen() mode), or false (0) otherwise.  (Note:\n   gzdirect() is not needed when writing.  Transparent writing must be\n   explicitly requested, so the application already knows the answer.  When\n   linking statically, using gzdirect() will include all of the zlib code for\n   gzip file reading and decompression, which may not be desired.)\n*/\n\nZEXTERN int ZEXPORT    gzclose OF((gzFile file));\n/*\n     Flushes all pending output if necessary, closes the compressed file and\n   deallocates the (de)compression state.  Note that once file is closed, you\n   cannot call gzerror with file, since its structures have been deallocated.\n   gzclose must not be called more than once on the same file, just as free\n   must not be called more than once on the same allocation.\n\n     gzclose will return Z_STREAM_ERROR if file is not valid, Z_ERRNO on a\n   file operation error, Z_MEM_ERROR if out of memory, Z_BUF_ERROR if the\n   last read ended in the middle of a gzip stream, or Z_OK on success.\n*/\n\nZEXTERN int ZEXPORT gzclose_r OF((gzFile file));\nZEXTERN int ZEXPORT gzclose_w OF((gzFile file));\n/*\n     Same as gzclose(), but gzclose_r() is only for use when reading, and\n   gzclose_w() is only for use when writing or appending.  The advantage to\n   using these instead of gzclose() is that they avoid linking in zlib\n   compression or decompression code that is not used when only reading or only\n   writing respectively.  If gzclose() is used, then both compression and\n   decompression code will be included the application when linking to a static\n   zlib library.\n*/\n\nZEXTERN const char * ZEXPORT gzerror OF((gzFile file, int *errnum));\n/*\n     Returns the error message for the last error which occurred on the given\n   compressed file.  errnum is set to zlib error number.  If an error occurred\n   in the file system and not in the compression library, errnum is set to\n   Z_ERRNO and the application may consult errno to get the exact error code.\n\n     The application must not modify the returned string.  Future calls to\n   this function may invalidate the previously returned string.  If file is\n   closed, then the string previously returned by gzerror will no longer be\n   available.\n\n     gzerror() should be used to distinguish errors from end-of-file for those\n   functions above that do not distinguish those cases in their return values.\n*/\n\nZEXTERN void ZEXPORT gzclearerr OF((gzFile file));\n/*\n     Clears the error and end-of-file flags for file.  This is analogous to the\n   clearerr() function in stdio.  This is useful for continuing to read a gzip\n   file that is being written concurrently.\n*/\n\n#endif /* !Z_SOLO */\n\n                        /* checksum functions */\n\n/*\n     These functions are not related to compression but are exported\n   anyway because they might be useful in applications using the compression\n   library.\n*/\n\nZEXTERN uLong ZEXPORT adler32 OF((uLong adler, const Bytef *buf, uInt len));\n/*\n     Update a running Adler-32 checksum with the bytes buf[0..len-1] and\n   return the updated checksum.  If buf is Z_NULL, this function returns the\n   required initial value for the checksum.\n\n     An Adler-32 checksum is almost as reliable as a CRC32 but can be computed\n   much faster.\n\n   Usage example:\n\n     uLong adler = adler32(0L, Z_NULL, 0);\n\n     while (read_buffer(buffer, length) != EOF) {\n       adler = adler32(adler, buffer, length);\n     }\n     if (adler != original_adler) error();\n*/\n\n/*\nZEXTERN uLong ZEXPORT adler32_combine OF((uLong adler1, uLong adler2,\n                                          z_off_t len2));\n\n     Combine two Adler-32 checksums into one.  For two sequences of bytes, seq1\n   and seq2 with lengths len1 and len2, Adler-32 checksums were calculated for\n   each, adler1 and adler2.  adler32_combine() returns the Adler-32 checksum of\n   seq1 and seq2 concatenated, requiring only adler1, adler2, and len2.  Note\n   that the z_off_t type (like off_t) is a signed integer.  If len2 is\n   negative, the result has no meaning or utility.\n*/\n\nZEXTERN uLong ZEXPORT crc32   OF((uLong crc, const Bytef *buf, uInt len));\n/*\n     Update a running CRC-32 with the bytes buf[0..len-1] and return the\n   updated CRC-32.  If buf is Z_NULL, this function returns the required\n   initial value for the crc.  Pre- and post-conditioning (one's complement) is\n   performed within this function so it shouldn't be done by the application.\n\n   Usage example:\n\n     uLong crc = crc32(0L, Z_NULL, 0);\n\n     while (read_buffer(buffer, length) != EOF) {\n       crc = crc32(crc, buffer, length);\n     }\n     if (crc != original_crc) error();\n*/\n\n/*\nZEXTERN uLong ZEXPORT crc32_combine OF((uLong crc1, uLong crc2, z_off_t len2));\n\n     Combine two CRC-32 check values into one.  For two sequences of bytes,\n   seq1 and seq2 with lengths len1 and len2, CRC-32 check values were\n   calculated for each, crc1 and crc2.  crc32_combine() returns the CRC-32\n   check value of seq1 and seq2 concatenated, requiring only crc1, crc2, and\n   len2.\n*/\n\n\n                        /* various hacks, don't look :) */\n\n/* deflateInit and inflateInit are macros to allow checking the zlib version\n * and the compiler's view of z_stream:\n */\nZEXTERN int ZEXPORT deflateInit_ OF((z_streamp strm, int level,\n                                     const char *version, int stream_size));\nZEXTERN int ZEXPORT inflateInit_ OF((z_streamp strm,\n                                     const char *version, int stream_size));\nZEXTERN int ZEXPORT deflateInit2_ OF((z_streamp strm, int  level, int  method,\n                                      int windowBits, int memLevel,\n                                      int strategy, const char *version,\n                                      int stream_size));\nZEXTERN int ZEXPORT inflateInit2_ OF((z_streamp strm, int  windowBits,\n                                      const char *version, int stream_size));\nZEXTERN int ZEXPORT inflateBackInit_ OF((z_streamp strm, int windowBits,\n                                         unsigned char FAR *window,\n                                         const char *version,\n                                         int stream_size));\n#define deflateInit(strm, level) \\\n        deflateInit_((strm), (level), ZLIB_VERSION, (int)sizeof(z_stream))\n#define inflateInit(strm) \\\n        inflateInit_((strm), ZLIB_VERSION, (int)sizeof(z_stream))\n#define deflateInit2(strm, level, method, windowBits, memLevel, strategy) \\\n        deflateInit2_((strm),(level),(method),(windowBits),(memLevel),\\\n                      (strategy), ZLIB_VERSION, (int)sizeof(z_stream))\n#define inflateInit2(strm, windowBits) \\\n        inflateInit2_((strm), (windowBits), ZLIB_VERSION, \\\n                      (int)sizeof(z_stream))\n#define inflateBackInit(strm, windowBits, window) \\\n        inflateBackInit_((strm), (windowBits), (window), \\\n                      ZLIB_VERSION, (int)sizeof(z_stream))\n\n#ifndef Z_SOLO\n\n/* gzgetc() macro and its supporting function and exposed data structure.  Note\n * that the real internal state is much larger than the exposed structure.\n * This abbreviated structure exposes just enough for the gzgetc() macro.  The\n * user should not mess with these exposed elements, since their names or\n * behavior could change in the future, perhaps even capriciously.  They can\n * only be used by the gzgetc() macro.  You have been warned.\n */\nstruct gzFile_s {\n    unsigned have;\n    unsigned char *next;\n    z_off64_t pos;\n};\nZEXTERN int ZEXPORT gzgetc_ OF((gzFile file));  /* backward compatibility */\n#ifdef Z_PREFIX_SET\n#  undef z_gzgetc\n#  define z_gzgetc(g) \\\n          ((g)->have ? ((g)->have--, (g)->pos++, *((g)->next)++) : gzgetc(g))\n#else\n#  define gzgetc(g) \\\n          ((g)->have ? ((g)->have--, (g)->pos++, *((g)->next)++) : gzgetc(g))\n#endif\n\n/* provide 64-bit offset functions if _LARGEFILE64_SOURCE defined, and/or\n * change the regular functions to 64 bits if _FILE_OFFSET_BITS is 64 (if\n * both are true, the application gets the *64 functions, and the regular\n * functions are changed to 64 bits) -- in case these are set on systems\n * without large file support, _LFS64_LARGEFILE must also be true\n */\n#ifdef Z_LARGE64\n   ZEXTERN gzFile ZEXPORT gzopen64 OF((const char *, const char *));\n   ZEXTERN z_off64_t ZEXPORT gzseek64 OF((gzFile, z_off64_t, int));\n   ZEXTERN z_off64_t ZEXPORT gztell64 OF((gzFile));\n   ZEXTERN z_off64_t ZEXPORT gzoffset64 OF((gzFile));\n   ZEXTERN uLong ZEXPORT adler32_combine64 OF((uLong, uLong, z_off64_t));\n   ZEXTERN uLong ZEXPORT crc32_combine64 OF((uLong, uLong, z_off64_t));\n#endif\n\n#if !defined(ZLIB_INTERNAL) && defined(Z_WANT64)\n#  ifdef Z_PREFIX_SET\n#    define z_gzopen z_gzopen64\n#    define z_gzseek z_gzseek64\n#    define z_gztell z_gztell64\n#    define z_gzoffset z_gzoffset64\n#    define z_adler32_combine z_adler32_combine64\n#    define z_crc32_combine z_crc32_combine64\n#  else\n#    define gzopen gzopen64\n#    define gzseek gzseek64\n#    define gztell gztell64\n#    define gzoffset gzoffset64\n#    define adler32_combine adler32_combine64\n#    define crc32_combine crc32_combine64\n#  endif\n#  ifndef Z_LARGE64\n     ZEXTERN gzFile ZEXPORT gzopen64 OF((const char *, const char *));\n     ZEXTERN z_off_t ZEXPORT gzseek64 OF((gzFile, z_off_t, int));\n     ZEXTERN z_off_t ZEXPORT gztell64 OF((gzFile));\n     ZEXTERN z_off_t ZEXPORT gzoffset64 OF((gzFile));\n     ZEXTERN uLong ZEXPORT adler32_combine64 OF((uLong, uLong, z_off_t));\n     ZEXTERN uLong ZEXPORT crc32_combine64 OF((uLong, uLong, z_off_t));\n#  endif\n#else\n   ZEXTERN gzFile ZEXPORT gzopen OF((const char *, const char *));\n   ZEXTERN z_off_t ZEXPORT gzseek OF((gzFile, z_off_t, int));\n   ZEXTERN z_off_t ZEXPORT gztell OF((gzFile));\n   ZEXTERN z_off_t ZEXPORT gzoffset OF((gzFile));\n   ZEXTERN uLong ZEXPORT adler32_combine OF((uLong, uLong, z_off_t));\n   ZEXTERN uLong ZEXPORT crc32_combine OF((uLong, uLong, z_off_t));\n#endif\n\n#else /* Z_SOLO */\n\n   ZEXTERN uLong ZEXPORT adler32_combine OF((uLong, uLong, z_off_t));\n   ZEXTERN uLong ZEXPORT crc32_combine OF((uLong, uLong, z_off_t));\n\n#endif /* !Z_SOLO */\n\n/* hack for buggy compilers */\n#if !defined(ZUTIL_H) && !defined(NO_DUMMY_DECL)\n    struct internal_state {int dummy;};\n#endif\n\n/* undocumented functions */\nZEXTERN const char   * ZEXPORT zError           OF((int));\nZEXTERN int            ZEXPORT inflateSyncPoint OF((z_streamp));\nZEXTERN const z_crc_t FAR * ZEXPORT get_crc_table    OF((void));\nZEXTERN int            ZEXPORT inflateUndermine OF((z_streamp, int));\nZEXTERN int            ZEXPORT inflateResetKeep OF((z_streamp));\nZEXTERN int            ZEXPORT deflateResetKeep OF((z_streamp));\n#if defined(_WIN32) && !defined(Z_SOLO)\nZEXTERN gzFile         ZEXPORT gzopen_w OF((const wchar_t *path,\n                                            const char *mode));\n#endif\n#if defined(STDC) || defined(Z_HAVE_STDARG_H)\n#  ifndef Z_SOLO\nZEXTERN int            ZEXPORTVA gzvprintf Z_ARG((gzFile file,\n                                                  const char *format,\n                                                  va_list va));\n#  endif\n#endif\n\n#ifdef __cplusplus\n}\n#endif\n\n#endif /* ZLIB_H */\n"
  },
  {
    "path": "external/zlib/zutil.c",
    "content": "/* zutil.c -- target dependent utility functions for the compression library\n * Copyright (C) 1995-2005, 2010, 2011, 2012 Jean-loup Gailly.\n * For conditions of distribution and use, see copyright notice in zlib.h\n */\n\n/* @(#) $Id$ */\n\n#include \"zutil.h\"\n#ifndef Z_SOLO\n#  include \"gzguts.h\"\n#endif\n\n#ifndef NO_DUMMY_DECL\nstruct internal_state      {int dummy;}; /* for buggy compilers */\n#endif\n\nz_const char * const z_errmsg[10] = {\n\"need dictionary\",     /* Z_NEED_DICT       2  */\n\"stream end\",          /* Z_STREAM_END      1  */\n\"\",                    /* Z_OK              0  */\n\"file error\",          /* Z_ERRNO         (-1) */\n\"stream error\",        /* Z_STREAM_ERROR  (-2) */\n\"data error\",          /* Z_DATA_ERROR    (-3) */\n\"insufficient memory\", /* Z_MEM_ERROR     (-4) */\n\"buffer error\",        /* Z_BUF_ERROR     (-5) */\n\"incompatible version\",/* Z_VERSION_ERROR (-6) */\n\"\"};\n\n\nconst char * ZEXPORT zlibVersion()\n{\n    return ZLIB_VERSION;\n}\n\nuLong ZEXPORT zlibCompileFlags()\n{\n    uLong flags;\n\n    flags = 0;\n    switch ((int)(sizeof(uInt))) {\n    case 2:     break;\n    case 4:     flags += 1;     break;\n    case 8:     flags += 2;     break;\n    default:    flags += 3;\n    }\n    switch ((int)(sizeof(uLong))) {\n    case 2:     break;\n    case 4:     flags += 1 << 2;        break;\n    case 8:     flags += 2 << 2;        break;\n    default:    flags += 3 << 2;\n    }\n    switch ((int)(sizeof(voidpf))) {\n    case 2:     break;\n    case 4:     flags += 1 << 4;        break;\n    case 8:     flags += 2 << 4;        break;\n    default:    flags += 3 << 4;\n    }\n    switch ((int)(sizeof(z_off_t))) {\n    case 2:     break;\n    case 4:     flags += 1 << 6;        break;\n    case 8:     flags += 2 << 6;        break;\n    default:    flags += 3 << 6;\n    }\n#ifdef DEBUG\n    flags += 1 << 8;\n#endif\n#if defined(ASMV) || defined(ASMINF)\n    flags += 1 << 9;\n#endif\n#ifdef ZLIB_WINAPI\n    flags += 1 << 10;\n#endif\n#ifdef BUILDFIXED\n    flags += 1 << 12;\n#endif\n#ifdef DYNAMIC_CRC_TABLE\n    flags += 1 << 13;\n#endif\n#ifdef NO_GZCOMPRESS\n    flags += 1L << 16;\n#endif\n#ifdef NO_GZIP\n    flags += 1L << 17;\n#endif\n#ifdef PKZIP_BUG_WORKAROUND\n    flags += 1L << 20;\n#endif\n#ifdef FASTEST\n    flags += 1L << 21;\n#endif\n#if defined(STDC) || defined(Z_HAVE_STDARG_H)\n#  ifdef NO_vsnprintf\n    flags += 1L << 25;\n#    ifdef HAS_vsprintf_void\n    flags += 1L << 26;\n#    endif\n#  else\n#    ifdef HAS_vsnprintf_void\n    flags += 1L << 26;\n#    endif\n#  endif\n#else\n    flags += 1L << 24;\n#  ifdef NO_snprintf\n    flags += 1L << 25;\n#    ifdef HAS_sprintf_void\n    flags += 1L << 26;\n#    endif\n#  else\n#    ifdef HAS_snprintf_void\n    flags += 1L << 26;\n#    endif\n#  endif\n#endif\n    return flags;\n}\n\n#ifdef DEBUG\n\n#  ifndef verbose\n#    define verbose 0\n#  endif\nint ZLIB_INTERNAL z_verbose = verbose;\n\nvoid ZLIB_INTERNAL z_error (m)\n    char *m;\n{\n    fprintf(stderr, \"%s\\n\", m);\n    exit(1);\n}\n#endif\n\n/* exported to allow conversion of error code to string for compress() and\n * uncompress()\n */\nconst char * ZEXPORT zError(err)\n    int err;\n{\n    return ERR_MSG(err);\n}\n\n#if defined(_WIN32_WCE)\n    /* The Microsoft C Run-Time Library for Windows CE doesn't have\n     * errno.  We define it as a global variable to simplify porting.\n     * Its value is always 0 and should not be used.\n     */\n    int errno = 0;\n#endif\n\n#ifndef HAVE_MEMCPY\n\nvoid ZLIB_INTERNAL zmemcpy(dest, source, len)\n    Bytef* dest;\n    const Bytef* source;\n    uInt  len;\n{\n    if (len == 0) return;\n    do {\n        *dest++ = *source++; /* ??? to be unrolled */\n    } while (--len != 0);\n}\n\nint ZLIB_INTERNAL zmemcmp(s1, s2, len)\n    const Bytef* s1;\n    const Bytef* s2;\n    uInt  len;\n{\n    uInt j;\n\n    for (j = 0; j < len; j++) {\n        if (s1[j] != s2[j]) return 2*(s1[j] > s2[j])-1;\n    }\n    return 0;\n}\n\nvoid ZLIB_INTERNAL zmemzero(dest, len)\n    Bytef* dest;\n    uInt  len;\n{\n    if (len == 0) return;\n    do {\n        *dest++ = 0;  /* ??? to be unrolled */\n    } while (--len != 0);\n}\n#endif\n\n#ifndef Z_SOLO\n\n#ifdef SYS16BIT\n\n#ifdef __TURBOC__\n/* Turbo C in 16-bit mode */\n\n#  define MY_ZCALLOC\n\n/* Turbo C malloc() does not allow dynamic allocation of 64K bytes\n * and farmalloc(64K) returns a pointer with an offset of 8, so we\n * must fix the pointer. Warning: the pointer must be put back to its\n * original form in order to free it, use zcfree().\n */\n\n#define MAX_PTR 10\n/* 10*64K = 640K */\n\nlocal int next_ptr = 0;\n\ntypedef struct ptr_table_s {\n    voidpf org_ptr;\n    voidpf new_ptr;\n} ptr_table;\n\nlocal ptr_table table[MAX_PTR];\n/* This table is used to remember the original form of pointers\n * to large buffers (64K). Such pointers are normalized with a zero offset.\n * Since MSDOS is not a preemptive multitasking OS, this table is not\n * protected from concurrent access. This hack doesn't work anyway on\n * a protected system like OS/2. Use Microsoft C instead.\n */\n\nvoidpf ZLIB_INTERNAL zcalloc (voidpf opaque, unsigned items, unsigned size)\n{\n    voidpf buf = opaque; /* just to make some compilers happy */\n    ulg bsize = (ulg)items*size;\n\n    /* If we allocate less than 65520 bytes, we assume that farmalloc\n     * will return a usable pointer which doesn't have to be normalized.\n     */\n    if (bsize < 65520L) {\n        buf = farmalloc(bsize);\n        if (*(ush*)&buf != 0) return buf;\n    } else {\n        buf = farmalloc(bsize + 16L);\n    }\n    if (buf == NULL || next_ptr >= MAX_PTR) return NULL;\n    table[next_ptr].org_ptr = buf;\n\n    /* Normalize the pointer to seg:0 */\n    *((ush*)&buf+1) += ((ush)((uch*)buf-0) + 15) >> 4;\n    *(ush*)&buf = 0;\n    table[next_ptr++].new_ptr = buf;\n    return buf;\n}\n\nvoid ZLIB_INTERNAL zcfree (voidpf opaque, voidpf ptr)\n{\n    int n;\n    if (*(ush*)&ptr != 0) { /* object < 64K */\n        farfree(ptr);\n        return;\n    }\n    /* Find the original pointer */\n    for (n = 0; n < next_ptr; n++) {\n        if (ptr != table[n].new_ptr) continue;\n\n        farfree(table[n].org_ptr);\n        while (++n < next_ptr) {\n            table[n-1] = table[n];\n        }\n        next_ptr--;\n        return;\n    }\n    ptr = opaque; /* just to make some compilers happy */\n    Assert(0, \"zcfree: ptr not found\");\n}\n\n#endif /* __TURBOC__ */\n\n\n#ifdef M_I86\n/* Microsoft C in 16-bit mode */\n\n#  define MY_ZCALLOC\n\n#if (!defined(_MSC_VER) || (_MSC_VER <= 600))\n#  define _halloc  halloc\n#  define _hfree   hfree\n#endif\n\nvoidpf ZLIB_INTERNAL zcalloc (voidpf opaque, uInt items, uInt size)\n{\n    if (opaque) opaque = 0; /* to make compiler happy */\n    return _halloc((long)items, size);\n}\n\nvoid ZLIB_INTERNAL zcfree (voidpf opaque, voidpf ptr)\n{\n    if (opaque) opaque = 0; /* to make compiler happy */\n    _hfree(ptr);\n}\n\n#endif /* M_I86 */\n\n#endif /* SYS16BIT */\n\n\n#ifndef MY_ZCALLOC /* Any system without a special alloc function */\n\n#ifndef STDC\nextern voidp  malloc OF((uInt size));\nextern voidp  calloc OF((uInt items, uInt size));\nextern void   free   OF((voidpf ptr));\n#endif\n\nvoidpf ZLIB_INTERNAL zcalloc (opaque, items, size)\n    voidpf opaque;\n    unsigned items;\n    unsigned size;\n{\n    if (opaque) items += size - size; /* make compiler happy */\n    return sizeof(uInt) > 2 ? (voidpf)malloc(items * size) :\n                              (voidpf)calloc(items, size);\n}\n\nvoid ZLIB_INTERNAL zcfree (opaque, ptr)\n    voidpf opaque;\n    voidpf ptr;\n{\n    free(ptr);\n    if (opaque) return; /* make compiler happy */\n}\n\n#endif /* MY_ZCALLOC */\n\n#endif /* !Z_SOLO */\n"
  },
  {
    "path": "external/zlib/zutil.h",
    "content": "/* zutil.h -- internal interface and configuration of the compression library\n * Copyright (C) 1995-2013 Jean-loup Gailly.\n * For conditions of distribution and use, see copyright notice in zlib.h\n */\n\n/* WARNING: this file should *not* be used by applications. It is\n   part of the implementation of the compression library and is\n   subject to change. Applications should only use zlib.h.\n */\n\n/* @(#) $Id$ */\n\n#ifndef ZUTIL_H\n#define ZUTIL_H\n\n#ifdef HAVE_HIDDEN\n#  define ZLIB_INTERNAL __attribute__((visibility (\"hidden\")))\n#else\n#  define ZLIB_INTERNAL\n#endif\n\n#include \"zlib.h\"\n\n#if defined(STDC) && !defined(Z_SOLO)\n#  if !(defined(_WIN32_WCE) && defined(_MSC_VER))\n#    include <stddef.h>\n#  endif\n#  include <string.h>\n#  include <stdlib.h>\n#endif\n\n#ifdef Z_SOLO\n   typedef long ptrdiff_t;  /* guess -- will be caught if guess is wrong */\n#endif\n\n#ifndef local\n#  define local static\n#endif\n/* compile with -Dlocal if your debugger can't find static symbols */\n\ntypedef unsigned char  uch;\ntypedef uch FAR uchf;\ntypedef unsigned short ush;\ntypedef ush FAR ushf;\ntypedef unsigned long  ulg;\n\nextern z_const char * const z_errmsg[10]; /* indexed by 2-zlib_error */\n/* (size given to avoid silly warnings with Visual C++) */\n\n#define ERR_MSG(err) z_errmsg[Z_NEED_DICT-(err)]\n\n#define ERR_RETURN(strm,err) \\\n  return (strm->msg = ERR_MSG(err), (err))\n/* To be used only when the state is known to be valid */\n\n        /* common constants */\n\n#ifndef DEF_WBITS\n#  define DEF_WBITS MAX_WBITS\n#endif\n/* default windowBits for decompression. MAX_WBITS is for compression only */\n\n#if MAX_MEM_LEVEL >= 8\n#  define DEF_MEM_LEVEL 8\n#else\n#  define DEF_MEM_LEVEL  MAX_MEM_LEVEL\n#endif\n/* default memLevel */\n\n#define STORED_BLOCK 0\n#define STATIC_TREES 1\n#define DYN_TREES    2\n/* The three kinds of block type */\n\n#define MIN_MATCH  3\n#define MAX_MATCH  258\n/* The minimum and maximum match lengths */\n\n#define PRESET_DICT 0x20 /* preset dictionary flag in zlib header */\n\n        /* target dependencies */\n\n#if defined(MSDOS) || (defined(WINDOWS) && !defined(WIN32))\n#  define OS_CODE  0x00\n#  ifndef Z_SOLO\n#    if defined(__TURBOC__) || defined(__BORLANDC__)\n#      if (__STDC__ == 1) && (defined(__LARGE__) || defined(__COMPACT__))\n         /* Allow compilation with ANSI keywords only enabled */\n         void _Cdecl farfree( void *block );\n         void *_Cdecl farmalloc( unsigned long nbytes );\n#      else\n#        include <alloc.h>\n#      endif\n#    else /* MSC or DJGPP */\n#      include <malloc.h>\n#    endif\n#  endif\n#endif\n\n#ifdef AMIGA\n#  define OS_CODE  0x01\n#endif\n\n#if defined(VAXC) || defined(VMS)\n#  define OS_CODE  0x02\n#  define F_OPEN(name, mode) \\\n     fopen((name), (mode), \"mbc=60\", \"ctx=stm\", \"rfm=fix\", \"mrs=512\")\n#endif\n\n#if defined(ATARI) || defined(atarist)\n#  define OS_CODE  0x05\n#endif\n\n#ifdef OS2\n#  define OS_CODE  0x06\n#  if defined(M_I86) && !defined(Z_SOLO)\n#    include <malloc.h>\n#  endif\n#endif\n\n#if defined(MACOS) || defined(TARGET_OS_MAC)\n#  define OS_CODE  0x07\n#  ifndef Z_SOLO\n#    if defined(__MWERKS__) && __dest_os != __be_os && __dest_os != __win32_os\n#      include <unix.h> /* for fdopen */\n#    else\n#      ifndef fdopen\n#        define fdopen(fd,mode) NULL /* No fdopen() */\n#      endif\n#    endif\n#  endif\n#endif\n\n#ifdef TOPS20\n#  define OS_CODE  0x0a\n#endif\n\n#ifdef WIN32\n#  ifndef __CYGWIN__  /* Cygwin is Unix, not Win32 */\n#    define OS_CODE  0x0b\n#  endif\n#endif\n\n#ifdef __50SERIES /* Prime/PRIMOS */\n#  define OS_CODE  0x0f\n#endif\n\n#if defined(_BEOS_) || defined(RISCOS)\n#  define fdopen(fd,mode) NULL /* No fdopen() */\n#endif\n\n#if (defined(_MSC_VER) && (_MSC_VER > 600)) && !defined __INTERIX\n#  if defined(_WIN32_WCE)\n#    define fdopen(fd,mode) NULL /* No fdopen() */\n#    ifndef _PTRDIFF_T_DEFINED\n       typedef int ptrdiff_t;\n#      define _PTRDIFF_T_DEFINED\n#    endif\n#  else\n#    define fdopen(fd,type)  _fdopen(fd,type)\n#  endif\n#endif\n\n#if defined(__BORLANDC__) && !defined(MSDOS)\n  #pragma warn -8004\n  #pragma warn -8008\n  #pragma warn -8066\n#endif\n\n/* provide prototypes for these when building zlib without LFS */\n#if !defined(_WIN32) && \\\n    (!defined(_LARGEFILE64_SOURCE) || _LFS64_LARGEFILE-0 == 0)\n    ZEXTERN uLong ZEXPORT adler32_combine64 OF((uLong, uLong, z_off_t));\n    ZEXTERN uLong ZEXPORT crc32_combine64 OF((uLong, uLong, z_off_t));\n#endif\n\n        /* common defaults */\n\n#ifndef OS_CODE\n#  define OS_CODE  0x03  /* assume Unix */\n#endif\n\n#ifndef F_OPEN\n#  define F_OPEN(name, mode) fopen((name), (mode))\n#endif\n\n         /* functions */\n\n#if defined(pyr) || defined(Z_SOLO)\n#  define NO_MEMCPY\n#endif\n#if defined(SMALL_MEDIUM) && !defined(_MSC_VER) && !defined(__SC__)\n /* Use our own functions for small and medium model with MSC <= 5.0.\n  * You may have to use the same strategy for Borland C (untested).\n  * The __SC__ check is for Symantec.\n  */\n#  define NO_MEMCPY\n#endif\n#if defined(STDC) && !defined(HAVE_MEMCPY) && !defined(NO_MEMCPY)\n#  define HAVE_MEMCPY\n#endif\n#ifdef HAVE_MEMCPY\n#  ifdef SMALL_MEDIUM /* MSDOS small or medium model */\n#    define zmemcpy _fmemcpy\n#    define zmemcmp _fmemcmp\n#    define zmemzero(dest, len) _fmemset(dest, 0, len)\n#  else\n#    define zmemcpy memcpy\n#    define zmemcmp memcmp\n#    define zmemzero(dest, len) memset(dest, 0, len)\n#  endif\n#else\n   void ZLIB_INTERNAL zmemcpy OF((Bytef* dest, const Bytef* source, uInt len));\n   int ZLIB_INTERNAL zmemcmp OF((const Bytef* s1, const Bytef* s2, uInt len));\n   void ZLIB_INTERNAL zmemzero OF((Bytef* dest, uInt len));\n#endif\n\n/* Diagnostic functions */\n#ifdef DEBUG\n#  include <stdio.h>\n   extern int ZLIB_INTERNAL z_verbose;\n   extern void ZLIB_INTERNAL z_error OF((char *m));\n#  define Assert(cond,msg) {if(!(cond)) z_error(msg);}\n#  define Trace(x) {if (z_verbose>=0) fprintf x ;}\n#  define Tracev(x) {if (z_verbose>0) fprintf x ;}\n#  define Tracevv(x) {if (z_verbose>1) fprintf x ;}\n#  define Tracec(c,x) {if (z_verbose>0 && (c)) fprintf x ;}\n#  define Tracecv(c,x) {if (z_verbose>1 && (c)) fprintf x ;}\n#else\n#  define Assert(cond,msg)\n#  define Trace(x)\n#  define Tracev(x)\n#  define Tracevv(x)\n#  define Tracec(c,x)\n#  define Tracecv(c,x)\n#endif\n\n#ifndef Z_SOLO\n   voidpf ZLIB_INTERNAL zcalloc OF((voidpf opaque, unsigned items,\n                                    unsigned size));\n   void ZLIB_INTERNAL zcfree  OF((voidpf opaque, voidpf ptr));\n#endif\n\n#define ZALLOC(strm, items, size) \\\n           (*((strm)->zalloc))((strm)->opaque, (items), (size))\n#define ZFREE(strm, addr)  (*((strm)->zfree))((strm)->opaque, (voidpf)(addr))\n#define TRY_FREE(s, p) {if (p) ZFREE(s, p);}\n\n/* Reverse the bytes in a 32-bit value */\n#define ZSWAP32(q) ((((q) >> 24) & 0xff) + (((q) >> 8) & 0xff00) + \\\n                    (((q) & 0xff00) << 8) + (((q) & 0xff) << 24))\n\n#endif /* ZUTIL_H */\n"
  },
  {
    "path": "external/zopfli/blocksplitter.c",
    "content": "/*\nCopyright 2011 Google Inc. All Rights Reserved.\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n    http://www.apache.org/licenses/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n\nAuthor: lode.vandevenne@gmail.com (Lode Vandevenne)\nAuthor: jyrki.alakuijala@gmail.com (Jyrki Alakuijala)\n*/\n\n#include \"blocksplitter.h\"\n\n#include <assert.h>\n#include <stdio.h>\n#include <stdlib.h>\n\n#include \"deflate.h\"\n#include \"squeeze.h\"\n#include \"tree.h\"\n#include \"util.h\"\n\n/*\nThe \"f\" for the FindMinimum function below.\ni: the current parameter of f(i)\ncontext: for your implementation\n*/\ntypedef double FindMinimumFun(size_t i, void* context);\n\n/*\nFinds minimum of function f(i) where is is of type size_t, f(i) is of type\ndouble, i is in range start-end (excluding end).\nOutputs the minimum value in *smallest and returns the index of this value.\n*/\nstatic size_t FindMinimum(FindMinimumFun f, void* context,\n                          size_t start, size_t end, double* smallest) {\n  if (end - start < 1024) {\n    double best = ZOPFLI_LARGE_FLOAT;\n    size_t result = start;\n    size_t i;\n    for (i = start; i < end; i++) {\n      double v = f(i, context);\n      if (v < best) {\n        best = v;\n        result = i;\n      }\n    }\n    *smallest = best;\n    return result;\n  } else {\n    /* Try to find minimum faster by recursively checking multiple points. */\n#define NUM 9  /* Good value: 9. */\n    size_t i;\n    size_t p[NUM];\n    double vp[NUM];\n    size_t besti;\n    double best;\n    double lastbest = ZOPFLI_LARGE_FLOAT;\n    size_t pos = start;\n\n    for (;;) {\n      if (end - start <= NUM) break;\n\n      for (i = 0; i < NUM; i++) {\n        p[i] = start + (i + 1) * ((end - start) / (NUM + 1));\n        vp[i] = f(p[i], context);\n      }\n      besti = 0;\n      best = vp[0];\n      for (i = 1; i < NUM; i++) {\n        if (vp[i] < best) {\n          best = vp[i];\n          besti = i;\n        }\n      }\n      if (best > lastbest) break;\n\n      start = besti == 0 ? start : p[besti - 1];\n      end = besti == NUM - 1 ? end : p[besti + 1];\n\n      pos = p[besti];\n      lastbest = best;\n    }\n    *smallest = lastbest;\n    return pos;\n#undef NUM\n  }\n}\n\n/*\nReturns estimated cost of a block in bits.  It includes the size to encode the\ntree and the size to encode all literal, length and distance symbols and their\nextra bits.\n\nlitlens: lz77 lit/lengths\ndists: ll77 distances\nlstart: start of block\nlend: end of block (not inclusive)\n*/\nstatic double EstimateCost(const ZopfliLZ77Store* lz77,\n                           size_t lstart, size_t lend) {\n  return ZopfliCalculateBlockSizeAutoType(lz77, lstart, lend);\n}\n\ntypedef struct SplitCostContext {\n  const ZopfliLZ77Store* lz77;\n  size_t start;\n  size_t end;\n} SplitCostContext;\n\n\n/*\nGets the cost which is the sum of the cost of the left and the right section\nof the data.\ntype: FindMinimumFun\n*/\nstatic double SplitCost(size_t i, void* context) {\n  SplitCostContext* c = (SplitCostContext*)context;\n  return EstimateCost(c->lz77, c->start, i) + EstimateCost(c->lz77, i, c->end);\n}\n\nstatic void AddSorted(size_t value, size_t** out, size_t* outsize) {\n  size_t i;\n  ZOPFLI_APPEND_DATA(value, out, outsize);\n  for (i = 0; i + 1 < *outsize; i++) {\n    if ((*out)[i] > value) {\n      size_t j;\n      for (j = *outsize - 1; j > i; j--) {\n        (*out)[j] = (*out)[j - 1];\n      }\n      (*out)[i] = value;\n      break;\n    }\n  }\n}\n\n/*\nPrints the block split points as decimal and hex values in the terminal.\n*/\nstatic void PrintBlockSplitPoints(const ZopfliLZ77Store* lz77,\n                                  const size_t* lz77splitpoints,\n                                  size_t nlz77points) {\n  size_t* splitpoints = 0;\n  size_t npoints = 0;\n  size_t i;\n  /* The input is given as lz77 indices, but we want to see the uncompressed\n  index values. */\n  size_t pos = 0;\n  if (nlz77points > 0) {\n    for (i = 0; i < lz77->size; i++) {\n      size_t length = lz77->dists[i] == 0 ? 1 : lz77->litlens[i];\n      if (lz77splitpoints[npoints] == i) {\n        ZOPFLI_APPEND_DATA(pos, &splitpoints, &npoints);\n        if (npoints == nlz77points) break;\n      }\n      pos += length;\n    }\n  }\n  assert(npoints == nlz77points);\n\n  fprintf(stderr, \"block split points: \");\n  for (i = 0; i < npoints; i++) {\n    fprintf(stderr, \"%d \", (int)splitpoints[i]);\n  }\n  fprintf(stderr, \"(hex:\");\n  for (i = 0; i < npoints; i++) {\n    fprintf(stderr, \" %x\", (int)splitpoints[i]);\n  }\n  fprintf(stderr, \")\\n\");\n\n  free(splitpoints);\n}\n\n/*\nFinds next block to try to split, the largest of the available ones.\nThe largest is chosen to make sure that if only a limited amount of blocks is\nrequested, their sizes are spread evenly.\nlz77size: the size of the LL77 data, which is the size of the done array here.\ndone: array indicating which blocks starting at that position are no longer\n    splittable (splitting them increases rather than decreases cost).\nsplitpoints: the splitpoints found so far.\nnpoints: the amount of splitpoints found so far.\nlstart: output variable, giving start of block.\nlend: output variable, giving end of block.\nreturns 1 if a block was found, 0 if no block found (all are done).\n*/\nstatic int FindLargestSplittableBlock(\n    size_t lz77size, const unsigned char* done,\n    const size_t* splitpoints, size_t npoints,\n    size_t* lstart, size_t* lend) {\n  size_t longest = 0;\n  int found = 0;\n  size_t i;\n  for (i = 0; i <= npoints; i++) {\n    size_t start = i == 0 ? 0 : splitpoints[i - 1];\n    size_t end = i == npoints ? lz77size - 1 : splitpoints[i];\n    if (!done[start] && end - start > longest) {\n      *lstart = start;\n      *lend = end;\n      found = 1;\n      longest = end - start;\n    }\n  }\n  return found;\n}\n\nvoid ZopfliBlockSplitLZ77(const ZopfliOptions* options,\n                          const ZopfliLZ77Store* lz77, size_t maxblocks,\n                          size_t** splitpoints, size_t* npoints) {\n  size_t lstart, lend;\n  size_t i;\n  size_t llpos = 0;\n  size_t numblocks = 1;\n  unsigned char* done;\n  double splitcost, origcost;\n\n  if (lz77->size < 10) return;  /* This code fails on tiny files. */\n\n  done = (unsigned char*)malloc(lz77->size);\n  if (!done) exit(-1); /* Allocation failed. */\n  for (i = 0; i < lz77->size; i++) done[i] = 0;\n\n  lstart = 0;\n  lend = lz77->size;\n  for (;;) {\n    SplitCostContext c;\n\n    if (maxblocks > 0 && numblocks >= maxblocks) {\n      break;\n    }\n\n    c.lz77 = lz77;\n    c.start = lstart;\n    c.end = lend;\n    assert(lstart < lend);\n    llpos = FindMinimum(SplitCost, &c, lstart + 1, lend, &splitcost);\n\n    assert(llpos > lstart);\n    assert(llpos < lend);\n\n    origcost = EstimateCost(lz77, lstart, lend);\n\n    if (splitcost > origcost || llpos == lstart + 1 || llpos == lend) {\n      done[lstart] = 1;\n    } else {\n      AddSorted(llpos, splitpoints, npoints);\n      numblocks++;\n    }\n\n    if (!FindLargestSplittableBlock(\n        lz77->size, done, *splitpoints, *npoints, &lstart, &lend)) {\n      break;  /* No further split will probably reduce compression. */\n    }\n\n    if (lend - lstart < 10) {\n      break;\n    }\n  }\n\n  if (options->verbose) {\n    PrintBlockSplitPoints(lz77, *splitpoints, *npoints);\n  }\n\n  free(done);\n}\n\nvoid ZopfliBlockSplit(const ZopfliOptions* options,\n                      const unsigned char* in, size_t instart, size_t inend,\n                      size_t maxblocks, size_t** splitpoints, size_t* npoints) {\n  size_t pos = 0;\n  size_t i;\n  ZopfliBlockState s;\n  size_t* lz77splitpoints = 0;\n  size_t nlz77points = 0;\n  ZopfliLZ77Store store;\n  ZopfliHash hash;\n  ZopfliHash* h = &hash;\n\n  ZopfliInitLZ77Store(in, &store);\n  ZopfliInitBlockState(options, instart, inend, 0, &s);\n  ZopfliAllocHash(ZOPFLI_WINDOW_SIZE, h);\n\n  *npoints = 0;\n  *splitpoints = 0;\n\n  /* Unintuitively, Using a simple LZ77 method here instead of ZopfliLZ77Optimal\n  results in better blocks. */\n  ZopfliLZ77Greedy(&s, in, instart, inend, &store, h);\n\n  ZopfliBlockSplitLZ77(options,\n                       &store, maxblocks,\n                       &lz77splitpoints, &nlz77points);\n\n  /* Convert LZ77 positions to positions in the uncompressed input. */\n  pos = instart;\n  if (nlz77points > 0) {\n    for (i = 0; i < store.size; i++) {\n      size_t length = store.dists[i] == 0 ? 1 : store.litlens[i];\n      if (lz77splitpoints[*npoints] == i) {\n        ZOPFLI_APPEND_DATA(pos, splitpoints, npoints);\n        if (*npoints == nlz77points) break;\n      }\n      pos += length;\n    }\n  }\n  assert(*npoints == nlz77points);\n\n  free(lz77splitpoints);\n  ZopfliCleanBlockState(&s);\n  ZopfliCleanLZ77Store(&store);\n  ZopfliCleanHash(h);\n}\n\nvoid ZopfliBlockSplitSimple(const unsigned char* in,\n                            size_t instart, size_t inend,\n                            size_t blocksize,\n                            size_t** splitpoints, size_t* npoints) {\n  size_t i = instart;\n  while (i < inend) {\n    ZOPFLI_APPEND_DATA(i, splitpoints, npoints);\n    i += blocksize;\n  }\n  (void)in;\n}\n"
  },
  {
    "path": "external/zopfli/blocksplitter.h",
    "content": "/*\nCopyright 2011 Google Inc. All Rights Reserved.\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n    http://www.apache.org/licenses/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n\nAuthor: lode.vandevenne@gmail.com (Lode Vandevenne)\nAuthor: jyrki.alakuijala@gmail.com (Jyrki Alakuijala)\n*/\n\n/*\nFunctions to choose good boundaries for block splitting. Deflate allows encoding\nthe data in multiple blocks, with a separate Huffman tree for each block. The\nHuffman tree itself requires some bytes to encode, so by choosing certain\nblocks, you can either hurt, or enhance compression. These functions choose good\nones that enhance it.\n*/\n\n#ifndef ZOPFLI_BLOCKSPLITTER_H_\n#define ZOPFLI_BLOCKSPLITTER_H_\n\n#include <stdlib.h>\n\n#include \"lz77.h\"\n#include \"zopfli.h\"\n\n\n/*\nDoes blocksplitting on LZ77 data.\nThe output splitpoints are indices in the LZ77 data.\nmaxblocks: set a limit to the amount of blocks. Set to 0 to mean no limit.\n*/\nvoid ZopfliBlockSplitLZ77(const ZopfliOptions* options,\n                          const ZopfliLZ77Store* lz77, size_t maxblocks,\n                          size_t** splitpoints, size_t* npoints);\n\n/*\nDoes blocksplitting on uncompressed data.\nThe output splitpoints are indices in the uncompressed bytes.\n\noptions: general program options.\nin: uncompressed input data\ninstart: where to start splitting\ninend: where to end splitting (not inclusive)\nmaxblocks: maximum amount of blocks to split into, or 0 for no limit\nsplitpoints: dynamic array to put the resulting split point coordinates into.\n  The coordinates are indices in the input array.\nnpoints: pointer to amount of splitpoints, for the dynamic array. The amount of\n  blocks is the amount of splitpoitns + 1.\n*/\nvoid ZopfliBlockSplit(const ZopfliOptions* options,\n                      const unsigned char* in, size_t instart, size_t inend,\n                      size_t maxblocks, size_t** splitpoints, size_t* npoints);\n\n/*\nDivides the input into equal blocks, does not even take LZ77 lengths into\naccount.\n*/\nvoid ZopfliBlockSplitSimple(const unsigned char* in,\n                            size_t instart, size_t inend,\n                            size_t blocksize,\n                            size_t** splitpoints, size_t* npoints);\n\n#endif  /* ZOPFLI_BLOCKSPLITTER_H_ */\n"
  },
  {
    "path": "external/zopfli/cache.c",
    "content": "/*\nCopyright 2011 Google Inc. All Rights Reserved.\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n    http://www.apache.org/licenses/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n\nAuthor: lode.vandevenne@gmail.com (Lode Vandevenne)\nAuthor: jyrki.alakuijala@gmail.com (Jyrki Alakuijala)\n*/\n\n#include \"cache.h\"\n\n#include <assert.h>\n#include <stdio.h>\n#include <stdlib.h>\n\n#ifdef ZOPFLI_LONGEST_MATCH_CACHE\n\nvoid ZopfliInitCache(size_t blocksize, ZopfliLongestMatchCache* lmc) {\n  size_t i;\n  lmc->length = (unsigned short*)malloc(sizeof(unsigned short) * blocksize);\n  lmc->dist = (unsigned short*)malloc(sizeof(unsigned short) * blocksize);\n  /* Rather large amount of memory. */\n  lmc->sublen = (unsigned char*)malloc(ZOPFLI_CACHE_LENGTH * 3 * blocksize);\n  if(lmc->sublen == NULL) {\n    fprintf(stderr,\n        \"Error: Out of memory. Tried allocating %lu bytes of memory.\\n\",\n        (unsigned long)ZOPFLI_CACHE_LENGTH * 3 * blocksize);\n    exit (EXIT_FAILURE);\n  }\n\n  /* length > 0 and dist 0 is invalid combination, which indicates on purpose\n  that this cache value is not filled in yet. */\n  for (i = 0; i < blocksize; i++) lmc->length[i] = 1;\n  for (i = 0; i < blocksize; i++) lmc->dist[i] = 0;\n  for (i = 0; i < ZOPFLI_CACHE_LENGTH * blocksize * 3; i++) lmc->sublen[i] = 0;\n}\n\nvoid ZopfliCleanCache(ZopfliLongestMatchCache* lmc) {\n  free(lmc->length);\n  free(lmc->dist);\n  free(lmc->sublen);\n}\n\nvoid ZopfliSublenToCache(const unsigned short* sublen,\n                         size_t pos, size_t length,\n                         ZopfliLongestMatchCache* lmc) {\n  size_t i;\n  size_t j = 0;\n  unsigned bestlength = 0;\n  unsigned char* cache;\n\n#if ZOPFLI_CACHE_LENGTH == 0\n  return;\n#endif\n\n  cache = &lmc->sublen[ZOPFLI_CACHE_LENGTH * pos * 3];\n  if (length < 3) return;\n  for (i = 3; i <= length; i++) {\n    if (i == length || sublen[i] != sublen[i + 1]) {\n      cache[j * 3] = i - 3;\n      cache[j * 3 + 1] = sublen[i] % 256;\n      cache[j * 3 + 2] = (sublen[i] >> 8) % 256;\n      bestlength = i;\n      j++;\n      if (j >= ZOPFLI_CACHE_LENGTH) break;\n    }\n  }\n  if (j < ZOPFLI_CACHE_LENGTH) {\n    assert(bestlength == length);\n    cache[(ZOPFLI_CACHE_LENGTH - 1) * 3] = bestlength - 3;\n  } else {\n    assert(bestlength <= length);\n  }\n  assert(bestlength == ZopfliMaxCachedSublen(lmc, pos, length));\n}\n\nvoid ZopfliCacheToSublen(const ZopfliLongestMatchCache* lmc,\n                         size_t pos, size_t length,\n                         unsigned short* sublen) {\n  size_t i, j;\n  unsigned maxlength = ZopfliMaxCachedSublen(lmc, pos, length);\n  unsigned prevlength = 0;\n  unsigned char* cache;\n#if ZOPFLI_CACHE_LENGTH == 0\n  return;\n#endif\n  if (length < 3) return;\n  cache = &lmc->sublen[ZOPFLI_CACHE_LENGTH * pos * 3];\n  for (j = 0; j < ZOPFLI_CACHE_LENGTH; j++) {\n    unsigned length = cache[j * 3] + 3;\n    unsigned dist = cache[j * 3 + 1] + 256 * cache[j * 3 + 2];\n    for (i = prevlength; i <= length; i++) {\n      sublen[i] = dist;\n    }\n    if (length == maxlength) break;\n    prevlength = length + 1;\n  }\n}\n\n/*\nReturns the length up to which could be stored in the cache.\n*/\nunsigned ZopfliMaxCachedSublen(const ZopfliLongestMatchCache* lmc,\n                               size_t pos, size_t length) {\n  unsigned char* cache;\n#if ZOPFLI_CACHE_LENGTH == 0\n  return 0;\n#endif\n  cache = &lmc->sublen[ZOPFLI_CACHE_LENGTH * pos * 3];\n  (void)length;\n  if (cache[1] == 0 && cache[2] == 0) return 0;  /* No sublen cached. */\n  return cache[(ZOPFLI_CACHE_LENGTH - 1) * 3] + 3;\n}\n\n#endif  /* ZOPFLI_LONGEST_MATCH_CACHE */\n"
  },
  {
    "path": "external/zopfli/cache.h",
    "content": "/*\nCopyright 2011 Google Inc. All Rights Reserved.\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n    http://www.apache.org/licenses/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n\nAuthor: lode.vandevenne@gmail.com (Lode Vandevenne)\nAuthor: jyrki.alakuijala@gmail.com (Jyrki Alakuijala)\n*/\n\n/*\nThe cache that speeds up ZopfliFindLongestMatch of lz77.c.\n*/\n\n#ifndef ZOPFLI_CACHE_H_\n#define ZOPFLI_CACHE_H_\n\n#include \"util.h\"\n\n#ifdef ZOPFLI_LONGEST_MATCH_CACHE\n\n/*\nCache used by ZopfliFindLongestMatch to remember previously found length/dist\nvalues.\nThis is needed because the squeeze runs will ask these values multiple times for\nthe same position.\nUses large amounts of memory, since it has to remember the distance belonging\nto every possible shorter-than-the-best length (the so called \"sublen\" array).\n*/\ntypedef struct ZopfliLongestMatchCache {\n  unsigned short* length;\n  unsigned short* dist;\n  unsigned char* sublen;\n} ZopfliLongestMatchCache;\n\n/* Initializes the ZopfliLongestMatchCache. */\nvoid ZopfliInitCache(size_t blocksize, ZopfliLongestMatchCache* lmc);\n\n/* Frees up the memory of the ZopfliLongestMatchCache. */\nvoid ZopfliCleanCache(ZopfliLongestMatchCache* lmc);\n\n/* Stores sublen array in the cache. */\nvoid ZopfliSublenToCache(const unsigned short* sublen,\n                         size_t pos, size_t length,\n                         ZopfliLongestMatchCache* lmc);\n\n/* Extracts sublen array from the cache. */\nvoid ZopfliCacheToSublen(const ZopfliLongestMatchCache* lmc,\n                         size_t pos, size_t length,\n                         unsigned short* sublen);\n/* Returns the length up to which could be stored in the cache. */\nunsigned ZopfliMaxCachedSublen(const ZopfliLongestMatchCache* lmc,\n                               size_t pos, size_t length);\n\n#endif  /* ZOPFLI_LONGEST_MATCH_CACHE */\n\n#endif  /* ZOPFLI_CACHE_H_ */\n"
  },
  {
    "path": "external/zopfli/deflate.c",
    "content": "/*\nCopyright 2011 Google Inc. All Rights Reserved.\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n    http://www.apache.org/licenses/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n\nAuthor: lode.vandevenne@gmail.com (Lode Vandevenne)\nAuthor: jyrki.alakuijala@gmail.com (Jyrki Alakuijala)\n*/\n\n#include \"deflate.h\"\n\n#include <assert.h>\n#include <stdio.h>\n#include <stdlib.h>\n\n#include \"blocksplitter.h\"\n#include \"squeeze.h\"\n#include \"symbols.h\"\n#include \"tree.h\"\n\n/*\nbp = bitpointer, always in range [0, 7].\nThe outsize is number of necessary bytes to encode the bits.\nGiven the value of bp and the amount of bytes, the amount of bits represented\nis not simply bytesize * 8 + bp because even representing one bit requires a\nwhole byte. It is: (bp == 0) ? (bytesize * 8) : ((bytesize - 1) * 8 + bp)\n*/\nstatic void AddBit(int bit,\n                   unsigned char* bp, unsigned char** out, size_t* outsize) {\n  if (*bp == 0) ZOPFLI_APPEND_DATA(0, out, outsize);\n  (*out)[*outsize - 1] |= bit << *bp;\n  *bp = (*bp + 1) & 7;\n}\n\nstatic void AddBits(unsigned symbol, unsigned length,\n                    unsigned char* bp, unsigned char** out, size_t* outsize) {\n  /* TODO(lode): make more efficient (add more bits at once). */\n  unsigned i;\n  for (i = 0; i < length; i++) {\n    unsigned bit = (symbol >> i) & 1;\n    if (*bp == 0) ZOPFLI_APPEND_DATA(0, out, outsize);\n    (*out)[*outsize - 1] |= bit << *bp;\n    *bp = (*bp + 1) & 7;\n  }\n}\n\n/*\nAdds bits, like AddBits, but the order is inverted. The deflate specification\nuses both orders in one standard.\n*/\nstatic void AddHuffmanBits(unsigned symbol, unsigned length,\n                           unsigned char* bp, unsigned char** out,\n                           size_t* outsize) {\n  /* TODO(lode): make more efficient (add more bits at once). */\n  unsigned i;\n  for (i = 0; i < length; i++) {\n    unsigned bit = (symbol >> (length - i - 1)) & 1;\n    if (*bp == 0) ZOPFLI_APPEND_DATA(0, out, outsize);\n    (*out)[*outsize - 1] |= bit << *bp;\n    *bp = (*bp + 1) & 7;\n  }\n}\n\n/*\nEnsures there are at least 2 distance codes to support buggy decoders.\nZlib 1.2.1 and below have a bug where it fails if there isn't at least 1\ndistance code (with length > 0), even though it's valid according to the\ndeflate spec to have 0 distance codes. On top of that, some mobile phones\nrequire at least two distance codes. To support these decoders too (but\npotentially at the cost of a few bytes), add dummy code lengths of 1.\nReferences to this bug can be found in the changelog of\nZlib 1.2.2 and here: http://www.jonof.id.au/forum/index.php?topic=515.0.\n\nd_lengths: the 32 lengths of the distance codes.\n*/\nstatic void PatchDistanceCodesForBuggyDecoders(unsigned* d_lengths) {\n  int num_dist_codes = 0; /* Amount of non-zero distance codes */\n  int i;\n  for (i = 0; i < 30 /* Ignore the two unused codes from the spec */; i++) {\n    if (d_lengths[i]) num_dist_codes++;\n    if (num_dist_codes >= 2) return; /* Two or more codes is fine. */\n  }\n\n  if (num_dist_codes == 0) {\n    d_lengths[0] = d_lengths[1] = 1;\n  } else if (num_dist_codes == 1) {\n    d_lengths[d_lengths[0] ? 1 : 0] = 1;\n  }\n}\n\n/*\nEncodes the Huffman tree and returns how many bits its encoding takes. If out\nis a null pointer, only returns the size and runs faster.\n*/\nstatic size_t EncodeTree(const unsigned* ll_lengths,\n                         const unsigned* d_lengths,\n                         int use_16, int use_17, int use_18,\n                         unsigned char* bp,\n                         unsigned char** out, size_t* outsize) {\n  unsigned lld_total;  /* Total amount of literal, length, distance codes. */\n  /* Runlength encoded version of lengths of litlen and dist trees. */\n  unsigned* rle = 0;\n  unsigned* rle_bits = 0;  /* Extra bits for rle values 16, 17 and 18. */\n  size_t rle_size = 0;  /* Size of rle array. */\n  size_t rle_bits_size = 0;  /* Should have same value as rle_size. */\n  unsigned hlit = 29;  /* 286 - 257 */\n  unsigned hdist = 29;  /* 32 - 1, but gzip does not like hdist > 29.*/\n  unsigned hclen;\n  unsigned hlit2;\n  size_t i, j;\n  size_t clcounts[19];\n  unsigned clcl[19];  /* Code length code lengths. */\n  unsigned clsymbols[19];\n  /* The order in which code length code lengths are encoded as per deflate. */\n  static const unsigned order[19] = {\n    16, 17, 18, 0, 8, 7, 9, 6, 10, 5, 11, 4, 12, 3, 13, 2, 14, 1, 15\n  };\n  int size_only = !out;\n  size_t result_size = 0;\n\n  for(i = 0; i < 19; i++) clcounts[i] = 0;\n\n  /* Trim zeros. */\n  while (hlit > 0 && ll_lengths[257 + hlit - 1] == 0) hlit--;\n  while (hdist > 0 && d_lengths[1 + hdist - 1] == 0) hdist--;\n  hlit2 = hlit + 257;\n\n  lld_total = hlit2 + hdist + 1;\n\n  for (i = 0; i < lld_total; i++) {\n    /* This is an encoding of a huffman tree, so now the length is a symbol */\n    unsigned char symbol = i < hlit2 ? ll_lengths[i] : d_lengths[i - hlit2];\n    unsigned count = 1;\n    if(use_16 || (symbol == 0 && (use_17 || use_18))) {\n      for (j = i + 1; j < lld_total && symbol ==\n          (j < hlit2 ? ll_lengths[j] : d_lengths[j - hlit2]); j++) {\n        count++;\n      }\n    }\n    i += count - 1;\n\n    /* Repetitions of zeroes */\n    if (symbol == 0 && count >= 3) {\n      if (use_18) {\n        while (count >= 11) {\n          unsigned count2 = count > 138 ? 138 : count;\n          if (!size_only) {\n            ZOPFLI_APPEND_DATA(18, &rle, &rle_size);\n            ZOPFLI_APPEND_DATA(count2 - 11, &rle_bits, &rle_bits_size);\n          }\n          clcounts[18]++;\n          count -= count2;\n        }\n      }\n      if (use_17) {\n        while (count >= 3) {\n          unsigned count2 = count > 10 ? 10 : count;\n          if (!size_only) {\n            ZOPFLI_APPEND_DATA(17, &rle, &rle_size);\n            ZOPFLI_APPEND_DATA(count2 - 3, &rle_bits, &rle_bits_size);\n          }\n          clcounts[17]++;\n          count -= count2;\n        }\n      }\n    }\n\n    /* Repetitions of any symbol */\n    if (use_16 && count >= 4) {\n      count--;  /* Since the first one is hardcoded. */\n      clcounts[symbol]++;\n      if (!size_only) {\n        ZOPFLI_APPEND_DATA(symbol, &rle, &rle_size);\n        ZOPFLI_APPEND_DATA(0, &rle_bits, &rle_bits_size);\n      }\n      while (count >= 3) {\n        unsigned count2 = count > 6 ? 6 : count;\n        if (!size_only) {\n          ZOPFLI_APPEND_DATA(16, &rle, &rle_size);\n          ZOPFLI_APPEND_DATA(count2 - 3, &rle_bits, &rle_bits_size);\n        }\n        clcounts[16]++;\n        count -= count2;\n      }\n    }\n\n    /* No or insufficient repetition */\n    clcounts[symbol] += count;\n    while (count > 0) {\n      if (!size_only) {\n        ZOPFLI_APPEND_DATA(symbol, &rle, &rle_size);\n        ZOPFLI_APPEND_DATA(0, &rle_bits, &rle_bits_size);\n      }\n      count--;\n    }\n  }\n\n  ZopfliCalculateBitLengths(clcounts, 19, 7, clcl);\n  if (!size_only) ZopfliLengthsToSymbols(clcl, 19, 7, clsymbols);\n\n  hclen = 15;\n  /* Trim zeros. */\n  while (hclen > 0 && clcounts[order[hclen + 4 - 1]] == 0) hclen--;\n\n  if (!size_only) {\n    AddBits(hlit, 5, bp, out, outsize);\n    AddBits(hdist, 5, bp, out, outsize);\n    AddBits(hclen, 4, bp, out, outsize);\n\n    for (i = 0; i < hclen + 4; i++) {\n      AddBits(clcl[order[i]], 3, bp, out, outsize);\n    }\n\n    for (i = 0; i < rle_size; i++) {\n      unsigned symbol = clsymbols[rle[i]];\n      AddHuffmanBits(symbol, clcl[rle[i]], bp, out, outsize);\n      /* Extra bits. */\n      if (rle[i] == 16) AddBits(rle_bits[i], 2, bp, out, outsize);\n      else if (rle[i] == 17) AddBits(rle_bits[i], 3, bp, out, outsize);\n      else if (rle[i] == 18) AddBits(rle_bits[i], 7, bp, out, outsize);\n    }\n  }\n\n  result_size += 14;  /* hlit, hdist, hclen bits */\n  result_size += (hclen + 4) * 3;  /* clcl bits */\n  for(i = 0; i < 19; i++) {\n    result_size += clcl[i] * clcounts[i];\n  }\n  /* Extra bits. */\n  result_size += clcounts[16] * 2;\n  result_size += clcounts[17] * 3;\n  result_size += clcounts[18] * 7;\n\n  /* Note: in case of \"size_only\" these are null pointers so no effect. */\n  free(rle);\n  free(rle_bits);\n\n  return result_size;\n}\n\nstatic void AddDynamicTree(const unsigned* ll_lengths,\n                           const unsigned* d_lengths,\n                           unsigned char* bp,\n                           unsigned char** out, size_t* outsize) {\n  int i;\n  int best = 0;\n  size_t bestsize = 0;\n\n  for(i = 0; i < 8; i++) {\n    size_t size = EncodeTree(ll_lengths, d_lengths,\n                             i & 1, i & 2, i & 4,\n                             0, 0, 0);\n    if (bestsize == 0 || size < bestsize) {\n      bestsize = size;\n      best = i;\n    }\n  }\n\n  EncodeTree(ll_lengths, d_lengths,\n             best & 1, best & 2, best & 4,\n             bp, out, outsize);\n}\n\n/*\nGives the exact size of the tree, in bits, as it will be encoded in DEFLATE.\n*/\nstatic size_t CalculateTreeSize(const unsigned* ll_lengths,\n                                const unsigned* d_lengths) {\n  size_t result = 0;\n  int i;\n\n  for(i = 0; i < 8; i++) {\n    size_t size = EncodeTree(ll_lengths, d_lengths,\n                             i & 1, i & 2, i & 4,\n                             0, 0, 0);\n    if (result == 0 || size < result) result = size;\n  }\n\n  return result;\n}\n\n/*\nAdds all lit/len and dist codes from the lists as huffman symbols. Does not add\nend code 256. expected_data_size is the uncompressed block size, used for\nassert, but you can set it to 0 to not do the assertion.\n*/\nstatic void AddLZ77Data(const ZopfliLZ77Store* lz77,\n                        size_t lstart, size_t lend,\n                        size_t expected_data_size,\n                        const unsigned* ll_symbols, const unsigned* ll_lengths,\n                        const unsigned* d_symbols, const unsigned* d_lengths,\n                        unsigned char* bp,\n                        unsigned char** out, size_t* outsize) {\n  size_t testlength = 0;\n  size_t i;\n\n  for (i = lstart; i < lend; i++) {\n    unsigned dist = lz77->dists[i];\n    unsigned litlen = lz77->litlens[i];\n    if (dist == 0) {\n      assert(litlen < 256);\n      assert(ll_lengths[litlen] > 0);\n      AddHuffmanBits(ll_symbols[litlen], ll_lengths[litlen], bp, out, outsize);\n      testlength++;\n    } else {\n      unsigned lls = ZopfliGetLengthSymbol(litlen);\n      unsigned ds = ZopfliGetDistSymbol(dist);\n      assert(litlen >= 3 && litlen <= 288);\n      assert(ll_lengths[lls] > 0);\n      assert(d_lengths[ds] > 0);\n      AddHuffmanBits(ll_symbols[lls], ll_lengths[lls], bp, out, outsize);\n      AddBits(ZopfliGetLengthExtraBitsValue(litlen),\n              ZopfliGetLengthExtraBits(litlen),\n              bp, out, outsize);\n      AddHuffmanBits(d_symbols[ds], d_lengths[ds], bp, out, outsize);\n      AddBits(ZopfliGetDistExtraBitsValue(dist),\n              ZopfliGetDistExtraBits(dist),\n              bp, out, outsize);\n      testlength += litlen;\n    }\n  }\n  assert(expected_data_size == 0 || testlength == expected_data_size);\n}\n\nstatic void GetFixedTree(unsigned* ll_lengths, unsigned* d_lengths) {\n  size_t i;\n  for (i = 0; i < 144; i++) ll_lengths[i] = 8;\n  for (i = 144; i < 256; i++) ll_lengths[i] = 9;\n  for (i = 256; i < 280; i++) ll_lengths[i] = 7;\n  for (i = 280; i < 288; i++) ll_lengths[i] = 8;\n  for (i = 0; i < 32; i++) d_lengths[i] = 5;\n}\n\n/*\nSame as CalculateBlockSymbolSize, but for block size smaller than histogram\nsize.\n*/\nstatic size_t CalculateBlockSymbolSizeSmall(const unsigned* ll_lengths,\n                                            const unsigned* d_lengths,\n                                            const ZopfliLZ77Store* lz77,\n                                            size_t lstart, size_t lend) {\n  size_t result = 0;\n  size_t i;\n  for (i = lstart; i < lend; i++) {\n    assert(i < lz77->size);\n    assert(lz77->litlens[i] < 259);\n    if (lz77->dists[i] == 0) {\n      result += ll_lengths[lz77->litlens[i]];\n    } else {\n      int ll_symbol = ZopfliGetLengthSymbol(lz77->litlens[i]);\n      int d_symbol = ZopfliGetDistSymbol(lz77->dists[i]);\n      result += ll_lengths[ll_symbol];\n      result += d_lengths[d_symbol];\n      result += ZopfliGetLengthSymbolExtraBits(ll_symbol);\n      result += ZopfliGetDistSymbolExtraBits(d_symbol);\n    }\n  }\n  result += ll_lengths[256]; /*end symbol*/\n  return result;\n}\n\n/*\nSame as CalculateBlockSymbolSize, but with the histogram provided by the caller.\n*/\nstatic size_t CalculateBlockSymbolSizeGivenCounts(const size_t* ll_counts,\n                                                  const size_t* d_counts,\n                                                  const unsigned* ll_lengths,\n                                                  const unsigned* d_lengths,\n                                                  const ZopfliLZ77Store* lz77,\n                                                  size_t lstart, size_t lend) {\n  size_t result = 0;\n  size_t i;\n  if (lstart + ZOPFLI_NUM_LL * 3 > lend) {\n    return CalculateBlockSymbolSizeSmall(\n        ll_lengths, d_lengths, lz77, lstart, lend);\n  } else {\n    for (i = 0; i < 256; i++) {\n      result += ll_lengths[i] * ll_counts[i];\n    }\n    for (i = 257; i < 286; i++) {\n      result += ll_lengths[i] * ll_counts[i];\n      result += ZopfliGetLengthSymbolExtraBits(i) * ll_counts[i];\n    }\n    for (i = 0; i < 30; i++) {\n      result += d_lengths[i] * d_counts[i];\n      result += ZopfliGetDistSymbolExtraBits(i) * d_counts[i];\n    }\n    result += ll_lengths[256]; /*end symbol*/\n    return result;\n  }\n}\n\n/*\nCalculates size of the part after the header and tree of an LZ77 block, in bits.\n*/\nstatic size_t CalculateBlockSymbolSize(const unsigned* ll_lengths,\n                                       const unsigned* d_lengths,\n                                       const ZopfliLZ77Store* lz77,\n                                       size_t lstart, size_t lend) {\n  if (lstart + ZOPFLI_NUM_LL * 3 > lend) {\n    return CalculateBlockSymbolSizeSmall(\n        ll_lengths, d_lengths, lz77, lstart, lend);\n  } else {\n    size_t ll_counts[ZOPFLI_NUM_LL];\n    size_t d_counts[ZOPFLI_NUM_D];\n    ZopfliLZ77GetHistogram(lz77, lstart, lend, ll_counts, d_counts);\n    return CalculateBlockSymbolSizeGivenCounts(\n        ll_counts, d_counts, ll_lengths, d_lengths, lz77, lstart, lend);\n  }\n}\n\nstatic size_t AbsDiff(size_t x, size_t y) {\n  if (x > y)\n    return x - y;\n  else\n    return y - x;\n}\n\n/*\nChanges the population counts in a way that the consequent Huffman tree\ncompression, especially its rle-part, will be more likely to compress this data\nmore efficiently. length contains the size of the histogram.\n*/\nvoid OptimizeHuffmanForRle(int length, size_t* counts) {\n  int i, k, stride;\n  size_t symbol, sum, limit;\n  int* good_for_rle;\n\n  /* 1) We don't want to touch the trailing zeros. We may break the\n  rules of the format by adding more data in the distance codes. */\n  for (; length >= 0; --length) {\n    if (length == 0) {\n      return;\n    }\n    if (counts[length - 1] != 0) {\n      /* Now counts[0..length - 1] does not have trailing zeros. */\n      break;\n    }\n  }\n  /* 2) Let's mark all population counts that already can be encoded\n  with an rle code.*/\n  good_for_rle = (int*)malloc((unsigned)length * sizeof(int));\n  for (i = 0; i < length; ++i) good_for_rle[i] = 0;\n\n  /* Let's not spoil any of the existing good rle codes.\n  Mark any seq of 0's that is longer than 5 as a good_for_rle.\n  Mark any seq of non-0's that is longer than 7 as a good_for_rle.*/\n  symbol = counts[0];\n  stride = 0;\n  for (i = 0; i < length + 1; ++i) {\n    if (i == length || counts[i] != symbol) {\n      if ((symbol == 0 && stride >= 5) || (symbol != 0 && stride >= 7)) {\n        for (k = 0; k < stride; ++k) {\n          good_for_rle[i - k - 1] = 1;\n        }\n      }\n      stride = 1;\n      if (i != length) {\n        symbol = counts[i];\n      }\n    } else {\n      ++stride;\n    }\n  }\n\n  /* 3) Let's replace those population counts that lead to more rle codes. */\n  stride = 0;\n  limit = counts[0];\n  sum = 0;\n  for (i = 0; i < length + 1; ++i) {\n    if (i == length || good_for_rle[i]\n        /* Heuristic for selecting the stride ranges to collapse. */\n        || AbsDiff(counts[i], limit) >= 4) {\n      if (stride >= 4 || (stride >= 3 && sum == 0)) {\n        /* The stride must end, collapse what we have, if we have enough (4). */\n        int count = (sum + stride / 2) / stride;\n        if (count < 1) count = 1;\n        if (sum == 0) {\n          /* Don't make an all zeros stride to be upgraded to ones. */\n          count = 0;\n        }\n        for (k = 0; k < stride; ++k) {\n          /* We don't want to change value at counts[i],\n          that is already belonging to the next stride. Thus - 1. */\n          counts[i - k - 1] = count;\n        }\n      }\n      stride = 0;\n      sum = 0;\n      if (i < length - 3) {\n        /* All interesting strides have a count of at least 4,\n        at least when non-zeros. */\n        limit = (counts[i] + counts[i + 1] +\n                 counts[i + 2] + counts[i + 3] + 2) / 4;\n      } else if (i < length) {\n        limit = counts[i];\n      } else {\n        limit = 0;\n      }\n    }\n    ++stride;\n    if (i != length) {\n      sum += counts[i];\n    }\n  }\n\n  free(good_for_rle);\n}\n\n/*\nTries out OptimizeHuffmanForRle for this block, if the result is smaller,\nuses it, otherwise keeps the original. Returns size of encoded tree and data in\nbits, not including the 3-bit block header.\n*/\nstatic double TryOptimizeHuffmanForRle(\n    const ZopfliLZ77Store* lz77, size_t lstart, size_t lend,\n    const size_t* ll_counts, const size_t* d_counts,\n    unsigned* ll_lengths, unsigned* d_lengths) {\n  size_t ll_counts2[ZOPFLI_NUM_LL];\n  size_t d_counts2[ZOPFLI_NUM_D];\n  unsigned ll_lengths2[ZOPFLI_NUM_LL];\n  unsigned d_lengths2[ZOPFLI_NUM_D];\n  double treesize;\n  double datasize;\n  double treesize2;\n  double datasize2;\n\n  treesize = CalculateTreeSize(ll_lengths, d_lengths);\n  datasize = CalculateBlockSymbolSizeGivenCounts(ll_counts, d_counts,\n      ll_lengths, d_lengths, lz77, lstart, lend);\n\n  memcpy(ll_counts2, ll_counts, sizeof(ll_counts2));\n  memcpy(d_counts2, d_counts, sizeof(d_counts2));\n  OptimizeHuffmanForRle(ZOPFLI_NUM_LL, ll_counts2);\n  OptimizeHuffmanForRle(ZOPFLI_NUM_D, d_counts2);\n  ZopfliCalculateBitLengths(ll_counts2, ZOPFLI_NUM_LL, 15, ll_lengths2);\n  ZopfliCalculateBitLengths(d_counts2, ZOPFLI_NUM_D, 15, d_lengths2);\n  PatchDistanceCodesForBuggyDecoders(d_lengths2);\n\n  treesize2 = CalculateTreeSize(ll_lengths2, d_lengths2);\n  datasize2 = CalculateBlockSymbolSizeGivenCounts(ll_counts, d_counts,\n      ll_lengths2, d_lengths2, lz77, lstart, lend);\n\n  if (treesize2 + datasize2 < treesize + datasize) {\n    memcpy(ll_lengths, ll_lengths2, sizeof(ll_lengths2));\n    memcpy(d_lengths, d_lengths2, sizeof(d_lengths2));\n    return treesize2 + datasize2;\n  }\n  return treesize + datasize;\n}\n\n/*\nCalculates the bit lengths for the symbols for dynamic blocks. Chooses bit\nlengths that give the smallest size of tree encoding + encoding of all the\nsymbols to have smallest output size. This are not necessarily the ideal Huffman\nbit lengths. Returns size of encoded tree and data in bits, not including the\n3-bit block header.\n*/\nstatic double GetDynamicLengths(const ZopfliLZ77Store* lz77,\n                                size_t lstart, size_t lend,\n                                unsigned* ll_lengths, unsigned* d_lengths) {\n  size_t ll_counts[ZOPFLI_NUM_LL];\n  size_t d_counts[ZOPFLI_NUM_D];\n\n  ZopfliLZ77GetHistogram(lz77, lstart, lend, ll_counts, d_counts);\n  ll_counts[256] = 1;  /* End symbol. */\n  ZopfliCalculateBitLengths(ll_counts, ZOPFLI_NUM_LL, 15, ll_lengths);\n  ZopfliCalculateBitLengths(d_counts, ZOPFLI_NUM_D, 15, d_lengths);\n  PatchDistanceCodesForBuggyDecoders(d_lengths);\n  return TryOptimizeHuffmanForRle(\n      lz77, lstart, lend, ll_counts, d_counts, ll_lengths, d_lengths);\n}\n\ndouble ZopfliCalculateBlockSize(const ZopfliLZ77Store* lz77,\n                                size_t lstart, size_t lend, int btype) {\n  unsigned ll_lengths[ZOPFLI_NUM_LL];\n  unsigned d_lengths[ZOPFLI_NUM_D];\n\n  double result = 3; /* bfinal and btype bits */\n\n  if (btype == 0) {\n    size_t length = ZopfliLZ77GetByteRange(lz77, lstart, lend);\n    size_t rem = length % 65535;\n    size_t blocks = length / 65535 + (rem ? 1 : 0);\n    /* An uncompressed block must actually be split into multiple blocks if it's\n       larger than 65535 bytes long. Eeach block header is 5 bytes: 3 bits,\n       padding, LEN and NLEN (potential less padding for first one ignored). */\n    return blocks * 5 * 8 + length * 8;\n  } if (btype == 1) {\n    GetFixedTree(ll_lengths, d_lengths);\n    result += CalculateBlockSymbolSize(\n        ll_lengths, d_lengths, lz77, lstart, lend);\n  } else {\n    result += GetDynamicLengths(lz77, lstart, lend, ll_lengths, d_lengths);\n  }\n\n  return result;\n}\n\ndouble ZopfliCalculateBlockSizeAutoType(const ZopfliLZ77Store* lz77,\n                                        size_t lstart, size_t lend) {\n  double uncompressedcost = ZopfliCalculateBlockSize(lz77, lstart, lend, 0);\n  /* Don't do the expensive fixed cost calculation for larger blocks that are\n     unlikely to use it. */\n  double fixedcost = (lz77->size > 1000) ?\n      uncompressedcost : ZopfliCalculateBlockSize(lz77, lstart, lend, 1);\n  double dyncost = ZopfliCalculateBlockSize(lz77, lstart, lend, 2);\n  return (uncompressedcost < fixedcost && uncompressedcost < dyncost)\n      ? uncompressedcost\n      : (fixedcost < dyncost ? fixedcost : dyncost);\n}\n\n/* Since an uncompressed block can be max 65535 in size, it actually adds\nmultible blocks if needed. */\nstatic void AddNonCompressedBlock(const ZopfliOptions* options, int final,\n                                  const unsigned char* in, size_t instart,\n                                  size_t inend,\n                                  unsigned char* bp,\n                                  unsigned char** out, size_t* outsize) {\n  size_t pos = instart;\n  (void)options;\n  for (;;) {\n    size_t i;\n    unsigned short blocksize = 65535;\n    unsigned short nlen;\n    int currentfinal;\n\n    if (pos + blocksize > inend) blocksize = inend - pos;\n    currentfinal = pos + blocksize >= inend;\n\n    nlen = ~blocksize;\n\n    AddBit(final && currentfinal, bp, out, outsize);\n    /* BTYPE 00 */\n    AddBit(0, bp, out, outsize);\n    AddBit(0, bp, out, outsize);\n\n    /* Any bits of input up to the next byte boundary are ignored. */\n    *bp = 0;\n\n    ZOPFLI_APPEND_DATA(blocksize % 256, out, outsize);\n    ZOPFLI_APPEND_DATA((blocksize / 256) % 256, out, outsize);\n    ZOPFLI_APPEND_DATA(nlen % 256, out, outsize);\n    ZOPFLI_APPEND_DATA((nlen / 256) % 256, out, outsize);\n\n    for (i = 0; i < blocksize; i++) {\n      ZOPFLI_APPEND_DATA(in[pos + i], out, outsize);\n    }\n\n    if (currentfinal) break;\n    pos += blocksize;\n  }\n}\n\n/*\nAdds a deflate block with the given LZ77 data to the output.\noptions: global program options\nbtype: the block type, must be 1 or 2\nfinal: whether to set the \"final\" bit on this block, must be the last block\nlitlens: literal/length array of the LZ77 data, in the same format as in\n    ZopfliLZ77Store.\ndists: distance array of the LZ77 data, in the same format as in\n    ZopfliLZ77Store.\nlstart: where to start in the LZ77 data\nlend: where to end in the LZ77 data (not inclusive)\nexpected_data_size: the uncompressed block size, used for assert, but you can\n  set it to 0 to not do the assertion.\nbp: output bit pointer\nout: dynamic output array to append to\noutsize: dynamic output array size\n*/\nstatic void AddLZ77Block(const ZopfliOptions* options, int btype, int final,\n                         const ZopfliLZ77Store* lz77,\n                         size_t lstart, size_t lend,\n                         size_t expected_data_size,\n                         unsigned char* bp,\n                         unsigned char** out, size_t* outsize) {\n  unsigned ll_lengths[ZOPFLI_NUM_LL];\n  unsigned d_lengths[ZOPFLI_NUM_D];\n  unsigned ll_symbols[ZOPFLI_NUM_LL];\n  unsigned d_symbols[ZOPFLI_NUM_D];\n  size_t detect_block_size = *outsize;\n  size_t compressed_size;\n  size_t uncompressed_size = 0;\n  size_t i;\n  if (btype == 0) {\n    size_t length = ZopfliLZ77GetByteRange(lz77, lstart, lend);\n    size_t pos = lstart == lend ? 0 : lz77->pos[lstart];\n    size_t end = pos + length;\n    AddNonCompressedBlock(options, final,\n                          lz77->data, pos, end, bp, out, outsize);\n    return;\n  }\n\n  AddBit(final, bp, out, outsize);\n  AddBit(btype & 1, bp, out, outsize);\n  AddBit((btype & 2) >> 1, bp, out, outsize);\n\n  if (btype == 1) {\n    /* Fixed block. */\n    GetFixedTree(ll_lengths, d_lengths);\n  } else {\n    /* Dynamic block. */\n    unsigned detect_tree_size;\n    assert(btype == 2);\n\n    GetDynamicLengths(lz77, lstart, lend, ll_lengths, d_lengths);\n\n    detect_tree_size = *outsize;\n    AddDynamicTree(ll_lengths, d_lengths, bp, out, outsize);\n    if (options->verbose) {\n      fprintf(stderr, \"treesize: %d\\n\", (int)(*outsize - detect_tree_size));\n    }\n  }\n\n  ZopfliLengthsToSymbols(ll_lengths, ZOPFLI_NUM_LL, 15, ll_symbols);\n  ZopfliLengthsToSymbols(d_lengths, ZOPFLI_NUM_D, 15, d_symbols);\n\n  detect_block_size = *outsize;\n  AddLZ77Data(lz77, lstart, lend, expected_data_size,\n              ll_symbols, ll_lengths, d_symbols, d_lengths,\n              bp, out, outsize);\n  /* End symbol. */\n  AddHuffmanBits(ll_symbols[256], ll_lengths[256], bp, out, outsize);\n\n  for (i = lstart; i < lend; i++) {\n    uncompressed_size += lz77->dists[i] == 0 ? 1 : lz77->litlens[i];\n  }\n  compressed_size = *outsize - detect_block_size;\n  if (options->verbose) {\n    fprintf(stderr, \"compressed block size: %d (%dk) (unc: %d)\\n\",\n           (int)compressed_size, (int)(compressed_size / 1024),\n           (int)(uncompressed_size));\n  }\n}\n\nstatic void AddLZ77BlockAutoType(const ZopfliOptions* options, int final,\n                                 const ZopfliLZ77Store* lz77,\n                                 size_t lstart, size_t lend,\n                                 size_t expected_data_size,\n                                 unsigned char* bp,\n                                 unsigned char** out, size_t* outsize) {\n  double uncompressedcost = ZopfliCalculateBlockSize(lz77, lstart, lend, 0);\n  double fixedcost = ZopfliCalculateBlockSize(lz77, lstart, lend, 1);\n  double dyncost = ZopfliCalculateBlockSize(lz77, lstart, lend, 2);\n\n  /* Whether to perform the expensive calculation of creating an optimal block\n  with fixed huffman tree to check if smaller. Only do this for small blocks or\n  blocks which already are pretty good with fixed huffman tree. */\n  int expensivefixed = (lz77->size < 1000) || fixedcost <= dyncost * 1.1;\n\n  ZopfliLZ77Store fixedstore;\n  if (lstart == lend) {\n    /* Smallest empty block is represented by fixed block */\n    AddBits(final, 1, bp, out, outsize);\n    AddBits(1, 2, bp, out, outsize);  /* btype 01 */\n    AddBits(0, 7, bp, out, outsize);  /* end symbol has code 0000000 */\n    return;\n  }\n  ZopfliInitLZ77Store(lz77->data, &fixedstore);\n  if (expensivefixed) {\n    /* Recalculate the LZ77 with ZopfliLZ77OptimalFixed */\n    size_t instart = lz77->pos[lstart];\n    size_t inend = instart + ZopfliLZ77GetByteRange(lz77, lstart, lend);\n\n    ZopfliBlockState s;\n    ZopfliInitBlockState(options, instart, inend, 1, &s);\n    ZopfliLZ77OptimalFixed(&s, lz77->data, instart, inend, &fixedstore);\n    fixedcost = ZopfliCalculateBlockSize(&fixedstore, 0, fixedstore.size, 1);\n    ZopfliCleanBlockState(&s);\n  }\n\n  if (uncompressedcost < fixedcost && uncompressedcost < dyncost) {\n    AddLZ77Block(options, 0, final, lz77, lstart, lend,\n                 expected_data_size, bp, out, outsize);\n  } else if (fixedcost < dyncost) {\n    if (expensivefixed) {\n      AddLZ77Block(options, 1, final, &fixedstore, 0, fixedstore.size,\n                   expected_data_size, bp, out, outsize);\n    } else {\n      AddLZ77Block(options, 1, final, lz77, lstart, lend,\n                   expected_data_size, bp, out, outsize);\n    }\n  } else {\n    AddLZ77Block(options, 2, final, lz77, lstart, lend,\n                 expected_data_size, bp, out, outsize);\n  }\n\n  ZopfliCleanLZ77Store(&fixedstore);\n}\n\n/*\nDeflate a part, to allow ZopfliDeflate() to use multiple master blocks if\nneeded.\nIt is possible to call this function multiple times in a row, shifting\ninstart and inend to next bytes of the data. If instart is larger than 0, then\nprevious bytes are used as the initial dictionary for LZ77.\nThis function will usually output multiple deflate blocks. If final is 1, then\nthe final bit will be set on the last block.\n*/\nvoid ZopfliDeflatePart(const ZopfliOptions* options, int btype, int final,\n                       const unsigned char* in, size_t instart, size_t inend,\n                       unsigned char* bp, unsigned char** out,\n                       size_t* outsize) {\n  size_t i;\n  /* byte coordinates rather than lz77 index */\n  size_t* splitpoints_uncompressed = 0;\n  size_t npoints = 0;\n  size_t* splitpoints = 0;\n  double totalcost = 0;\n  ZopfliLZ77Store lz77;\n\n  /* If btype=2 is specified, it tries all block types. If a lesser btype is\n  given, then however it forces that one. Neither of the lesser types needs\n  block splitting as they have no dynamic huffman trees. */\n  if (btype == 0) {\n    AddNonCompressedBlock(options, final, in, instart, inend, bp, out, outsize);\n    return;\n  } else if (btype == 1) {\n    ZopfliLZ77Store store;\n    ZopfliBlockState s;\n    ZopfliInitLZ77Store(in, &store);\n    ZopfliInitBlockState(options, instart, inend, 1, &s);\n\n    ZopfliLZ77OptimalFixed(&s, in, instart, inend, &store);\n    AddLZ77Block(options, btype, final, &store, 0, store.size, 0,\n                 bp, out, outsize);\n\n    ZopfliCleanBlockState(&s);\n    ZopfliCleanLZ77Store(&store);\n    return;\n  }\n\n\n  if (options->blocksplitting) {\n    ZopfliBlockSplit(options, in, instart, inend,\n                     options->blocksplittingmax,\n                     &splitpoints_uncompressed, &npoints);\n    splitpoints = (size_t*)malloc(sizeof(*splitpoints) * npoints);\n  }\n\n  ZopfliInitLZ77Store(in, &lz77);\n\n  for (i = 0; i <= npoints; i++) {\n    size_t start = i == 0 ? instart : splitpoints_uncompressed[i - 1];\n    size_t end = i == npoints ? inend : splitpoints_uncompressed[i];\n    ZopfliBlockState s;\n    ZopfliLZ77Store store;\n    ZopfliInitLZ77Store(in, &store);\n    ZopfliInitBlockState(options, start, end, 1, &s);\n    ZopfliLZ77Optimal(&s, in, start, end, options->numiterations, &store);\n    totalcost += ZopfliCalculateBlockSizeAutoType(&store, 0, store.size);\n\n    ZopfliAppendLZ77Store(&store, &lz77);\n    if (i < npoints) splitpoints[i] = lz77.size;\n\n    ZopfliCleanBlockState(&s);\n    ZopfliCleanLZ77Store(&store);\n  }\n\n  /* Second block splitting attempt */\n  if (options->blocksplitting && npoints > 1) {\n    size_t* splitpoints2 = 0;\n    size_t npoints2 = 0;\n    double totalcost2 = 0;\n\n    ZopfliBlockSplitLZ77(options, &lz77,\n                         options->blocksplittingmax, &splitpoints2, &npoints2);\n\n    for (i = 0; i <= npoints2; i++) {\n      size_t start = i == 0 ? 0 : splitpoints2[i - 1];\n      size_t end = i == npoints2 ? lz77.size : splitpoints2[i];\n      totalcost2 += ZopfliCalculateBlockSizeAutoType(&lz77, start, end);\n    }\n\n    if (totalcost2 < totalcost) {\n      free(splitpoints);\n      splitpoints = splitpoints2;\n      npoints = npoints2;\n    } else {\n      free(splitpoints2);\n    }\n  }\n\n  for (i = 0; i <= npoints; i++) {\n    size_t start = i == 0 ? 0 : splitpoints[i - 1];\n    size_t end = i == npoints ? lz77.size : splitpoints[i];\n    AddLZ77BlockAutoType(options, i == npoints && final,\n                         &lz77, start, end, 0,\n                         bp, out, outsize);\n  }\n\n  ZopfliCleanLZ77Store(&lz77);\n  free(splitpoints);\n  free(splitpoints_uncompressed);\n}\n\nvoid ZopfliDeflate(const ZopfliOptions* options, int btype, int final,\n                   const unsigned char* in, size_t insize,\n                   unsigned char* bp, unsigned char** out, size_t* outsize) {\n size_t offset = *outsize;\n#if ZOPFLI_MASTER_BLOCK_SIZE == 0\n  ZopfliDeflatePart(options, btype, final, in, 0, insize, bp, out, outsize);\n#else\n  size_t i = 0;\n  do {\n    int masterfinal = (i + ZOPFLI_MASTER_BLOCK_SIZE >= insize);\n    int final2 = final && masterfinal;\n    size_t size = masterfinal ? insize - i : ZOPFLI_MASTER_BLOCK_SIZE;\n    ZopfliDeflatePart(options, btype, final2,\n                      in, i, i + size, bp, out, outsize);\n    i += size;\n  } while (i < insize);\n#endif\n  if (options->verbose) {\n    fprintf(stderr,\n            \"Original Size: %lu, Deflate: %lu, Compression: %f%% Removed\\n\",\n            (unsigned long)insize, (unsigned long)(*outsize - offset),\n            100.0 * (double)(insize - (*outsize - offset)) / (double)insize);\n  }\n}\n"
  },
  {
    "path": "external/zopfli/deflate.h",
    "content": "/*\nCopyright 2011 Google Inc. All Rights Reserved.\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n    http://www.apache.org/licenses/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n\nAuthor: lode.vandevenne@gmail.com (Lode Vandevenne)\nAuthor: jyrki.alakuijala@gmail.com (Jyrki Alakuijala)\n*/\n\n#ifndef ZOPFLI_DEFLATE_H_\n#define ZOPFLI_DEFLATE_H_\n\n/*\nFunctions to compress according to the DEFLATE specification, using the\n\"squeeze\" LZ77 compression backend.\n*/\n\n#include \"lz77.h\"\n#include \"zopfli.h\"\n\n#ifdef __cplusplus\nextern \"C\" {\n#endif\n\n/*\nCompresses according to the deflate specification and append the compressed\nresult to the output.\nThis function will usually output multiple deflate blocks. If final is 1, then\nthe final bit will be set on the last block.\n\noptions: global program options\nbtype: the deflate block type. Use 2 for best compression.\n  -0: non compressed blocks (00)\n  -1: blocks with fixed tree (01)\n  -2: blocks with dynamic tree (10)\nfinal: whether this is the last section of the input, sets the final bit to the\n  last deflate block.\nin: the input bytes\ninsize: number of input bytes\nbp: bit pointer for the output array. This must initially be 0, and for\n  consecutive calls must be reused (it can have values from 0-7). This is\n  because deflate appends blocks as bit-based data, rather than on byte\n  boundaries.\nout: pointer to the dynamic output array to which the result is appended. Must\n  be freed after use.\noutsize: pointer to the dynamic output array size.\n*/\nvoid ZopfliDeflate(const ZopfliOptions* options, int btype, int final,\n                   const unsigned char* in, size_t insize,\n                   unsigned char* bp, unsigned char** out, size_t* outsize);\n\n/*\nLike ZopfliDeflate, but allows to specify start and end byte with instart and\ninend. Only that part is compressed, but earlier bytes are still used for the\nback window.\n*/\nvoid ZopfliDeflatePart(const ZopfliOptions* options, int btype, int final,\n                       const unsigned char* in, size_t instart, size_t inend,\n                       unsigned char* bp, unsigned char** out,\n                       size_t* outsize);\n\n/*\nCalculates block size in bits.\nlitlens: lz77 lit/lengths\ndists: ll77 distances\nlstart: start of block\nlend: end of block (not inclusive)\n*/\ndouble ZopfliCalculateBlockSize(const ZopfliLZ77Store* lz77,\n                                size_t lstart, size_t lend, int btype);\n\n/*\nCalculates block size in bits, automatically using the best btype.\n*/\ndouble ZopfliCalculateBlockSizeAutoType(const ZopfliLZ77Store* lz77,\n                                        size_t lstart, size_t lend);\n\n#ifdef __cplusplus\n}  // extern \"C\"\n#endif\n\n#endif  /* ZOPFLI_DEFLATE_H_ */\n"
  },
  {
    "path": "external/zopfli/gzip_container.c",
    "content": "/*\nCopyright 2013 Google Inc. All Rights Reserved.\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n    http://www.apache.org/licenses/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n\nAuthor: lode.vandevenne@gmail.com (Lode Vandevenne)\nAuthor: jyrki.alakuijala@gmail.com (Jyrki Alakuijala)\n*/\n\n#include \"gzip_container.h\"\n#include \"util.h\"\n\n#include <stdio.h>\n\n#include \"deflate.h\"\n\n/* CRC polynomial: 0xedb88320 */\nstatic const unsigned long crc32_table[256] = {\n           0u, 1996959894u, 3993919788u, 2567524794u,  124634137u, 1886057615u,\n  3915621685u, 2657392035u,  249268274u, 2044508324u, 3772115230u, 2547177864u,\n   162941995u, 2125561021u, 3887607047u, 2428444049u,  498536548u, 1789927666u,\n  4089016648u, 2227061214u,  450548861u, 1843258603u, 4107580753u, 2211677639u,\n   325883990u, 1684777152u, 4251122042u, 2321926636u,  335633487u, 1661365465u,\n  4195302755u, 2366115317u,  997073096u, 1281953886u, 3579855332u, 2724688242u,\n  1006888145u, 1258607687u, 3524101629u, 2768942443u,  901097722u, 1119000684u,\n  3686517206u, 2898065728u,  853044451u, 1172266101u, 3705015759u, 2882616665u,\n   651767980u, 1373503546u, 3369554304u, 3218104598u,  565507253u, 1454621731u,\n  3485111705u, 3099436303u,  671266974u, 1594198024u, 3322730930u, 2970347812u,\n   795835527u, 1483230225u, 3244367275u, 3060149565u, 1994146192u,   31158534u,\n  2563907772u, 4023717930u, 1907459465u,  112637215u, 2680153253u, 3904427059u,\n  2013776290u,  251722036u, 2517215374u, 3775830040u, 2137656763u,  141376813u,\n  2439277719u, 3865271297u, 1802195444u,  476864866u, 2238001368u, 4066508878u,\n  1812370925u,  453092731u, 2181625025u, 4111451223u, 1706088902u,  314042704u,\n  2344532202u, 4240017532u, 1658658271u,  366619977u, 2362670323u, 4224994405u,\n  1303535960u,  984961486u, 2747007092u, 3569037538u, 1256170817u, 1037604311u,\n  2765210733u, 3554079995u, 1131014506u,  879679996u, 2909243462u, 3663771856u,\n  1141124467u,  855842277u, 2852801631u, 3708648649u, 1342533948u,  654459306u,\n  3188396048u, 3373015174u, 1466479909u,  544179635u, 3110523913u, 3462522015u,\n  1591671054u,  702138776u, 2966460450u, 3352799412u, 1504918807u,  783551873u,\n  3082640443u, 3233442989u, 3988292384u, 2596254646u,   62317068u, 1957810842u,\n  3939845945u, 2647816111u,   81470997u, 1943803523u, 3814918930u, 2489596804u,\n   225274430u, 2053790376u, 3826175755u, 2466906013u,  167816743u, 2097651377u,\n  4027552580u, 2265490386u,  503444072u, 1762050814u, 4150417245u, 2154129355u,\n   426522225u, 1852507879u, 4275313526u, 2312317920u,  282753626u, 1742555852u,\n  4189708143u, 2394877945u,  397917763u, 1622183637u, 3604390888u, 2714866558u,\n   953729732u, 1340076626u, 3518719985u, 2797360999u, 1068828381u, 1219638859u,\n  3624741850u, 2936675148u,  906185462u, 1090812512u, 3747672003u, 2825379669u,\n   829329135u, 1181335161u, 3412177804u, 3160834842u,  628085408u, 1382605366u,\n  3423369109u, 3138078467u,  570562233u, 1426400815u, 3317316542u, 2998733608u,\n   733239954u, 1555261956u, 3268935591u, 3050360625u,  752459403u, 1541320221u,\n  2607071920u, 3965973030u, 1969922972u,   40735498u, 2617837225u, 3943577151u,\n  1913087877u,   83908371u, 2512341634u, 3803740692u, 2075208622u,  213261112u,\n  2463272603u, 3855990285u, 2094854071u,  198958881u, 2262029012u, 4057260610u,\n  1759359992u,  534414190u, 2176718541u, 4139329115u, 1873836001u,  414664567u,\n  2282248934u, 4279200368u, 1711684554u,  285281116u, 2405801727u, 4167216745u,\n  1634467795u,  376229701u, 2685067896u, 3608007406u, 1308918612u,  956543938u,\n  2808555105u, 3495958263u, 1231636301u, 1047427035u, 2932959818u, 3654703836u,\n  1088359270u,  936918000u, 2847714899u, 3736837829u, 1202900863u,  817233897u,\n  3183342108u, 3401237130u, 1404277552u,  615818150u, 3134207493u, 3453421203u,\n  1423857449u,  601450431u, 3009837614u, 3294710456u, 1567103746u,  711928724u,\n  3020668471u, 3272380065u, 1510334235u,  755167117u\n};\n\n/* Returns the CRC32 */\nstatic unsigned long CRC(const unsigned char* data, size_t size) {\n  unsigned long result = 0xffffffffu;\n  for (; size > 0; size--) {\n    result = crc32_table[(result ^ *(data++)) & 0xff] ^ (result >> 8);\n  }\n  return result ^ 0xffffffffu;\n}\n\n/* Compresses the data according to the gzip specification, RFC 1952. */\nvoid ZopfliGzipCompress(const ZopfliOptions* options,\n                        const unsigned char* in, size_t insize,\n                        unsigned char** out, size_t* outsize) {\n  unsigned long crcvalue = CRC(in, insize);\n  unsigned char bp = 0;\n\n  ZOPFLI_APPEND_DATA(31, out, outsize);  /* ID1 */\n  ZOPFLI_APPEND_DATA(139, out, outsize);  /* ID2 */\n  ZOPFLI_APPEND_DATA(8, out, outsize);  /* CM */\n  ZOPFLI_APPEND_DATA(0, out, outsize);  /* FLG */\n  /* MTIME */\n  ZOPFLI_APPEND_DATA(0, out, outsize);\n  ZOPFLI_APPEND_DATA(0, out, outsize);\n  ZOPFLI_APPEND_DATA(0, out, outsize);\n  ZOPFLI_APPEND_DATA(0, out, outsize);\n\n  ZOPFLI_APPEND_DATA(2, out, outsize);  /* XFL, 2 indicates best compression. */\n  ZOPFLI_APPEND_DATA(3, out, outsize);  /* OS follows Unix conventions. */\n\n  ZopfliDeflate(options, 2 /* Dynamic block */, 1,\n                in, insize, &bp, out, outsize);\n\n  /* CRC */\n  ZOPFLI_APPEND_DATA(crcvalue % 256, out, outsize);\n  ZOPFLI_APPEND_DATA((crcvalue >> 8) % 256, out, outsize);\n  ZOPFLI_APPEND_DATA((crcvalue >> 16) % 256, out, outsize);\n  ZOPFLI_APPEND_DATA((crcvalue >> 24) % 256, out, outsize);\n\n  /* ISIZE */\n  ZOPFLI_APPEND_DATA(insize % 256, out, outsize);\n  ZOPFLI_APPEND_DATA((insize >> 8) % 256, out, outsize);\n  ZOPFLI_APPEND_DATA((insize >> 16) % 256, out, outsize);\n  ZOPFLI_APPEND_DATA((insize >> 24) % 256, out, outsize);\n\n  if (options->verbose) {\n    fprintf(stderr,\n            \"Original Size: %d, Gzip: %d, Compression: %f%% Removed\\n\",\n            (int)insize, (int)*outsize,\n            100.0 * (double)(insize - *outsize) / (double)insize);\n  }\n}\n"
  },
  {
    "path": "external/zopfli/gzip_container.h",
    "content": "/*\nCopyright 2013 Google Inc. All Rights Reserved.\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n    http://www.apache.org/licenses/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n\nAuthor: lode.vandevenne@gmail.com (Lode Vandevenne)\nAuthor: jyrki.alakuijala@gmail.com (Jyrki Alakuijala)\n*/\n\n#ifndef ZOPFLI_GZIP_H_\n#define ZOPFLI_GZIP_H_\n\n/*\nFunctions to compress according to the Gzip specification.\n*/\n\n#include \"zopfli.h\"\n\n#ifdef __cplusplus\nextern \"C\" {\n#endif\n\n/*\nCompresses according to the gzip specification and append the compressed\nresult to the output.\n\noptions: global program options\nout: pointer to the dynamic output array to which the result is appended. Must\n  be freed after use.\noutsize: pointer to the dynamic output array size.\n*/\nvoid ZopfliGzipCompress(const ZopfliOptions* options,\n                        const unsigned char* in, size_t insize,\n                        unsigned char** out, size_t* outsize);\n\n#ifdef __cplusplus\n}  // extern \"C\"\n#endif\n\n#endif  /* ZOPFLI_GZIP_H_ */\n"
  },
  {
    "path": "external/zopfli/hash.c",
    "content": "/*\nCopyright 2011 Google Inc. All Rights Reserved.\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n    http://www.apache.org/licenses/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n\nAuthor: lode.vandevenne@gmail.com (Lode Vandevenne)\nAuthor: jyrki.alakuijala@gmail.com (Jyrki Alakuijala)\n*/\n\n#include \"hash.h\"\n\n#include <assert.h>\n#include <stdio.h>\n#include <stdlib.h>\n\n#define HASH_SHIFT 5\n#define HASH_MASK 32767\n\nvoid ZopfliAllocHash(size_t window_size, ZopfliHash* h) {\n  h->head = (int*)malloc(sizeof(*h->head) * 65536);\n  h->prev = (unsigned short*)malloc(sizeof(*h->prev) * window_size);\n  h->hashval = (int*)malloc(sizeof(*h->hashval) * window_size);\n\n#ifdef ZOPFLI_HASH_SAME\n  h->same = (unsigned short*)malloc(sizeof(*h->same) * window_size);\n#endif\n\n#ifdef ZOPFLI_HASH_SAME_HASH\n  h->head2 = (int*)malloc(sizeof(*h->head2) * 65536);\n  h->prev2 = (unsigned short*)malloc(sizeof(*h->prev2) * window_size);\n  h->hashval2 = (int*)malloc(sizeof(*h->hashval2) * window_size);\n#endif\n}\n\nvoid ZopfliResetHash(size_t window_size, ZopfliHash* h) {\n  size_t i;\n\n  h->val = 0;\n  for (i = 0; i < 65536; i++) {\n    h->head[i] = -1;  /* -1 indicates no head so far. */\n  }\n  for (i = 0; i < window_size; i++) {\n    h->prev[i] = i;  /* If prev[j] == j, then prev[j] is uninitialized. */\n    h->hashval[i] = -1;\n  }\n\n#ifdef ZOPFLI_HASH_SAME\n  for (i = 0; i < window_size; i++) {\n    h->same[i] = 0;\n  }\n#endif\n\n#ifdef ZOPFLI_HASH_SAME_HASH\n  h->val2 = 0;\n  for (i = 0; i < 65536; i++) {\n    h->head2[i] = -1;\n  }\n  for (i = 0; i < window_size; i++) {\n    h->prev2[i] = i;\n    h->hashval2[i] = -1;\n  }\n#endif\n}\n\nvoid ZopfliCleanHash(ZopfliHash* h) {\n  free(h->head);\n  free(h->prev);\n  free(h->hashval);\n\n#ifdef ZOPFLI_HASH_SAME_HASH\n  free(h->head2);\n  free(h->prev2);\n  free(h->hashval2);\n#endif\n\n#ifdef ZOPFLI_HASH_SAME\n  free(h->same);\n#endif\n}\n\n/*\nUpdate the sliding hash value with the given byte. All calls to this function\nmust be made on consecutive input characters. Since the hash value exists out\nof multiple input bytes, a few warmups with this function are needed initially.\n*/\nstatic void UpdateHashValue(ZopfliHash* h, unsigned char c) {\n  h->val = (((h->val) << HASH_SHIFT) ^ (c)) & HASH_MASK;\n}\n\nvoid ZopfliUpdateHash(const unsigned char* array, size_t pos, size_t end,\n                ZopfliHash* h) {\n  unsigned short hpos = pos & ZOPFLI_WINDOW_MASK;\n#ifdef ZOPFLI_HASH_SAME\n  size_t amount = 0;\n#endif\n\n  UpdateHashValue(h, pos + ZOPFLI_MIN_MATCH <= end ?\n      array[pos + ZOPFLI_MIN_MATCH - 1] : 0);\n  h->hashval[hpos] = h->val;\n  if (h->head[h->val] != -1 && h->hashval[h->head[h->val]] == h->val) {\n    h->prev[hpos] = h->head[h->val];\n  }\n  else h->prev[hpos] = hpos;\n  h->head[h->val] = hpos;\n\n#ifdef ZOPFLI_HASH_SAME\n  /* Update \"same\". */\n  if (h->same[(pos - 1) & ZOPFLI_WINDOW_MASK] > 1) {\n    amount = h->same[(pos - 1) & ZOPFLI_WINDOW_MASK] - 1;\n  }\n  while (pos + amount + 1 < end &&\n      array[pos] == array[pos + amount + 1] && amount < (unsigned short)(-1)) {\n    amount++;\n  }\n  h->same[hpos] = amount;\n#endif\n\n#ifdef ZOPFLI_HASH_SAME_HASH\n  h->val2 = ((h->same[hpos] - ZOPFLI_MIN_MATCH) & 255) ^ h->val;\n  h->hashval2[hpos] = h->val2;\n  if (h->head2[h->val2] != -1 && h->hashval2[h->head2[h->val2]] == h->val2) {\n    h->prev2[hpos] = h->head2[h->val2];\n  }\n  else h->prev2[hpos] = hpos;\n  h->head2[h->val2] = hpos;\n#endif\n}\n\nvoid ZopfliWarmupHash(const unsigned char* array, size_t pos, size_t end,\n                ZopfliHash* h) {\n  UpdateHashValue(h, array[pos + 0]);\n  if (pos + 1 < end) UpdateHashValue(h, array[pos + 1]);\n}\n"
  },
  {
    "path": "external/zopfli/hash.h",
    "content": "/*\nCopyright 2011 Google Inc. All Rights Reserved.\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n    http://www.apache.org/licenses/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n\nAuthor: lode.vandevenne@gmail.com (Lode Vandevenne)\nAuthor: jyrki.alakuijala@gmail.com (Jyrki Alakuijala)\n*/\n\n/*\nThe hash for ZopfliFindLongestMatch of lz77.c.\n*/\n\n#ifndef ZOPFLI_HASH_H_\n#define ZOPFLI_HASH_H_\n\n#include \"util.h\"\n\ntypedef struct ZopfliHash {\n  int* head;  /* Hash value to index of its most recent occurrence. */\n  unsigned short* prev;  /* Index to index of prev. occurrence of same hash. */\n  int* hashval;  /* Index to hash value at this index. */\n  int val;  /* Current hash value. */\n\n#ifdef ZOPFLI_HASH_SAME_HASH\n  /* Fields with similar purpose as the above hash, but for the second hash with\n  a value that is calculated differently.  */\n  int* head2;  /* Hash value to index of its most recent occurrence. */\n  unsigned short* prev2;  /* Index to index of prev. occurrence of same hash. */\n  int* hashval2;  /* Index to hash value at this index. */\n  int val2;  /* Current hash value. */\n#endif\n\n#ifdef ZOPFLI_HASH_SAME\n  unsigned short* same;  /* Amount of repetitions of same byte after this .*/\n#endif\n} ZopfliHash;\n\n/* Allocates ZopfliHash memory. */\nvoid ZopfliAllocHash(size_t window_size, ZopfliHash* h);\n\n/* Resets all fields of ZopfliHash. */\nvoid ZopfliResetHash(size_t window_size, ZopfliHash* h);\n\n/* Frees ZopfliHash memory. */\nvoid ZopfliCleanHash(ZopfliHash* h);\n\n/*\nUpdates the hash values based on the current position in the array. All calls\nto this must be made for consecutive bytes.\n*/\nvoid ZopfliUpdateHash(const unsigned char* array, size_t pos, size_t end,\n                      ZopfliHash* h);\n\n/*\nPrepopulates hash:\nFills in the initial values in the hash, before ZopfliUpdateHash can be used\ncorrectly.\n*/\nvoid ZopfliWarmupHash(const unsigned char* array, size_t pos, size_t end,\n                      ZopfliHash* h);\n\n#endif  /* ZOPFLI_HASH_H_ */\n"
  },
  {
    "path": "external/zopfli/katajainen.c",
    "content": "/*\nCopyright 2011 Google Inc. All Rights Reserved.\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n    http://www.apache.org/licenses/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n\nAuthor: lode.vandevenne@gmail.com (Lode Vandevenne)\nAuthor: jyrki.alakuijala@gmail.com (Jyrki Alakuijala)\n*/\n\n/*\nBounded package merge algorithm, based on the paper\n\"A Fast and Space-Economical Algorithm for Length-Limited Coding\nJyrki Katajainen, Alistair Moffat, Andrew Turpin\".\n*/\n\n#include \"katajainen.h\"\n#include <assert.h>\n#include <stdlib.h>\n#include <limits.h>\n\ntypedef struct Node Node;\n\n/*\nNodes forming chains. Also used to represent leaves.\n*/\nstruct Node {\n  size_t weight;  /* Total weight (symbol count) of this chain. */\n  Node* tail;  /* Previous node(s) of this chain, or 0 if none. */\n  int count;  /* Leaf symbol index, or number of leaves before this chain. */\n};\n\n/*\nMemory pool for nodes.\n*/\ntypedef struct NodePool {\n  Node* next;  /* Pointer to a free node in the pool. */\n} NodePool;\n\n/*\nInitializes a chain node with the given values and marks it as in use.\n*/\nstatic void InitNode(size_t weight, int count, Node* tail, Node* node) {\n  node->weight = weight;\n  node->count = count;\n  node->tail = tail;\n}\n\n/*\nPerforms a Boundary Package-Merge step. Puts a new chain in the given list. The\nnew chain is, depending on the weights, a leaf or a combination of two chains\nfrom the previous list.\nlists: The lists of chains.\nmaxbits: Number of lists.\nleaves: The leaves, one per symbol.\nnumsymbols: Number of leaves.\npool: the node memory pool.\nindex: The index of the list in which a new chain or leaf is required.\n*/\nstatic void BoundaryPM(Node* (*lists)[2], Node* leaves, int numsymbols,\n                       NodePool* pool, int index) {\n  Node* newchain;\n  Node* oldchain;\n  int lastcount = lists[index][1]->count;  /* Count of last chain of list. */\n\n  if (index == 0 && lastcount >= numsymbols) return;\n\n  newchain = pool->next++;\n  oldchain = lists[index][1];\n\n  /* These are set up before the recursive calls below, so that there is a list\n  pointing to the new node, to let the garbage collection know it's in use. */\n  lists[index][0] = oldchain;\n  lists[index][1] = newchain;\n\n  if (index == 0) {\n    /* New leaf node in list 0. */\n    InitNode(leaves[lastcount].weight, lastcount + 1, 0, newchain);\n  } else {\n    size_t sum = lists[index - 1][0]->weight + lists[index - 1][1]->weight;\n    if (lastcount < numsymbols && sum > leaves[lastcount].weight) {\n      /* New leaf inserted in list, so count is incremented. */\n      InitNode(leaves[lastcount].weight, lastcount + 1, oldchain->tail,\n          newchain);\n    } else {\n      InitNode(sum, lastcount, lists[index - 1][1], newchain);\n      /* Two lookahead chains of previous list used up, create new ones. */\n      BoundaryPM(lists, leaves, numsymbols, pool, index - 1);\n      BoundaryPM(lists, leaves, numsymbols, pool, index - 1);\n    }\n  }\n}\n\nstatic void BoundaryPMFinal(Node* (*lists)[2],\n    Node* leaves, int numsymbols, NodePool* pool, int index) {\n  int lastcount = lists[index][1]->count;  /* Count of last chain of list. */\n\n  size_t sum = lists[index - 1][0]->weight + lists[index - 1][1]->weight;\n\n  if (lastcount < numsymbols && sum > leaves[lastcount].weight) {\n    Node* newchain = pool->next;\n    Node* oldchain = lists[index][1]->tail;\n\n    lists[index][1] = newchain;\n    newchain->count = lastcount + 1;\n    newchain->tail = oldchain;\n  } else {\n    lists[index][1]->tail = lists[index - 1][1];\n  }\n}\n\n/*\nInitializes each list with as lookahead chains the two leaves with lowest\nweights.\n*/\nstatic void InitLists(\n    NodePool* pool, const Node* leaves, int maxbits, Node* (*lists)[2]) {\n  int i;\n  Node* node0 = pool->next++;\n  Node* node1 = pool->next++;\n  InitNode(leaves[0].weight, 1, 0, node0);\n  InitNode(leaves[1].weight, 2, 0, node1);\n  for (i = 0; i < maxbits; i++) {\n    lists[i][0] = node0;\n    lists[i][1] = node1;\n  }\n}\n\n/*\nConverts result of boundary package-merge to the bitlengths. The result in the\nlast chain of the last list contains the amount of active leaves in each list.\nchain: Chain to extract the bit length from (last chain from last list).\n*/\nstatic void ExtractBitLengths(Node* chain, Node* leaves, unsigned* bitlengths) {\n  int counts[16] = {0};\n  unsigned end = 16;\n  unsigned ptr = 15;\n  unsigned value = 1;\n  Node* node;\n  int val;\n\n  for (node = chain; node; node = node->tail) {\n    counts[--end] = node->count;\n  }\n\n  val = counts[15];\n  while (ptr >= end) {\n    for (; val > counts[ptr - 1]; val--) {\n      bitlengths[leaves[val - 1].count] = value;\n    }\n    ptr--;\n    value++;\n  }\n}\n\n/*\nComparator for sorting the leaves. Has the function signature for qsort.\n*/\nstatic int LeafComparator(const void* a, const void* b) {\n  return ((const Node*)a)->weight - ((const Node*)b)->weight;\n}\n\nint ZopfliLengthLimitedCodeLengths(\n    const size_t* frequencies, int n, int maxbits, unsigned* bitlengths) {\n  NodePool pool;\n  int i;\n  int numsymbols = 0;  /* Amount of symbols with frequency > 0. */\n  int numBoundaryPMRuns;\n  Node* nodes;\n\n  /* Array of lists of chains. Each list requires only two lookahead chains at\n  a time, so each list is a array of two Node*'s. */\n  Node* (*lists)[2];\n\n  /* One leaf per symbol. Only numsymbols leaves will be used. */\n  Node* leaves = (Node*)malloc(n * sizeof(*leaves));\n\n  /* Initialize all bitlengths at 0. */\n  for (i = 0; i < n; i++) {\n    bitlengths[i] = 0;\n  }\n\n  /* Count used symbols and place them in the leaves. */\n  for (i = 0; i < n; i++) {\n    if (frequencies[i]) {\n      leaves[numsymbols].weight = frequencies[i];\n      leaves[numsymbols].count = i;  /* Index of symbol this leaf represents. */\n      numsymbols++;\n    }\n  }\n\n  /* Check special cases and error conditions. */\n  if ((1 << maxbits) < numsymbols) {\n    free(leaves);\n    return 1;  /* Error, too few maxbits to represent symbols. */\n  }\n  if (numsymbols == 0) {\n    free(leaves);\n    return 0;  /* No symbols at all. OK. */\n  }\n  if (numsymbols == 1) {\n    bitlengths[leaves[0].count] = 1;\n    free(leaves);\n    return 0;  /* Only one symbol, give it bitlength 1, not 0. OK. */\n  }\n  if (numsymbols == 2) {\n    bitlengths[leaves[0].count]++;\n    bitlengths[leaves[1].count]++;\n    free(leaves);\n    return 0;\n  }\n\n  /* Sort the leaves from lightest to heaviest. Add count into the same\n  variable for stable sorting. */\n  for (i = 0; i < numsymbols; i++) {\n    if (leaves[i].weight >=\n        ((size_t)1 << (sizeof(leaves[0].weight) * CHAR_BIT - 9))) {\n      free(leaves);\n      return 1;  /* Error, we need 9 bits for the count. */\n    }\n    leaves[i].weight = (leaves[i].weight << 9) | leaves[i].count;\n  }\n  qsort(leaves, numsymbols, sizeof(Node), LeafComparator);\n  for (i = 0; i < numsymbols; i++) {\n    leaves[i].weight >>= 9;\n  }\n\n  if (numsymbols - 1 < maxbits) {\n    maxbits = numsymbols - 1;\n  }\n\n  /* Initialize node memory pool. */\n  nodes = (Node*)malloc(maxbits * 2 * numsymbols * sizeof(Node));\n  pool.next = nodes;\n\n  lists = (Node* (*)[2])malloc(maxbits * sizeof(*lists));\n  InitLists(&pool, leaves, maxbits, lists);\n\n  /* In the last list, 2 * numsymbols - 2 active chains need to be created. Two\n  are already created in the initialization. Each BoundaryPM run creates one. */\n  numBoundaryPMRuns = 2 * numsymbols - 4;\n  for (i = 0; i < numBoundaryPMRuns - 1; i++) {\n    BoundaryPM(lists, leaves, numsymbols, &pool, maxbits - 1);\n  }\n  BoundaryPMFinal(lists, leaves, numsymbols, &pool, maxbits - 1);\n\n  ExtractBitLengths(lists[maxbits - 1][1], leaves, bitlengths);\n\n  free(lists);\n  free(leaves);\n  free(nodes);\n  return 0;  /* OK. */\n}\n"
  },
  {
    "path": "external/zopfli/katajainen.h",
    "content": "/*\nCopyright 2011 Google Inc. All Rights Reserved.\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n    http://www.apache.org/licenses/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n\nAuthor: lode.vandevenne@gmail.com (Lode Vandevenne)\nAuthor: jyrki.alakuijala@gmail.com (Jyrki Alakuijala)\n*/\n\n#ifndef ZOPFLI_KATAJAINEN_H_\n#define ZOPFLI_KATAJAINEN_H_\n\n#include <string.h>\n\n/*\nOutputs minimum-redundancy length-limited code bitlengths for symbols with the\ngiven counts. The bitlengths are limited by maxbits.\n\nThe output is tailored for DEFLATE: symbols that never occur, get a bit length\nof 0, and if only a single symbol occurs at least once, its bitlength will be 1,\nand not 0 as would theoretically be needed for a single symbol.\n\nfrequencies: The amount of occurrences of each symbol.\nn: The amount of symbols.\nmaxbits: Maximum bit length, inclusive.\nbitlengths: Output, the bitlengths for the symbol prefix codes.\nreturn: 0 for OK, non-0 for error.\n*/\nint ZopfliLengthLimitedCodeLengths(\n    const size_t* frequencies, int n, int maxbits, unsigned* bitlengths);\n\n#endif  /* ZOPFLI_KATAJAINEN_H_ */\n"
  },
  {
    "path": "external/zopfli/lz77.c",
    "content": "/*\nCopyright 2011 Google Inc. All Rights Reserved.\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n    http://www.apache.org/licenses/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n\nAuthor: lode.vandevenne@gmail.com (Lode Vandevenne)\nAuthor: jyrki.alakuijala@gmail.com (Jyrki Alakuijala)\n*/\n\n#include \"lz77.h\"\n#include \"symbols.h\"\n#include \"util.h\"\n\n#include <assert.h>\n#include <stdio.h>\n#include <stdlib.h>\n\nvoid ZopfliInitLZ77Store(const unsigned char* data, ZopfliLZ77Store* store) {\n  store->size = 0;\n  store->litlens = 0;\n  store->dists = 0;\n  store->pos = 0;\n  store->data = data;\n  store->ll_symbol = 0;\n  store->d_symbol = 0;\n  store->ll_counts = 0;\n  store->d_counts = 0;\n}\n\nvoid ZopfliCleanLZ77Store(ZopfliLZ77Store* store) {\n  free(store->litlens);\n  free(store->dists);\n  free(store->pos);\n  free(store->ll_symbol);\n  free(store->d_symbol);\n  free(store->ll_counts);\n  free(store->d_counts);\n}\n\nstatic size_t CeilDiv(size_t a, size_t b) {\n  return (a + b - 1) / b;\n}\n\nvoid ZopfliCopyLZ77Store(\n    const ZopfliLZ77Store* source, ZopfliLZ77Store* dest) {\n  size_t i;\n  size_t llsize = ZOPFLI_NUM_LL * CeilDiv(source->size, ZOPFLI_NUM_LL);\n  size_t dsize = ZOPFLI_NUM_D * CeilDiv(source->size, ZOPFLI_NUM_D);\n  ZopfliCleanLZ77Store(dest);\n  ZopfliInitLZ77Store(source->data, dest);\n  dest->litlens =\n      (unsigned short*)malloc(sizeof(*dest->litlens) * source->size);\n  dest->dists = (unsigned short*)malloc(sizeof(*dest->dists) * source->size);\n  dest->pos = (size_t*)malloc(sizeof(*dest->pos) * source->size);\n  dest->ll_symbol =\n      (unsigned short*)malloc(sizeof(*dest->ll_symbol) * source->size);\n  dest->d_symbol =\n      (unsigned short*)malloc(sizeof(*dest->d_symbol) * source->size);\n  dest->ll_counts = (size_t*)malloc(sizeof(*dest->ll_counts) * llsize);\n  dest->d_counts = (size_t*)malloc(sizeof(*dest->d_counts) * dsize);\n\n  /* Allocation failed. */\n  if (!dest->litlens || !dest->dists) exit(-1);\n  if (!dest->pos) exit(-1);\n  if (!dest->ll_symbol || !dest->d_symbol) exit(-1);\n  if (!dest->ll_counts || !dest->d_counts) exit(-1);\n\n  dest->size = source->size;\n  for (i = 0; i < source->size; i++) {\n    dest->litlens[i] = source->litlens[i];\n    dest->dists[i] = source->dists[i];\n    dest->pos[i] = source->pos[i];\n    dest->ll_symbol[i] = source->ll_symbol[i];\n    dest->d_symbol[i] = source->d_symbol[i];\n  }\n  for (i = 0; i < llsize; i++) {\n    dest->ll_counts[i] = source->ll_counts[i];\n  }\n  for (i = 0; i < dsize; i++) {\n    dest->d_counts[i] = source->d_counts[i];\n  }\n}\n\n/*\nAppends the length and distance to the LZ77 arrays of the ZopfliLZ77Store.\ncontext must be a ZopfliLZ77Store*.\n*/\nvoid ZopfliStoreLitLenDist(unsigned short length, unsigned short dist,\n                           size_t pos, ZopfliLZ77Store* store) {\n  size_t i;\n  /* Needed for using ZOPFLI_APPEND_DATA multiple times. */\n  size_t origsize = store->size;\n  size_t llstart = ZOPFLI_NUM_LL * (origsize / ZOPFLI_NUM_LL);\n  size_t dstart = ZOPFLI_NUM_D * (origsize / ZOPFLI_NUM_D);\n\n  /* Everytime the index wraps around, a new cumulative histogram is made: we're\n  keeping one histogram value per LZ77 symbol rather than a full histogram for\n  each to save memory. */\n  if (origsize % ZOPFLI_NUM_LL == 0) {\n    size_t llsize = origsize;\n    for (i = 0; i < ZOPFLI_NUM_LL; i++) {\n      ZOPFLI_APPEND_DATA(\n          origsize == 0 ? 0 : store->ll_counts[origsize - ZOPFLI_NUM_LL + i],\n          &store->ll_counts, &llsize);\n    }\n  }\n  if (origsize % ZOPFLI_NUM_D == 0) {\n    size_t dsize = origsize;\n    for (i = 0; i < ZOPFLI_NUM_D; i++) {\n      ZOPFLI_APPEND_DATA(\n          origsize == 0 ? 0 : store->d_counts[origsize - ZOPFLI_NUM_D + i],\n          &store->d_counts, &dsize);\n    }\n  }\n\n  ZOPFLI_APPEND_DATA(length, &store->litlens, &store->size);\n  store->size = origsize;\n  ZOPFLI_APPEND_DATA(dist, &store->dists, &store->size);\n  store->size = origsize;\n  ZOPFLI_APPEND_DATA(pos, &store->pos, &store->size);\n  assert(length < 259);\n\n  if (dist == 0) {\n    store->size = origsize;\n    ZOPFLI_APPEND_DATA(length, &store->ll_symbol, &store->size);\n    store->size = origsize;\n    ZOPFLI_APPEND_DATA(0, &store->d_symbol, &store->size);\n    store->ll_counts[llstart + length]++;\n  } else {\n    store->size = origsize;\n    ZOPFLI_APPEND_DATA(ZopfliGetLengthSymbol(length),\n                       &store->ll_symbol, &store->size);\n    store->size = origsize;\n    ZOPFLI_APPEND_DATA(ZopfliGetDistSymbol(dist),\n                       &store->d_symbol, &store->size);\n    store->ll_counts[llstart + ZopfliGetLengthSymbol(length)]++;\n    store->d_counts[dstart + ZopfliGetDistSymbol(dist)]++;\n  }\n}\n\nvoid ZopfliAppendLZ77Store(const ZopfliLZ77Store* store,\n                           ZopfliLZ77Store* target) {\n  size_t i;\n  for (i = 0; i < store->size; i++) {\n    ZopfliStoreLitLenDist(store->litlens[i], store->dists[i],\n                          store->pos[i], target);\n  }\n}\n\nsize_t ZopfliLZ77GetByteRange(const ZopfliLZ77Store* lz77,\n                              size_t lstart, size_t lend) {\n  size_t l = lend - 1;\n  if (lstart == lend) return 0;\n  return lz77->pos[l] + ((lz77->dists[l] == 0) ?\n      1 : lz77->litlens[l]) - lz77->pos[lstart];\n}\n\nstatic void ZopfliLZ77GetHistogramAt(const ZopfliLZ77Store* lz77, size_t lpos,\n                                     size_t* ll_counts, size_t* d_counts) {\n  /* The real histogram is created by using the histogram for this chunk, but\n  all superfluous values of this chunk subtracted. */\n  size_t llpos = ZOPFLI_NUM_LL * (lpos / ZOPFLI_NUM_LL);\n  size_t dpos = ZOPFLI_NUM_D * (lpos / ZOPFLI_NUM_D);\n  size_t i;\n  for (i = 0; i < ZOPFLI_NUM_LL; i++) {\n    ll_counts[i] = lz77->ll_counts[llpos + i];\n  }\n  for (i = lpos + 1; i < llpos + ZOPFLI_NUM_LL && i < lz77->size; i++) {\n    ll_counts[lz77->ll_symbol[i]]--;\n  }\n  for (i = 0; i < ZOPFLI_NUM_D; i++) {\n    d_counts[i] = lz77->d_counts[dpos + i];\n  }\n  for (i = lpos + 1; i < dpos + ZOPFLI_NUM_D && i < lz77->size; i++) {\n    if (lz77->dists[i] != 0) d_counts[lz77->d_symbol[i]]--;\n  }\n}\n\nvoid ZopfliLZ77GetHistogram(const ZopfliLZ77Store* lz77,\n                           size_t lstart, size_t lend,\n                           size_t* ll_counts, size_t* d_counts) {\n  size_t i;\n  if (lstart + ZOPFLI_NUM_LL * 3 > lend) {\n    memset(ll_counts, 0, sizeof(*ll_counts) * ZOPFLI_NUM_LL);\n    memset(d_counts, 0, sizeof(*d_counts) * ZOPFLI_NUM_D);\n    for (i = lstart; i < lend; i++) {\n      ll_counts[lz77->ll_symbol[i]]++;\n      if (lz77->dists[i] != 0) d_counts[lz77->d_symbol[i]]++;\n    }\n  } else {\n    /* Subtract the cumulative histograms at the end and the start to get the\n    histogram for this range. */\n    ZopfliLZ77GetHistogramAt(lz77, lend - 1, ll_counts, d_counts);\n    if (lstart > 0) {\n      size_t ll_counts2[ZOPFLI_NUM_LL];\n      size_t d_counts2[ZOPFLI_NUM_D];\n      ZopfliLZ77GetHistogramAt(lz77, lstart - 1, ll_counts2, d_counts2);\n\n      for (i = 0; i < ZOPFLI_NUM_LL; i++) {\n        ll_counts[i] -= ll_counts2[i];\n      }\n      for (i = 0; i < ZOPFLI_NUM_D; i++) {\n        d_counts[i] -= d_counts2[i];\n      }\n    }\n  }\n}\n\nvoid ZopfliInitBlockState(const ZopfliOptions* options,\n                          size_t blockstart, size_t blockend, int add_lmc,\n                          ZopfliBlockState* s) {\n  s->options = options;\n  s->blockstart = blockstart;\n  s->blockend = blockend;\n#ifdef ZOPFLI_LONGEST_MATCH_CACHE\n  if (add_lmc) {\n    s->lmc = (ZopfliLongestMatchCache*)malloc(sizeof(ZopfliLongestMatchCache));\n    ZopfliInitCache(blockend - blockstart, s->lmc);\n  } else {\n    s->lmc = 0;\n  }\n#endif\n}\n\nvoid ZopfliCleanBlockState(ZopfliBlockState* s) {\n#ifdef ZOPFLI_LONGEST_MATCH_CACHE\n  if (s->lmc) {\n    ZopfliCleanCache(s->lmc);\n    free(s->lmc);\n  }\n#endif\n}\n\n/*\nGets a score of the length given the distance. Typically, the score of the\nlength is the length itself, but if the distance is very long, decrease the\nscore of the length a bit to make up for the fact that long distances use large\namounts of extra bits.\n\nThis is not an accurate score, it is a heuristic only for the greedy LZ77\nimplementation. More accurate cost models are employed later. Making this\nheuristic more accurate may hurt rather than improve compression.\n\nThe two direct uses of this heuristic are:\n-avoid using a length of 3 in combination with a long distance. This only has\n an effect if length == 3.\n-make a slightly better choice between the two options of the lazy matching.\n\nIndirectly, this affects:\n-the block split points if the default of block splitting first is used, in a\n rather unpredictable way\n-the first zopfli run, so it affects the chance of the first run being closer\n to the optimal output\n*/\nstatic int GetLengthScore(int length, int distance) {\n  /*\n  At 1024, the distance uses 9+ extra bits and this seems to be the sweet spot\n  on tested files.\n  */\n  return distance > 1024 ? length - 1 : length;\n}\n\nvoid ZopfliVerifyLenDist(const unsigned char* data, size_t datasize, size_t pos,\n                         unsigned short dist, unsigned short length) {\n\n  /* TODO(lode): make this only run in a debug compile, it's for assert only. */\n  size_t i;\n\n  assert(pos + length <= datasize);\n  for (i = 0; i < length; i++) {\n    if (data[pos - dist + i] != data[pos + i]) {\n      assert(data[pos - dist + i] == data[pos + i]);\n      break;\n    }\n  }\n}\n\n/*\nFinds how long the match of scan and match is. Can be used to find how many\nbytes starting from scan, and from match, are equal. Returns the last byte\nafter scan, which is still equal to the correspondinb byte after match.\nscan is the position to compare\nmatch is the earlier position to compare.\nend is the last possible byte, beyond which to stop looking.\nsafe_end is a few (8) bytes before end, for comparing multiple bytes at once.\n*/\nstatic const unsigned char* GetMatch(const unsigned char* scan,\n                                     const unsigned char* match,\n                                     const unsigned char* end,\n                                     const unsigned char* safe_end) {\n\n  if (sizeof(size_t) == 8) {\n    /* 8 checks at once per array bounds check (size_t is 64-bit). */\n    while (scan < safe_end && *((size_t*)scan) == *((size_t*)match)) {\n      scan += 8;\n      match += 8;\n    }\n  } else if (sizeof(unsigned int) == 4) {\n    /* 4 checks at once per array bounds check (unsigned int is 32-bit). */\n    while (scan < safe_end\n        && *((unsigned int*)scan) == *((unsigned int*)match)) {\n      scan += 4;\n      match += 4;\n    }\n  } else {\n    /* do 8 checks at once per array bounds check. */\n    while (scan < safe_end && *scan == *match && *++scan == *++match\n          && *++scan == *++match && *++scan == *++match\n          && *++scan == *++match && *++scan == *++match\n          && *++scan == *++match && *++scan == *++match) {\n      scan++; match++;\n    }\n  }\n\n  /* The remaining few bytes. */\n  while (scan != end && *scan == *match) {\n    scan++; match++;\n  }\n\n  return scan;\n}\n\n#ifdef ZOPFLI_LONGEST_MATCH_CACHE\n/*\nGets distance, length and sublen values from the cache if possible.\nReturns 1 if it got the values from the cache, 0 if not.\nUpdates the limit value to a smaller one if possible with more limited\ninformation from the cache.\n*/\nstatic int TryGetFromLongestMatchCache(ZopfliBlockState* s,\n    size_t pos, size_t* limit,\n    unsigned short* sublen, unsigned short* distance, unsigned short* length) {\n  /* The LMC cache starts at the beginning of the block rather than the\n     beginning of the whole array. */\n  size_t lmcpos = pos - s->blockstart;\n\n  /* Length > 0 and dist 0 is invalid combination, which indicates on purpose\n     that this cache value is not filled in yet. */\n  unsigned char cache_available = s->lmc && (s->lmc->length[lmcpos] == 0 ||\n      s->lmc->dist[lmcpos] != 0);\n  unsigned char limit_ok_for_cache = cache_available &&\n      (*limit == ZOPFLI_MAX_MATCH || s->lmc->length[lmcpos] <= *limit ||\n      (sublen && ZopfliMaxCachedSublen(s->lmc,\n          lmcpos, s->lmc->length[lmcpos]) >= *limit));\n\n  if (s->lmc && limit_ok_for_cache && cache_available) {\n    if (!sublen || s->lmc->length[lmcpos]\n        <= ZopfliMaxCachedSublen(s->lmc, lmcpos, s->lmc->length[lmcpos])) {\n      *length = s->lmc->length[lmcpos];\n      if (*length > *limit) *length = *limit;\n      if (sublen) {\n        ZopfliCacheToSublen(s->lmc, lmcpos, *length, sublen);\n        *distance = sublen[*length];\n        if (*limit == ZOPFLI_MAX_MATCH && *length >= ZOPFLI_MIN_MATCH) {\n          assert(sublen[*length] == s->lmc->dist[lmcpos]);\n        }\n      } else {\n        *distance = s->lmc->dist[lmcpos];\n      }\n      return 1;\n    }\n    /* Can't use much of the cache, since the \"sublens\" need to be calculated,\n       but at  least we already know when to stop. */\n    *limit = s->lmc->length[lmcpos];\n  }\n\n  return 0;\n}\n\n/*\nStores the found sublen, distance and length in the longest match cache, if\npossible.\n*/\nstatic void StoreInLongestMatchCache(ZopfliBlockState* s,\n    size_t pos, size_t limit,\n    const unsigned short* sublen,\n    unsigned short distance, unsigned short length) {\n  /* The LMC cache starts at the beginning of the block rather than the\n     beginning of the whole array. */\n  size_t lmcpos = pos - s->blockstart;\n\n  /* Length > 0 and dist 0 is invalid combination, which indicates on purpose\n     that this cache value is not filled in yet. */\n  unsigned char cache_available = s->lmc && (s->lmc->length[lmcpos] == 0 ||\n      s->lmc->dist[lmcpos] != 0);\n\n  if (s->lmc && limit == ZOPFLI_MAX_MATCH && sublen && !cache_available) {\n    assert(s->lmc->length[lmcpos] == 1 && s->lmc->dist[lmcpos] == 0);\n    s->lmc->dist[lmcpos] = length < ZOPFLI_MIN_MATCH ? 0 : distance;\n    s->lmc->length[lmcpos] = length < ZOPFLI_MIN_MATCH ? 0 : length;\n    assert(!(s->lmc->length[lmcpos] == 1 && s->lmc->dist[lmcpos] == 0));\n    ZopfliSublenToCache(sublen, lmcpos, length, s->lmc);\n  }\n}\n#endif\n\nvoid ZopfliFindLongestMatch(ZopfliBlockState* s, const ZopfliHash* h,\n    const unsigned char* array,\n    size_t pos, size_t size, size_t limit,\n    unsigned short* sublen, unsigned short* distance, unsigned short* length) {\n  unsigned short hpos = pos & ZOPFLI_WINDOW_MASK, p, pp;\n  unsigned short bestdist = 0;\n  unsigned short bestlength = 1;\n  const unsigned char* scan;\n  const unsigned char* match;\n  const unsigned char* arrayend;\n  const unsigned char* arrayend_safe;\n#if ZOPFLI_MAX_CHAIN_HITS < ZOPFLI_WINDOW_SIZE\n  int chain_counter = ZOPFLI_MAX_CHAIN_HITS;  /* For quitting early. */\n#endif\n\n  unsigned dist = 0;  /* Not unsigned short on purpose. */\n\n  int* hhead = h->head;\n  unsigned short* hprev = h->prev;\n  int* hhashval = h->hashval;\n  int hval = h->val;\n\n#ifdef ZOPFLI_LONGEST_MATCH_CACHE\n  if (TryGetFromLongestMatchCache(s, pos, &limit, sublen, distance, length)) {\n    assert(pos + *length <= size);\n    return;\n  }\n#endif\n\n  assert(limit <= ZOPFLI_MAX_MATCH);\n  assert(limit >= ZOPFLI_MIN_MATCH);\n  assert(pos < size);\n\n  if (size - pos < ZOPFLI_MIN_MATCH) {\n    /* The rest of the code assumes there are at least ZOPFLI_MIN_MATCH bytes to\n       try. */\n    *length = 0;\n    *distance = 0;\n    return;\n  }\n\n  if (pos + limit > size) {\n    limit = size - pos;\n  }\n  arrayend = &array[pos] + limit;\n  arrayend_safe = arrayend - 8;\n\n  assert(hval < 65536);\n\n  pp = hhead[hval];  /* During the whole loop, p == hprev[pp]. */\n  p = hprev[pp];\n\n  assert(pp == hpos);\n\n  dist = p < pp ? pp - p : ((ZOPFLI_WINDOW_SIZE - p) + pp);\n\n  /* Go through all distances. */\n  while (dist < ZOPFLI_WINDOW_SIZE) {\n    unsigned short currentlength = 0;\n\n    assert(p < ZOPFLI_WINDOW_SIZE);\n    assert(p == hprev[pp]);\n    assert(hhashval[p] == hval);\n\n    if (dist > 0) {\n      assert(pos < size);\n      assert(dist <= pos);\n      scan = &array[pos];\n      match = &array[pos - dist];\n\n      /* Testing the byte at position bestlength first, goes slightly faster. */\n      if (pos + bestlength >= size\n          || *(scan + bestlength) == *(match + bestlength)) {\n\n#ifdef ZOPFLI_HASH_SAME\n        unsigned short same0 = h->same[pos & ZOPFLI_WINDOW_MASK];\n        if (same0 > 2 && *scan == *match) {\n          unsigned short same1 = h->same[(pos - dist) & ZOPFLI_WINDOW_MASK];\n          unsigned short same = same0 < same1 ? same0 : same1;\n          if (same > limit) same = limit;\n          scan += same;\n          match += same;\n        }\n#endif\n        scan = GetMatch(scan, match, arrayend, arrayend_safe);\n        currentlength = scan - &array[pos];  /* The found length. */\n      }\n\n      if (currentlength > bestlength) {\n        if (sublen) {\n          unsigned short j;\n          for (j = bestlength + 1; j <= currentlength; j++) {\n            sublen[j] = dist;\n          }\n        }\n        bestdist = dist;\n        bestlength = currentlength;\n        if (currentlength >= limit) break;\n      }\n    }\n\n\n#ifdef ZOPFLI_HASH_SAME_HASH\n    /* Switch to the other hash once this will be more efficient. */\n    if (hhead != h->head2 && bestlength >= h->same[hpos] &&\n        h->val2 == h->hashval2[p]) {\n      /* Now use the hash that encodes the length and first byte. */\n      hhead = h->head2;\n      hprev = h->prev2;\n      hhashval = h->hashval2;\n      hval = h->val2;\n    }\n#endif\n\n    pp = p;\n    p = hprev[p];\n    if (p == pp) break;  /* Uninited prev value. */\n\n    dist += p < pp ? pp - p : ((ZOPFLI_WINDOW_SIZE - p) + pp);\n\n#if ZOPFLI_MAX_CHAIN_HITS < ZOPFLI_WINDOW_SIZE\n    chain_counter--;\n    if (chain_counter <= 0) break;\n#endif\n  }\n\n#ifdef ZOPFLI_LONGEST_MATCH_CACHE\n  StoreInLongestMatchCache(s, pos, limit, sublen, bestdist, bestlength);\n#endif\n\n  assert(bestlength <= limit);\n\n  *distance = bestdist;\n  *length = bestlength;\n  assert(pos + *length <= size);\n}\n\nvoid ZopfliLZ77Greedy(ZopfliBlockState* s, const unsigned char* in,\n                      size_t instart, size_t inend,\n                      ZopfliLZ77Store* store, ZopfliHash* h) {\n  size_t i = 0, j;\n  unsigned short leng;\n  unsigned short dist;\n  int lengthscore;\n  size_t windowstart = instart > ZOPFLI_WINDOW_SIZE\n      ? instart - ZOPFLI_WINDOW_SIZE : 0;\n  unsigned short dummysublen[259];\n\n#ifdef ZOPFLI_LAZY_MATCHING\n  /* Lazy matching. */\n  unsigned prev_length = 0;\n  unsigned prev_match = 0;\n  int prevlengthscore;\n  int match_available = 0;\n#endif\n\n  if (instart == inend) return;\n\n  ZopfliResetHash(ZOPFLI_WINDOW_SIZE, h);\n  ZopfliWarmupHash(in, windowstart, inend, h);\n  for (i = windowstart; i < instart; i++) {\n    ZopfliUpdateHash(in, i, inend, h);\n  }\n\n  for (i = instart; i < inend; i++) {\n    ZopfliUpdateHash(in, i, inend, h);\n\n    ZopfliFindLongestMatch(s, h, in, i, inend, ZOPFLI_MAX_MATCH, dummysublen,\n                           &dist, &leng);\n    lengthscore = GetLengthScore(leng, dist);\n\n#ifdef ZOPFLI_LAZY_MATCHING\n    /* Lazy matching. */\n    prevlengthscore = GetLengthScore(prev_length, prev_match);\n    if (match_available) {\n      match_available = 0;\n      if (lengthscore > prevlengthscore + 1) {\n        ZopfliStoreLitLenDist(in[i - 1], 0, i - 1, store);\n        if (lengthscore >= ZOPFLI_MIN_MATCH && leng < ZOPFLI_MAX_MATCH) {\n          match_available = 1;\n          prev_length = leng;\n          prev_match = dist;\n          continue;\n        }\n      } else {\n        /* Add previous to output. */\n        leng = prev_length;\n        dist = prev_match;\n        lengthscore = prevlengthscore;\n        /* Add to output. */\n        ZopfliVerifyLenDist(in, inend, i - 1, dist, leng);\n        ZopfliStoreLitLenDist(leng, dist, i - 1, store);\n        for (j = 2; j < leng; j++) {\n          assert(i < inend);\n          i++;\n          ZopfliUpdateHash(in, i, inend, h);\n        }\n        continue;\n      }\n    }\n    else if (lengthscore >= ZOPFLI_MIN_MATCH && leng < ZOPFLI_MAX_MATCH) {\n      match_available = 1;\n      prev_length = leng;\n      prev_match = dist;\n      continue;\n    }\n    /* End of lazy matching. */\n#endif\n\n    /* Add to output. */\n    if (lengthscore >= ZOPFLI_MIN_MATCH) {\n      ZopfliVerifyLenDist(in, inend, i, dist, leng);\n      ZopfliStoreLitLenDist(leng, dist, i, store);\n    } else {\n      leng = 1;\n      ZopfliStoreLitLenDist(in[i], 0, i, store);\n    }\n    for (j = 1; j < leng; j++) {\n      assert(i < inend);\n      i++;\n      ZopfliUpdateHash(in, i, inend, h);\n    }\n  }\n}\n"
  },
  {
    "path": "external/zopfli/lz77.h",
    "content": "/*\nCopyright 2011 Google Inc. All Rights Reserved.\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n    http://www.apache.org/licenses/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n\nAuthor: lode.vandevenne@gmail.com (Lode Vandevenne)\nAuthor: jyrki.alakuijala@gmail.com (Jyrki Alakuijala)\n*/\n\n/*\nFunctions for basic LZ77 compression and utilities for the \"squeeze\" LZ77\ncompression.\n*/\n\n#ifndef ZOPFLI_LZ77_H_\n#define ZOPFLI_LZ77_H_\n\n#include <stdlib.h>\n\n#include \"cache.h\"\n#include \"hash.h\"\n#include \"zopfli.h\"\n\n/*\nStores lit/length and dist pairs for LZ77.\nParameter litlens: Contains the literal symbols or length values.\nParameter dists: Contains the distances. A value is 0 to indicate that there is\nno dist and the corresponding litlens value is a literal instead of a length.\nParameter size: The size of both the litlens and dists arrays.\nThe memory can best be managed by using ZopfliInitLZ77Store to initialize it,\nZopfliCleanLZ77Store to destroy it, and ZopfliStoreLitLenDist to append values.\n\n*/\ntypedef struct ZopfliLZ77Store {\n  unsigned short* litlens;  /* Lit or len. */\n  unsigned short* dists;  /* If 0: indicates literal in corresponding litlens,\n      if > 0: length in corresponding litlens, this is the distance. */\n  size_t size;\n\n  const unsigned char* data;  /* original data */\n  size_t* pos;  /* position in data where this LZ77 command begins */\n\n  unsigned short* ll_symbol;\n  unsigned short* d_symbol;\n\n  /* Cumulative histograms wrapping around per chunk. Each chunk has the amount\n  of distinct symbols as length, so using 1 value per LZ77 symbol, we have a\n  precise histogram at every N symbols, and the rest can be calculated by\n  looping through the actual symbols of this chunk. */\n  size_t* ll_counts;\n  size_t* d_counts;\n} ZopfliLZ77Store;\n\nvoid ZopfliInitLZ77Store(const unsigned char* data, ZopfliLZ77Store* store);\nvoid ZopfliCleanLZ77Store(ZopfliLZ77Store* store);\nvoid ZopfliCopyLZ77Store(const ZopfliLZ77Store* source, ZopfliLZ77Store* dest);\nvoid ZopfliStoreLitLenDist(unsigned short length, unsigned short dist,\n                           size_t pos, ZopfliLZ77Store* store);\nvoid ZopfliAppendLZ77Store(const ZopfliLZ77Store* store,\n                           ZopfliLZ77Store* target);\n/* Gets the amount of raw bytes that this range of LZ77 symbols spans. */\nsize_t ZopfliLZ77GetByteRange(const ZopfliLZ77Store* lz77,\n                              size_t lstart, size_t lend);\n/* Gets the histogram of lit/len and dist symbols in the given range, using the\ncumulative histograms, so faster than adding one by one for large range. Does\nnot add the one end symbol of value 256. */\nvoid ZopfliLZ77GetHistogram(const ZopfliLZ77Store* lz77,\n                            size_t lstart, size_t lend,\n                            size_t* ll_counts, size_t* d_counts);\n\n/*\nSome state information for compressing a block.\nThis is currently a bit under-used (with mainly only the longest match cache),\nbut is kept for easy future expansion.\n*/\ntypedef struct ZopfliBlockState {\n  const ZopfliOptions* options;\n\n#ifdef ZOPFLI_LONGEST_MATCH_CACHE\n  /* Cache for length/distance pairs found so far. */\n  ZopfliLongestMatchCache* lmc;\n#endif\n\n  /* The start (inclusive) and end (not inclusive) of the current block. */\n  size_t blockstart;\n  size_t blockend;\n} ZopfliBlockState;\n\nvoid ZopfliInitBlockState(const ZopfliOptions* options,\n                          size_t blockstart, size_t blockend, int add_lmc,\n                          ZopfliBlockState* s);\nvoid ZopfliCleanBlockState(ZopfliBlockState* s);\n\n/*\nFinds the longest match (length and corresponding distance) for LZ77\ncompression.\nEven when not using \"sublen\", it can be more efficient to provide an array,\nbecause only then the caching is used.\narray: the data\npos: position in the data to find the match for\nsize: size of the data\nlimit: limit length to maximum this value (default should be 258). This allows\n    finding a shorter dist for that length (= less extra bits). Must be\n    in the range [ZOPFLI_MIN_MATCH, ZOPFLI_MAX_MATCH].\nsublen: output array of 259 elements, or null. Has, for each length, the\n    smallest distance required to reach this length. Only 256 of its 259 values\n    are used, the first 3 are ignored (the shortest length is 3. It is purely\n    for convenience that the array is made 3 longer).\n*/\nvoid ZopfliFindLongestMatch(\n    ZopfliBlockState *s, const ZopfliHash* h, const unsigned char* array,\n    size_t pos, size_t size, size_t limit,\n    unsigned short* sublen, unsigned short* distance, unsigned short* length);\n\n/*\nVerifies if length and dist are indeed valid, only used for assertion.\n*/\nvoid ZopfliVerifyLenDist(const unsigned char* data, size_t datasize, size_t pos,\n                         unsigned short dist, unsigned short length);\n\n/*\nDoes LZ77 using an algorithm similar to gzip, with lazy matching, rather than\nwith the slow but better \"squeeze\" implementation.\nThe result is placed in the ZopfliLZ77Store.\nIf instart is larger than 0, it uses values before instart as starting\ndictionary.\n*/\nvoid ZopfliLZ77Greedy(ZopfliBlockState* s, const unsigned char* in,\n                      size_t instart, size_t inend,\n                      ZopfliLZ77Store* store, ZopfliHash* h);\n\n#endif  /* ZOPFLI_LZ77_H_ */\n"
  },
  {
    "path": "external/zopfli/squeeze.c",
    "content": "/*\nCopyright 2011 Google Inc. All Rights Reserved.\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n    http://www.apache.org/licenses/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n\nAuthor: lode.vandevenne@gmail.com (Lode Vandevenne)\nAuthor: jyrki.alakuijala@gmail.com (Jyrki Alakuijala)\n*/\n\n#include \"squeeze.h\"\n\n#include <assert.h>\n#include <math.h>\n#include <stdio.h>\n\n#include \"blocksplitter.h\"\n#include \"deflate.h\"\n#include \"symbols.h\"\n#include \"tree.h\"\n#include \"util.h\"\n\ntypedef struct SymbolStats {\n  /* The literal and length symbols. */\n  size_t litlens[ZOPFLI_NUM_LL];\n  /* The 32 unique dist symbols, not the 32768 possible dists. */\n  size_t dists[ZOPFLI_NUM_D];\n\n  /* Length of each lit/len symbol in bits. */\n  double ll_symbols[ZOPFLI_NUM_LL];\n  /* Length of each dist symbol in bits. */\n  double d_symbols[ZOPFLI_NUM_D];\n} SymbolStats;\n\n/* Sets everything to 0. */\nstatic void InitStats(SymbolStats* stats) {\n  memset(stats->litlens, 0, ZOPFLI_NUM_LL * sizeof(stats->litlens[0]));\n  memset(stats->dists, 0, ZOPFLI_NUM_D * sizeof(stats->dists[0]));\n\n  memset(stats->ll_symbols, 0, ZOPFLI_NUM_LL * sizeof(stats->ll_symbols[0]));\n  memset(stats->d_symbols, 0, ZOPFLI_NUM_D * sizeof(stats->d_symbols[0]));\n}\n\nstatic void CopyStats(SymbolStats* source, SymbolStats* dest) {\n  memcpy(dest->litlens, source->litlens,\n         ZOPFLI_NUM_LL * sizeof(dest->litlens[0]));\n  memcpy(dest->dists, source->dists, ZOPFLI_NUM_D * sizeof(dest->dists[0]));\n\n  memcpy(dest->ll_symbols, source->ll_symbols,\n         ZOPFLI_NUM_LL * sizeof(dest->ll_symbols[0]));\n  memcpy(dest->d_symbols, source->d_symbols,\n         ZOPFLI_NUM_D * sizeof(dest->d_symbols[0]));\n}\n\n/* Adds the bit lengths. */\nstatic void AddWeighedStatFreqs(const SymbolStats* stats1, double w1,\n                                const SymbolStats* stats2, double w2,\n                                SymbolStats* result) {\n  size_t i;\n  for (i = 0; i < ZOPFLI_NUM_LL; i++) {\n    result->litlens[i] =\n        (size_t) (stats1->litlens[i] * w1 + stats2->litlens[i] * w2);\n  }\n  for (i = 0; i < ZOPFLI_NUM_D; i++) {\n    result->dists[i] =\n        (size_t) (stats1->dists[i] * w1 + stats2->dists[i] * w2);\n  }\n  result->litlens[256] = 1;  /* End symbol. */\n}\n\ntypedef struct RanState {\n  unsigned int m_w, m_z;\n} RanState;\n\nstatic void InitRanState(RanState* state) {\n  state->m_w = 1;\n  state->m_z = 2;\n}\n\n/* Get random number: \"Multiply-With-Carry\" generator of G. Marsaglia */\nstatic unsigned int Ran(RanState* state) {\n  state->m_z = 36969 * (state->m_z & 65535) + (state->m_z >> 16);\n  state->m_w = 18000 * (state->m_w & 65535) + (state->m_w >> 16);\n  return (state->m_z << 16) + state->m_w;  /* 32-bit result. */\n}\n\nstatic void RandomizeFreqs(RanState* state, size_t* freqs, int n) {\n  int i;\n  for (i = 0; i < n; i++) {\n    if ((Ran(state) >> 4) % 3 == 0) freqs[i] = freqs[Ran(state) % n];\n  }\n}\n\nstatic void RandomizeStatFreqs(RanState* state, SymbolStats* stats) {\n  RandomizeFreqs(state, stats->litlens, ZOPFLI_NUM_LL);\n  RandomizeFreqs(state, stats->dists, ZOPFLI_NUM_D);\n  stats->litlens[256] = 1;  /* End symbol. */\n}\n\nstatic void ClearStatFreqs(SymbolStats* stats) {\n  size_t i;\n  for (i = 0; i < ZOPFLI_NUM_LL; i++) stats->litlens[i] = 0;\n  for (i = 0; i < ZOPFLI_NUM_D; i++) stats->dists[i] = 0;\n}\n\n/*\nFunction that calculates a cost based on a model for the given LZ77 symbol.\nlitlen: means literal symbol if dist is 0, length otherwise.\n*/\ntypedef double CostModelFun(unsigned litlen, unsigned dist, void* context);\n\n/*\nCost model which should exactly match fixed tree.\ntype: CostModelFun\n*/\nstatic double GetCostFixed(unsigned litlen, unsigned dist, void* unused) {\n  (void)unused;\n  if (dist == 0) {\n    if (litlen <= 143) return 8;\n    else return 9;\n  } else {\n    int dbits = ZopfliGetDistExtraBits(dist);\n    int lbits = ZopfliGetLengthExtraBits(litlen);\n    int lsym = ZopfliGetLengthSymbol(litlen);\n    int cost = 0;\n    if (lsym <= 279) cost += 7;\n    else cost += 8;\n    cost += 5;  /* Every dist symbol has length 5. */\n    return cost + dbits + lbits;\n  }\n}\n\n/*\nCost model based on symbol statistics.\ntype: CostModelFun\n*/\nstatic double GetCostStat(unsigned litlen, unsigned dist, void* context) {\n  SymbolStats* stats = (SymbolStats*)context;\n  if (dist == 0) {\n    return stats->ll_symbols[litlen];\n  } else {\n    int lsym = ZopfliGetLengthSymbol(litlen);\n    int lbits = ZopfliGetLengthExtraBits(litlen);\n    int dsym = ZopfliGetDistSymbol(dist);\n    int dbits = ZopfliGetDistExtraBits(dist);\n    return lbits + dbits + stats->ll_symbols[lsym] + stats->d_symbols[dsym];\n  }\n}\n\n/*\nFinds the minimum possible cost this cost model can return for valid length and\ndistance symbols.\n*/\nstatic double GetCostModelMinCost(CostModelFun* costmodel, void* costcontext) {\n  double mincost;\n  int bestlength = 0; /* length that has lowest cost in the cost model */\n  int bestdist = 0; /* distance that has lowest cost in the cost model */\n  int i;\n  /*\n  Table of distances that have a different distance symbol in the deflate\n  specification. Each value is the first distance that has a new symbol. Only\n  different symbols affect the cost model so only these need to be checked.\n  See RFC 1951 section 3.2.5. Compressed blocks (length and distance codes).\n  */\n  static const int dsymbols[30] = {\n    1, 2, 3, 4, 5, 7, 9, 13, 17, 25, 33, 49, 65, 97, 129, 193, 257, 385, 513,\n    769, 1025, 1537, 2049, 3073, 4097, 6145, 8193, 12289, 16385, 24577\n  };\n\n  mincost = ZOPFLI_LARGE_FLOAT;\n  for (i = 3; i < 259; i++) {\n    double c = costmodel(i, 1, costcontext);\n    if (c < mincost) {\n      bestlength = i;\n      mincost = c;\n    }\n  }\n\n  mincost = ZOPFLI_LARGE_FLOAT;\n  for (i = 0; i < 30; i++) {\n    double c = costmodel(3, dsymbols[i], costcontext);\n    if (c < mincost) {\n      bestdist = dsymbols[i];\n      mincost = c;\n    }\n  }\n\n  return costmodel(bestlength, bestdist, costcontext);\n}\n\nstatic size_t zopfli_min(size_t a, size_t b) {\n  return a < b ? a : b;\n}\n\n/*\nPerforms the forward pass for \"squeeze\". Gets the most optimal length to reach\nevery byte from a previous byte, using cost calculations.\ns: the ZopfliBlockState\nin: the input data array\ninstart: where to start\ninend: where to stop (not inclusive)\ncostmodel: function to calculate the cost of some lit/len/dist pair.\ncostcontext: abstract context for the costmodel function\nlength_array: output array of size (inend - instart) which will receive the best\n    length to reach this byte from a previous byte.\nreturns the cost that was, according to the costmodel, needed to get to the end.\n*/\nstatic double GetBestLengths(ZopfliBlockState *s,\n                             const unsigned char* in,\n                             size_t instart, size_t inend,\n                             CostModelFun* costmodel, void* costcontext,\n                             unsigned short* length_array,\n                             ZopfliHash* h, float* costs) {\n  /* Best cost to get here so far. */\n  size_t blocksize = inend - instart;\n  size_t i = 0, k, kend;\n  unsigned short leng;\n  unsigned short dist;\n  unsigned short sublen[259];\n  size_t windowstart = instart > ZOPFLI_WINDOW_SIZE\n      ? instart - ZOPFLI_WINDOW_SIZE : 0;\n  double result;\n  double mincost = GetCostModelMinCost(costmodel, costcontext);\n  double mincostaddcostj;\n\n  if (instart == inend) return 0;\n\n  ZopfliResetHash(ZOPFLI_WINDOW_SIZE, h);\n  ZopfliWarmupHash(in, windowstart, inend, h);\n  for (i = windowstart; i < instart; i++) {\n    ZopfliUpdateHash(in, i, inend, h);\n  }\n\n  for (i = 1; i < blocksize + 1; i++) costs[i] = ZOPFLI_LARGE_FLOAT;\n  costs[0] = 0;  /* Because it's the start. */\n  length_array[0] = 0;\n\n  for (i = instart; i < inend; i++) {\n    size_t j = i - instart;  /* Index in the costs array and length_array. */\n    ZopfliUpdateHash(in, i, inend, h);\n\n#ifdef ZOPFLI_SHORTCUT_LONG_REPETITIONS\n    /* If we're in a long repetition of the same character and have more than\n    ZOPFLI_MAX_MATCH characters before and after our position. */\n    if (h->same[i & ZOPFLI_WINDOW_MASK] > ZOPFLI_MAX_MATCH * 2\n        && i > instart + ZOPFLI_MAX_MATCH + 1\n        && i + ZOPFLI_MAX_MATCH * 2 + 1 < inend\n        && h->same[(i - ZOPFLI_MAX_MATCH) & ZOPFLI_WINDOW_MASK]\n            > ZOPFLI_MAX_MATCH) {\n      double symbolcost = costmodel(ZOPFLI_MAX_MATCH, 1, costcontext);\n      /* Set the length to reach each one to ZOPFLI_MAX_MATCH, and the cost to\n      the cost corresponding to that length. Doing this, we skip\n      ZOPFLI_MAX_MATCH values to avoid calling ZopfliFindLongestMatch. */\n      for (k = 0; k < ZOPFLI_MAX_MATCH; k++) {\n        costs[j + ZOPFLI_MAX_MATCH] = costs[j] + symbolcost;\n        length_array[j + ZOPFLI_MAX_MATCH] = ZOPFLI_MAX_MATCH;\n        i++;\n        j++;\n        ZopfliUpdateHash(in, i, inend, h);\n      }\n    }\n#endif\n\n    ZopfliFindLongestMatch(s, h, in, i, inend, ZOPFLI_MAX_MATCH, sublen,\n                           &dist, &leng);\n\n    /* Literal. */\n    if (i + 1 <= inend) {\n      double newCost = costmodel(in[i], 0, costcontext) + costs[j];\n      assert(newCost >= 0);\n      if (newCost < costs[j + 1]) {\n        costs[j + 1] = newCost;\n        length_array[j + 1] = 1;\n      }\n    }\n    /* Lengths. */\n    kend = zopfli_min(leng, inend-i);\n    mincostaddcostj = mincost + costs[j];\n    for (k = 3; k <= kend; k++) {\n      double newCost;\n\n      /* Calling the cost model is expensive, avoid this if we are already at\n      the minimum possible cost that it can return. */\n     if (costs[j + k] <= mincostaddcostj) continue;\n\n      newCost = costmodel(k, sublen[k], costcontext) + costs[j];\n      assert(newCost >= 0);\n      if (newCost < costs[j + k]) {\n        assert(k <= ZOPFLI_MAX_MATCH);\n        costs[j + k] = newCost;\n        length_array[j + k] = k;\n      }\n    }\n  }\n\n  assert(costs[blocksize] >= 0);\n  result = costs[blocksize];\n\n  return result;\n}\n\n/*\nCalculates the optimal path of lz77 lengths to use, from the calculated\nlength_array. The length_array must contain the optimal length to reach that\nbyte. The path will be filled with the lengths to use, so its data size will be\nthe amount of lz77 symbols.\n*/\nstatic void TraceBackwards(size_t size, const unsigned short* length_array,\n                           unsigned short** path, size_t* pathsize) {\n  size_t index = size;\n  if (size == 0) return;\n  for (;;) {\n    ZOPFLI_APPEND_DATA(length_array[index], path, pathsize);\n    assert(length_array[index] <= index);\n    assert(length_array[index] <= ZOPFLI_MAX_MATCH);\n    assert(length_array[index] != 0);\n    index -= length_array[index];\n    if (index == 0) break;\n  }\n\n  /* Mirror result. */\n  for (index = 0; index < *pathsize / 2; index++) {\n    unsigned short temp = (*path)[index];\n    (*path)[index] = (*path)[*pathsize - index - 1];\n    (*path)[*pathsize - index - 1] = temp;\n  }\n}\n\nstatic void FollowPath(ZopfliBlockState* s,\n                       const unsigned char* in, size_t instart, size_t inend,\n                       unsigned short* path, size_t pathsize,\n                       ZopfliLZ77Store* store, ZopfliHash *h) {\n  size_t i, j, pos = 0;\n  size_t windowstart = instart > ZOPFLI_WINDOW_SIZE\n      ? instart - ZOPFLI_WINDOW_SIZE : 0;\n\n  size_t total_length_test = 0;\n\n  if (instart == inend) return;\n\n  ZopfliResetHash(ZOPFLI_WINDOW_SIZE, h);\n  ZopfliWarmupHash(in, windowstart, inend, h);\n  for (i = windowstart; i < instart; i++) {\n    ZopfliUpdateHash(in, i, inend, h);\n  }\n\n  pos = instart;\n  for (i = 0; i < pathsize; i++) {\n    unsigned short length = path[i];\n    unsigned short dummy_length;\n    unsigned short dist;\n    assert(pos < inend);\n\n    ZopfliUpdateHash(in, pos, inend, h);\n\n    /* Add to output. */\n    if (length >= ZOPFLI_MIN_MATCH) {\n      /* Get the distance by recalculating longest match. The found length\n      should match the length from the path. */\n      ZopfliFindLongestMatch(s, h, in, pos, inend, length, 0,\n                             &dist, &dummy_length);\n      assert(!(dummy_length != length && length > 2 && dummy_length > 2));\n      ZopfliVerifyLenDist(in, inend, pos, dist, length);\n      ZopfliStoreLitLenDist(length, dist, pos, store);\n      total_length_test += length;\n    } else {\n      length = 1;\n      ZopfliStoreLitLenDist(in[pos], 0, pos, store);\n      total_length_test++;\n    }\n\n\n    assert(pos + length <= inend);\n    for (j = 1; j < length; j++) {\n      ZopfliUpdateHash(in, pos + j, inend, h);\n    }\n\n    pos += length;\n  }\n}\n\n/* Calculates the entropy of the statistics */\nstatic void CalculateStatistics(SymbolStats* stats) {\n  ZopfliCalculateEntropy(stats->litlens, ZOPFLI_NUM_LL, stats->ll_symbols);\n  ZopfliCalculateEntropy(stats->dists, ZOPFLI_NUM_D, stats->d_symbols);\n}\n\n/* Appends the symbol statistics from the store. */\nstatic void GetStatistics(const ZopfliLZ77Store* store, SymbolStats* stats) {\n  size_t i;\n  for (i = 0; i < store->size; i++) {\n    if (store->dists[i] == 0) {\n      stats->litlens[store->litlens[i]]++;\n    } else {\n      stats->litlens[ZopfliGetLengthSymbol(store->litlens[i])]++;\n      stats->dists[ZopfliGetDistSymbol(store->dists[i])]++;\n    }\n  }\n  stats->litlens[256] = 1;  /* End symbol. */\n\n  CalculateStatistics(stats);\n}\n\n/*\nDoes a single run for ZopfliLZ77Optimal. For good compression, repeated runs\nwith updated statistics should be performed.\ns: the block state\nin: the input data array\ninstart: where to start\ninend: where to stop (not inclusive)\npath: pointer to dynamically allocated memory to store the path\npathsize: pointer to the size of the dynamic path array\nlength_array: array of size (inend - instart) used to store lengths\ncostmodel: function to use as the cost model for this squeeze run\ncostcontext: abstract context for the costmodel function\nstore: place to output the LZ77 data\nreturns the cost that was, according to the costmodel, needed to get to the end.\n    This is not the actual cost.\n*/\nstatic double LZ77OptimalRun(ZopfliBlockState* s,\n    const unsigned char* in, size_t instart, size_t inend,\n    unsigned short** path, size_t* pathsize,\n    unsigned short* length_array, CostModelFun* costmodel,\n    void* costcontext, ZopfliLZ77Store* store,\n    ZopfliHash* h, float* costs) {\n  double cost = GetBestLengths(s, in, instart, inend, costmodel,\n                costcontext, length_array, h, costs);\n  free(*path);\n  *path = 0;\n  *pathsize = 0;\n  TraceBackwards(inend - instart, length_array, path, pathsize);\n  FollowPath(s, in, instart, inend, *path, *pathsize, store, h);\n  assert(cost < ZOPFLI_LARGE_FLOAT);\n  return cost;\n}\n\nvoid ZopfliLZ77Optimal(ZopfliBlockState *s,\n                       const unsigned char* in, size_t instart, size_t inend,\n                       int numiterations,\n                       ZopfliLZ77Store* store) {\n  /* Dist to get to here with smallest cost. */\n  size_t blocksize = inend - instart;\n  unsigned short* length_array =\n      (unsigned short*)malloc(sizeof(unsigned short) * (blocksize + 1));\n  unsigned short* path = 0;\n  size_t pathsize = 0;\n  ZopfliLZ77Store currentstore;\n  ZopfliHash hash;\n  ZopfliHash* h = &hash;\n  SymbolStats stats, beststats, laststats;\n  int i;\n  float* costs = (float*)malloc(sizeof(float) * (blocksize + 1));\n  double cost;\n  double bestcost = ZOPFLI_LARGE_FLOAT;\n  double lastcost = 0;\n  /* Try randomizing the costs a bit once the size stabilizes. */\n  RanState ran_state;\n  int lastrandomstep = -1;\n\n  if (!costs) exit(-1); /* Allocation failed. */\n  if (!length_array) exit(-1); /* Allocation failed. */\n\n  InitRanState(&ran_state);\n  InitStats(&stats);\n  ZopfliInitLZ77Store(in, &currentstore);\n  ZopfliAllocHash(ZOPFLI_WINDOW_SIZE, h);\n\n  /* Do regular deflate, then loop multiple shortest path runs, each time using\n  the statistics of the previous run. */\n\n  /* Initial run. */\n  ZopfliLZ77Greedy(s, in, instart, inend, &currentstore, h);\n  GetStatistics(&currentstore, &stats);\n\n  /* Repeat statistics with each time the cost model from the previous stat\n  run. */\n  for (i = 0; i < numiterations; i++) {\n    ZopfliCleanLZ77Store(&currentstore);\n    ZopfliInitLZ77Store(in, &currentstore);\n    LZ77OptimalRun(s, in, instart, inend, &path, &pathsize,\n                   length_array, GetCostStat, (void*)&stats,\n                   &currentstore, h, costs);\n    cost = ZopfliCalculateBlockSize(&currentstore, 0, currentstore.size, 2);\n    if (s->options->verbose_more || (s->options->verbose && cost < bestcost)) {\n      fprintf(stderr, \"Iteration %d: %d bit\\n\", i, (int) cost);\n    }\n    if (cost < bestcost) {\n      /* Copy to the output store. */\n      ZopfliCopyLZ77Store(&currentstore, store);\n      CopyStats(&stats, &beststats);\n      bestcost = cost;\n    }\n    CopyStats(&stats, &laststats);\n    ClearStatFreqs(&stats);\n    GetStatistics(&currentstore, &stats);\n    if (lastrandomstep != -1) {\n      /* This makes it converge slower but better. Do it only once the\n      randomness kicks in so that if the user does few iterations, it gives a\n      better result sooner. */\n      AddWeighedStatFreqs(&stats, 1.0, &laststats, 0.5, &stats);\n      CalculateStatistics(&stats);\n    }\n    if (i > 5 && cost == lastcost) {\n      CopyStats(&beststats, &stats);\n      RandomizeStatFreqs(&ran_state, &stats);\n      CalculateStatistics(&stats);\n      lastrandomstep = i;\n    }\n    lastcost = cost;\n  }\n\n  free(length_array);\n  free(path);\n  free(costs);\n  ZopfliCleanLZ77Store(&currentstore);\n  ZopfliCleanHash(h);\n}\n\nvoid ZopfliLZ77OptimalFixed(ZopfliBlockState *s,\n                            const unsigned char* in,\n                            size_t instart, size_t inend,\n                            ZopfliLZ77Store* store)\n{\n  /* Dist to get to here with smallest cost. */\n  size_t blocksize = inend - instart;\n  unsigned short* length_array =\n      (unsigned short*)malloc(sizeof(unsigned short) * (blocksize + 1));\n  unsigned short* path = 0;\n  size_t pathsize = 0;\n  ZopfliHash hash;\n  ZopfliHash* h = &hash;\n  float* costs = (float*)malloc(sizeof(float) * (blocksize + 1));\n\n  if (!costs) exit(-1); /* Allocation failed. */\n  if (!length_array) exit(-1); /* Allocation failed. */\n\n  ZopfliAllocHash(ZOPFLI_WINDOW_SIZE, h);\n\n  s->blockstart = instart;\n  s->blockend = inend;\n\n  /* Shortest path for fixed tree This one should give the shortest possible\n  result for fixed tree, no repeated runs are needed since the tree is known. */\n  LZ77OptimalRun(s, in, instart, inend, &path, &pathsize,\n                 length_array, GetCostFixed, 0, store, h, costs);\n\n  free(length_array);\n  free(path);\n  free(costs);\n  ZopfliCleanHash(h);\n}\n"
  },
  {
    "path": "external/zopfli/squeeze.h",
    "content": "/*\nCopyright 2011 Google Inc. All Rights Reserved.\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n    http://www.apache.org/licenses/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n\nAuthor: lode.vandevenne@gmail.com (Lode Vandevenne)\nAuthor: jyrki.alakuijala@gmail.com (Jyrki Alakuijala)\n*/\n\n/*\nThe squeeze functions do enhanced LZ77 compression by optimal parsing with a\ncost model, rather than greedily choosing the longest length or using a single\nstep of lazy matching like regular implementations.\n\nSince the cost model is based on the Huffman tree that can only be calculated\nafter the LZ77 data is generated, there is a chicken and egg problem, and\nmultiple runs are done with updated cost models to converge to a better\nsolution.\n*/\n\n#ifndef ZOPFLI_SQUEEZE_H_\n#define ZOPFLI_SQUEEZE_H_\n\n#include \"lz77.h\"\n\n/*\nCalculates lit/len and dist pairs for given data.\nIf instart is larger than 0, it uses values before instart as starting\ndictionary.\n*/\nvoid ZopfliLZ77Optimal(ZopfliBlockState *s,\n                       const unsigned char* in, size_t instart, size_t inend,\n                       int numiterations,\n                       ZopfliLZ77Store* store);\n\n/*\nDoes the same as ZopfliLZ77Optimal, but optimized for the fixed tree of the\ndeflate standard.\nThe fixed tree never gives the best compression. But this gives the best\npossible LZ77 encoding possible with the fixed tree.\nThis does not create or output any fixed tree, only LZ77 data optimized for\nusing with a fixed tree.\nIf instart is larger than 0, it uses values before instart as starting\ndictionary.\n*/\nvoid ZopfliLZ77OptimalFixed(ZopfliBlockState *s,\n                            const unsigned char* in,\n                            size_t instart, size_t inend,\n                            ZopfliLZ77Store* store);\n\n#endif  /* ZOPFLI_SQUEEZE_H_ */\n"
  },
  {
    "path": "external/zopfli/symbols.h",
    "content": "/*\nCopyright 2016 Google Inc. All Rights Reserved.\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n    http://www.apache.org/licenses/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n\nAuthor: lode.vandevenne@gmail.com (Lode Vandevenne)\nAuthor: jyrki.alakuijala@gmail.com (Jyrki Alakuijala)\n*/\n\n/*\nUtilities for using the lz77 symbols of the deflate spec.\n*/\n\n#ifndef ZOPFLI_SYMBOLS_H_\n#define ZOPFLI_SYMBOLS_H_\n\n/* __has_builtin available in clang */\n#ifdef __has_builtin\n# if __has_builtin(__builtin_clz)\n#   define ZOPFLI_HAS_BUILTIN_CLZ\n# endif\n/* __builtin_clz available beginning with GCC 3.4 */\n#elif __GNUC__ * 100 + __GNUC_MINOR__ >= 304\n# define ZOPFLI_HAS_BUILTIN_CLZ\n#endif\n\n/* Gets the amount of extra bits for the given dist, cfr. the DEFLATE spec. */\nstatic int ZopfliGetDistExtraBits(int dist) {\n#ifdef ZOPFLI_HAS_BUILTIN_CLZ\n  if (dist < 5) return 0;\n  return (31 ^ __builtin_clz(dist - 1)) - 1; /* log2(dist - 1) - 1 */\n#else\n  if (dist < 5) return 0;\n  else if (dist < 9) return 1;\n  else if (dist < 17) return 2;\n  else if (dist < 33) return 3;\n  else if (dist < 65) return 4;\n  else if (dist < 129) return 5;\n  else if (dist < 257) return 6;\n  else if (dist < 513) return 7;\n  else if (dist < 1025) return 8;\n  else if (dist < 2049) return 9;\n  else if (dist < 4097) return 10;\n  else if (dist < 8193) return 11;\n  else if (dist < 16385) return 12;\n  else return 13;\n#endif\n}\n\n/* Gets value of the extra bits for the given dist, cfr. the DEFLATE spec. */\nstatic int ZopfliGetDistExtraBitsValue(int dist) {\n#ifdef ZOPFLI_HAS_BUILTIN_CLZ\n  if (dist < 5) {\n    return 0;\n  } else {\n    int l = 31 ^ __builtin_clz(dist - 1); /* log2(dist - 1) */\n    return (dist - (1 + (1 << l))) & ((1 << (l - 1)) - 1);\n  }\n#else\n  if (dist < 5) return 0;\n  else if (dist < 9) return (dist - 5) & 1;\n  else if (dist < 17) return (dist - 9) & 3;\n  else if (dist < 33) return (dist - 17) & 7;\n  else if (dist < 65) return (dist - 33) & 15;\n  else if (dist < 129) return (dist - 65) & 31;\n  else if (dist < 257) return (dist - 129) & 63;\n  else if (dist < 513) return (dist - 257) & 127;\n  else if (dist < 1025) return (dist - 513) & 255;\n  else if (dist < 2049) return (dist - 1025) & 511;\n  else if (dist < 4097) return (dist - 2049) & 1023;\n  else if (dist < 8193) return (dist - 4097) & 2047;\n  else if (dist < 16385) return (dist - 8193) & 4095;\n  else return (dist - 16385) & 8191;\n#endif\n}\n\n/* Gets the symbol for the given dist, cfr. the DEFLATE spec. */\nstatic int ZopfliGetDistSymbol(int dist) {\n#ifdef ZOPFLI_HAS_BUILTIN_CLZ\n  if (dist < 5) {\n    return dist - 1;\n  } else {\n    int l = (31 ^ __builtin_clz(dist - 1)); /* log2(dist - 1) */\n    int r = ((dist - 1) >> (l - 1)) & 1;\n    return l * 2 + r;\n  }\n#else\n  if (dist < 193) {\n    if (dist < 13) {  /* dist 0..13. */\n      if (dist < 5) return dist - 1;\n      else if (dist < 7) return 4;\n      else if (dist < 9) return 5;\n      else return 6;\n    } else {  /* dist 13..193. */\n      if (dist < 17) return 7;\n      else if (dist < 25) return 8;\n      else if (dist < 33) return 9;\n      else if (dist < 49) return 10;\n      else if (dist < 65) return 11;\n      else if (dist < 97) return 12;\n      else if (dist < 129) return 13;\n      else return 14;\n    }\n  } else {\n    if (dist < 2049) {  /* dist 193..2049. */\n      if (dist < 257) return 15;\n      else if (dist < 385) return 16;\n      else if (dist < 513) return 17;\n      else if (dist < 769) return 18;\n      else if (dist < 1025) return 19;\n      else if (dist < 1537) return 20;\n      else return 21;\n    } else {  /* dist 2049..32768. */\n      if (dist < 3073) return 22;\n      else if (dist < 4097) return 23;\n      else if (dist < 6145) return 24;\n      else if (dist < 8193) return 25;\n      else if (dist < 12289) return 26;\n      else if (dist < 16385) return 27;\n      else if (dist < 24577) return 28;\n      else return 29;\n    }\n  }\n#endif\n}\n\n/* Gets the amount of extra bits for the given length, cfr. the DEFLATE spec. */\nstatic int ZopfliGetLengthExtraBits(int l) {\n  static const int table[259] = {\n    0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1,\n    2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2,\n    3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3,\n    3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3,\n    4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4,\n    4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4,\n    4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4,\n    4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4,\n    5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5,\n    5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5,\n    5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5,\n    5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5,\n    5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5,\n    5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5,\n    5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5,\n    5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 0\n  };\n  return table[l];\n}\n\n/* Gets value of the extra bits for the given length, cfr. the DEFLATE spec. */\nstatic int ZopfliGetLengthExtraBitsValue(int l) {\n  static const int table[259] = {\n    0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 2, 3, 0,\n    1, 2, 3, 0, 1, 2, 3, 0, 1, 2, 3, 0, 1, 2, 3, 4, 5, 6, 7, 0, 1, 2, 3, 4, 5,\n    6, 7, 0, 1, 2, 3, 4, 5, 6, 7, 0, 1, 2, 3, 4, 5, 6, 7, 0, 1, 2, 3, 4, 5, 6,\n    7, 8, 9, 10, 11, 12, 13, 14, 15, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12,\n    13, 14, 15, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 0, 1, 2,\n    3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9,\n    10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28,\n    29, 30, 31, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17,\n    18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 0, 1, 2, 3, 4, 5, 6,\n    7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26,\n    27, 28, 29, 30, 31, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15,\n    16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 0\n  };\n  return table[l];\n}\n\n/*\nGets the symbol for the given length, cfr. the DEFLATE spec.\nReturns the symbol in the range [257-285] (inclusive)\n*/\nstatic int ZopfliGetLengthSymbol(int l) {\n  static const int table[259] = {\n    0, 0, 0, 257, 258, 259, 260, 261, 262, 263, 264,\n    265, 265, 266, 266, 267, 267, 268, 268,\n    269, 269, 269, 269, 270, 270, 270, 270,\n    271, 271, 271, 271, 272, 272, 272, 272,\n    273, 273, 273, 273, 273, 273, 273, 273,\n    274, 274, 274, 274, 274, 274, 274, 274,\n    275, 275, 275, 275, 275, 275, 275, 275,\n    276, 276, 276, 276, 276, 276, 276, 276,\n    277, 277, 277, 277, 277, 277, 277, 277,\n    277, 277, 277, 277, 277, 277, 277, 277,\n    278, 278, 278, 278, 278, 278, 278, 278,\n    278, 278, 278, 278, 278, 278, 278, 278,\n    279, 279, 279, 279, 279, 279, 279, 279,\n    279, 279, 279, 279, 279, 279, 279, 279,\n    280, 280, 280, 280, 280, 280, 280, 280,\n    280, 280, 280, 280, 280, 280, 280, 280,\n    281, 281, 281, 281, 281, 281, 281, 281,\n    281, 281, 281, 281, 281, 281, 281, 281,\n    281, 281, 281, 281, 281, 281, 281, 281,\n    281, 281, 281, 281, 281, 281, 281, 281,\n    282, 282, 282, 282, 282, 282, 282, 282,\n    282, 282, 282, 282, 282, 282, 282, 282,\n    282, 282, 282, 282, 282, 282, 282, 282,\n    282, 282, 282, 282, 282, 282, 282, 282,\n    283, 283, 283, 283, 283, 283, 283, 283,\n    283, 283, 283, 283, 283, 283, 283, 283,\n    283, 283, 283, 283, 283, 283, 283, 283,\n    283, 283, 283, 283, 283, 283, 283, 283,\n    284, 284, 284, 284, 284, 284, 284, 284,\n    284, 284, 284, 284, 284, 284, 284, 284,\n    284, 284, 284, 284, 284, 284, 284, 284,\n    284, 284, 284, 284, 284, 284, 284, 285\n  };\n  return table[l];\n}\n\n/* Gets the amount of extra bits for the given length symbol. */\nstatic int ZopfliGetLengthSymbolExtraBits(int s) {\n  static const int table[29] = {\n    0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 2, 2, 2, 2,\n    3, 3, 3, 3, 4, 4, 4, 4, 5, 5, 5, 5, 0\n  };\n  return table[s - 257];\n}\n\n/* Gets the amount of extra bits for the given distance symbol. */\nstatic int ZopfliGetDistSymbolExtraBits(int s) {\n  static const int table[30] = {\n    0, 0, 0, 0, 1, 1, 2, 2, 3, 3, 4, 4, 5, 5, 6, 6, 7, 7, 8, 8,\n    9, 9, 10, 10, 11, 11, 12, 12, 13, 13\n  };\n  return table[s];\n}\n\n#endif  /* ZOPFLI_SYMBOLS_H_ */\n"
  },
  {
    "path": "external/zopfli/tree.c",
    "content": "/*\nCopyright 2011 Google Inc. All Rights Reserved.\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n    http://www.apache.org/licenses/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n\nAuthor: lode.vandevenne@gmail.com (Lode Vandevenne)\nAuthor: jyrki.alakuijala@gmail.com (Jyrki Alakuijala)\n*/\n\n#include \"tree.h\"\n\n#include <assert.h>\n#include <math.h>\n#include <stdio.h>\n#include <stdlib.h>\n\n#include \"katajainen.h\"\n#include \"util.h\"\n\nvoid ZopfliLengthsToSymbols(const unsigned* lengths, size_t n, unsigned maxbits,\n                            unsigned* symbols) {\n  size_t* bl_count = (size_t*)malloc(sizeof(size_t) * (maxbits + 1));\n  size_t* next_code = (size_t*)malloc(sizeof(size_t) * (maxbits + 1));\n  unsigned bits, i;\n  unsigned code;\n\n  for (i = 0; i < n; i++) {\n    symbols[i] = 0;\n  }\n\n  /* 1) Count the number of codes for each code length. Let bl_count[N] be the\n  number of codes of length N, N >= 1. */\n  for (bits = 0; bits <= maxbits; bits++) {\n    bl_count[bits] = 0;\n  }\n  for (i = 0; i < n; i++) {\n    assert(lengths[i] <= maxbits);\n    bl_count[lengths[i]]++;\n  }\n  /* 2) Find the numerical value of the smallest code for each code length. */\n  code = 0;\n  bl_count[0] = 0;\n  for (bits = 1; bits <= maxbits; bits++) {\n    code = (code + bl_count[bits-1]) << 1;\n    next_code[bits] = code;\n  }\n  /* 3) Assign numerical values to all codes, using consecutive values for all\n  codes of the same length with the base values determined at step 2. */\n  for (i = 0;  i < n; i++) {\n    unsigned len = lengths[i];\n    if (len != 0) {\n      symbols[i] = next_code[len];\n      next_code[len]++;\n    }\n  }\n\n  free(bl_count);\n  free(next_code);\n}\n\nvoid ZopfliCalculateEntropy(const size_t* count, size_t n, double* bitlengths) {\n  static const double kInvLog2 = 1.4426950408889;  /* 1.0 / log(2.0) */\n  unsigned sum = 0;\n  unsigned i;\n  double log2sum;\n  for (i = 0; i < n; ++i) {\n    sum += count[i];\n  }\n  log2sum = (sum == 0 ? log(n) : log(sum)) * kInvLog2;\n  for (i = 0; i < n; ++i) {\n    /* When the count of the symbol is 0, but its cost is requested anyway, it\n    means the symbol will appear at least once anyway, so give it the cost as if\n    its count is 1.*/\n    if (count[i] == 0) bitlengths[i] = log2sum;\n    else bitlengths[i] = log2sum - log(count[i]) * kInvLog2;\n    /* Depending on compiler and architecture, the above subtraction of two\n    floating point numbers may give a negative result very close to zero\n    instead of zero (e.g. -5.973954e-17 with gcc 4.1.2 on Ubuntu 11.4). Clamp\n    it to zero. These floating point imprecisions do not affect the cost model\n    significantly so this is ok. */\n    if (bitlengths[i] < 0 && bitlengths[i] > -1e-5) bitlengths[i] = 0;\n    assert(bitlengths[i] >= 0);\n  }\n}\n\nvoid ZopfliCalculateBitLengths(const size_t* count, size_t n, int maxbits,\n                               unsigned* bitlengths) {\n  int error = ZopfliLengthLimitedCodeLengths(count, n, maxbits, bitlengths);\n  (void) error;\n  assert(!error);\n}\n"
  },
  {
    "path": "external/zopfli/tree.h",
    "content": "/*\nCopyright 2011 Google Inc. All Rights Reserved.\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n    http://www.apache.org/licenses/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n\nAuthor: lode.vandevenne@gmail.com (Lode Vandevenne)\nAuthor: jyrki.alakuijala@gmail.com (Jyrki Alakuijala)\n*/\n\n/*\nUtilities for creating and using Huffman trees.\n*/\n\n#ifndef ZOPFLI_TREE_H_\n#define ZOPFLI_TREE_H_\n\n#include <string.h>\n\n/*\nCalculates the bitlengths for the Huffman tree, based on the counts of each\nsymbol.\n*/\nvoid ZopfliCalculateBitLengths(const size_t* count, size_t n, int maxbits,\n                               unsigned *bitlengths);\n\n/*\nConverts a series of Huffman tree bitlengths, to the bit values of the symbols.\n*/\nvoid ZopfliLengthsToSymbols(const unsigned* lengths, size_t n, unsigned maxbits,\n                            unsigned* symbols);\n\n/*\nCalculates the entropy of each symbol, based on the counts of each symbol. The\nresult is similar to the result of ZopfliCalculateBitLengths, but with the\nactual theoritical bit lengths according to the entropy. Since the resulting\nvalues are fractional, they cannot be used to encode the tree specified by\nDEFLATE.\n*/\nvoid ZopfliCalculateEntropy(const size_t* count, size_t n, double* bitlengths);\n\n#endif  /* ZOPFLI_TREE_H_ */\n"
  },
  {
    "path": "external/zopfli/util.c",
    "content": "/*\nCopyright 2011 Google Inc. All Rights Reserved.\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n    http://www.apache.org/licenses/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n\nAuthor: lode.vandevenne@gmail.com (Lode Vandevenne)\nAuthor: jyrki.alakuijala@gmail.com (Jyrki Alakuijala)\n*/\n\n#include \"util.h\"\n\n#include \"zopfli.h\"\n\n#include <assert.h>\n#include <stdio.h>\n#include <stdlib.h>\n\nvoid ZopfliInitOptions(ZopfliOptions* options) {\n  options->verbose = 0;\n  options->verbose_more = 0;\n  options->numiterations = 15;\n  options->blocksplitting = 1;\n  options->blocksplittinglast = 0;\n  options->blocksplittingmax = 15;\n}\n"
  },
  {
    "path": "external/zopfli/util.h",
    "content": "/*\nCopyright 2011 Google Inc. All Rights Reserved.\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n    http://www.apache.org/licenses/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n\nAuthor: lode.vandevenne@gmail.com (Lode Vandevenne)\nAuthor: jyrki.alakuijala@gmail.com (Jyrki Alakuijala)\n*/\n\n/*\nSeveral utilities, including: #defines to try different compression results,\nbasic deflate specification values and generic program options.\n*/\n\n#ifndef ZOPFLI_UTIL_H_\n#define ZOPFLI_UTIL_H_\n\n#include <string.h>\n#include <stdlib.h>\n\n/* Minimum and maximum length that can be encoded in deflate. */\n#define ZOPFLI_MAX_MATCH 258\n#define ZOPFLI_MIN_MATCH 3\n\n/* Number of distinct literal/length and distance symbols in DEFLATE */\n#define ZOPFLI_NUM_LL 288\n#define ZOPFLI_NUM_D 32\n\n/*\nThe window size for deflate. Must be a power of two. This should be 32768, the\nmaximum possible by the deflate spec. Anything less hurts compression more than\nspeed.\n*/\n#define ZOPFLI_WINDOW_SIZE 32768\n\n/*\nThe window mask used to wrap indices into the window. This is why the\nwindow size must be a power of two.\n*/\n#define ZOPFLI_WINDOW_MASK (ZOPFLI_WINDOW_SIZE - 1)\n\n/*\nA block structure of huge, non-smart, blocks to divide the input into, to allow\noperating on huge files without exceeding memory, such as the 1GB wiki9 corpus.\nThe whole compression algorithm, including the smarter block splitting, will\nbe executed independently on each huge block.\nDividing into huge blocks hurts compression, but not much relative to the size.\nSet it to 0 to disable master blocks.\n*/\n#define ZOPFLI_MASTER_BLOCK_SIZE 1000000\n\n/*\nUsed to initialize costs for example\n*/\n#define ZOPFLI_LARGE_FLOAT 1e30\n\n/*\nFor longest match cache. max 256. Uses huge amounts of memory but makes it\nfaster. Uses this many times three bytes per single byte of the input data.\nThis is so because longest match finding has to find the exact distance\nthat belongs to each length for the best lz77 strategy.\nGood values: e.g. 5, 8.\n*/\n#define ZOPFLI_CACHE_LENGTH 8\n\n/*\nlimit the max hash chain hits for this hash value. This has an effect only\non files where the hash value is the same very often. On these files, this\ngives worse compression (the value should ideally be 32768, which is the\nZOPFLI_WINDOW_SIZE, while zlib uses 4096 even for best level), but makes it\nfaster on some specific files.\nGood value: e.g. 8192.\n*/\n#define ZOPFLI_MAX_CHAIN_HITS 8192\n\n/*\nWhether to use the longest match cache for ZopfliFindLongestMatch. This cache\nconsumes a lot of memory but speeds it up. No effect on compression size.\n*/\n#define ZOPFLI_LONGEST_MATCH_CACHE\n\n/*\nEnable to remember amount of successive identical bytes in the hash chain for\nfinding longest match\nrequired for ZOPFLI_HASH_SAME_HASH and ZOPFLI_SHORTCUT_LONG_REPETITIONS\nThis has no effect on the compression result, and enabling it increases speed.\n*/\n#define ZOPFLI_HASH_SAME\n\n/*\nSwitch to a faster hash based on the info from ZOPFLI_HASH_SAME once the\nbest length so far is long enough. This is way faster for files with lots of\nidentical bytes, on which the compressor is otherwise too slow. Regular files\nare unaffected or maybe a tiny bit slower.\nThis has no effect on the compression result, only on speed.\n*/\n#define ZOPFLI_HASH_SAME_HASH\n\n/*\nEnable this, to avoid slowness for files which are a repetition of the same\ncharacter more than a multiple of ZOPFLI_MAX_MATCH times. This should not affect\nthe compression result.\n*/\n#define ZOPFLI_SHORTCUT_LONG_REPETITIONS\n\n/*\nWhether to use lazy matching in the greedy LZ77 implementation. This gives a\nbetter result of ZopfliLZ77Greedy, but the effect this has on the optimal LZ77\nvaries from file to file.\n*/\n#define ZOPFLI_LAZY_MATCHING\n\n/*\nAppends value to dynamically allocated memory, doubling its allocation size\nwhenever needed.\n\nvalue: the value to append, type T\ndata: pointer to the dynamic array to append to, type T**\nsize: pointer to the size of the array to append to, type size_t*. This is the\nsize that you consider the array to be, not the internal allocation size.\nPrecondition: allocated size of data is at least a power of two greater than or\nequal than *size.\n*/\n#ifdef __cplusplus /* C++ cannot assign void* from malloc to *data */\n#define ZOPFLI_APPEND_DATA(/* T */ value, /* T** */ data, /* size_t* */ size) {\\\n  if (!((*size) & ((*size) - 1))) {\\\n    /*double alloc size if it's a power of two*/\\\n    void** data_void = reinterpret_cast<void**>(data);\\\n    *data_void = (*size) == 0 ? malloc(sizeof(**data))\\\n                              : realloc((*data), (*size) * 2 * sizeof(**data));\\\n  }\\\n  (*data)[(*size)] = (value);\\\n  (*size)++;\\\n}\n#else /* C gives problems with strict-aliasing rules for (void**) cast */\n#define ZOPFLI_APPEND_DATA(/* T */ value, /* T** */ data, /* size_t* */ size) {\\\n  if (!((*size) & ((*size) - 1))) {\\\n    /*double alloc size if it's a power of two*/\\\n    (*data) = (*size) == 0 ? malloc(sizeof(**data))\\\n                           : realloc((*data), (*size) * 2 * sizeof(**data));\\\n  }\\\n  (*data)[(*size)] = (value);\\\n  (*size)++;\\\n}\n#endif\n\n\n#endif  /* ZOPFLI_UTIL_H_ */\n"
  },
  {
    "path": "external/zopfli/zlib_container.c",
    "content": "/*\nCopyright 2013 Google Inc. All Rights Reserved.\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n    http://www.apache.org/licenses/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n\nAuthor: lode.vandevenne@gmail.com (Lode Vandevenne)\nAuthor: jyrki.alakuijala@gmail.com (Jyrki Alakuijala)\n*/\n\n#include \"zlib_container.h\"\n#include \"util.h\"\n\n#include <stdio.h>\n\n#include \"deflate.h\"\n\n\n/* Calculates the adler32 checksum of the data */\nstatic unsigned adler32(const unsigned char* data, size_t size)\n{\n  static const unsigned sums_overflow = 5550;\n  unsigned s1 = 1;\n  unsigned s2 = 1 >> 16;\n\n  while (size > 0) {\n    size_t amount = size > sums_overflow ? sums_overflow : size;\n    size -= amount;\n    while (amount > 0) {\n      s1 += (*data++);\n      s2 += s1;\n      amount--;\n    }\n    s1 %= 65521;\n    s2 %= 65521;\n  }\n\n  return (s2 << 16) | s1;\n}\n\nvoid ZopfliZlibCompress(const ZopfliOptions* options,\n                        const unsigned char* in, size_t insize,\n                        unsigned char** out, size_t* outsize) {\n  unsigned char bitpointer = 0;\n  unsigned checksum = adler32(in, (unsigned)insize);\n  unsigned cmf = 120;  /* CM 8, CINFO 7. See zlib spec.*/\n  unsigned flevel = 3;\n  unsigned fdict = 0;\n  unsigned cmfflg = 256 * cmf + fdict * 32 + flevel * 64;\n  unsigned fcheck = 31 - cmfflg % 31;\n  cmfflg += fcheck;\n\n  ZOPFLI_APPEND_DATA(cmfflg / 256, out, outsize);\n  ZOPFLI_APPEND_DATA(cmfflg % 256, out, outsize);\n\n  ZopfliDeflate(options, 2 /* dynamic block */, 1 /* final */,\n                in, insize, &bitpointer, out, outsize);\n\n  ZOPFLI_APPEND_DATA((checksum >> 24) % 256, out, outsize);\n  ZOPFLI_APPEND_DATA((checksum >> 16) % 256, out, outsize);\n  ZOPFLI_APPEND_DATA((checksum >> 8) % 256, out, outsize);\n  ZOPFLI_APPEND_DATA(checksum % 256, out, outsize);\n\n  if (options->verbose) {\n    fprintf(stderr,\n            \"Original Size: %d, Zlib: %d, Compression: %f%% Removed\\n\",\n            (int)insize, (int)*outsize,\n            100.0 * (double)(insize - *outsize) / (double)insize);\n  }\n}\n"
  },
  {
    "path": "external/zopfli/zlib_container.h",
    "content": "/*\nCopyright 2013 Google Inc. All Rights Reserved.\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n    http://www.apache.org/licenses/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n\nAuthor: lode.vandevenne@gmail.com (Lode Vandevenne)\nAuthor: jyrki.alakuijala@gmail.com (Jyrki Alakuijala)\n*/\n\n#ifndef ZOPFLI_ZLIB_H_\n#define ZOPFLI_ZLIB_H_\n\n/*\nFunctions to compress according to the Zlib specification.\n*/\n\n#include \"zopfli.h\"\n\n#ifdef __cplusplus\nextern \"C\" {\n#endif\n\n/*\nCompresses according to the zlib specification and append the compressed\nresult to the output.\n\noptions: global program options\nout: pointer to the dynamic output array to which the result is appended. Must\n  be freed after use.\noutsize: pointer to the dynamic output array size.\n*/\nvoid ZopfliZlibCompress(const ZopfliOptions* options,\n                        const unsigned char* in, size_t insize,\n                        unsigned char** out, size_t* outsize);\n\n#ifdef __cplusplus\n}  // extern \"C\"\n#endif\n\n#endif  /* ZOPFLI_ZLIB_H_ */\n"
  },
  {
    "path": "external/zopfli/zopfli.h",
    "content": "/*\nCopyright 2011 Google Inc. All Rights Reserved.\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n    http://www.apache.org/licenses/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n\nAuthor: lode.vandevenne@gmail.com (Lode Vandevenne)\nAuthor: jyrki.alakuijala@gmail.com (Jyrki Alakuijala)\n*/\n\n#ifndef ZOPFLI_ZOPFLI_H_\n#define ZOPFLI_ZOPFLI_H_\n\n#include <stddef.h>\n#include <stdlib.h> /* for size_t */\n\n#ifdef __cplusplus\nextern \"C\" {\n#endif\n\n/*\nOptions used throughout the program.\n*/\ntypedef struct ZopfliOptions {\n  /* Whether to print output */\n  int verbose;\n\n  /* Whether to print more detailed output */\n  int verbose_more;\n\n  /*\n  Maximum amount of times to rerun forward and backward pass to optimize LZ77\n  compression cost. Good values: 10, 15 for small files, 5 for files over\n  several MB in size or it will be too slow.\n  */\n  int numiterations;\n\n  /*\n  If true, splits the data in multiple deflate blocks with optimal choice\n  for the block boundaries. Block splitting gives better compression. Default:\n  true (1).\n  */\n  int blocksplitting;\n\n  /*\n  No longer used, left for compatibility.\n  */\n  int blocksplittinglast;\n\n  /*\n  Maximum amount of blocks to split into (0 for unlimited, but this can give\n  extreme results that hurt compression on some files). Default value: 15.\n  */\n  int blocksplittingmax;\n} ZopfliOptions;\n\n/* Initializes options with default values. */\nvoid ZopfliInitOptions(ZopfliOptions* options);\n\n/* Output format */\ntypedef enum {\n  ZOPFLI_FORMAT_GZIP,\n  ZOPFLI_FORMAT_ZLIB,\n  ZOPFLI_FORMAT_DEFLATE\n} ZopfliFormat;\n\n/*\nCompresses according to the given output format and appends the result to the\noutput.\n\noptions: global program options\noutput_type: the output format to use\nout: pointer to the dynamic output array to which the result is appended. Must\n  be freed after use\noutsize: pointer to the dynamic output array size\n*/\nvoid ZopfliCompress(const ZopfliOptions* options, ZopfliFormat output_type,\n                    const unsigned char* in, size_t insize,\n                    unsigned char** out, size_t* outsize);\n\n#ifdef __cplusplus\n}  // extern \"C\"\n#endif\n\n#endif  /* ZOPFLI_ZOPFLI_H_ */\n"
  },
  {
    "path": "external/zopfli/zopfli_bin.c",
    "content": "/*\nCopyright 2011 Google Inc. All Rights Reserved.\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n    http://www.apache.org/licenses/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n\nAuthor: lode.vandevenne@gmail.com (Lode Vandevenne)\nAuthor: jyrki.alakuijala@gmail.com (Jyrki Alakuijala)\n*/\n\n/*\nZopfli compressor program. It can output gzip-, zlib- or deflate-compatible\ndata. By default it creates a .gz file. This tool can only compress, not\ndecompress. Decompression can be done by any standard gzip, zlib or deflate\ndecompressor.\n*/\n\n#include <assert.h>\n#include <stdio.h>\n#include <stdlib.h>\n#include <string.h>\n\n#include \"deflate.h\"\n#include \"gzip_container.h\"\n#include \"zlib_container.h\"\n\n/* Windows workaround for stdout output. */\n#if _WIN32\n#include <fcntl.h>\n#endif\n\n/*\nLoads a file into a memory array. Returns 1 on success, 0 if file doesn't exist\nor couldn't be opened.\n*/\nstatic int LoadFile(const char* filename,\n                    unsigned char** out, size_t* outsize) {\n  FILE* file;\n\n  *out = 0;\n  *outsize = 0;\n  file = fopen(filename, \"rb\");\n  if (!file) return 0;\n\n  fseek(file , 0 , SEEK_END);\n  *outsize = ftell(file);\n  if(*outsize > 2147483647) {\n    fprintf(stderr,\"Files larger than 2GB are not supported.\\n\");\n    exit(EXIT_FAILURE);\n  }\n  rewind(file);\n\n  *out = (unsigned char*)malloc(*outsize);\n\n  if (*outsize && (*out)) {\n    size_t testsize = fread(*out, 1, *outsize, file);\n    if (testsize != *outsize) {\n      /* It could be a directory */\n      free(*out);\n      *out = 0;\n      *outsize = 0;\n      fclose(file);\n      return 0;\n    }\n  }\n\n  assert(!(*outsize) || out);  /* If size is not zero, out must be allocated. */\n  fclose(file);\n  return 1;\n}\n\n/*\nSaves a file from a memory array, overwriting the file if it existed.\n*/\nstatic void SaveFile(const char* filename,\n                     const unsigned char* in, size_t insize) {\n  FILE* file = fopen(filename, \"wb\" );\n  if (file == NULL) {\n      fprintf(stderr,\"Error: Cannot write to output file, terminating.\\n\");\n      exit (EXIT_FAILURE);\n  }\n  assert(file);\n  fwrite((char*)in, 1, insize, file);\n  fclose(file);\n}\n\n/*\noutfilename: filename to write output to, or 0 to write to stdout instead\n*/\nstatic void CompressFile(const ZopfliOptions* options,\n                         ZopfliFormat output_type,\n                         const char* infilename,\n                         const char* outfilename) {\n  unsigned char* in;\n  size_t insize;\n  unsigned char* out = 0;\n  size_t outsize = 0;\n  if (!LoadFile(infilename, &in, &insize)) {\n    fprintf(stderr, \"Invalid filename: %s\\n\", infilename);\n    return;\n  }\n\n  ZopfliCompress(options, output_type, in, insize, &out, &outsize);\n\n  if (outfilename) {\n    SaveFile(outfilename, out, outsize);\n  } else {\n#if _WIN32\n    /* Windows workaround for stdout output. */\n    _setmode(_fileno(stdout), _O_BINARY);\n#endif\n    fwrite(out, 1, outsize, stdout);\n  }\n\n  free(out);\n  free(in);\n}\n\n/*\nAdd two strings together. Size does not matter. Result must be freed.\n*/\nstatic char* AddStrings(const char* str1, const char* str2) {\n  size_t len = strlen(str1) + strlen(str2);\n  char* result = (char*)malloc(len + 1);\n  if (!result) exit(-1); /* Allocation failed. */\n  strcpy(result, str1);\n  strcat(result, str2);\n  return result;\n}\n\nstatic char StringsEqual(const char* str1, const char* str2) {\n  return strcmp(str1, str2) == 0;\n}\n\nint main(int argc, char* argv[]) {\n  ZopfliOptions options;\n  ZopfliFormat output_type = ZOPFLI_FORMAT_GZIP;\n  const char* filename = 0;\n  int output_to_stdout = 0;\n  int i;\n\n  ZopfliInitOptions(&options);\n\n  for (i = 1; i < argc; i++) {\n    const char* arg = argv[i];\n    if (StringsEqual(arg, \"-v\")) options.verbose = 1;\n    else if (StringsEqual(arg, \"-c\")) output_to_stdout = 1;\n    else if (StringsEqual(arg, \"--deflate\")) {\n      output_type = ZOPFLI_FORMAT_DEFLATE;\n    }\n    else if (StringsEqual(arg, \"--zlib\")) output_type = ZOPFLI_FORMAT_ZLIB;\n    else if (StringsEqual(arg, \"--gzip\")) output_type = ZOPFLI_FORMAT_GZIP;\n    else if (StringsEqual(arg, \"--splitlast\"))  /* Ignore */;\n    else if (arg[0] == '-' && arg[1] == '-' && arg[2] == 'i'\n        && arg[3] >= '0' && arg[3] <= '9') {\n      options.numiterations = atoi(arg + 3);\n    }\n    else if (StringsEqual(arg, \"-h\")) {\n      fprintf(stderr,\n          \"Usage: zopfli [OPTION]... FILE...\\n\"\n          \"  -h    gives this help\\n\"\n          \"  -c    write the result on standard output, instead of disk\"\n          \" filename + '.gz'\\n\"\n          \"  -v    verbose mode\\n\"\n          \"  --i#  perform # iterations (default 15). More gives\"\n          \" more compression but is slower.\"\n          \" Examples: --i10, --i50, --i1000\\n\");\n      fprintf(stderr,\n          \"  --gzip        output to gzip format (default)\\n\"\n          \"  --zlib        output to zlib format instead of gzip\\n\"\n          \"  --deflate     output to deflate format instead of gzip\\n\"\n          \"  --splitlast   ignored, left for backwards compatibility\\n\");\n      return 0;\n    }\n  }\n\n  if (options.numiterations < 1) {\n    fprintf(stderr, \"Error: must have 1 or more iterations\\n\");\n    return 0;\n  }\n\n  for (i = 1; i < argc; i++) {\n    if (argv[i][0] != '-') {\n      char* outfilename;\n      filename = argv[i];\n      if (output_to_stdout) {\n        outfilename = 0;\n      } else if (output_type == ZOPFLI_FORMAT_GZIP) {\n        outfilename = AddStrings(filename, \".gz\");\n      } else if (output_type == ZOPFLI_FORMAT_ZLIB) {\n        outfilename = AddStrings(filename, \".zlib\");\n      } else {\n        assert(output_type == ZOPFLI_FORMAT_DEFLATE);\n        outfilename = AddStrings(filename, \".deflate\");\n      }\n      if (options.verbose && outfilename) {\n        fprintf(stderr, \"Saving to: %s\\n\", outfilename);\n      }\n      CompressFile(&options, output_type, filename, outfilename);\n      free(outfilename);\n    }\n  }\n\n  if (!filename) {\n    fprintf(stderr,\n            \"Please provide filename\\nFor help, type: %s -h\\n\", argv[0]);\n  }\n\n  return 0;\n}\n"
  },
  {
    "path": "external/zopfli/zopfli_lib.c",
    "content": "/*\nCopyright 2011 Google Inc. All Rights Reserved.\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n    http://www.apache.org/licenses/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n\nAuthor: lode.vandevenne@gmail.com (Lode Vandevenne)\nAuthor: jyrki.alakuijala@gmail.com (Jyrki Alakuijala)\n*/\n\n#include \"zopfli.h\"\n\n#include \"deflate.h\"\n#include \"gzip_container.h\"\n#include \"zlib_container.h\"\n\n#include <assert.h>\n\nvoid ZopfliCompress(const ZopfliOptions* options, ZopfliFormat output_type,\n                    const unsigned char* in, size_t insize,\n                    unsigned char** out, size_t* outsize) {\n  if (output_type == ZOPFLI_FORMAT_GZIP) {\n    ZopfliGzipCompress(options, in, insize, out, outsize);\n  } else if (output_type == ZOPFLI_FORMAT_ZLIB) {\n    ZopfliZlibCompress(options, in, insize, out, outsize);\n  } else if (output_type == ZOPFLI_FORMAT_DEFLATE) {\n    unsigned char bp = 0;\n    ZopfliDeflate(options, 2 /* Dynamic block */, 1,\n                  in, insize, &bp, out, outsize);\n  } else {\n    assert(0);\n  }\n}\n"
  },
  {
    "path": "format.cpp",
    "content": "#include \"format.hpp\"\n\nName2Fmt name2fmt;\nFmt2Name fmt2name;\nFmt2Ext fmt2ext;\n\n#define CHECKED_MATCH(s) (len >= (sizeof(s) - 1) && BUFFER_MATCH(buf, s))\n\nformat_t check_fmt(const void *buf, size_t len) {\n    if (CHECKED_MATCH(CHROMEOS_MAGIC)) {\n        return CHROMEOS;\n    } else if (CHECKED_MATCH(BOOT_MAGIC)) {\n        return AOSP;\n    } else if (CHECKED_MATCH(VENDOR_BOOT_MAGIC)) {\n        return AOSP_VENDOR;\n    } else if (CHECKED_MATCH(GZIP1_MAGIC) || CHECKED_MATCH(GZIP2_MAGIC)) {\n        return GZIP;\n    } else if (CHECKED_MATCH(LZOP_MAGIC)) {\n        return LZOP;\n    } else if (CHECKED_MATCH(XZ_MAGIC)) {\n        return XZ;\n    } else if (len >= 13 && memcmp(buf, \"\\x5d\\x00\\x00\", 3) == 0\n            && (((char *)buf)[12] == '\\xff' || ((char *)buf)[12] == '\\x00')) {\n        return LZMA;\n    } else if (CHECKED_MATCH(BZIP_MAGIC)) {\n        return BZIP2;\n    } else if (CHECKED_MATCH(LZ41_MAGIC) || CHECKED_MATCH(LZ42_MAGIC)) {\n        return LZ4;\n    } else if (CHECKED_MATCH(LZ4_LEG_MAGIC)) {\n        return LZ4_LEGACY;\n    } else if (CHECKED_MATCH(MTK_MAGIC)) {\n        return MTK;\n    } else if (CHECKED_MATCH(DTB_MAGIC)) {\n        return DTB;\n    } else if (CHECKED_MATCH(DHTB_MAGIC)) {\n        return DHTB;\n    } else if (CHECKED_MATCH(TEGRABLOB_MAGIC)) {\n        return BLOB_FMT;\n    } else if (len >= 0x28 && memcmp(&((char *)buf)[0x24], ZIMAGE_MAGIC, 4) == 0) {\n        return ZIMAGE;\n    } else {\n        return UNKNOWN;\n    }\n}\n\nconst char *Fmt2Name::operator[](format_t fmt) {\n    switch (fmt) {\n        case GZIP:\n            return \"gzip\";\n        case ZOPFLI:\n            return \"zopfli\";\n        case LZOP:\n            return \"lzop\";\n        case XZ:\n            return \"xz\";\n        case LZMA:\n            return \"lzma\";\n        case BZIP2:\n            return \"bzip2\";\n        case LZ4:\n            return \"lz4\";\n        case LZ4_LEGACY:\n            return \"lz4_legacy\";\n        case LZ4_LG:\n            return \"lz4_lg\";\n        case DTB:\n            return \"dtb\";\n        case ZIMAGE:\n            return \"zimage\";\n        default:\n            return \"raw\";\n    }\n}\n\nconst char *Fmt2Ext::operator[](format_t fmt) {\n    switch (fmt) {\n        case GZIP:\n        case ZOPFLI:\n            return \".gz\";\n        case LZOP:\n            return \".lzo\";\n        case XZ:\n            return \".xz\";\n        case LZMA:\n            return \".lzma\";\n        case BZIP2:\n            return \".bz2\";\n        case LZ4:\n        case LZ4_LEGACY:\n        case LZ4_LG:\n            return \".lz4\";\n        default:\n            return \"\";\n    }\n}\n\n#define CHECK(s, f) else if (name == s) return f;\n\nformat_t Name2Fmt::operator[](std::string_view name) {\n    if (0) {}\n    CHECK(\"gzip\", GZIP)\n    CHECK(\"zopfli\", ZOPFLI)\n    CHECK(\"xz\", XZ)\n    CHECK(\"lzma\", LZMA)\n    CHECK(\"bzip2\", BZIP2)\n    CHECK(\"lz4\", LZ4)\n    CHECK(\"lz4_legacy\", LZ4_LEGACY)\n    CHECK(\"lz4_lg\", LZ4_LG)\n    else return UNKNOWN;\n}\n"
  },
  {
    "path": "format.hpp",
    "content": "#pragma once\n\n#include <string_view>\n\ntypedef enum {\n    UNKNOWN,\n/* Boot formats */\n    CHROMEOS,\n    AOSP,\n    AOSP_VENDOR,\n    DHTB,\n    BLOB_FMT,\n/* Compression formats */\n    GZIP,\n    ZOPFLI,\n    XZ,\n    LZMA,\n    BZIP2,\n    LZ4,\n    LZ4_LEGACY,\n    LZ4_LG,\n/* Unsupported compression */\n    LZOP,\n/* Misc */\n    MTK,\n    DTB,\n    ZIMAGE,\n} format_t;\n\n#define COMPRESSED(fmt)      ((fmt) >= GZIP && (fmt) < LZOP)\n#define COMPRESSED_ANY(fmt)  ((fmt) >= GZIP && (fmt) <= LZOP)\n\n#define BUFFER_MATCH(buf, s) (memcmp(buf, s, sizeof(s) - 1) == 0)\n#define BUFFER_CONTAIN(buf, sz, s) (memmem(buf, sz, s, sizeof(s) - 1) != nullptr)\n\n#define BOOT_MAGIC      \"ANDROID!\"\n#define VENDOR_BOOT_MAGIC \"VNDRBOOT\"\n#define CHROMEOS_MAGIC  \"CHROMEOS\"\n#define GZIP1_MAGIC     \"\\x1f\\x8b\"\n#define GZIP2_MAGIC     \"\\x1f\\x9e\"\n#define LZOP_MAGIC      \"\\x89\"\"LZO\"\n#define XZ_MAGIC        \"\\xfd\"\"7zXZ\"\n#define BZIP_MAGIC      \"BZh\"\n#define LZ4_LEG_MAGIC   \"\\x02\\x21\\x4c\\x18\"\n#define LZ41_MAGIC      \"\\x03\\x21\\x4c\\x18\"\n#define LZ42_MAGIC      \"\\x04\\x22\\x4d\\x18\"\n#define MTK_MAGIC       \"\\x88\\x16\\x88\\x58\"\n#define DTB_MAGIC       \"\\xd0\\x0d\\xfe\\xed\"\n#define LG_BUMP_MAGIC   \"\\x41\\xa9\\xe4\\x67\\x74\\x4d\\x1d\\x1b\\xa4\\x29\\xf2\\xec\\xea\\x65\\x52\\x79\"\n#define DHTB_MAGIC      \"\\x44\\x48\\x54\\x42\\x01\\x00\\x00\\x00\"\n#define SEANDROID_MAGIC \"SEANDROIDENFORCE\"\n#define TEGRABLOB_MAGIC \"-SIGNED-BY-SIGNBLOB-\"\n#define NOOKHD_RL_MAGIC \"Red Loader\"\n#define NOOKHD_GL_MAGIC \"Green Loader\"\n#define NOOKHD_GR_MAGIC \"Green Recovery\"\n#define NOOKHD_EB_MAGIC \"eMMC boot.img+secondloader\"\n#define NOOKHD_ER_MAGIC \"eMMC recovery.img+secondloader\"\n#define NOOKHD_PRE_HEADER_SZ 1048576\n#define ACCLAIM_MAGIC   \"BauwksBoot\"\n#define ACCLAIM_PRE_HEADER_SZ 262144\n#define AMONET_MICROLOADER_MAGIC \"microloader\"\n#define AMONET_MICROLOADER_SZ 1024\n#define AVB_FOOTER_MAGIC \"AVBf\"\n#define AVB_MAGIC \"AVB0\"\n#define ZIMAGE_MAGIC \"\\x18\\x28\\x6f\\x01\"\n\nclass Fmt2Name {\npublic:\n    const char *operator[](format_t fmt);\n};\n\nclass Fmt2Ext {\npublic:\n    const char *operator[](format_t fmt);\n};\n\nclass Name2Fmt {\npublic:\n    format_t operator[](std::string_view name);\n};\n\nformat_t check_fmt(const void *buf, size_t len);\n\nextern Name2Fmt name2fmt;\nextern Fmt2Name fmt2name;\nextern Fmt2Ext fmt2ext;\n"
  },
  {
    "path": "hexpatch.cpp",
    "content": "#include <sys/mman.h>\n\n#include <base.hpp>\n\n#include \"magiskboot.hpp\"\n\nusing namespace std;\n\nstatic void hex2byte(const char *hex, uint8_t *buf) {\n    char high, low;\n    for (int i = 0, length = strlen(hex); i < length; i += 2) {\n        high = toupper(hex[i]) - '0';\n        low = toupper(hex[i + 1]) - '0';\n        buf[i / 2] = ((high > 9 ? high - 7 : high) << 4) + (low > 9 ? low - 7 : low);\n    }\n}\n\nint hexpatch(const char *file, const char *from, const char *to) {\n    int patched = 1;\n\n    auto m = mmap_data(file, true);\n\n    vector<uint8_t> pattern(strlen(from) / 2);\n    vector<uint8_t> patch(strlen(to) / 2);\n\n    hex2byte(from, pattern.data());\n    hex2byte(to, patch.data());\n\n    uint8_t * const end = m.buf + m.sz;\n    for (uint8_t *curr = m.buf; curr < end; curr += pattern.size()) {\n        curr = static_cast<uint8_t*>(memmem(curr, end - curr, pattern.data(), pattern.size()));\n        if (curr == nullptr)\n            return patched;\n        fprintf(stderr, \"Patch @ %08X [%s] -> [%s]\\n\", (unsigned)(curr - m.buf), from, to);\n        memset(curr, 0, pattern.size());\n        memcpy(curr, patch.data(), patch.size());\n        patched = 0;\n    }\n\n    return patched;\n}\n"
  },
  {
    "path": "magiskbase/files.cpp",
    "content": "#ifndef SVB_WIN32\n#include <sys/sendfile.h>\n#include <linux/fs.h>\n#endif\n\n#include <fcntl.h>\n#include <unistd.h>\n#include <libgen.h>\n\n#include <base.hpp>\n#ifndef SVB_WIN32\n#include <selinux.hpp>\n#endif\n\nusing namespace std;\n\n#ifdef SVB_MINGW\n#include \"libnt.h\"\n#define mkdir(y, x) mkdir(y)\n#endif\n\n#ifndef SVB_WIN32\nssize_t fd_path(int fd, char *path, size_t size) {\n    snprintf(path, size, \"/proc/self/fd/%d\", fd);\n    return xreadlink(path, path, size);\n}\n\nint fd_pathat(int dirfd, const char *name, char *path, size_t size) {\n    if (fd_path(dirfd, path, size) < 0)\n        return -1;\n    auto len = strlen(path);\n    path[len] = '/';\n    strlcpy(path + len + 1, name, size - len - 1);\n    return 0;\n}\n#endif\n\nint mkdirs(const char *path, mode_t mode) {\n    char buf[4096];\n    strlcpy(buf, path, sizeof(buf));\n    errno = 0;\n    for (char *p = &buf[1]; *p; ++p) {\n        if (*p == '/') {\n            *p = '\\0';\n            if (mkdir(buf, mode) == -1) {\n                if (errno != EEXIST)\n                    return -1;\n            }\n            *p = '/';\n        }\n    }\n    if (mkdir(buf, mode) == -1) {\n        if (errno != EEXIST)\n            return -1;\n    }\n    return 0;\n}\n\n#ifndef SVB_MINGW\ntemplate <typename Func>\nstatic void post_order_walk(int dirfd, const Func &fn) {\n    auto dir = xopen_dir(dirfd);\n    if (!dir) return;\n\n    for (dirent *entry; (entry = xreaddir(dir.get()));) {\n        if (entry->d_type == DT_DIR)\n            post_order_walk(xopenat(dirfd, entry->d_name, O_RDONLY | O_CLOEXEC), fn);\n        fn(dirfd, entry);\n    }\n}\n\nenum walk_result {\n    CONTINUE, SKIP, ABORT\n};\n\ntemplate <typename Func>\nstatic walk_result pre_order_walk(int dirfd, const Func &fn) {\n    auto dir = xopen_dir(dirfd);\n    if (!dir) {\n        close(dirfd);\n        return SKIP;\n    }\n\n    for (dirent *entry; (entry = xreaddir(dir.get()));) {\n        switch (fn(dirfd, entry)) {\n        case CONTINUE:\n            break;\n        case SKIP:\n            continue;\n        case ABORT:\n            return ABORT;\n        }\n        if (entry->d_type == DT_DIR) {\n            int fd = xopenat(dirfd, entry->d_name, O_RDONLY | O_CLOEXEC);\n            if (pre_order_walk(fd, fn) == ABORT)\n                return ABORT;\n        }\n    }\n    return CONTINUE;\n}\n\nstatic void remove_at(int dirfd, struct dirent *entry) {\n    unlinkat(dirfd, entry->d_name, entry->d_type == DT_DIR ? AT_REMOVEDIR : 0);\n}\n\nvoid frm_rf(int dirfd) {\n    post_order_walk(dirfd, remove_at);\n}\n\nvoid rm_rf(const char *path) {\n    struct stat st;\n    if (lstat(path, &st) < 0)\n        return;\n    if (S_ISDIR(st.st_mode))\n        frm_rf(xopen(path, O_RDONLY | O_CLOEXEC));\n    remove(path);\n}\n#endif\n\n#ifndef SVB_WIN32\nvoid mv_path(const char *src, const char *dest) {\n    file_attr attr;\n    getattr(src, &attr);\n    if (S_ISDIR(attr.st.st_mode)) {\n        if (access(dest, F_OK) != 0) {\n            xmkdirs(dest, 0);\n            setattr(dest, &attr);\n        }\n        mv_dir(xopen(src, O_RDONLY | O_CLOEXEC), xopen(dest, O_RDONLY | O_CLOEXEC));\n    } else{\n        xrename(src, dest);\n    }\n    rmdir(src);\n}\n\nvoid mv_dir(int src, int dest) {\n    auto dir = xopen_dir(src);\n    run_finally f([=]{ close(dest); });\n    for (dirent *entry; (entry = xreaddir(dir.get()));) {\n        switch (entry->d_type) {\n        case DT_DIR:\n            if (xfaccessat(dest, entry->d_name) == 0) {\n                // Destination folder exists, needs recursive move\n                int newsrc = xopenat(src, entry->d_name, O_RDONLY | O_CLOEXEC);\n                int newdest = xopenat(dest, entry->d_name, O_RDONLY | O_CLOEXEC);\n                mv_dir(newsrc, newdest);\n                unlinkat(src, entry->d_name, AT_REMOVEDIR);\n                break;\n            }\n            // Else fall through\n        case DT_LNK:\n        case DT_REG:\n            renameat(src, entry->d_name, dest, entry->d_name);\n            break;\n        }\n    }\n}\n\nvoid cp_afc(const char *src, const char *dest) {\n    file_attr a;\n    getattr(src, &a);\n\n    if (S_ISDIR(a.st.st_mode)) {\n        xmkdirs(dest, 0);\n        clone_dir(xopen(src, O_RDONLY | O_CLOEXEC), xopen(dest, O_RDONLY | O_CLOEXEC));\n    } else{\n        unlink(dest);\n        if (S_ISREG(a.st.st_mode)) {\n            int sfd = xopen(src, O_RDONLY | O_CLOEXEC);\n            int dfd = xopen(dest, O_WRONLY | O_CREAT | O_TRUNC | O_CLOEXEC, 0);\n            xsendfile(dfd, sfd, nullptr, a.st.st_size);\n            close(sfd);\n            close(dfd);\n        } else if (S_ISLNK(a.st.st_mode)) {\n            char buf[4096];\n            xreadlink(src, buf, sizeof(buf));\n            xsymlink(buf, dest);\n        }\n    }\n    setattr(dest, &a);\n}\n\nvoid clone_dir(int src, int dest) {\n    auto dir = xopen_dir(src);\n    run_finally f([&]{ close(dest); });\n    for (dirent *entry; (entry = xreaddir(dir.get()));) {\n        file_attr a;\n        getattrat(src, entry->d_name, &a);\n        switch (entry->d_type) {\n            case DT_DIR: {\n                xmkdirat(dest, entry->d_name, 0);\n                setattrat(dest, entry->d_name, &a);\n                int sfd = xopenat(src, entry->d_name, O_RDONLY | O_CLOEXEC);\n                int dst = xopenat(dest, entry->d_name, O_RDONLY | O_CLOEXEC);\n                clone_dir(sfd, dst);\n                break;\n            }\n            case DT_REG: {\n                int sfd = xopenat(src, entry->d_name, O_RDONLY | O_CLOEXEC);\n                int dfd = xopenat(dest, entry->d_name, O_WRONLY | O_CREAT | O_TRUNC | O_CLOEXEC, 0);\n                xsendfile(dfd, sfd, nullptr, a.st.st_size);\n                fsetattr(dfd, &a);\n                close(dfd);\n                close(sfd);\n                break;\n            }\n            case DT_LNK: {\n                char buf[4096];\n                xreadlinkat(src, entry->d_name, buf, sizeof(buf));\n                xsymlinkat(buf, dest, entry->d_name);\n                setattrat(dest, entry->d_name, &a);\n                break;\n            }\n        }\n    }\n}\n\nvoid link_path(const char *src, const char *dest) {\n    link_dir(xopen(src, O_RDONLY | O_CLOEXEC), xopen(dest, O_RDONLY | O_CLOEXEC));\n}\n\nvoid link_dir(int src, int dest) {\n    auto dir = xopen_dir(src);\n    run_finally f([&]{ close(dest); });\n    for (dirent *entry; (entry = xreaddir(dir.get()));) {\n        if (entry->d_type == DT_DIR) {\n            file_attr a;\n            getattrat(src, entry->d_name, &a);\n            xmkdirat(dest, entry->d_name, 0);\n            setattrat(dest, entry->d_name, &a);\n            int sfd = xopenat(src, entry->d_name, O_RDONLY | O_CLOEXEC);\n            int dfd = xopenat(dest, entry->d_name, O_RDONLY | O_CLOEXEC);\n            link_dir(sfd, dfd);\n        } else {\n            xlinkat(src, entry->d_name, dest, entry->d_name, 0);\n        }\n    }\n}\n\nint getattr(const char *path, file_attr *a) {\n    if (xlstat(path, &a->st) == -1)\n        return -1;\n    char *con;\n    if (lgetfilecon(path, &con) == -1)\n        return -1;\n    strcpy(a->con, con);\n    freecon(con);\n    return 0;\n}\n\nint getattrat(int dirfd, const char *name, file_attr *a) {\n    char path[4096];\n    fd_pathat(dirfd, name, path, sizeof(path));\n    return getattr(path, a);\n}\n\nint fgetattr(int fd, file_attr *a) {\n    if (xfstat(fd, &a->st) < 0)\n        return -1;\n    char *con;\n    if (fgetfilecon(fd, &con) < 0)\n        return -1;\n    strcpy(a->con, con);\n    freecon(con);\n    return 0;\n}\n\nint setattr(const char *path, file_attr *a) {\n    if (chmod(path, a->st.st_mode & 0777) < 0)\n        return -1;\n    if (chown(path, a->st.st_uid, a->st.st_gid) < 0)\n        return -1;\n    if (a->con[0] && lsetfilecon(path, a->con) < 0)\n        return -1;\n    return 0;\n}\n\nint setattrat(int dirfd, const char *name, file_attr *a) {\n    char path[4096];\n    fd_pathat(dirfd, name, path, sizeof(path));\n    return setattr(path, a);\n}\n\nint fsetattr(int fd, file_attr *a) {\n    if (fchmod(fd, a->st.st_mode & 0777) < 0)\n        return -1;\n    if (fchown(fd, a->st.st_uid, a->st.st_gid) < 0)\n        return -1;\n    if (a->con[0] && fsetfilecon(fd, a->con) < 0)\n        return -1;\n    return 0;\n}\n\nvoid clone_attr(const char *src, const char *dest) {\n    file_attr a;\n    getattr(src, &a);\n    setattr(dest, &a);\n}\n\nvoid fclone_attr(int src, int dest) {\n    file_attr a;\n    fgetattr(src, &a);\n    fsetattr(dest, &a);\n}\n#endif\n\nvoid full_read(int fd, string &str) {\n    char buf[4096];\n    for (ssize_t len; (len = xread(fd, buf, sizeof(buf))) > 0;)\n        str.insert(str.end(), buf, buf + len);\n}\n\nvoid full_read(const char *filename, string &str) {\n    if (int fd = xopen(filename, O_RDONLY | O_CLOEXEC); fd >= 0) {\n        full_read(fd, str);\n        close(fd);\n    }\n}\n\nstring full_read(int fd) {\n    string str;\n    full_read(fd, str);\n    return str;\n}\n\nstring full_read(const char *filename) {\n    string str;\n    full_read(filename, str);\n    return str;\n}\n\nvoid write_zero(int fd, size_t size) {\n    char buf[4096] = {0};\n    size_t len;\n    while (size > 0) {\n        len = sizeof(buf) > size ? size : sizeof(buf);\n        write(fd, buf, len);\n        size -= len;\n    }\n}\n\nvoid file_readline(bool trim, FILE *fp, const function<bool(string_view)> &fn) {\n    size_t len = 1024;\n    char *buf = (char *) malloc(len);\n    char *start;\n    ssize_t read;\n    while ((read = getline(&buf, &len, fp)) >= 0) {\n        start = buf;\n        if (trim) {\n            while (read && \"\\n\\r \"sv.find(buf[read - 1]) != string::npos)\n                --read;\n            buf[read] = '\\0';\n            while (*start == ' ')\n                ++start;\n        }\n        if (!fn(start))\n            break;\n    }\n    free(buf);\n}\n\nvoid file_readline(bool trim, const char *file, const function<bool(string_view)> &fn) {\n    if (auto fp = open_file(file, \"re\"))\n        file_readline(trim, fp.get(), fn);\n}\n\nvoid file_readline(const char *file, const function<bool(string_view)> &fn) {\n    file_readline(false, file, fn);\n}\n\nvoid parse_prop_file(FILE *fp, const function<bool(string_view, string_view)> &fn) {\n    file_readline(true, fp, [&](string_view line_view) -> bool {\n        char *line = (char *) line_view.data();\n        if (line[0] == '#')\n            return true;\n        char *eql = strchr(line, '=');\n        if (eql == nullptr || eql == line)\n            return true;\n        *eql = '\\0';\n        return fn(line, eql + 1);\n    });\n}\n\nvoid parse_prop_file(const char *file, const function<bool(string_view, string_view)> &fn) {\n    if (auto fp = open_file(file, \"re\"))\n        parse_prop_file(fp.get(), fn);\n}\n\n#ifndef SVB_WIN32\n// Original source: https://android.googlesource.com/platform/bionic/+/master/libc/bionic/mntent.cpp\n// License: AOSP, full copyright notice please check original source\nstatic struct mntent *compat_getmntent_r(FILE *fp, struct mntent *e, char *buf, int buf_len) {\n    memset(e, 0, sizeof(*e));\n    while (fgets(buf, buf_len, fp) != nullptr) {\n        // Entries look like \"proc /proc proc rw,nosuid,nodev,noexec,relatime 0 0\".\n        // That is: mnt_fsname mnt_dir mnt_type mnt_opts 0 0.\n        int fsname0, fsname1, dir0, dir1, type0, type1, opts0, opts1;\n        if (sscanf(buf, \" %n%*s%n %n%*s%n %n%*s%n %n%*s%n %d %d\",\n                   &fsname0, &fsname1, &dir0, &dir1, &type0, &type1, &opts0, &opts1,\n                   &e->mnt_freq, &e->mnt_passno) == 2) {\n            e->mnt_fsname = &buf[fsname0];\n            buf[fsname1] = '\\0';\n            e->mnt_dir = &buf[dir0];\n            buf[dir1] = '\\0';\n            e->mnt_type = &buf[type0];\n            buf[type1] = '\\0';\n            e->mnt_opts = &buf[opts0];\n            buf[opts1] = '\\0';\n            return e;\n        }\n    }\n    return nullptr;\n}\n\nvoid parse_mnt(const char *file, const function<bool(mntent*)> &fn) {\n    auto fp = sFILE(setmntent(file, \"re\"), endmntent);\n    if (fp) {\n        mntent mentry{};\n        char buf[4096];\n        // getmntent_r from system's libc.so is broken on old platform\n        // use the compat one instead\n        while (compat_getmntent_r(fp.get(), &mentry, buf, sizeof(buf))) {\n            if (!fn(&mentry))\n                break;\n        }\n    }\n}\n\nvoid backup_folder(const char *dir, vector<raw_file> &files) {\n    char path[PATH_MAX];\n    xrealpath(dir, path);\n    int len = strlen(path);\n    pre_order_walk(xopen(dir, O_RDONLY), [&](int dfd, dirent *entry) -> walk_result {\n        int fd = xopenat(dfd, entry->d_name, O_RDONLY);\n        if (fd < 0)\n            return SKIP;\n        run_finally f([&]{ close(fd); });\n        if (fd_path(fd, path, sizeof(path)) < 0)\n            return SKIP;\n        raw_file file;\n        file.path = path + len + 1;\n        if (fgetattr(fd, &file.attr) < 0)\n            return SKIP;\n        if (entry->d_type == DT_REG) {\n            file.content = full_read(fd);\n        } else if (entry->d_type == DT_LNK) {\n            xreadlinkat(dfd, entry->d_name, path, sizeof(path));\n            file.content = path;\n        }\n        files.emplace_back(std::move(file));\n        return CONTINUE;\n    });\n}\n\nvoid restore_folder(const char *dir, vector<raw_file> &files) {\n    string base(dir);\n    // Pre-order means folders will always be first\n    for (raw_file &file : files) {\n        string path = base + \"/\" + file.path;\n        if (S_ISDIR(file.attr.st.st_mode)) {\n            mkdirs(path, 0);\n        } else if (S_ISREG(file.attr.st.st_mode)) {\n            if (auto fp = xopen_file(path.data(), \"we\"))\n                fwrite(file.content.data(), 1, file.content.size(), fp.get());\n        } else if (S_ISLNK(file.attr.st.st_mode)) {\n            symlink(file.content.data(), path.data());\n        }\n        setattr(path.data(), &file.attr);\n    }\n}\n#endif\n\nsDIR make_dir(DIR *dp) {\n#ifdef SVB_MINGW\n    return sDIR(dp);\n#else\n    return sDIR(dp, [](DIR *dp){ return dp ? closedir(dp) : 1; });\n#endif\n}\n\nsFILE make_file(FILE *fp) {\n    return sFILE(fp, [](FILE *fp){ return fp ? fclose(fp) : 1; });\n}\n\nint byte_data::patch(bool log, str_pairs list) {\n    if (buf == nullptr)\n        return 0;\n    int count = 0;\n    for (uint8_t *p = buf, *eof = buf + sz; p < eof; ++p) {\n        for (auto [from, to] : list) {\n            if (memcmp(p, from.data(), from.length() + 1) == 0) {\n                if (log) LOGD(\"Replace [%s] -> [%s]\\n\", from.data(), to.data());\n                memset(p, 0, from.length());\n                memcpy(p, to.data(), to.length());\n                ++count;\n                p += from.length();\n            }\n        }\n    }\n    return count;\n}\n\nbool byte_data::contains(string_view pattern, bool log) const {\n    if (buf == nullptr)\n        return false;\n    for (uint8_t *p = buf, *eof = buf + sz; p < eof; ++p) {\n        if (memcmp(p, pattern.data(), pattern.length() + 1) == 0) {\n            if (log) LOGD(\"Found pattern [%s]\\n\", pattern.data());\n            return true;\n        }\n    }\n    return false;\n}\n\nvoid byte_data::swap(byte_data &o) {\n    std::swap(buf, o.buf);\n    std::swap(sz, o.sz);\n}\n\nmmap_data::mmap_data(const char *name, bool rw) {\n    int fd = xopen(name, (rw ? O_RDWR : O_RDONLY) | O_CLOEXEC);\n    if (fd < 0)\n        return;\n    struct stat st;\n    if (fstat(fd, &st))\n        return;\n#ifndef SVB_WIN32\n    if (S_ISBLK(st.st_mode)) {\n        uint64_t size;\n        ioctl(fd, BLKGETSIZE64, &size);\n        sz = size;\n    } else {\n        sz = st.st_size;\n    }\n#else\n    sz = st.st_size;\n#endif\n    void *b = sz > 0\n            ? xmmap(nullptr, sz, rw ? PROT_READ | PROT_WRITE : PROT_READ, rw ? MAP_SHARED : MAP_PRIVATE, fd, 0)\n            : nullptr;\n    close(fd);\n    buf = static_cast<uint8_t *>(b);\n}\n\n#ifndef SVB_WIN32\nstring find_apk_path(const char *pkg) {\n    char buf[PATH_MAX];\n    pre_order_walk(xopen(\"/data/app\", O_RDONLY), [&](int dfd, dirent *entry) -> walk_result {\n        if (entry->d_type != DT_DIR)\n            return SKIP;\n        size_t len = strlen(pkg);\n        if (strncmp(entry->d_name, pkg, len) == 0 && entry->d_name[len] == '-') {\n            fd_pathat(dfd, entry->d_name, buf, sizeof(buf));\n            return ABORT;\n        } else if (strncmp(entry->d_name, \"~~\", 2) == 0) {\n            return CONTINUE;\n        } else return SKIP;\n    });\n    string path(buf);\n    return path.append(\"/base.apk\");\n}\n#endif\n"
  },
  {
    "path": "magiskbase/files.hpp",
    "content": "#pragma once\n#include <sys/mman.h>\n#ifndef SVB_WIN32\n#include <mntent.h>\n#endif\n#include <sys/stat.h>\n#include <functional>\n#include <string_view>\n#include <string>\n#include <vector>\n\n#include \"xwrap.hpp\"\n\ntemplate <typename T>\nstatic inline T align_to(T v, int a) {\n    static_assert(std::is_integral<T>::value);\n    return (v + a - 1) / a * a;\n}\n\ntemplate <typename T>\nstatic inline T align_padding(T v, int a) {\n    return align_to(v, a) - v;\n}\n\nstruct file_attr {\n    struct stat st;\n    char con[128];\n};\n\nstruct byte_data {\n    using str_pairs = std::initializer_list<std::pair<std::string_view, std::string_view>>;\n\n    uint8_t *buf = nullptr;\n    size_t sz = 0;\n\n    int patch(str_pairs list) { return patch(true, list); }\n    int patch(bool log, str_pairs list);\n    bool contains(std::string_view pattern, bool log = true) const;\nprotected:\n    void swap(byte_data &o);\n};\n\nstruct raw_file {\n    std::string path;\n    file_attr attr;\n    std::string content;\n\n    raw_file() : attr{} {}\n    raw_file(const raw_file&) = delete;\n    raw_file(raw_file &&o) : path(std::move(o.path)), attr(o.attr), content(std::move(o.content)) {}\n};\n\nstruct mmap_data : public byte_data {\n    mmap_data() = default;\n    mmap_data(const mmap_data&) = delete;\n    mmap_data(mmap_data &&o) { swap(o); }\n    mmap_data(const char *name, bool rw = false);\n    ~mmap_data() { if (buf) munmap(buf, sz); }\n    mmap_data& operator=(mmap_data &&other) { swap(other); return *this; }\n};\n\n#ifndef SVB_WIN32\nssize_t fd_path(int fd, char *path, size_t size);\nint fd_pathat(int dirfd, const char *name, char *path, size_t size);\nvoid mv_path(const char *src, const char *dest);\nvoid mv_dir(int src, int dest);\nvoid cp_afc(const char *src, const char *dest);\nvoid link_path(const char *src, const char *dest);\nvoid link_dir(int src, int dest);\nint getattr(const char *path, file_attr *a);\nint getattrat(int dirfd, const char *name, file_attr *a);\nint fgetattr(int fd, file_attr *a);\nint setattr(const char *path, file_attr *a);\nint setattrat(int dirfd, const char *name, file_attr *a);\nint fsetattr(int fd, file_attr *a);\nvoid fclone_attr(int src, int dest);\nvoid clone_attr(const char *src, const char *dest);\nvoid clone_dir(int src, int dest);\nvoid parse_mnt(const char *file, const std::function<bool(mntent*)> &fn);\nvoid backup_folder(const char *dir, std::vector<raw_file> &files);\nvoid restore_folder(const char *dir, std::vector<raw_file> &files);\nstd::string find_apk_path(const char *pkg);\n#endif\n\nint mkdirs(const char *path, mode_t mode);\nvoid rm_rf(const char *path);\nvoid full_read(int fd, std::string &str);\nvoid full_read(const char *filename, std::string &str);\nstd::string full_read(int fd);\nstd::string full_read(const char *filename);\nvoid write_zero(int fd, size_t size);\nvoid file_readline(bool trim, FILE *fp, const std::function<bool(std::string_view)> &fn);\nvoid file_readline(bool trim, const char *file, const std::function<bool(std::string_view)> &fn);\nvoid file_readline(const char *file, const std::function<bool(std::string_view)> &fn);\nvoid parse_prop_file(FILE *fp, const std::function<bool(std::string_view, std::string_view)> &fn);\nvoid parse_prop_file(const char *file,\n        const std::function<bool(std::string_view, std::string_view)> &fn);\nvoid frm_rf(int dirfd);\n\n#ifdef SVB_MINGW\nstruct delDIR {\n    void operator()(DIR* p) const\n    {\n        if (p) closedir(p);\n    }\n};\n#endif\nusing sFILE = std::unique_ptr<FILE, decltype(&fclose)>;\n#ifdef SVB_MINGW\nusing sDIR = std::unique_ptr<DIR, delDIR>;\n#else\nusing sDIR = std::unique_ptr<DIR, decltype(&closedir)>;\n#endif\nsDIR make_dir(DIR *dp);\nsFILE make_file(FILE *fp);\n\nstatic inline sDIR open_dir(const char *path) {\n    return make_dir(opendir(path));\n}\n\nstatic inline sDIR xopen_dir(const char *path) {\n    return make_dir(xopendir(path));\n}\n\n#ifndef SVB_MINGW\nstatic inline sDIR xopen_dir(int dirfd) {\n    return make_dir(xfdopendir(dirfd));\n}\n#endif\n\nstatic inline sFILE open_file(const char *path, const char *mode) {\n    return make_file(fopen(path, mode));\n}\n\nstatic inline sFILE xopen_file(const char *path, const char *mode) {\n    return make_file(xfopen(path, mode));\n}\n\nstatic inline sFILE xopen_file(int fd, const char *mode) {\n    return make_file(xfdopen(fd, mode));\n}\n"
  },
  {
    "path": "magiskbase/include/base.hpp",
    "content": "#pragma once\n\n#include <functional>\n\n#ifdef SVB_WIN32\n#include <fcntl.h>\n#include <unistd.h>\n#include <cerrno>\n#else\n#include \"../missing.hpp\"\n#endif\n\n#include \"../xwrap.hpp\"\n#include \"../files.hpp\"\n#include \"../misc.hpp\"\n\n#ifndef SVB_WIN32\n#include <base-rs.hpp>\n#endif\n\n#define LOG(fmt, args...) fprintf(stderr, fmt, ##args)\n#define LOGE(fmt, args...) { \\\n        LOG(\"Error: \" fmt, ##args); \\\n        exit(errno); \\\n   }\n#define PLOGE(fmt, args...) LOGE(fmt \" failed with %d: %s\\n\", ##args, errno, std::strerror(errno))\n#define LOGW(fmt, args...) LOG(\"Warning: \" fmt, ##args)\n#define LOGD(fmt, args...) LOG(\"Debug: \" fmt, ##args)\n"
  },
  {
    "path": "magiskbase/include/stream.hpp",
    "content": "#pragma once\n\n#if defined(SVB_WIN32) && !defined(SVB_MINGW)\n#include <sys/uio.h>\n#endif\n#include <cstdio>\n#include <memory>\n\n#include \"../files.hpp\"\n\nclass stream {\npublic:\n    virtual ssize_t read(void *buf, size_t len);\n    virtual ssize_t readFully(void *buf, size_t len);\n    virtual ssize_t readv(const iovec *iov, int iovcnt);\n    virtual bool write(const void *buf, size_t len);\n    virtual ssize_t writev(const iovec *iov, int iovcnt);\n    virtual off_t seek(off_t off, int whence);\n    virtual ~stream() = default;\n};\n\nusing stream_ptr = std::unique_ptr<stream>;\n\n// Delegates all operations to base stream\nclass filter_stream : public stream {\npublic:\n    filter_stream(stream_ptr &&base) : base(std::move(base)) {}\n\n    ssize_t read(void *buf, size_t len) override;\n    bool write(const void *buf, size_t len) override;\n    virtual bool write(const void *buf, size_t len, bool final);\n\n    // Seeking while filtering does not make sense\n    off_t seek(off_t off, int whence) final { return stream::seek(off, whence); }\n\nprotected:\n    stream_ptr base;\n};\n\nusing filter_strm_ptr = std::unique_ptr<filter_stream>;\n\n// Buffered output stream, writing in chunks\nclass chunk_out_stream : public filter_stream {\npublic:\n    chunk_out_stream(stream_ptr &&base, size_t buf_sz, size_t chunk_sz)\n    : filter_stream(std::move(base)), chunk_sz(chunk_sz), buf_sz(buf_sz) {}\n\n    chunk_out_stream(stream_ptr &&base, size_t buf_sz = 4096)\n    : chunk_out_stream(std::move(base), buf_sz, buf_sz) {}\n\n    ~chunk_out_stream() override { delete[] _buf; }\n\n    // Reading does not make sense\n    ssize_t read(void *buf, size_t len) final { return stream::read(buf, len); }\n    bool write(const void *buf, size_t len) final;\n    bool write(const void *buf, size_t len, bool final) final;\n\nprotected:\n    // Classes inheriting this class has to call finalize() in its destructor\n    void finalize();\n    virtual bool write_chunk(const void *buf, size_t len, bool final) = 0;\n\n    size_t chunk_sz;\n\nprivate:\n    size_t buf_sz;\n    size_t buf_off = 0;\n    uint8_t *_buf = nullptr;\n};\n\n// Byte stream that dynamically allocates memory\nclass byte_stream : public stream {\npublic:\n    byte_stream(uint8_t *&buf, size_t &len);\n    template <class Byte>\n    byte_stream(Byte *&buf, size_t &len) : byte_stream(reinterpret_cast<uint8_t *&>(buf), len) {}\n\n    ssize_t read(void *buf, size_t len) override;\n    bool write(const void *buf, size_t len) override;\n    off_t seek(off_t off, int whence) override;\n\nprivate:\n    uint8_t *&_buf;\n    size_t &_len;\n    size_t _pos = 0;\n    size_t _cap = 0;\n\n    void resize(size_t new_pos, bool zero = false);\n};\n\nclass file_stream : public stream {\npublic:\n    bool write(const void *buf, size_t len) final;\nprotected:\n    virtual ssize_t do_write(const void *buf, size_t len) = 0;\n};\n\n// File stream but does not close the file descriptor at any time\nclass fd_stream : public file_stream {\npublic:\n    fd_stream(int fd) : fd(fd) {}\n    ssize_t read(void *buf, size_t len) override;\n    ssize_t readv(const iovec *iov, int iovcnt) override;\n    ssize_t writev(const iovec *iov, int iovcnt) override;\n\n    off_t seek(off_t off, int whence) override;\nprotected:\n    ssize_t do_write(const void *buf, size_t len) override;\nprivate:\n    int fd;\n};\n\n/* ****************************************\n * Bridge between stream class and C stdio\n * ****************************************/\n\n// sFILE -> stream_ptr\nclass fp_stream final : public file_stream {\npublic:\n    fp_stream(FILE *fp = nullptr) : fp(fp, fclose) {}\n    fp_stream(sFILE &&fp) : fp(std::move(fp)) {}\n    ssize_t read(void *buf, size_t len) override;\n    off_t seek(off_t off, int whence) override;\nprotected:\n    ssize_t do_write(const void *buf, size_t len) override;\nprivate:\n    sFILE fp;\n};\n\n// stream_ptr -> sFILE\nsFILE make_stream_fp(stream_ptr &&strm);\n\ntemplate <class T, class... Args>\nsFILE make_stream_fp(Args &&... args) {\n    return make_stream_fp(stream_ptr(new T(std::forward<Args>(args)...)));\n}\n"
  },
  {
    "path": "magiskbase/misc.cpp",
    "content": "#include <sys/types.h>\n#include <fcntl.h>\n#include <pwd.h>\n#include <unistd.h>\n#include <random>\n#include <string>\n\n#include <base.hpp>\n\nusing namespace std;\n\n#ifndef SVB_WIN32\n#include <sys/prctl.h>\n#include <sys/sysmacros.h>\n#include <syscall.h>\n#include <sys/wait.h>\n\nint fork_dont_care() {\n    if (int pid = xfork()) {\n        waitpid(pid, nullptr, 0);\n        return pid;\n    } else if (xfork()) {\n        exit(0);\n    }\n    return 0;\n}\n\nint fork_no_orphan() {\n    int pid = xfork();\n    if (pid)\n        return pid;\n    prctl(PR_SET_PDEATHSIG, SIGKILL);\n    if (getppid() == 1)\n        exit(1);\n    return 0;\n}\n\nint gen_rand_str(char *buf, int len, bool varlen) {\n    constexpr char ALPHANUM[] = \"abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789\";\n    static std::mt19937 gen([]{\n        if (access(\"/dev/urandom\", F_OK) != 0)\n            mknod(\"/dev/urandom\", 0600 | S_IFCHR, makedev(1, 9));\n        int fd = xopen(\"/dev/urandom\", O_RDONLY | O_CLOEXEC);\n        unsigned seed;\n        xxread(fd, &seed, sizeof(seed));\n        return seed;\n    }());\n    std::uniform_int_distribution<int> dist(0, sizeof(ALPHANUM) - 2);\n    if (varlen) {\n        std::uniform_int_distribution<int> len_dist(len / 2, len);\n        len = len_dist(gen);\n    }\n    for (int i = 0; i < len - 1; ++i)\n        buf[i] = ALPHANUM[dist(gen)];\n    buf[len - 1] = '\\0';\n    return len - 1;\n}\n\nint exec_command(exec_t &exec) {\n    int pipefd[] = {-1, -1};\n    int outfd = -1;\n\n    if (exec.fd == -1) {\n        if (xpipe2(pipefd, O_CLOEXEC) == -1)\n            return -1;\n        outfd = pipefd[1];\n    } else if (exec.fd >= 0) {\n        outfd = exec.fd;\n    }\n\n    int pid = exec.fork();\n    if (pid < 0) {\n        close(pipefd[0]);\n        close(pipefd[1]);\n        return -1;\n    } else if (pid) {\n        if (exec.fd == -1) {\n            exec.fd = pipefd[0];\n            close(pipefd[1]);\n        }\n        return pid;\n    }\n\n    // Unblock all signals\n    sigset_t set;\n    sigfillset(&set);\n    pthread_sigmask(SIG_UNBLOCK, &set, nullptr);\n\n    if (outfd >= 0) {\n        xdup2(outfd, STDOUT_FILENO);\n        if (exec.err)\n            xdup2(outfd, STDERR_FILENO);\n        close(outfd);\n    }\n\n    // Call the pre-exec callback\n    if (exec.pre_exec)\n        exec.pre_exec();\n\n    execve(exec.argv[0], (char **) exec.argv, environ);\n    PLOGE(\"execve %s\", exec.argv[0]);\n    exit(-1);\n}\n\nint exec_command_sync(exec_t &exec) {\n    int pid = exec_command(exec);\n    if (pid < 0)\n        return -1;\n    int status;\n    waitpid(pid, &status, 0);\n    return WEXITSTATUS(status);\n}\n\nint new_daemon_thread(thread_entry entry, void *arg) {\n    pthread_t thread;\n    pthread_attr_t attr;\n    pthread_attr_init(&attr);\n    pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_DETACHED);\n    return xpthread_create(&thread, &attr, entry, arg);\n}\n\nstatic char *argv0;\nstatic size_t name_len;\nvoid init_argv0(int argc, char **argv) {\n    argv0 = argv[0];\n    name_len = (argv[argc - 1] - argv[0]) + strlen(argv[argc - 1]) + 1;\n}\n\nvoid set_nice_name(const char *name) {\n    memset(argv0, 0, name_len);\n    strlcpy(argv0, name, name_len);\n    prctl(PR_SET_NAME, name);\n}\n\n/*\n * Bionic's atoi runs through strtol().\n * Use our own implementation for faster conversion.\n */\nint parse_int(string_view s) {\n    int val = 0;\n    for (char c : s) {\n        if (!c) break;\n        if (c > '9' || c < '0')\n            return -1;\n        val = val * 10 + c - '0';\n    }\n    return val;\n}\n#endif\n\nuint32_t binary_gcd(uint32_t u, uint32_t v) {\n    if (u == 0) return v;\n    if (v == 0) return u;\n    auto shift = __builtin_ctz(u | v);\n    u >>= __builtin_ctz(u);\n    do {\n        v >>= __builtin_ctz(v);\n        if (u > v) {\n            auto t = v;\n            v = u;\n            u = t;\n        }\n        v -= u;\n    } while (v != 0);\n    return u << shift;\n}\n#ifndef SVB_WIN32\nint switch_mnt_ns(int pid) {\n    char mnt[32];\n    snprintf(mnt, sizeof(mnt), \"/proc/%d/ns/mnt\", pid);\n    if (access(mnt, R_OK) == -1) return 1; // Maybe process died..\n\n    int fd, ret;\n    fd = xopen(mnt, O_RDONLY);\n    if (fd < 0) return 1;\n    // Switch to its namespace\n    ret = xsetns(fd, 0);\n    close(fd);\n    return ret;\n}\n#endif\nstring &replace_all(string &str, string_view from, string_view to) {\n    size_t pos = 0;\n    while((pos = str.find(from, pos)) != string::npos) {\n        str.replace(pos, from.length(), to);\n        pos += to.length();\n    }\n    return str;\n}\n\ntemplate <class T>\nstatic auto split_impl(T s, T delims) {\n    vector<std::decay_t<T>> result;\n    size_t base = 0;\n    size_t found;\n    while (true) {\n        found = s.find_first_of(delims, base);\n        result.push_back(s.substr(base, found - base));\n        if (found == string::npos)\n            break;\n        base = found + 1;\n    }\n    return result;\n}\n\nvector<string> split(const string &s, const string &delims) {\n    return split_impl<const string&>(s, delims);\n}\n\nvector<string_view> split_ro(string_view s, string_view delims) {\n    return split_impl<string_view>(s, delims);\n}\n"
  },
  {
    "path": "magiskbase/misc.hpp",
    "content": "#pragma once\n#ifndef SVB_WIN32\n#include <pthread.h>\n#endif\n#include <string>\n#include <functional>\n#include <string_view>\n#include <bitset>\n\n#define DISALLOW_COPY_AND_MOVE(clazz) \\\nclazz(const clazz &) = delete; \\\nclazz(clazz &&) = delete;\n#ifndef SVB_WIN32\nclass mutex_guard {\n    DISALLOW_COPY_AND_MOVE(mutex_guard)\npublic:\n    explicit mutex_guard(pthread_mutex_t &m): mutex(&m) {\n        pthread_mutex_lock(mutex);\n    }\n    void unlock() {\n        pthread_mutex_unlock(mutex);\n        mutex = nullptr;\n    }\n    ~mutex_guard() {\n        if (mutex) pthread_mutex_unlock(mutex);\n    }\nprivate:\n    pthread_mutex_t *mutex;\n};\n\ntemplate <class Func>\nclass run_finally {\n    DISALLOW_COPY_AND_MOVE(run_finally)\npublic:\n    explicit run_finally(Func &&fn) : fn(std::move(fn)) {}\n    ~run_finally() { fn(); }\nprivate:\n    Func fn;\n};\n\ntemplate <typename T>\nclass reversed_container {\npublic:\n    reversed_container(T &base) : base(base) {}\n    decltype(std::declval<T>().rbegin()) begin() { return base.rbegin(); }\n    decltype(std::declval<T>().crbegin()) begin() const { return base.crbegin(); }\n    decltype(std::declval<T>().crbegin()) cbegin() const { return base.crbegin(); }\n    decltype(std::declval<T>().rend()) end() { return base.rend(); }\n    decltype(std::declval<T>().crend()) end() const { return base.crend(); }\n    decltype(std::declval<T>().crend()) cend() const { return base.crend(); }\nprivate:\n    T &base;\n};\n\ntemplate <typename T>\nreversed_container<T> reversed(T &base) {\n    return reversed_container<T>(base);\n}\n\ntemplate<class T>\nstatic inline void default_new(T *&p) { p = new T(); }\n\ntemplate<class T>\nstatic inline void default_new(std::unique_ptr<T> &p) { p.reset(new T()); }\n\ntemplate<typename T, typename Impl>\nclass stateless_allocator {\npublic:\n    using value_type = T;\n    T *allocate(size_t num) { return static_cast<T*>(Impl::allocate(sizeof(T) * num)); }\n    void deallocate(T *ptr, size_t num) { Impl::deallocate(ptr, sizeof(T) * num); }\n    stateless_allocator()                           = default;\n    stateless_allocator(const stateless_allocator&) = default;\n    stateless_allocator(stateless_allocator&&)      = default;\n    template <typename U>\n    stateless_allocator(const stateless_allocator<U, Impl>&) {}\n    bool operator==(const stateless_allocator&) { return true; }\n    bool operator!=(const stateless_allocator&) { return false; }\n};\n\nclass dynamic_bitset_impl {\npublic:\n    using slot_type = unsigned long;\n    constexpr static int slot_size = sizeof(slot_type) * 8;\n    using slot_bits = std::bitset<slot_size>;\n\n    size_t slots() const { return slot_list.size(); }\n    slot_type get_slot(size_t slot) const {\n        return slot_list.size() > slot ? slot_list[slot].to_ulong() : 0ul;\n    }\n    void emplace_back(slot_type l) {\n        slot_list.emplace_back(l);\n    }\nprotected:\n    slot_bits::reference get(size_t pos) {\n        size_t slot = pos / slot_size;\n        size_t index = pos % slot_size;\n        if (slot_list.size() <= slot) {\n            slot_list.resize(slot + 1);\n        }\n        return slot_list[slot][index];\n    }\n    bool get(size_t pos) const {\n        size_t slot = pos / slot_size;\n        size_t index = pos % slot_size;\n        return slot_list.size() > slot && slot_list[slot][index];\n    }\nprivate:\n    std::vector<slot_bits> slot_list;\n};\n\nstruct dynamic_bitset : public dynamic_bitset_impl {\n    slot_bits::reference operator[] (size_t pos) { return get(pos); }\n    bool operator[] (size_t pos) const { return get(pos); }\n};\n\nstruct StringCmp {\n    using is_transparent = void;\n    bool operator()(std::string_view a, std::string_view b) const { return a < b; }\n};\n\nint parse_int(std::string_view s);\n\nusing thread_entry = void *(*)(void *);\nint new_daemon_thread(thread_entry entry, void *arg = nullptr);\n#endif\nstatic inline bool str_contains(std::string_view s, std::string_view ss) {\n    return s.find(ss) != std::string::npos;\n}\nstatic inline bool str_starts(std::string_view s, std::string_view ss) {\n    return s.size() >= ss.size() && s.compare(0, ss.size(), ss) == 0;\n}\nstatic inline bool str_ends(std::string_view s, std::string_view ss) {\n    return s.size() >= ss.size() && s.compare(s.size() - ss.size(), std::string::npos, ss) == 0;\n}\nstatic inline std::string ltrim(std::string &&s) {\n    s.erase(s.begin(), std::find_if(s.begin(), s.end(), [](unsigned char ch) {\n        return !std::isspace(ch);\n    }));\n    return std::move(s);\n}\nstatic inline std::string rtrim(std::string &&s) {\n    s.erase(std::find_if(s.rbegin(), s.rend(), [](unsigned char ch) {\n        return !std::isspace(ch) && ch != '\\0';\n    }).base(), s.end());\n    return std::move(s);\n}\n\n#ifndef SVB_WIN32\nint fork_dont_care();\nint fork_no_orphan();\nvoid init_argv0(int argc, char **argv);\nvoid set_nice_name(const char *name);\nint switch_mnt_ns(int pid);\nint gen_rand_str(char *buf, int len, bool varlen = true);\n#endif\n\nuint32_t binary_gcd(uint32_t u, uint32_t v);\nstd::string &replace_all(std::string &str, std::string_view from, std::string_view to);\nstd::vector<std::string> split(const std::string &s, const std::string &delims);\nstd::vector<std::string_view> split_ro(std::string_view, std::string_view delims);\n\n#ifndef SVB_WIN32\nstruct exec_t {\n    bool err = false;\n    int fd = -2;\n    void (*pre_exec)() = nullptr;\n    int (*fork)() = xfork;\n    const char **argv = nullptr;\n};\n\nint exec_command(exec_t &exec);\ntemplate <class ...Args>\nint exec_command(exec_t &exec, Args &&...args) {\n    const char *argv[] = {args..., nullptr};\n    exec.argv = argv;\n    return exec_command(exec);\n}\nint exec_command_sync(exec_t &exec);\ntemplate <class ...Args>\nint exec_command_sync(exec_t &exec, Args &&...args) {\n    const char *argv[] = {args..., nullptr};\n    exec.argv = argv;\n    return exec_command_sync(exec);\n}\ntemplate <class ...Args>\nint exec_command_sync(Args &&...args) {\n    exec_t exec;\n    return exec_command_sync(exec, args...);\n}\ntemplate <class ...Args>\nvoid exec_command_async(Args &&...args) {\n    const char *argv[] = {args..., nullptr};\n    exec_t exec {\n        .fork = fork_dont_care,\n        .argv = argv,\n    };\n    exec_command(exec);\n}\n#endif"
  },
  {
    "path": "magiskbase/stream.cpp",
    "content": "#include <unistd.h>\n#include <cstddef>\n\n#include <base.hpp>\n#include <stream.hpp>\n\nusing namespace std;\n\nstatic int strm_read(void *v, char *buf, size_t len) {\n    auto strm = static_cast<stream *>(v);\n    return strm->read(buf, len);\n}\n\nstatic int strm_write(void *v, const char *buf, size_t len) {\n    auto strm = static_cast<stream *>(v);\n    if (!strm->write(buf, len))\n        return -1;\n    return len;\n}\n\nstatic fpos_t strm_seek(void *v, fpos_t off, int whence) {\n    auto strm = static_cast<stream *>(v);\n    return strm->seek(off, whence);\n}\n\nstatic int strm_close(void *v) {\n    auto strm = static_cast<stream *>(v);\n    delete strm;\n    return 0;\n}\n\n#ifndef SVB_MINGW\nsFILE make_stream_fp(stream_ptr &&strm) {\n    auto fp = make_file(funopen(strm.release(), strm_read, strm_write, strm_seek, strm_close));\n    setbuf(fp.get(), nullptr);\n    return fp;\n}\n#endif\n\nssize_t stream::read(void *buf, size_t len)  {\n    LOGE(\"This stream does not implement read\\n\");\n    return -1;\n}\n\nssize_t stream::readFully(void *buf, size_t len) {\n    size_t read_sz = 0;\n    ssize_t ret;\n    do {\n        ret = read((::byte *) buf + read_sz, len - read_sz);\n        if (ret < 0) {\n            if (errno == EINTR)\n                continue;\n            return ret;\n        }\n        read_sz += ret;\n    } while (read_sz != len && ret != 0);\n    return read_sz;\n}\n\nssize_t stream::readv(const iovec *iov, int iovcnt) {\n    size_t read_sz = 0;\n    for (int i = 0; i < iovcnt; ++i) {\n        auto ret = readFully(iov[i].iov_base, iov[i].iov_len);\n        if (ret < 0)\n            return ret;\n        read_sz += ret;\n    }\n    return read_sz;\n}\n\nbool stream::write(const void *buf, size_t len) {\n    LOGE(\"This stream does not implement write\\n\");\n    return false;\n}\n\nssize_t stream::writev(const iovec *iov, int iovcnt) {\n    size_t write_sz = 0;\n    for (int i = 0; i < iovcnt; ++i) {\n        if (!write(iov[i].iov_base, iov[i].iov_len))\n            return write_sz;\n        write_sz += iov[i].iov_len;\n    }\n    return write_sz;\n}\n\noff_t stream::seek(off_t off, int whence) {\n    LOGE(\"This stream does not implement seek\\n\");\n    return -1;\n}\n\nssize_t fp_stream::read(void *buf, size_t len) {\n    auto ret = fread(buf, 1, len, fp.get());\n    return ret ? ret : (ferror(fp.get()) ? -1 : 0);\n}\n\nssize_t fp_stream::do_write(const void *buf, size_t len) {\n    return fwrite(buf, 1, len, fp.get());\n}\n\noff_t fp_stream::seek(off_t off, int whence) {\n    return fseek(fp.get(), off, whence);\n}\n\nssize_t filter_stream::read(void *buf, size_t len) {\n    return base->read(buf, len);\n}\n\nbool filter_stream::write(const void *buf, size_t len) {\n    return base->write(buf, len);\n}\n\nbool filter_stream::write(const void *buf, size_t len, bool final) {\n    return write(buf, len);\n}\n\nbool chunk_out_stream::write(const void *buf, size_t len) {\n    return write(buf, len, false);\n}\n\nbool chunk_out_stream::write(const void *_in, size_t len, bool final) {\n    auto in = static_cast<const uint8_t *>(_in);\n    while (len) {\n        if (buf_off + len >= chunk_sz) {\n            // Enough input for a chunk\n            const uint8_t *src;\n            if (buf_off) {\n                src = _buf;\n                auto copy = chunk_sz - buf_off;\n                memcpy(_buf + buf_off, in, copy);\n                in += copy;\n                len -= copy;\n                buf_off = 0;\n            } else {\n                src = in;\n                in += chunk_sz;\n                len -= chunk_sz;\n            }\n            if (!write_chunk(src, chunk_sz, final && len == 0))\n                return false;\n        } else if (final) {\n            // Final input data, write regardless whether it is chunk sized\n            if (buf_off) {\n                memcpy(_buf + buf_off, in, len);\n                auto avail = buf_off + len;\n                buf_off = 0;\n                if (!write_chunk(_buf, avail, true))\n                    return false;\n            } else {\n                if (!write_chunk(in, len, true))\n                    return false;\n            }\n            break;\n        } else {\n            // Buffer internally\n            if (!_buf) {\n                _buf = new uint8_t[buf_sz];\n            }\n            memcpy(_buf + buf_off, in, len);\n            buf_off += len;\n            break;\n        }\n    }\n    return true;\n}\n\nvoid chunk_out_stream::finalize() {\n    if (buf_off) {\n        if (!write_chunk(_buf, buf_off, true)) {\n            LOGE(\"Error in finalize, file truncated\\n\");\n        }\n        delete[] _buf;\n        _buf = nullptr;\n        buf_off = 0;\n    }\n}\n\nbyte_stream::byte_stream(uint8_t *&buf, size_t &len) : _buf(buf), _len(len) {\n    buf = nullptr;\n    len = 0;\n}\n\nssize_t byte_stream::read(void *buf, size_t len) {\n    len = std::min((size_t) len, _len - _pos);\n    memcpy(buf, _buf + _pos, len);\n    return len;\n}\n\nbool byte_stream::write(const void *buf, size_t len) {\n    resize(_pos + len);\n    memcpy(_buf + _pos, buf, len);\n    _pos += len;\n    _len = std::max(_len, _pos);\n    return true;\n}\n\noff_t byte_stream::seek(off_t off, int whence) {\n    off_t np;\n    switch (whence) {\n        case SEEK_CUR:\n            np = _pos + off;\n            break;\n        case SEEK_END:\n            np = _len + off;\n            break;\n        case SEEK_SET:\n            np = off;\n            break;\n        default:\n            return -1;\n    }\n    resize(np, true);\n    _pos = np;\n    return np;\n}\n\nvoid byte_stream::resize(size_t new_pos, bool zero) {\n    bool resize = false;\n    size_t old_cap = _cap;\n    while (new_pos > _cap) {\n        _cap = _cap ? (_cap << 1) - (_cap >> 1) : 1 << 12;\n        resize = true;\n    }\n    if (resize) {\n        _buf = (uint8_t *) xrealloc(_buf, _cap);\n        if (zero)\n            memset(_buf + old_cap, 0, _cap - old_cap);\n    }\n}\n\nssize_t fd_stream::read(void *buf, size_t len) {\n    return ::read(fd, buf, len);\n}\n\nssize_t fd_stream::readv(const iovec *iov, int iovcnt) {\n    return ::readv(fd, iov, iovcnt);\n}\n\nssize_t fd_stream::do_write(const void *buf, size_t len) {\n    return ::write(fd, buf, len);\n}\n\nssize_t fd_stream::writev(const iovec *iov, int iovcnt) {\n    return ::writev(fd, iov, iovcnt);\n}\n\noff_t fd_stream::seek(off_t off, int whence) {\n    return lseek(fd, off, whence);\n}\n\nbool file_stream::write(const void *buf, size_t len) {\n    size_t write_sz = 0;\n    ssize_t ret;\n    do {\n        ret = do_write((::byte *) buf + write_sz, len - write_sz);\n        if (ret < 0) {\n            if (errno == EINTR)\n                continue;\n            return false;\n        }\n        write_sz += ret;\n    } while (write_sz != len && ret != 0);\n    return true;\n}\n"
  },
  {
    "path": "magiskbase/xwrap.cpp",
    "content": "#include <sched.h>\n#include <unistd.h>\n#include <pthread.h>\n#include <sys/types.h>\n#include <sys/stat.h>\n#include <sys/mman.h>\n#ifndef SVB_WIN32\n#include <sys/socket.h>\n#include <sys/sendfile.h>\n#include <sys/ptrace.h>\n#include <sys/inotify.h>\n#include <sys/mount.h>\n#else\n#include <errno.h>\n#include \"windows.h\"\n#endif\n\n#include <base.hpp>\n\nusing namespace std;\n\nFILE *xfopen(const char *pathname, const char *mode) {\n    FILE *fp = fopen(pathname, mode);\n    if (fp == nullptr) {\n        PLOGE(\"fopen: %s\", pathname);\n    }\n    return fp;\n}\n\nFILE *xfdopen(int fd, const char *mode) {\n    FILE *fp = fdopen(fd, mode);\n    if (fp == nullptr) {\n        PLOGE(\"fopen\");\n    }\n    return fp;\n}\n\nint xopen(const char *pathname, int flags) {\n    int fd = open(pathname, flags);\n    if (fd < 0) {\n        PLOGE(\"open: %s\", pathname);\n    }\n    return fd;\n}\n\nint xopen(const char *pathname, int flags, mode_t mode) {\n    int fd = open(pathname, flags, mode);\n    if (fd < 0) {\n        PLOGE(\"open: %s\", pathname);\n    }\n    return fd;\n}\n\n#ifndef SVB_MINGW\nint xopenat(int dirfd, const char *pathname, int flags) {\n    int fd = openat(dirfd, pathname, flags);\n    if (fd < 0) {\n        PLOGE(\"openat: %s\", pathname);\n    }\n    return fd;\n}\n\nint xopenat(int dirfd, const char *pathname, int flags, mode_t mode) {\n    int fd = openat(dirfd, pathname, flags, mode);\n    if (fd < 0) {\n        PLOGE(\"openat: %s\", pathname);\n    }\n    return fd;\n}\n#endif\n\n// Write exact same size as count\nssize_t xwrite(int fd, const void *buf, size_t count) {\n    size_t write_sz = 0;\n    ssize_t ret;\n    do {\n        ret = write(fd, (::byte *) buf + write_sz, count - write_sz);\n        if (ret < 0) {\n            if (errno == EINTR)\n                continue;\n            PLOGE(\"write\");\n            return ret;\n        }\n        write_sz += ret;\n    } while (write_sz != count && ret != 0);\n    if (write_sz != count) {\n        PLOGE(\"write (%zu != %zu)\", count, write_sz);\n    }\n    return write_sz;\n}\n\n// Read error other than EOF\nssize_t xread(int fd, void *buf, size_t count) {\n    int ret = read(fd, buf, count);\n    if (ret < 0) {\n        PLOGE(\"read\");\n    }\n    return ret;\n}\n\n// Read exact same size as count\nssize_t xxread(int fd, void *buf, size_t count) {\n    size_t read_sz = 0;\n    ssize_t ret;\n    do {\n        ret = read(fd, (::byte *) buf + read_sz, count - read_sz);\n        if (ret < 0) {\n            if (errno == EINTR)\n                continue;\n            PLOGE(\"read\");\n            return ret;\n        }\n        read_sz += ret;\n    } while (read_sz != count && ret != 0);\n    if (read_sz != count) {\n        PLOGE(\"read (%zu != %zu)\", count, read_sz);\n    }\n    return read_sz;\n}\n\noff_t xlseek(int fd, off_t offset, int whence) {\n    off_t ret = lseek(fd, offset, whence);\n    if (ret < 0) {\n        PLOGE(\"lseek\");\n    }\n    return ret;\n}\n\n#ifndef SVB_MINGW\nint xpipe2(int pipefd[2], int flags) {\n    int ret = pipe2(pipefd, flags);\n    if (ret < 0) {\n        PLOGE(\"pipe2\");\n    }\n    return ret;\n}\n#endif\n\n#ifndef SVB_WIN32\nint xsetns(int fd, int nstype) {\n    int ret = setns(fd, nstype);\n    if (ret < 0) {\n        PLOGE(\"setns\");\n    }\n    return ret;\n}\n\nint xunshare(int flags) {\n    int ret = unshare(flags);\n    if (ret < 0) {\n        PLOGE(\"unshare\");\n    }\n    return ret;\n}\n#endif\n\nDIR *xopendir(const char *name) {\n    DIR *d = opendir(name);\n    if (d == nullptr) {\n        PLOGE(\"opendir: %s\", name);\n    }\n    return d;\n}\n\n#ifndef SVB_MINGW\nDIR *xfdopendir(int fd) {\n    DIR *d = fdopendir(fd);\n    if (d == nullptr) {\n        PLOGE(\"fdopendir\");\n    }\n    return d;\n}\n#endif\n\nstruct dirent *xreaddir(DIR *dirp) {\n    errno = 0;\n    for (dirent *e;;) {\n        e = readdir(dirp);\n        if (e == nullptr) {\n            if (errno)\n                PLOGE(\"readdir\");\n            return nullptr;\n        } else if (e->d_name == \".\"sv || e->d_name == \"..\"sv) {\n            // Filter . and .. for users\n            continue;\n        }\n        return e;\n    }\n}\n\n#ifndef SVB_WIN32\npid_t xsetsid() {\n    pid_t pid = setsid();\n    if (pid < 0) {\n        PLOGE(\"setsid\");\n    }\n    return pid;\n}\n\nint xsocket(int domain, int type, int protocol) {\n    int fd = socket(domain, type, protocol);\n    if (fd < 0) {\n        PLOGE(\"socket\");\n    }\n    return fd;\n}\n\nint xbind(int sockfd, const struct sockaddr *addr, socklen_t addrlen) {\n    int ret = bind(sockfd, addr, addrlen);\n    if (ret < 0) {\n        PLOGE(\"bind\");\n    }\n    return ret;\n}\n\nint xlisten(int sockfd, int backlog) {\n    int ret = listen(sockfd, backlog);\n    if (ret < 0) {\n        PLOGE(\"listen\");\n    }\n    return ret;\n}\n\nint xaccept4(int sockfd, struct sockaddr *addr, socklen_t *addrlen, int flags) {\n    int fd = accept4(sockfd, addr, addrlen, flags);\n    if (fd < 0) {\n        PLOGE(\"accept4\");\n    }\n    return fd;\n}\n#endif\n\nvoid *xmalloc(size_t size) {\n    void *p = malloc(size);\n    if (p == nullptr) {\n        PLOGE(\"malloc\");\n    }\n    return p;\n}\n\nvoid *xcalloc(size_t nmemb, size_t size) {\n    void *p = calloc(nmemb, size);\n    if (p == nullptr) {\n        PLOGE(\"calloc\");\n    }\n    return p;\n}\n\nvoid *xrealloc(void *ptr, size_t size) {\n    void *p = realloc(ptr, size);\n    if (p == nullptr) {\n        PLOGE(\"realloc\");\n    }\n    return p;\n}\n\n#ifndef SVB_WIN32\nssize_t xsendmsg(int sockfd, const struct msghdr *msg, int flags) {\n    int sent = sendmsg(sockfd, msg, flags);\n    if (sent < 0) {\n        PLOGE(\"sendmsg\");\n    }\n    return sent;\n}\n\nssize_t xrecvmsg(int sockfd, struct msghdr *msg, int flags) {\n    int rec = recvmsg(sockfd, msg, flags);\n    if (rec < 0) {\n        PLOGE(\"recvmsg\");\n    }\n    return rec;\n}\n\nint xpthread_create(pthread_t *thread, const pthread_attr_t *attr,\n                    void *(*start_routine) (void *), void *arg) {\n    errno = pthread_create(thread, attr, start_routine, arg);\n    if (errno) {\n        PLOGE(\"pthread_create\");\n    }\n    return errno;\n}\n#endif\nint xaccess(const char *path, int mode) {\n    int ret = access(path, mode);\n    if (ret < 0) {\n        PLOGE(\"access %s\", path);\n    }\n    return ret;\n}\n\nint xstat(const char *pathname, struct stat *buf) {\n    int ret = stat(pathname, buf);\n    if (ret < 0) {\n        PLOGE(\"stat %s\", pathname);\n    }\n    return ret;\n}\n\nint xlstat(const char *pathname, struct stat *buf) {\n    int ret = lstat(pathname, buf);\n    if (ret < 0) {\n        PLOGE(\"lstat %s\", pathname);\n    }\n    return ret;\n}\n\nint xfstat(int fd, struct stat *buf) {\n    int ret = fstat(fd, buf);\n    if (ret < 0) {\n        PLOGE(\"fstat %d\", fd);\n    }\n    return ret;\n}\n\n#ifndef SVB_MINGW\nint xfstatat(int dirfd, const char *pathname, struct stat *buf, int flags) {\n    int ret = fstatat(dirfd, pathname, buf, flags);\n    if (ret < 0) {\n        PLOGE(\"fstatat %s\", pathname);\n    }\n    return ret;\n}\n#endif\n\nint xdup(int fd) {\n    int ret = dup(fd);\n    if (ret < 0) {\n        PLOGE(\"dup\");\n    }\n    return ret;\n}\n\nint xdup2(int oldfd, int newfd) {\n    int ret = dup2(oldfd, newfd);\n    if (ret < 0) {\n        PLOGE(\"dup2\");\n    }\n    return ret;\n}\n\n#ifndef SVB_MINGW\nint xdup3(int oldfd, int newfd, int flags) {\n    int ret = dup3(oldfd, newfd, flags);\n    if (ret < 0) {\n        PLOGE(\"dup3\");\n    }\n    return ret;\n}\n#endif\n\nssize_t xreadlink(const char *pathname, char *buf, size_t bufsiz) {\n    ssize_t ret = readlink(pathname, buf, bufsiz);\n    if (ret < 0) {\n        PLOGE(\"readlink %s\", pathname);\n    } else {\n        buf[ret] = '\\0';\n    }\n    return ret;\n}\n\n#ifndef SVB_MINGW\nssize_t xreadlinkat(int dirfd, const char *pathname, char *buf, size_t bufsiz) {\n    // readlinkat() may fail on x86 platform, returning random value\n    // instead of number of bytes placed in buf (length of link)\n#if defined(__i386__) || defined(__x86_64__)\n    memset(buf, 0, bufsiz);\n    ssize_t ret = readlinkat(dirfd, pathname, buf, bufsiz);\n    if (ret < 0) {\n        PLOGE(\"readlinkat %s\", pathname);\n    }\n    return ret;\n#else\n    ssize_t ret = readlinkat(dirfd, pathname, buf, bufsiz);\n    if (ret < 0) {\n        PLOGE(\"readlinkat %s\", pathname);\n    } else {\n        buf[ret] = '\\0';\n    }\n    return ret;\n#endif\n}\n\nint xfaccessat(int dirfd, const char *pathname) {\n    int ret = faccessat(dirfd, pathname, F_OK, 0);\n    if (ret < 0) {\n        PLOGE(\"faccessat %s\", pathname);\n    }\n#if defined(__i386__) || defined(__x86_64__)\n    if (ret > 0 && errno == 0) {\n        LOGD(\"faccessat success but ret is %d\\n\", ret);\n        ret = 0;\n    }\n#endif\n    return ret;\n}\n#endif\n\n#if defined(SVB_WIN32) && !defined(SVB_MINGW)\n#define symlink xxsymlink\n#endif\nint xsymlink(const char *target, const char *linkpath) {\n    int ret = symlink(target, linkpath);\n    if (ret < 0) {\n        PLOGE(\"symlink %s->%s\", target, linkpath);\n    }\n    return ret;\n}\n\n#if defined SVB_WIN32 && !defined SVB_MINGW\n#define SYMLINK_ID\t\"!<symlink>\\xff\\xfe\"\n#define SYMLINK_IDLEN\tstrlen(SYMLINK_ID)\n#define SYMLINK_MAXSIZE\t1024\nint xxsymlink(const char *target, const char *file)\n{\n    int sz = strlen(target) + 1;\n    char buf[sz * sizeof(WCHAR)];\n\n    FILE *lnk = fopen(file, \"wb\");\n    if (!lnk || fprintf(lnk, SYMLINK_ID) < 0)\n        return -1;\n\n    if (MultiByteToWideChar(CP_UTF8, 0, target, sz, (LPWSTR)buf, sz) != sz) {\n        errno = EINVAL;\n        sz = -1;\n        goto err;\n    }\n    sz = fwrite(buf, 1, sizeof(buf), lnk);\n    if (sz != sizeof(buf)) {\n\tsz = -1;\n        goto err;\n    }\n    if (!SetFileAttributes(file, FILE_ATTRIBUTE_SYSTEM)) {\n        sz = -1;\n        goto err;\n    }\n    sz = 0;\nerr:\n    fclose(lnk);\n    return sz;\n}\n#endif\n\n#ifndef SVB_MINGW\nint xsymlinkat(const char *target, int newdirfd, const char *linkpath) {\n    int ret = symlinkat(target, newdirfd, linkpath);\n    if (ret < 0) {\n        PLOGE(\"symlinkat %s->%s\", target, linkpath);\n    }\n    return ret;\n}\n\nint xlinkat(int olddirfd, const char *oldpath, int newdirfd, const char *newpath, int flags) {\n    int ret = linkat(olddirfd, oldpath, newdirfd, newpath, flags);\n    if (ret < 0) {\n        PLOGE(\"linkat %s->%s\", oldpath, newpath);\n    }\n    return ret;\n}\n#endif\n\n#ifndef SVB_WIN32\nint xmount(const char *source, const char *target,\n    const char *filesystemtype, unsigned long mountflags,\n    const void *data) {\n    int ret = mount(source, target, filesystemtype, mountflags, data);\n    if (ret < 0) {\n        PLOGE(\"mount %s->%s\", source, target);\n    }\n    return ret;\n}\n\nint xumount(const char *target) {\n    int ret = umount(target);\n    if (ret < 0) {\n        PLOGE(\"umount %s\", target);\n    }\n    return ret;\n}\n\nint xumount2(const char *target, int flags) {\n    int ret = umount2(target, flags);\n    if (ret < 0) {\n        PLOGE(\"umount2 %s\", target);\n    }\n    return ret;\n}\n#endif\n\nint xrename(const char *oldpath, const char *newpath) {\n    int ret = rename(oldpath, newpath);\n    if (ret < 0) {\n        PLOGE(\"rename %s->%s\", oldpath, newpath);\n    }\n    return ret;\n}\n\nint xmkdir(const char *pathname, mode_t mode) {\n#ifdef SVB_MINGW\n#define mkdir(y, x) mkdir(y)\n#endif\n    int ret = mkdir(pathname, mode);\n    if (ret < 0 && errno != EEXIST) {\n        PLOGE(\"mkdir %s %u\", pathname, mode);\n    }\n    return ret;\n}\n\nint xmkdirs(const char *pathname, mode_t mode) {\n    int ret = mkdirs(pathname, mode);\n    if (ret < 0) {\n        PLOGE(\"mkdirs %s\", pathname);\n    }\n    return ret;\n}\n\n#ifndef SVB_MINGW\nint xmkdirat(int dirfd, const char *pathname, mode_t mode) {\n    int ret = mkdirat(dirfd, pathname, mode);\n    if (ret < 0 && errno != EEXIST) {\n        PLOGE(\"mkdirat %s %u\", pathname, mode);\n    }\n    return ret;\n}\n#endif\n\nvoid *xmmap(void *addr, size_t length, int prot, int flags,\n    int fd, off_t offset) {\n    void *ret = mmap(addr, length, prot, flags, fd, offset);\n    if (ret == MAP_FAILED) {\n        PLOGE(\"mmap\");\n        return nullptr;\n    }\n    return ret;\n}\n\nssize_t xsendfile(int out_fd, int in_fd, off_t *offset, size_t count) {\n    ssize_t ret = sendfile(out_fd, in_fd, offset, count);\n    if (ret < 0) {\n        PLOGE(\"sendfile\");\n    }\n    return ret;\n}\n\n#ifndef SVB_WIN32\npid_t xfork() {\n    int ret = fork();\n    if (ret < 0) {\n        PLOGE(\"fork\");\n    }\n    return ret;\n}\n\nint xpoll(struct pollfd *fds, nfds_t nfds, int timeout) {\n    int ret = poll(fds, nfds, timeout);\n    if (ret < 0) {\n        PLOGE(\"poll\");\n    }\n    return ret;\n}\n\nint xinotify_init1(int flags) {\n    int ret = inotify_init1(flags);\n    if (ret < 0) {\n        PLOGE(\"inotify_init1\");\n    }\n    return ret;\n}\n#endif\n\n#ifndef SVB_MINGW\nchar *xrealpath(const char *path, char *resolved_path) {\n    char buf[PATH_MAX];\n    char *ret = realpath(path, buf);\n    if (ret == nullptr) {\n        PLOGE(\"xrealpath\");\n    } else {\n        strcpy(resolved_path, buf);\n    }\n    return ret;\n}\n#endif\n\n#ifndef SVB_WIN32\nint xmknod(const char *pathname, mode_t mode, dev_t dev) {\n    int ret = mknod(pathname, mode, dev);\n    if (ret < 0) {\n        PLOGE(\"mknod\");\n    }\n    return ret;\n}\n\nlong xptrace(int request, pid_t pid, void *addr, void *data) {\n    long ret = ptrace(request, pid, addr, data);\n    if (ret < 0)\n        PLOGE(\"ptrace %d\", pid);\n    return ret;\n}\n#endif\n"
  },
  {
    "path": "magiskbase/xwrap.hpp",
    "content": "#pragma once\n\n#include <dirent.h>\n#include <stdio.h>\n#include <fcntl.h>\n#ifndef SVB_WIN32\n#include <pthread.h>\n#endif\n#if defined(SVB_WIN32) && !defined(SVB_MINGW)\n#include <poll.h>\n#endif\n\n#ifdef SVB_MINGW\n#include \"libnt.h\"\n#endif\n\n#ifndef SVB_WIN32\npid_t xfork();\nint xsetns(int fd, int nstype);\nint xunshare(int flags);\nint xmount(const char *source, const char *target,\n           const char *filesystemtype, unsigned long mountflags,\n           const void *data);\nint xumount(const char *target);\nint xumount2(const char *target, int flags);\nint xinotify_init1(int flags);\nint xmknod(const char *pathname, mode_t mode, dev_t dev);\nlong xptrace(int request, pid_t pid, void *addr = nullptr, void *data = nullptr);\nstatic inline long xptrace(int request, pid_t pid, void *addr, uintptr_t data) {\n    return xptrace(request, pid, addr, reinterpret_cast<void *>(data));\n}\nint xsocket(int domain, int type, int protocol);\nint xbind(int sockfd, const struct sockaddr *addr, socklen_t addrlen);9\nint xconnect(int sockfd, const struct sockaddr *addr, socklen_t addrlen);\nint xlisten(int sockfd, int backlog);\nint xaccept4(int sockfd, struct sockaddr *addr, socklen_t *addrlen, int flags);\nssize_t xsendmsg(int sockfd, const struct msghdr *msg, int flags);\nssize_t xrecvmsg(int sockfd, struct msghdr *msg, int flags);\nint xpthread_create(pthread_t *thread, const pthread_attr_t *attr,\n                    void *(*start_routine) (void *), void *arg);\n#else\nint xxsymlink(const char *target, const char *file);\n#endif\n\n#if defined(SVB_WIN32) && !defined(SVB_MINGW)\nint xpoll(struct pollfd *fds, nfds_t nfds, int timeout);\nint xopenat(int dirfd, const char *pathname, int flags);\nint xopenat(int dirfd, const char *pathname, int flags, mode_t mode);\nDIR *xfdopendir(int fd);\nint xpipe2(int pipefd[2], int flags);\nint xdup3(int oldfd, int newfd, int flags);\nint xsymlink(const char *target, const char *linkpath);\nint xsymlinkat(const char *target, int newdirfd, const char *linkpath);\nint xlinkat(int olddirfd, const char *oldpath, int newdirfd, const char *newpath, int flags);\nssize_t xreadlinkat(int dirfd, const char *pathname, char *buf, size_t bufsiz);\nint xmkdirat(int dirfd, const char *pathname, mode_t mode);\nchar *xrealpath(const char *path, char *resolved_path);\nint xfstatat(int dirfd, const char *pathname, struct stat *buf, int flags);\n#endif\n\nssize_t xreadlink(const char *pathname, char *buf, size_t bufsiz);\nFILE *xfopen(const char *pathname, const char *mode);\nFILE *xfdopen(int fd, const char *mode);\nint xopen(const char *pathname, int flags);\nint xopen(const char *pathname, int flags, mode_t mode);\nssize_t xwrite(int fd, const void *buf, size_t count);\nssize_t xread(int fd, void *buf, size_t count);\nssize_t xxread(int fd, void *buf, size_t count);\noff_t xlseek(int fd, off_t offset, int whence);\n\nDIR *xopendir(const char *name);\nstruct dirent *xreaddir(DIR *dirp);\nvoid *xmalloc(size_t size);\nvoid *xcalloc(size_t nmemb, size_t size);\nvoid *xrealloc(void *ptr, size_t size);\npid_t xsetsid();\nint xaccess(const char *path, int mode);\nint xstat(const char *pathname, struct stat *buf);\nint xlstat(const char *pathname, struct stat *buf);\nint xfstat(int fd, struct stat *buf);\nint xdup(int fd);\nint xdup2(int oldfd, int newfd);\nint xfaccessat(int dirfd, const char *pathname);\nint xrename(const char *oldpath, const char *newpath);\nint xmkdir(const char *pathname, mode_t mode);\nint xmkdirs(const char *pathname, mode_t mode);\nvoid *xmmap(void *addr, size_t length, int prot, int flags, int fd, off_t offset);\nssize_t xsendfile(int out_fd, int in_fd, off_t *offset, size_t count);\n#define WEVENT(s) (((s) & 0xffff0000) >> 16)\n"
  },
  {
    "path": "magiskboot.hpp",
    "content": "#pragma once\r\n\r\n#include <sys/types.h>\r\n\r\n#define HEADER_FILE     \"header\"\r\n#define KERNEL_FILE     \"kernel\"\r\n#define RAMDISK_FILE    \"ramdisk.cpio\"\r\n#define SECOND_FILE     \"second\"\r\n#define EXTRA_FILE      \"extra\"\r\n#define KER_DTB_FILE    \"kernel_dtb\"\r\n#define RECV_DTBO_FILE  \"recovery_dtbo\"\r\n#define DTB_FILE        \"dtb\"\r\n#define NEW_BOOT        \"new-boot.img\"\r\n\r\nint unpack(const char *image, bool skip_decomp = false, bool hdr = false);\r\nvoid repack(const char *src_img, const char *out_img, bool skip_comp = false);\r\nint split_image_dtb(const char *filename);\r\nint hexpatch(const char *file, const char *from, const char *to);\r\nint cpio_commands(int argc, char *argv[]);\r\nint dtb_commands(int argc, char *argv[]);\r\n\r\nuint32_t patch_verity(void *buf, uint32_t size);\r\nuint32_t patch_encryption(void *buf, uint32_t size);\r\nbool check_env(const char *name);\r\n"
  },
  {
    "path": "main.cpp",
    "content": "#include <mincrypt/sha.h>\n#include <base.hpp>\n\n#include \"magiskboot.hpp\"\n#include \"compress.hpp\"\n\nusing namespace std;\n\nstatic void print_formats() {\n    for (int fmt = GZIP; fmt < LZOP; ++fmt) {\n        fprintf(stderr, \"%s \", fmt2name[(format_t) fmt]);\n    }\n}\n\nstatic void usage(char *arg0) {\n    fprintf(stderr,\nR\"EOF(MagiskBoot - Boot Image Modification Tool\n\nUsage: %s <action> [args...]\n\nSupported actions:\n  unpack [-n] [-h] <bootimg>\n    Unpack <bootimg> to its individual components, each component to\n    a file with its corresponding file name in the current directory.\n    Supported components: kernel, kernel_dtb, ramdisk.cpio, second,\n    dtb, extra, and recovery_dtbo.\n    By default, each component will be automatically decompressed\n    on-the-fly before writing to the output file.\n    If '-n' is provided, all decompression operations will be skipped;\n    each component will remain untouched, dumped in its original format.\n    If '-h' is provided, the boot image header information will be\n    dumped to the file 'header', which can be used to modify header\n    configurations during repacking.\n    Return values:\n    0:valid    1:error    2:chromeos\n\n  repack [-n] <origbootimg> [outbootimg]\n    Repack boot image components using files from the current directory\n    to [outbootimg], or 'new-boot.img' if not specified.\n    <origbootimg> is the original boot image used to unpack the components.\n    By default, each component will be automatically compressed using its\n    corresponding format detected in <origbootimg>. If a component file\n    in the current directory is already compressed, then no addition\n    compression will be performed for that specific component.\n    If '-n' is provided, all compression operations will be skipped.\n    If env variable PATCHVBMETAFLAG is set to true, all disable flags in\n    the boot image's vbmeta header will be set.\n\n  hexpatch <file> <hexpattern1> <hexpattern2>\n    Search <hexpattern1> in <file>, and replace it with <hexpattern2>\n\n  cpio <incpio> [commands...]\n    Do cpio commands to <incpio> (modifications are done in-place)\n    Each command is a single argument, add quotes for each command.\n    Supported commands:\n      exists ENTRY\n        Return 0 if ENTRY exists, else return 1\n      rm [-r] ENTRY\n        Remove ENTRY, specify [-r] to remove recursively\n      mkdir MODE ENTRY\n        Create directory ENTRY in permissions MODE\n      ln TARGET ENTRY\n        Create a symlink to TARGET with the name ENTRY\n      mv SOURCE DEST\n        Move SOURCE to DEST\n      add MODE ENTRY INFILE\n        Add INFILE as ENTRY in permissions MODE; replaces ENTRY if exists\n      extract [ENTRY OUT]\n        Extract ENTRY to OUT, or extract all entries to \"ramdisk\" directory.\n        Creates \"cpio\" config file to support modes changes in Windows.\n      sync\n        Synchronize \"ramdisk\" directory with incpio entries.\n        Reads entries mode from \"cpio\" config.\n        Any changes will be captured and dumped to incpio.\n      test\n        Test the cpio's status\n        Return value is 0 or bitwise or-ed of following values:\n        0x1:Magisk    0x2:unsupported    0x4:Sony\n      patch\n        Apply ramdisk patches\n        Configure with env variables: KEEPVERITY KEEPFORCEENCRYPT\n      backup ORIG\n        Create ramdisk backups from ORIG\n      restore\n        Restore ramdisk from ramdisk backup stored within incpio\n      sha1\n        Print stock boot SHA1 if previously backed up in ramdisk\n  cpio pack [-c <config>] <infolder> <outcpio>\n    Creates <outcpio> from <infolder> entries.\n    Entries mode are read from <config> (\"cpio\" if undefined) to support changing modes in Windows.\n\n  dtb <file> <action> [args...]\n    Do dtb related actions to <file>\n    Supported actions:\n      print [-f]\n        Print all contents of dtb for debugging\n        Specify [-f] to only print fstab nodes\n      patch\n        Search for fstab and remove verity/avb\n        Modifications are done directly to the file in-place\n        Configure with env variables: KEEPVERITY\n      test\n        Test the fstab's status\n        Return values:\n        0:valid    1:error\n\n  split <file>\n    Split image.*-dtb into kernel + kernel_dtb\n\n  sha1 <file>\n    Print the SHA1 checksum for <file>\n\n  cleanup\n    Cleanup the current working directory\n\n  compress[=format] <infile> [outfile]\n    Compress <infile> with [format] to [outfile].\n    <infile>/[outfile] can be '-' to be STDIN/STDOUT.\n    If [format] is not specified, then gzip will be used.\n    If [outfile] is not specified, then <infile> will be replaced\n    with another file suffixed with a matching file extension.\n    Supported formats: )EOF\", arg0);\n\n    print_formats();\n\n    fprintf(stderr, R\"EOF(\n\n  decompress <infile> [outfile]\n    Detect format and decompress <infile> to [outfile].\n    <infile>/[outfile] can be '-' to be STDIN/STDOUT.\n    If [outfile] is not specified, then <infile> will be replaced\n    with another file removing its archive format file extension.\n    Supported formats: )EOF\");\n\n    print_formats();\n\n    fprintf(stderr, \"\\n\\n\");\n    exit(1);\n}\n\nint main(int argc, char *argv[]) {\n\n    if (argc < 2)\n        usage(argv[0]);\n\n    // Skip '--' for backwards compatibility\n    string_view action(argv[1]);\n    if (str_starts(action, \"--\"))\n        action = argv[1] + 2;\n\n    if (action == \"cleanup\") {\n        fprintf(stderr, \"Cleaning up...\\n\");\n        unlink(HEADER_FILE);\n        unlink(KERNEL_FILE);\n        unlink(RAMDISK_FILE);\n        unlink(SECOND_FILE);\n        unlink(KER_DTB_FILE);\n        unlink(EXTRA_FILE);\n        unlink(RECV_DTBO_FILE);\n        unlink(DTB_FILE);\n    } else if (argc > 2 && action == \"sha1\") {\n        uint8_t sha1[SHA_DIGEST_SIZE];\n        auto m = mmap_data(argv[2]);\n        SHA_hash(m.buf, m.sz, sha1);\n        for (uint8_t i : sha1)\n            printf(\"%02x\", i);\n        printf(\"\\n\");\n    } else if (argc > 2 && action == \"split\") {\n        return split_image_dtb(argv[2]);\n    } else if (argc > 2 && action == \"unpack\") {\n        int idx = 2;\n        bool nodecomp = false;\n        bool hdr = false;\n        for (;;) {\n            if (idx >= argc)\n                usage(argv[0]);\n            if (argv[idx][0] != '-')\n                break;\n            for (char *flag = &argv[idx][1]; *flag; ++flag) {\n                if (*flag == 'n')\n                    nodecomp = true;\n                else if (*flag == 'h')\n                    hdr = true;\n                else\n                    usage(argv[0]);\n            }\n            ++idx;\n        }\n        return unpack(argv[idx], nodecomp, hdr);\n    } else if (argc > 2 && action == \"repack\") {\n        if (argv[2] == \"-n\"sv) {\n            if (argc == 3)\n                usage(argv[0]);\n            repack(argv[3], argv[4] ? argv[4] : NEW_BOOT, true);\n        } else {\n            repack(argv[2], argv[3] ? argv[3] : NEW_BOOT);\n        }\n    } else if (argc > 2 && action == \"decompress\") {\n        decompress(argv[2], argv[3]);\n    } else if (argc > 2 && str_starts(action, \"compress\")) {\n        compress(action[8] == '=' ? &action[9] : \"gzip\", argv[2], argv[3]);\n    } else if (argc > 4 && action == \"hexpatch\") {\n        return hexpatch(argv[2], argv[3], argv[4]);\n    } else if (argc > 2 && action == \"cpio\"sv) {\n        if (cpio_commands(argc - 2, argv + 2))\n            usage(argv[0]);\n    } else if (argc > 3 && action == \"dtb\") {\n        if (dtb_commands(argc - 2, argv + 2))\n            usage(argv[0]);\n    } else {\n        usage(argv[0]);\n    }\n\n    return 0;\n}\n"
  },
  {
    "path": "pattern.cpp",
    "content": "#include <base.hpp>\n\n#include \"magiskboot.hpp\"\n\n#define MATCH(p) else if (strncmp(s + skip, p, sizeof(p) - 1) == 0) skip += (sizeof(p) - 1)\n\nstatic int skip_verity_pattern(const char *s) {\n    int skip = s[0] == ',';\n\n    if (0) {}\n    MATCH(\"verifyatboot\");\n    MATCH(\"verify\");\n    MATCH(\"avb_keys\");\n    MATCH(\"avb\");\n    MATCH(\"support_scfs\");\n    MATCH(\"fsverity\");\n    else return -1;\n\n    if (s[skip] == '=') {\n        while (!strchr(\" \\n,\", s[skip]))\n            ++skip;\n    }\n    return skip;\n}\n\nstatic int skip_encryption_pattern(const char *s) {\n    int skip = s[0] == ',';\n\n    if (0) {}\n    MATCH(\"forceencrypt\");\n    MATCH(\"forcefdeorfbe\");\n    MATCH(\"fileencryption\");\n    else return -1;\n\n    if (s[skip] == '=') {\n        while (!strchr(\" \\n,\", s[skip]))\n            ++skip;\n    }\n    return skip;\n}\n\nstatic uint32_t remove_pattern(char *src, uint32_t size, int(*pattern_skip)(const char *)) {\n    int orig_sz = size;\n    int write = 0;\n    for (int read = 0; read < orig_sz;) {\n        if (int skip = pattern_skip(src + read); skip > 0) {\n            fprintf(stderr, \"Remove pattern [%.*s]\\n\", skip, src + read);\n            size -= skip;\n            read += skip;\n        } else {\n            src[write++] = src[read++];\n        }\n    }\n    memset(src + write, 0, orig_sz - write);\n    return size;\n}\n\nuint32_t patch_verity(void *buf, uint32_t size) {\n    return remove_pattern(static_cast<char *>(buf), size, skip_verity_pattern);\n}\n\nuint32_t patch_encryption(void *buf, uint32_t size) {\n    return remove_pattern(static_cast<char *>(buf), size, skip_encryption_pattern);\n}\n"
  },
  {
    "path": "ramdisk.cpp",
    "content": "#include <base.hpp>\r\n\r\n#include \"cpio.hpp\"\r\n#include \"magiskboot.hpp\"\r\n#include \"compress.hpp\"\r\n\r\nusing namespace std;\r\n\r\nstatic const char *UNSUPPORT_LIST[] =\r\n        { \"sbin/launch_daemonsu.sh\", \"sbin/su\", \"init.xposed.rc\",\r\n          \"boot/sbin/launch_daemonsu.sh\" };\r\n\r\nstatic const char *MAGISK_LIST[] =\r\n        { \".backup/.magisk\", \"init.magisk.rc\",\r\n          \"overlay/init.magisk.rc\" };\r\n\r\nclass magisk_cpio : public cpio {\r\npublic:\r\n    void patch();\r\n    int test();\r\n    char *sha1();\r\n    void restore();\r\n    void backup(const char *orig);\r\n};\r\n\r\nbool check_env(const char *name) {\r\n    const char *val = getenv(name);\r\n    return val != nullptr && val == \"true\"sv;\r\n}\r\n\r\nvoid magisk_cpio::patch() {\r\n    bool keepverity = check_env(\"KEEPVERITY\");\r\n    bool keepforceencrypt = check_env(\"KEEPFORCEENCRYPT\");\r\n    fprintf(stderr, \"Patch with flag KEEPVERITY=[%s] KEEPFORCEENCRYPT=[%s]\\n\",\r\n            keepverity ? \"true\" : \"false\", keepforceencrypt ? \"true\" : \"false\");\r\n\r\n    for (auto it = entries.begin(); it != entries.end();) {\r\n        auto cur = it++;\r\n        bool fstab = (!keepverity || !keepforceencrypt) &&\r\n                     S_ISREG(cur->second->mode) &&\r\n                     !str_starts(cur->first, \".backup\") &&\r\n                     !str_contains(cur->first, \"twrp\") &&\r\n                     !str_contains(cur->first, \"recovery\") &&\r\n                     str_contains(cur->first, \"fstab\");\r\n        if (!keepverity) {\r\n            if (fstab) {\r\n                fprintf(stderr, \"Found fstab file [%s]\\n\", cur->first.data());\r\n                cur->second->filesize = patch_verity(cur->second->data, cur->second->filesize);\r\n            } else if (cur->first == \"verity_key\") {\r\n                rm(cur);\r\n                continue;\r\n            }\r\n        }\r\n        if (!keepforceencrypt) {\r\n            if (fstab) {\r\n                cur->second->filesize = patch_encryption(cur->second->data, cur->second->filesize);\r\n            }\r\n        }\r\n    }\r\n}\r\n\r\n#define MAGISK_PATCHED    (1 << 0)\r\n#define UNSUPPORTED_CPIO  (1 << 1)\r\n#define SONY_INIT         (1 << 2)\r\n\r\nint magisk_cpio::test() {\r\n    int ret = 0;\r\n    for (auto file : UNSUPPORT_LIST) {\r\n        if (exists(file)) {\r\n            return UNSUPPORTED_CPIO;\r\n        }\r\n    }\r\n    for (auto file : MAGISK_LIST) {\r\n        if (exists(file)) {\r\n            ret |= MAGISK_PATCHED;\r\n            break;\r\n        }\r\n    }\r\n    if (exists(\"init.real\"))\r\n        ret |= SONY_INIT;\r\n    return ret;\r\n}\r\n\r\n#define for_each_line(line, buf, size) \\\r\nfor (char *line = (char *) buf; line < (char *) buf + size && line[0]; line = strchr(line + 1, '\\n') + 1)\r\n\r\nchar *magisk_cpio::sha1() {\r\n    char sha1[41];\r\n    for (auto &e : entries) {\r\n        if (e.first == \"init.magisk.rc\" || e.first == \"overlay/init.magisk.rc\") {\r\n            for_each_line(line, e.second->data, e.second->filesize) {\r\n                if (strncmp(line, \"#STOCKSHA1=\", 11) == 0) {\r\n                    strncpy(sha1, line + 12, 40);\r\n                    sha1[40] = '\\0';\r\n                    return strdup(sha1);\r\n                }\r\n            }\r\n        } else if (e.first == \".backup/.magisk\") {\r\n            for_each_line(line, e.second->data, e.second->filesize) {\r\n                if (str_starts(line, \"SHA1=\")) {\r\n                    strncpy(sha1, line + 5, 40);\r\n                    sha1[40] = '\\0';\r\n                    return strdup(sha1);\r\n                }\r\n            }\r\n        } else if (e.first == \".backup/.sha1\") {\r\n            return (char *) e.second->data;\r\n        }\r\n    }\r\n    return nullptr;\r\n}\r\n\r\n#define for_each_str(str, buf, size) \\\r\nfor (char *str = (char *) buf; str < (char *) buf + size; str += strlen(str) + 1)\r\n\r\nvoid magisk_cpio::restore() {\r\n    // Collect files\r\n    auto bk = entries.end();\r\n    auto rl = entries.end();\r\n    auto mg = entries.end();\r\n    vector<entry_map::iterator> backups;\r\n    for (auto it = entries.begin(); it != entries.end(); ++it) {\r\n        if (it->first == \".backup\") {\r\n            bk = it;\r\n        } else if (it->first == \".backup/.rmlist\") {\r\n            rl = it;\r\n        } else if (it->first == \".backup/.magisk\") {\r\n            mg = it;\r\n        } else if (str_starts(it->first, \".backup/\")) {\r\n            backups.emplace_back(it);\r\n        }\r\n    }\r\n\r\n    // If the .backup folder is effectively empty, this means that the boot ramdisk was\r\n    // created from scratch by an old broken magiskboot. This is just a hacky workaround.\r\n    if (bk != entries.end() && mg != entries.end() && rl == entries.end() && backups.empty()) {\r\n        fprintf(stderr, \"Remove all in ramdisk\\n\");\r\n        entries.clear();\r\n        return;\r\n    }\r\n\r\n    // Remove files\r\n    rm(bk);\r\n    rm(mg);\r\n    if (rl != entries.end()) {\r\n        for_each_str(file, rl->second->data, rl->second->filesize) {\r\n            rm(file);\r\n        }\r\n        rm(rl);\r\n    }\r\n\r\n    // Restore files\r\n    for (auto it : backups) {\r\n        const char *name = &it->first[8];\r\n        mv(it, name);\r\n    }\r\n}\r\n\r\nvoid magisk_cpio::backup(const char *orig) {\r\n    entry_map backups;\r\n    string rm_list;\r\n    backups.emplace(\".backup\", new cpio_entry(S_IFDIR));\r\n\r\n    magisk_cpio o;\r\n    if (access(orig, R_OK) == 0)\r\n        o.load_cpio(orig);\r\n\r\n    // Remove existing backups in original ramdisk\r\n    o.rm(\".backup\", true);\r\n    rm(\".backup\", true);\r\n\r\n    auto lhs = o.entries.begin();\r\n    auto rhs = entries.begin();\r\n\r\n    while (lhs != o.entries.end() || rhs != entries.end()) {\r\n        int res;\r\n        bool do_backup = false;\r\n        if (lhs != o.entries.end() && rhs != entries.end()) {\r\n            res = lhs->first.compare(rhs->first);\r\n        } else if (lhs == o.entries.end()) {\r\n            res = 1;\r\n        } else {\r\n            res = -1;\r\n        }\r\n\r\n        if (res < 0) {\r\n            // Something is missing in new ramdisk, do_backup!\r\n            do_backup = true;\r\n            fprintf(stderr, \"Backup missing entry: \");\r\n        } else if (res == 0) {\r\n            if (lhs->second->filesize != rhs->second->filesize ||\r\n                memcmp(lhs->second->data, rhs->second->data, lhs->second->filesize) != 0) {\r\n                // Not the same!\r\n                do_backup = true;\r\n                fprintf(stderr, \"Backup mismatch entry: \");\r\n            }\r\n        } else {\r\n            // Something new in ramdisk\r\n            rm_list += rhs->first;\r\n            rm_list += (char) '\\0';\r\n            fprintf(stderr, \"Record new entry: [%s] -> [.backup/.rmlist]\\n\", rhs->first.data());\r\n        }\r\n\r\n        if (do_backup) {\r\n            string name = \".backup/\" + lhs->first;\r\n            fprintf(stderr, \"[%s] -> [%s]\\n\", lhs->first.data(), name.data());\r\n            auto e = lhs->second.release();\r\n            backups.emplace(name, e);\r\n        }\r\n\r\n        // Increment positions\r\n        if (res < 0) {\r\n            ++lhs;\r\n        } else if (res == 0) {\r\n            ++lhs; ++rhs;\r\n        } else {\r\n            ++rhs;\r\n        }\r\n    }\r\n\r\n    if (!rm_list.empty()) {\r\n        auto rm_list_file = new cpio_entry(S_IFREG);\r\n        rm_list_file->filesize = rm_list.length();\r\n        rm_list_file->data = xmalloc(rm_list.length());\r\n        memcpy(rm_list_file->data, rm_list.data(), rm_list.length());\r\n        backups.emplace(\".backup/.rmlist\", rm_list_file);\r\n    }\r\n\r\n    if (backups.size() > 1)\r\n        entries.merge(backups);\r\n}\r\n\r\nint cpio_commands(int argc, char *argv[]) {\r\n    magisk_cpio cpio;\r\n\r\n    /* pack doesn`t need incpio */\r\n    if (argc >= 3 && argv[0] == \"pack\"sv) {\r\n        bool c = argc == 5 && argv[1] == \"-c\"sv;\r\n        cpio.load_cpio(argv[1 + 2*c], c ? argv[2] : \"cpio\", false);\r\n        cpio.dump(argv[2 + 2*c]);\r\n        return 0;\r\n    }\r\n\r\n    char *incpio = argv[0];\r\n    ++argv;\r\n    --argc;\r\n\r\n    if (access(incpio, R_OK) == 0)\r\n        cpio.load_cpio(incpio);\r\n\r\n    unsigned int cmdc;\r\n    char *cmdv[6];\r\n\r\n    for (int i = 0; i < argc; ++i) {\r\n        // Reset\r\n        cmdc = 0;\r\n        memset(cmdv, 0, sizeof(cmdv));\r\n\r\n        // Split the commands\r\n        char *tok = strtok(argv[i], \" \");\r\n        while (tok && cmdc < std::size(cmdv)) {\r\n            if (cmdc == 0 && tok[0] == '#')\r\n                break;\r\n            cmdv[cmdc++] = tok;\r\n            tok = strtok(nullptr, \" \");\r\n        }\r\n\r\n        if (cmdc == 0)\r\n            continue;\r\n\r\n        if (cmdv[0] == \"test\"sv) {\r\n            exit(cpio.test());\r\n        } else if (cmdv[0] == \"restore\"sv) {\r\n            cpio.restore();\r\n        } else if (cmdv[0] == \"sha1\"sv) {\r\n            char *sha1 = cpio.sha1();\r\n            if (sha1) printf(\"%s\\n\", sha1);\r\n            return 0;\r\n        } else if (cmdv[0] == \"patch\"sv) {\r\n            cpio.patch();\r\n        } else if (cmdc == 2 && cmdv[0] == \"exists\"sv) {\r\n            exit(!cpio.exists(cmdv[1]));\r\n        } else if (cmdc == 2 && cmdv[0] == \"backup\"sv) {\r\n            cpio.backup(cmdv[1]);\r\n        } else if (cmdc >= 2 && cmdv[0] == \"rm\"sv) {\r\n            bool r = cmdc > 2 && cmdv[1] == \"-r\"sv;\r\n            cpio.rm(cmdv[1 + r], r);\r\n        } else if (cmdc == 3 && cmdv[0] == \"mv\"sv) {\r\n            cpio.mv(cmdv[1], cmdv[2]);\r\n        } else if (cmdv[0] == \"extract\"sv) {\r\n            if (cmdc == 3) {\r\n                return !cpio.extract(cmdv[1], cmdv[2]);\r\n            } else {\r\n                cpio.extract();\r\n                return 0;\r\n            }\r\n        } else if (cmdv[0] == \"sync\"sv) {\r\n            cpio.load_cpio(\"ramdisk\", \"cpio\", true);\r\n        } else if (cmdc == 3 && cmdv[0] == \"mkdir\"sv) {\r\n            cpio.mkdir(strtoul(cmdv[1], nullptr, 8), cmdv[2]);\r\n        } else if (cmdc == 3 && cmdv[0] == \"ln\"sv) {\r\n            cpio.ln(cmdv[1], cmdv[2]);\r\n        } else if (cmdc == 4 && cmdv[0] == \"add\"sv) {\r\n            cpio.add(strtoul(cmdv[1], nullptr, 8), cmdv[2], cmdv[3]);\r\n        } else {\r\n            return 1;\r\n        }\r\n    }\r\n\r\n    cpio.dump(incpio);\r\n    return 0;\r\n}\r\n"
  },
  {
    "path": "scripts/mkdir.sh",
    "content": "#!/clang64/xbin/ash\r\n# mkdir-wrapper to create directories only when required\r\nset -e\r\n\r\nMKDIR_FLAGS=\"\"\r\nDIRS=\"\"\r\n\r\nwhile [[ $# -gt 0 ]]; do # last arg(s) are/is DIRECTORY(ies)\r\n    case \"$1\" in\r\n        --help|--version);; # ignored, for production.\r\n        -m) MKDIR_FLAGS=\"${MKDIR_FLAGS} $1 $2 \"; shift;; # pass args accordingly\r\n        -*|--*) MKDIR_FLAGS=\"${MKDIR_FLAGS} $1 \";;\r\n        *) [ -d \"$1\" ] || { DIR=${1//$TOPDIR\\//}; echo -e \"  MKDIR\\t    ${DIR}\"; DIRS=\"${DIRS} $1 \"; } ;; # this is a file\r\n    esac\r\n    shift\r\ndone\r\n\r\n[ -n \"$DIRS\" ] || exit 0\r\n\r\neval mkdir ${MKDIR_FLAGS} ${DIRS}\r\n\r\nexit $?"
  },
  {
    "path": "scripts/strip.sh",
    "content": "#!/bin/bash\r\n# strip-wrapper to generate NEW stripped files out of INPUT\r\nset -e\r\n\r\n[[ $DEBUG -eq 1 ]] && exit 0 # target only rel builds\r\n\r\nSTANDALONE_STRIPPED=false\r\nSTRIP_FLAGS=\"\"\r\n\r\n$STANDALONE_STRIPPED && eval ${SH} ${MKDIR} ${SRP} # use our mkdir wrapper\r\n\r\nwhile [[ $# -gt 0 ]]; do # last arg(s) are/is file(s)\r\n    #echo \"info: arg: $1\"\r\n    if [[ -n \"$FILE_NAME\" && \"$1\" =~ ^- ]]; then\r\n\t\techo \"strip: invalid arguments\"\r\n\t\texit 1\r\n    fi\r\n    case \"$1\" in\r\n        -o) shift;; # ignored, we will generate it conditionally.\r\n        -V|--version);; # ignored, for production.\r\n        -K|-N|-R) STRIP_FLAGS=\"${STRIP_FLAGS} $1 $2 \"; shift;; # pass args accordingly\r\n        -*|--*) STRIP_FLAGS=\"${STRIP_FLAGS} $1 \";;\r\n        *) FILE_NAME=\"$(basename \"$1\")\"; echo -e \"  STRIP     $FILE_NAME\"; $STANDALONE_STRIPPED && FILE_NAME=\"-o ${SRP}/$FILE_NAME $1\" || FILE_NAME=\"$1\"; STRIP_FLAGS=\"${STRIP_FLAGS} $FILE_NAME \";;#eval $TOPDIR/scripts/genpdb.sh \"$FILE_NAME\r\n    esac\r\n    shift\r\ndone\r\n\r\neval ${STRIP_CMD} ${STRIP_FLAGS}\r\n\r\nexit $?\r\n"
  }
]