├── .clang-format ├── .github └── workflows │ ├── c-cpp.yml │ ├── ci-fuzz.yml │ └── release.yml ├── .gitignore ├── .travis.yml ├── CMakeLists.txt ├── CMakePresets.json ├── ChangeLog.md ├── Config.cmake.in ├── LICENSE ├── amalgamate.sh ├── examples ├── example1.c ├── example2.c ├── example3.c ├── example4.c ├── example5.c └── example6.c ├── meson.build ├── miniz.c ├── miniz.h ├── miniz.pc.in ├── miniz_common.h ├── miniz_tdef.c ├── miniz_tdef.h ├── miniz_tinfl.c ├── miniz_tinfl.h ├── miniz_zip.c ├── miniz_zip.h ├── readme.md ├── test.sh └── tests ├── catch_amalgamated.cpp ├── catch_amalgamated.hpp ├── checksum_fuzzer.c ├── compress_fuzzer.c ├── flush_fuzzer.c ├── fuzz_main.c ├── large_fuzzer.c ├── main.cpp ├── miniz_tester.cpp ├── ossfuzz.sh ├── small_fuzzer.c ├── timer.cpp ├── timer.h ├── uncompress2_fuzzer.c ├── uncompress_fuzzer.c ├── zip.dict └── zip_fuzzer.c /.clang-format: -------------------------------------------------------------------------------- 1 | # 2 | # http://clang.llvm.org/docs/ClangFormatStyleOptions.html 3 | # 4 | AccessModifierOffset: -4 5 | ConstructorInitializerIndentWidth: 4 6 | AlignEscapedNewlinesLeft: false 7 | AlignTrailingComments: true 8 | AllowAllParametersOfDeclarationOnNextLine: true 9 | AllowShortIfStatementsOnASingleLine: false 10 | AllowShortLoopsOnASingleLine: false 11 | AlwaysBreakTemplateDeclarations: false 12 | AlwaysBreakBeforeMultilineStrings: false 13 | BreakBeforeBinaryOperators: false 14 | BreakBeforeTernaryOperators: true 15 | BreakConstructorInitializersBeforeComma: false 16 | BinPackParameters: true 17 | ColumnLimit: 0 18 | ConstructorInitializerAllOnOneLineOrOnePerLine: false 19 | DerivePointerBinding: false 20 | ExperimentalAutoDetectBinPacking: false 21 | IndentCaseLabels: true 22 | MaxEmptyLinesToKeep: 1 23 | NamespaceIndentation: All 24 | ObjCSpaceBeforeProtocolList: true 25 | PenaltyBreakBeforeFirstCallParameter: 19 26 | PenaltyBreakComment: 60 27 | PenaltyBreakString: 1000 28 | PenaltyBreakFirstLessLess: 120 29 | PenaltyExcessCharacter: 1000000 30 | PenaltyReturnTypeOnItsOwnLine: 60 31 | PointerBindsToType: false 32 | SpacesBeforeTrailingComments: 1 33 | Cpp11BracedListStyle: false 34 | Standard: Cpp03 35 | IndentWidth: 4 36 | TabWidth: 4 37 | UseTab: Never 38 | BreakBeforeBraces: Allman 39 | IndentFunctionDeclarationAfterType: false 40 | SpacesInParentheses: false 41 | SpacesInAngles: false 42 | SpaceInEmptyParentheses: false 43 | SpacesInCStyleCastParentheses: false 44 | SpaceAfterControlStatementKeyword: true 45 | SpaceBeforeAssignmentOperators: true 46 | ContinuationIndentWidth: 4 47 | -------------------------------------------------------------------------------- /.github/workflows/c-cpp.yml: -------------------------------------------------------------------------------- 1 | name: C/C++ CI 2 | 3 | on: 4 | push: 5 | branches: [ master ] 6 | pull_request: 7 | branches: [ master ] 8 | 9 | jobs: 10 | build: 11 | 12 | runs-on: ubuntu-latest 13 | 14 | steps: 15 | - uses: actions/checkout@v2 16 | - name: amalgamate 17 | run: bash amalgamate.sh 18 | - name: Run CMake consuming CMakePreset.json and run tests 19 | uses: lukka/run-cmake@v10 20 | with: 21 | # This is the name of the CMakePresets.json's configuration to use to generate 22 | # the project files. This configuration leverages the vcpkg.cmake toolchain file to 23 | # run vcpkg and install all dependencies specified in vcpkg.json. 24 | configurePreset: 'gcc' 25 | # Additional arguments can be appended to the cmake command. 26 | # This is useful to reduce the number of CMake's Presets since you can reuse 27 | # an existing preset with different variables. 28 | configurePresetAdditionalArgs: "['-DENABLE_YOUR_FEATURE=1']" 29 | # This is the name of the CMakePresets.json's configuration to build the project. 30 | buildPreset: 'gcc' 31 | # Additional arguments can be appended when building, for example to specify the 32 | # configuration to build. 33 | # This is useful to reduce the number of CMake's Presets you need in CMakePresets.json. 34 | buildPresetAdditionalArgs: "['--config Release']" 35 | 36 | # This is the name of the CMakePresets.json's configuration to test the project with. 37 | testPreset: 'gcc' 38 | # Additional arguments can be appended when testing, for example to specify the config 39 | # to test. 40 | # This is useful to reduce the number of CMake's Presets you need in CMakePresets.json. 41 | testPresetAdditionalArgs: "['--config Release']" 42 | -------------------------------------------------------------------------------- /.github/workflows/ci-fuzz.yml: -------------------------------------------------------------------------------- 1 | name: CIFuzz 2 | on: [pull_request] 3 | jobs: 4 | Fuzzing: 5 | runs-on: ubuntu-latest 6 | steps: 7 | - name: Build Fuzzers 8 | uses: google/oss-fuzz/infra/cifuzz/actions/build_fuzzers@master 9 | with: 10 | oss-fuzz-project-name: 'miniz' 11 | dry-run: false 12 | - name: Run Fuzzers 13 | uses: google/oss-fuzz/infra/cifuzz/actions/run_fuzzers@master 14 | with: 15 | oss-fuzz-project-name: 'miniz' 16 | fuzz-seconds: 900 17 | dry-run: false 18 | - name: Upload Crash 19 | uses: actions/upload-artifact@v1 20 | if: failure() 21 | with: 22 | name: artifacts 23 | path: ./out/artifacts -------------------------------------------------------------------------------- /.github/workflows/release.yml: -------------------------------------------------------------------------------- 1 | name: Create release 2 | 3 | # Controls when the action will run. 4 | on: 5 | # Allows you to run this workflow manually from the Actions tab 6 | workflow_dispatch: 7 | 8 | jobs: 9 | build: 10 | name: Create new release 11 | runs-on: ubuntu-latest 12 | 13 | steps: 14 | # Checks-out your repository under $GITHUB_WORKSPACE, so your job can access it 15 | - name: Checkout code 16 | uses: actions/checkout@v2 17 | with: 18 | path: source 19 | 20 | - name: Install dependencies 21 | run: | 22 | sudo apt-get install -y cmake 23 | 24 | - name: Configure 25 | run: | 26 | mkdir build 27 | mkdir inst 28 | cd build 29 | cmake ../source -G"Unix Makefiles" -DAMALGAMATE_SOURCES=ON -DCMAKE_INSTALL_PREFIX=../inst 30 | 31 | - name: Build 32 | run: | 33 | cd build 34 | make install 35 | 36 | - name: Get current version 37 | id: relver 38 | run: echo "::set-output name=relver::$(cat build/miniz.pc | grep Version | cut -d ':' -f2 | xargs)" 39 | 40 | - name: Create Release 41 | id: create_release 42 | uses: actions/create-release@v1 43 | env: 44 | GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} 45 | with: 46 | tag_name: ${{ steps.relver.outputs.relver }} 47 | release_name: Release ${{ steps.relver.outputs.relver }} 48 | draft: false 49 | prerelease: false 50 | 51 | - name: Upload Release Asset 52 | id: upload-release-asset 53 | uses: actions/upload-release-asset@v1 54 | env: 55 | GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} 56 | with: 57 | upload_url: ${{ steps.create_release.outputs.upload_url }} 58 | asset_path: ./build/miniz-${{ steps.relver.outputs.relver }}.zip 59 | asset_name: miniz-${{ steps.relver.outputs.relver }}.zip 60 | asset_content_type: application/zip -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | /_build 2 | /amalgamation 3 | /bin 4 | -------------------------------------------------------------------------------- /.travis.yml: -------------------------------------------------------------------------------- 1 | language: c 2 | script: bash amalgamate.sh -------------------------------------------------------------------------------- /CMakeLists.txt: -------------------------------------------------------------------------------- 1 | cmake_minimum_required(VERSION 3.5) 2 | 3 | # determine whether this is a standalone project or included by other projects 4 | set (MINIZ_STANDALONE_PROJECT ON) 5 | if(DEFINED PROJECT_NAME) 6 | set(MINIZ_STANDALONE_PROJECT OFF) 7 | endif() 8 | 9 | if(CMAKE_MINOR_VERSION LESS 12) 10 | project(miniz) 11 | # see issue https://gitlab.kitware.com/cmake/cmake/merge_requests/1799 12 | else() 13 | project(miniz) 14 | set(CMAKE_C_STANDARD 90) 15 | set(CMAKE_VERBOSE_MAKEFILE ON) 16 | # set(CMAKE_C_VISIBILITY_PRESET hidden) 17 | # set(CMAKE_VISIBILITY_INLINES_HIDDEN YES) 18 | 19 | if (MSVC) 20 | set(CMAKE_C_FLAGS "${CMAKE_C_FLAGS} /W3 /Zi /permissive-") 21 | else () 22 | set(CMAKE_C_FLAGS "${CMAKE_C_FLAGS} -Wshadow -Wformat=2 -Wall -Wno-overlength-strings -pedantic") 23 | endif () 24 | endif() 25 | 26 | set(MINIZ_API_VERSION 3) 27 | set(MINIZ_MINOR_VERSION 0) 28 | set(MINIZ_PATCH_VERSION 2) 29 | set(MINIZ_VERSION 30 | ${MINIZ_API_VERSION}.${MINIZ_MINOR_VERSION}.${MINIZ_PATCH_VERSION}) 31 | 32 | if(CMAKE_BUILD_TYPE STREQUAL "") 33 | # CMake defaults to leaving CMAKE_BUILD_TYPE empty. This screws up 34 | # differentiation between debug and release builds. 35 | set(CMAKE_BUILD_TYPE "Release" CACHE STRING 36 | "Choose the type of build, options are: None (CMAKE_CXX_FLAGS or \ 37 | CMAKE_C_FLAGS used) Debug Release RelWithDebInfo MinSizeRel." FORCE) 38 | endif () 39 | 40 | option(BUILD_EXAMPLES "Build examples" ${MINIZ_STANDALONE_PROJECT}) 41 | option(BUILD_FUZZERS "Build fuzz targets" OFF) 42 | option(AMALGAMATE_SOURCES "Amalgamate sources into miniz.h/c" OFF) 43 | option(BUILD_HEADER_ONLY "Build a header-only version" OFF) 44 | option(BUILD_SHARED_LIBS "Build shared library instead of static" OFF) 45 | option(BUILD_TESTS "Build tests" ${MINIZ_STANDALONE_PROJECT}) 46 | option(INSTALL_PROJECT "Install project" ${MINIZ_STANDALONE_PROJECT}) 47 | 48 | set(CMAKE_RUNTIME_OUTPUT_DIRECTORY ${CMAKE_CURRENT_SOURCE_DIR}/bin) 49 | 50 | if(INSTALL_PROJECT) 51 | include(GNUInstallDirs) 52 | endif() 53 | 54 | if(BUILD_HEADER_ONLY) 55 | set(AMALGAMATE_SOURCES ON CACHE BOOL "Build a header-only version" FORCE) 56 | endif(BUILD_HEADER_ONLY) 57 | 58 | if(AMALGAMATE_SOURCES) 59 | # Amalgamate 60 | file(COPY miniz.h DESTINATION ${CMAKE_CURRENT_BINARY_DIR}/amalgamation/) 61 | file(READ miniz.h MINIZ_H) 62 | file(READ miniz_common.h MINIZ_COMMON_H) 63 | file(READ miniz_tdef.h MINIZ_TDEF_H) 64 | file(READ miniz_tinfl.h MINIZ_TINFL_H) 65 | file(READ miniz_zip.h MINIZ_ZIP_H) 66 | file(APPEND ${CMAKE_CURRENT_BINARY_DIR}/amalgamation/miniz.h 67 | "${MINIZ_COMMON_H} ${MINIZ_TDEF_H} ${MINIZ_TINFL_H} ${MINIZ_ZIP_H}") 68 | 69 | file(COPY miniz.c DESTINATION ${CMAKE_CURRENT_BINARY_DIR}/amalgamation/) 70 | file(READ miniz_tdef.c MINIZ_TDEF_C) 71 | file(READ miniz_tinfl.c MINIZ_TINFL_C) 72 | file(READ miniz_zip.c MINIZ_ZIP_C) 73 | file(APPEND ${CMAKE_CURRENT_BINARY_DIR}/amalgamation/miniz.c 74 | "${MINIZ_TDEF_C} ${MINIZ_TINFL_C} ${MINIZ_ZIP_C}") 75 | 76 | file(READ ${CMAKE_CURRENT_BINARY_DIR}/amalgamation/miniz.h AMAL_MINIZ_H) 77 | file(READ ${CMAKE_CURRENT_BINARY_DIR}/amalgamation/miniz.c AMAL_MINIZ_C) 78 | foreach(REPLACE_STRING miniz;miniz_common;miniz_tdef;miniz_tinfl;miniz_zip;miniz_export) 79 | string(REPLACE "#include \"${REPLACE_STRING}.h\"" "" AMAL_MINIZ_H "${AMAL_MINIZ_H}") 80 | string(REPLACE "#include \"${REPLACE_STRING}.h\"" "" AMAL_MINIZ_C "${AMAL_MINIZ_C}") 81 | endforeach() 82 | string(CONCAT AMAL_MINIZ_H "#ifndef MINIZ_EXPORT\n#define MINIZ_EXPORT\n#endif\n" "${AMAL_MINIZ_H}") 83 | if(BUILD_HEADER_ONLY) 84 | string(CONCAT AMAL_MINIZ_H "${AMAL_MINIZ_H}" "\n#ifndef MINIZ_HEADER_FILE_ONLY\n" 85 | "${AMAL_MINIZ_C}" "\n#endif // MINIZ_HEADER_FILE_ONLY\n") 86 | file(WRITE ${CMAKE_CURRENT_BINARY_DIR}/amalgamation/miniz.h "${AMAL_MINIZ_H}") 87 | add_library(${PROJECT_NAME} INTERFACE) 88 | 89 | # Might not be a good idea to force this on the library user 90 | # as it could bloat the global namespace 91 | # https://github.com/libevent/libevent/issues/460 92 | # target_compile_definitions(${PROJECT_NAME} 93 | # INTERFACE $<$:_GNU_SOURCE>) 94 | 95 | set_property(TARGET ${PROJECT_NAME} APPEND 96 | PROPERTY INTERFACE_INCLUDE_DIRECTORIES 97 | $ 98 | $ 99 | ) 100 | else(BUILD_HEADER_ONLY) 101 | string(CONCAT AMAL_MINIZ_C "#include \"miniz.h\"\n" "${AMAL_MINIZ_C}") 102 | file(WRITE ${CMAKE_CURRENT_BINARY_DIR}/amalgamation/miniz.h "${AMAL_MINIZ_H}") 103 | file(WRITE ${CMAKE_CURRENT_BINARY_DIR}/amalgamation/miniz.c "${AMAL_MINIZ_C}") 104 | set(miniz_SOURCE ${CMAKE_CURRENT_BINARY_DIR}/amalgamation/miniz.h 105 | ${CMAKE_CURRENT_BINARY_DIR}/amalgamation/miniz.c) 106 | add_library(${PROJECT_NAME} STATIC ${miniz_SOURCE}) 107 | target_include_directories(${PROJECT_NAME} PUBLIC 108 | $ 109 | $ 110 | ) 111 | endif(BUILD_HEADER_ONLY) 112 | 113 | set(INSTALL_HEADERS ${CMAKE_CURRENT_BINARY_DIR}/amalgamation/miniz.h) 114 | 115 | file(GLOB_RECURSE ZIP_FILES RELATIVE "${CMAKE_CURRENT_BINARY_DIR}/amalgamation" "${CMAKE_CURRENT_BINARY_DIR}/amalgamation/*") 116 | file(GLOB_RECURSE ZIP_FILES2 RELATIVE "${CMAKE_SOURCE_DIR}" "${CMAKE_SOURCE_DIR}/examples/*") 117 | list(APPEND ZIP_FILES ${ZIP_FILES2}) 118 | list(APPEND ZIP_FILES "ChangeLog.md") 119 | list(APPEND ZIP_FILES "readme.md") 120 | list(APPEND ZIP_FILES "LICENSE") 121 | set(ZIP_OUT_FN "${CMAKE_CURRENT_BINARY_DIR}/miniz-${MINIZ_VERSION}.zip") 122 | message(STATUS "Zip files: ${ZIP_FILES}") 123 | add_custom_command( 124 | COMMAND ${CMAKE_COMMAND} -E copy_directory ${CMAKE_SOURCE_DIR}/examples ${CMAKE_CURRENT_BINARY_DIR}/amalgamation/examples 125 | COMMAND ${CMAKE_COMMAND} -E copy ${CMAKE_SOURCE_DIR}/ChangeLog.md ${CMAKE_CURRENT_BINARY_DIR}/amalgamation/ChangeLog.md 126 | COMMAND ${CMAKE_COMMAND} -E copy ${CMAKE_SOURCE_DIR}/readme.md ${CMAKE_CURRENT_BINARY_DIR}/amalgamation/readme.md 127 | COMMAND ${CMAKE_COMMAND} -E copy ${CMAKE_SOURCE_DIR}/LICENSE ${CMAKE_CURRENT_BINARY_DIR}/amalgamation/LICENSE 128 | COMMAND ${CMAKE_COMMAND} -E tar "cf" "${ZIP_OUT_FN}" --format=zip -- ${ZIP_FILES} 129 | WORKING_DIRECTORY "${CMAKE_CURRENT_BINARY_DIR}/amalgamation" 130 | OUTPUT "${ZIP_OUT_FN}" 131 | DEPENDS ${ZIP_FILES} 132 | COMMENT "Zipping to ${CMAKE_CURRENT_BINARY_DIR}/miniz.zip." 133 | ) 134 | 135 | add_custom_target( 136 | create_zip ALL 137 | DEPENDS "${ZIP_OUT_FN}" 138 | ) 139 | else(AMALGAMATE_SOURCES) 140 | include(GenerateExportHeader) 141 | set(miniz_SOURCE miniz.c miniz_zip.c miniz_tinfl.c miniz_tdef.c) 142 | add_library(${PROJECT_NAME} ${miniz_SOURCE}) 143 | generate_export_header(${PROJECT_NAME}) 144 | 145 | if(NOT BUILD_SHARED_LIBS) 146 | string(TOUPPER ${PROJECT_NAME} PROJECT_UPPER) 147 | set_target_properties(${PROJECT_NAME} 148 | PROPERTIES INTERFACE_COMPILE_DEFINITIONS ${PROJECT_UPPER}_STATIC_DEFINE) 149 | else() 150 | set_property(TARGET ${PROJECT_NAME} PROPERTY C_VISIBILITY_PRESET hidden) 151 | endif() 152 | 153 | set_property(TARGET ${PROJECT_NAME} PROPERTY VERSION ${MINIZ_VERSION}) 154 | set_property(TARGET ${PROJECT_NAME} PROPERTY SOVERSION ${MINIZ_API_VERSION}) 155 | 156 | target_include_directories(${PROJECT_NAME} PUBLIC 157 | $ 158 | $ 159 | $ 160 | ) 161 | 162 | file(GLOB INSTALL_HEADERS ${CMAKE_CURRENT_SOURCE_DIR}/*.h) 163 | list(APPEND 164 | INSTALL_HEADERS ${CMAKE_CURRENT_BINARY_DIR}/${PROJECT_NAME}_export.h) 165 | endif(AMALGAMATE_SOURCES) 166 | 167 | if(NOT BUILD_HEADER_ONLY) 168 | target_compile_definitions(${PROJECT_NAME} 169 | PRIVATE $<$:_GNU_SOURCE>) 170 | 171 | # pkg-config file 172 | configure_file(miniz.pc.in ${CMAKE_CURRENT_BINARY_DIR}/miniz.pc @ONLY) 173 | 174 | if(INSTALL_PROJECT) 175 | install(FILES 176 | ${CMAKE_CURRENT_BINARY_DIR}/miniz.pc 177 | DESTINATION ${CMAKE_INSTALL_LIBDIR}/pkgconfig) 178 | endif() 179 | endif() 180 | 181 | set_property(TARGET ${PROJECT_NAME} PROPERTY 182 | INTERFACE_${PROJECT_NAME}_MAJOR_VERSION ${MINIZ_API_VERSION}) 183 | set_property(TARGET ${PROJECT_NAME} APPEND PROPERTY 184 | COMPATIBLE_INTERFACE_STRING ${PROJECT_NAME}_MAJOR_VERSION 185 | ) 186 | 187 | if(INSTALL_PROJECT) 188 | install(TARGETS ${PROJECT_NAME} EXPORT ${PROJECT_NAME}Targets 189 | RUNTIME DESTINATION ${CMAKE_INSTALL_BINDIR} 190 | ARCHIVE DESTINATION ${CMAKE_INSTALL_LIBDIR} 191 | LIBRARY DESTINATION ${CMAKE_INSTALL_LIBDIR} 192 | # users can use or 193 | INCLUDES DESTINATION include ${CMAKE_INSTALL_INCLUDEDIR}/${PROJECT_NAME} 194 | ) 195 | 196 | include(CMakePackageConfigHelpers) 197 | write_basic_package_version_file( 198 | "${CMAKE_CURRENT_BINARY_DIR}/${PROJECT_NAME}/${PROJECT_NAME}ConfigVersion.cmake" 199 | VERSION ${MINIZ_VERSION} 200 | COMPATIBILITY AnyNewerVersion 201 | ) 202 | 203 | export(EXPORT ${PROJECT_NAME}Targets 204 | FILE "${CMAKE_CURRENT_BINARY_DIR}/${PROJECT_NAME}/${PROJECT_NAME}Targets.cmake" 205 | NAMESPACE ${PROJECT_NAME}:: 206 | ) 207 | configure_file(Config.cmake.in 208 | "${CMAKE_CURRENT_BINARY_DIR}/${PROJECT_NAME}/${PROJECT_NAME}Config.cmake" 209 | @ONLY 210 | ) 211 | 212 | set(ConfigPackageLocation ${CMAKE_INSTALL_LIBDIR}/cmake/${PROJECT_NAME}) 213 | install(EXPORT ${PROJECT_NAME}Targets 214 | FILE 215 | ${PROJECT_NAME}Targets.cmake 216 | NAMESPACE 217 | ${PROJECT_NAME}:: 218 | DESTINATION 219 | ${ConfigPackageLocation} 220 | ) 221 | install( 222 | FILES 223 | "${CMAKE_CURRENT_BINARY_DIR}/${PROJECT_NAME}/${PROJECT_NAME}Config.cmake" 224 | "${CMAKE_CURRENT_BINARY_DIR}/${PROJECT_NAME}/${PROJECT_NAME}ConfigVersion.cmake" 225 | DESTINATION 226 | ${ConfigPackageLocation} 227 | COMPONENT 228 | Devel 229 | ) 230 | endif() 231 | 232 | if(BUILD_EXAMPLES) 233 | set(EXAMPLE1_SRC_LIST "${CMAKE_CURRENT_SOURCE_DIR}/examples/example1.c") 234 | set(EXAMPLE2_SRC_LIST "${CMAKE_CURRENT_SOURCE_DIR}/examples/example2.c") 235 | set(EXAMPLE3_SRC_LIST "${CMAKE_CURRENT_SOURCE_DIR}/examples/example3.c") 236 | set(EXAMPLE4_SRC_LIST "${CMAKE_CURRENT_SOURCE_DIR}/examples/example4.c") 237 | set(EXAMPLE5_SRC_LIST "${CMAKE_CURRENT_SOURCE_DIR}/examples/example5.c") 238 | set(EXAMPLE6_SRC_LIST "${CMAKE_CURRENT_SOURCE_DIR}/examples/example6.c") 239 | set(MINIZ_TESTER_SRC_LIST 240 | "${CMAKE_CURRENT_SOURCE_DIR}/tests/miniz_tester.cpp" 241 | "${CMAKE_CURRENT_SOURCE_DIR}/tests/timer.cpp") 242 | 243 | add_executable(example1 ${EXAMPLE1_SRC_LIST}) 244 | target_link_libraries(example1 miniz) 245 | add_executable(example2 ${EXAMPLE2_SRC_LIST}) 246 | target_link_libraries(example2 miniz) 247 | add_executable(example3 ${EXAMPLE3_SRC_LIST}) 248 | target_link_libraries(example3 miniz) 249 | add_executable(example4 ${EXAMPLE4_SRC_LIST}) 250 | target_link_libraries(example4 miniz) 251 | add_executable(example5 ${EXAMPLE5_SRC_LIST}) 252 | target_link_libraries(example5 miniz) 253 | add_executable(example6 ${EXAMPLE6_SRC_LIST}) 254 | target_link_libraries(example6 miniz) 255 | if(${UNIX}) 256 | target_link_libraries(example6 m) 257 | endif() 258 | 259 | # add_executable(miniz_tester ${MINIZ_TESTER_SRC_LIST}) 260 | # target_link_libraries(miniz_tester miniz) 261 | endif(BUILD_EXAMPLES) 262 | 263 | if(BUILD_FUZZERS) 264 | set(FUZZ_MAIN_SRC "${CMAKE_CURRENT_SOURCE_DIR}/tests/fuzz_main.c") 265 | 266 | set(CHECKSUM_FUZZER_SRC_LIST "${FUZZ_MAIN_SRC}" "${CMAKE_CURRENT_SOURCE_DIR}/tests/checksum_fuzzer.c") 267 | set(FLUSH_FUZZER_SRC_LIST "${FUZZ_MAIN_SRC}" "${CMAKE_CURRENT_SOURCE_DIR}/tests/flush_fuzzer.c") 268 | set(UNCOMPRESS_FUZZER_SRC_LIST "${FUZZ_MAIN_SRC}" "${CMAKE_CURRENT_SOURCE_DIR}/tests/uncompress_fuzzer.c") 269 | set(UNCOMPRESS2_FUZZER_SRC_LIST "${FUZZ_MAIN_SRC}" "${CMAKE_CURRENT_SOURCE_DIR}/tests/uncompress2_fuzzer.c") 270 | set(COMPRESS_FUZZER_SRC_LIST "${FUZZ_MAIN_SRC}" "${CMAKE_CURRENT_SOURCE_DIR}/tests/compress_fuzzer.c") 271 | set(SMALL_FUZZER_SRC_LIST "${FUZZ_MAIN_SRC}" "${CMAKE_CURRENT_SOURCE_DIR}/tests/small_fuzzer.c") 272 | set(LARGE_FUZZER_SRC_LIST "${FUZZ_MAIN_SRC}" "${CMAKE_CURRENT_SOURCE_DIR}/tests/large_fuzzer.c") 273 | set(ZIP_FUZZER_SRC_LIST "${FUZZ_MAIN_SRC}" "${CMAKE_CURRENT_SOURCE_DIR}/tests/zip_fuzzer.c") 274 | 275 | add_executable(checksum_fuzzer ${CHECKSUM_FUZZER_SRC_LIST}) 276 | target_link_libraries(checksum_fuzzer miniz) 277 | 278 | add_executable(flush_fuzzer ${FLUSH_FUZZER_SRC_LIST}) 279 | target_link_libraries(flush_fuzzer miniz) 280 | 281 | add_executable(uncompress_fuzzer ${UNCOMPRESS_FUZZER_SRC_LIST}) 282 | target_link_libraries(uncompress_fuzzer miniz) 283 | 284 | add_executable(uncompress2_fuzzer ${UNCOMPRESS2_FUZZER_SRC_LIST}) 285 | target_link_libraries(uncompress2_fuzzer miniz) 286 | 287 | add_executable(compress_fuzzer ${COMPRESS_FUZZER_SRC_LIST}) 288 | target_link_libraries(compress_fuzzer miniz) 289 | 290 | add_executable(small_fuzzer ${SMALL_FUZZER_SRC_LIST}) 291 | target_link_libraries(small_fuzzer miniz) 292 | 293 | add_executable(large_fuzzer ${LARGE_FUZZER_SRC_LIST}) 294 | target_link_libraries(large_fuzzer miniz) 295 | 296 | add_executable(zip_fuzzer ${ZIP_FUZZER_SRC_LIST}) 297 | target_link_libraries(zip_fuzzer miniz) 298 | endif() 299 | 300 | if(BUILD_TESTS) 301 | set(CMAKE_CXX_STANDARD 20) 302 | set(CMAKE_CXX_STANDARD_REQUIRED YES) 303 | 304 | add_executable(catch_tests tests/main.cpp 305 | tests/catch_amalgamated.cpp) 306 | target_link_libraries(catch_tests miniz) 307 | 308 | enable_testing() 309 | 310 | add_test(NAME catch_tests 311 | COMMAND $) 312 | endif() 313 | 314 | set(INCLUDE_INSTALL_DIR "include") 315 | 316 | if(INSTALL_PROJECT) 317 | install(FILES ${INSTALL_HEADERS} DESTINATION ${CMAKE_INSTALL_INCLUDEDIR}/${PROJECT_NAME}) 318 | endif() 319 | 320 | -------------------------------------------------------------------------------- /CMakePresets.json: -------------------------------------------------------------------------------- 1 | { 2 | "version": 6, 3 | "cmakeMinimumRequired": { 4 | "major": 3, 5 | "minor": 5, 6 | "patch": 0 7 | }, 8 | "configurePresets": [ 9 | { 10 | "name": "gcc", 11 | "displayName": "GCC", 12 | "description": "Default build options for GCC", 13 | "generator": "Unix Makefiles", 14 | "binaryDir": "${sourceDir}/build" 15 | } 16 | ], 17 | "buildPresets": [ 18 | { 19 | "name": "gcc", 20 | "configurePreset": "gcc" 21 | } 22 | ], 23 | "testPresets": [ 24 | { 25 | "name": "gcc", 26 | "configurePreset": "gcc", 27 | "output": {"outputOnFailure": true}, 28 | "execution": {"noTestsAction": "error", "stopOnFailure": true} 29 | } 30 | ] 31 | } 32 | -------------------------------------------------------------------------------- /ChangeLog.md: -------------------------------------------------------------------------------- 1 | ## Changelog 2 | 3 | ### 3.0.2 4 | 5 | - Fix buffer overrun in mz_utf8z_to_widechar on Windows 6 | 7 | ### 3.0.1 8 | 9 | - Fix compilation error with MINIZ_USE_UNALIGNED_LOADS_AND_STORES=1 10 | 11 | ### 3.0.0 12 | 13 | - Reduce memory usage for inflate. This changes `struct tinfl_decompressor_tag` and therefore requires a major version bump (breaks ABI compatibility) 14 | - Add padding to structures so it continues to work if features differ. This also changes some structures 15 | - Use _ftelli64, _fseeki64 and stat with MinGW32 and OpenWatcom 16 | - Fix varios warnings with OpenWatcom compiler 17 | - Avoid using unaligned memory access in UBSan builds 18 | - Set MINIZ_LITTLE_ENDIAN only if not set 19 | - Add MINIZ_NO_DEFLATE_APIS and MINIZ_NO_INFLATE_APIS 20 | - Fix use of uninitialized memory in tinfl_decompress_mem_to_callback() 21 | - Use wfopen on windows 22 | - Use _wstat64 instead _stat64 on windows 23 | - Use level_and_flags after MZ_DEFAULT_COMPRESSION has been handled 24 | - Improve endianess detection 25 | - Don't use unaligned stores and loads per default 26 | - Fix function declaration if MINIZ_NO_STDIO is used 27 | - Fix MZ_ZIP_GENERAL_PURPOSE_BIT_FLAG_UTF8 not being set 28 | - Remove total files check (its 32-bit uint) 29 | - tinfl_decompress: avoid NULL ptr arithmetic UB 30 | - miniz_zip: fix mz_zip_reader_extract_to_heap to read correct sizes 31 | - Eliminate 64-bit operations on 32-bit machines 32 | - Disable treating warnings as error with MSVC 33 | - Disable building shared lib via CMake by default 34 | - Fixed alignment problems on MacOS 35 | - Fixed get error string for MZ_ZIP_TOTAL_ERRORS 36 | - Write correct FLEVEL 2-bit value in zlib header 37 | - miniz.pc.in: fix include path not containing the "miniz" suffix 38 | - Fix compatibility with FreeBSD 39 | - pkg-config tweaks 40 | - Fix integer overflow in header corruption check 41 | - Fix some warnings 42 | - tdefl_compress_normal: Avoid NULL ptr arithmetic UB 43 | - replace use of stdint.h types with mz_ variants 44 | 45 | 46 | ### 2.2.0 47 | 48 | - Fix examples with amalgamation 49 | - Modified cmake script to support shared library mode and find_package 50 | - Fix for misleading doc comment on `mz_zip_reader_init_cfile` function 51 | - Add include location tolerance and stop forcing `_GNU_SOURCE` 52 | - Fix: mz_zip_reader_locate_file_v2 returns an mz_bool 53 | - Fix large file system checks 54 | - Add #elif to enable an external mz_crc32() to be linked in 55 | - Write with dynamic size (size of file/data to be added not known before adding) 56 | - Added uncompress2 for zlib compatibility 57 | - Add support for building as a Meson subproject 58 | - Added OSSFuzz support; Integrate with CIFuzz 59 | - Add pkg-config file 60 | - Fixed use-of-uninitialized value msan error when copying dist bytes with no output bytes written. 61 | - mz_zip_validate_file(): fix memory leak on errors 62 | - Fixed MSAN use-of-uninitialized in tinfl_decompress when invalid dist is decoded. In this instance dist was 31 which s_dist_base translates as 0 63 | - Add flag to set (compressed) size in local file header 64 | - avoid use of uninitialized value in tdefl_record_literal 65 | 66 | ### 2.1.0 67 | 68 | - More instances of memcpy instead of cast and use memcpy per default 69 | - Remove inline for c90 support 70 | - New function to read files via callback functions when adding them 71 | - Fix out of bounds read while reading Zip64 extended information 72 | - guard memcpy when n == 0 because buffer may be NULL 73 | - Implement inflateReset() function 74 | - Move comp/decomp alloc/free prototypes under guarding #ifndef MZ_NO_MALLOC 75 | - Fix large file support under Windows 76 | - Don't warn if _LARGEFILE64_SOURCE is not defined to 1 77 | - Fixes for MSVC warnings 78 | - Remove check that path of file added to archive contains ':' or '\' 79 | - Add !defined check on MINIZ_USE_ALIGNED_LOADS_AND_STORES 80 | 81 | ### 2.0.8 82 | 83 | - Remove unimplemented functions (mz_zip_locate_file and mz_zip_locate_file_v2) 84 | - Add license, changelog, readme and example files to release zip 85 | - Fix heap overflow to user buffer in tinfl_status tinfl_decompress 86 | - Fix corrupt archive if uncompressed file smaller than 4 byte and the file is added by mz_zip_writer_add_mem* 87 | 88 | ### 2.0.7 89 | 90 | - Removed need in C++ compiler in cmake build 91 | - Fixed a lot of uninitialized value errors found with Valgrind by memsetting m_dict to 0 in tdefl_init 92 | - Fix resource leak in mz_zip_reader_init_file_v2 93 | - Fix assert with mz_zip_writer_add_mem* w/MZ_DEFAULT_COMPRESSION 94 | - cmake build: install library and headers 95 | - Remove _LARGEFILE64_SOURCE requirement from apple defines for large files 96 | 97 | ### 2.0.6 98 | 99 | - Improve MZ_ZIP_FLAG_WRITE_ZIP64 documentation 100 | - Remove check for cur_archive_file_ofs > UINT_MAX because cur_archive_file_ofs is not used after this point 101 | - Add cmake debug configuration 102 | - Fix PNG height when creating png files 103 | - Add "iterative" file extraction method based on mz_zip_reader_extract_to_callback. 104 | - Option to use memcpy for unaligned data access 105 | - Define processor/arch macros as zero if not set to one 106 | 107 | ### 2.0.4/2.0.5 108 | 109 | - Fix compilation with the various omission compile definitions 110 | 111 | ### 2.0.3 112 | 113 | - Fix GCC/clang compile warnings 114 | - Added callback for periodic flushes (for ZIP file streaming) 115 | - Use UTF-8 for file names in ZIP files per default 116 | 117 | ### 2.0.2 118 | 119 | - Fix source backwards compatibility with 1.x 120 | - Fix a ZIP bit not being set correctly 121 | 122 | ### 2.0.1 123 | 124 | - Added some tests 125 | - Added CI 126 | - Make source code ANSI C compatible 127 | 128 | ### 2.0.0 beta 129 | 130 | - Matthew Sitton merged miniz 1.x to Rich Geldreich's vogl ZIP64 changes. Miniz is now licensed as MIT since the vogl code base is MIT licensed 131 | - Miniz is now split into several files 132 | - Miniz does now not seek backwards when creating ZIP files. That is the ZIP files can be streamed 133 | - Miniz automatically switches to the ZIP64 format when the created ZIP files goes over ZIP file limits 134 | - Similar to [SQLite](https://www.sqlite.org/amalgamation.html) the Miniz source code is amalgamated into one miniz.c/miniz.h pair in a build step (amalgamate.sh). Please use miniz.c/miniz.h in your projects 135 | - Miniz 2 is only source back-compatible with miniz 1.x. It breaks binary compatibility because structures changed 136 | 137 | ### v1.16 BETA Oct 19, 2013 138 | 139 | Still testing, this release is downloadable from [here](http://www.tenacioussoftware.com/miniz_v116_beta_r1.7z). Two key inflator-only robustness and streaming related changes. Also merged in tdefl_compressor_alloc(), tdefl_compressor_free() helpers to make script bindings easier for rustyzip. I would greatly appreciate any help with testing or any feedback. 140 | 141 | The inflator in raw (non-zlib) mode is now usable on gzip or similar streams that have a bunch of bytes following the raw deflate data (problem discovered by rustyzip author williamw520). This version should never read beyond the last byte of the raw deflate data independent of how many bytes you pass into the input buffer. 142 | 143 | The inflator now has a new failure status TINFL_STATUS_FAILED_CANNOT_MAKE_PROGRESS (-4). Previously, if the inflator was starved of bytes and could not make progress (because the input buffer was empty and the caller did not set the TINFL_FLAG_HAS_MORE_INPUT flag - say on truncated or corrupted compressed data stream) it would append all 0's to the input and try to soldier on. This is scary behavior if the caller didn't know when to stop accepting output (because it didn't know how much uncompressed data was expected, or didn't enforce a sane maximum). v1.16 will instead return TINFL_STATUS_FAILED_CANNOT_MAKE_PROGRESS immediately if it needs 1 or more bytes to make progress, the input buf is empty, and the caller has indicated that no more input is available. This is a "soft" failure, so you can call the inflator again with more input and it will try to continue, or you can give up and fail. This could be very useful in network streaming scenarios. 144 | 145 | - The inflator coroutine func. is subtle and complex so I'm being cautious about this release. I would greatly appreciate any help with testing or any feedback. 146 | I feel good about these changes, and they've been through several hours of automated testing, but they will probably not fix anything for the majority of prev. users so I'm 147 | going to mark this release as beta for a few weeks and continue testing it at work/home on various things. 148 | - The inflator in raw (non-zlib) mode is now usable on gzip or similar data streams that have a bunch of bytes following the raw deflate data (problem discovered by rustyzip author williamw520). 149 | This version should *never* read beyond the last byte of the raw deflate data independent of how many bytes you pass into the input buffer. This issue was caused by the various Huffman bitbuffer lookahead optimizations, and 150 | would not be an issue if the caller knew and enforced the precise size of the raw compressed data *or* if the compressed data was in zlib format (i.e. always followed by the byte aligned zlib adler32). 151 | So in other words, you can now call the inflator on deflate streams that are followed by arbitrary amounts of data and it's guaranteed that decompression will stop exactly on the last byte. 152 | - The inflator now has a new failure status: TINFL_STATUS_FAILED_CANNOT_MAKE_PROGRESS (-4). Previously, if the inflator was starved of bytes and could not make progress (because the input buffer was empty and the 153 | caller did not set the TINFL_FLAG_HAS_MORE_INPUT flag - say on truncated or corrupted compressed data stream) it would append all 0's to the input and try to soldier on. 154 | This is scary, because in the worst case, I believe it was possible for the prev. inflator to start outputting large amounts of literal data. If the caller didn't know when to stop accepting output 155 | (because it didn't know how much uncompressed data was expected, or didn't enforce a sane maximum) it could continue forever. v1.16 cannot fall into this failure mode, instead it'll return 156 | TINFL_STATUS_FAILED_CANNOT_MAKE_PROGRESS immediately if it needs 1 or more bytes to make progress, the input buf is empty, and the caller has indicated that no more input is available. This is a "soft" 157 | failure, so you can call the inflator again with more input and it will try to continue, or you can give up and fail. This could be very useful in network streaming scenarios. 158 | - Added documentation to all the tinfl return status codes, fixed miniz_tester so it accepts double minus params for Linux, tweaked example1.c, added a simple "follower bytes" test to miniz_tester.cpp. 159 | ### v1.15 r4 STABLE - Oct 13, 2013 160 | 161 | Merged over a few very minor bug fixes that I fixed in the zip64 branch. This is downloadable from [here](http://code.google.com/p/miniz/downloads/list) and also in SVN head (as of 10/19/13). 162 | 163 | 164 | ### v1.15 - Oct. 13, 2013 165 | 166 | Interim bugfix release while I work on the next major release with zip64 and streaming compression/decompression support. Fixed the MZ_ZIP_FLAG_DO_NOT_SORT_CENTRAL_DIRECTORY bug (thanks kahmyong.moon@hp.com), which could cause the locate files func to not find files when this flag was specified. Also fixed a bug in mz_zip_reader_extract_to_mem_no_alloc() with user provided read buffers (thanks kymoon). I also merged lots of compiler fixes from various github repo branches and Google Code issue reports. I finally added cmake support (only tested under for Linux so far), compiled and tested with clang v3.3 and gcc 4.6 (under Linux), added defl_write_image_to_png_file_in_memory_ex() (supports Y flipping for OpenGL use, real-time compression), added a new PNG example (example6.c - Mandelbrot), and I added 64-bit file I/O support (stat64(), etc.) for glibc. 167 | 168 | - Critical fix for the MZ_ZIP_FLAG_DO_NOT_SORT_CENTRAL_DIRECTORY bug (thanks kahmyong.moon@hp.com) which could cause locate files to not find files. This bug 169 | would only have occurred in earlier versions if you explicitly used this flag, OR if you used mz_zip_extract_archive_file_to_heap() or mz_zip_add_mem_to_archive_file_in_place() 170 | (which used this flag). If you can't switch to v1.15 but want to fix this bug, just remove the uses of this flag from both helper funcs (and of course don't use the flag). 171 | - Bugfix in mz_zip_reader_extract_to_mem_no_alloc() from kymoon when pUser_read_buf is not NULL and compressed size is > uncompressed size 172 | - Fixing mz_zip_reader_extract_*() funcs so they don't try to extract compressed data from directory entries, to account for weird zipfiles which contain zero-size compressed data on dir entries. 173 | Hopefully this fix won't cause any issues on weird zip archives, because it assumes the low 16-bits of zip external attributes are DOS attributes (which I believe they always are in practice). 174 | - Fixing mz_zip_reader_is_file_a_directory() so it doesn't check the internal attributes, just the filename and external attributes 175 | - mz_zip_reader_init_file() - missing MZ_FCLOSE() call if the seek failed 176 | - Added cmake support for Linux builds which builds all the examples, tested with clang v3.3 and gcc v4.6. 177 | - Clang fix for tdefl_write_image_to_png_file_in_memory() from toffaletti 178 | - Merged MZ_FORCEINLINE fix from hdeanclark 179 | - Fix include before config #ifdef, thanks emil.brink 180 | - Added tdefl_write_image_to_png_file_in_memory_ex(): supports Y flipping (super useful for OpenGL apps), and explicit control over the compression level (so you can 181 | set it to 1 for real-time compression). 182 | - Merged in some compiler fixes from paulharris's github repro. 183 | - Retested this build under Windows (VS 2010, including static analysis), tcc 0.9.26, gcc v4.6 and clang v3.3. 184 | - Added example6.c, which dumps an image of the mandelbrot set to a PNG file. 185 | - Modified example2 to help test the MZ_ZIP_FLAG_DO_NOT_SORT_CENTRAL_DIRECTORY flag more. 186 | - In r3: Bugfix to mz_zip_writer_add_file() found during merge: Fix possible src file fclose() leak if alignment bytes+local header file write faiiled 187 | - In r4: Minor bugfix to mz_zip_writer_add_from_zip_reader(): Was pushing the wrong central dir header offset, appears harmless in this release, but it became a problem in the zip64 branch 188 | 189 | ### v1.14 - May 20, 2012 190 | 191 | (SVN Only) Minor tweaks to get miniz.c compiling with the Tiny C Compiler, added #ifndef MINIZ_NO_TIME guards around utime.h includes. Adding mz_free() function, so the caller can free heap blocks returned by miniz using whatever heap functions it has been configured to use, MSVC specific fixes to use "safe" variants of several functions (localtime_s, fopen_s, freopen_s). 192 | 193 | MinGW32/64 GCC 4.6.1 compiler fixes: added MZ_FORCEINLINE, #include (thanks fermtect). 194 | 195 | Compiler specific fixes, some from fermtect. I upgraded to TDM GCC 4.6.1 and now static __forceinline is giving it fits, so I'm changing all usage of __forceinline to MZ_FORCEINLINE and forcing gcc to use __attribute__((__always_inline__)) (and MSVC to use __forceinline). Also various fixes from fermtect for MinGW32: added #include , 64-bit ftell/fseek fixes. 196 | 197 | ### v1.13 - May 19, 2012 198 | 199 | From jason@cornsyrup.org and kelwert@mtu.edu - Most importantly, fixed mz_crc32() so it doesn't compute the wrong CRC-32's when mz_ulong is 64-bits. Temporarily/locally slammed in "typedef unsigned long mz_ulong" and re-ran a randomized regression test on ~500k files. Other stuff: 200 | 201 | Eliminated a bunch of warnings when compiling with GCC 32-bit/64. Ran all examples, miniz.c, and tinfl.c through MSVC 2008's /analyze (static analysis) option and fixed all warnings (except for the silly "Use of the comma-operator in a tested expression.." analysis warning, which I purposely use to work around a MSVC compiler warning). 202 | 203 | Created 32-bit and 64-bit Codeblocks projects/workspace. Built and tested Linux executables. The codeblocks workspace is compatible with Linux+Win32/x64. Added miniz_tester solution/project, which is a useful little app derived from LZHAM's tester app that I use as part of the regression test. Ran miniz.c and tinfl.c through another series of regression testing on ~500,000 files and archives. Modified example5.c so it purposely disables a bunch of high-level functionality (MINIZ_NO_STDIO, etc.). (Thanks to corysama for the MINIZ_NO_STDIO bug report.) 204 | 205 | Fix ftell() usage in a few of the examples so they exit with an error on files which are too large (a limitation of the examples, not miniz itself). Fix fail logic handling in mz_zip_add_mem_to_archive_file_in_place() so it always calls mz_zip_writer_finalize_archive() and mz_zip_writer_end(), even if the file add fails. 206 | 207 | - From jason@cornsyrup.org and kelwert@mtu.edu - Fix mz_crc32() so it doesn't compute the wrong CRC-32's when mz_ulong is 64-bit. 208 | - Temporarily/locally slammed in "typedef unsigned long mz_ulong" and re-ran a randomized regression test on ~500k files. 209 | - Eliminated a bunch of warnings when compiling with GCC 32-bit/64. 210 | - Ran all examples, miniz.c, and tinfl.c through MSVC 2008's /analyze (static analysis) option and fixed all warnings (except for the silly 211 | "Use of the comma-operator in a tested expression.." analysis warning, which I purposely use to work around a MSVC compiler warning). 212 | - Created 32-bit and 64-bit Codeblocks projects/workspace. Built and tested Linux executables. The codeblocks workspace is compatible with Linux+Win32/x64. 213 | - Added miniz_tester solution/project, which is a useful little app derived from LZHAM's tester app that I use as part of the regression test. 214 | - Ran miniz.c and tinfl.c through another series of regression testing on ~500,000 files and archives. 215 | - Modified example5.c so it purposely disables a bunch of high-level functionality (MINIZ_NO_STDIO, etc.). (Thanks to corysama for the MINIZ_NO_STDIO bug report.) 216 | - Fix ftell() usage in examples so they exit with an error on files which are too large (a limitation of the examples, not miniz itself). 217 | 218 | ### v1.12 - 4/12/12 219 | 220 | More comments, added low-level example5.c, fixed a couple minor level_and_flags issues in the archive API's. 221 | level_and_flags can now be set to MZ_DEFAULT_COMPRESSION. Thanks to Bruce Dawson for the feedback/bug report. 222 | 223 | ### v1.11 - 5/28/11 224 | 225 | Added statement from unlicense.org 226 | 227 | ### v1.10 - 5/27/11 228 | 229 | - Substantial compressor optimizations: 230 | - Level 1 is now ~4x faster than before. The L1 compressor's throughput now varies between 70-110MB/sec. on a Core i7 (actual throughput varies depending on the type of data, and x64 vs. x86). 231 | - Improved baseline L2-L9 compression perf. Also, greatly improved compression perf. issues on some file types. 232 | - Refactored the compression code for better readability and maintainability. 233 | - Added level 10 compression level (L10 has slightly better ratio than level 9, but could have a potentially large drop in throughput on some files). 234 | 235 | ### v1.09 - 5/15/11 236 | 237 | Initial stable release. 238 | 239 | 240 | -------------------------------------------------------------------------------- /Config.cmake.in: -------------------------------------------------------------------------------- 1 | include("${CMAKE_CURRENT_LIST_DIR}/@PROJECT_NAME@Targets.cmake") -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | Copyright 2013-2014 RAD Game Tools and Valve Software 2 | Copyright 2010-2014 Rich Geldreich and Tenacious Software LLC 3 | 4 | All Rights Reserved. 5 | 6 | Permission is hereby granted, free of charge, to any person obtaining a copy 7 | of this software and associated documentation files (the "Software"), to deal 8 | in the Software without restriction, including without limitation the rights 9 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 10 | copies of the Software, and to permit persons to whom the Software is 11 | furnished to do so, subject to the following conditions: 12 | 13 | The above copyright notice and this permission notice shall be included in 14 | all copies or substantial portions of the Software. 15 | 16 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 17 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 18 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 19 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 20 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 21 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN 22 | THE SOFTWARE. 23 | -------------------------------------------------------------------------------- /amalgamate.sh: -------------------------------------------------------------------------------- 1 | #!/bin/bash 2 | 3 | set -e 4 | 5 | mkdir -p amalgamation 6 | 7 | OUTPUT_PREFIX=_build/amalgamation 8 | 9 | cmake -H. -B_build -DAMALGAMATE_SOURCES=ON -G"Unix Makefiles" 10 | 11 | echo "int main() { return 0; }" > main.c 12 | echo "Test compile with GCC..." 13 | gcc -pedantic -Wall -I$OUTPUT_PREFIX main.c $OUTPUT_PREFIX/miniz.c -o test.out 14 | echo "Test compile with GCC ANSI..." 15 | gcc -ansi -pedantic -Wall -I$OUTPUT_PREFIX main.c $OUTPUT_PREFIX/miniz.c -o test.out 16 | if command -v clang 17 | then 18 | echo "Test compile with clang..." 19 | clang -Wall -Wpedantic -fsanitize=unsigned-integer-overflow -I$OUTPUT_PREFIX main.c $OUTPUT_PREFIX/miniz.c -o test.out 20 | fi 21 | for def in MINIZ_NO_STDIO MINIZ_NO_TIME MINIZ_NO_DEFLATE_APIS MINIZ_NO_INFLATE_APIS MINIZ_NO_ARCHIVE_APIS MINIZ_NO_ARCHIVE_WRITING_APIS MINIZ_NO_ZLIB_APIS MINIZ_NO_ZLIB_COMPATIBLE_NAMES MINIZ_NO_MALLOC 22 | do 23 | echo "Test compile with GCC and define $def..." 24 | gcc -ansi -pedantic -Wall -I$OUTPUT_PREFIX main.c $OUTPUT_PREFIX/miniz.c -o test.out -D${def} 25 | done 26 | echo "Test compile with GCC and MINIZ_USE_UNALIGNED_LOADS_AND_STORES=1..." 27 | gcc -ansi -pedantic -Wall -I$OUTPUT_PREFIX main.c $OUTPUT_PREFIX/miniz.c -o test.out -DMINIZ_USE_UNALIGNED_LOADS_AND_STORES=1 28 | rm test.out 29 | rm main.c 30 | 31 | cp $OUTPUT_PREFIX/miniz.* amalgamation/ 32 | cp ChangeLog.md amalgamation/ 33 | cp LICENSE amalgamation/ 34 | cp readme.md amalgamation/ 35 | mkdir -p amalgamation/examples 36 | cp examples/* amalgamation/examples/ 37 | 38 | cd amalgamation 39 | ! test -e miniz.zip || rm miniz.zip 40 | cat << EOF | zip -@ miniz 41 | miniz.c 42 | miniz.h 43 | ChangeLog.md 44 | LICENSE 45 | readme.md 46 | examples/example1.c 47 | examples/example2.c 48 | examples/example3.c 49 | examples/example4.c 50 | examples/example5.c 51 | examples/example6.c 52 | EOF 53 | cd .. 54 | 55 | echo "Amalgamation created." 56 | 57 | 58 | -------------------------------------------------------------------------------- /examples/example1.c: -------------------------------------------------------------------------------- 1 | // example1.c - Demonstrates miniz.c's compress() and uncompress() functions (same as zlib's). 2 | // Public domain, May 15 2011, Rich Geldreich, richgel99@gmail.com. See "unlicense" statement at the end of tinfl.c. 3 | #include 4 | #include "miniz.h" 5 | typedef unsigned char uint8; 6 | typedef unsigned short uint16; 7 | typedef unsigned int uint; 8 | 9 | // The string to compress. 10 | static const char *s_pStr = "Good morning Dr. Chandra. This is Hal. I am ready for my first lesson." \ 11 | "Good morning Dr. Chandra. This is Hal. I am ready for my first lesson." \ 12 | "Good morning Dr. Chandra. This is Hal. I am ready for my first lesson." \ 13 | "Good morning Dr. Chandra. This is Hal. I am ready for my first lesson." \ 14 | "Good morning Dr. Chandra. This is Hal. I am ready for my first lesson." \ 15 | "Good morning Dr. Chandra. This is Hal. I am ready for my first lesson." \ 16 | "Good morning Dr. Chandra. This is Hal. I am ready for my first lesson."; 17 | 18 | int main(int argc, char *argv[]) 19 | { 20 | uint step = 0; 21 | int cmp_status; 22 | uLong src_len = (uLong)strlen(s_pStr); 23 | uLong cmp_len = compressBound(src_len); 24 | uLong uncomp_len = src_len; 25 | uint8 *pCmp, *pUncomp; 26 | uint total_succeeded = 0; 27 | (void)argc, (void)argv; 28 | 29 | printf("miniz.c version: %s\n", MZ_VERSION); 30 | 31 | do 32 | { 33 | // Allocate buffers to hold compressed and uncompressed data. 34 | pCmp = (mz_uint8 *)malloc((size_t)cmp_len); 35 | pUncomp = (mz_uint8 *)malloc((size_t)src_len); 36 | if ((!pCmp) || (!pUncomp)) 37 | { 38 | printf("Out of memory!\n"); 39 | return EXIT_FAILURE; 40 | } 41 | 42 | // Compress the string. 43 | cmp_status = compress(pCmp, &cmp_len, (const unsigned char *)s_pStr, src_len); 44 | if (cmp_status != Z_OK) 45 | { 46 | printf("compress() failed!\n"); 47 | free(pCmp); 48 | free(pUncomp); 49 | return EXIT_FAILURE; 50 | } 51 | 52 | printf("Compressed from %u to %u bytes\n", (mz_uint32)src_len, (mz_uint32)cmp_len); 53 | 54 | if (step) 55 | { 56 | // Purposely corrupt the compressed data if fuzzy testing (this is a very crude fuzzy test). 57 | uint n = 1 + (rand() % 3); 58 | while (n--) 59 | { 60 | uint i = rand() % cmp_len; 61 | pCmp[i] ^= (rand() & 0xFF); 62 | } 63 | } 64 | 65 | // Decompress. 66 | cmp_status = uncompress(pUncomp, &uncomp_len, pCmp, cmp_len); 67 | total_succeeded += (cmp_status == Z_OK); 68 | 69 | if (step) 70 | { 71 | printf("Simple fuzzy test: step %u total_succeeded: %u\n", step, total_succeeded); 72 | } 73 | else 74 | { 75 | if (cmp_status != Z_OK) 76 | { 77 | printf("uncompress failed!\n"); 78 | free(pCmp); 79 | free(pUncomp); 80 | return EXIT_FAILURE; 81 | } 82 | 83 | printf("Decompressed from %u to %u bytes\n", (mz_uint32)cmp_len, (mz_uint32)uncomp_len); 84 | 85 | // Ensure uncompress() returned the expected data. 86 | if ((uncomp_len != src_len) || (memcmp(pUncomp, s_pStr, (size_t)src_len))) 87 | { 88 | printf("Decompression failed!\n"); 89 | free(pCmp); 90 | free(pUncomp); 91 | return EXIT_FAILURE; 92 | } 93 | } 94 | 95 | free(pCmp); 96 | free(pUncomp); 97 | 98 | step++; 99 | 100 | // Keep on fuzzy testing if there's a non-empty command line. 101 | } while (argc >= 2); 102 | 103 | printf("Success.\n"); 104 | return EXIT_SUCCESS; 105 | } 106 | -------------------------------------------------------------------------------- /examples/example2.c: -------------------------------------------------------------------------------- 1 | // example2.c - Simple demonstration of miniz.c's ZIP archive API's. 2 | // Note this test deletes the test archive file "__mz_example2_test__.zip" in the current directory, then creates a new one with test data. 3 | // Public domain, May 15 2011, Rich Geldreich, richgel99@gmail.com. See "unlicense" statement at the end of tinfl.c. 4 | 5 | #if defined(__GNUC__) 6 | // Ensure we get the 64-bit variants of the CRT's file I/O calls 7 | #ifndef _FILE_OFFSET_BITS 8 | #define _FILE_OFFSET_BITS 64 9 | #endif 10 | #ifndef _LARGEFILE64_SOURCE 11 | #define _LARGEFILE64_SOURCE 1 12 | #endif 13 | #endif 14 | 15 | #include 16 | #include "miniz.h" 17 | 18 | typedef unsigned char uint8; 19 | typedef unsigned short uint16; 20 | typedef unsigned int uint; 21 | 22 | // The string to compress. 23 | static const char *s_pTest_str = 24 | "MISSION CONTROL I wouldn't worry too much about the computer. First of all, there is still a chance that he is right, despite your tests, and" \ 25 | "if it should happen again, we suggest eliminating this possibility by allowing the unit to remain in place and seeing whether or not it" \ 26 | "actually fails. If the computer should turn out to be wrong, the situation is still not alarming. The type of obsessional error he may be" \ 27 | "guilty of is not unknown among the latest generation of HAL 9000 computers. It has almost always revolved around a single detail, such as" \ 28 | "the one you have described, and it has never interfered with the integrity or reliability of the computer's performance in other areas." \ 29 | "No one is certain of the cause of this kind of malfunctioning. It may be over-programming, but it could also be any number of reasons. In any" \ 30 | "event, it is somewhat analogous to human neurotic behavior. Does this answer your query? Zero-five-three-Zero, MC, transmission concluded."; 31 | 32 | static const char *s_pComment = "This is a comment"; 33 | 34 | int main(int argc, char *argv[]) 35 | { 36 | int i, sort_iter; 37 | mz_bool status; 38 | size_t uncomp_size; 39 | mz_zip_archive zip_archive; 40 | void *p; 41 | const int N = 50; 42 | char data[2048]; 43 | char archive_filename[64]; 44 | static const char *s_Test_archive_filename = "__mz_example2_test__.zip"; 45 | 46 | assert((strlen(s_pTest_str) + 64) < sizeof(data)); 47 | 48 | printf("miniz.c version: %s\n", MZ_VERSION); 49 | 50 | (void)argc, (void)argv; 51 | 52 | // Delete the test archive, so it doesn't keep growing as we run this test 53 | remove(s_Test_archive_filename); 54 | 55 | // Append a bunch of text files to the test archive 56 | for (i = (N - 1); i >= 0; --i) 57 | { 58 | sprintf(archive_filename, "%u.txt", i); 59 | sprintf(data, "%u %s %u", (N - 1) - i, s_pTest_str, i); 60 | 61 | // Add a new file to the archive. Note this is an IN-PLACE operation, so if it fails your archive is probably hosed (its central directory may not be complete) but it should be recoverable using zip -F or -FF. So use caution with this guy. 62 | // A more robust way to add a file to an archive would be to read it into memory, perform the operation, then write a new archive out to a temp file and then delete/rename the files. 63 | // Or, write a new archive to disk to a temp file, then delete/rename the files. For this test this API is fine. 64 | status = mz_zip_add_mem_to_archive_file_in_place(s_Test_archive_filename, archive_filename, data, strlen(data) + 1, s_pComment, (uint16)strlen(s_pComment), MZ_BEST_COMPRESSION); 65 | if (!status) 66 | { 67 | printf("mz_zip_add_mem_to_archive_file_in_place failed!\n"); 68 | return EXIT_FAILURE; 69 | } 70 | } 71 | 72 | // Add a directory entry for testing 73 | status = mz_zip_add_mem_to_archive_file_in_place(s_Test_archive_filename, "directory/", NULL, 0, "no comment", (uint16)strlen("no comment"), MZ_BEST_COMPRESSION); 74 | if (!status) 75 | { 76 | printf("mz_zip_add_mem_to_archive_file_in_place failed!\n"); 77 | return EXIT_FAILURE; 78 | } 79 | 80 | // Now try to open the archive. 81 | memset(&zip_archive, 0, sizeof(zip_archive)); 82 | 83 | status = mz_zip_reader_init_file(&zip_archive, s_Test_archive_filename, 0); 84 | if (!status) 85 | { 86 | printf("mz_zip_reader_init_file() failed!\n"); 87 | return EXIT_FAILURE; 88 | } 89 | 90 | // Get and print information about each file in the archive. 91 | for (i = 0; i < (int)mz_zip_reader_get_num_files(&zip_archive); i++) 92 | { 93 | mz_zip_archive_file_stat file_stat; 94 | if (!mz_zip_reader_file_stat(&zip_archive, i, &file_stat)) 95 | { 96 | printf("mz_zip_reader_file_stat() failed!\n"); 97 | mz_zip_reader_end(&zip_archive); 98 | return EXIT_FAILURE; 99 | } 100 | 101 | printf("Filename: \"%s\", Comment: \"%s\", Uncompressed size: %u, Compressed size: %u, Is Dir: %u\n", file_stat.m_filename, file_stat.m_comment, (uint)file_stat.m_uncomp_size, (uint)file_stat.m_comp_size, mz_zip_reader_is_file_a_directory(&zip_archive, i)); 102 | 103 | if (!strcmp(file_stat.m_filename, "directory/")) 104 | { 105 | if (!mz_zip_reader_is_file_a_directory(&zip_archive, i)) 106 | { 107 | printf("mz_zip_reader_is_file_a_directory() didn't return the expected results!\n"); 108 | mz_zip_reader_end(&zip_archive); 109 | return EXIT_FAILURE; 110 | } 111 | } 112 | } 113 | 114 | // Close the archive, freeing any resources it was using 115 | mz_zip_reader_end(&zip_archive); 116 | 117 | // Now verify the compressed data 118 | for (sort_iter = 0; sort_iter < 2; sort_iter++) 119 | { 120 | memset(&zip_archive, 0, sizeof(zip_archive)); 121 | status = mz_zip_reader_init_file(&zip_archive, s_Test_archive_filename, sort_iter ? MZ_ZIP_FLAG_DO_NOT_SORT_CENTRAL_DIRECTORY : 0); 122 | if (!status) 123 | { 124 | printf("mz_zip_reader_init_file() failed!\n"); 125 | return EXIT_FAILURE; 126 | } 127 | 128 | for (i = 0; i < N; i++) 129 | { 130 | sprintf(archive_filename, "%u.txt", i); 131 | sprintf(data, "%u %s %u", (N - 1) - i, s_pTest_str, i); 132 | 133 | // Try to extract all the files to the heap. 134 | p = mz_zip_reader_extract_file_to_heap(&zip_archive, archive_filename, &uncomp_size, 0); 135 | if (!p) 136 | { 137 | printf("mz_zip_reader_extract_file_to_heap() failed!\n"); 138 | mz_zip_reader_end(&zip_archive); 139 | return EXIT_FAILURE; 140 | } 141 | 142 | // Make sure the extraction really succeeded. 143 | if ((uncomp_size != (strlen(data) + 1)) || (memcmp(p, data, strlen(data)))) 144 | { 145 | printf("mz_zip_reader_extract_file_to_heap() failed to extract the proper data\n"); 146 | mz_free(p); 147 | mz_zip_reader_end(&zip_archive); 148 | return EXIT_FAILURE; 149 | } 150 | 151 | printf("Successfully extracted file \"%s\", size %u\n", archive_filename, (uint)uncomp_size); 152 | printf("File data: \"%s\"\n", (const char *)p); 153 | 154 | // We're done. 155 | mz_free(p); 156 | } 157 | 158 | // Close the archive, freeing any resources it was using 159 | mz_zip_reader_end(&zip_archive); 160 | } 161 | 162 | printf("Success.\n"); 163 | return EXIT_SUCCESS; 164 | } 165 | -------------------------------------------------------------------------------- /examples/example3.c: -------------------------------------------------------------------------------- 1 | // example3.c - Demonstrates how to use miniz.c's deflate() and inflate() functions for simple file compression. 2 | // Public domain, May 15 2011, Rich Geldreich, richgel99@gmail.com. See "unlicense" statement at the end of tinfl.c. 3 | // For simplicity, this example is limited to files smaller than 4GB, but this is not a limitation of miniz.c. 4 | #include 5 | #include 6 | #include "miniz.h" 7 | 8 | typedef unsigned char uint8; 9 | typedef unsigned short uint16; 10 | typedef unsigned int uint; 11 | 12 | #define my_max(a,b) (((a) > (b)) ? (a) : (b)) 13 | #define my_min(a,b) (((a) < (b)) ? (a) : (b)) 14 | 15 | #define BUF_SIZE (1024 * 1024) 16 | static uint8 s_inbuf[BUF_SIZE]; 17 | static uint8 s_outbuf[BUF_SIZE]; 18 | 19 | int main(int argc, char *argv[]) 20 | { 21 | const char *pMode; 22 | FILE *pInfile, *pOutfile; 23 | uint infile_size; 24 | int level = Z_BEST_COMPRESSION; 25 | z_stream stream; 26 | int p = 1; 27 | const char *pSrc_filename; 28 | const char *pDst_filename; 29 | long file_loc; 30 | 31 | printf("miniz.c version: %s\n", MZ_VERSION); 32 | 33 | if (argc < 4) 34 | { 35 | printf("Usage: example3 [options] [mode:c or d] infile outfile\n"); 36 | printf("\nModes:\n"); 37 | printf("c - Compresses file infile to a zlib stream in file outfile\n"); 38 | printf("d - Decompress zlib stream in file infile to file outfile\n"); 39 | printf("\nOptions:\n"); 40 | printf("-l[0-10] - Compression level, higher values are slower.\n"); 41 | return EXIT_FAILURE; 42 | } 43 | 44 | while ((p < argc) && (argv[p][0] == '-')) 45 | { 46 | switch (argv[p][1]) 47 | { 48 | case 'l': 49 | { 50 | level = atoi(&argv[1][2]); 51 | if ((level < 0) || (level > 10)) 52 | { 53 | printf("Invalid level!\n"); 54 | return EXIT_FAILURE; 55 | } 56 | break; 57 | } 58 | default: 59 | { 60 | printf("Invalid option: %s\n", argv[p]); 61 | return EXIT_FAILURE; 62 | } 63 | } 64 | p++; 65 | } 66 | 67 | if ((argc - p) < 3) 68 | { 69 | printf("Must specify mode, input filename, and output filename after options!\n"); 70 | return EXIT_FAILURE; 71 | } 72 | else if ((argc - p) > 3) 73 | { 74 | printf("Too many filenames!\n"); 75 | return EXIT_FAILURE; 76 | } 77 | 78 | pMode = argv[p++]; 79 | if (!strchr("cCdD", pMode[0])) 80 | { 81 | printf("Invalid mode!\n"); 82 | return EXIT_FAILURE; 83 | } 84 | 85 | pSrc_filename = argv[p++]; 86 | pDst_filename = argv[p++]; 87 | 88 | printf("Mode: %c, Level: %u\nInput File: \"%s\"\nOutput File: \"%s\"\n", pMode[0], level, pSrc_filename, pDst_filename); 89 | 90 | // Open input file. 91 | pInfile = fopen(pSrc_filename, "rb"); 92 | if (!pInfile) 93 | { 94 | printf("Failed opening input file!\n"); 95 | return EXIT_FAILURE; 96 | } 97 | 98 | // Determine input file's size. 99 | fseek(pInfile, 0, SEEK_END); 100 | file_loc = ftell(pInfile); 101 | fseek(pInfile, 0, SEEK_SET); 102 | 103 | if ((file_loc < 0) || ((mz_uint64)file_loc > INT_MAX)) 104 | { 105 | // This is not a limitation of miniz or tinfl, but this example. 106 | printf("File is too large to be processed by this example.\n"); 107 | return EXIT_FAILURE; 108 | } 109 | 110 | infile_size = (uint)file_loc; 111 | 112 | // Open output file. 113 | pOutfile = fopen(pDst_filename, "wb"); 114 | if (!pOutfile) 115 | { 116 | printf("Failed opening output file!\n"); 117 | return EXIT_FAILURE; 118 | } 119 | 120 | printf("Input file size: %u\n", infile_size); 121 | 122 | // Init the z_stream 123 | memset(&stream, 0, sizeof(stream)); 124 | stream.next_in = s_inbuf; 125 | stream.avail_in = 0; 126 | stream.next_out = s_outbuf; 127 | stream.avail_out = BUF_SIZE; 128 | 129 | if ((pMode[0] == 'c') || (pMode[0] == 'C')) 130 | { 131 | // Compression. 132 | uint infile_remaining = infile_size; 133 | 134 | if (deflateInit(&stream, level) != Z_OK) 135 | { 136 | printf("deflateInit() failed!\n"); 137 | return EXIT_FAILURE; 138 | } 139 | 140 | for ( ; ; ) 141 | { 142 | int status; 143 | if (!stream.avail_in) 144 | { 145 | // Input buffer is empty, so read more bytes from input file. 146 | uint n = my_min(BUF_SIZE, infile_remaining); 147 | 148 | if (fread(s_inbuf, 1, n, pInfile) != n) 149 | { 150 | printf("Failed reading from input file!\n"); 151 | return EXIT_FAILURE; 152 | } 153 | 154 | stream.next_in = s_inbuf; 155 | stream.avail_in = n; 156 | 157 | infile_remaining -= n; 158 | //printf("Input bytes remaining: %u\n", infile_remaining); 159 | } 160 | 161 | status = deflate(&stream, infile_remaining ? Z_NO_FLUSH : Z_FINISH); 162 | 163 | if ((status == Z_STREAM_END) || (!stream.avail_out)) 164 | { 165 | // Output buffer is full, or compression is done, so write buffer to output file. 166 | uint n = BUF_SIZE - stream.avail_out; 167 | if (fwrite(s_outbuf, 1, n, pOutfile) != n) 168 | { 169 | printf("Failed writing to output file!\n"); 170 | return EXIT_FAILURE; 171 | } 172 | stream.next_out = s_outbuf; 173 | stream.avail_out = BUF_SIZE; 174 | } 175 | 176 | if (status == Z_STREAM_END) 177 | break; 178 | else if (status != Z_OK) 179 | { 180 | printf("deflate() failed with status %i!\n", status); 181 | return EXIT_FAILURE; 182 | } 183 | } 184 | 185 | if (deflateEnd(&stream) != Z_OK) 186 | { 187 | printf("deflateEnd() failed!\n"); 188 | return EXIT_FAILURE; 189 | } 190 | } 191 | else if ((pMode[0] == 'd') || (pMode[0] == 'D')) 192 | { 193 | // Decompression. 194 | uint infile_remaining = infile_size; 195 | 196 | if (inflateInit(&stream)) 197 | { 198 | printf("inflateInit() failed!\n"); 199 | return EXIT_FAILURE; 200 | } 201 | 202 | for ( ; ; ) 203 | { 204 | int status; 205 | if (!stream.avail_in) 206 | { 207 | // Input buffer is empty, so read more bytes from input file. 208 | uint n = my_min(BUF_SIZE, infile_remaining); 209 | 210 | if (fread(s_inbuf, 1, n, pInfile) != n) 211 | { 212 | printf("Failed reading from input file!\n"); 213 | return EXIT_FAILURE; 214 | } 215 | 216 | stream.next_in = s_inbuf; 217 | stream.avail_in = n; 218 | 219 | infile_remaining -= n; 220 | } 221 | 222 | status = inflate(&stream, Z_SYNC_FLUSH); 223 | 224 | if ((status == Z_STREAM_END) || (!stream.avail_out)) 225 | { 226 | // Output buffer is full, or decompression is done, so write buffer to output file. 227 | uint n = BUF_SIZE - stream.avail_out; 228 | if (fwrite(s_outbuf, 1, n, pOutfile) != n) 229 | { 230 | printf("Failed writing to output file!\n"); 231 | return EXIT_FAILURE; 232 | } 233 | stream.next_out = s_outbuf; 234 | stream.avail_out = BUF_SIZE; 235 | } 236 | 237 | if (status == Z_STREAM_END) 238 | break; 239 | else if (status != Z_OK) 240 | { 241 | printf("inflate() failed with status %i!\n", status); 242 | return EXIT_FAILURE; 243 | } 244 | } 245 | 246 | if (inflateEnd(&stream) != Z_OK) 247 | { 248 | printf("inflateEnd() failed!\n"); 249 | return EXIT_FAILURE; 250 | } 251 | } 252 | else 253 | { 254 | printf("Invalid mode!\n"); 255 | return EXIT_FAILURE; 256 | } 257 | 258 | fclose(pInfile); 259 | if (EOF == fclose(pOutfile)) 260 | { 261 | printf("Failed writing to output file!\n"); 262 | return EXIT_FAILURE; 263 | } 264 | 265 | printf("Total input bytes: %u\n", (mz_uint32)stream.total_in); 266 | printf("Total output bytes: %u\n", (mz_uint32)stream.total_out); 267 | printf("Success.\n"); 268 | return EXIT_SUCCESS; 269 | } 270 | -------------------------------------------------------------------------------- /examples/example4.c: -------------------------------------------------------------------------------- 1 | // example4.c - Uses tinfl.c to decompress a zlib stream in memory to an output file 2 | // Public domain, May 15 2011, Rich Geldreich, richgel99@gmail.com. See "unlicense" statement at the end of tinfl.c. 3 | #include "miniz.h" 4 | #include 5 | #include 6 | 7 | typedef unsigned char uint8; 8 | typedef unsigned short uint16; 9 | typedef unsigned int uint; 10 | 11 | #define my_max(a,b) (((a) > (b)) ? (a) : (b)) 12 | #define my_min(a,b) (((a) < (b)) ? (a) : (b)) 13 | 14 | static int tinfl_put_buf_func(const void* pBuf, int len, void *pUser) 15 | { 16 | return len == (int)fwrite(pBuf, 1, len, (FILE*)pUser); 17 | } 18 | 19 | int main(int argc, char *argv[]) 20 | { 21 | int status; 22 | FILE *pInfile, *pOutfile; 23 | uint infile_size, outfile_size; 24 | size_t in_buf_size; 25 | uint8 *pCmp_data; 26 | long file_loc; 27 | 28 | if (argc != 3) 29 | { 30 | printf("Usage: example4 infile outfile\n"); 31 | printf("Decompresses zlib stream in file infile to file outfile.\n"); 32 | printf("Input file must be able to fit entirely in memory.\n"); 33 | printf("example3 can be used to create compressed zlib streams.\n"); 34 | return EXIT_FAILURE; 35 | } 36 | 37 | // Open input file. 38 | pInfile = fopen(argv[1], "rb"); 39 | if (!pInfile) 40 | { 41 | printf("Failed opening input file!\n"); 42 | return EXIT_FAILURE; 43 | } 44 | 45 | // Determine input file's size. 46 | fseek(pInfile, 0, SEEK_END); 47 | file_loc = ftell(pInfile); 48 | fseek(pInfile, 0, SEEK_SET); 49 | 50 | if ((file_loc < 0) || ((mz_uint64)file_loc > INT_MAX)) 51 | { 52 | // This is not a limitation of miniz or tinfl, but this example. 53 | printf("File is too large to be processed by this example.\n"); 54 | return EXIT_FAILURE; 55 | } 56 | 57 | infile_size = (uint)file_loc; 58 | 59 | pCmp_data = (uint8 *)malloc(infile_size); 60 | if (!pCmp_data) 61 | { 62 | printf("Out of memory!\n"); 63 | return EXIT_FAILURE; 64 | } 65 | if (fread(pCmp_data, 1, infile_size, pInfile) != infile_size) 66 | { 67 | printf("Failed reading input file!\n"); 68 | return EXIT_FAILURE; 69 | } 70 | 71 | // Open output file. 72 | pOutfile = fopen(argv[2], "wb"); 73 | if (!pOutfile) 74 | { 75 | printf("Failed opening output file!\n"); 76 | return EXIT_FAILURE; 77 | } 78 | 79 | printf("Input file size: %u\n", infile_size); 80 | 81 | in_buf_size = infile_size; 82 | status = tinfl_decompress_mem_to_callback(pCmp_data, &in_buf_size, tinfl_put_buf_func, pOutfile, TINFL_FLAG_PARSE_ZLIB_HEADER); 83 | if (!status) 84 | { 85 | printf("tinfl_decompress_mem_to_callback() failed with status %i!\n", status); 86 | return EXIT_FAILURE; 87 | } 88 | 89 | outfile_size = ftell(pOutfile); 90 | 91 | fclose(pInfile); 92 | if (EOF == fclose(pOutfile)) 93 | { 94 | printf("Failed writing to output file!\n"); 95 | return EXIT_FAILURE; 96 | } 97 | 98 | printf("Total input bytes: %u\n", (uint)in_buf_size); 99 | printf("Total output bytes: %u\n", outfile_size); 100 | printf("Success.\n"); 101 | return EXIT_SUCCESS; 102 | } 103 | -------------------------------------------------------------------------------- /examples/example5.c: -------------------------------------------------------------------------------- 1 | // example5.c - Demonstrates how to use miniz.c's low-level tdefl_compress() and tinfl_inflate() API's for simple file to file compression/decompression. 2 | // The low-level API's are the fastest, make no use of dynamic memory allocation, and are the most flexible functions exposed by miniz.c. 3 | // Public domain, April 11 2012, Rich Geldreich, richgel99@gmail.com. See "unlicense" statement at the end of tinfl.c. 4 | // For simplicity, this example is limited to files smaller than 4GB, but this is not a limitation of miniz.c. 5 | 6 | // Purposely disable a whole bunch of stuff this low-level example doesn't use. 7 | #define MINIZ_NO_STDIO 8 | #define MINIZ_NO_ARCHIVE_APIS 9 | #define MINIZ_NO_TIME 10 | #define MINIZ_NO_ZLIB_APIS 11 | #define MINIZ_NO_MALLOC 12 | #include "miniz.h" 13 | 14 | // Now include stdio.h because this test uses fopen(), etc. (but we still don't want miniz.c's stdio stuff, for testing). 15 | #include 16 | #include 17 | 18 | typedef unsigned char uint8; 19 | typedef unsigned short uint16; 20 | typedef unsigned int uint; 21 | 22 | #define my_max(a,b) (((a) > (b)) ? (a) : (b)) 23 | #define my_min(a,b) (((a) < (b)) ? (a) : (b)) 24 | 25 | // IN_BUF_SIZE is the size of the file read buffer. 26 | // IN_BUF_SIZE must be >= 1 27 | #define IN_BUF_SIZE (1024*512) 28 | static uint8 s_inbuf[IN_BUF_SIZE]; 29 | 30 | // COMP_OUT_BUF_SIZE is the size of the output buffer used during compression. 31 | // COMP_OUT_BUF_SIZE must be >= 1 and <= OUT_BUF_SIZE 32 | #define COMP_OUT_BUF_SIZE (1024*512) 33 | 34 | // OUT_BUF_SIZE is the size of the output buffer used during decompression. 35 | // OUT_BUF_SIZE must be a power of 2 >= TINFL_LZ_DICT_SIZE (because the low-level decompressor not only writes, but reads from the output buffer as it decompresses) 36 | //#define OUT_BUF_SIZE (TINFL_LZ_DICT_SIZE) 37 | #define OUT_BUF_SIZE (1024*512) 38 | static uint8 s_outbuf[OUT_BUF_SIZE]; 39 | 40 | // tdefl_compressor contains all the state needed by the low-level compressor so it's a pretty big struct (~300k). 41 | // This example makes it a global vs. putting it on the stack, of course in real-world usage you'll probably malloc() or new it. 42 | tdefl_compressor g_deflator; 43 | 44 | int main(int argc, char *argv[]) 45 | { 46 | const char *pMode; 47 | FILE *pInfile, *pOutfile; 48 | uint infile_size; 49 | int level = 9; 50 | int p = 1; 51 | const char *pSrc_filename; 52 | const char *pDst_filename; 53 | const void *next_in = s_inbuf; 54 | size_t avail_in = 0; 55 | void *next_out = s_outbuf; 56 | size_t avail_out = OUT_BUF_SIZE; 57 | size_t total_in = 0, total_out = 0; 58 | long file_loc; 59 | 60 | assert(COMP_OUT_BUF_SIZE <= OUT_BUF_SIZE); 61 | 62 | printf("miniz.c example5 (demonstrates tinfl/tdefl)\n"); 63 | 64 | if (argc < 4) 65 | { 66 | printf("File to file compression/decompression using the low-level tinfl/tdefl API's.\n"); 67 | printf("Usage: example5 [options] [mode:c or d] infile outfile\n"); 68 | printf("\nModes:\n"); 69 | printf("c - Compresses file infile to a zlib stream in file outfile\n"); 70 | printf("d - Decompress zlib stream in file infile to file outfile\n"); 71 | printf("\nOptions:\n"); 72 | printf("-l[0-10] - Compression level, higher values are slower, 0 is none.\n"); 73 | return EXIT_FAILURE; 74 | } 75 | 76 | while ((p < argc) && (argv[p][0] == '-')) 77 | { 78 | switch (argv[p][1]) 79 | { 80 | case 'l': 81 | { 82 | level = atoi(&argv[1][2]); 83 | if ((level < 0) || (level > 10)) 84 | { 85 | printf("Invalid level!\n"); 86 | return EXIT_FAILURE; 87 | } 88 | break; 89 | } 90 | default: 91 | { 92 | printf("Invalid option: %s\n", argv[p]); 93 | return EXIT_FAILURE; 94 | } 95 | } 96 | p++; 97 | } 98 | 99 | if ((argc - p) < 3) 100 | { 101 | printf("Must specify mode, input filename, and output filename after options!\n"); 102 | return EXIT_FAILURE; 103 | } 104 | else if ((argc - p) > 3) 105 | { 106 | printf("Too many filenames!\n"); 107 | return EXIT_FAILURE; 108 | } 109 | 110 | pMode = argv[p++]; 111 | if (!strchr("cCdD", pMode[0])) 112 | { 113 | printf("Invalid mode!\n"); 114 | return EXIT_FAILURE; 115 | } 116 | 117 | pSrc_filename = argv[p++]; 118 | pDst_filename = argv[p++]; 119 | 120 | printf("Mode: %c, Level: %u\nInput File: \"%s\"\nOutput File: \"%s\"\n", pMode[0], level, pSrc_filename, pDst_filename); 121 | 122 | // Open input file. 123 | pInfile = fopen(pSrc_filename, "rb"); 124 | if (!pInfile) 125 | { 126 | printf("Failed opening input file!\n"); 127 | return EXIT_FAILURE; 128 | } 129 | 130 | // Determine input file's size. 131 | fseek(pInfile, 0, SEEK_END); 132 | file_loc = ftell(pInfile); 133 | fseek(pInfile, 0, SEEK_SET); 134 | 135 | if ((file_loc < 0) || ((mz_uint64)file_loc > INT_MAX)) 136 | { 137 | // This is not a limitation of miniz or tinfl, but this example. 138 | printf("File is too large to be processed by this example.\n"); 139 | return EXIT_FAILURE; 140 | } 141 | 142 | infile_size = (uint)file_loc; 143 | 144 | // Open output file. 145 | pOutfile = fopen(pDst_filename, "wb"); 146 | if (!pOutfile) 147 | { 148 | printf("Failed opening output file!\n"); 149 | return EXIT_FAILURE; 150 | } 151 | 152 | printf("Input file size: %u\n", infile_size); 153 | 154 | if ((pMode[0] == 'c') || (pMode[0] == 'C')) 155 | { 156 | // The number of dictionary probes to use at each compression level (0-10). 0=implies fastest/minimal possible probing. 157 | static const mz_uint s_tdefl_num_probes[11] = { 0, 1, 6, 32, 16, 32, 128, 256, 512, 768, 1500 }; 158 | 159 | tdefl_status status; 160 | uint infile_remaining = infile_size; 161 | 162 | // create tdefl() compatible flags (we have to compose the low-level flags ourselves, or use tdefl_create_comp_flags_from_zip_params() but that means MINIZ_NO_ZLIB_APIS can't be defined). 163 | mz_uint comp_flags = TDEFL_WRITE_ZLIB_HEADER | s_tdefl_num_probes[MZ_MIN(10, level)] | ((level <= 3) ? TDEFL_GREEDY_PARSING_FLAG : 0); 164 | if (!level) 165 | comp_flags |= TDEFL_FORCE_ALL_RAW_BLOCKS; 166 | 167 | // Initialize the low-level compressor. 168 | status = tdefl_init(&g_deflator, NULL, NULL, comp_flags); 169 | if (status != TDEFL_STATUS_OKAY) 170 | { 171 | printf("tdefl_init() failed!\n"); 172 | return EXIT_FAILURE; 173 | } 174 | 175 | avail_out = COMP_OUT_BUF_SIZE; 176 | 177 | // Compression. 178 | for ( ; ; ) 179 | { 180 | size_t in_bytes, out_bytes; 181 | 182 | if (!avail_in) 183 | { 184 | // Input buffer is empty, so read more bytes from input file. 185 | uint n = my_min(IN_BUF_SIZE, infile_remaining); 186 | 187 | if (fread(s_inbuf, 1, n, pInfile) != n) 188 | { 189 | printf("Failed reading from input file!\n"); 190 | return EXIT_FAILURE; 191 | } 192 | 193 | next_in = s_inbuf; 194 | avail_in = n; 195 | 196 | infile_remaining -= n; 197 | //printf("Input bytes remaining: %u\n", infile_remaining); 198 | } 199 | 200 | in_bytes = avail_in; 201 | out_bytes = avail_out; 202 | // Compress as much of the input as possible (or all of it) to the output buffer. 203 | status = tdefl_compress(&g_deflator, next_in, &in_bytes, next_out, &out_bytes, infile_remaining ? TDEFL_NO_FLUSH : TDEFL_FINISH); 204 | 205 | next_in = (const char *)next_in + in_bytes; 206 | avail_in -= in_bytes; 207 | total_in += in_bytes; 208 | 209 | next_out = (char *)next_out + out_bytes; 210 | avail_out -= out_bytes; 211 | total_out += out_bytes; 212 | 213 | if ((status != TDEFL_STATUS_OKAY) || (!avail_out)) 214 | { 215 | // Output buffer is full, or compression is done or failed, so write buffer to output file. 216 | uint n = COMP_OUT_BUF_SIZE - (uint)avail_out; 217 | if (fwrite(s_outbuf, 1, n, pOutfile) != n) 218 | { 219 | printf("Failed writing to output file!\n"); 220 | return EXIT_FAILURE; 221 | } 222 | next_out = s_outbuf; 223 | avail_out = COMP_OUT_BUF_SIZE; 224 | } 225 | 226 | if (status == TDEFL_STATUS_DONE) 227 | { 228 | // Compression completed successfully. 229 | break; 230 | } 231 | else if (status != TDEFL_STATUS_OKAY) 232 | { 233 | // Compression somehow failed. 234 | printf("tdefl_compress() failed with status %i!\n", status); 235 | return EXIT_FAILURE; 236 | } 237 | } 238 | } 239 | else if ((pMode[0] == 'd') || (pMode[0] == 'D')) 240 | { 241 | // Decompression. 242 | uint infile_remaining = infile_size; 243 | 244 | tinfl_decompressor inflator; 245 | tinfl_init(&inflator); 246 | 247 | for ( ; ; ) 248 | { 249 | size_t in_bytes, out_bytes; 250 | tinfl_status status; 251 | if (!avail_in) 252 | { 253 | // Input buffer is empty, so read more bytes from input file. 254 | uint n = my_min(IN_BUF_SIZE, infile_remaining); 255 | 256 | if (fread(s_inbuf, 1, n, pInfile) != n) 257 | { 258 | printf("Failed reading from input file!\n"); 259 | return EXIT_FAILURE; 260 | } 261 | 262 | next_in = s_inbuf; 263 | avail_in = n; 264 | 265 | infile_remaining -= n; 266 | } 267 | 268 | in_bytes = avail_in; 269 | out_bytes = avail_out; 270 | status = tinfl_decompress(&inflator, (const mz_uint8 *)next_in, &in_bytes, s_outbuf, (mz_uint8 *)next_out, &out_bytes, (infile_remaining ? TINFL_FLAG_HAS_MORE_INPUT : 0) | TINFL_FLAG_PARSE_ZLIB_HEADER); 271 | 272 | avail_in -= in_bytes; 273 | next_in = (const mz_uint8 *)next_in + in_bytes; 274 | total_in += in_bytes; 275 | 276 | avail_out -= out_bytes; 277 | next_out = (mz_uint8 *)next_out + out_bytes; 278 | total_out += out_bytes; 279 | 280 | if ((status <= TINFL_STATUS_DONE) || (!avail_out)) 281 | { 282 | // Output buffer is full, or decompression is done, so write buffer to output file. 283 | uint n = OUT_BUF_SIZE - (uint)avail_out; 284 | if (fwrite(s_outbuf, 1, n, pOutfile) != n) 285 | { 286 | printf("Failed writing to output file!\n"); 287 | return EXIT_FAILURE; 288 | } 289 | next_out = s_outbuf; 290 | avail_out = OUT_BUF_SIZE; 291 | } 292 | 293 | // If status is <= TINFL_STATUS_DONE then either decompression is done or something went wrong. 294 | if (status <= TINFL_STATUS_DONE) 295 | { 296 | if (status == TINFL_STATUS_DONE) 297 | { 298 | // Decompression completed successfully. 299 | break; 300 | } 301 | else 302 | { 303 | // Decompression failed. 304 | printf("tinfl_decompress() failed with status %i!\n", status); 305 | return EXIT_FAILURE; 306 | } 307 | } 308 | } 309 | } 310 | else 311 | { 312 | printf("Invalid mode!\n"); 313 | return EXIT_FAILURE; 314 | } 315 | 316 | fclose(pInfile); 317 | if (EOF == fclose(pOutfile)) 318 | { 319 | printf("Failed writing to output file!\n"); 320 | return EXIT_FAILURE; 321 | } 322 | 323 | printf("Total input bytes: %u\n", (mz_uint32)total_in); 324 | printf("Total output bytes: %u\n", (mz_uint32)total_out); 325 | printf("Success.\n"); 326 | return EXIT_SUCCESS; 327 | } 328 | -------------------------------------------------------------------------------- /examples/example6.c: -------------------------------------------------------------------------------- 1 | // example6.c - Demonstrates how to miniz's PNG writer func 2 | // Public domain, April 11 2012, Rich Geldreich, richgel99@gmail.com. See "unlicense" statement at the end of tinfl.c. 3 | // Mandlebrot set code from http://rosettacode.org/wiki/Mandelbrot_set#C 4 | // Must link this example against libm on Linux. 5 | 6 | // Purposely disable a whole bunch of stuff this low-level example doesn't use. 7 | #define MINIZ_NO_STDIO 8 | #define MINIZ_NO_TIME 9 | #define MINIZ_NO_ZLIB_APIS 10 | #include "miniz.h" 11 | 12 | // Now include stdio.h because this test uses fopen(), etc. (but we still don't want miniz.c's stdio stuff, for testing). 13 | #include 14 | #include 15 | #include 16 | 17 | typedef unsigned char uint8; 18 | typedef unsigned short uint16; 19 | typedef unsigned int uint; 20 | 21 | typedef struct 22 | { 23 | uint8 r, g, b; 24 | } rgb_t; 25 | 26 | static void hsv_to_rgb(int hue, int min, int max, rgb_t *p) 27 | { 28 | const int invert = 0; 29 | const int saturation = 1; 30 | const int color_rotate = 0; 31 | 32 | if (min == max) max = min + 1; 33 | if (invert) hue = max - (hue - min); 34 | if (!saturation) { 35 | p->r = p->g = p->b = 255 * (max - hue) / (max - min); 36 | return; 37 | } else { 38 | const double h_dbl = fmod(color_rotate + 1e-4 + 4.0 * (hue - min) / (max - min), 6); 39 | const double c_dbl = 255 * saturation; 40 | const double X_dbl = c_dbl * (1 - fabs(fmod(h_dbl, 2) - 1)); 41 | const int h = (int)h_dbl; 42 | const int c = (int)c_dbl; 43 | const int X = (int)X_dbl; 44 | 45 | p->r = p->g = p->b = 0; 46 | 47 | switch(h) { 48 | case 0: p->r = c; p->g = X; return; 49 | case 1: p->r = X; p->g = c; return; 50 | case 2: p->g = c; p->b = X; return; 51 | case 3: p->g = X; p->b = c; return; 52 | case 4: p->r = X; p->b = c; return; 53 | default:p->r = c; p->b = X; 54 | } 55 | } 56 | } 57 | 58 | int main(int argc, char *argv[]) 59 | { 60 | // Image resolution 61 | const int iXmax = 4096; 62 | const int iYmax = 4096; 63 | 64 | // Output filename 65 | static const char *pFilename = "mandelbrot.png"; 66 | 67 | int iX, iY; 68 | const double CxMin = -2.5; 69 | const double CxMax = 1.5; 70 | const double CyMin = -2.0; 71 | const double CyMax = 2.0; 72 | 73 | double PixelWidth = (CxMax - CxMin) / iXmax; 74 | double PixelHeight = (CyMax - CyMin) / iYmax; 75 | 76 | // Z=Zx+Zy*i ; Z0 = 0 77 | double Zx, Zy; 78 | double Zx2, Zy2; // Zx2=Zx*Zx; Zy2=Zy*Zy 79 | 80 | int Iteration; 81 | const int IterationMax = 200; 82 | 83 | // bail-out value , radius of circle 84 | const double EscapeRadius = 2; 85 | double ER2=EscapeRadius * EscapeRadius; 86 | 87 | uint8 *pImage = (uint8 *)malloc(iXmax * 3 * iYmax); 88 | 89 | // world ( double) coordinate = parameter plane 90 | double Cx,Cy; 91 | 92 | int MinIter = 9999, MaxIter = 0; 93 | 94 | (void)argc, (void)argv; 95 | 96 | for(iY = 0; iY < iYmax; iY++) 97 | { 98 | Cy = CyMin + iY * PixelHeight; 99 | if (fabs(Cy) < PixelHeight/2) 100 | Cy = 0.0; // Main antenna 101 | 102 | for(iX = 0; iX < iXmax; iX++) 103 | { 104 | uint8 *color = pImage + (iX * 3) + (iY * iXmax * 3); 105 | 106 | Cx = CxMin + iX * PixelWidth; 107 | 108 | // initial value of orbit = critical point Z= 0 109 | Zx = 0.0; 110 | Zy = 0.0; 111 | Zx2 = Zx * Zx; 112 | Zy2 = Zy * Zy; 113 | 114 | for (Iteration=0;Iteration> 8; 124 | color[2] = 0; 125 | 126 | if (Iteration < MinIter) 127 | MinIter = Iteration; 128 | if (Iteration > MaxIter) 129 | MaxIter = Iteration; 130 | } 131 | } 132 | 133 | for(iY = 0; iY < iYmax; iY++) 134 | { 135 | for(iX = 0; iX < iXmax; iX++) 136 | { 137 | uint8 *color = (uint8 *)(pImage + (iX * 3) + (iY * iXmax * 3)); 138 | 139 | uint Iterations = color[0] | (color[1] << 8U); 140 | 141 | hsv_to_rgb((int)Iterations, MinIter, MaxIter, (rgb_t *)color); 142 | } 143 | } 144 | 145 | // Now write the PNG image. 146 | { 147 | size_t png_data_size = 0; 148 | void *pPNG_data = tdefl_write_image_to_png_file_in_memory_ex(pImage, iXmax, iYmax, 3, &png_data_size, 6, MZ_FALSE); 149 | if (!pPNG_data) 150 | fprintf(stderr, "tdefl_write_image_to_png_file_in_memory_ex() failed!\n"); 151 | else 152 | { 153 | FILE *pFile = fopen(pFilename, "wb"); 154 | fwrite(pPNG_data, 1, png_data_size, pFile); 155 | fclose(pFile); 156 | printf("Wrote %s\n", pFilename); 157 | } 158 | 159 | // mz_free() is by default just an alias to free() internally, but if you've overridden miniz's allocation funcs you'll probably need to call mz_free(). 160 | mz_free(pPNG_data); 161 | } 162 | 163 | free(pImage); 164 | 165 | return EXIT_SUCCESS; 166 | } 167 | -------------------------------------------------------------------------------- /meson.build: -------------------------------------------------------------------------------- 1 | project('miniz', 'c') 2 | 3 | miniz_includes = include_directories('.') 4 | 5 | cfg = configuration_data() 6 | cfg.set('MINIZ_EXPORT', '') 7 | miniz_export_h = configure_file(output: 'miniz_export.h', 8 | configuration: cfg) 9 | 10 | libminiz = static_library('miniz', 11 | miniz_export_h, 'miniz.c', 'miniz_zip.c', 'miniz_tinfl.c', 'miniz_tdef.c', 12 | include_directories: miniz_includes) 13 | 14 | miniz_dependency = declare_dependency(link_with: libminiz, 15 | include_directories: miniz_includes) 16 | 17 | miniz_dep = miniz_dependency # Compatibility for WrapDB users 18 | 19 | if meson.version().version_compare('>= 0.54.0') 20 | meson.override_dependency('miniz', miniz_dep) 21 | endif 22 | -------------------------------------------------------------------------------- /miniz.c: -------------------------------------------------------------------------------- 1 | /************************************************************************** 2 | * 3 | * Copyright 2013-2014 RAD Game Tools and Valve Software 4 | * Copyright 2010-2014 Rich Geldreich and Tenacious Software LLC 5 | * All Rights Reserved. 6 | * 7 | * Permission is hereby granted, free of charge, to any person obtaining a copy 8 | * of this software and associated documentation files (the "Software"), to deal 9 | * in the Software without restriction, including without limitation the rights 10 | * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 11 | * copies of the Software, and to permit persons to whom the Software is 12 | * furnished to do so, subject to the following conditions: 13 | * 14 | * The above copyright notice and this permission notice shall be included in 15 | * all copies or substantial portions of the Software. 16 | * 17 | * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 18 | * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 19 | * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 20 | * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 21 | * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 22 | * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN 23 | * THE SOFTWARE. 24 | * 25 | **************************************************************************/ 26 | 27 | #include "miniz.h" 28 | 29 | typedef unsigned char mz_validate_uint16[sizeof(mz_uint16) == 2 ? 1 : -1]; 30 | typedef unsigned char mz_validate_uint32[sizeof(mz_uint32) == 4 ? 1 : -1]; 31 | typedef unsigned char mz_validate_uint64[sizeof(mz_uint64) == 8 ? 1 : -1]; 32 | 33 | #ifdef __cplusplus 34 | extern "C" { 35 | #endif 36 | 37 | /* ------------------- zlib-style API's */ 38 | 39 | mz_ulong mz_adler32(mz_ulong adler, const unsigned char *ptr, size_t buf_len) 40 | { 41 | mz_uint32 i, s1 = (mz_uint32)(adler & 0xffff), s2 = (mz_uint32)(adler >> 16); 42 | size_t block_len = buf_len % 5552; 43 | if (!ptr) 44 | return MZ_ADLER32_INIT; 45 | while (buf_len) 46 | { 47 | for (i = 0; i + 7 < block_len; i += 8, ptr += 8) 48 | { 49 | s1 += ptr[0], s2 += s1; 50 | s1 += ptr[1], s2 += s1; 51 | s1 += ptr[2], s2 += s1; 52 | s1 += ptr[3], s2 += s1; 53 | s1 += ptr[4], s2 += s1; 54 | s1 += ptr[5], s2 += s1; 55 | s1 += ptr[6], s2 += s1; 56 | s1 += ptr[7], s2 += s1; 57 | } 58 | for (; i < block_len; ++i) 59 | s1 += *ptr++, s2 += s1; 60 | s1 %= 65521U, s2 %= 65521U; 61 | buf_len -= block_len; 62 | block_len = 5552; 63 | } 64 | return (s2 << 16) + s1; 65 | } 66 | 67 | /* Karl Malbrain's compact CRC-32. See "A compact CCITT crc16 and crc32 C implementation that balances processor cache usage against speed": http://www.geocities.com/malbrain/ */ 68 | #if 0 69 | mz_ulong mz_crc32(mz_ulong crc, const mz_uint8 *ptr, size_t buf_len) 70 | { 71 | static const mz_uint32 s_crc32[16] = { 0, 0x1db71064, 0x3b6e20c8, 0x26d930ac, 0x76dc4190, 0x6b6b51f4, 0x4db26158, 0x5005713c, 72 | 0xedb88320, 0xf00f9344, 0xd6d6a3e8, 0xcb61b38c, 0x9b64c2b0, 0x86d3d2d4, 0xa00ae278, 0xbdbdf21c }; 73 | mz_uint32 crcu32 = (mz_uint32)crc; 74 | if (!ptr) 75 | return MZ_CRC32_INIT; 76 | crcu32 = ~crcu32; 77 | while (buf_len--) 78 | { 79 | mz_uint8 b = *ptr++; 80 | crcu32 = (crcu32 >> 4) ^ s_crc32[(crcu32 & 0xF) ^ (b & 0xF)]; 81 | crcu32 = (crcu32 >> 4) ^ s_crc32[(crcu32 & 0xF) ^ (b >> 4)]; 82 | } 83 | return ~crcu32; 84 | } 85 | #elif defined(USE_EXTERNAL_MZCRC) 86 | /* If USE_EXTERNAL_CRC is defined, an external module will export the 87 | * mz_crc32() symbol for us to use, e.g. an SSE-accelerated version. 88 | * Depending on the impl, it may be necessary to ~ the input/output crc values. 89 | */ 90 | mz_ulong mz_crc32(mz_ulong crc, const mz_uint8 *ptr, size_t buf_len); 91 | #else 92 | /* Faster, but larger CPU cache footprint. 93 | */ 94 | mz_ulong mz_crc32(mz_ulong crc, const mz_uint8 *ptr, size_t buf_len) 95 | { 96 | static const mz_uint32 s_crc_table[256] = 97 | { 98 | 0x00000000, 0x77073096, 0xEE0E612C, 0x990951BA, 0x076DC419, 0x706AF48F, 0xE963A535, 99 | 0x9E6495A3, 0x0EDB8832, 0x79DCB8A4, 0xE0D5E91E, 0x97D2D988, 0x09B64C2B, 0x7EB17CBD, 100 | 0xE7B82D07, 0x90BF1D91, 0x1DB71064, 0x6AB020F2, 0xF3B97148, 0x84BE41DE, 0x1ADAD47D, 101 | 0x6DDDE4EB, 0xF4D4B551, 0x83D385C7, 0x136C9856, 0x646BA8C0, 0xFD62F97A, 0x8A65C9EC, 102 | 0x14015C4F, 0x63066CD9, 0xFA0F3D63, 0x8D080DF5, 0x3B6E20C8, 0x4C69105E, 0xD56041E4, 103 | 0xA2677172, 0x3C03E4D1, 0x4B04D447, 0xD20D85FD, 0xA50AB56B, 0x35B5A8FA, 0x42B2986C, 104 | 0xDBBBC9D6, 0xACBCF940, 0x32D86CE3, 0x45DF5C75, 0xDCD60DCF, 0xABD13D59, 0x26D930AC, 105 | 0x51DE003A, 0xC8D75180, 0xBFD06116, 0x21B4F4B5, 0x56B3C423, 0xCFBA9599, 0xB8BDA50F, 106 | 0x2802B89E, 0x5F058808, 0xC60CD9B2, 0xB10BE924, 0x2F6F7C87, 0x58684C11, 0xC1611DAB, 107 | 0xB6662D3D, 0x76DC4190, 0x01DB7106, 0x98D220BC, 0xEFD5102A, 0x71B18589, 0x06B6B51F, 108 | 0x9FBFE4A5, 0xE8B8D433, 0x7807C9A2, 0x0F00F934, 0x9609A88E, 0xE10E9818, 0x7F6A0DBB, 109 | 0x086D3D2D, 0x91646C97, 0xE6635C01, 0x6B6B51F4, 0x1C6C6162, 0x856530D8, 0xF262004E, 110 | 0x6C0695ED, 0x1B01A57B, 0x8208F4C1, 0xF50FC457, 0x65B0D9C6, 0x12B7E950, 0x8BBEB8EA, 111 | 0xFCB9887C, 0x62DD1DDF, 0x15DA2D49, 0x8CD37CF3, 0xFBD44C65, 0x4DB26158, 0x3AB551CE, 112 | 0xA3BC0074, 0xD4BB30E2, 0x4ADFA541, 0x3DD895D7, 0xA4D1C46D, 0xD3D6F4FB, 0x4369E96A, 113 | 0x346ED9FC, 0xAD678846, 0xDA60B8D0, 0x44042D73, 0x33031DE5, 0xAA0A4C5F, 0xDD0D7CC9, 114 | 0x5005713C, 0x270241AA, 0xBE0B1010, 0xC90C2086, 0x5768B525, 0x206F85B3, 0xB966D409, 115 | 0xCE61E49F, 0x5EDEF90E, 0x29D9C998, 0xB0D09822, 0xC7D7A8B4, 0x59B33D17, 0x2EB40D81, 116 | 0xB7BD5C3B, 0xC0BA6CAD, 0xEDB88320, 0x9ABFB3B6, 0x03B6E20C, 0x74B1D29A, 0xEAD54739, 117 | 0x9DD277AF, 0x04DB2615, 0x73DC1683, 0xE3630B12, 0x94643B84, 0x0D6D6A3E, 0x7A6A5AA8, 118 | 0xE40ECF0B, 0x9309FF9D, 0x0A00AE27, 0x7D079EB1, 0xF00F9344, 0x8708A3D2, 0x1E01F268, 119 | 0x6906C2FE, 0xF762575D, 0x806567CB, 0x196C3671, 0x6E6B06E7, 0xFED41B76, 0x89D32BE0, 120 | 0x10DA7A5A, 0x67DD4ACC, 0xF9B9DF6F, 0x8EBEEFF9, 0x17B7BE43, 0x60B08ED5, 0xD6D6A3E8, 121 | 0xA1D1937E, 0x38D8C2C4, 0x4FDFF252, 0xD1BB67F1, 0xA6BC5767, 0x3FB506DD, 0x48B2364B, 122 | 0xD80D2BDA, 0xAF0A1B4C, 0x36034AF6, 0x41047A60, 0xDF60EFC3, 0xA867DF55, 0x316E8EEF, 123 | 0x4669BE79, 0xCB61B38C, 0xBC66831A, 0x256FD2A0, 0x5268E236, 0xCC0C7795, 0xBB0B4703, 124 | 0x220216B9, 0x5505262F, 0xC5BA3BBE, 0xB2BD0B28, 0x2BB45A92, 0x5CB36A04, 0xC2D7FFA7, 125 | 0xB5D0CF31, 0x2CD99E8B, 0x5BDEAE1D, 0x9B64C2B0, 0xEC63F226, 0x756AA39C, 0x026D930A, 126 | 0x9C0906A9, 0xEB0E363F, 0x72076785, 0x05005713, 0x95BF4A82, 0xE2B87A14, 0x7BB12BAE, 127 | 0x0CB61B38, 0x92D28E9B, 0xE5D5BE0D, 0x7CDCEFB7, 0x0BDBDF21, 0x86D3D2D4, 0xF1D4E242, 128 | 0x68DDB3F8, 0x1FDA836E, 0x81BE16CD, 0xF6B9265B, 0x6FB077E1, 0x18B74777, 0x88085AE6, 129 | 0xFF0F6A70, 0x66063BCA, 0x11010B5C, 0x8F659EFF, 0xF862AE69, 0x616BFFD3, 0x166CCF45, 130 | 0xA00AE278, 0xD70DD2EE, 0x4E048354, 0x3903B3C2, 0xA7672661, 0xD06016F7, 0x4969474D, 131 | 0x3E6E77DB, 0xAED16A4A, 0xD9D65ADC, 0x40DF0B66, 0x37D83BF0, 0xA9BCAE53, 0xDEBB9EC5, 132 | 0x47B2CF7F, 0x30B5FFE9, 0xBDBDF21C, 0xCABAC28A, 0x53B39330, 0x24B4A3A6, 0xBAD03605, 133 | 0xCDD70693, 0x54DE5729, 0x23D967BF, 0xB3667A2E, 0xC4614AB8, 0x5D681B02, 0x2A6F2B94, 134 | 0xB40BBE37, 0xC30C8EA1, 0x5A05DF1B, 0x2D02EF8D 135 | }; 136 | 137 | mz_uint32 crc32 = (mz_uint32)crc ^ 0xFFFFFFFF; 138 | const mz_uint8 *pByte_buf = (const mz_uint8 *)ptr; 139 | 140 | while (buf_len >= 4) 141 | { 142 | crc32 = (crc32 >> 8) ^ s_crc_table[(crc32 ^ pByte_buf[0]) & 0xFF]; 143 | crc32 = (crc32 >> 8) ^ s_crc_table[(crc32 ^ pByte_buf[1]) & 0xFF]; 144 | crc32 = (crc32 >> 8) ^ s_crc_table[(crc32 ^ pByte_buf[2]) & 0xFF]; 145 | crc32 = (crc32 >> 8) ^ s_crc_table[(crc32 ^ pByte_buf[3]) & 0xFF]; 146 | pByte_buf += 4; 147 | buf_len -= 4; 148 | } 149 | 150 | while (buf_len) 151 | { 152 | crc32 = (crc32 >> 8) ^ s_crc_table[(crc32 ^ pByte_buf[0]) & 0xFF]; 153 | ++pByte_buf; 154 | --buf_len; 155 | } 156 | 157 | return ~crc32; 158 | } 159 | #endif 160 | 161 | void mz_free(void *p) 162 | { 163 | MZ_FREE(p); 164 | } 165 | 166 | MINIZ_EXPORT void *miniz_def_alloc_func(void *opaque, size_t items, size_t size) 167 | { 168 | (void)opaque, (void)items, (void)size; 169 | return MZ_MALLOC(items * size); 170 | } 171 | MINIZ_EXPORT void miniz_def_free_func(void *opaque, void *address) 172 | { 173 | (void)opaque, (void)address; 174 | MZ_FREE(address); 175 | } 176 | MINIZ_EXPORT void *miniz_def_realloc_func(void *opaque, void *address, size_t items, size_t size) 177 | { 178 | (void)opaque, (void)address, (void)items, (void)size; 179 | return MZ_REALLOC(address, items * size); 180 | } 181 | 182 | const char *mz_version(void) 183 | { 184 | return MZ_VERSION; 185 | } 186 | 187 | #ifndef MINIZ_NO_ZLIB_APIS 188 | 189 | #ifndef MINIZ_NO_DEFLATE_APIS 190 | 191 | int mz_deflateInit(mz_streamp pStream, int level) 192 | { 193 | return mz_deflateInit2(pStream, level, MZ_DEFLATED, MZ_DEFAULT_WINDOW_BITS, 9, MZ_DEFAULT_STRATEGY); 194 | } 195 | 196 | int mz_deflateInit2(mz_streamp pStream, int level, int method, int window_bits, int mem_level, int strategy) 197 | { 198 | tdefl_compressor *pComp; 199 | mz_uint comp_flags = TDEFL_COMPUTE_ADLER32 | tdefl_create_comp_flags_from_zip_params(level, window_bits, strategy); 200 | 201 | if (!pStream) 202 | return MZ_STREAM_ERROR; 203 | if ((method != MZ_DEFLATED) || ((mem_level < 1) || (mem_level > 9)) || ((window_bits != MZ_DEFAULT_WINDOW_BITS) && (-window_bits != MZ_DEFAULT_WINDOW_BITS))) 204 | return MZ_PARAM_ERROR; 205 | 206 | pStream->data_type = 0; 207 | pStream->adler = MZ_ADLER32_INIT; 208 | pStream->msg = NULL; 209 | pStream->reserved = 0; 210 | pStream->total_in = 0; 211 | pStream->total_out = 0; 212 | if (!pStream->zalloc) 213 | pStream->zalloc = miniz_def_alloc_func; 214 | if (!pStream->zfree) 215 | pStream->zfree = miniz_def_free_func; 216 | 217 | pComp = (tdefl_compressor *)pStream->zalloc(pStream->opaque, 1, sizeof(tdefl_compressor)); 218 | if (!pComp) 219 | return MZ_MEM_ERROR; 220 | 221 | pStream->state = (struct mz_internal_state *)pComp; 222 | 223 | if (tdefl_init(pComp, NULL, NULL, comp_flags) != TDEFL_STATUS_OKAY) 224 | { 225 | mz_deflateEnd(pStream); 226 | return MZ_PARAM_ERROR; 227 | } 228 | 229 | return MZ_OK; 230 | } 231 | 232 | int mz_deflateReset(mz_streamp pStream) 233 | { 234 | if ((!pStream) || (!pStream->state) || (!pStream->zalloc) || (!pStream->zfree)) 235 | return MZ_STREAM_ERROR; 236 | pStream->total_in = pStream->total_out = 0; 237 | tdefl_init((tdefl_compressor *)pStream->state, NULL, NULL, ((tdefl_compressor *)pStream->state)->m_flags); 238 | return MZ_OK; 239 | } 240 | 241 | int mz_deflate(mz_streamp pStream, int flush) 242 | { 243 | size_t in_bytes, out_bytes; 244 | mz_ulong orig_total_in, orig_total_out; 245 | int mz_status = MZ_OK; 246 | 247 | if ((!pStream) || (!pStream->state) || (flush < 0) || (flush > MZ_FINISH) || (!pStream->next_out)) 248 | return MZ_STREAM_ERROR; 249 | if (!pStream->avail_out) 250 | return MZ_BUF_ERROR; 251 | 252 | if (flush == MZ_PARTIAL_FLUSH) 253 | flush = MZ_SYNC_FLUSH; 254 | 255 | if (((tdefl_compressor *)pStream->state)->m_prev_return_status == TDEFL_STATUS_DONE) 256 | return (flush == MZ_FINISH) ? MZ_STREAM_END : MZ_BUF_ERROR; 257 | 258 | orig_total_in = pStream->total_in; 259 | orig_total_out = pStream->total_out; 260 | for (;;) 261 | { 262 | tdefl_status defl_status; 263 | in_bytes = pStream->avail_in; 264 | out_bytes = pStream->avail_out; 265 | 266 | defl_status = tdefl_compress((tdefl_compressor *)pStream->state, pStream->next_in, &in_bytes, pStream->next_out, &out_bytes, (tdefl_flush)flush); 267 | pStream->next_in += (mz_uint)in_bytes; 268 | pStream->avail_in -= (mz_uint)in_bytes; 269 | pStream->total_in += (mz_uint)in_bytes; 270 | pStream->adler = tdefl_get_adler32((tdefl_compressor *)pStream->state); 271 | 272 | pStream->next_out += (mz_uint)out_bytes; 273 | pStream->avail_out -= (mz_uint)out_bytes; 274 | pStream->total_out += (mz_uint)out_bytes; 275 | 276 | if (defl_status < 0) 277 | { 278 | mz_status = MZ_STREAM_ERROR; 279 | break; 280 | } 281 | else if (defl_status == TDEFL_STATUS_DONE) 282 | { 283 | mz_status = MZ_STREAM_END; 284 | break; 285 | } 286 | else if (!pStream->avail_out) 287 | break; 288 | else if ((!pStream->avail_in) && (flush != MZ_FINISH)) 289 | { 290 | if ((flush) || (pStream->total_in != orig_total_in) || (pStream->total_out != orig_total_out)) 291 | break; 292 | return MZ_BUF_ERROR; /* Can't make forward progress without some input. 293 | */ 294 | } 295 | } 296 | return mz_status; 297 | } 298 | 299 | int mz_deflateEnd(mz_streamp pStream) 300 | { 301 | if (!pStream) 302 | return MZ_STREAM_ERROR; 303 | if (pStream->state) 304 | { 305 | pStream->zfree(pStream->opaque, pStream->state); 306 | pStream->state = NULL; 307 | } 308 | return MZ_OK; 309 | } 310 | 311 | mz_ulong mz_deflateBound(mz_streamp pStream, mz_ulong source_len) 312 | { 313 | (void)pStream; 314 | /* This is really over conservative. (And lame, but it's actually pretty tricky to compute a true upper bound given the way tdefl's blocking works.) */ 315 | return MZ_MAX(128 + (source_len * 110) / 100, 128 + source_len + ((source_len / (31 * 1024)) + 1) * 5); 316 | } 317 | 318 | int mz_compress2(unsigned char *pDest, mz_ulong *pDest_len, const unsigned char *pSource, mz_ulong source_len, int level) 319 | { 320 | int status; 321 | mz_stream stream; 322 | memset(&stream, 0, sizeof(stream)); 323 | 324 | /* In case mz_ulong is 64-bits (argh I hate longs). */ 325 | if ((mz_uint64)(source_len | *pDest_len) > 0xFFFFFFFFU) 326 | return MZ_PARAM_ERROR; 327 | 328 | stream.next_in = pSource; 329 | stream.avail_in = (mz_uint32)source_len; 330 | stream.next_out = pDest; 331 | stream.avail_out = (mz_uint32)*pDest_len; 332 | 333 | status = mz_deflateInit(&stream, level); 334 | if (status != MZ_OK) 335 | return status; 336 | 337 | status = mz_deflate(&stream, MZ_FINISH); 338 | if (status != MZ_STREAM_END) 339 | { 340 | mz_deflateEnd(&stream); 341 | return (status == MZ_OK) ? MZ_BUF_ERROR : status; 342 | } 343 | 344 | *pDest_len = stream.total_out; 345 | return mz_deflateEnd(&stream); 346 | } 347 | 348 | int mz_compress(unsigned char *pDest, mz_ulong *pDest_len, const unsigned char *pSource, mz_ulong source_len) 349 | { 350 | return mz_compress2(pDest, pDest_len, pSource, source_len, MZ_DEFAULT_COMPRESSION); 351 | } 352 | 353 | mz_ulong mz_compressBound(mz_ulong source_len) 354 | { 355 | return mz_deflateBound(NULL, source_len); 356 | } 357 | 358 | #endif /*#ifndef MINIZ_NO_DEFLATE_APIS*/ 359 | 360 | #ifndef MINIZ_NO_INFLATE_APIS 361 | 362 | typedef struct 363 | { 364 | tinfl_decompressor m_decomp; 365 | mz_uint m_dict_ofs, m_dict_avail, m_first_call, m_has_flushed; 366 | int m_window_bits; 367 | mz_uint8 m_dict[TINFL_LZ_DICT_SIZE]; 368 | tinfl_status m_last_status; 369 | } inflate_state; 370 | 371 | int mz_inflateInit2(mz_streamp pStream, int window_bits) 372 | { 373 | inflate_state *pDecomp; 374 | if (!pStream) 375 | return MZ_STREAM_ERROR; 376 | if ((window_bits != MZ_DEFAULT_WINDOW_BITS) && (-window_bits != MZ_DEFAULT_WINDOW_BITS)) 377 | return MZ_PARAM_ERROR; 378 | 379 | pStream->data_type = 0; 380 | pStream->adler = 0; 381 | pStream->msg = NULL; 382 | pStream->total_in = 0; 383 | pStream->total_out = 0; 384 | pStream->reserved = 0; 385 | if (!pStream->zalloc) 386 | pStream->zalloc = miniz_def_alloc_func; 387 | if (!pStream->zfree) 388 | pStream->zfree = miniz_def_free_func; 389 | 390 | pDecomp = (inflate_state *)pStream->zalloc(pStream->opaque, 1, sizeof(inflate_state)); 391 | if (!pDecomp) 392 | return MZ_MEM_ERROR; 393 | 394 | pStream->state = (struct mz_internal_state *)pDecomp; 395 | 396 | tinfl_init(&pDecomp->m_decomp); 397 | pDecomp->m_dict_ofs = 0; 398 | pDecomp->m_dict_avail = 0; 399 | pDecomp->m_last_status = TINFL_STATUS_NEEDS_MORE_INPUT; 400 | pDecomp->m_first_call = 1; 401 | pDecomp->m_has_flushed = 0; 402 | pDecomp->m_window_bits = window_bits; 403 | 404 | return MZ_OK; 405 | } 406 | 407 | int mz_inflateInit(mz_streamp pStream) 408 | { 409 | return mz_inflateInit2(pStream, MZ_DEFAULT_WINDOW_BITS); 410 | } 411 | 412 | int mz_inflateReset(mz_streamp pStream) 413 | { 414 | inflate_state *pDecomp; 415 | if (!pStream) 416 | return MZ_STREAM_ERROR; 417 | 418 | pStream->data_type = 0; 419 | pStream->adler = 0; 420 | pStream->msg = NULL; 421 | pStream->total_in = 0; 422 | pStream->total_out = 0; 423 | pStream->reserved = 0; 424 | 425 | pDecomp = (inflate_state *)pStream->state; 426 | 427 | tinfl_init(&pDecomp->m_decomp); 428 | pDecomp->m_dict_ofs = 0; 429 | pDecomp->m_dict_avail = 0; 430 | pDecomp->m_last_status = TINFL_STATUS_NEEDS_MORE_INPUT; 431 | pDecomp->m_first_call = 1; 432 | pDecomp->m_has_flushed = 0; 433 | /* pDecomp->m_window_bits = window_bits */; 434 | 435 | return MZ_OK; 436 | } 437 | 438 | int mz_inflate(mz_streamp pStream, int flush) 439 | { 440 | inflate_state *pState; 441 | mz_uint n, first_call, decomp_flags = TINFL_FLAG_COMPUTE_ADLER32; 442 | size_t in_bytes, out_bytes, orig_avail_in; 443 | tinfl_status status; 444 | 445 | if ((!pStream) || (!pStream->state)) 446 | return MZ_STREAM_ERROR; 447 | if (flush == MZ_PARTIAL_FLUSH) 448 | flush = MZ_SYNC_FLUSH; 449 | if ((flush) && (flush != MZ_SYNC_FLUSH) && (flush != MZ_FINISH)) 450 | return MZ_STREAM_ERROR; 451 | 452 | pState = (inflate_state *)pStream->state; 453 | if (pState->m_window_bits > 0) 454 | decomp_flags |= TINFL_FLAG_PARSE_ZLIB_HEADER; 455 | orig_avail_in = pStream->avail_in; 456 | 457 | first_call = pState->m_first_call; 458 | pState->m_first_call = 0; 459 | if (pState->m_last_status < 0) 460 | return MZ_DATA_ERROR; 461 | 462 | if (pState->m_has_flushed && (flush != MZ_FINISH)) 463 | return MZ_STREAM_ERROR; 464 | pState->m_has_flushed |= (flush == MZ_FINISH); 465 | 466 | if ((flush == MZ_FINISH) && (first_call)) 467 | { 468 | /* MZ_FINISH on the first call implies that the input and output buffers are large enough to hold the entire compressed/decompressed file. */ 469 | decomp_flags |= TINFL_FLAG_USING_NON_WRAPPING_OUTPUT_BUF; 470 | in_bytes = pStream->avail_in; 471 | out_bytes = pStream->avail_out; 472 | status = tinfl_decompress(&pState->m_decomp, pStream->next_in, &in_bytes, pStream->next_out, pStream->next_out, &out_bytes, decomp_flags); 473 | pState->m_last_status = status; 474 | pStream->next_in += (mz_uint)in_bytes; 475 | pStream->avail_in -= (mz_uint)in_bytes; 476 | pStream->total_in += (mz_uint)in_bytes; 477 | pStream->adler = tinfl_get_adler32(&pState->m_decomp); 478 | pStream->next_out += (mz_uint)out_bytes; 479 | pStream->avail_out -= (mz_uint)out_bytes; 480 | pStream->total_out += (mz_uint)out_bytes; 481 | 482 | if (status < 0) 483 | return MZ_DATA_ERROR; 484 | else if (status != TINFL_STATUS_DONE) 485 | { 486 | pState->m_last_status = TINFL_STATUS_FAILED; 487 | return MZ_BUF_ERROR; 488 | } 489 | return MZ_STREAM_END; 490 | } 491 | /* flush != MZ_FINISH then we must assume there's more input. */ 492 | if (flush != MZ_FINISH) 493 | decomp_flags |= TINFL_FLAG_HAS_MORE_INPUT; 494 | 495 | if (pState->m_dict_avail) 496 | { 497 | n = MZ_MIN(pState->m_dict_avail, pStream->avail_out); 498 | memcpy(pStream->next_out, pState->m_dict + pState->m_dict_ofs, n); 499 | pStream->next_out += n; 500 | pStream->avail_out -= n; 501 | pStream->total_out += n; 502 | pState->m_dict_avail -= n; 503 | pState->m_dict_ofs = (pState->m_dict_ofs + n) & (TINFL_LZ_DICT_SIZE - 1); 504 | return ((pState->m_last_status == TINFL_STATUS_DONE) && (!pState->m_dict_avail)) ? MZ_STREAM_END : MZ_OK; 505 | } 506 | 507 | for (;;) 508 | { 509 | in_bytes = pStream->avail_in; 510 | out_bytes = TINFL_LZ_DICT_SIZE - pState->m_dict_ofs; 511 | 512 | status = tinfl_decompress(&pState->m_decomp, pStream->next_in, &in_bytes, pState->m_dict, pState->m_dict + pState->m_dict_ofs, &out_bytes, decomp_flags); 513 | pState->m_last_status = status; 514 | 515 | pStream->next_in += (mz_uint)in_bytes; 516 | pStream->avail_in -= (mz_uint)in_bytes; 517 | pStream->total_in += (mz_uint)in_bytes; 518 | pStream->adler = tinfl_get_adler32(&pState->m_decomp); 519 | 520 | pState->m_dict_avail = (mz_uint)out_bytes; 521 | 522 | n = MZ_MIN(pState->m_dict_avail, pStream->avail_out); 523 | memcpy(pStream->next_out, pState->m_dict + pState->m_dict_ofs, n); 524 | pStream->next_out += n; 525 | pStream->avail_out -= n; 526 | pStream->total_out += n; 527 | pState->m_dict_avail -= n; 528 | pState->m_dict_ofs = (pState->m_dict_ofs + n) & (TINFL_LZ_DICT_SIZE - 1); 529 | 530 | if (status < 0) 531 | return MZ_DATA_ERROR; /* Stream is corrupted (there could be some uncompressed data left in the output dictionary - oh well). */ 532 | else if ((status == TINFL_STATUS_NEEDS_MORE_INPUT) && (!orig_avail_in)) 533 | return MZ_BUF_ERROR; /* Signal caller that we can't make forward progress without supplying more input or by setting flush to MZ_FINISH. */ 534 | else if (flush == MZ_FINISH) 535 | { 536 | /* The output buffer MUST be large to hold the remaining uncompressed data when flush==MZ_FINISH. */ 537 | if (status == TINFL_STATUS_DONE) 538 | return pState->m_dict_avail ? MZ_BUF_ERROR : MZ_STREAM_END; 539 | /* status here must be TINFL_STATUS_HAS_MORE_OUTPUT, which means there's at least 1 more byte on the way. If there's no more room left in the output buffer then something is wrong. */ 540 | else if (!pStream->avail_out) 541 | return MZ_BUF_ERROR; 542 | } 543 | else if ((status == TINFL_STATUS_DONE) || (!pStream->avail_in) || (!pStream->avail_out) || (pState->m_dict_avail)) 544 | break; 545 | } 546 | 547 | return ((status == TINFL_STATUS_DONE) && (!pState->m_dict_avail)) ? MZ_STREAM_END : MZ_OK; 548 | } 549 | 550 | int mz_inflateEnd(mz_streamp pStream) 551 | { 552 | if (!pStream) 553 | return MZ_STREAM_ERROR; 554 | if (pStream->state) 555 | { 556 | pStream->zfree(pStream->opaque, pStream->state); 557 | pStream->state = NULL; 558 | } 559 | return MZ_OK; 560 | } 561 | int mz_uncompress2(unsigned char *pDest, mz_ulong *pDest_len, const unsigned char *pSource, mz_ulong *pSource_len) 562 | { 563 | mz_stream stream; 564 | int status; 565 | memset(&stream, 0, sizeof(stream)); 566 | 567 | /* In case mz_ulong is 64-bits (argh I hate longs). */ 568 | if ((mz_uint64)(*pSource_len | *pDest_len) > 0xFFFFFFFFU) 569 | return MZ_PARAM_ERROR; 570 | 571 | stream.next_in = pSource; 572 | stream.avail_in = (mz_uint32)*pSource_len; 573 | stream.next_out = pDest; 574 | stream.avail_out = (mz_uint32)*pDest_len; 575 | 576 | status = mz_inflateInit(&stream); 577 | if (status != MZ_OK) 578 | return status; 579 | 580 | status = mz_inflate(&stream, MZ_FINISH); 581 | *pSource_len = *pSource_len - stream.avail_in; 582 | if (status != MZ_STREAM_END) 583 | { 584 | mz_inflateEnd(&stream); 585 | return ((status == MZ_BUF_ERROR) && (!stream.avail_in)) ? MZ_DATA_ERROR : status; 586 | } 587 | *pDest_len = stream.total_out; 588 | 589 | return mz_inflateEnd(&stream); 590 | } 591 | 592 | int mz_uncompress(unsigned char *pDest, mz_ulong *pDest_len, const unsigned char *pSource, mz_ulong source_len) 593 | { 594 | return mz_uncompress2(pDest, pDest_len, pSource, &source_len); 595 | } 596 | 597 | #endif /*#ifndef MINIZ_NO_INFLATE_APIS*/ 598 | 599 | const char *mz_error(int err) 600 | { 601 | static struct 602 | { 603 | int m_err; 604 | const char *m_pDesc; 605 | } s_error_descs[] = 606 | { 607 | { MZ_OK, "" }, { MZ_STREAM_END, "stream end" }, { MZ_NEED_DICT, "need dictionary" }, { MZ_ERRNO, "file error" }, { MZ_STREAM_ERROR, "stream error" }, { MZ_DATA_ERROR, "data error" }, { MZ_MEM_ERROR, "out of memory" }, { MZ_BUF_ERROR, "buf error" }, { MZ_VERSION_ERROR, "version error" }, { MZ_PARAM_ERROR, "parameter error" } 608 | }; 609 | mz_uint i; 610 | for (i = 0; i < sizeof(s_error_descs) / sizeof(s_error_descs[0]); ++i) 611 | if (s_error_descs[i].m_err == err) 612 | return s_error_descs[i].m_pDesc; 613 | return NULL; 614 | } 615 | 616 | #endif /*MINIZ_NO_ZLIB_APIS */ 617 | 618 | #ifdef __cplusplus 619 | } 620 | #endif 621 | 622 | /* 623 | This is free and unencumbered software released into the public domain. 624 | 625 | Anyone is free to copy, modify, publish, use, compile, sell, or 626 | distribute this software, either in source code form or as a compiled 627 | binary, for any purpose, commercial or non-commercial, and by any 628 | means. 629 | 630 | In jurisdictions that recognize copyright laws, the author or authors 631 | of this software dedicate any and all copyright interest in the 632 | software to the public domain. We make this dedication for the benefit 633 | of the public at large and to the detriment of our heirs and 634 | successors. We intend this dedication to be an overt act of 635 | relinquishment in perpetuity of all present and future rights to this 636 | software under copyright law. 637 | 638 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, 639 | EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF 640 | MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. 641 | IN NO EVENT SHALL THE AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR 642 | OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, 643 | ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR 644 | OTHER DEALINGS IN THE SOFTWARE. 645 | 646 | For more information, please refer to 647 | */ 648 | -------------------------------------------------------------------------------- /miniz.h: -------------------------------------------------------------------------------- 1 | /* miniz.c 3.0.2 - public domain deflate/inflate, zlib-subset, ZIP reading/writing/appending, PNG writing 2 | See "unlicense" statement at the end of this file. 3 | Rich Geldreich , last updated Oct. 13, 2013 4 | Implements RFC 1950: http://www.ietf.org/rfc/rfc1950.txt and RFC 1951: http://www.ietf.org/rfc/rfc1951.txt 5 | 6 | Most API's defined in miniz.c are optional. For example, to disable the archive related functions just define 7 | MINIZ_NO_ARCHIVE_APIS, or to get rid of all stdio usage define MINIZ_NO_STDIO (see the list below for more macros). 8 | 9 | * Low-level Deflate/Inflate implementation notes: 10 | 11 | Compression: Use the "tdefl" API's. The compressor supports raw, static, and dynamic blocks, lazy or 12 | greedy parsing, match length filtering, RLE-only, and Huffman-only streams. It performs and compresses 13 | approximately as well as zlib. 14 | 15 | Decompression: Use the "tinfl" API's. The entire decompressor is implemented as a single function 16 | coroutine: see tinfl_decompress(). It supports decompression into a 32KB (or larger power of 2) wrapping buffer, or into a memory 17 | block large enough to hold the entire file. 18 | 19 | The low-level tdefl/tinfl API's do not make any use of dynamic memory allocation. 20 | 21 | * zlib-style API notes: 22 | 23 | miniz.c implements a fairly large subset of zlib. There's enough functionality present for it to be a drop-in 24 | zlib replacement in many apps: 25 | The z_stream struct, optional memory allocation callbacks 26 | deflateInit/deflateInit2/deflate/deflateReset/deflateEnd/deflateBound 27 | inflateInit/inflateInit2/inflate/inflateReset/inflateEnd 28 | compress, compress2, compressBound, uncompress 29 | CRC-32, Adler-32 - Using modern, minimal code size, CPU cache friendly routines. 30 | Supports raw deflate streams or standard zlib streams with adler-32 checking. 31 | 32 | Limitations: 33 | The callback API's are not implemented yet. No support for gzip headers or zlib static dictionaries. 34 | I've tried to closely emulate zlib's various flavors of stream flushing and return status codes, but 35 | there are no guarantees that miniz.c pulls this off perfectly. 36 | 37 | * PNG writing: See the tdefl_write_image_to_png_file_in_memory() function, originally written by 38 | Alex Evans. Supports 1-4 bytes/pixel images. 39 | 40 | * ZIP archive API notes: 41 | 42 | The ZIP archive API's where designed with simplicity and efficiency in mind, with just enough abstraction to 43 | get the job done with minimal fuss. There are simple API's to retrieve file information, read files from 44 | existing archives, create new archives, append new files to existing archives, or clone archive data from 45 | one archive to another. It supports archives located in memory or the heap, on disk (using stdio.h), 46 | or you can specify custom file read/write callbacks. 47 | 48 | - Archive reading: Just call this function to read a single file from a disk archive: 49 | 50 | void *mz_zip_extract_archive_file_to_heap(const char *pZip_filename, const char *pArchive_name, 51 | size_t *pSize, mz_uint zip_flags); 52 | 53 | For more complex cases, use the "mz_zip_reader" functions. Upon opening an archive, the entire central 54 | directory is located and read as-is into memory, and subsequent file access only occurs when reading individual files. 55 | 56 | - Archives file scanning: The simple way is to use this function to scan a loaded archive for a specific file: 57 | 58 | int mz_zip_reader_locate_file(mz_zip_archive *pZip, const char *pName, const char *pComment, mz_uint flags); 59 | 60 | The locate operation can optionally check file comments too, which (as one example) can be used to identify 61 | multiple versions of the same file in an archive. This function uses a simple linear search through the central 62 | directory, so it's not very fast. 63 | 64 | Alternately, you can iterate through all the files in an archive (using mz_zip_reader_get_num_files()) and 65 | retrieve detailed info on each file by calling mz_zip_reader_file_stat(). 66 | 67 | - Archive creation: Use the "mz_zip_writer" functions. The ZIP writer immediately writes compressed file data 68 | to disk and builds an exact image of the central directory in memory. The central directory image is written 69 | all at once at the end of the archive file when the archive is finalized. 70 | 71 | The archive writer can optionally align each file's local header and file data to any power of 2 alignment, 72 | which can be useful when the archive will be read from optical media. Also, the writer supports placing 73 | arbitrary data blobs at the very beginning of ZIP archives. Archives written using either feature are still 74 | readable by any ZIP tool. 75 | 76 | - Archive appending: The simple way to add a single file to an archive is to call this function: 77 | 78 | mz_bool mz_zip_add_mem_to_archive_file_in_place(const char *pZip_filename, const char *pArchive_name, 79 | const void *pBuf, size_t buf_size, const void *pComment, mz_uint16 comment_size, mz_uint level_and_flags); 80 | 81 | The archive will be created if it doesn't already exist, otherwise it'll be appended to. 82 | Note the appending is done in-place and is not an atomic operation, so if something goes wrong 83 | during the operation it's possible the archive could be left without a central directory (although the local 84 | file headers and file data will be fine, so the archive will be recoverable). 85 | 86 | For more complex archive modification scenarios: 87 | 1. The safest way is to use a mz_zip_reader to read the existing archive, cloning only those bits you want to 88 | preserve into a new archive using using the mz_zip_writer_add_from_zip_reader() function (which compiles the 89 | compressed file data as-is). When you're done, delete the old archive and rename the newly written archive, and 90 | you're done. This is safe but requires a bunch of temporary disk space or heap memory. 91 | 92 | 2. Or, you can convert an mz_zip_reader in-place to an mz_zip_writer using mz_zip_writer_init_from_reader(), 93 | append new files as needed, then finalize the archive which will write an updated central directory to the 94 | original archive. (This is basically what mz_zip_add_mem_to_archive_file_in_place() does.) There's a 95 | possibility that the archive's central directory could be lost with this method if anything goes wrong, though. 96 | 97 | - ZIP archive support limitations: 98 | No spanning support. Extraction functions can only handle unencrypted, stored or deflated files. 99 | Requires streams capable of seeking. 100 | 101 | * This is a header file library, like stb_image.c. To get only a header file, either cut and paste the 102 | below header, or create miniz.h, #define MINIZ_HEADER_FILE_ONLY, and then include miniz.c from it. 103 | 104 | * Important: For best perf. be sure to customize the below macros for your target platform: 105 | #define MINIZ_USE_UNALIGNED_LOADS_AND_STORES 1 106 | #define MINIZ_LITTLE_ENDIAN 1 107 | #define MINIZ_HAS_64BIT_REGISTERS 1 108 | 109 | * On platforms using glibc, Be sure to "#define _LARGEFILE64_SOURCE 1" before including miniz.c to ensure miniz 110 | uses the 64-bit variants: fopen64(), stat64(), etc. Otherwise you won't be able to process large files 111 | (i.e. 32-bit stat() fails for me on files > 0x7FFFFFFF bytes). 112 | */ 113 | #pragma once 114 | 115 | #include "miniz_export.h" 116 | 117 | /* Defines to completely disable specific portions of miniz.c: 118 | If all macros here are defined the only functionality remaining will be CRC-32 and adler-32. */ 119 | 120 | /* Define MINIZ_NO_STDIO to disable all usage and any functions which rely on stdio for file I/O. */ 121 | /*#define MINIZ_NO_STDIO */ 122 | 123 | /* If MINIZ_NO_TIME is specified then the ZIP archive functions will not be able to get the current time, or */ 124 | /* get/set file times, and the C run-time funcs that get/set times won't be called. */ 125 | /* The current downside is the times written to your archives will be from 1979. */ 126 | /*#define MINIZ_NO_TIME */ 127 | 128 | /* Define MINIZ_NO_DEFLATE_APIS to disable all compression API's. */ 129 | /*#define MINIZ_NO_DEFLATE_APIS */ 130 | 131 | /* Define MINIZ_NO_INFLATE_APIS to disable all decompression API's. */ 132 | /*#define MINIZ_NO_INFLATE_APIS */ 133 | 134 | /* Define MINIZ_NO_ARCHIVE_APIS to disable all ZIP archive API's. */ 135 | /*#define MINIZ_NO_ARCHIVE_APIS */ 136 | 137 | /* Define MINIZ_NO_ARCHIVE_WRITING_APIS to disable all writing related ZIP archive API's. */ 138 | /*#define MINIZ_NO_ARCHIVE_WRITING_APIS */ 139 | 140 | /* Define MINIZ_NO_ZLIB_APIS to remove all ZLIB-style compression/decompression API's. */ 141 | /*#define MINIZ_NO_ZLIB_APIS */ 142 | 143 | /* Define MINIZ_NO_ZLIB_COMPATIBLE_NAME to disable zlib names, to prevent conflicts against stock zlib. */ 144 | /*#define MINIZ_NO_ZLIB_COMPATIBLE_NAMES */ 145 | 146 | /* Define MINIZ_NO_MALLOC to disable all calls to malloc, free, and realloc. 147 | Note if MINIZ_NO_MALLOC is defined then the user must always provide custom user alloc/free/realloc 148 | callbacks to the zlib and archive API's, and a few stand-alone helper API's which don't provide custom user 149 | functions (such as tdefl_compress_mem_to_heap() and tinfl_decompress_mem_to_heap()) won't work. */ 150 | /*#define MINIZ_NO_MALLOC */ 151 | 152 | #ifdef MINIZ_NO_INFLATE_APIS 153 | #define MINIZ_NO_ARCHIVE_APIS 154 | #endif 155 | 156 | #ifdef MINIZ_NO_DEFLATE_APIS 157 | #define MINIZ_NO_ARCHIVE_WRITING_APIS 158 | #endif 159 | 160 | #if defined(__TINYC__) && (defined(__linux) || defined(__linux__)) 161 | /* TODO: Work around "error: include file 'sys\utime.h' when compiling with tcc on Linux */ 162 | #define MINIZ_NO_TIME 163 | #endif 164 | 165 | #include 166 | 167 | #if !defined(MINIZ_NO_TIME) && !defined(MINIZ_NO_ARCHIVE_APIS) 168 | #include 169 | #endif 170 | 171 | #if defined(_M_IX86) || defined(_M_X64) || defined(__i386__) || defined(__i386) || defined(__i486__) || defined(__i486) || defined(i386) || defined(__ia64__) || defined(__x86_64__) 172 | /* MINIZ_X86_OR_X64_CPU is only used to help set the below macros. */ 173 | #define MINIZ_X86_OR_X64_CPU 1 174 | #else 175 | #define MINIZ_X86_OR_X64_CPU 0 176 | #endif 177 | 178 | /* Set MINIZ_LITTLE_ENDIAN only if not set */ 179 | #if !defined(MINIZ_LITTLE_ENDIAN) 180 | #if defined(__BYTE_ORDER__) && defined(__ORDER_LITTLE_ENDIAN__) 181 | 182 | #if (__BYTE_ORDER__ == __ORDER_LITTLE_ENDIAN__) 183 | /* Set MINIZ_LITTLE_ENDIAN to 1 if the processor is little endian. */ 184 | #define MINIZ_LITTLE_ENDIAN 1 185 | #else 186 | #define MINIZ_LITTLE_ENDIAN 0 187 | #endif 188 | 189 | #else 190 | 191 | #if MINIZ_X86_OR_X64_CPU 192 | #define MINIZ_LITTLE_ENDIAN 1 193 | #else 194 | #define MINIZ_LITTLE_ENDIAN 0 195 | #endif 196 | 197 | #endif 198 | #endif 199 | 200 | /* Using unaligned loads and stores causes errors when using UBSan */ 201 | #if defined(__has_feature) 202 | #if __has_feature(undefined_behavior_sanitizer) 203 | #define MINIZ_USE_UNALIGNED_LOADS_AND_STORES 0 204 | #endif 205 | #endif 206 | 207 | /* Set MINIZ_USE_UNALIGNED_LOADS_AND_STORES only if not set */ 208 | #if !defined(MINIZ_USE_UNALIGNED_LOADS_AND_STORES) 209 | #if MINIZ_X86_OR_X64_CPU 210 | /* Set MINIZ_USE_UNALIGNED_LOADS_AND_STORES to 1 on CPU's that permit efficient integer loads and stores from unaligned addresses. */ 211 | #define MINIZ_USE_UNALIGNED_LOADS_AND_STORES 0 212 | #define MINIZ_UNALIGNED_USE_MEMCPY 213 | #else 214 | #define MINIZ_USE_UNALIGNED_LOADS_AND_STORES 0 215 | #endif 216 | #endif 217 | 218 | #if defined(_M_X64) || defined(_WIN64) || defined(__MINGW64__) || defined(_LP64) || defined(__LP64__) || defined(__ia64__) || defined(__x86_64__) 219 | /* Set MINIZ_HAS_64BIT_REGISTERS to 1 if operations on 64-bit integers are reasonably fast (and don't involve compiler generated calls to helper functions). */ 220 | #define MINIZ_HAS_64BIT_REGISTERS 1 221 | #else 222 | #define MINIZ_HAS_64BIT_REGISTERS 0 223 | #endif 224 | 225 | #ifdef __cplusplus 226 | extern "C" { 227 | #endif 228 | 229 | /* ------------------- zlib-style API Definitions. */ 230 | 231 | /* For more compatibility with zlib, miniz.c uses unsigned long for some parameters/struct members. Beware: mz_ulong can be either 32 or 64-bits! */ 232 | typedef unsigned long mz_ulong; 233 | 234 | /* mz_free() internally uses the MZ_FREE() macro (which by default calls free() unless you've modified the MZ_MALLOC macro) to release a block allocated from the heap. */ 235 | MINIZ_EXPORT void mz_free(void *p); 236 | 237 | #define MZ_ADLER32_INIT (1) 238 | /* mz_adler32() returns the initial adler-32 value to use when called with ptr==NULL. */ 239 | MINIZ_EXPORT mz_ulong mz_adler32(mz_ulong adler, const unsigned char *ptr, size_t buf_len); 240 | 241 | #define MZ_CRC32_INIT (0) 242 | /* mz_crc32() returns the initial CRC-32 value to use when called with ptr==NULL. */ 243 | MINIZ_EXPORT mz_ulong mz_crc32(mz_ulong crc, const unsigned char *ptr, size_t buf_len); 244 | 245 | /* Compression strategies. */ 246 | enum 247 | { 248 | MZ_DEFAULT_STRATEGY = 0, 249 | MZ_FILTERED = 1, 250 | MZ_HUFFMAN_ONLY = 2, 251 | MZ_RLE = 3, 252 | MZ_FIXED = 4 253 | }; 254 | 255 | /* Method */ 256 | #define MZ_DEFLATED 8 257 | 258 | /* Heap allocation callbacks. 259 | Note that mz_alloc_func parameter types purposely differ from zlib's: items/size is size_t, not unsigned long. */ 260 | typedef void *(*mz_alloc_func)(void *opaque, size_t items, size_t size); 261 | typedef void (*mz_free_func)(void *opaque, void *address); 262 | typedef void *(*mz_realloc_func)(void *opaque, void *address, size_t items, size_t size); 263 | 264 | /* Compression levels: 0-9 are the standard zlib-style levels, 10 is best possible compression (not zlib compatible, and may be very slow), MZ_DEFAULT_COMPRESSION=MZ_DEFAULT_LEVEL. */ 265 | enum 266 | { 267 | MZ_NO_COMPRESSION = 0, 268 | MZ_BEST_SPEED = 1, 269 | MZ_BEST_COMPRESSION = 9, 270 | MZ_UBER_COMPRESSION = 10, 271 | MZ_DEFAULT_LEVEL = 6, 272 | MZ_DEFAULT_COMPRESSION = -1 273 | }; 274 | 275 | #define MZ_VERSION "11.0.2" 276 | #define MZ_VERNUM 0xB002 277 | #define MZ_VER_MAJOR 11 278 | #define MZ_VER_MINOR 2 279 | #define MZ_VER_REVISION 0 280 | #define MZ_VER_SUBREVISION 0 281 | 282 | #ifndef MINIZ_NO_ZLIB_APIS 283 | 284 | /* Flush values. For typical usage you only need MZ_NO_FLUSH and MZ_FINISH. The other values are for advanced use (refer to the zlib docs). */ 285 | enum 286 | { 287 | MZ_NO_FLUSH = 0, 288 | MZ_PARTIAL_FLUSH = 1, 289 | MZ_SYNC_FLUSH = 2, 290 | MZ_FULL_FLUSH = 3, 291 | MZ_FINISH = 4, 292 | MZ_BLOCK = 5 293 | }; 294 | 295 | /* Return status codes. MZ_PARAM_ERROR is non-standard. */ 296 | enum 297 | { 298 | MZ_OK = 0, 299 | MZ_STREAM_END = 1, 300 | MZ_NEED_DICT = 2, 301 | MZ_ERRNO = -1, 302 | MZ_STREAM_ERROR = -2, 303 | MZ_DATA_ERROR = -3, 304 | MZ_MEM_ERROR = -4, 305 | MZ_BUF_ERROR = -5, 306 | MZ_VERSION_ERROR = -6, 307 | MZ_PARAM_ERROR = -10000 308 | }; 309 | 310 | /* Window bits */ 311 | #define MZ_DEFAULT_WINDOW_BITS 15 312 | 313 | struct mz_internal_state; 314 | 315 | /* Compression/decompression stream struct. */ 316 | typedef struct mz_stream_s 317 | { 318 | const unsigned char *next_in; /* pointer to next byte to read */ 319 | unsigned int avail_in; /* number of bytes available at next_in */ 320 | mz_ulong total_in; /* total number of bytes consumed so far */ 321 | 322 | unsigned char *next_out; /* pointer to next byte to write */ 323 | unsigned int avail_out; /* number of bytes that can be written to next_out */ 324 | mz_ulong total_out; /* total number of bytes produced so far */ 325 | 326 | char *msg; /* error msg (unused) */ 327 | struct mz_internal_state *state; /* internal state, allocated by zalloc/zfree */ 328 | 329 | mz_alloc_func zalloc; /* optional heap allocation function (defaults to malloc) */ 330 | mz_free_func zfree; /* optional heap free function (defaults to free) */ 331 | void *opaque; /* heap alloc function user pointer */ 332 | 333 | int data_type; /* data_type (unused) */ 334 | mz_ulong adler; /* adler32 of the source or uncompressed data */ 335 | mz_ulong reserved; /* not used */ 336 | } mz_stream; 337 | 338 | typedef mz_stream *mz_streamp; 339 | 340 | /* Returns the version string of miniz.c. */ 341 | MINIZ_EXPORT const char *mz_version(void); 342 | 343 | #ifndef MINIZ_NO_DEFLATE_APIS 344 | 345 | /* mz_deflateInit() initializes a compressor with default options: */ 346 | /* Parameters: */ 347 | /* pStream must point to an initialized mz_stream struct. */ 348 | /* level must be between [MZ_NO_COMPRESSION, MZ_BEST_COMPRESSION]. */ 349 | /* level 1 enables a specially optimized compression function that's been optimized purely for performance, not ratio. */ 350 | /* (This special func. is currently only enabled when MINIZ_USE_UNALIGNED_LOADS_AND_STORES and MINIZ_LITTLE_ENDIAN are defined.) */ 351 | /* Return values: */ 352 | /* MZ_OK on success. */ 353 | /* MZ_STREAM_ERROR if the stream is bogus. */ 354 | /* MZ_PARAM_ERROR if the input parameters are bogus. */ 355 | /* MZ_MEM_ERROR on out of memory. */ 356 | MINIZ_EXPORT int mz_deflateInit(mz_streamp pStream, int level); 357 | 358 | /* mz_deflateInit2() is like mz_deflate(), except with more control: */ 359 | /* Additional parameters: */ 360 | /* method must be MZ_DEFLATED */ 361 | /* window_bits must be MZ_DEFAULT_WINDOW_BITS (to wrap the deflate stream with zlib header/adler-32 footer) or -MZ_DEFAULT_WINDOW_BITS (raw deflate/no header or footer) */ 362 | /* mem_level must be between [1, 9] (it's checked but ignored by miniz.c) */ 363 | MINIZ_EXPORT int mz_deflateInit2(mz_streamp pStream, int level, int method, int window_bits, int mem_level, int strategy); 364 | 365 | /* Quickly resets a compressor without having to reallocate anything. Same as calling mz_deflateEnd() followed by mz_deflateInit()/mz_deflateInit2(). */ 366 | MINIZ_EXPORT int mz_deflateReset(mz_streamp pStream); 367 | 368 | /* mz_deflate() compresses the input to output, consuming as much of the input and producing as much output as possible. */ 369 | /* Parameters: */ 370 | /* pStream is the stream to read from and write to. You must initialize/update the next_in, avail_in, next_out, and avail_out members. */ 371 | /* flush may be MZ_NO_FLUSH, MZ_PARTIAL_FLUSH/MZ_SYNC_FLUSH, MZ_FULL_FLUSH, or MZ_FINISH. */ 372 | /* Return values: */ 373 | /* MZ_OK on success (when flushing, or if more input is needed but not available, and/or there's more output to be written but the output buffer is full). */ 374 | /* MZ_STREAM_END if all input has been consumed and all output bytes have been written. Don't call mz_deflate() on the stream anymore. */ 375 | /* MZ_STREAM_ERROR if the stream is bogus. */ 376 | /* MZ_PARAM_ERROR if one of the parameters is invalid. */ 377 | /* MZ_BUF_ERROR if no forward progress is possible because the input and/or output buffers are empty. (Fill up the input buffer or free up some output space and try again.) */ 378 | MINIZ_EXPORT int mz_deflate(mz_streamp pStream, int flush); 379 | 380 | /* mz_deflateEnd() deinitializes a compressor: */ 381 | /* Return values: */ 382 | /* MZ_OK on success. */ 383 | /* MZ_STREAM_ERROR if the stream is bogus. */ 384 | MINIZ_EXPORT int mz_deflateEnd(mz_streamp pStream); 385 | 386 | /* mz_deflateBound() returns a (very) conservative upper bound on the amount of data that could be generated by deflate(), assuming flush is set to only MZ_NO_FLUSH or MZ_FINISH. */ 387 | MINIZ_EXPORT mz_ulong mz_deflateBound(mz_streamp pStream, mz_ulong source_len); 388 | 389 | /* Single-call compression functions mz_compress() and mz_compress2(): */ 390 | /* Returns MZ_OK on success, or one of the error codes from mz_deflate() on failure. */ 391 | MINIZ_EXPORT int mz_compress(unsigned char *pDest, mz_ulong *pDest_len, const unsigned char *pSource, mz_ulong source_len); 392 | MINIZ_EXPORT int mz_compress2(unsigned char *pDest, mz_ulong *pDest_len, const unsigned char *pSource, mz_ulong source_len, int level); 393 | 394 | /* mz_compressBound() returns a (very) conservative upper bound on the amount of data that could be generated by calling mz_compress(). */ 395 | MINIZ_EXPORT mz_ulong mz_compressBound(mz_ulong source_len); 396 | 397 | #endif /*#ifndef MINIZ_NO_DEFLATE_APIS*/ 398 | 399 | #ifndef MINIZ_NO_INFLATE_APIS 400 | 401 | /* Initializes a decompressor. */ 402 | MINIZ_EXPORT int mz_inflateInit(mz_streamp pStream); 403 | 404 | /* mz_inflateInit2() is like mz_inflateInit() with an additional option that controls the window size and whether or not the stream has been wrapped with a zlib header/footer: */ 405 | /* window_bits must be MZ_DEFAULT_WINDOW_BITS (to parse zlib header/footer) or -MZ_DEFAULT_WINDOW_BITS (raw deflate). */ 406 | MINIZ_EXPORT int mz_inflateInit2(mz_streamp pStream, int window_bits); 407 | 408 | /* Quickly resets a compressor without having to reallocate anything. Same as calling mz_inflateEnd() followed by mz_inflateInit()/mz_inflateInit2(). */ 409 | MINIZ_EXPORT int mz_inflateReset(mz_streamp pStream); 410 | 411 | /* Decompresses the input stream to the output, consuming only as much of the input as needed, and writing as much to the output as possible. */ 412 | /* Parameters: */ 413 | /* pStream is the stream to read from and write to. You must initialize/update the next_in, avail_in, next_out, and avail_out members. */ 414 | /* flush may be MZ_NO_FLUSH, MZ_SYNC_FLUSH, or MZ_FINISH. */ 415 | /* On the first call, if flush is MZ_FINISH it's assumed the input and output buffers are both sized large enough to decompress the entire stream in a single call (this is slightly faster). */ 416 | /* MZ_FINISH implies that there are no more source bytes available beside what's already in the input buffer, and that the output buffer is large enough to hold the rest of the decompressed data. */ 417 | /* Return values: */ 418 | /* MZ_OK on success. Either more input is needed but not available, and/or there's more output to be written but the output buffer is full. */ 419 | /* MZ_STREAM_END if all needed input has been consumed and all output bytes have been written. For zlib streams, the adler-32 of the decompressed data has also been verified. */ 420 | /* MZ_STREAM_ERROR if the stream is bogus. */ 421 | /* MZ_DATA_ERROR if the deflate stream is invalid. */ 422 | /* MZ_PARAM_ERROR if one of the parameters is invalid. */ 423 | /* MZ_BUF_ERROR if no forward progress is possible because the input buffer is empty but the inflater needs more input to continue, or if the output buffer is not large enough. Call mz_inflate() again */ 424 | /* with more input data, or with more room in the output buffer (except when using single call decompression, described above). */ 425 | MINIZ_EXPORT int mz_inflate(mz_streamp pStream, int flush); 426 | 427 | /* Deinitializes a decompressor. */ 428 | MINIZ_EXPORT int mz_inflateEnd(mz_streamp pStream); 429 | 430 | /* Single-call decompression. */ 431 | /* Returns MZ_OK on success, or one of the error codes from mz_inflate() on failure. */ 432 | MINIZ_EXPORT int mz_uncompress(unsigned char *pDest, mz_ulong *pDest_len, const unsigned char *pSource, mz_ulong source_len); 433 | MINIZ_EXPORT int mz_uncompress2(unsigned char *pDest, mz_ulong *pDest_len, const unsigned char *pSource, mz_ulong *pSource_len); 434 | #endif /*#ifndef MINIZ_NO_INFLATE_APIS*/ 435 | 436 | /* Returns a string description of the specified error code, or NULL if the error code is invalid. */ 437 | MINIZ_EXPORT const char *mz_error(int err); 438 | 439 | /* Redefine zlib-compatible names to miniz equivalents, so miniz.c can be used as a drop-in replacement for the subset of zlib that miniz.c supports. */ 440 | /* Define MINIZ_NO_ZLIB_COMPATIBLE_NAMES to disable zlib-compatibility if you use zlib in the same project. */ 441 | #ifndef MINIZ_NO_ZLIB_COMPATIBLE_NAMES 442 | typedef unsigned char Byte; 443 | typedef unsigned int uInt; 444 | typedef mz_ulong uLong; 445 | typedef Byte Bytef; 446 | typedef uInt uIntf; 447 | typedef char charf; 448 | typedef int intf; 449 | typedef void *voidpf; 450 | typedef uLong uLongf; 451 | typedef void *voidp; 452 | typedef void *const voidpc; 453 | #define Z_NULL 0 454 | #define Z_NO_FLUSH MZ_NO_FLUSH 455 | #define Z_PARTIAL_FLUSH MZ_PARTIAL_FLUSH 456 | #define Z_SYNC_FLUSH MZ_SYNC_FLUSH 457 | #define Z_FULL_FLUSH MZ_FULL_FLUSH 458 | #define Z_FINISH MZ_FINISH 459 | #define Z_BLOCK MZ_BLOCK 460 | #define Z_OK MZ_OK 461 | #define Z_STREAM_END MZ_STREAM_END 462 | #define Z_NEED_DICT MZ_NEED_DICT 463 | #define Z_ERRNO MZ_ERRNO 464 | #define Z_STREAM_ERROR MZ_STREAM_ERROR 465 | #define Z_DATA_ERROR MZ_DATA_ERROR 466 | #define Z_MEM_ERROR MZ_MEM_ERROR 467 | #define Z_BUF_ERROR MZ_BUF_ERROR 468 | #define Z_VERSION_ERROR MZ_VERSION_ERROR 469 | #define Z_PARAM_ERROR MZ_PARAM_ERROR 470 | #define Z_NO_COMPRESSION MZ_NO_COMPRESSION 471 | #define Z_BEST_SPEED MZ_BEST_SPEED 472 | #define Z_BEST_COMPRESSION MZ_BEST_COMPRESSION 473 | #define Z_DEFAULT_COMPRESSION MZ_DEFAULT_COMPRESSION 474 | #define Z_DEFAULT_STRATEGY MZ_DEFAULT_STRATEGY 475 | #define Z_FILTERED MZ_FILTERED 476 | #define Z_HUFFMAN_ONLY MZ_HUFFMAN_ONLY 477 | #define Z_RLE MZ_RLE 478 | #define Z_FIXED MZ_FIXED 479 | #define Z_DEFLATED MZ_DEFLATED 480 | #define Z_DEFAULT_WINDOW_BITS MZ_DEFAULT_WINDOW_BITS 481 | #define alloc_func mz_alloc_func 482 | #define free_func mz_free_func 483 | #define internal_state mz_internal_state 484 | #define z_stream mz_stream 485 | 486 | #ifndef MINIZ_NO_DEFLATE_APIS 487 | #define deflateInit mz_deflateInit 488 | #define deflateInit2 mz_deflateInit2 489 | #define deflateReset mz_deflateReset 490 | #define deflate mz_deflate 491 | #define deflateEnd mz_deflateEnd 492 | #define deflateBound mz_deflateBound 493 | #define compress mz_compress 494 | #define compress2 mz_compress2 495 | #define compressBound mz_compressBound 496 | #endif /*#ifndef MINIZ_NO_DEFLATE_APIS*/ 497 | 498 | #ifndef MINIZ_NO_INFLATE_APIS 499 | #define inflateInit mz_inflateInit 500 | #define inflateInit2 mz_inflateInit2 501 | #define inflateReset mz_inflateReset 502 | #define inflate mz_inflate 503 | #define inflateEnd mz_inflateEnd 504 | #define uncompress mz_uncompress 505 | #define uncompress2 mz_uncompress2 506 | #endif /*#ifndef MINIZ_NO_INFLATE_APIS*/ 507 | 508 | #define crc32 mz_crc32 509 | #define adler32 mz_adler32 510 | #define MAX_WBITS 15 511 | #define MAX_MEM_LEVEL 9 512 | #define zError mz_error 513 | #define ZLIB_VERSION MZ_VERSION 514 | #define ZLIB_VERNUM MZ_VERNUM 515 | #define ZLIB_VER_MAJOR MZ_VER_MAJOR 516 | #define ZLIB_VER_MINOR MZ_VER_MINOR 517 | #define ZLIB_VER_REVISION MZ_VER_REVISION 518 | #define ZLIB_VER_SUBREVISION MZ_VER_SUBREVISION 519 | #define zlibVersion mz_version 520 | #define zlib_version mz_version() 521 | #endif /* #ifndef MINIZ_NO_ZLIB_COMPATIBLE_NAMES */ 522 | 523 | #endif /* MINIZ_NO_ZLIB_APIS */ 524 | 525 | #ifdef __cplusplus 526 | } 527 | #endif 528 | 529 | #include "miniz_common.h" 530 | #include "miniz_tdef.h" 531 | #include "miniz_tinfl.h" 532 | #include "miniz_zip.h" 533 | -------------------------------------------------------------------------------- /miniz.pc.in: -------------------------------------------------------------------------------- 1 | prefix=@CMAKE_INSTALL_PREFIX@ 2 | exec_prefix=${prefix} 3 | libdir=${exec_prefix}/@CMAKE_INSTALL_LIBDIR@ 4 | includedir=${prefix}/@CMAKE_INSTALL_INCLUDEDIR@/@PROJECT_NAME@ 5 | 6 | Name: @PROJECT_NAME@ 7 | Description: @PROJECT_DESCRIPTION@ 8 | Version: @MINIZ_VERSION@ 9 | URL: @PROJECT_HOMEPAGE_URL@ 10 | 11 | Requires: 12 | Libs: -L${libdir} -lminiz 13 | Cflags: -I${includedir} 14 | -------------------------------------------------------------------------------- /miniz_common.h: -------------------------------------------------------------------------------- 1 | #pragma once 2 | #include 3 | #include 4 | #include 5 | #include 6 | 7 | #include "miniz_export.h" 8 | 9 | /* ------------------- Types and macros */ 10 | typedef unsigned char mz_uint8; 11 | typedef signed short mz_int16; 12 | typedef unsigned short mz_uint16; 13 | typedef unsigned int mz_uint32; 14 | typedef unsigned int mz_uint; 15 | typedef int64_t mz_int64; 16 | typedef uint64_t mz_uint64; 17 | typedef int mz_bool; 18 | 19 | #define MZ_FALSE (0) 20 | #define MZ_TRUE (1) 21 | 22 | /* Works around MSVC's spammy "warning C4127: conditional expression is constant" message. */ 23 | #ifdef _MSC_VER 24 | #define MZ_MACRO_END while (0, 0) 25 | #else 26 | #define MZ_MACRO_END while (0) 27 | #endif 28 | 29 | #ifdef MINIZ_NO_STDIO 30 | #define MZ_FILE void * 31 | #else 32 | #include 33 | #define MZ_FILE FILE 34 | #endif /* #ifdef MINIZ_NO_STDIO */ 35 | 36 | #ifdef MINIZ_NO_TIME 37 | typedef struct mz_dummy_time_t_tag 38 | { 39 | mz_uint32 m_dummy1; 40 | mz_uint32 m_dummy2; 41 | } mz_dummy_time_t; 42 | #define MZ_TIME_T mz_dummy_time_t 43 | #else 44 | #define MZ_TIME_T time_t 45 | #endif 46 | 47 | #define MZ_ASSERT(x) assert(x) 48 | 49 | #ifdef MINIZ_NO_MALLOC 50 | #define MZ_MALLOC(x) NULL 51 | #define MZ_FREE(x) (void)x, ((void)0) 52 | #define MZ_REALLOC(p, x) NULL 53 | #else 54 | #define MZ_MALLOC(x) malloc(x) 55 | #define MZ_FREE(x) free(x) 56 | #define MZ_REALLOC(p, x) realloc(p, x) 57 | #endif 58 | 59 | #define MZ_MAX(a, b) (((a) > (b)) ? (a) : (b)) 60 | #define MZ_MIN(a, b) (((a) < (b)) ? (a) : (b)) 61 | #define MZ_CLEAR_OBJ(obj) memset(&(obj), 0, sizeof(obj)) 62 | #define MZ_CLEAR_ARR(obj) memset((obj), 0, sizeof(obj)) 63 | #define MZ_CLEAR_PTR(obj) memset((obj), 0, sizeof(*obj)) 64 | 65 | #if MINIZ_USE_UNALIGNED_LOADS_AND_STORES && MINIZ_LITTLE_ENDIAN 66 | #define MZ_READ_LE16(p) *((const mz_uint16 *)(p)) 67 | #define MZ_READ_LE32(p) *((const mz_uint32 *)(p)) 68 | #else 69 | #define MZ_READ_LE16(p) ((mz_uint32)(((const mz_uint8 *)(p))[0]) | ((mz_uint32)(((const mz_uint8 *)(p))[1]) << 8U)) 70 | #define MZ_READ_LE32(p) ((mz_uint32)(((const mz_uint8 *)(p))[0]) | ((mz_uint32)(((const mz_uint8 *)(p))[1]) << 8U) | ((mz_uint32)(((const mz_uint8 *)(p))[2]) << 16U) | ((mz_uint32)(((const mz_uint8 *)(p))[3]) << 24U)) 71 | #endif 72 | 73 | #define MZ_READ_LE64(p) (((mz_uint64)MZ_READ_LE32(p)) | (((mz_uint64)MZ_READ_LE32((const mz_uint8 *)(p) + sizeof(mz_uint32))) << 32U)) 74 | 75 | #ifdef _MSC_VER 76 | #define MZ_FORCEINLINE __forceinline 77 | #elif defined(__GNUC__) 78 | #define MZ_FORCEINLINE __inline__ __attribute__((__always_inline__)) 79 | #else 80 | #define MZ_FORCEINLINE inline 81 | #endif 82 | 83 | #ifdef __cplusplus 84 | extern "C" { 85 | #endif 86 | 87 | extern MINIZ_EXPORT void *miniz_def_alloc_func(void *opaque, size_t items, size_t size); 88 | extern MINIZ_EXPORT void miniz_def_free_func(void *opaque, void *address); 89 | extern MINIZ_EXPORT void *miniz_def_realloc_func(void *opaque, void *address, size_t items, size_t size); 90 | 91 | #define MZ_UINT16_MAX (0xFFFFU) 92 | #define MZ_UINT32_MAX (0xFFFFFFFFU) 93 | 94 | #ifdef __cplusplus 95 | } 96 | #endif 97 | -------------------------------------------------------------------------------- /miniz_tdef.h: -------------------------------------------------------------------------------- 1 | #pragma once 2 | #include "miniz_common.h" 3 | 4 | #ifndef MINIZ_NO_DEFLATE_APIS 5 | 6 | #ifdef __cplusplus 7 | extern "C" { 8 | #endif 9 | /* ------------------- Low-level Compression API Definitions */ 10 | 11 | /* Set TDEFL_LESS_MEMORY to 1 to use less memory (compression will be slightly slower, and raw/dynamic blocks will be output more frequently). */ 12 | #define TDEFL_LESS_MEMORY 0 13 | 14 | /* tdefl_init() compression flags logically OR'd together (low 12 bits contain the max. number of probes per dictionary search): */ 15 | /* TDEFL_DEFAULT_MAX_PROBES: The compressor defaults to 128 dictionary probes per dictionary search. 0=Huffman only, 1=Huffman+LZ (fastest/crap compression), 4095=Huffman+LZ (slowest/best compression). */ 16 | enum 17 | { 18 | TDEFL_HUFFMAN_ONLY = 0, 19 | TDEFL_DEFAULT_MAX_PROBES = 128, 20 | TDEFL_MAX_PROBES_MASK = 0xFFF 21 | }; 22 | 23 | /* TDEFL_WRITE_ZLIB_HEADER: If set, the compressor outputs a zlib header before the deflate data, and the Adler-32 of the source data at the end. Otherwise, you'll get raw deflate data. */ 24 | /* TDEFL_COMPUTE_ADLER32: Always compute the adler-32 of the input data (even when not writing zlib headers). */ 25 | /* TDEFL_GREEDY_PARSING_FLAG: Set to use faster greedy parsing, instead of more efficient lazy parsing. */ 26 | /* TDEFL_NONDETERMINISTIC_PARSING_FLAG: Enable to decrease the compressor's initialization time to the minimum, but the output may vary from run to run given the same input (depending on the contents of memory). */ 27 | /* TDEFL_RLE_MATCHES: Only look for RLE matches (matches with a distance of 1) */ 28 | /* TDEFL_FILTER_MATCHES: Discards matches <= 5 chars if enabled. */ 29 | /* TDEFL_FORCE_ALL_STATIC_BLOCKS: Disable usage of optimized Huffman tables. */ 30 | /* TDEFL_FORCE_ALL_RAW_BLOCKS: Only use raw (uncompressed) deflate blocks. */ 31 | /* The low 12 bits are reserved to control the max # of hash probes per dictionary lookup (see TDEFL_MAX_PROBES_MASK). */ 32 | enum 33 | { 34 | TDEFL_WRITE_ZLIB_HEADER = 0x01000, 35 | TDEFL_COMPUTE_ADLER32 = 0x02000, 36 | TDEFL_GREEDY_PARSING_FLAG = 0x04000, 37 | TDEFL_NONDETERMINISTIC_PARSING_FLAG = 0x08000, 38 | TDEFL_RLE_MATCHES = 0x10000, 39 | TDEFL_FILTER_MATCHES = 0x20000, 40 | TDEFL_FORCE_ALL_STATIC_BLOCKS = 0x40000, 41 | TDEFL_FORCE_ALL_RAW_BLOCKS = 0x80000 42 | }; 43 | 44 | /* High level compression functions: */ 45 | /* tdefl_compress_mem_to_heap() compresses a block in memory to a heap block allocated via malloc(). */ 46 | /* On entry: */ 47 | /* pSrc_buf, src_buf_len: Pointer and size of source block to compress. */ 48 | /* flags: The max match finder probes (default is 128) logically OR'd against the above flags. Higher probes are slower but improve compression. */ 49 | /* On return: */ 50 | /* Function returns a pointer to the compressed data, or NULL on failure. */ 51 | /* *pOut_len will be set to the compressed data's size, which could be larger than src_buf_len on uncompressible data. */ 52 | /* The caller must free() the returned block when it's no longer needed. */ 53 | MINIZ_EXPORT void *tdefl_compress_mem_to_heap(const void *pSrc_buf, size_t src_buf_len, size_t *pOut_len, int flags); 54 | 55 | /* tdefl_compress_mem_to_mem() compresses a block in memory to another block in memory. */ 56 | /* Returns 0 on failure. */ 57 | MINIZ_EXPORT size_t tdefl_compress_mem_to_mem(void *pOut_buf, size_t out_buf_len, const void *pSrc_buf, size_t src_buf_len, int flags); 58 | 59 | /* Compresses an image to a compressed PNG file in memory. */ 60 | /* On entry: */ 61 | /* pImage, w, h, and num_chans describe the image to compress. num_chans may be 1, 2, 3, or 4. */ 62 | /* The image pitch in bytes per scanline will be w*num_chans. The leftmost pixel on the top scanline is stored first in memory. */ 63 | /* level may range from [0,10], use MZ_NO_COMPRESSION, MZ_BEST_SPEED, MZ_BEST_COMPRESSION, etc. or a decent default is MZ_DEFAULT_LEVEL */ 64 | /* If flip is true, the image will be flipped on the Y axis (useful for OpenGL apps). */ 65 | /* On return: */ 66 | /* Function returns a pointer to the compressed data, or NULL on failure. */ 67 | /* *pLen_out will be set to the size of the PNG image file. */ 68 | /* The caller must mz_free() the returned heap block (which will typically be larger than *pLen_out) when it's no longer needed. */ 69 | MINIZ_EXPORT void *tdefl_write_image_to_png_file_in_memory_ex(const void *pImage, int w, int h, int num_chans, size_t *pLen_out, mz_uint level, mz_bool flip); 70 | MINIZ_EXPORT void *tdefl_write_image_to_png_file_in_memory(const void *pImage, int w, int h, int num_chans, size_t *pLen_out); 71 | 72 | /* Output stream interface. The compressor uses this interface to write compressed data. It'll typically be called TDEFL_OUT_BUF_SIZE at a time. */ 73 | typedef mz_bool (*tdefl_put_buf_func_ptr)(const void *pBuf, int len, void *pUser); 74 | 75 | /* tdefl_compress_mem_to_output() compresses a block to an output stream. The above helpers use this function internally. */ 76 | MINIZ_EXPORT mz_bool tdefl_compress_mem_to_output(const void *pBuf, size_t buf_len, tdefl_put_buf_func_ptr pPut_buf_func, void *pPut_buf_user, int flags); 77 | 78 | enum 79 | { 80 | TDEFL_MAX_HUFF_TABLES = 3, 81 | TDEFL_MAX_HUFF_SYMBOLS_0 = 288, 82 | TDEFL_MAX_HUFF_SYMBOLS_1 = 32, 83 | TDEFL_MAX_HUFF_SYMBOLS_2 = 19, 84 | TDEFL_LZ_DICT_SIZE = 32768, 85 | TDEFL_LZ_DICT_SIZE_MASK = TDEFL_LZ_DICT_SIZE - 1, 86 | TDEFL_MIN_MATCH_LEN = 3, 87 | TDEFL_MAX_MATCH_LEN = 258 88 | }; 89 | 90 | /* TDEFL_OUT_BUF_SIZE MUST be large enough to hold a single entire compressed output block (using static/fixed Huffman codes). */ 91 | #if TDEFL_LESS_MEMORY 92 | enum 93 | { 94 | TDEFL_LZ_CODE_BUF_SIZE = 24 * 1024, 95 | TDEFL_OUT_BUF_SIZE = (TDEFL_LZ_CODE_BUF_SIZE * 13) / 10, 96 | TDEFL_MAX_HUFF_SYMBOLS = 288, 97 | TDEFL_LZ_HASH_BITS = 12, 98 | TDEFL_LEVEL1_HASH_SIZE_MASK = 4095, 99 | TDEFL_LZ_HASH_SHIFT = (TDEFL_LZ_HASH_BITS + 2) / 3, 100 | TDEFL_LZ_HASH_SIZE = 1 << TDEFL_LZ_HASH_BITS 101 | }; 102 | #else 103 | enum 104 | { 105 | TDEFL_LZ_CODE_BUF_SIZE = 64 * 1024, 106 | TDEFL_OUT_BUF_SIZE = (TDEFL_LZ_CODE_BUF_SIZE * 13) / 10, 107 | TDEFL_MAX_HUFF_SYMBOLS = 288, 108 | TDEFL_LZ_HASH_BITS = 15, 109 | TDEFL_LEVEL1_HASH_SIZE_MASK = 4095, 110 | TDEFL_LZ_HASH_SHIFT = (TDEFL_LZ_HASH_BITS + 2) / 3, 111 | TDEFL_LZ_HASH_SIZE = 1 << TDEFL_LZ_HASH_BITS 112 | }; 113 | #endif 114 | 115 | /* The low-level tdefl functions below may be used directly if the above helper functions aren't flexible enough. The low-level functions don't make any heap allocations, unlike the above helper functions. */ 116 | typedef enum { 117 | TDEFL_STATUS_BAD_PARAM = -2, 118 | TDEFL_STATUS_PUT_BUF_FAILED = -1, 119 | TDEFL_STATUS_OKAY = 0, 120 | TDEFL_STATUS_DONE = 1 121 | } tdefl_status; 122 | 123 | /* Must map to MZ_NO_FLUSH, MZ_SYNC_FLUSH, etc. enums */ 124 | typedef enum { 125 | TDEFL_NO_FLUSH = 0, 126 | TDEFL_SYNC_FLUSH = 2, 127 | TDEFL_FULL_FLUSH = 3, 128 | TDEFL_FINISH = 4 129 | } tdefl_flush; 130 | 131 | /* tdefl's compression state structure. */ 132 | typedef struct 133 | { 134 | tdefl_put_buf_func_ptr m_pPut_buf_func; 135 | void *m_pPut_buf_user; 136 | mz_uint m_flags, m_max_probes[2]; 137 | int m_greedy_parsing; 138 | mz_uint m_adler32, m_lookahead_pos, m_lookahead_size, m_dict_size; 139 | mz_uint8 *m_pLZ_code_buf, *m_pLZ_flags, *m_pOutput_buf, *m_pOutput_buf_end; 140 | mz_uint m_num_flags_left, m_total_lz_bytes, m_lz_code_buf_dict_pos, m_bits_in, m_bit_buffer; 141 | mz_uint m_saved_match_dist, m_saved_match_len, m_saved_lit, m_output_flush_ofs, m_output_flush_remaining, m_finished, m_block_index, m_wants_to_finish; 142 | tdefl_status m_prev_return_status; 143 | const void *m_pIn_buf; 144 | void *m_pOut_buf; 145 | size_t *m_pIn_buf_size, *m_pOut_buf_size; 146 | tdefl_flush m_flush; 147 | const mz_uint8 *m_pSrc; 148 | size_t m_src_buf_left, m_out_buf_ofs; 149 | mz_uint8 m_dict[TDEFL_LZ_DICT_SIZE + TDEFL_MAX_MATCH_LEN - 1]; 150 | mz_uint16 m_huff_count[TDEFL_MAX_HUFF_TABLES][TDEFL_MAX_HUFF_SYMBOLS]; 151 | mz_uint16 m_huff_codes[TDEFL_MAX_HUFF_TABLES][TDEFL_MAX_HUFF_SYMBOLS]; 152 | mz_uint8 m_huff_code_sizes[TDEFL_MAX_HUFF_TABLES][TDEFL_MAX_HUFF_SYMBOLS]; 153 | mz_uint8 m_lz_code_buf[TDEFL_LZ_CODE_BUF_SIZE]; 154 | mz_uint16 m_next[TDEFL_LZ_DICT_SIZE]; 155 | mz_uint16 m_hash[TDEFL_LZ_HASH_SIZE]; 156 | mz_uint8 m_output_buf[TDEFL_OUT_BUF_SIZE]; 157 | } tdefl_compressor; 158 | 159 | /* Initializes the compressor. */ 160 | /* There is no corresponding deinit() function because the tdefl API's do not dynamically allocate memory. */ 161 | /* pBut_buf_func: If NULL, output data will be supplied to the specified callback. In this case, the user should call the tdefl_compress_buffer() API for compression. */ 162 | /* If pBut_buf_func is NULL the user should always call the tdefl_compress() API. */ 163 | /* flags: See the above enums (TDEFL_HUFFMAN_ONLY, TDEFL_WRITE_ZLIB_HEADER, etc.) */ 164 | MINIZ_EXPORT tdefl_status tdefl_init(tdefl_compressor *d, tdefl_put_buf_func_ptr pPut_buf_func, void *pPut_buf_user, int flags); 165 | 166 | /* Compresses a block of data, consuming as much of the specified input buffer as possible, and writing as much compressed data to the specified output buffer as possible. */ 167 | MINIZ_EXPORT tdefl_status tdefl_compress(tdefl_compressor *d, const void *pIn_buf, size_t *pIn_buf_size, void *pOut_buf, size_t *pOut_buf_size, tdefl_flush flush); 168 | 169 | /* tdefl_compress_buffer() is only usable when the tdefl_init() is called with a non-NULL tdefl_put_buf_func_ptr. */ 170 | /* tdefl_compress_buffer() always consumes the entire input buffer. */ 171 | MINIZ_EXPORT tdefl_status tdefl_compress_buffer(tdefl_compressor *d, const void *pIn_buf, size_t in_buf_size, tdefl_flush flush); 172 | 173 | MINIZ_EXPORT tdefl_status tdefl_get_prev_return_status(tdefl_compressor *d); 174 | MINIZ_EXPORT mz_uint32 tdefl_get_adler32(tdefl_compressor *d); 175 | 176 | /* Create tdefl_compress() flags given zlib-style compression parameters. */ 177 | /* level may range from [0,10] (where 10 is absolute max compression, but may be much slower on some files) */ 178 | /* window_bits may be -15 (raw deflate) or 15 (zlib) */ 179 | /* strategy may be either MZ_DEFAULT_STRATEGY, MZ_FILTERED, MZ_HUFFMAN_ONLY, MZ_RLE, or MZ_FIXED */ 180 | MINIZ_EXPORT mz_uint tdefl_create_comp_flags_from_zip_params(int level, int window_bits, int strategy); 181 | 182 | #ifndef MINIZ_NO_MALLOC 183 | /* Allocate the tdefl_compressor structure in C so that */ 184 | /* non-C language bindings to tdefl_ API don't need to worry about */ 185 | /* structure size and allocation mechanism. */ 186 | MINIZ_EXPORT tdefl_compressor *tdefl_compressor_alloc(void); 187 | MINIZ_EXPORT void tdefl_compressor_free(tdefl_compressor *pComp); 188 | #endif 189 | 190 | #ifdef __cplusplus 191 | } 192 | #endif 193 | 194 | #endif /*#ifndef MINIZ_NO_DEFLATE_APIS*/ 195 | -------------------------------------------------------------------------------- /miniz_tinfl.h: -------------------------------------------------------------------------------- 1 | #pragma once 2 | #include "miniz_common.h" 3 | /* ------------------- Low-level Decompression API Definitions */ 4 | 5 | #ifndef MINIZ_NO_INFLATE_APIS 6 | 7 | #ifdef __cplusplus 8 | extern "C" { 9 | #endif 10 | /* Decompression flags used by tinfl_decompress(). */ 11 | /* TINFL_FLAG_PARSE_ZLIB_HEADER: If set, the input has a valid zlib header and ends with an adler32 checksum (it's a valid zlib stream). Otherwise, the input is a raw deflate stream. */ 12 | /* TINFL_FLAG_HAS_MORE_INPUT: If set, there are more input bytes available beyond the end of the supplied input buffer. If clear, the input buffer contains all remaining input. */ 13 | /* TINFL_FLAG_USING_NON_WRAPPING_OUTPUT_BUF: If set, the output buffer is large enough to hold the entire decompressed stream. If clear, the output buffer is at least the size of the dictionary (typically 32KB). */ 14 | /* TINFL_FLAG_COMPUTE_ADLER32: Force adler-32 checksum computation of the decompressed bytes. */ 15 | enum 16 | { 17 | TINFL_FLAG_PARSE_ZLIB_HEADER = 1, 18 | TINFL_FLAG_HAS_MORE_INPUT = 2, 19 | TINFL_FLAG_USING_NON_WRAPPING_OUTPUT_BUF = 4, 20 | TINFL_FLAG_COMPUTE_ADLER32 = 8 21 | }; 22 | 23 | /* High level decompression functions: */ 24 | /* tinfl_decompress_mem_to_heap() decompresses a block in memory to a heap block allocated via malloc(). */ 25 | /* On entry: */ 26 | /* pSrc_buf, src_buf_len: Pointer and size of the Deflate or zlib source data to decompress. */ 27 | /* On return: */ 28 | /* Function returns a pointer to the decompressed data, or NULL on failure. */ 29 | /* *pOut_len will be set to the decompressed data's size, which could be larger than src_buf_len on uncompressible data. */ 30 | /* The caller must call mz_free() on the returned block when it's no longer needed. */ 31 | MINIZ_EXPORT void *tinfl_decompress_mem_to_heap(const void *pSrc_buf, size_t src_buf_len, size_t *pOut_len, int flags); 32 | 33 | /* tinfl_decompress_mem_to_mem() decompresses a block in memory to another block in memory. */ 34 | /* Returns TINFL_DECOMPRESS_MEM_TO_MEM_FAILED on failure, or the number of bytes written on success. */ 35 | #define TINFL_DECOMPRESS_MEM_TO_MEM_FAILED ((size_t)(-1)) 36 | MINIZ_EXPORT size_t tinfl_decompress_mem_to_mem(void *pOut_buf, size_t out_buf_len, const void *pSrc_buf, size_t src_buf_len, int flags); 37 | 38 | /* tinfl_decompress_mem_to_callback() decompresses a block in memory to an internal 32KB buffer, and a user provided callback function will be called to flush the buffer. */ 39 | /* Returns 1 on success or 0 on failure. */ 40 | typedef int (*tinfl_put_buf_func_ptr)(const void *pBuf, int len, void *pUser); 41 | MINIZ_EXPORT int tinfl_decompress_mem_to_callback(const void *pIn_buf, size_t *pIn_buf_size, tinfl_put_buf_func_ptr pPut_buf_func, void *pPut_buf_user, int flags); 42 | 43 | struct tinfl_decompressor_tag; 44 | typedef struct tinfl_decompressor_tag tinfl_decompressor; 45 | 46 | #ifndef MINIZ_NO_MALLOC 47 | /* Allocate the tinfl_decompressor structure in C so that */ 48 | /* non-C language bindings to tinfl_ API don't need to worry about */ 49 | /* structure size and allocation mechanism. */ 50 | MINIZ_EXPORT tinfl_decompressor *tinfl_decompressor_alloc(void); 51 | MINIZ_EXPORT void tinfl_decompressor_free(tinfl_decompressor *pDecomp); 52 | #endif 53 | 54 | /* Max size of LZ dictionary. */ 55 | #define TINFL_LZ_DICT_SIZE 32768 56 | 57 | /* Return status. */ 58 | typedef enum { 59 | /* This flags indicates the inflator needs 1 or more input bytes to make forward progress, but the caller is indicating that no more are available. The compressed data */ 60 | /* is probably corrupted. If you call the inflator again with more bytes it'll try to continue processing the input but this is a BAD sign (either the data is corrupted or you called it incorrectly). */ 61 | /* If you call it again with no input you'll just get TINFL_STATUS_FAILED_CANNOT_MAKE_PROGRESS again. */ 62 | TINFL_STATUS_FAILED_CANNOT_MAKE_PROGRESS = -4, 63 | 64 | /* This flag indicates that one or more of the input parameters was obviously bogus. (You can try calling it again, but if you get this error the calling code is wrong.) */ 65 | TINFL_STATUS_BAD_PARAM = -3, 66 | 67 | /* This flags indicate the inflator is finished but the adler32 check of the uncompressed data didn't match. If you call it again it'll return TINFL_STATUS_DONE. */ 68 | TINFL_STATUS_ADLER32_MISMATCH = -2, 69 | 70 | /* This flags indicate the inflator has somehow failed (bad code, corrupted input, etc.). If you call it again without resetting via tinfl_init() it it'll just keep on returning the same status failure code. */ 71 | TINFL_STATUS_FAILED = -1, 72 | 73 | /* Any status code less than TINFL_STATUS_DONE must indicate a failure. */ 74 | 75 | /* This flag indicates the inflator has returned every byte of uncompressed data that it can, has consumed every byte that it needed, has successfully reached the end of the deflate stream, and */ 76 | /* if zlib headers and adler32 checking enabled that it has successfully checked the uncompressed data's adler32. If you call it again you'll just get TINFL_STATUS_DONE over and over again. */ 77 | TINFL_STATUS_DONE = 0, 78 | 79 | /* This flag indicates the inflator MUST have more input data (even 1 byte) before it can make any more forward progress, or you need to clear the TINFL_FLAG_HAS_MORE_INPUT */ 80 | /* flag on the next call if you don't have any more source data. If the source data was somehow corrupted it's also possible (but unlikely) for the inflator to keep on demanding input to */ 81 | /* proceed, so be sure to properly set the TINFL_FLAG_HAS_MORE_INPUT flag. */ 82 | TINFL_STATUS_NEEDS_MORE_INPUT = 1, 83 | 84 | /* This flag indicates the inflator definitely has 1 or more bytes of uncompressed data available, but it cannot write this data into the output buffer. */ 85 | /* Note if the source compressed data was corrupted it's possible for the inflator to return a lot of uncompressed data to the caller. I've been assuming you know how much uncompressed data to expect */ 86 | /* (either exact or worst case) and will stop calling the inflator and fail after receiving too much. In pure streaming scenarios where you have no idea how many bytes to expect this may not be possible */ 87 | /* so I may need to add some code to address this. */ 88 | TINFL_STATUS_HAS_MORE_OUTPUT = 2 89 | } tinfl_status; 90 | 91 | /* Initializes the decompressor to its initial state. */ 92 | #define tinfl_init(r) \ 93 | do \ 94 | { \ 95 | (r)->m_state = 0; \ 96 | } \ 97 | MZ_MACRO_END 98 | #define tinfl_get_adler32(r) (r)->m_check_adler32 99 | 100 | /* Main low-level decompressor coroutine function. This is the only function actually needed for decompression. All the other functions are just high-level helpers for improved usability. */ 101 | /* This is a universal API, i.e. it can be used as a building block to build any desired higher level decompression API. In the limit case, it can be called once per every byte input or output. */ 102 | MINIZ_EXPORT tinfl_status tinfl_decompress(tinfl_decompressor *r, const mz_uint8 *pIn_buf_next, size_t *pIn_buf_size, mz_uint8 *pOut_buf_start, mz_uint8 *pOut_buf_next, size_t *pOut_buf_size, const mz_uint32 decomp_flags); 103 | 104 | /* Internal/private bits follow. */ 105 | enum 106 | { 107 | TINFL_MAX_HUFF_TABLES = 3, 108 | TINFL_MAX_HUFF_SYMBOLS_0 = 288, 109 | TINFL_MAX_HUFF_SYMBOLS_1 = 32, 110 | TINFL_MAX_HUFF_SYMBOLS_2 = 19, 111 | TINFL_FAST_LOOKUP_BITS = 10, 112 | TINFL_FAST_LOOKUP_SIZE = 1 << TINFL_FAST_LOOKUP_BITS 113 | }; 114 | 115 | #if MINIZ_HAS_64BIT_REGISTERS 116 | #define TINFL_USE_64BIT_BITBUF 1 117 | #else 118 | #define TINFL_USE_64BIT_BITBUF 0 119 | #endif 120 | 121 | #if TINFL_USE_64BIT_BITBUF 122 | typedef mz_uint64 tinfl_bit_buf_t; 123 | #define TINFL_BITBUF_SIZE (64) 124 | #else 125 | typedef mz_uint32 tinfl_bit_buf_t; 126 | #define TINFL_BITBUF_SIZE (32) 127 | #endif 128 | 129 | struct tinfl_decompressor_tag 130 | { 131 | mz_uint32 m_state, m_num_bits, m_zhdr0, m_zhdr1, m_z_adler32, m_final, m_type, m_check_adler32, m_dist, m_counter, m_num_extra, m_table_sizes[TINFL_MAX_HUFF_TABLES]; 132 | tinfl_bit_buf_t m_bit_buf; 133 | size_t m_dist_from_out_buf_start; 134 | mz_int16 m_look_up[TINFL_MAX_HUFF_TABLES][TINFL_FAST_LOOKUP_SIZE]; 135 | mz_int16 m_tree_0[TINFL_MAX_HUFF_SYMBOLS_0 * 2]; 136 | mz_int16 m_tree_1[TINFL_MAX_HUFF_SYMBOLS_1 * 2]; 137 | mz_int16 m_tree_2[TINFL_MAX_HUFF_SYMBOLS_2 * 2]; 138 | mz_uint8 m_code_size_0[TINFL_MAX_HUFF_SYMBOLS_0]; 139 | mz_uint8 m_code_size_1[TINFL_MAX_HUFF_SYMBOLS_1]; 140 | mz_uint8 m_code_size_2[TINFL_MAX_HUFF_SYMBOLS_2]; 141 | mz_uint8 m_raw_header[4], m_len_codes[TINFL_MAX_HUFF_SYMBOLS_0 + TINFL_MAX_HUFF_SYMBOLS_1 + 137]; 142 | }; 143 | 144 | #ifdef __cplusplus 145 | } 146 | #endif 147 | 148 | #endif /*#ifndef MINIZ_NO_INFLATE_APIS*/ 149 | -------------------------------------------------------------------------------- /miniz_zip.h: -------------------------------------------------------------------------------- 1 | 2 | #pragma once 3 | #include "miniz_common.h" 4 | 5 | /* ------------------- ZIP archive reading/writing */ 6 | 7 | #ifndef MINIZ_NO_ARCHIVE_APIS 8 | 9 | #ifdef __cplusplus 10 | extern "C" { 11 | #endif 12 | 13 | enum 14 | { 15 | /* Note: These enums can be reduced as needed to save memory or stack space - they are pretty conservative. */ 16 | MZ_ZIP_MAX_IO_BUF_SIZE = 64 * 1024, 17 | MZ_ZIP_MAX_ARCHIVE_FILENAME_SIZE = 512, 18 | MZ_ZIP_MAX_ARCHIVE_FILE_COMMENT_SIZE = 512 19 | }; 20 | 21 | typedef struct 22 | { 23 | /* Central directory file index. */ 24 | mz_uint32 m_file_index; 25 | 26 | /* Byte offset of this entry in the archive's central directory. Note we currently only support up to UINT_MAX or less bytes in the central dir. */ 27 | mz_uint64 m_central_dir_ofs; 28 | 29 | /* These fields are copied directly from the zip's central dir. */ 30 | mz_uint16 m_version_made_by; 31 | mz_uint16 m_version_needed; 32 | mz_uint16 m_bit_flag; 33 | mz_uint16 m_method; 34 | 35 | /* CRC-32 of uncompressed data. */ 36 | mz_uint32 m_crc32; 37 | 38 | /* File's compressed size. */ 39 | mz_uint64 m_comp_size; 40 | 41 | /* File's uncompressed size. Note, I've seen some old archives where directory entries had 512 bytes for their uncompressed sizes, but when you try to unpack them you actually get 0 bytes. */ 42 | mz_uint64 m_uncomp_size; 43 | 44 | /* Zip internal and external file attributes. */ 45 | mz_uint16 m_internal_attr; 46 | mz_uint32 m_external_attr; 47 | 48 | /* Entry's local header file offset in bytes. */ 49 | mz_uint64 m_local_header_ofs; 50 | 51 | /* Size of comment in bytes. */ 52 | mz_uint32 m_comment_size; 53 | 54 | /* MZ_TRUE if the entry appears to be a directory. */ 55 | mz_bool m_is_directory; 56 | 57 | /* MZ_TRUE if the entry uses encryption/strong encryption (which miniz_zip doesn't support) */ 58 | mz_bool m_is_encrypted; 59 | 60 | /* MZ_TRUE if the file is not encrypted, a patch file, and if it uses a compression method we support. */ 61 | mz_bool m_is_supported; 62 | 63 | /* Filename. If string ends in '/' it's a subdirectory entry. */ 64 | /* Guaranteed to be zero terminated, may be truncated to fit. */ 65 | char m_filename[MZ_ZIP_MAX_ARCHIVE_FILENAME_SIZE]; 66 | 67 | /* Comment field. */ 68 | /* Guaranteed to be zero terminated, may be truncated to fit. */ 69 | char m_comment[MZ_ZIP_MAX_ARCHIVE_FILE_COMMENT_SIZE]; 70 | 71 | #ifdef MINIZ_NO_TIME 72 | MZ_TIME_T m_padding; 73 | #else 74 | MZ_TIME_T m_time; 75 | #endif 76 | } mz_zip_archive_file_stat; 77 | 78 | typedef size_t (*mz_file_read_func)(void *pOpaque, mz_uint64 file_ofs, void *pBuf, size_t n); 79 | typedef size_t (*mz_file_write_func)(void *pOpaque, mz_uint64 file_ofs, const void *pBuf, size_t n); 80 | typedef mz_bool (*mz_file_needs_keepalive)(void *pOpaque); 81 | 82 | struct mz_zip_internal_state_tag; 83 | typedef struct mz_zip_internal_state_tag mz_zip_internal_state; 84 | 85 | typedef enum { 86 | MZ_ZIP_MODE_INVALID = 0, 87 | MZ_ZIP_MODE_READING = 1, 88 | MZ_ZIP_MODE_WRITING = 2, 89 | MZ_ZIP_MODE_WRITING_HAS_BEEN_FINALIZED = 3 90 | } mz_zip_mode; 91 | 92 | typedef enum { 93 | MZ_ZIP_FLAG_CASE_SENSITIVE = 0x0100, 94 | MZ_ZIP_FLAG_IGNORE_PATH = 0x0200, 95 | MZ_ZIP_FLAG_COMPRESSED_DATA = 0x0400, 96 | MZ_ZIP_FLAG_DO_NOT_SORT_CENTRAL_DIRECTORY = 0x0800, 97 | MZ_ZIP_FLAG_VALIDATE_LOCATE_FILE_FLAG = 0x1000, /* if enabled, mz_zip_reader_locate_file() will be called on each file as its validated to ensure the func finds the file in the central dir (intended for testing) */ 98 | MZ_ZIP_FLAG_VALIDATE_HEADERS_ONLY = 0x2000, /* validate the local headers, but don't decompress the entire file and check the crc32 */ 99 | MZ_ZIP_FLAG_WRITE_ZIP64 = 0x4000, /* always use the zip64 file format, instead of the original zip file format with automatic switch to zip64. Use as flags parameter with mz_zip_writer_init*_v2 */ 100 | MZ_ZIP_FLAG_WRITE_ALLOW_READING = 0x8000, 101 | MZ_ZIP_FLAG_ASCII_FILENAME = 0x10000, 102 | /*After adding a compressed file, seek back 103 | to local file header and set the correct sizes*/ 104 | MZ_ZIP_FLAG_WRITE_HEADER_SET_SIZE = 0x20000 105 | } mz_zip_flags; 106 | 107 | typedef enum { 108 | MZ_ZIP_TYPE_INVALID = 0, 109 | MZ_ZIP_TYPE_USER, 110 | MZ_ZIP_TYPE_MEMORY, 111 | MZ_ZIP_TYPE_HEAP, 112 | MZ_ZIP_TYPE_FILE, 113 | MZ_ZIP_TYPE_CFILE, 114 | MZ_ZIP_TOTAL_TYPES 115 | } mz_zip_type; 116 | 117 | /* miniz error codes. Be sure to update mz_zip_get_error_string() if you add or modify this enum. */ 118 | typedef enum { 119 | MZ_ZIP_NO_ERROR = 0, 120 | MZ_ZIP_UNDEFINED_ERROR, 121 | MZ_ZIP_TOO_MANY_FILES, 122 | MZ_ZIP_FILE_TOO_LARGE, 123 | MZ_ZIP_UNSUPPORTED_METHOD, 124 | MZ_ZIP_UNSUPPORTED_ENCRYPTION, 125 | MZ_ZIP_UNSUPPORTED_FEATURE, 126 | MZ_ZIP_FAILED_FINDING_CENTRAL_DIR, 127 | MZ_ZIP_NOT_AN_ARCHIVE, 128 | MZ_ZIP_INVALID_HEADER_OR_CORRUPTED, 129 | MZ_ZIP_UNSUPPORTED_MULTIDISK, 130 | MZ_ZIP_DECOMPRESSION_FAILED, 131 | MZ_ZIP_COMPRESSION_FAILED, 132 | MZ_ZIP_UNEXPECTED_DECOMPRESSED_SIZE, 133 | MZ_ZIP_CRC_CHECK_FAILED, 134 | MZ_ZIP_UNSUPPORTED_CDIR_SIZE, 135 | MZ_ZIP_ALLOC_FAILED, 136 | MZ_ZIP_FILE_OPEN_FAILED, 137 | MZ_ZIP_FILE_CREATE_FAILED, 138 | MZ_ZIP_FILE_WRITE_FAILED, 139 | MZ_ZIP_FILE_READ_FAILED, 140 | MZ_ZIP_FILE_CLOSE_FAILED, 141 | MZ_ZIP_FILE_SEEK_FAILED, 142 | MZ_ZIP_FILE_STAT_FAILED, 143 | MZ_ZIP_INVALID_PARAMETER, 144 | MZ_ZIP_INVALID_FILENAME, 145 | MZ_ZIP_BUF_TOO_SMALL, 146 | MZ_ZIP_INTERNAL_ERROR, 147 | MZ_ZIP_FILE_NOT_FOUND, 148 | MZ_ZIP_ARCHIVE_TOO_LARGE, 149 | MZ_ZIP_VALIDATION_FAILED, 150 | MZ_ZIP_WRITE_CALLBACK_FAILED, 151 | MZ_ZIP_TOTAL_ERRORS 152 | } mz_zip_error; 153 | 154 | typedef struct 155 | { 156 | mz_uint64 m_archive_size; 157 | mz_uint64 m_central_directory_file_ofs; 158 | 159 | /* We only support up to UINT32_MAX files in zip64 mode. */ 160 | mz_uint32 m_total_files; 161 | mz_zip_mode m_zip_mode; 162 | mz_zip_type m_zip_type; 163 | mz_zip_error m_last_error; 164 | 165 | mz_uint64 m_file_offset_alignment; 166 | 167 | mz_alloc_func m_pAlloc; 168 | mz_free_func m_pFree; 169 | mz_realloc_func m_pRealloc; 170 | void *m_pAlloc_opaque; 171 | 172 | mz_file_read_func m_pRead; 173 | mz_file_write_func m_pWrite; 174 | mz_file_needs_keepalive m_pNeeds_keepalive; 175 | void *m_pIO_opaque; 176 | 177 | mz_zip_internal_state *m_pState; 178 | 179 | } mz_zip_archive; 180 | 181 | typedef struct 182 | { 183 | mz_zip_archive *pZip; 184 | mz_uint flags; 185 | 186 | int status; 187 | 188 | mz_uint64 read_buf_size, read_buf_ofs, read_buf_avail, comp_remaining, out_buf_ofs, cur_file_ofs; 189 | mz_zip_archive_file_stat file_stat; 190 | void *pRead_buf; 191 | void *pWrite_buf; 192 | 193 | size_t out_blk_remain; 194 | 195 | tinfl_decompressor inflator; 196 | 197 | #ifdef MINIZ_DISABLE_ZIP_READER_CRC32_CHECKS 198 | mz_uint padding; 199 | #else 200 | mz_uint file_crc32; 201 | #endif 202 | 203 | } mz_zip_reader_extract_iter_state; 204 | 205 | /* -------- ZIP reading */ 206 | 207 | /* Inits a ZIP archive reader. */ 208 | /* These functions read and validate the archive's central directory. */ 209 | MINIZ_EXPORT mz_bool mz_zip_reader_init(mz_zip_archive *pZip, mz_uint64 size, mz_uint flags); 210 | 211 | MINIZ_EXPORT mz_bool mz_zip_reader_init_mem(mz_zip_archive *pZip, const void *pMem, size_t size, mz_uint flags); 212 | 213 | #ifndef MINIZ_NO_STDIO 214 | /* Read a archive from a disk file. */ 215 | /* file_start_ofs is the file offset where the archive actually begins, or 0. */ 216 | /* actual_archive_size is the true total size of the archive, which may be smaller than the file's actual size on disk. If zero the entire file is treated as the archive. */ 217 | MINIZ_EXPORT mz_bool mz_zip_reader_init_file(mz_zip_archive *pZip, const char *pFilename, mz_uint32 flags); 218 | MINIZ_EXPORT mz_bool mz_zip_reader_init_file_v2(mz_zip_archive *pZip, const char *pFilename, mz_uint flags, mz_uint64 file_start_ofs, mz_uint64 archive_size); 219 | 220 | /* Read an archive from an already opened FILE, beginning at the current file position. */ 221 | /* The archive is assumed to be archive_size bytes long. If archive_size is 0, then the entire rest of the file is assumed to contain the archive. */ 222 | /* The FILE will NOT be closed when mz_zip_reader_end() is called. */ 223 | MINIZ_EXPORT mz_bool mz_zip_reader_init_cfile(mz_zip_archive *pZip, MZ_FILE *pFile, mz_uint64 archive_size, mz_uint flags); 224 | #endif 225 | 226 | /* Ends archive reading, freeing all allocations, and closing the input archive file if mz_zip_reader_init_file() was used. */ 227 | MINIZ_EXPORT mz_bool mz_zip_reader_end(mz_zip_archive *pZip); 228 | 229 | /* -------- ZIP reading or writing */ 230 | 231 | /* Clears a mz_zip_archive struct to all zeros. */ 232 | /* Important: This must be done before passing the struct to any mz_zip functions. */ 233 | MINIZ_EXPORT void mz_zip_zero_struct(mz_zip_archive *pZip); 234 | 235 | MINIZ_EXPORT mz_zip_mode mz_zip_get_mode(mz_zip_archive *pZip); 236 | MINIZ_EXPORT mz_zip_type mz_zip_get_type(mz_zip_archive *pZip); 237 | 238 | /* Returns the total number of files in the archive. */ 239 | MINIZ_EXPORT mz_uint mz_zip_reader_get_num_files(mz_zip_archive *pZip); 240 | 241 | MINIZ_EXPORT mz_uint64 mz_zip_get_archive_size(mz_zip_archive *pZip); 242 | MINIZ_EXPORT mz_uint64 mz_zip_get_archive_file_start_offset(mz_zip_archive *pZip); 243 | MINIZ_EXPORT MZ_FILE *mz_zip_get_cfile(mz_zip_archive *pZip); 244 | 245 | /* Reads n bytes of raw archive data, starting at file offset file_ofs, to pBuf. */ 246 | MINIZ_EXPORT size_t mz_zip_read_archive_data(mz_zip_archive *pZip, mz_uint64 file_ofs, void *pBuf, size_t n); 247 | 248 | /* All mz_zip funcs set the m_last_error field in the mz_zip_archive struct. These functions retrieve/manipulate this field. */ 249 | /* Note that the m_last_error functionality is not thread safe. */ 250 | MINIZ_EXPORT mz_zip_error mz_zip_set_last_error(mz_zip_archive *pZip, mz_zip_error err_num); 251 | MINIZ_EXPORT mz_zip_error mz_zip_peek_last_error(mz_zip_archive *pZip); 252 | MINIZ_EXPORT mz_zip_error mz_zip_clear_last_error(mz_zip_archive *pZip); 253 | MINIZ_EXPORT mz_zip_error mz_zip_get_last_error(mz_zip_archive *pZip); 254 | MINIZ_EXPORT const char *mz_zip_get_error_string(mz_zip_error mz_err); 255 | 256 | /* MZ_TRUE if the archive file entry is a directory entry. */ 257 | MINIZ_EXPORT mz_bool mz_zip_reader_is_file_a_directory(mz_zip_archive *pZip, mz_uint file_index); 258 | 259 | /* MZ_TRUE if the file is encrypted/strong encrypted. */ 260 | MINIZ_EXPORT mz_bool mz_zip_reader_is_file_encrypted(mz_zip_archive *pZip, mz_uint file_index); 261 | 262 | /* MZ_TRUE if the compression method is supported, and the file is not encrypted, and the file is not a compressed patch file. */ 263 | MINIZ_EXPORT mz_bool mz_zip_reader_is_file_supported(mz_zip_archive *pZip, mz_uint file_index); 264 | 265 | /* Retrieves the filename of an archive file entry. */ 266 | /* Returns the number of bytes written to pFilename, or if filename_buf_size is 0 this function returns the number of bytes needed to fully store the filename. */ 267 | MINIZ_EXPORT mz_uint mz_zip_reader_get_filename(mz_zip_archive *pZip, mz_uint file_index, char *pFilename, mz_uint filename_buf_size); 268 | 269 | /* Attempts to locates a file in the archive's central directory. */ 270 | /* Valid flags: MZ_ZIP_FLAG_CASE_SENSITIVE, MZ_ZIP_FLAG_IGNORE_PATH */ 271 | /* Returns -1 if the file cannot be found. */ 272 | MINIZ_EXPORT int mz_zip_reader_locate_file(mz_zip_archive *pZip, const char *pName, const char *pComment, mz_uint flags); 273 | MINIZ_EXPORT mz_bool mz_zip_reader_locate_file_v2(mz_zip_archive *pZip, const char *pName, const char *pComment, mz_uint flags, mz_uint32 *file_index); 274 | 275 | /* Returns detailed information about an archive file entry. */ 276 | MINIZ_EXPORT mz_bool mz_zip_reader_file_stat(mz_zip_archive *pZip, mz_uint file_index, mz_zip_archive_file_stat *pStat); 277 | 278 | /* MZ_TRUE if the file is in zip64 format. */ 279 | /* A file is considered zip64 if it contained a zip64 end of central directory marker, or if it contained any zip64 extended file information fields in the central directory. */ 280 | MINIZ_EXPORT mz_bool mz_zip_is_zip64(mz_zip_archive *pZip); 281 | 282 | /* Returns the total central directory size in bytes. */ 283 | /* The current max supported size is <= MZ_UINT32_MAX. */ 284 | MINIZ_EXPORT size_t mz_zip_get_central_dir_size(mz_zip_archive *pZip); 285 | 286 | /* Extracts a archive file to a memory buffer using no memory allocation. */ 287 | /* There must be at least enough room on the stack to store the inflator's state (~34KB or so). */ 288 | MINIZ_EXPORT mz_bool mz_zip_reader_extract_to_mem_no_alloc(mz_zip_archive *pZip, mz_uint file_index, void *pBuf, size_t buf_size, mz_uint flags, void *pUser_read_buf, size_t user_read_buf_size); 289 | MINIZ_EXPORT mz_bool mz_zip_reader_extract_file_to_mem_no_alloc(mz_zip_archive *pZip, const char *pFilename, void *pBuf, size_t buf_size, mz_uint flags, void *pUser_read_buf, size_t user_read_buf_size); 290 | 291 | /* Extracts a archive file to a memory buffer. */ 292 | MINIZ_EXPORT mz_bool mz_zip_reader_extract_to_mem(mz_zip_archive *pZip, mz_uint file_index, void *pBuf, size_t buf_size, mz_uint flags); 293 | MINIZ_EXPORT mz_bool mz_zip_reader_extract_file_to_mem(mz_zip_archive *pZip, const char *pFilename, void *pBuf, size_t buf_size, mz_uint flags); 294 | 295 | /* Extracts a archive file to a dynamically allocated heap buffer. */ 296 | /* The memory will be allocated via the mz_zip_archive's alloc/realloc functions. */ 297 | /* Returns NULL and sets the last error on failure. */ 298 | MINIZ_EXPORT void *mz_zip_reader_extract_to_heap(mz_zip_archive *pZip, mz_uint file_index, size_t *pSize, mz_uint flags); 299 | MINIZ_EXPORT void *mz_zip_reader_extract_file_to_heap(mz_zip_archive *pZip, const char *pFilename, size_t *pSize, mz_uint flags); 300 | 301 | /* Extracts a archive file using a callback function to output the file's data. */ 302 | MINIZ_EXPORT mz_bool mz_zip_reader_extract_to_callback(mz_zip_archive *pZip, mz_uint file_index, mz_file_write_func pCallback, void *pOpaque, mz_uint flags); 303 | MINIZ_EXPORT mz_bool mz_zip_reader_extract_file_to_callback(mz_zip_archive *pZip, const char *pFilename, mz_file_write_func pCallback, void *pOpaque, mz_uint flags); 304 | 305 | /* Extract a file iteratively */ 306 | MINIZ_EXPORT mz_zip_reader_extract_iter_state* mz_zip_reader_extract_iter_new(mz_zip_archive *pZip, mz_uint file_index, mz_uint flags); 307 | MINIZ_EXPORT mz_zip_reader_extract_iter_state* mz_zip_reader_extract_file_iter_new(mz_zip_archive *pZip, const char *pFilename, mz_uint flags); 308 | MINIZ_EXPORT size_t mz_zip_reader_extract_iter_read(mz_zip_reader_extract_iter_state* pState, void* pvBuf, size_t buf_size); 309 | MINIZ_EXPORT mz_bool mz_zip_reader_extract_iter_free(mz_zip_reader_extract_iter_state* pState); 310 | 311 | #ifndef MINIZ_NO_STDIO 312 | /* Extracts a archive file to a disk file and sets its last accessed and modified times. */ 313 | /* This function only extracts files, not archive directory records. */ 314 | MINIZ_EXPORT mz_bool mz_zip_reader_extract_to_file(mz_zip_archive *pZip, mz_uint file_index, const char *pDst_filename, mz_uint flags); 315 | MINIZ_EXPORT mz_bool mz_zip_reader_extract_file_to_file(mz_zip_archive *pZip, const char *pArchive_filename, const char *pDst_filename, mz_uint flags); 316 | 317 | /* Extracts a archive file starting at the current position in the destination FILE stream. */ 318 | MINIZ_EXPORT mz_bool mz_zip_reader_extract_to_cfile(mz_zip_archive *pZip, mz_uint file_index, MZ_FILE *File, mz_uint flags); 319 | MINIZ_EXPORT mz_bool mz_zip_reader_extract_file_to_cfile(mz_zip_archive *pZip, const char *pArchive_filename, MZ_FILE *pFile, mz_uint flags); 320 | #endif 321 | 322 | #if 0 323 | /* TODO */ 324 | typedef void *mz_zip_streaming_extract_state_ptr; 325 | mz_zip_streaming_extract_state_ptr mz_zip_streaming_extract_begin(mz_zip_archive *pZip, mz_uint file_index, mz_uint flags); 326 | mz_uint64 mz_zip_streaming_extract_get_size(mz_zip_archive *pZip, mz_zip_streaming_extract_state_ptr pState); 327 | mz_uint64 mz_zip_streaming_extract_get_cur_ofs(mz_zip_archive *pZip, mz_zip_streaming_extract_state_ptr pState); 328 | mz_bool mz_zip_streaming_extract_seek(mz_zip_archive *pZip, mz_zip_streaming_extract_state_ptr pState, mz_uint64 new_ofs); 329 | size_t mz_zip_streaming_extract_read(mz_zip_archive *pZip, mz_zip_streaming_extract_state_ptr pState, void *pBuf, size_t buf_size); 330 | mz_bool mz_zip_streaming_extract_end(mz_zip_archive *pZip, mz_zip_streaming_extract_state_ptr pState); 331 | #endif 332 | 333 | /* This function compares the archive's local headers, the optional local zip64 extended information block, and the optional descriptor following the compressed data vs. the data in the central directory. */ 334 | /* It also validates that each file can be successfully uncompressed unless the MZ_ZIP_FLAG_VALIDATE_HEADERS_ONLY is specified. */ 335 | MINIZ_EXPORT mz_bool mz_zip_validate_file(mz_zip_archive *pZip, mz_uint file_index, mz_uint flags); 336 | 337 | /* Validates an entire archive by calling mz_zip_validate_file() on each file. */ 338 | MINIZ_EXPORT mz_bool mz_zip_validate_archive(mz_zip_archive *pZip, mz_uint flags); 339 | 340 | /* Misc utils/helpers, valid for ZIP reading or writing */ 341 | MINIZ_EXPORT mz_bool mz_zip_validate_mem_archive(const void *pMem, size_t size, mz_uint flags, mz_zip_error *pErr); 342 | #ifndef MINIZ_NO_STDIO 343 | MINIZ_EXPORT mz_bool mz_zip_validate_file_archive(const char *pFilename, mz_uint flags, mz_zip_error *pErr); 344 | #endif 345 | 346 | /* Universal end function - calls either mz_zip_reader_end() or mz_zip_writer_end(). */ 347 | MINIZ_EXPORT mz_bool mz_zip_end(mz_zip_archive *pZip); 348 | 349 | /* -------- ZIP writing */ 350 | 351 | #ifndef MINIZ_NO_ARCHIVE_WRITING_APIS 352 | 353 | /* Inits a ZIP archive writer. */ 354 | /*Set pZip->m_pWrite (and pZip->m_pIO_opaque) before calling mz_zip_writer_init or mz_zip_writer_init_v2*/ 355 | /*The output is streamable, i.e. file_ofs in mz_file_write_func always increases only by n*/ 356 | MINIZ_EXPORT mz_bool mz_zip_writer_init(mz_zip_archive *pZip, mz_uint64 existing_size); 357 | MINIZ_EXPORT mz_bool mz_zip_writer_init_v2(mz_zip_archive *pZip, mz_uint64 existing_size, mz_uint flags); 358 | 359 | MINIZ_EXPORT mz_bool mz_zip_writer_init_heap(mz_zip_archive *pZip, size_t size_to_reserve_at_beginning, size_t initial_allocation_size); 360 | MINIZ_EXPORT mz_bool mz_zip_writer_init_heap_v2(mz_zip_archive *pZip, size_t size_to_reserve_at_beginning, size_t initial_allocation_size, mz_uint flags); 361 | 362 | #ifndef MINIZ_NO_STDIO 363 | MINIZ_EXPORT mz_bool mz_zip_writer_init_file(mz_zip_archive *pZip, const char *pFilename, mz_uint64 size_to_reserve_at_beginning); 364 | MINIZ_EXPORT mz_bool mz_zip_writer_init_file_v2(mz_zip_archive *pZip, const char *pFilename, mz_uint64 size_to_reserve_at_beginning, mz_uint flags); 365 | MINIZ_EXPORT mz_bool mz_zip_writer_init_cfile(mz_zip_archive *pZip, MZ_FILE *pFile, mz_uint flags); 366 | #endif 367 | 368 | /* Converts a ZIP archive reader object into a writer object, to allow efficient in-place file appends to occur on an existing archive. */ 369 | /* For archives opened using mz_zip_reader_init_file, pFilename must be the archive's filename so it can be reopened for writing. If the file can't be reopened, mz_zip_reader_end() will be called. */ 370 | /* For archives opened using mz_zip_reader_init_mem, the memory block must be growable using the realloc callback (which defaults to realloc unless you've overridden it). */ 371 | /* Finally, for archives opened using mz_zip_reader_init, the mz_zip_archive's user provided m_pWrite function cannot be NULL. */ 372 | /* Note: In-place archive modification is not recommended unless you know what you're doing, because if execution stops or something goes wrong before */ 373 | /* the archive is finalized the file's central directory will be hosed. */ 374 | MINIZ_EXPORT mz_bool mz_zip_writer_init_from_reader(mz_zip_archive *pZip, const char *pFilename); 375 | MINIZ_EXPORT mz_bool mz_zip_writer_init_from_reader_v2(mz_zip_archive *pZip, const char *pFilename, mz_uint flags); 376 | 377 | /* Adds the contents of a memory buffer to an archive. These functions record the current local time into the archive. */ 378 | /* To add a directory entry, call this method with an archive name ending in a forwardslash with an empty buffer. */ 379 | /* level_and_flags - compression level (0-10, see MZ_BEST_SPEED, MZ_BEST_COMPRESSION, etc.) logically OR'd with zero or more mz_zip_flags, or just set to MZ_DEFAULT_COMPRESSION. */ 380 | MINIZ_EXPORT mz_bool mz_zip_writer_add_mem(mz_zip_archive *pZip, const char *pArchive_name, const void *pBuf, size_t buf_size, mz_uint level_and_flags); 381 | 382 | /* Like mz_zip_writer_add_mem(), except you can specify a file comment field, and optionally supply the function with already compressed data. */ 383 | /* uncomp_size/uncomp_crc32 are only used if the MZ_ZIP_FLAG_COMPRESSED_DATA flag is specified. */ 384 | MINIZ_EXPORT mz_bool mz_zip_writer_add_mem_ex(mz_zip_archive *pZip, const char *pArchive_name, const void *pBuf, size_t buf_size, const void *pComment, mz_uint16 comment_size, mz_uint level_and_flags, 385 | mz_uint64 uncomp_size, mz_uint32 uncomp_crc32); 386 | 387 | MINIZ_EXPORT mz_bool mz_zip_writer_add_mem_ex_v2(mz_zip_archive *pZip, const char *pArchive_name, const void *pBuf, size_t buf_size, const void *pComment, mz_uint16 comment_size, mz_uint level_and_flags, 388 | mz_uint64 uncomp_size, mz_uint32 uncomp_crc32, MZ_TIME_T *last_modified, const char *user_extra_data_local, mz_uint user_extra_data_local_len, 389 | const char *user_extra_data_central, mz_uint user_extra_data_central_len); 390 | 391 | /* Adds the contents of a file to an archive. This function also records the disk file's modified time into the archive. */ 392 | /* File data is supplied via a read callback function. User mz_zip_writer_add_(c)file to add a file directly.*/ 393 | MINIZ_EXPORT mz_bool mz_zip_writer_add_read_buf_callback(mz_zip_archive *pZip, const char *pArchive_name, mz_file_read_func read_callback, void* callback_opaque, mz_uint64 max_size, 394 | const MZ_TIME_T *pFile_time, const void *pComment, mz_uint16 comment_size, mz_uint level_and_flags, const char *user_extra_data_local, mz_uint user_extra_data_local_len, 395 | const char *user_extra_data_central, mz_uint user_extra_data_central_len); 396 | 397 | 398 | #ifndef MINIZ_NO_STDIO 399 | /* Adds the contents of a disk file to an archive. This function also records the disk file's modified time into the archive. */ 400 | /* level_and_flags - compression level (0-10, see MZ_BEST_SPEED, MZ_BEST_COMPRESSION, etc.) logically OR'd with zero or more mz_zip_flags, or just set to MZ_DEFAULT_COMPRESSION. */ 401 | MINIZ_EXPORT mz_bool mz_zip_writer_add_file(mz_zip_archive *pZip, const char *pArchive_name, const char *pSrc_filename, const void *pComment, mz_uint16 comment_size, mz_uint level_and_flags); 402 | 403 | /* Like mz_zip_writer_add_file(), except the file data is read from the specified FILE stream. */ 404 | MINIZ_EXPORT mz_bool mz_zip_writer_add_cfile(mz_zip_archive *pZip, const char *pArchive_name, MZ_FILE *pSrc_file, mz_uint64 max_size, 405 | const MZ_TIME_T *pFile_time, const void *pComment, mz_uint16 comment_size, mz_uint level_and_flags, const char *user_extra_data_local, mz_uint user_extra_data_local_len, 406 | const char *user_extra_data_central, mz_uint user_extra_data_central_len); 407 | #endif 408 | 409 | /* Adds a file to an archive by fully cloning the data from another archive. */ 410 | /* This function fully clones the source file's compressed data (no recompression), along with its full filename, extra data (it may add or modify the zip64 local header extra data field), and the optional descriptor following the compressed data. */ 411 | MINIZ_EXPORT mz_bool mz_zip_writer_add_from_zip_reader(mz_zip_archive *pZip, mz_zip_archive *pSource_zip, mz_uint src_file_index); 412 | 413 | /* Finalizes the archive by writing the central directory records followed by the end of central directory record. */ 414 | /* After an archive is finalized, the only valid call on the mz_zip_archive struct is mz_zip_writer_end(). */ 415 | /* An archive must be manually finalized by calling this function for it to be valid. */ 416 | MINIZ_EXPORT mz_bool mz_zip_writer_finalize_archive(mz_zip_archive *pZip); 417 | 418 | /* Finalizes a heap archive, returning a pointer to the heap block and its size. */ 419 | /* The heap block will be allocated using the mz_zip_archive's alloc/realloc callbacks. */ 420 | MINIZ_EXPORT mz_bool mz_zip_writer_finalize_heap_archive(mz_zip_archive *pZip, void **ppBuf, size_t *pSize); 421 | 422 | /* Ends archive writing, freeing all allocations, and closing the output file if mz_zip_writer_init_file() was used. */ 423 | /* Note for the archive to be valid, it *must* have been finalized before ending (this function will not do it for you). */ 424 | MINIZ_EXPORT mz_bool mz_zip_writer_end(mz_zip_archive *pZip); 425 | 426 | /* -------- Misc. high-level helper functions: */ 427 | 428 | /* mz_zip_add_mem_to_archive_file_in_place() efficiently (but not atomically) appends a memory blob to a ZIP archive. */ 429 | /* Note this is NOT a fully safe operation. If it crashes or dies in some way your archive can be left in a screwed up state (without a central directory). */ 430 | /* level_and_flags - compression level (0-10, see MZ_BEST_SPEED, MZ_BEST_COMPRESSION, etc.) logically OR'd with zero or more mz_zip_flags, or just set to MZ_DEFAULT_COMPRESSION. */ 431 | /* TODO: Perhaps add an option to leave the existing central dir in place in case the add dies? We could then truncate the file (so the old central dir would be at the end) if something goes wrong. */ 432 | MINIZ_EXPORT mz_bool mz_zip_add_mem_to_archive_file_in_place(const char *pZip_filename, const char *pArchive_name, const void *pBuf, size_t buf_size, const void *pComment, mz_uint16 comment_size, mz_uint level_and_flags); 433 | MINIZ_EXPORT mz_bool mz_zip_add_mem_to_archive_file_in_place_v2(const char *pZip_filename, const char *pArchive_name, const void *pBuf, size_t buf_size, const void *pComment, mz_uint16 comment_size, mz_uint level_and_flags, mz_zip_error *pErr); 434 | 435 | #ifndef MINIZ_NO_STDIO 436 | /* Reads a single file from an archive into a heap block. */ 437 | /* If pComment is not NULL, only the file with the specified comment will be extracted. */ 438 | /* Returns NULL on failure. */ 439 | MINIZ_EXPORT void *mz_zip_extract_archive_file_to_heap(const char *pZip_filename, const char *pArchive_name, size_t *pSize, mz_uint flags); 440 | MINIZ_EXPORT void *mz_zip_extract_archive_file_to_heap_v2(const char *pZip_filename, const char *pArchive_name, const char *pComment, size_t *pSize, mz_uint flags, mz_zip_error *pErr); 441 | #endif 442 | 443 | #endif /* #ifndef MINIZ_NO_ARCHIVE_WRITING_APIS */ 444 | 445 | #ifdef __cplusplus 446 | } 447 | #endif 448 | 449 | #endif /* MINIZ_NO_ARCHIVE_APIS */ 450 | -------------------------------------------------------------------------------- /readme.md: -------------------------------------------------------------------------------- 1 | ## Miniz 2 | 3 | Miniz is a lossless, high performance data compression library in a single source file that implements the zlib (RFC 1950) and Deflate (RFC 1951) compressed data format specification standards. It supports the most commonly used functions exported by the zlib library, but is a completely independent implementation so zlib's licensing requirements do not apply. Miniz also contains simple to use functions for writing .PNG format image files and reading/writing/appending .ZIP format archives. Miniz's compression speed has been tuned to be comparable to zlib's, and it also has a specialized real-time compressor function designed to compare well against fastlz/minilzo. 4 | 5 | ## Usage 6 | 7 | Releases are available at the [releases page](https://github.com/richgel999/miniz/releases) as a pair of `miniz.c`/`miniz.h` files which can be simply added to a project. To create this file pair the different source and header files are [amalgamated](https://www.sqlite.org/amalgamation.html) during build. Alternatively use as cmake or meson module (or build system of your choice). 8 | 9 | ## Features 10 | 11 | * MIT licensed 12 | * A portable, single source and header file library written in plain C. Tested with GCC, clang and Visual Studio. 13 | * Easily tuned and trimmed down by defines 14 | * A drop-in replacement for zlib's most used API's (tested in several open source projects that use zlib, such as libpng and libzip). 15 | * Fills a single threaded performance vs. compression ratio gap between several popular real-time compressors and zlib. For example, at level 1, miniz.c compresses around 5-9% better than minilzo, but is approx. 35% slower. At levels 2-9, miniz.c is designed to compare favorably against zlib's ratio and speed. See the miniz performance comparison page for example timings. 16 | * Not a block based compressor: miniz.c fully supports stream based processing using a coroutine-style implementation. The zlib-style API functions can be called a single byte at a time if that's all you've got. 17 | * Easy to use. The low-level compressor (tdefl) and decompressor (tinfl) have simple state structs which can be saved/restored as needed with simple memcpy's. The low-level codec API's don't use the heap in any way. 18 | * Entire inflater (including optional zlib header parsing and Adler-32 checking) is implemented in a single function as a coroutine, which is separately available in a small (~550 line) source file: miniz_tinfl.c 19 | * A fairly complete (but totally optional) set of .ZIP archive manipulation and extraction API's. The archive functionality is intended to solve common problems encountered in embedded, mobile, or game development situations. (The archive API's are purposely just powerful enough to write an entire archiver given a bit of additional higher-level logic.) 20 | 21 | ## Building miniz - Using vcpkg 22 | 23 | You can download and install miniz using the [vcpkg](https://github.com/Microsoft/vcpkg) dependency manager: 24 | 25 | git clone https://github.com/Microsoft/vcpkg.git 26 | cd vcpkg 27 | ./bootstrap-vcpkg.sh 28 | ./vcpkg integrate install 29 | ./vcpkg install miniz 30 | 31 | The miniz port in vcpkg is kept up to date by Microsoft team members and community contributors. If the version is out of date, please [create an issue or pull request](https://github.com/Microsoft/vcpkg) on the vcpkg repository. 32 | 33 | ## Known Problems 34 | 35 | * No support for encrypted archives. Not sure how useful this stuff is in practice. 36 | * Minimal documentation. The assumption is that the user is already familiar with the basic zlib API. I need to write an API wiki - for now I've tried to place key comments before each enum/API, and I've included 6 examples that demonstrate how to use the module's major features. 37 | 38 | ## Special Thanks 39 | 40 | Thanks to Alex Evans for the PNG writer function. Also, thanks to Paul Holden and Thorsten Scheuermann for feedback and testing, Matt Pritchard for all his encouragement, and Sean Barrett's various public domain libraries for inspiration (and encouraging me to write miniz.c in C, which was much more enjoyable and less painful than I thought it would be considering I've been programming in C++ for so long). 41 | 42 | Thanks to Bruce Dawson for reporting a problem with the level_and_flags archive API parameter (which is fixed in v1.12) and general feedback, and Janez Zemva for indirectly encouraging me into writing more examples. 43 | 44 | ## Patents 45 | 46 | I was recently asked if miniz avoids patent issues. miniz purposely uses the same core algorithms as the ones used by zlib. The compressor uses vanilla hash chaining as described [here](https://datatracker.ietf.org/doc/html/rfc1951#section-4). Also see the [gzip FAQ](https://web.archive.org/web/20160308045258/http://www.gzip.org/#faq11). In my opinion, if miniz falls prey to a patent attack then zlib/gzip are likely to be at serious risk too. 47 | -------------------------------------------------------------------------------- /test.sh: -------------------------------------------------------------------------------- 1 | #!/bin/bash 2 | 3 | set -e 4 | 5 | . amalgamate.sh 6 | 7 | cat << "EOF" > miniz_export.h 8 | #ifndef MINIZ_EXPORT 9 | #define MINIZ_EXPORT 10 | #endif 11 | EOF 12 | g++ tests/miniz_tester.cpp tests/timer.cpp amalgamation/miniz.c -o miniz_tester -I. -ggdb -O2 13 | 14 | for i in 1 2 3 4 5 6 15 | do 16 | gcc examples/example$i.c amalgamation/miniz.c -o example$i -lm -I. -ggdb 17 | done 18 | 19 | mkdir -p test_scratch 20 | if ! test -e "test_scratch/linux-4.8.11" 21 | then 22 | cd test_scratch 23 | wget https://cdn.kernel.org/pub/linux/kernel/v4.x/linux-4.8.11.tar.xz -O linux-4.8.11.tar.xz 24 | tar xf linux-4.8.11.tar.xz 25 | cd .. 26 | fi 27 | 28 | cd test_scratch 29 | ../miniz_tester -v a linux-4.8.11 30 | ../miniz_tester -v -r a linux-4.8.11 31 | ../miniz_tester -v -b -r a linux-4.8.11 32 | ../miniz_tester -v -a a linux-4.8.11 33 | 34 | mkdir -p large_file 35 | truncate -s 5G large_file/lf 36 | ../miniz_tester -v -a a large_file 37 | -------------------------------------------------------------------------------- /tests/checksum_fuzzer.c: -------------------------------------------------------------------------------- 1 | /* Derived from zlib fuzzers at http://github.com/google/oss-fuzz/tree/master/projects/zlib, 2 | * see ossfuzz.sh for full license text. 3 | */ 4 | 5 | #include 6 | #include 7 | #include 8 | 9 | #include "miniz.h" 10 | 11 | static const size_t kMaxSize = 1024 * 1024; 12 | 13 | int LLVMFuzzerTestOneInput(const uint8_t *data, size_t dataLen) 14 | { 15 | /* Discard inputs larger than 1Mb. */ 16 | if (dataLen < 1 || dataLen > kMaxSize) return 0; 17 | 18 | uint32_t crc = crc32(0L, NULL, 0); 19 | uint32_t adler = adler32(0L, NULL, 0); 20 | 21 | crc = crc32(crc, data, (uint32_t) dataLen); 22 | adler = adler32(adler, data, (uint32_t) dataLen); 23 | 24 | return 0; 25 | } 26 | -------------------------------------------------------------------------------- /tests/compress_fuzzer.c: -------------------------------------------------------------------------------- 1 | /* Derived from zlib fuzzers at http://github.com/google/oss-fuzz/tree/master/projects/zlib, 2 | * see ossfuzz.sh for full license text. 3 | */ 4 | 5 | #include 6 | #include 7 | #include 8 | #include 9 | #include 10 | #include 11 | #include 12 | #include "miniz.h" 13 | 14 | static const uint8_t *data; 15 | static size_t dataLen; 16 | 17 | static void check_compress_level(uint8_t *compr, size_t comprLen, 18 | uint8_t *uncompr, size_t uncomprLen, 19 | int level) 20 | { 21 | compress2(compr, &comprLen, data, dataLen, level); 22 | uncompress(uncompr, &uncomprLen, compr, comprLen); 23 | 24 | /* Make sure compress + uncompress gives back the input data. */ 25 | assert(dataLen == uncomprLen); 26 | assert(0 == memcmp(data, uncompr, dataLen)); 27 | } 28 | 29 | #define put_byte(s, i, c) {s[i] = (unsigned char)(c);} 30 | 31 | static void write_zlib_header(uint8_t *s) 32 | { 33 | unsigned level_flags = 0; /* compression level (0..3) */ 34 | unsigned w_bits = 8; /* window size log2(w_size) (8..16) */ 35 | unsigned int header = (Z_DEFLATED + ((w_bits-8)<<4)) << 8; 36 | header |= (level_flags << 6); 37 | 38 | header += 31 - (header % 31); 39 | 40 | /* s is guaranteed to be longer than 2 bytes. */ 41 | put_byte(s, 0, (unsigned char)(header >> 8)); 42 | put_byte(s, 1, (unsigned char)(header & 0xff)); 43 | } 44 | 45 | static void check_decompress(uint8_t *compr, size_t comprLen) 46 | { 47 | /* We need to write a valid zlib header of size two bytes. Copy the input data 48 | in a larger buffer. Do not modify the input data to avoid libFuzzer error: 49 | fuzz target overwrites its const input. */ 50 | size_t copyLen = dataLen + 2; 51 | uint8_t *copy = malloc(copyLen); 52 | memcpy(copy + 2, data, dataLen); 53 | write_zlib_header(copy); 54 | 55 | uncompress(compr, &comprLen, copy, copyLen); 56 | free(copy); 57 | } 58 | 59 | int LLVMFuzzerTestOneInput(const uint8_t *d, size_t size) 60 | { 61 | /* compressBound does not provide enough space for low compression levels. */ 62 | size_t comprLen = 100 + 2 * compressBound(size); 63 | size_t uncomprLen = size; 64 | uint8_t *compr, *uncompr; 65 | 66 | /* Discard inputs larger than 1Mb. */ 67 | static size_t kMaxSize = 1024 * 1024; 68 | 69 | if (size < 1 || size > kMaxSize) 70 | return 0; 71 | 72 | data = d; 73 | dataLen = size; 74 | compr = calloc(1, comprLen); 75 | uncompr = calloc(1, uncomprLen); 76 | 77 | check_compress_level(compr, comprLen, uncompr, uncomprLen, 1); 78 | check_compress_level(compr, comprLen, uncompr, uncomprLen, 3); 79 | check_compress_level(compr, comprLen, uncompr, uncomprLen, 6); 80 | check_compress_level(compr, comprLen, uncompr, uncomprLen, 7); 81 | 82 | check_decompress(compr, comprLen); 83 | 84 | free(compr); 85 | free(uncompr); 86 | 87 | return 0; 88 | } 89 | -------------------------------------------------------------------------------- /tests/flush_fuzzer.c: -------------------------------------------------------------------------------- 1 | /* Derived from zlib fuzzers at http://github.com/google/oss-fuzz/tree/master/projects/zlib, 2 | * see ossfuzz.sh for full license text. 3 | */ 4 | 5 | #include 6 | #include 7 | #include 8 | #include 9 | #include 10 | #include 11 | 12 | #include "miniz.h" 13 | 14 | #define CHECK_ERR(err, msg) { \ 15 | if (err != Z_OK) { \ 16 | fprintf(stderr, "%s error: %d\n", msg, err); \ 17 | exit(1); \ 18 | } \ 19 | } 20 | 21 | static const uint8_t *data; 22 | static size_t dataLen; 23 | static alloc_func zalloc = NULL; 24 | static free_func zfree = NULL; 25 | 26 | 27 | void test_flush(unsigned char *compr, size_t *comprLen) 28 | { 29 | z_stream c_stream; /* compression stream */ 30 | int err; 31 | unsigned int len = dataLen; 32 | 33 | c_stream.zalloc = zalloc; 34 | c_stream.zfree = zfree; 35 | c_stream.opaque = NULL; 36 | 37 | err = deflateInit(&c_stream, Z_DEFAULT_COMPRESSION); 38 | CHECK_ERR(err, "deflateInit"); 39 | 40 | c_stream.next_in = (Bytef *)data; 41 | c_stream.next_out = compr; 42 | c_stream.avail_in = 3; 43 | c_stream.avail_out = (unsigned int)*comprLen; 44 | err = deflate(&c_stream, Z_FULL_FLUSH); 45 | CHECK_ERR(err, "deflate flush 1"); 46 | 47 | compr[3]++; /* force an error in first compressed block */ 48 | c_stream.avail_in = len - 3; 49 | 50 | err = deflate(&c_stream, Z_FINISH); 51 | 52 | if (err != Z_STREAM_END) 53 | { 54 | CHECK_ERR(err, "deflate flush 2"); 55 | } 56 | 57 | err = deflateEnd(&c_stream); 58 | CHECK_ERR(err, "deflateEnd"); 59 | 60 | *comprLen = (size_t)c_stream.total_out; 61 | } 62 | 63 | int LLVMFuzzerTestOneInput(const uint8_t *d, size_t size) 64 | { 65 | size_t comprLen = 100 + 2 * compressBound(size); 66 | size_t uncomprLen = size; 67 | uint8_t *compr, *uncompr; 68 | 69 | /* Discard inputs larger than 1Mb. */ 70 | static const size_t kMaxSize = 1024 * 1024; 71 | 72 | /* This test requires at least 3 bytes of input data. */ 73 | if (size <= 3 || size > kMaxSize) 74 | return 0; 75 | 76 | data = d; 77 | dataLen = size; 78 | compr = calloc(1, comprLen); 79 | uncompr = calloc(1, uncomprLen); 80 | 81 | test_flush(compr, &comprLen); 82 | 83 | free(compr); 84 | free(uncompr); 85 | 86 | return 0; 87 | } 88 | -------------------------------------------------------------------------------- /tests/fuzz_main.c: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | 5 | /* Fuzz target entry point for building without libFuzzer */ 6 | 7 | int LLVMFuzzerTestOneInput(const uint8_t *d, size_t size); 8 | 9 | int main(int argc, char **argv) 10 | { 11 | FILE *f; 12 | char *buf = NULL; 13 | long siz_buf; 14 | 15 | if(argc < 2) 16 | { 17 | fprintf(stderr, "no input file\n"); 18 | goto err; 19 | } 20 | 21 | f = fopen(argv[1], "rb"); 22 | if(f == NULL) 23 | { 24 | fprintf(stderr, "error opening input file %s\n", argv[1]); 25 | goto err; 26 | } 27 | 28 | fseek(f, 0, SEEK_END); 29 | 30 | siz_buf = ftell(f); 31 | rewind(f); 32 | 33 | if(siz_buf < 1) goto err; 34 | 35 | buf = (char*)malloc(siz_buf); 36 | if(buf == NULL) 37 | { 38 | fprintf(stderr, "malloc() failed\n"); 39 | goto err; 40 | } 41 | 42 | if(fread(buf, siz_buf, 1, f) != 1) 43 | { 44 | fprintf(stderr, "fread() failed\n"); 45 | goto err; 46 | } 47 | 48 | (void)LLVMFuzzerTestOneInput((uint8_t*)buf, siz_buf); 49 | 50 | err: 51 | free(buf); 52 | 53 | return 0; 54 | } -------------------------------------------------------------------------------- /tests/large_fuzzer.c: -------------------------------------------------------------------------------- 1 | /* Derived from zlib fuzzers at http://github.com/google/oss-fuzz/tree/master/projects/zlib, 2 | * see ossfuzz.sh for full license text. 3 | */ 4 | 5 | #include 6 | #include 7 | #include 8 | #include 9 | #include 10 | #include 11 | 12 | #include "miniz.h" 13 | 14 | #define CHECK_ERR(err, msg) { \ 15 | if (err != Z_OK) { \ 16 | fprintf(stderr, "%s error: %d\n", msg, err); \ 17 | exit(1); \ 18 | } \ 19 | } 20 | 21 | static const uint8_t *data; 22 | static size_t dataLen; 23 | static alloc_func zalloc = NULL; 24 | static free_func zfree = NULL; 25 | static unsigned int diff; 26 | 27 | /* Test deflate() with large buffers and dynamic change of compression level */ 28 | void test_large_deflate(unsigned char *compr, size_t comprLen, 29 | unsigned char *uncompr, size_t uncomprLen) 30 | { 31 | z_stream c_stream; /* compression stream */ 32 | int err; 33 | 34 | c_stream.zalloc = zalloc; 35 | c_stream.zfree = zfree; 36 | c_stream.opaque = NULL; 37 | 38 | err = deflateInit(&c_stream, Z_BEST_COMPRESSION); 39 | CHECK_ERR(err, "deflateInit"); 40 | 41 | c_stream.next_out = compr; 42 | c_stream.avail_out = (unsigned int)comprLen; 43 | 44 | /* At this point, uncompr is still mostly zeroes, so it should compress 45 | * very well: 46 | */ 47 | c_stream.next_in = uncompr; 48 | c_stream.avail_in = (unsigned int)uncomprLen; 49 | err = deflate(&c_stream, Z_NO_FLUSH); 50 | CHECK_ERR(err, "deflate large 1"); 51 | 52 | if (c_stream.avail_in != 0) 53 | { 54 | fprintf(stderr, "deflate not greedy\n"); 55 | exit(1); 56 | } 57 | 58 | /* Feed in already compressed data: */ 59 | c_stream.next_in = compr; 60 | diff = (unsigned int)(c_stream.next_out - compr); 61 | c_stream.avail_in = diff; 62 | 63 | deflate(&c_stream, Z_NO_FLUSH); 64 | err = deflate(&c_stream, Z_FINISH); 65 | 66 | if (err != Z_STREAM_END) 67 | { 68 | fprintf(stderr, "deflate large should report Z_STREAM_END\n"); 69 | exit(1); 70 | } 71 | err = deflateEnd(&c_stream); 72 | CHECK_ERR(err, "deflateEnd"); 73 | } 74 | 75 | /* Test inflate() with large buffers */ 76 | void test_large_inflate(unsigned char *compr, size_t comprLen, 77 | unsigned char *uncompr, size_t uncomprLen) 78 | { 79 | int err; 80 | z_stream d_stream; /* decompression stream */ 81 | 82 | d_stream.zalloc = zalloc; 83 | d_stream.zfree = zfree; 84 | d_stream.opaque = NULL; 85 | 86 | d_stream.next_in = compr; 87 | d_stream.avail_in = (unsigned int)comprLen; 88 | 89 | err = inflateInit(&d_stream); 90 | CHECK_ERR(err, "inflateInit"); 91 | 92 | for (;;) 93 | { 94 | d_stream.next_out = uncompr; /* discard the output */ 95 | d_stream.avail_out = (unsigned int)uncomprLen; 96 | err = inflate(&d_stream, Z_NO_FLUSH); 97 | if (err == Z_STREAM_END) break; 98 | 99 | CHECK_ERR(err, "large inflate"); 100 | } 101 | 102 | err = inflateEnd(&d_stream); 103 | CHECK_ERR(err, "inflateEnd"); 104 | } 105 | 106 | int LLVMFuzzerTestOneInput(const uint8_t *d, size_t size) 107 | { 108 | size_t comprLen = 100 + 3 * size; 109 | size_t uncomprLen = comprLen; 110 | uint8_t *compr, *uncompr; 111 | 112 | /* Discard inputs larger than 512Kb. */ 113 | static size_t kMaxSize = 512 * 1024; 114 | 115 | if (size < 1 || size > kMaxSize) 116 | return 0; 117 | 118 | data = d; 119 | dataLen = size; 120 | compr = calloc(1, comprLen); 121 | uncompr = calloc(1, uncomprLen); 122 | 123 | test_large_deflate(compr, comprLen, uncompr, uncomprLen); 124 | test_large_inflate(compr, comprLen, uncompr, uncomprLen); 125 | 126 | free(compr); 127 | free(uncompr); 128 | 129 | return 0; 130 | } 131 | -------------------------------------------------------------------------------- /tests/main.cpp: -------------------------------------------------------------------------------- 1 | #include "catch_amalgamated.hpp" 2 | #include "../miniz.h" 3 | #include 4 | #include 5 | 6 | #ifdef _WIN32 7 | #define unlink _unlink 8 | #endif 9 | 10 | bool create_test_zip() 11 | { 12 | unlink("test.zip"); 13 | mz_zip_archive zip_archive = {}; 14 | auto b = mz_zip_writer_init_file(&zip_archive, "test.zip", 0); 15 | if (!b) 16 | return false; 17 | 18 | b = mz_zip_writer_add_mem(&zip_archive, "test.txt", "foo", 3, MZ_DEFAULT_COMPRESSION); 19 | if (!b) 20 | return false; 21 | 22 | b = mz_zip_writer_finalize_archive(&zip_archive); 23 | if (!b) 24 | return false; 25 | 26 | b = mz_zip_writer_end(&zip_archive); 27 | if (!b) 28 | return false; 29 | 30 | return true; 31 | } 32 | 33 | TEST_CASE("Zip writer tests") 34 | { 35 | auto b = create_test_zip(); 36 | REQUIRE(b); 37 | 38 | SECTION("Test test.txt content correct") 39 | { 40 | mz_zip_archive zip_archive = {}; 41 | 42 | auto b = mz_zip_reader_init_file(&zip_archive, "test.zip", 0); 43 | REQUIRE(b); 44 | 45 | size_t content_size; 46 | auto content = mz_zip_reader_extract_file_to_heap(&zip_archive, "test.txt", &content_size, 0); 47 | 48 | std::string_view content_view(reinterpret_cast(content), content_size); 49 | 50 | REQUIRE(content_view == "foo"); 51 | REQUIRE(content_view.size() == 3); 52 | 53 | free(content); 54 | } 55 | } 56 | 57 | TEST_CASE("Tinfl / tdefl tests") 58 | { 59 | SECTION("simple_test1") 60 | { 61 | size_t cmp_len = 0; 62 | 63 | const char *p = "This is a test.This is a test.This is a test.1234567This is a test.This is a test.123456"; 64 | size_t uncomp_len = strlen(p); 65 | 66 | void *pComp_data = tdefl_compress_mem_to_heap(p, uncomp_len, &cmp_len, TDEFL_WRITE_ZLIB_HEADER); 67 | REQUIRE(pComp_data); 68 | 69 | size_t decomp_len = 0; 70 | void *pDecomp_data = tinfl_decompress_mem_to_heap(pComp_data, cmp_len, &decomp_len, TINFL_FLAG_PARSE_ZLIB_HEADER); 71 | 72 | REQUIRE(pDecomp_data); 73 | REQUIRE(decomp_len == uncomp_len); 74 | REQUIRE(memcmp(pDecomp_data, p, uncomp_len) == 0); 75 | 76 | free(pComp_data); 77 | free(pDecomp_data); 78 | } 79 | 80 | SECTION("simple_test2") 81 | { 82 | uint8_t cmp_buf[1024], decomp_buf[1024]; 83 | uLong cmp_len = sizeof(cmp_buf); 84 | 85 | const char *p = "This is a test.This is a test.This is a test.1234567This is a test.This is a test.123456"; 86 | uLong uncomp_len = (uLong)strlen(p); 87 | 88 | int status = compress(cmp_buf, &cmp_len, (const uint8_t *)p, uncomp_len); 89 | REQUIRE(status == Z_OK); 90 | 91 | REQUIRE(cmp_len <= compressBound(uncomp_len)); 92 | 93 | uLong decomp_len = sizeof(decomp_buf); 94 | status = uncompress(decomp_buf, &decomp_len, cmp_buf, cmp_len); 95 | ; 96 | 97 | REQUIRE(status == Z_OK); 98 | REQUIRE(decomp_len == uncomp_len); 99 | REQUIRE(memcmp(decomp_buf, p, uncomp_len) == 0); 100 | } 101 | } -------------------------------------------------------------------------------- /tests/ossfuzz.sh: -------------------------------------------------------------------------------- 1 | #!/bin/bash -eu 2 | # Copyright 2020 Google Inc. 3 | # 4 | # Licensed under the Apache License, Version 2.0 (the "License"); 5 | # you may not use this file except in compliance with the License. 6 | # You may obtain a copy of the License at 7 | # 8 | # http://www.apache.org/licenses/LICENSE-2.0 9 | # 10 | # Unless required by applicable law or agreed to in writing, software 11 | # distributed under the License is distributed on an "AS IS" BASIS, 12 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | # See the License for the specific language governing permissions and 14 | # limitations under the License. 15 | # 16 | ################################################################################ 17 | 18 | # This script is meant to be run by 19 | # https://github.com/google/oss-fuzz/blob/master/projects/miniz/Dockerfile 20 | 21 | mkdir build 22 | cd build 23 | cmake .. -DAMALGAMATE_SOURCES=ON -DBUILD_SHARED_LIBS=OFF -DBUILD_FUZZERS=ON 24 | make -j$(nproc) 25 | cd .. 26 | 27 | zip $OUT/seed_corpus.zip *.* 28 | 29 | for f in $(find $SRC -name '*_fuzzer.c'); do 30 | b=$(basename -s .c $f) 31 | $CC $CFLAGS -Ibuild/amalgamation $f -c -o /tmp/$b.o 32 | $CXX $CXXFLAGS -stdlib=libc++ -Ibuild/amalgamation /tmp/$b.o -o $OUT/$b $LIB_FUZZING_ENGINE ./build/libminiz.a 33 | rm -f /tmp/$b.o 34 | ln -sf $OUT/seed_corpus.zip $OUT/${b}_seed_corpus.zip 35 | done 36 | 37 | 38 | # Add .zip input file for the zip fuzzer 39 | rm -f $OUT/zip_fuzzer_seed_corpus.zip 40 | zip $OUT/zip_fuzzer_seed_corpus.zip $OUT/seed_corpus.zip 41 | 42 | cp tests/zip.dict $OUT/zip_fuzzer.dict -------------------------------------------------------------------------------- /tests/small_fuzzer.c: -------------------------------------------------------------------------------- 1 | /* Derived from zlib fuzzers at http://github.com/google/oss-fuzz/tree/master/projects/zlib, 2 | * see ossfuzz.sh for full license text. 3 | */ 4 | 5 | #include 6 | #include 7 | #include 8 | #include 9 | #include 10 | #include 11 | 12 | #include "miniz.h" 13 | 14 | #define CHECK_ERR(err, msg) { \ 15 | if (err != Z_OK) { \ 16 | fprintf(stderr, "%s error: %d\n", msg, err); \ 17 | exit(1); \ 18 | } \ 19 | } 20 | 21 | static const uint8_t *data; 22 | static size_t dataLen; 23 | static alloc_func zalloc = NULL; 24 | static free_func zfree = NULL; 25 | 26 | /* Test deflate() with small buffers */ 27 | void test_deflate(unsigned char *compr, size_t comprLen) 28 | { 29 | z_stream c_stream; /* compression stream */ 30 | int err; 31 | unsigned long len = dataLen; 32 | 33 | c_stream.zalloc = zalloc; 34 | c_stream.zfree = zfree; 35 | c_stream.opaque = NULL; 36 | 37 | err = deflateInit(&c_stream, Z_DEFAULT_COMPRESSION); 38 | CHECK_ERR(err, "deflateInit"); 39 | 40 | c_stream.next_in = (Bytef *)data; 41 | c_stream.next_out = compr; 42 | 43 | while (c_stream.total_in != len && c_stream.total_out < comprLen) 44 | { 45 | c_stream.avail_in = c_stream.avail_out = 1; /* force small buffers */ 46 | err = deflate(&c_stream, Z_NO_FLUSH); 47 | CHECK_ERR(err, "deflate small 1"); 48 | } 49 | 50 | /* Finish the stream, still forcing small buffers: */ 51 | for (;;) 52 | { 53 | c_stream.avail_out = 1; 54 | err = deflate(&c_stream, Z_FINISH); 55 | if (err == Z_STREAM_END) 56 | break; 57 | CHECK_ERR(err, "deflate small 2"); 58 | } 59 | 60 | err = deflateEnd(&c_stream); 61 | CHECK_ERR(err, "deflateEnd"); 62 | } 63 | 64 | /* Test inflate() with small buffers */ 65 | void test_inflate(unsigned char *compr, size_t comprLen, unsigned char *uncompr, size_t uncomprLen) 66 | { 67 | int err; 68 | z_stream d_stream; /* decompression stream */ 69 | 70 | d_stream.zalloc = zalloc; 71 | d_stream.zfree = zfree; 72 | d_stream.opaque = NULL; 73 | 74 | d_stream.next_in = compr; 75 | d_stream.avail_in = 0; 76 | d_stream.next_out = uncompr; 77 | 78 | err = inflateInit(&d_stream); 79 | CHECK_ERR(err, "inflateInit"); 80 | 81 | while (d_stream.total_out < uncomprLen && d_stream.total_in < comprLen) 82 | { 83 | d_stream.avail_in = d_stream.avail_out = 1; /* force small buffers */ 84 | err = inflate(&d_stream, Z_NO_FLUSH); 85 | if (err == Z_STREAM_END) 86 | break; 87 | CHECK_ERR(err, "inflate"); 88 | } 89 | 90 | err = inflateEnd(&d_stream); 91 | CHECK_ERR(err, "inflateEnd"); 92 | 93 | if (memcmp(uncompr, data, dataLen)) 94 | { 95 | fprintf(stderr, "bad inflate\n"); 96 | exit(1); 97 | } 98 | } 99 | 100 | int LLVMFuzzerTestOneInput(const uint8_t *d, size_t size) 101 | { 102 | size_t comprLen = compressBound(size); 103 | size_t uncomprLen = size; 104 | uint8_t *compr, *uncompr; 105 | 106 | /* Discard inputs larger than 1Mb. */ 107 | static size_t kMaxSize = 1024 * 1024; 108 | 109 | if (size < 1 || size > kMaxSize) 110 | return 0; 111 | 112 | data = d; 113 | dataLen = size; 114 | compr = calloc(1, comprLen); 115 | uncompr = calloc(1, uncomprLen); 116 | 117 | test_deflate(compr, comprLen); 118 | test_inflate(compr, comprLen, uncompr, uncomprLen); 119 | 120 | free(compr); 121 | free(uncompr); 122 | 123 | return 0; 124 | } 125 | -------------------------------------------------------------------------------- /tests/timer.cpp: -------------------------------------------------------------------------------- 1 | // File: timer.cpp - Simple high-precision timer class. Supports Win32, X360, and POSIX/Linux 2 | #include 3 | #include 4 | #include 5 | #include 6 | 7 | #include "timer.h" 8 | 9 | #if defined(WIN32) 10 | #include 11 | #elif defined(_XBOX) 12 | #include 13 | #endif 14 | 15 | unsigned long long timer::g_init_ticks; 16 | unsigned long long timer::g_freq; 17 | double timer::g_inv_freq; 18 | 19 | #if defined(WIN32) || defined(_XBOX) 20 | inline void query_counter(timer_ticks *pTicks) 21 | { 22 | QueryPerformanceCounter(reinterpret_cast(pTicks)); 23 | } 24 | inline void query_counter_frequency(timer_ticks *pTicks) 25 | { 26 | QueryPerformanceFrequency(reinterpret_cast(pTicks)); 27 | } 28 | #elif defined(__GNUC__) 29 | #include 30 | inline void query_counter(timer_ticks *pTicks) 31 | { 32 | struct timeval cur_time; 33 | gettimeofday(&cur_time, NULL); 34 | *pTicks = static_cast(cur_time.tv_sec)*1000000ULL + static_cast(cur_time.tv_usec); 35 | } 36 | inline void query_counter_frequency(timer_ticks *pTicks) 37 | { 38 | *pTicks = 1000000; 39 | } 40 | #endif 41 | 42 | timer::timer() : 43 | m_start_time(0), 44 | m_stop_time(0), 45 | m_started(false), 46 | m_stopped(false) 47 | { 48 | if (!g_inv_freq) 49 | init(); 50 | } 51 | 52 | timer::timer(timer_ticks start_ticks) 53 | { 54 | if (!g_inv_freq) 55 | init(); 56 | 57 | m_start_time = start_ticks; 58 | 59 | m_started = true; 60 | m_stopped = false; 61 | } 62 | 63 | void timer::start(timer_ticks start_ticks) 64 | { 65 | m_start_time = start_ticks; 66 | 67 | m_started = true; 68 | m_stopped = false; 69 | } 70 | 71 | void timer::start() 72 | { 73 | query_counter(&m_start_time); 74 | 75 | m_started = true; 76 | m_stopped = false; 77 | } 78 | 79 | void timer::stop() 80 | { 81 | assert(m_started); 82 | 83 | query_counter(&m_stop_time); 84 | 85 | m_stopped = true; 86 | } 87 | 88 | double timer::get_elapsed_secs() const 89 | { 90 | assert(m_started); 91 | if (!m_started) 92 | return 0; 93 | 94 | timer_ticks stop_time = m_stop_time; 95 | if (!m_stopped) 96 | query_counter(&stop_time); 97 | 98 | timer_ticks delta = stop_time - m_start_time; 99 | return delta * g_inv_freq; 100 | } 101 | 102 | timer_ticks timer::get_elapsed_us() const 103 | { 104 | assert(m_started); 105 | if (!m_started) 106 | return 0; 107 | 108 | timer_ticks stop_time = m_stop_time; 109 | if (!m_stopped) 110 | query_counter(&stop_time); 111 | 112 | timer_ticks delta = stop_time - m_start_time; 113 | return (delta * 1000000ULL + (g_freq >> 1U)) / g_freq; 114 | } 115 | 116 | void timer::init() 117 | { 118 | if (!g_inv_freq) 119 | { 120 | query_counter_frequency(&g_freq); 121 | g_inv_freq = 1.0f / g_freq; 122 | 123 | query_counter(&g_init_ticks); 124 | } 125 | } 126 | 127 | timer_ticks timer::get_init_ticks() 128 | { 129 | if (!g_inv_freq) 130 | init(); 131 | 132 | return g_init_ticks; 133 | } 134 | 135 | timer_ticks timer::get_ticks() 136 | { 137 | if (!g_inv_freq) 138 | init(); 139 | 140 | timer_ticks ticks; 141 | query_counter(&ticks); 142 | return ticks - g_init_ticks; 143 | } 144 | 145 | double timer::ticks_to_secs(timer_ticks ticks) 146 | { 147 | if (!g_inv_freq) 148 | init(); 149 | 150 | return ticks * g_inv_freq; 151 | } 152 | 153 | -------------------------------------------------------------------------------- /tests/timer.h: -------------------------------------------------------------------------------- 1 | // File: timer.h 2 | #pragma once 3 | 4 | typedef unsigned long long timer_ticks; 5 | 6 | class timer 7 | { 8 | public: 9 | timer(); 10 | timer(timer_ticks start_ticks); 11 | 12 | void start(); 13 | void start(timer_ticks start_ticks); 14 | 15 | void stop(); 16 | 17 | double get_elapsed_secs() const; 18 | inline double get_elapsed_ms() const { return get_elapsed_secs() * 1000.0f; } 19 | timer_ticks get_elapsed_us() const; 20 | 21 | static void init(); 22 | static inline timer_ticks get_ticks_per_sec() { return g_freq; } 23 | static timer_ticks get_init_ticks(); 24 | static timer_ticks get_ticks(); 25 | static double ticks_to_secs(timer_ticks ticks); 26 | static inline double ticks_to_ms(timer_ticks ticks) { return ticks_to_secs(ticks) * 1000.0f; } 27 | static inline double get_secs() { return ticks_to_secs(get_ticks()); } 28 | static inline double get_ms() { return ticks_to_ms(get_ticks()); } 29 | 30 | private: 31 | static timer_ticks g_init_ticks; 32 | static timer_ticks g_freq; 33 | static double g_inv_freq; 34 | 35 | timer_ticks m_start_time; 36 | timer_ticks m_stop_time; 37 | 38 | bool m_started : 1; 39 | bool m_stopped : 1; 40 | }; 41 | -------------------------------------------------------------------------------- /tests/uncompress2_fuzzer.c: -------------------------------------------------------------------------------- 1 | /* Derived from zlib fuzzers at http://github.com/google/oss-fuzz/tree/master/projects/zlib, 2 | * see ossfuzz.sh for full license text. 3 | */ 4 | 5 | #include 6 | #include 7 | #include 8 | 9 | #include "miniz.h" 10 | 11 | static unsigned char buffer[256 * 1024] = { 0 }; 12 | 13 | int LLVMFuzzerTestOneInput(const uint8_t* data, size_t size) 14 | { 15 | unsigned long int buffer_length = sizeof(buffer); 16 | 17 | if (Z_OK != uncompress2(buffer, &buffer_length, data, &size)) return 0; 18 | 19 | return 0; 20 | } 21 | -------------------------------------------------------------------------------- /tests/uncompress_fuzzer.c: -------------------------------------------------------------------------------- 1 | /* Derived from zlib fuzzers at http://github.com/google/oss-fuzz/tree/master/projects/zlib, 2 | * see ossfuzz.sh for full license text. 3 | */ 4 | 5 | #include 6 | #include 7 | #include 8 | 9 | #include "miniz.h" 10 | 11 | int LLVMFuzzerTestOneInput(const uint8_t* data, size_t size) 12 | { 13 | unsigned long int buffer_length = 1; 14 | unsigned char *buffer = NULL; 15 | int z_status = 0; 16 | 17 | if (size > 0) 18 | buffer_length *= data[0]; 19 | if (size > 1) 20 | buffer_length *= data[1]; 21 | 22 | buffer = (unsigned char *)malloc(buffer_length); 23 | 24 | z_status = uncompress(buffer, &buffer_length, data, size); 25 | free(buffer); 26 | 27 | if (Z_OK != z_status) 28 | return 0; 29 | return 0; 30 | } 31 | -------------------------------------------------------------------------------- /tests/zip.dict: -------------------------------------------------------------------------------- 1 | # Fuzzing dictionary for .zip files 2 | 3 | header_lfh="\x50\x4b\x03\x04" 4 | header_cd="\x50\x4b\x01\x02" 5 | header_eocd="\x50\x4b\x05\x06" 6 | header_eocd64="\x50\x4b\x06\x06" 7 | data_descriptor="\x50\x4b\x07\x08" 8 | extra_data_sig="\x50\x4b\x06\x08" 9 | digital_sig="\x50\x4b\x05\x05" 10 | -------------------------------------------------------------------------------- /tests/zip_fuzzer.c: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | 4 | #include "miniz.h" 5 | 6 | static char filename[260]; 7 | static unsigned char read_buf[1024 * 256]; 8 | 9 | static const size_t filename_max = sizeof(filename); 10 | static const size_t read_buf_size = sizeof(read_buf); 11 | static const size_t data_max = 1024 * 256; 12 | 13 | int LLVMFuzzerTestOneInput(const uint8_t *data, size_t size) 14 | { 15 | if(size > data_max) return 0; 16 | 17 | int ret = 0; 18 | mz_zip_archive zip; 19 | mz_zip_zero_struct(&zip); 20 | 21 | mz_uint flags = 0; 22 | 23 | if(!mz_zip_reader_init_mem(&zip, data, size, flags)) return 0; 24 | 25 | mz_uint i, files; 26 | 27 | files = mz_zip_reader_get_num_files(&zip); 28 | 29 | for(i=0; i < files; i++) 30 | { 31 | mz_zip_clear_last_error(&zip); 32 | 33 | if(mz_zip_reader_is_file_a_directory(&zip, i)) continue; 34 | 35 | mz_zip_validate_file(&zip, i, MZ_ZIP_FLAG_VALIDATE_HEADERS_ONLY); 36 | 37 | if(mz_zip_reader_is_file_encrypted(&zip, i)) continue; 38 | 39 | mz_zip_clear_last_error(&zip); 40 | 41 | mz_uint ret = mz_zip_reader_get_filename(&zip, i, filename, filename_max); 42 | 43 | if(mz_zip_get_last_error(&zip)) continue; 44 | 45 | mz_zip_archive_file_stat file_stat = {0}; 46 | mz_bool status = mz_zip_reader_file_stat(&zip, i, &file_stat) != 0; 47 | 48 | if ((file_stat.m_method) && (file_stat.m_method != MZ_DEFLATED)) continue; 49 | 50 | mz_zip_reader_extract_file_to_mem(&zip, file_stat.m_filename, read_buf, read_buf_size, 0); 51 | } 52 | 53 | cleanup: 54 | mz_zip_reader_end(&zip); 55 | 56 | return ret; 57 | } --------------------------------------------------------------------------------