├── CarthageSupport └── DataCompression.xcodeproj │ ├── project.xcworkspace │ ├── contents.xcworkspacedata │ └── xcshareddata │ │ ├── IDEWorkspaceChecks.plist │ │ └── WorkspaceSettings.xcsettings │ ├── DataCompression_Info.plist │ ├── DataCompressionTests_Info.plist │ ├── xcshareddata │ └── xcschemes │ │ └── DataCompression-Package.xcscheme │ └── project.pbxproj ├── Package.swift ├── DataCompression.podspec ├── .gitignore ├── Tests └── DataCompressionTests │ ├── XCTestManifests.swift │ └── CompressionTest.swift ├── README.md ├── LICENSE └── Sources └── DataCompression └── DataCompression.swift /CarthageSupport/DataCompression.xcodeproj/project.xcworkspace/contents.xcworkspacedata: -------------------------------------------------------------------------------- 1 | 2 | 4 | 6 | 7 | -------------------------------------------------------------------------------- /CarthageSupport/DataCompression.xcodeproj/project.xcworkspace/xcshareddata/IDEWorkspaceChecks.plist: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | IDEDidComputeMac32BitWarning 6 | 7 | 8 | 9 | -------------------------------------------------------------------------------- /CarthageSupport/DataCompression.xcodeproj/project.xcworkspace/xcshareddata/WorkspaceSettings.xcsettings: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | IDEWorkspaceSharedSettings_AutocreateContextsIfNeeded 6 | 7 | 8 | -------------------------------------------------------------------------------- /Package.swift: -------------------------------------------------------------------------------- 1 | // swift-tools-version:5.9 2 | 3 | import PackageDescription 4 | 5 | let package = Package( 6 | name: "DataCompression", 7 | platforms: [ 8 | .macOS(.v10_13), 9 | .iOS(.v12), 10 | .tvOS(.v12), 11 | .watchOS(.v4), 12 | .visionOS(.v1), 13 | ], 14 | products: [ 15 | .library( 16 | name: "DataCompression", 17 | targets: ["DataCompression"]), 18 | ], 19 | targets: [ 20 | .target( 21 | name: "DataCompression", 22 | dependencies: []), 23 | .testTarget( 24 | name: "DataCompressionTests", 25 | dependencies: ["DataCompression"]), 26 | ] 27 | ) 28 | -------------------------------------------------------------------------------- /CarthageSupport/DataCompression.xcodeproj/DataCompression_Info.plist: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | CFBundleDevelopmentRegion 5 | en 6 | CFBundleExecutable 7 | $(EXECUTABLE_NAME) 8 | CFBundleIdentifier 9 | $(PRODUCT_BUNDLE_IDENTIFIER) 10 | CFBundleInfoDictionaryVersion 11 | 6.0 12 | CFBundleName 13 | $(PRODUCT_NAME) 14 | CFBundlePackageType 15 | FMWK 16 | CFBundleShortVersionString 17 | 1.0 18 | CFBundleSignature 19 | ???? 20 | CFBundleVersion 21 | 1 22 | NSPrincipalClass 23 | 24 | 25 | 26 | -------------------------------------------------------------------------------- /CarthageSupport/DataCompression.xcodeproj/DataCompressionTests_Info.plist: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | CFBundleDevelopmentRegion 5 | en 6 | CFBundleExecutable 7 | $(EXECUTABLE_NAME) 8 | CFBundleIdentifier 9 | $(PRODUCT_BUNDLE_IDENTIFIER) 10 | CFBundleInfoDictionaryVersion 11 | 6.0 12 | CFBundleName 13 | $(PRODUCT_NAME) 14 | CFBundlePackageType 15 | BNDL 16 | CFBundleShortVersionString 17 | 1.0 18 | CFBundleSignature 19 | ???? 20 | CFBundleVersion 21 | $(CURRENT_PROJECT_VERSION) 22 | NSPrincipalClass 23 | 24 | 25 | 26 | -------------------------------------------------------------------------------- /DataCompression.podspec: -------------------------------------------------------------------------------- 1 | Pod::Spec.new do |s| 2 | s.name = "DataCompression" 3 | s.version = "3.9.0" 4 | s.summary = "Swift libcompression wrapper as an extension for the Data type (GZIP, ZLIB, LZFSE, LZMA, LZ4, deflate, RFC-1950, RFC-1951, RFC-1952)" 5 | s.authors = { "Markus Wanke" => "mw99@users.noreply.github.com" } 6 | s.homepage = "https://github.com/mw99/DataCompression" 7 | s.license = { :type => 'Apache 2.0', :file => 'LICENSE' } 8 | s.source = { :git => "https://github.com/mw99/DataCompression.git", :tag => s.version } 9 | 10 | s.swift_version = '5' 11 | 12 | s.ios.deployment_target = '12.0' 13 | s.osx.deployment_target = '10.13' 14 | s.tvos.deployment_target = '12.0' 15 | s.watchos.deployment_target = '4.0' 16 | s.visionos.deployment_target = '1.0' 17 | 18 | s.source_files = 'Sources/DataCompression/*.swift' 19 | s.requires_arc = true 20 | end 21 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | # Xcode 2 | # 3 | # gitignore contributors: remember to update Global/Xcode.gitignore, Objective-C.gitignore & Swift.gitignore 4 | 5 | ## Build generated 6 | build/ 7 | DerivedData/ 8 | development/ 9 | 10 | ## Various settings 11 | *.pbxuser 12 | !default.pbxuser 13 | *.mode1v3 14 | !default.mode1v3 15 | *.mode2v3 16 | !default.mode2v3 17 | *.perspectivev3 18 | !default.perspectivev3 19 | xcuserdata/ 20 | 21 | ## Other 22 | *.moved-aside 23 | *.xccheckout 24 | *.xcscmblueprint 25 | 26 | ## Obj-C/Swift specific 27 | *.hmap 28 | *.ipa 29 | *.dSYM.zip 30 | *.dSYM 31 | *.swp 32 | 33 | ## Playgrounds 34 | timeline.xctimeline 35 | playground.xcworkspace 36 | 37 | # Swift Package Manager 38 | # 39 | # Add this line if you want to avoid checking in source code from Swift Package Manager dependencies. 40 | # Packages/ 41 | # Package.pins 42 | .build/ 43 | .swiftpm/ 44 | 45 | # CocoaPods 46 | # 47 | # We recommend against adding the Pods directory to your .gitignore. However 48 | # you should judge for yourself, the pros and cons are mentioned at: 49 | # https://guides.cocoapods.org/using/using-cocoapods.html#should-i-check-the-pods-directory-into-source-control 50 | # 51 | # Pods/ 52 | 53 | # Carthage 54 | # 55 | # Add this line if you want to avoid checking in source code from Carthage dependencies. 56 | # Carthage/Checkouts 57 | 58 | Carthage/Build 59 | 60 | # fastlane 61 | # 62 | # It is recommended to not store the screenshots in the git repo. Instead, use fastlane to re-generate the 63 | # screenshots whenever they are needed. 64 | # For more information about the recommended setup visit: 65 | # https://docs.fastlane.tools/best-practices/source-control/#source-control 66 | 67 | fastlane/report.xml 68 | fastlane/Preview.html 69 | fastlane/screenshots 70 | fastlane/test_output 71 | -------------------------------------------------------------------------------- /Tests/DataCompressionTests/XCTestManifests.swift: -------------------------------------------------------------------------------- 1 | 2 | extension CompressionTest 3 | { 4 | static var allTests = [ 5 | ("testEmptyString", testEmptyString), 6 | ("testEmptyData", testEmptyData), 7 | ("testAdler32", testAdler32), 8 | ("testCrc32", testCrc32), 9 | ("testMiscSmall_deflate_inflate", testMiscSmall_deflate_inflate), 10 | ("testMiscSmall_zip_unzip", testMiscSmall_zip_unzip), 11 | ("testMiscSmall_gzip_gunzip", testMiscSmall_gzip_gunzip), 12 | ("testMiscSmall_lz4_delz4", testMiscSmall_lz4_delz4), 13 | ("testMiscSmall_lzma_delzma", testMiscSmall_lzma_delzma), 14 | ("testMiscSmall_lzfse_delzfse", testMiscSmall_lzfse_delzfse), 15 | ("testAsciiNumbers_deflate_inflate", testAsciiNumbers_deflate_inflate), 16 | ("testAsciiNumbers_zip_unzip", testAsciiNumbers_zip_unzip), 17 | ("testAsciiNumbers_gzip_gunzip", testAsciiNumbers_gzip_gunzip), 18 | ("testAsciiNumbers_lz4_delz4", testAsciiNumbers_lz4_delz4), 19 | ("testAsciiNumbers_lzma_delzma", testAsciiNumbers_lzma_delzma), 20 | ("testAsciiNumbers_lzfse_delzfse", testAsciiNumbers_lzfse_delzfse), 21 | ("testRandomDataChunks_deflate_inflate", testRandomDataChunks_deflate_inflate), 22 | ("testRandomDataChunks_zip_unzip", testRandomDataChunks_zip_unzip), 23 | ("testRandomDataChunks_gzip_gunzip", testRandomDataChunks_gzip_gunzip), 24 | ("testRandomDataChunks_lz4_delz4", testRandomDataChunks_lz4_delz4), 25 | ("testRandomDataChunks_lzma_delzma", testRandomDataChunks_lzma_delzma), 26 | ("testRandomDataChunks_lzfse_delzfse", testRandomDataChunks_lzfse_delzfse), 27 | ("testRandomDataBlob_16MB_deflate_inflate", testRandomDataBlob_16MB_deflate_inflate), 28 | ("testRandomDataBlob_16MB_zip_unzip", testRandomDataBlob_16MB_zip_unzip), 29 | ("testRandomDataBlob_16MB_gzip_gunzip", testRandomDataBlob_16MB_gzip_gunzip), 30 | ("testRandomDataBlob_16MB_lz4_delz4", testRandomDataBlob_16MB_lz4_delz4), 31 | ("testRandomDataBlob_16MB_lzma_delzma", testRandomDataBlob_16MB_lzma_delzma), 32 | ("testRandomDataBlob_16MB_lzfse_delzfse", testRandomDataBlob_16MB_lzfse_delzfse), 33 | ("testGzipCrcFail", testGzipCrcFail), 34 | ("testGzipISizeFail", testGzipISizeFail), 35 | ] 36 | } 37 | -------------------------------------------------------------------------------- /CarthageSupport/DataCompression.xcodeproj/xcshareddata/xcschemes/DataCompression-Package.xcscheme: -------------------------------------------------------------------------------- 1 | 2 | 5 | 8 | 9 | 15 | 21 | 22 | 23 | 24 | 25 | 30 | 31 | 33 | 39 | 40 | 41 | 42 | 43 | 44 | 45 | 55 | 56 | 62 | 63 | 64 | 65 | 66 | 67 | 73 | 74 | 76 | 77 | 80 | 81 | 82 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # DataCompression 2 | 3 | ### A libcompression wrapper extension for the `Data` type 4 | 5 | #### Supported compression algorithms are: 6 | 7 | * GZIP format (.gz files) [RFC-1952](https://www.ietf.org/rfc/rfc1952.txt) 8 | * ZLIB deflate stream [RFC-1950](https://www.ietf.org/rfc/rfc1950.txt) 9 | * ZLIB deflate raw [RFC-1951](https://www.ietf.org/rfc/rfc1951.txt) 10 | * [LZMA](https://en.wikipedia.org/wiki/Lempel%E2%80%93Ziv%E2%80%93Markov_chain_algorithm) 11 | * [LZFSE](https://github.com/lzfse/lzfse) 12 | * [LZ4](https://en.wikipedia.org/wiki/LZ4_(compression_algorithm)) 13 | 14 | #### Requirements 15 | * iOS deployment target **>= 9.0** 16 | * macOS deployment target **>= 10.11** 17 | * tvOS deployment target **>= 9.0** 18 | * watchOS deployment target **>= 2.0** 19 | 20 | 21 | #### Swift version support 22 | | Library Version | Swift Version | 23 | |-----------------|---------------| 24 | | 3.9.0 | 6+ (Xcode 16)| 25 | | 3.8.0 | 5.7 (Xcode 14)| 26 | | 3.6.0 | 5.1 (Xcode 11)| 27 | | 3.5.0 | 5.0 | 28 | | 3.1.0 | 4.2 | 29 | | 3.0.0 | 3.0 -> 4.1 | 30 | | 2.0.1 | < 3.0 | 31 | 32 | 33 | ## Usage example 34 | 35 | ### Try all algorithms and compare the compression ratio 36 | ```swift 37 | let raw: Data! = String(repeating: "There is no place like 127.0.0.1", count: 25).data(using: .utf8) 38 | 39 | print("raw => \(raw.count) bytes") 40 | 41 | for algo: Data.CompressionAlgorithm in [.zlib, .lzfse, .lz4, .lzma] { 42 | let compressedData: Data! = raw.compress(withAlgorithm: algo) 43 | 44 | let ratio = Double(raw.count) / Double(compressedData.count) 45 | print("\(algo) => \(compressedData.count) bytes, ratio: \(ratio)") 46 | 47 | assert(compressedData.decompress(withAlgorithm: algo)! == raw) 48 | } 49 | ``` 50 | 51 | Will print something like: 52 | ``` 53 | raw => 800 bytes 54 | zlib => 40 bytes, ratio: 20.00 55 | lzfse => 69 bytes, ratio: 11.59 56 | lz4 => 181 bytes, ratio: 4.42 57 | lzma => 100 bytes, ratio: 8.00 58 | ``` 59 | 60 | ### Container formats 61 | 62 | 63 | ##### The famous zlib deflate algorithm ([RFC-1951](https://www.ietf.org/rfc/rfc1951.txt)) can also be used with the shortcuts `.deflate()` and `.inflate()` 64 | ``` 65 | let data: Data! = "https://www.ietf.org/rfc/rfc1951.txt".data(using: .utf8) 66 | let deflated: Data! = data.deflate() 67 | let inflated: Data? = deflated?.inflate() 68 | assert(data == inflated) 69 | ``` 70 | 71 | ##### Data in gzip format ([RFC-1952](https://www.ietf.org/rfc/rfc1952.txt)) can be handled with `.gzip()` and `.gunzip()` 72 | ``` 73 | let data: Data! = "https://www.ietf.org/rfc/rfc1952.txt".data(using: .utf8) 74 | let gzipped: Data! = data.gzip() 75 | let gunzipped: Data? = gzipped.gunzip() 76 | assert(data == gunzipped) 77 | ``` 78 | *Note: Compressed data in gzip format will always be 18 bytes larger than raw deflated data and will append/perform a crc32 checksum based data integrity test .* 79 | 80 | ##### Data in zip format ([RFC-1950](https://www.ietf.org/rfc/rfc1950.txt)) can be handled with `.zip()` and `.unzip()` 81 | ``` 82 | let data: Data! = "https://www.ietf.org/rfc/rfc1950.txt".data(using: .utf8) 83 | let zipped: Data! = data.zip() 84 | let unzipped: Data? = zipped.unzip() 85 | assert(data == unzipped) 86 | ``` 87 | *Note: Compressed data in zip format will always be 6 bytes larger than raw deflated data and will append/perform a adler32 checksum based data integrity test .* 88 | 89 | 90 | ### Compress a file on the command line and decompress it in Swift 91 | The easiest way is using the already installed **gzip** command line tool. Assuming you have a file called **file.txt**, after calling 92 | ```bash 93 | gzip -9 file.txt 94 | ``` 95 | the file should have been compressed to **file.txt.gz**. You can now load and uncompress the contents of your file with: 96 | ``` 97 | let compressedData = try? Data(contentsOf: URL(fileURLWithPath: "/path/to/your/file.txt.gz")) 98 | 99 | if let uncompressedData = compressedData?.gunzip() { 100 | print(String(data: uncompressedData, encoding: .utf8) ?? "Can't decode UTF-8") 101 | } 102 | ``` 103 | 104 | ### Checksum extensions 105 | Unrelated to compression but for convenience **Crc32** and **Adler32** methods are also exposed on the `Data` type which may come in handy. 106 | ``` 107 | let classicExample = "The quick brown fox jumps over the lazy dog".data(using: .utf8)! 108 | let crc32 = classicExample.crc32() 109 | let adler32 = classicExample.adler32() 110 | print("crc32: \(crc32), adler32: \(adler32)") 111 | ``` 112 | Will print: 113 | ``` 114 | crc32: 414fa339, adler32: 5bdc0fda 115 | ``` 116 | 117 | 118 | 119 | ## Install 120 | 121 | #### Cocoa Pods 122 | 123 | To integrate DataCompression into your Xcode project using CocoaPods, add it to your `Podfile`: 124 | 125 | ```ruby 126 | target '' do 127 | pod 'DataCompression' 128 | end 129 | ``` 130 | 131 | Then, run the following command: 132 | 133 | ```bash 134 | $ pod install 135 | ``` 136 | 137 | You then will need to add `import DataCompression` at the top of your swift source files to use the extension. 138 | 139 | 140 | #### Carthage 141 | 142 | **Note:** DataCompression versions < 3.3.0 are not compatible with carthage. That means Swift 5 only. 143 | 144 | To integrate DataCompression into your Xcode project using Carthage, add it as a dependency to your `Cartfile`. Just add: 145 | ``` 146 | github "mw99/DataCompression" 147 | ``` 148 | 149 | You will then have to add the framework paths in the `carthage copy-frameworks` run script phase of your Xcode project. 150 | The paths may differ depending on you have setup your project in relation to Carthage. 151 | 152 | ##### Input: 153 | ``` 154 | $(SRCROOT)/Carthage/Build/iOS/DataCompression.framework 155 | ``` 156 | ##### Output: 157 | ``` 158 | $(BUILT_PRODUCTS_DIR)/$(FRAMEWORKS_FOLDER_PATH)/DataCompression.framework 159 | ``` 160 | 161 | You then will need to add `import DataCompression` at the top of your swift source files to use the extension. 162 | 163 | 164 | #### Swift Package Manager 165 | 166 | To integrate DataCompression into your Xcode project using the swift package manager, add it as a dependency to your `Package.swift` file: 167 | 168 | ```swift 169 | import PackageDescription 170 | 171 | let package = Package( 172 | name: "", 173 | dependencies: [ 174 | .Package(url: "https://github.com/mw99/DataCompression.git", majorVersion: 3) 175 | ] 176 | ) 177 | ``` 178 | 179 | You then will need to add `import DataCompression` at the top of your swift source files to use the extension. 180 | 181 | The next time you run `swift build`, the new dependencies will be resolved. 182 | 183 | ```bash 184 | $ swift build 185 | ``` 186 | 187 | 188 | #### Or just copy the file into your project 189 | 190 | You only need one file located at `Sources/DataCompression.swift`. Drag and drop it into the Xcode project navigator. 191 | 192 | 193 | ## Change log / Upgrading guide 194 | 195 | 196 | ##### Version `3.8.0` to `3.9.0` 197 | - Support for visionOS added. 198 | - All other platform support versions bumped in order to reduce compile time warnings. 199 | 200 | ##### Version `3.7.0` to `3.8.0` 201 | - Solved a bug causing crashes when using `.unzip()`, because of unaligned pointer loading caused by internal changes in Swift 5.7. 202 | 203 | ##### Version `3.6.0` to `3.7.0` 204 | - Support for Xcode 14 with Swift 5.7 205 | 206 | ##### Version `3.5.0` to `3.6.0` 207 | - Target platforms finally added to the SPM Package file 208 | - Carthage support improved 209 | - Support for Xcode 11 SPM integration 210 | 211 | ##### Version `3.4.0` to `3.5.0` 212 | - Fix that prevents a bug in Apples lzfse compressor when working with large chunks of data. 213 | 214 | ##### Version `3.3.0` to `3.4.0` 215 | - Swift 5 release had further deprecation warnings than in the Swift 5 beta. Fixed. 216 | 217 | ##### Version `3.2.0` to `3.3.0` 218 | - Added support for Carthage 219 | 220 | ##### Version `3.1.0` to `3.2.0` 221 | - Podspec swift version set to **5.0** 222 | - Library file structure updated to fit the new swift package manager layout 223 | 224 | ##### Version `3.0.0` to `3.1.0` 225 | - Podspec swift version set to **4.2** 226 | 227 | ##### Version `2.0.X` to `3.0.0` 228 | 229 | - The encoded data in zip format is not copied anymore, which should improve performance. 230 | - Checksum validation is now always performed with libz and way faster. 231 | - The `skipCheckSumValidation:` parameter of `.unzip()` was removed. 232 | - Items of the algorithm enum type are now Swift like lowercase, e.g. `.LZMA` → `.lzma` 233 | 234 | 235 | ## License 236 | 237 | 238 | ##### Apache License, Version 2.0 239 | 240 | ##### Copyright 2016, Markus Wanke 241 | 242 | Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at 243 | 244 | [http://www.apache.org/licenses/LICENSE-2.0](http://www.apache.org/licenses/LICENSE-2.0) 245 | 246 | Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. 247 | 248 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | Apache License 2 | Version 2.0, January 2004 3 | http://www.apache.org/licenses/ 4 | 5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 6 | 7 | 1. Definitions. 8 | 9 | "License" shall mean the terms and conditions for use, reproduction, 10 | and distribution as defined by Sections 1 through 9 of this document. 11 | 12 | "Licensor" shall mean the copyright owner or entity authorized by 13 | the copyright owner that is granting the License. 14 | 15 | "Legal Entity" shall mean the union of the acting entity and all 16 | other entities that control, are controlled by, or are under common 17 | control with that entity. For the purposes of this definition, 18 | "control" means (i) the power, direct or indirect, to cause the 19 | direction or management of such entity, whether by contract or 20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 21 | outstanding shares, or (iii) beneficial ownership of such entity. 22 | 23 | "You" (or "Your") shall mean an individual or Legal Entity 24 | exercising permissions granted by this License. 25 | 26 | "Source" form shall mean the preferred form for making modifications, 27 | including but not limited to software source code, documentation 28 | source, and configuration files. 29 | 30 | "Object" form shall mean any form resulting from mechanical 31 | transformation or translation of a Source form, including but 32 | not limited to compiled object code, generated documentation, 33 | and conversions to other media types. 34 | 35 | "Work" shall mean the work of authorship, whether in Source or 36 | Object form, made available under the License, as indicated by a 37 | copyright notice that is included in or attached to the work 38 | (an example is provided in the Appendix below). 39 | 40 | "Derivative Works" shall mean any work, whether in Source or Object 41 | form, that is based on (or derived from) the Work and for which the 42 | editorial revisions, annotations, elaborations, or other modifications 43 | represent, as a whole, an original work of authorship. For the purposes 44 | of this License, Derivative Works shall not include works that remain 45 | separable from, or merely link (or bind by name) to the interfaces of, 46 | the Work and Derivative Works thereof. 47 | 48 | "Contribution" shall mean any work of authorship, including 49 | the original version of the Work and any modifications or additions 50 | to that Work or Derivative Works thereof, that is intentionally 51 | submitted to Licensor for inclusion in the Work by the copyright owner 52 | or by an individual or Legal Entity authorized to submit on behalf of 53 | the copyright owner. For the purposes of this definition, "submitted" 54 | means any form of electronic, verbal, or written communication sent 55 | to the Licensor or its representatives, including but not limited to 56 | communication on electronic mailing lists, source code control systems, 57 | and issue tracking systems that are managed by, or on behalf of, the 58 | Licensor for the purpose of discussing and improving the Work, but 59 | excluding communication that is conspicuously marked or otherwise 60 | designated in writing by the copyright owner as "Not a Contribution." 61 | 62 | "Contributor" shall mean Licensor and any individual or Legal Entity 63 | on behalf of whom a Contribution has been received by Licensor and 64 | subsequently incorporated within the Work. 65 | 66 | 2. Grant of Copyright License. Subject to the terms and conditions of 67 | this License, each Contributor hereby grants to You a perpetual, 68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 69 | copyright license to reproduce, prepare Derivative Works of, 70 | publicly display, publicly perform, sublicense, and distribute the 71 | Work and such Derivative Works in Source or Object form. 72 | 73 | 3. Grant of Patent License. Subject to the terms and conditions of 74 | this License, each Contributor hereby grants to You a perpetual, 75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 76 | (except as stated in this section) patent license to make, have made, 77 | use, offer to sell, sell, import, and otherwise transfer the Work, 78 | where such license applies only to those patent claims licensable 79 | by such Contributor that are necessarily infringed by their 80 | Contribution(s) alone or by combination of their Contribution(s) 81 | with the Work to which such Contribution(s) was submitted. If You 82 | institute patent litigation against any entity (including a 83 | cross-claim or counterclaim in a lawsuit) alleging that the Work 84 | or a Contribution incorporated within the Work constitutes direct 85 | or contributory patent infringement, then any patent licenses 86 | granted to You under this License for that Work shall terminate 87 | as of the date such litigation is filed. 88 | 89 | 4. Redistribution. You may reproduce and distribute copies of the 90 | Work or Derivative Works thereof in any medium, with or without 91 | modifications, and in Source or Object form, provided that You 92 | meet the following conditions: 93 | 94 | (a) You must give any other recipients of the Work or 95 | Derivative Works a copy of this License; and 96 | 97 | (b) You must cause any modified files to carry prominent notices 98 | stating that You changed the files; and 99 | 100 | (c) You must retain, in the Source form of any Derivative Works 101 | that You distribute, all copyright, patent, trademark, and 102 | attribution notices from the Source form of the Work, 103 | excluding those notices that do not pertain to any part of 104 | the Derivative Works; and 105 | 106 | (d) If the Work includes a "NOTICE" text file as part of its 107 | distribution, then any Derivative Works that You distribute must 108 | include a readable copy of the attribution notices contained 109 | within such NOTICE file, excluding those notices that do not 110 | pertain to any part of the Derivative Works, in at least one 111 | of the following places: within a NOTICE text file distributed 112 | as part of the Derivative Works; within the Source form or 113 | documentation, if provided along with the Derivative Works; or, 114 | within a display generated by the Derivative Works, if and 115 | wherever such third-party notices normally appear. The contents 116 | of the NOTICE file are for informational purposes only and 117 | do not modify the License. You may add Your own attribution 118 | notices within Derivative Works that You distribute, alongside 119 | or as an addendum to the NOTICE text from the Work, provided 120 | that such additional attribution notices cannot be construed 121 | as modifying the License. 122 | 123 | You may add Your own copyright statement to Your modifications and 124 | may provide additional or different license terms and conditions 125 | for use, reproduction, or distribution of Your modifications, or 126 | for any such Derivative Works as a whole, provided Your use, 127 | reproduction, and distribution of the Work otherwise complies with 128 | the conditions stated in this License. 129 | 130 | 5. Submission of Contributions. Unless You explicitly state otherwise, 131 | any Contribution intentionally submitted for inclusion in the Work 132 | by You to the Licensor shall be under the terms and conditions of 133 | this License, without any additional terms or conditions. 134 | Notwithstanding the above, nothing herein shall supersede or modify 135 | the terms of any separate license agreement you may have executed 136 | with Licensor regarding such Contributions. 137 | 138 | 6. Trademarks. This License does not grant permission to use the trade 139 | names, trademarks, service marks, or product names of the Licensor, 140 | except as required for reasonable and customary use in describing the 141 | origin of the Work and reproducing the content of the NOTICE file. 142 | 143 | 7. Disclaimer of Warranty. Unless required by applicable law or 144 | agreed to in writing, Licensor provides the Work (and each 145 | Contributor provides its Contributions) on an "AS IS" BASIS, 146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 147 | implied, including, without limitation, any warranties or conditions 148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 149 | PARTICULAR PURPOSE. You are solely responsible for determining the 150 | appropriateness of using or redistributing the Work and assume any 151 | risks associated with Your exercise of permissions under this License. 152 | 153 | 8. Limitation of Liability. In no event and under no legal theory, 154 | whether in tort (including negligence), contract, or otherwise, 155 | unless required by applicable law (such as deliberate and grossly 156 | negligent acts) or agreed to in writing, shall any Contributor be 157 | liable to You for damages, including any direct, indirect, special, 158 | incidental, or consequential damages of any character arising as a 159 | result of this License or out of the use or inability to use the 160 | Work (including but not limited to damages for loss of goodwill, 161 | work stoppage, computer failure or malfunction, or any and all 162 | other commercial damages or losses), even if such Contributor 163 | has been advised of the possibility of such damages. 164 | 165 | 9. Accepting Warranty or Additional Liability. While redistributing 166 | the Work or Derivative Works thereof, You may choose to offer, 167 | and charge a fee for, acceptance of support, warranty, indemnity, 168 | or other liability obligations and/or rights consistent with this 169 | License. However, in accepting such obligations, You may act only 170 | on Your own behalf and on Your sole responsibility, not on behalf 171 | of any other Contributor, and only if You agree to indemnify, 172 | defend, and hold each Contributor harmless for any liability 173 | incurred by, or claims asserted against, such Contributor by reason 174 | of your accepting any such warranty or additional liability. 175 | 176 | END OF TERMS AND CONDITIONS 177 | 178 | APPENDIX: How to apply the Apache License to your work. 179 | 180 | To apply the Apache License to your work, attach the following 181 | boilerplate notice, with the fields enclosed by brackets "{}" 182 | replaced with your own identifying information. (Don't include 183 | the brackets!) The text should be enclosed in the appropriate 184 | comment syntax for the file format. We also recommend that a 185 | file or class name and description of purpose be included on the 186 | same "printed page" as the copyright notice for easier 187 | identification within third-party archives. 188 | 189 | Copyright {yyyy} {name of copyright owner} 190 | 191 | Licensed under the Apache License, Version 2.0 (the "License"); 192 | you may not use this file except in compliance with the License. 193 | You may obtain a copy of the License at 194 | 195 | http://www.apache.org/licenses/LICENSE-2.0 196 | 197 | Unless required by applicable law or agreed to in writing, software 198 | distributed under the License is distributed on an "AS IS" BASIS, 199 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 200 | See the License for the specific language governing permissions and 201 | limitations under the License. 202 | -------------------------------------------------------------------------------- /Tests/DataCompressionTests/CompressionTest.swift: -------------------------------------------------------------------------------- 1 | 2 | import XCTest 3 | 4 | @testable import DataCompression 5 | 6 | 7 | extension Data 8 | { 9 | func deflate_inflate() -> Data? { return c_deflate()?.c_inflate() } 10 | func zip_unzip() -> Data? { return c_zip()?.c_unzip() } 11 | func gzip_gunzip() -> Data? { return c_gzip()?.c_gunzip() } 12 | func lz4_delz4() -> Data? { return c_lz4()?.c_delz4() } 13 | func lzma_delzma() -> Data? { return c_lzma()?.c_delzma() } 14 | func lzfse_delzfse() -> Data? { return c_lzfse()?.c_delzfse() } 15 | 16 | 17 | func c_deflate() -> Data? { let res: Data? = self.deflate(); XCTAssertNotNil(res, "\(#function) failed"); return res } 18 | func c_inflate() -> Data? { let res: Data? = self.inflate(); XCTAssertNotNil(res, "\(#function) failed"); return res } 19 | 20 | func c_zip() -> Data? { let res: Data? = self.zip(); XCTAssertNotNil(res, "\(#function) failed"); return res } 21 | func c_unzip() -> Data? { let res: Data? = self.unzip(skipCheckSumValidation: false); XCTAssertNotNil(res, "\(#function) failed"); return res } 22 | 23 | func c_gzip() -> Data? { let res: Data? = self.gzip(); XCTAssertNotNil(res, "\(#function) failed"); return res } 24 | func c_gunzip() -> Data? { let res: Data? = self.gunzip(); XCTAssertNotNil(res, "\(#function) failed"); return res } 25 | 26 | func c_lz4() -> Data? { let res: Data? = self.compress(withAlgorithm: .lz4); XCTAssertNotNil(res, "\(#function) failed"); return res } 27 | func c_delz4() -> Data? { let res: Data? = self.decompress(withAlgorithm: .lz4); XCTAssertNotNil(res, "\(#function) failed"); return res } 28 | 29 | func c_lzma() -> Data? { let res: Data? = self.compress(withAlgorithm: .lzma); XCTAssertNotNil(res, "\(#function) failed"); return res } 30 | func c_delzma() -> Data? { let res: Data? = self.decompress(withAlgorithm: .lzma); XCTAssertNotNil(res, "\(#function) failed"); return res } 31 | 32 | func c_lzfse() -> Data? { let res: Data? = self.compress(withAlgorithm: .lzfse); XCTAssertNotNil(res, "\(#function) failed"); return res } 33 | func c_delzfse() -> Data? { let res: Data? = self.decompress(withAlgorithm: .lzfse); XCTAssertNotNil(res, "\(#function) failed"); return res } 34 | } 35 | 36 | 37 | extension String 38 | { 39 | func deflate_inflate() -> Data? { return data(using: .ascii)?.deflate_inflate() } 40 | func zip_unzip() -> Data? { return data(using: .ascii)?.zip_unzip() } 41 | func gzip_gunzip() -> Data? { return data(using: .ascii)?.gzip_gunzip() } 42 | func lz4_delz4() -> Data? { return data(using: .ascii)?.lz4_delz4() } 43 | func lzma_delzma() -> Data? { return data(using: .ascii)?.lzma_delzma() } 44 | func lzfse_delzfse() -> Data? { return data(using: .ascii)?.lzfse_delzfse() } 45 | } 46 | 47 | 48 | class CompressionTest: XCTestCase 49 | { 50 | static var blob16mb: Data! 51 | 52 | override class func setUp() 53 | { 54 | super.setUp() 55 | let b = 1024 * 1024 * 16 // 16 MB 56 | let ints = [UInt32](repeating: 0, count: b / 4).map { _ in arc4random() } 57 | self.blob16mb = Data(bytes: ints, count: b) 58 | } 59 | 60 | func testEmptyString() 61 | { 62 | XCTAssertEqual(Data(), "".deflate_inflate()) 63 | XCTAssertEqual(Data(), "".zip_unzip()) 64 | XCTAssertEqual(Data(), "".gzip_gunzip()) 65 | XCTAssertEqual(Data(), "".lz4_delz4()) 66 | XCTAssertEqual(Data(), "".lzma_delzma()) 67 | XCTAssertEqual(Data(), "".lzfse_delzfse()) 68 | } 69 | 70 | func testEmptyData() 71 | { 72 | XCTAssertEqual(Data(), Data().deflate_inflate()) 73 | XCTAssertEqual(Data(), Data().zip_unzip()) 74 | XCTAssertEqual(Data(), Data().gzip_gunzip()) 75 | XCTAssertEqual(Data(), Data().lz4_delz4()) 76 | XCTAssertEqual(Data(), Data().lzma_delzma()) 77 | XCTAssertEqual(Data(), Data().lzfse_delzfse()) 78 | } 79 | 80 | func testAdler32() 81 | { 82 | var adler = Adler32() 83 | XCTAssertEqual(adler.checksum, 0x1) 84 | adler.advance(withChunk: "The quick brown ".data(using: .ascii)!) 85 | adler.advance(withChunk: "fox jumps over ".data(using: .ascii)!) 86 | adler.advance(withChunk: "the lazy dog.".data(using: .ascii)!) 87 | XCTAssertEqual(adler.checksum, 0x6be41008) 88 | } 89 | 90 | func testCrc32() 91 | { 92 | var crc = Crc32() 93 | XCTAssertEqual(crc.checksum, 0x0) 94 | crc.advance(withChunk: "The quick brown ".data(using: .ascii)!) 95 | crc.advance(withChunk: "fox jumps over ".data(using: .ascii)!) 96 | crc.advance(withChunk: "the lazy dog.".data(using: .ascii)!) 97 | XCTAssertEqual(crc.checksum, 0x519025e9) 98 | } 99 | 100 | func testMiscSmall_deflate_inflate() 101 | { 102 | for i in 1...500 { 103 | let s = String(repeating: "a", count: i) 104 | XCTAssertEqual(s.data(using: .ascii), s.deflate_inflate(), "Fails with: \(s)") 105 | } 106 | } 107 | 108 | func testMiscSmall_zip_unzip() 109 | { 110 | for i in 1...500 { 111 | let s = String(repeating: "a", count: i) 112 | XCTAssertEqual(s.data(using: .ascii), s.zip_unzip(), "Fails with: \(s)") 113 | } 114 | } 115 | 116 | func testMiscSmall_gzip_gunzip() 117 | { 118 | for i in 1...500 { 119 | let s = String(repeating: "a", count: i) 120 | XCTAssertEqual(s.data(using: .ascii), s.gzip_gunzip(), "Fails with: \(s)") 121 | } 122 | } 123 | 124 | func testMiscSmall_lz4_delz4() 125 | { 126 | for i in 1...500 { 127 | let s = String(repeating: "a", count: i) 128 | XCTAssertEqual(s.data(using: .ascii), s.lz4_delz4(), "Fails with: \(s)") 129 | } 130 | } 131 | 132 | func testMiscSmall_lzma_delzma() 133 | { 134 | for i in 1...500 { 135 | let s = String(repeating: "a", count: i) 136 | XCTAssertEqual(s.data(using: .ascii), s.lzma_delzma(), "Fails with: \(s)") 137 | } 138 | } 139 | 140 | func testMiscSmall_lzfse_delzfse() 141 | { 142 | for i in 1...500 { 143 | let s = String(repeating: "a", count: i) 144 | XCTAssertEqual(s.data(using: .ascii), s.lzfse_delzfse(), "Fails with: \(s)") 145 | } 146 | } 147 | 148 | func testAsciiNumbers_deflate_inflate() 149 | { 150 | for i in 1...500 { 151 | let r = sqrt(Double(i)) / .pi 152 | let s = String(repeating: "\(r)", count: i) 153 | XCTAssertEqual(s.data(using: .ascii), s.deflate_inflate(), "Fails with: \(s)") 154 | } 155 | } 156 | 157 | func testAsciiNumbers_zip_unzip() 158 | { 159 | for i in 1...500 { 160 | let r = sqrt(Double(i)) / .pi 161 | let s = String(repeating: "\(r)", count: i) 162 | XCTAssertEqual(s.data(using: .ascii), s.zip_unzip(), "Fails with: \(s)") 163 | } 164 | } 165 | 166 | func testAsciiNumbers_gzip_gunzip() 167 | { 168 | for i in 1...500 { 169 | let r = sqrt(Double(i)) / .pi 170 | let s = String(repeating: "\(r)", count: i) 171 | XCTAssertEqual(s.data(using: .ascii), s.gzip_gunzip(), "Fails with: \(s)") 172 | } 173 | } 174 | 175 | func testAsciiNumbers_lz4_delz4() 176 | { 177 | for i in 1...500 { 178 | let r = sqrt(Double(i)) / .pi 179 | let s = String(repeating: "\(r)", count: i) 180 | XCTAssertEqual(s.data(using: .ascii), s.lz4_delz4(), "Fails with: \(s)") 181 | } 182 | } 183 | 184 | func testAsciiNumbers_lzma_delzma() 185 | { 186 | for i in 1...500 { 187 | let r = sqrt(Double(i)) / .pi 188 | let s = String(repeating: "\(r)", count: i) 189 | XCTAssertEqual(s.data(using: .ascii), s.lzma_delzma(), "Fails with: \(s)") 190 | } 191 | } 192 | 193 | func testAsciiNumbers_lzfse_delzfse() 194 | { 195 | for i in 1...500 { 196 | let r = sqrt(Double(i)) / .pi 197 | let s = String(repeating: "\(r)", count: i) 198 | XCTAssertEqual(s.data(using: .ascii), s.lzfse_delzfse(), "Fails with: \(s)") 199 | } 200 | } 201 | 202 | 203 | func testRandomDataChunks_deflate_inflate() 204 | { 205 | for i in 1...500 { 206 | let ints = [UInt32](repeating: 0, count: 1 + (i / 4)).map { _ in arc4random() } 207 | let data = Data(bytes: ints, count: i) 208 | XCTAssertEqual(data, data.deflate_inflate(), "Fails with random data (\(data.count) bytes) :(") 209 | } 210 | } 211 | 212 | func testRandomDataChunks_zip_unzip() 213 | { 214 | for i in 1...500 { 215 | let ints = [UInt32](repeating: 0, count: 1 + (i / 4)).map { _ in arc4random() } 216 | let data = Data(bytes: ints, count: i) 217 | XCTAssertEqual(data, data.zip_unzip(), "Fails with random data (\(data.count) bytes) :(") 218 | } 219 | } 220 | 221 | func testRandomDataChunks_gzip_gunzip() 222 | { 223 | for i in 1...500 { 224 | let ints = [UInt32](repeating: 0, count: 1 + (i / 4)).map { _ in arc4random() } 225 | let data = Data(bytes: ints, count: i) 226 | XCTAssertEqual(data, data.gzip_gunzip(), "Fails with random data (\(data.count) bytes) :(") 227 | } 228 | } 229 | 230 | func testRandomDataChunks_lz4_delz4() 231 | { 232 | for i in 1...500 { 233 | let ints = [UInt32](repeating: 0, count: 1 + (i / 4)).map { _ in arc4random() } 234 | let data = Data(bytes: ints, count: i) 235 | XCTAssertEqual(data, data.lz4_delz4(), "Fails with random data (\(data.count) bytes) :(") 236 | } 237 | } 238 | 239 | func testRandomDataChunks_lzma_delzma() 240 | { 241 | for i in 1...500 { 242 | let ints = [UInt32](repeating: 0, count: 1 + (i / 4)).map { _ in arc4random() } 243 | let data = Data(bytes: ints, count: i) 244 | XCTAssertEqual(data, data.lzma_delzma(), "Fails with random data (\(data.count) bytes) :(") 245 | } 246 | } 247 | 248 | func testRandomDataChunks_lzfse_delzfse() 249 | { 250 | for i in 1...500 { 251 | let ints = [UInt32](repeating: 0, count: 1 + (i / 4)).map { _ in arc4random() } 252 | let data = Data(bytes: ints, count: i) 253 | XCTAssertEqual(data, data.lzfse_delzfse(), "Fails with random data (\(data.count) bytes) :(") 254 | } 255 | } 256 | 257 | func testRandomDataBlob_16MB_deflate_inflate() 258 | { 259 | XCTAssertEqual(CompressionTest.blob16mb, CompressionTest.blob16mb.deflate_inflate()) 260 | } 261 | 262 | func testRandomDataBlob_16MB_zip_unzip() 263 | { 264 | XCTAssertEqual(CompressionTest.blob16mb, CompressionTest.blob16mb.zip_unzip()) 265 | } 266 | 267 | func testRandomDataBlob_16MB_gzip_gunzip() 268 | { 269 | XCTAssertEqual(CompressionTest.blob16mb, CompressionTest.blob16mb.gzip_gunzip()) 270 | } 271 | 272 | func testRandomDataBlob_16MB_lz4_delz4() 273 | { 274 | XCTAssertEqual(CompressionTest.blob16mb, CompressionTest.blob16mb.lz4_delz4()) 275 | } 276 | 277 | func testRandomDataBlob_16MB_lzma_delzma() 278 | { 279 | XCTAssertEqual(CompressionTest.blob16mb, CompressionTest.blob16mb.lzma_delzma()) 280 | } 281 | 282 | func testRandomDataBlob_16MB_lzfse_delzfse() 283 | { 284 | XCTAssertEqual(CompressionTest.blob16mb, CompressionTest.blob16mb.lzfse_delzfse()) 285 | } 286 | 287 | func testGzipCrcFail() 288 | { 289 | let b = 1024 * 16 290 | let ints = [UInt32](repeating: 0xcafeabee, count: b / 4) 291 | var zipped_blob = Data(bytes: ints, count: b).gzip()! 292 | 293 | let wrong_crc = Data(bytes: [0xcafeabee], count: 1) 294 | let range = (zipped_blob.count - 8)..<(zipped_blob.count - 4) 295 | zipped_blob.replaceSubrange(range, with: wrong_crc) 296 | 297 | XCTAssertNil(zipped_blob.gunzip()) 298 | } 299 | 300 | func testGzipISizeFail() 301 | { 302 | let b = 1024 * 16 303 | let ints = [UInt32](repeating: 0xcafeabee, count: b / 4) 304 | var zipped_blob = Data(bytes: ints, count: b).gzip()! 305 | 306 | let wrong_isize = Data(bytes: [0xcafeabee], count: 1) 307 | let range = (zipped_blob.count - 4)..<(zipped_blob.count) 308 | zipped_blob.replaceSubrange(range, with: wrong_isize) 309 | 310 | XCTAssertNil(zipped_blob.gunzip()) 311 | } 312 | } 313 | 314 | -------------------------------------------------------------------------------- /CarthageSupport/DataCompression.xcodeproj/project.pbxproj: -------------------------------------------------------------------------------- 1 | // !$*UTF8*$! 2 | { 3 | archiveVersion = 1; 4 | classes = { 5 | }; 6 | objectVersion = 46; 7 | objects = { 8 | 9 | /* Begin PBXAggregateTarget section */ 10 | "DataCompression::DataCompressionPackageTests::ProductTarget" /* DataCompressionPackageTests */ = { 11 | isa = PBXAggregateTarget; 12 | buildConfigurationList = OBJ_35 /* Build configuration list for PBXAggregateTarget "DataCompressionPackageTests" */; 13 | buildPhases = ( 14 | ); 15 | dependencies = ( 16 | OBJ_38 /* PBXTargetDependency */, 17 | ); 18 | name = DataCompressionPackageTests; 19 | productName = DataCompressionPackageTests; 20 | }; 21 | /* End PBXAggregateTarget section */ 22 | 23 | /* Begin PBXBuildFile section */ 24 | OBJ_26 /* DataCompression.swift in Sources */ = {isa = PBXBuildFile; fileRef = OBJ_9 /* DataCompression.swift */; }; 25 | OBJ_33 /* Package.swift in Sources */ = {isa = PBXBuildFile; fileRef = OBJ_6 /* Package.swift */; }; 26 | OBJ_44 /* CompressionTest.swift in Sources */ = {isa = PBXBuildFile; fileRef = OBJ_12 /* CompressionTest.swift */; }; 27 | OBJ_45 /* XCTestManifests.swift in Sources */ = {isa = PBXBuildFile; fileRef = OBJ_13 /* XCTestManifests.swift */; }; 28 | OBJ_47 /* DataCompression.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = "DataCompression::DataCompression::Product" /* DataCompression.framework */; }; 29 | /* End PBXBuildFile section */ 30 | 31 | /* Begin PBXContainerItemProxy section */ 32 | 985A76C1222471FB0042A178 /* PBXContainerItemProxy */ = { 33 | isa = PBXContainerItemProxy; 34 | containerPortal = OBJ_1 /* Project object */; 35 | proxyType = 1; 36 | remoteGlobalIDString = "DataCompression::DataCompression"; 37 | remoteInfo = DataCompression; 38 | }; 39 | /* End PBXContainerItemProxy section */ 40 | 41 | /* Begin PBXFileReference section */ 42 | "DataCompression::DataCompression::Product" /* DataCompression.framework */ = {isa = PBXFileReference; lastKnownFileType = wrapper.framework; path = DataCompression.framework; sourceTree = BUILT_PRODUCTS_DIR; }; 43 | "DataCompression::DataCompressionTests::Product" /* DataCompressionTests.xctest */ = {isa = PBXFileReference; lastKnownFileType = file; path = DataCompressionTests.xctest; sourceTree = BUILT_PRODUCTS_DIR; }; 44 | OBJ_12 /* CompressionTest.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = CompressionTest.swift; sourceTree = ""; }; 45 | OBJ_13 /* XCTestManifests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = XCTestManifests.swift; sourceTree = ""; }; 46 | OBJ_17 /* CarthageSupport */ = {isa = PBXFileReference; lastKnownFileType = folder; path = CarthageSupport; sourceTree = SOURCE_ROOT; }; 47 | OBJ_18 /* LICENSE */ = {isa = PBXFileReference; lastKnownFileType = text; path = LICENSE; sourceTree = ""; }; 48 | OBJ_19 /* README.md */ = {isa = PBXFileReference; lastKnownFileType = net.daringfireball.markdown; path = README.md; sourceTree = ""; }; 49 | OBJ_20 /* DataCompression.podspec */ = {isa = PBXFileReference; lastKnownFileType = text; path = DataCompression.podspec; sourceTree = ""; }; 50 | OBJ_6 /* Package.swift */ = {isa = PBXFileReference; explicitFileType = sourcecode.swift; path = Package.swift; sourceTree = ""; }; 51 | OBJ_9 /* DataCompression.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = DataCompression.swift; sourceTree = ""; }; 52 | /* End PBXFileReference section */ 53 | 54 | /* Begin PBXFrameworksBuildPhase section */ 55 | OBJ_27 /* Frameworks */ = { 56 | isa = PBXFrameworksBuildPhase; 57 | buildActionMask = 0; 58 | files = ( 59 | ); 60 | runOnlyForDeploymentPostprocessing = 0; 61 | }; 62 | OBJ_46 /* Frameworks */ = { 63 | isa = PBXFrameworksBuildPhase; 64 | buildActionMask = 0; 65 | files = ( 66 | OBJ_47 /* DataCompression.framework in Frameworks */, 67 | ); 68 | runOnlyForDeploymentPostprocessing = 0; 69 | }; 70 | /* End PBXFrameworksBuildPhase section */ 71 | 72 | /* Begin PBXGroup section */ 73 | OBJ_10 /* Tests */ = { 74 | isa = PBXGroup; 75 | children = ( 76 | OBJ_11 /* DataCompressionTests */, 77 | ); 78 | name = Tests; 79 | sourceTree = SOURCE_ROOT; 80 | }; 81 | OBJ_11 /* DataCompressionTests */ = { 82 | isa = PBXGroup; 83 | children = ( 84 | OBJ_12 /* CompressionTest.swift */, 85 | OBJ_13 /* XCTestManifests.swift */, 86 | ); 87 | name = DataCompressionTests; 88 | path = Tests/DataCompressionTests; 89 | sourceTree = SOURCE_ROOT; 90 | }; 91 | OBJ_14 /* Products */ = { 92 | isa = PBXGroup; 93 | children = ( 94 | "DataCompression::DataCompressionTests::Product" /* DataCompressionTests.xctest */, 95 | "DataCompression::DataCompression::Product" /* DataCompression.framework */, 96 | ); 97 | name = Products; 98 | sourceTree = BUILT_PRODUCTS_DIR; 99 | }; 100 | OBJ_5 /* */ = { 101 | isa = PBXGroup; 102 | children = ( 103 | OBJ_6 /* Package.swift */, 104 | OBJ_7 /* Sources */, 105 | OBJ_10 /* Tests */, 106 | OBJ_14 /* Products */, 107 | OBJ_17 /* CarthageSupport */, 108 | OBJ_18 /* LICENSE */, 109 | OBJ_19 /* README.md */, 110 | OBJ_20 /* DataCompression.podspec */, 111 | ); 112 | name = ""; 113 | sourceTree = ""; 114 | }; 115 | OBJ_7 /* Sources */ = { 116 | isa = PBXGroup; 117 | children = ( 118 | OBJ_8 /* DataCompression */, 119 | ); 120 | name = Sources; 121 | sourceTree = SOURCE_ROOT; 122 | }; 123 | OBJ_8 /* DataCompression */ = { 124 | isa = PBXGroup; 125 | children = ( 126 | OBJ_9 /* DataCompression.swift */, 127 | ); 128 | name = DataCompression; 129 | path = Sources/DataCompression; 130 | sourceTree = SOURCE_ROOT; 131 | }; 132 | /* End PBXGroup section */ 133 | 134 | /* Begin PBXNativeTarget section */ 135 | "DataCompression::DataCompression" /* DataCompression */ = { 136 | isa = PBXNativeTarget; 137 | buildConfigurationList = OBJ_22 /* Build configuration list for PBXNativeTarget "DataCompression" */; 138 | buildPhases = ( 139 | OBJ_25 /* Sources */, 140 | OBJ_27 /* Frameworks */, 141 | ); 142 | buildRules = ( 143 | ); 144 | dependencies = ( 145 | ); 146 | name = DataCompression; 147 | productName = DataCompression; 148 | productReference = "DataCompression::DataCompression::Product" /* DataCompression.framework */; 149 | productType = "com.apple.product-type.framework"; 150 | }; 151 | "DataCompression::DataCompressionTests" /* DataCompressionTests */ = { 152 | isa = PBXNativeTarget; 153 | buildConfigurationList = OBJ_40 /* Build configuration list for PBXNativeTarget "DataCompressionTests" */; 154 | buildPhases = ( 155 | OBJ_43 /* Sources */, 156 | OBJ_46 /* Frameworks */, 157 | ); 158 | buildRules = ( 159 | ); 160 | dependencies = ( 161 | OBJ_48 /* PBXTargetDependency */, 162 | ); 163 | name = DataCompressionTests; 164 | productName = DataCompressionTests; 165 | productReference = "DataCompression::DataCompressionTests::Product" /* DataCompressionTests.xctest */; 166 | productType = "com.apple.product-type.bundle.unit-test"; 167 | }; 168 | "DataCompression::SwiftPMPackageDescription" /* DataCompressionPackageDescription */ = { 169 | isa = PBXNativeTarget; 170 | buildConfigurationList = OBJ_29 /* Build configuration list for PBXNativeTarget "DataCompressionPackageDescription" */; 171 | buildPhases = ( 172 | OBJ_32 /* Sources */, 173 | ); 174 | buildRules = ( 175 | ); 176 | dependencies = ( 177 | ); 178 | name = DataCompressionPackageDescription; 179 | productName = DataCompressionPackageDescription; 180 | productType = "com.apple.product-type.framework"; 181 | }; 182 | /* End PBXNativeTarget section */ 183 | 184 | /* Begin PBXProject section */ 185 | OBJ_1 /* Project object */ = { 186 | isa = PBXProject; 187 | attributes = { 188 | LastSwiftMigration = 9999; 189 | LastUpgradeCheck = 9999; 190 | }; 191 | buildConfigurationList = OBJ_2 /* Build configuration list for PBXProject "DataCompression" */; 192 | compatibilityVersion = "Xcode 3.2"; 193 | developmentRegion = English; 194 | hasScannedForEncodings = 0; 195 | knownRegions = ( 196 | en, 197 | ); 198 | mainGroup = OBJ_5 /* */; 199 | productRefGroup = OBJ_14 /* Products */; 200 | projectDirPath = ..; 201 | projectRoot = ""; 202 | targets = ( 203 | "DataCompression::DataCompression" /* DataCompression */, 204 | "DataCompression::SwiftPMPackageDescription" /* DataCompressionPackageDescription */, 205 | "DataCompression::DataCompressionPackageTests::ProductTarget" /* DataCompressionPackageTests */, 206 | "DataCompression::DataCompressionTests" /* DataCompressionTests */, 207 | ); 208 | }; 209 | /* End PBXProject section */ 210 | 211 | /* Begin PBXSourcesBuildPhase section */ 212 | OBJ_25 /* Sources */ = { 213 | isa = PBXSourcesBuildPhase; 214 | buildActionMask = 0; 215 | files = ( 216 | OBJ_26 /* DataCompression.swift in Sources */, 217 | ); 218 | runOnlyForDeploymentPostprocessing = 0; 219 | }; 220 | OBJ_32 /* Sources */ = { 221 | isa = PBXSourcesBuildPhase; 222 | buildActionMask = 0; 223 | files = ( 224 | OBJ_33 /* Package.swift in Sources */, 225 | ); 226 | runOnlyForDeploymentPostprocessing = 0; 227 | }; 228 | OBJ_43 /* Sources */ = { 229 | isa = PBXSourcesBuildPhase; 230 | buildActionMask = 0; 231 | files = ( 232 | OBJ_44 /* CompressionTest.swift in Sources */, 233 | OBJ_45 /* XCTestManifests.swift in Sources */, 234 | ); 235 | runOnlyForDeploymentPostprocessing = 0; 236 | }; 237 | /* End PBXSourcesBuildPhase section */ 238 | 239 | /* Begin PBXTargetDependency section */ 240 | OBJ_38 /* PBXTargetDependency */ = { 241 | isa = PBXTargetDependency; 242 | target = "DataCompression::DataCompressionTests" /* DataCompressionTests */; 243 | targetProxy = "DataCompression::DataCompressionTests" /* DataCompressionTests */; 244 | }; 245 | OBJ_48 /* PBXTargetDependency */ = { 246 | isa = PBXTargetDependency; 247 | target = "DataCompression::DataCompression" /* DataCompression */; 248 | targetProxy = 985A76C1222471FB0042A178 /* PBXContainerItemProxy */; 249 | }; 250 | /* End PBXTargetDependency section */ 251 | 252 | /* Begin XCBuildConfiguration section */ 253 | OBJ_23 /* Debug */ = { 254 | isa = XCBuildConfiguration; 255 | buildSettings = { 256 | ENABLE_TESTABILITY = YES; 257 | FRAMEWORK_SEARCH_PATHS = ( 258 | "$(inherited)", 259 | "$(PLATFORM_DIR)/Developer/Library/Frameworks", 260 | ); 261 | HEADER_SEARCH_PATHS = "$(inherited)"; 262 | INFOPLIST_FILE = CarthageSupport/DataCompression.xcodeproj/DataCompression_Info.plist; 263 | IPHONEOS_DEPLOYMENT_TARGET = 9.0; 264 | LD_RUNPATH_SEARCH_PATHS = "$(inherited) $(TOOLCHAIN_DIR)/usr/lib/swift/macosx"; 265 | MACOSX_DEPLOYMENT_TARGET = 10.11; 266 | OTHER_CFLAGS = "$(inherited)"; 267 | OTHER_LDFLAGS = "$(inherited)"; 268 | OTHER_SWIFT_FLAGS = "$(inherited)"; 269 | PRODUCT_BUNDLE_IDENTIFIER = DataCompression; 270 | PRODUCT_MODULE_NAME = "$(TARGET_NAME:c99extidentifier)"; 271 | PRODUCT_NAME = "$(TARGET_NAME:c99extidentifier)"; 272 | SKIP_INSTALL = YES; 273 | SWIFT_ACTIVE_COMPILATION_CONDITIONS = "$(inherited)"; 274 | SWIFT_VERSION = 5.0; 275 | TARGET_NAME = DataCompression; 276 | TVOS_DEPLOYMENT_TARGET = 9.0; 277 | WATCHOS_DEPLOYMENT_TARGET = 2.0; 278 | }; 279 | name = Debug; 280 | }; 281 | OBJ_24 /* Release */ = { 282 | isa = XCBuildConfiguration; 283 | buildSettings = { 284 | ENABLE_TESTABILITY = YES; 285 | FRAMEWORK_SEARCH_PATHS = ( 286 | "$(inherited)", 287 | "$(PLATFORM_DIR)/Developer/Library/Frameworks", 288 | ); 289 | HEADER_SEARCH_PATHS = "$(inherited)"; 290 | INFOPLIST_FILE = CarthageSupport/DataCompression.xcodeproj/DataCompression_Info.plist; 291 | IPHONEOS_DEPLOYMENT_TARGET = 9.0; 292 | LD_RUNPATH_SEARCH_PATHS = "$(inherited) $(TOOLCHAIN_DIR)/usr/lib/swift/macosx"; 293 | MACOSX_DEPLOYMENT_TARGET = 10.11; 294 | OTHER_CFLAGS = "$(inherited)"; 295 | OTHER_LDFLAGS = "$(inherited)"; 296 | OTHER_SWIFT_FLAGS = "$(inherited)"; 297 | PRODUCT_BUNDLE_IDENTIFIER = DataCompression; 298 | PRODUCT_MODULE_NAME = "$(TARGET_NAME:c99extidentifier)"; 299 | PRODUCT_NAME = "$(TARGET_NAME:c99extidentifier)"; 300 | SKIP_INSTALL = YES; 301 | SWIFT_ACTIVE_COMPILATION_CONDITIONS = "$(inherited)"; 302 | SWIFT_VERSION = 5.0; 303 | TARGET_NAME = DataCompression; 304 | TVOS_DEPLOYMENT_TARGET = 9.0; 305 | WATCHOS_DEPLOYMENT_TARGET = 2.0; 306 | }; 307 | name = Release; 308 | }; 309 | OBJ_3 /* Debug */ = { 310 | isa = XCBuildConfiguration; 311 | buildSettings = { 312 | CLANG_ENABLE_OBJC_ARC = YES; 313 | COMBINE_HIDPI_IMAGES = YES; 314 | COPY_PHASE_STRIP = NO; 315 | DEBUG_INFORMATION_FORMAT = dwarf; 316 | DYLIB_INSTALL_NAME_BASE = "@rpath"; 317 | ENABLE_NS_ASSERTIONS = YES; 318 | GCC_OPTIMIZATION_LEVEL = 0; 319 | GCC_PREPROCESSOR_DEFINITIONS = ( 320 | "$(inherited)", 321 | "SWIFT_PACKAGE=1", 322 | "DEBUG=1", 323 | ); 324 | ONLY_ACTIVE_ARCH = YES; 325 | OTHER_SWIFT_FLAGS = "-DXcode"; 326 | PRODUCT_NAME = "$(TARGET_NAME)"; 327 | SDKROOT = macosx; 328 | SUPPORTED_PLATFORMS = "macosx iphoneos iphonesimulator appletvos appletvsimulator watchos watchsimulator"; 329 | SWIFT_ACTIVE_COMPILATION_CONDITIONS = "$(inherited) SWIFT_PACKAGE DEBUG"; 330 | SWIFT_OPTIMIZATION_LEVEL = "-Onone"; 331 | SWIFT_VERSION = 5.0; 332 | USE_HEADERMAP = NO; 333 | }; 334 | name = Debug; 335 | }; 336 | OBJ_30 /* Debug */ = { 337 | isa = XCBuildConfiguration; 338 | buildSettings = { 339 | LD = /usr/bin/true; 340 | OTHER_SWIFT_FLAGS = "-swift-version 4 -I $(TOOLCHAIN_DIR)/usr/lib/swift/pm/4 -target x86_64-apple-macosx10.10 -sdk /Applications/Xcode.10.2.beta.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX10.14.sdk"; 341 | SWIFT_VERSION = 5.0; 342 | }; 343 | name = Debug; 344 | }; 345 | OBJ_31 /* Release */ = { 346 | isa = XCBuildConfiguration; 347 | buildSettings = { 348 | LD = /usr/bin/true; 349 | OTHER_SWIFT_FLAGS = "-swift-version 4 -I $(TOOLCHAIN_DIR)/usr/lib/swift/pm/4 -target x86_64-apple-macosx10.10 -sdk /Applications/Xcode.10.2.beta.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX10.14.sdk"; 350 | SWIFT_VERSION = 5.0; 351 | }; 352 | name = Release; 353 | }; 354 | OBJ_36 /* Debug */ = { 355 | isa = XCBuildConfiguration; 356 | buildSettings = { 357 | }; 358 | name = Debug; 359 | }; 360 | OBJ_37 /* Release */ = { 361 | isa = XCBuildConfiguration; 362 | buildSettings = { 363 | }; 364 | name = Release; 365 | }; 366 | OBJ_4 /* Release */ = { 367 | isa = XCBuildConfiguration; 368 | buildSettings = { 369 | CLANG_ENABLE_OBJC_ARC = YES; 370 | COMBINE_HIDPI_IMAGES = YES; 371 | COPY_PHASE_STRIP = YES; 372 | DEBUG_INFORMATION_FORMAT = "dwarf-with-dsym"; 373 | DYLIB_INSTALL_NAME_BASE = "@rpath"; 374 | GCC_OPTIMIZATION_LEVEL = s; 375 | GCC_PREPROCESSOR_DEFINITIONS = ( 376 | "$(inherited)", 377 | "SWIFT_PACKAGE=1", 378 | ); 379 | OTHER_SWIFT_FLAGS = "-DXcode"; 380 | PRODUCT_NAME = "$(TARGET_NAME)"; 381 | SDKROOT = macosx; 382 | SUPPORTED_PLATFORMS = "macosx iphoneos iphonesimulator appletvos appletvsimulator watchos watchsimulator"; 383 | SWIFT_ACTIVE_COMPILATION_CONDITIONS = "$(inherited) SWIFT_PACKAGE"; 384 | SWIFT_OPTIMIZATION_LEVEL = "-Owholemodule"; 385 | SWIFT_VERSION = 5.0; 386 | USE_HEADERMAP = NO; 387 | }; 388 | name = Release; 389 | }; 390 | OBJ_41 /* Debug */ = { 391 | isa = XCBuildConfiguration; 392 | buildSettings = { 393 | CLANG_ENABLE_MODULES = YES; 394 | EMBEDDED_CONTENT_CONTAINS_SWIFT = YES; 395 | FRAMEWORK_SEARCH_PATHS = ( 396 | "$(inherited)", 397 | "$(PLATFORM_DIR)/Developer/Library/Frameworks", 398 | ); 399 | HEADER_SEARCH_PATHS = "$(inherited)"; 400 | INFOPLIST_FILE = CarthageSupport/DataCompression.xcodeproj/DataCompressionTests_Info.plist; 401 | IPHONEOS_DEPLOYMENT_TARGET = 9.0; 402 | LD_RUNPATH_SEARCH_PATHS = "$(inherited) @loader_path/../Frameworks @loader_path/Frameworks"; 403 | MACOSX_DEPLOYMENT_TARGET = 10.11; 404 | OTHER_CFLAGS = "$(inherited)"; 405 | OTHER_LDFLAGS = "$(inherited)"; 406 | OTHER_SWIFT_FLAGS = "$(inherited)"; 407 | SWIFT_ACTIVE_COMPILATION_CONDITIONS = "$(inherited)"; 408 | SWIFT_VERSION = 5.0; 409 | TARGET_NAME = DataCompressionTests; 410 | TVOS_DEPLOYMENT_TARGET = 9.0; 411 | WATCHOS_DEPLOYMENT_TARGET = 2.0; 412 | }; 413 | name = Debug; 414 | }; 415 | OBJ_42 /* Release */ = { 416 | isa = XCBuildConfiguration; 417 | buildSettings = { 418 | CLANG_ENABLE_MODULES = YES; 419 | EMBEDDED_CONTENT_CONTAINS_SWIFT = YES; 420 | FRAMEWORK_SEARCH_PATHS = ( 421 | "$(inherited)", 422 | "$(PLATFORM_DIR)/Developer/Library/Frameworks", 423 | ); 424 | HEADER_SEARCH_PATHS = "$(inherited)"; 425 | INFOPLIST_FILE = CarthageSupport/DataCompression.xcodeproj/DataCompressionTests_Info.plist; 426 | IPHONEOS_DEPLOYMENT_TARGET = 9.0; 427 | LD_RUNPATH_SEARCH_PATHS = "$(inherited) @loader_path/../Frameworks @loader_path/Frameworks"; 428 | MACOSX_DEPLOYMENT_TARGET = 10.11; 429 | OTHER_CFLAGS = "$(inherited)"; 430 | OTHER_LDFLAGS = "$(inherited)"; 431 | OTHER_SWIFT_FLAGS = "$(inherited)"; 432 | SWIFT_ACTIVE_COMPILATION_CONDITIONS = "$(inherited)"; 433 | SWIFT_VERSION = 5.0; 434 | TARGET_NAME = DataCompressionTests; 435 | TVOS_DEPLOYMENT_TARGET = 9.0; 436 | WATCHOS_DEPLOYMENT_TARGET = 2.0; 437 | }; 438 | name = Release; 439 | }; 440 | /* End XCBuildConfiguration section */ 441 | 442 | /* Begin XCConfigurationList section */ 443 | OBJ_2 /* Build configuration list for PBXProject "DataCompression" */ = { 444 | isa = XCConfigurationList; 445 | buildConfigurations = ( 446 | OBJ_3 /* Debug */, 447 | OBJ_4 /* Release */, 448 | ); 449 | defaultConfigurationIsVisible = 0; 450 | defaultConfigurationName = Release; 451 | }; 452 | OBJ_22 /* Build configuration list for PBXNativeTarget "DataCompression" */ = { 453 | isa = XCConfigurationList; 454 | buildConfigurations = ( 455 | OBJ_23 /* Debug */, 456 | OBJ_24 /* Release */, 457 | ); 458 | defaultConfigurationIsVisible = 0; 459 | defaultConfigurationName = Release; 460 | }; 461 | OBJ_29 /* Build configuration list for PBXNativeTarget "DataCompressionPackageDescription" */ = { 462 | isa = XCConfigurationList; 463 | buildConfigurations = ( 464 | OBJ_30 /* Debug */, 465 | OBJ_31 /* Release */, 466 | ); 467 | defaultConfigurationIsVisible = 0; 468 | defaultConfigurationName = Release; 469 | }; 470 | OBJ_35 /* Build configuration list for PBXAggregateTarget "DataCompressionPackageTests" */ = { 471 | isa = XCConfigurationList; 472 | buildConfigurations = ( 473 | OBJ_36 /* Debug */, 474 | OBJ_37 /* Release */, 475 | ); 476 | defaultConfigurationIsVisible = 0; 477 | defaultConfigurationName = Release; 478 | }; 479 | OBJ_40 /* Build configuration list for PBXNativeTarget "DataCompressionTests" */ = { 480 | isa = XCConfigurationList; 481 | buildConfigurations = ( 482 | OBJ_41 /* Debug */, 483 | OBJ_42 /* Release */, 484 | ); 485 | defaultConfigurationIsVisible = 0; 486 | defaultConfigurationName = Release; 487 | }; 488 | /* End XCConfigurationList section */ 489 | }; 490 | rootObject = OBJ_1 /* Project object */; 491 | } 492 | -------------------------------------------------------------------------------- /Sources/DataCompression/DataCompression.swift: -------------------------------------------------------------------------------- 1 | /// 2 | /// DataCompression 3 | /// 4 | /// A libcompression wrapper as an extension for the `Data` type 5 | /// (GZIP, ZLIB, LZFSE, LZMA, LZ4, deflate, RFC-1950, RFC-1951, RFC-1952) 6 | /// 7 | /// Created by Markus Wanke, 2016/12/05 8 | /// 9 | 10 | 11 | /// 12 | /// Apache License, Version 2.0 13 | /// 14 | /// Copyright 2016, Markus Wanke 15 | /// 16 | /// Licensed under the Apache License, Version 2.0 (the "License"); 17 | /// you may not use this file except in compliance with the License. 18 | /// You may obtain a copy of the License at 19 | /// 20 | /// http://www.apache.org/licenses/LICENSE-2.0 21 | /// 22 | /// Unless required by applicable law or agreed to in writing, software 23 | /// distributed under the License is distributed on an "AS IS" BASIS, 24 | /// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 25 | /// See the License for the specific language governing permissions and 26 | /// limitations under the License. 27 | /// 28 | 29 | 30 | import Foundation 31 | import Compression 32 | 33 | public extension Data 34 | { 35 | /// Compresses the data. 36 | /// - parameter withAlgorithm: Compression algorithm to use. See the `CompressionAlgorithm` type 37 | /// - returns: compressed data 38 | func compress(withAlgorithm algo: CompressionAlgorithm) -> Data? 39 | { 40 | return self.withUnsafeBytes { (sourcePtr: UnsafePointer) -> Data? in 41 | let config = (operation: COMPRESSION_STREAM_ENCODE, algorithm: algo.lowLevelType) 42 | return perform(config, source: sourcePtr, sourceSize: count) 43 | } 44 | } 45 | 46 | /// Decompresses the data. 47 | /// - parameter withAlgorithm: Compression algorithm to use. See the `CompressionAlgorithm` type 48 | /// - returns: decompressed data 49 | func decompress(withAlgorithm algo: CompressionAlgorithm) -> Data? 50 | { 51 | return self.withUnsafeBytes { (sourcePtr: UnsafePointer) -> Data? in 52 | let config = (operation: COMPRESSION_STREAM_DECODE, algorithm: algo.lowLevelType) 53 | return perform(config, source: sourcePtr, sourceSize: count) 54 | } 55 | } 56 | 57 | /// Please consider the [libcompression documentation](https://developer.apple.com/reference/compression/1665429-data_compression) 58 | /// for further details. Short info: 59 | /// zlib : Aka deflate. Fast with a good compression rate. Proved itself over time and is supported everywhere. 60 | /// lzfse : Apples custom Lempel-Ziv style compression algorithm. Claims to compress as good as zlib but 2 to 3 times faster. 61 | /// lzma : Horribly slow. Compression as well as decompression. Compresses better than zlib though. 62 | /// lz4 : Fast, but compression rate is very bad. Apples lz4 implementation often to not compress at all. 63 | enum CompressionAlgorithm 64 | { 65 | case zlib 66 | case lzfse 67 | case lzma 68 | case lz4 69 | } 70 | 71 | /// Compresses the data using the zlib deflate algorithm. 72 | /// - returns: raw deflated data according to [RFC-1951](https://tools.ietf.org/html/rfc1951). 73 | /// - note: Fixed at compression level 5 (best trade off between speed and time) 74 | func deflate() -> Data? 75 | { 76 | return self.withUnsafeBytes { (sourcePtr: UnsafePointer) -> Data? in 77 | let config = (operation: COMPRESSION_STREAM_ENCODE, algorithm: COMPRESSION_ZLIB) 78 | return perform(config, source: sourcePtr, sourceSize: count) 79 | } 80 | } 81 | 82 | /// Decompresses the data using the zlib deflate algorithm. Self is expected to be a raw deflate 83 | /// stream according to [RFC-1951](https://tools.ietf.org/html/rfc1951). 84 | /// - returns: uncompressed data 85 | func inflate() -> Data? 86 | { 87 | return self.withUnsafeBytes { (sourcePtr: UnsafePointer) -> Data? in 88 | let config = (operation: COMPRESSION_STREAM_DECODE, algorithm: COMPRESSION_ZLIB) 89 | return perform(config, source: sourcePtr, sourceSize: count) 90 | } 91 | } 92 | 93 | /// Compresses the data using the deflate algorithm and makes it comply to the zlib format. 94 | /// - returns: deflated data in zlib format [RFC-1950](https://tools.ietf.org/html/rfc1950) 95 | /// - note: Fixed at compression level 5 (best trade off between speed and time) 96 | func zip() -> Data? 97 | { 98 | let header = Data([0x78, 0x5e]) 99 | 100 | let deflated = self.withUnsafeBytes { (sourcePtr: UnsafePointer) -> Data? in 101 | let config = (operation: COMPRESSION_STREAM_ENCODE, algorithm: COMPRESSION_ZLIB) 102 | return perform(config, source: sourcePtr, sourceSize: count, preload: header) 103 | } 104 | 105 | guard var result = deflated else { return nil } 106 | 107 | var adler = self.adler32().checksum.bigEndian 108 | result.append(Data(bytes: &adler, count: MemoryLayout.size)) 109 | 110 | return result 111 | } 112 | 113 | /// Decompresses the data using the zlib deflate algorithm. Self is expected to be a zlib deflate 114 | /// stream according to [RFC-1950](https://tools.ietf.org/html/rfc1950). 115 | /// - returns: uncompressed data 116 | func unzip(skipCheckSumValidation: Bool = true) -> Data? 117 | { 118 | // 2 byte header + 4 byte adler32 checksum 119 | let overhead = 6 120 | guard count > overhead else { return nil } 121 | 122 | let header: UInt16 = withUnsafeBytes { (ptr: UnsafePointer) -> UInt16 in 123 | return ptr.pointee.bigEndian 124 | } 125 | 126 | // check for the deflate stream bit 127 | guard header >> 8 & 0b1111 == 0b1000 else { return nil } 128 | // check the header checksum 129 | guard header % 31 == 0 else { return nil } 130 | 131 | let cresult: Data? = withUnsafeBytes { (ptr: UnsafePointer) -> Data? in 132 | let source = ptr.advanced(by: 2) 133 | let config = (operation: COMPRESSION_STREAM_DECODE, algorithm: COMPRESSION_ZLIB) 134 | return perform(config, source: source, sourceSize: count - overhead) 135 | } 136 | 137 | guard let inflated = cresult else { return nil } 138 | 139 | if skipCheckSumValidation { return inflated } 140 | 141 | let cksum = Data(self.suffix(from: count - 4)).withUnsafeBytes { rawPtr in 142 | return rawPtr.load(as: UInt32.self).bigEndian 143 | } 144 | 145 | return cksum == inflated.adler32().checksum ? inflated : nil 146 | } 147 | 148 | /// Compresses the data using the deflate algorithm and makes it comply to the gzip stream format. 149 | /// - returns: deflated data in gzip format [RFC-1952](https://tools.ietf.org/html/rfc1952) 150 | /// - note: Fixed at compression level 5 (best trade off between speed and time) 151 | func gzip() -> Data? 152 | { 153 | var header = Data([0x1f, 0x8b, 0x08, 0x00]) // magic, magic, deflate, noflags 154 | 155 | var unixtime = UInt32(Date().timeIntervalSince1970).littleEndian 156 | header.append(Data(bytes: &unixtime, count: MemoryLayout.size)) 157 | 158 | header.append(contentsOf: [0x00, 0x03]) // normal compression level, unix file type 159 | 160 | let deflated = self.withUnsafeBytes { (sourcePtr: UnsafePointer) -> Data? in 161 | let config = (operation: COMPRESSION_STREAM_ENCODE, algorithm: COMPRESSION_ZLIB) 162 | return perform(config, source: sourcePtr, sourceSize: count, preload: header) 163 | } 164 | 165 | guard var result = deflated else { return nil } 166 | 167 | // append checksum 168 | var crc32: UInt32 = self.crc32().checksum.littleEndian 169 | result.append(Data(bytes: &crc32, count: MemoryLayout.size)) 170 | 171 | // append size of original data 172 | var isize: UInt32 = UInt32(truncatingIfNeeded: count).littleEndian 173 | result.append(Data(bytes: &isize, count: MemoryLayout.size)) 174 | 175 | return result 176 | } 177 | 178 | /// Decompresses the data using the gzip deflate algorithm. Self is expected to be a gzip deflate 179 | /// stream according to [RFC-1952](https://tools.ietf.org/html/rfc1952). 180 | /// - returns: uncompressed data 181 | func gunzip() -> Data? 182 | { 183 | // 10 byte header + data + 8 byte footer. See https://tools.ietf.org/html/rfc1952#section-2 184 | let overhead = 10 + 8 185 | guard count >= overhead else { return nil } 186 | 187 | 188 | typealias GZipHeader = (id1: UInt8, id2: UInt8, cm: UInt8, flg: UInt8, xfl: UInt8, os: UInt8) 189 | let hdr: GZipHeader = withUnsafeBytes { (ptr: UnsafePointer) -> GZipHeader in 190 | // +---+---+---+---+---+---+---+---+---+---+ 191 | // |ID1|ID2|CM |FLG| MTIME |XFL|OS | 192 | // +---+---+---+---+---+---+---+---+---+---+ 193 | return (id1: ptr[0], id2: ptr[1], cm: ptr[2], flg: ptr[3], xfl: ptr[8], os: ptr[9]) 194 | } 195 | 196 | typealias GZipFooter = (crc32: UInt32, isize: UInt32) 197 | let alignedFtr = Data(self.suffix(from: count - 8)) 198 | let ftr: GZipFooter = alignedFtr.withUnsafeBytes { (ptr: UnsafePointer) -> GZipFooter in 199 | // +---+---+---+---+---+---+---+---+ 200 | // | CRC32 | ISIZE | 201 | // +---+---+---+---+---+---+---+---+ 202 | return (ptr[0].littleEndian, ptr[1].littleEndian) 203 | } 204 | 205 | // Wrong gzip magic or unsupported compression method 206 | guard hdr.id1 == 0x1f && hdr.id2 == 0x8b && hdr.cm == 0x08 else { return nil } 207 | 208 | let has_crc16: Bool = hdr.flg & 0b00010 != 0 209 | let has_extra: Bool = hdr.flg & 0b00100 != 0 210 | let has_fname: Bool = hdr.flg & 0b01000 != 0 211 | let has_cmmnt: Bool = hdr.flg & 0b10000 != 0 212 | 213 | let cresult: Data? = withUnsafeBytes { (ptr: UnsafePointer) -> Data? in 214 | var pos = 10 ; let limit = count - 8 215 | 216 | if has_extra { 217 | pos += ptr.advanced(by: pos).withMemoryRebound(to: UInt16.self, capacity: 1) { 218 | return Int($0.pointee.littleEndian) + 2 // +2 for xlen 219 | } 220 | } 221 | if has_fname { 222 | while pos < limit && ptr[pos] != 0x0 { pos += 1 } 223 | pos += 1 // skip null byte as well 224 | } 225 | if has_cmmnt { 226 | while pos < limit && ptr[pos] != 0x0 { pos += 1 } 227 | pos += 1 // skip null byte as well 228 | } 229 | if has_crc16 { 230 | pos += 2 // ignoring header crc16 231 | } 232 | 233 | guard pos < limit else { return nil } 234 | let config = (operation: COMPRESSION_STREAM_DECODE, algorithm: COMPRESSION_ZLIB) 235 | return perform(config, source: ptr.advanced(by: pos), sourceSize: limit - pos) 236 | } 237 | 238 | guard let inflated = cresult else { return nil } 239 | guard ftr.isize == UInt32(truncatingIfNeeded: inflated.count) else { return nil } 240 | guard ftr.crc32 == inflated.crc32().checksum else { return nil } 241 | return inflated 242 | } 243 | 244 | /// Calculate the Adler32 checksum of the data. 245 | /// - returns: Adler32 checksum type. Can still be further advanced. 246 | func adler32() -> Adler32 247 | { 248 | var res = Adler32() 249 | res.advance(withChunk: self) 250 | return res 251 | } 252 | 253 | /// Calculate the Crc32 checksum of the data. 254 | /// - returns: Crc32 checksum type. Can still be further advanced. 255 | func crc32() -> Crc32 256 | { 257 | var res = Crc32() 258 | res.advance(withChunk: self) 259 | return res 260 | } 261 | } 262 | 263 | 264 | 265 | 266 | /// Struct based type representing a Crc32 checksum. 267 | public struct Crc32: CustomStringConvertible 268 | { 269 | private static let zLibCrc32: ZLibCrc32FuncPtr? = loadCrc32fromZLib() 270 | 271 | public init() {} 272 | 273 | // C convention function pointer type matching the signature of `libz::crc32` 274 | private typealias ZLibCrc32FuncPtr = @convention(c) ( 275 | _ cks: UInt32, 276 | _ buf: UnsafePointer, 277 | _ len: UInt32 278 | ) -> UInt32 279 | 280 | /// Raw checksum. Updated after a every call to `advance(withChunk:)` 281 | public var checksum: UInt32 = 0 282 | 283 | /// Advance the current checksum with a chunk of data. Designed t be called multiple times. 284 | /// - parameter chunk: data to advance the checksum 285 | public mutating func advance(withChunk chunk: Data) 286 | { 287 | if let fastCrc32 = Crc32.zLibCrc32 { 288 | checksum = chunk.withUnsafeBytes({ (ptr: UnsafePointer) -> UInt32 in 289 | return fastCrc32(checksum, ptr, UInt32(chunk.count)) 290 | }) 291 | } 292 | else { 293 | checksum = slowCrc32(start: checksum, data: chunk) 294 | } 295 | } 296 | 297 | /// Formatted checksum. 298 | public var description: String 299 | { 300 | return String(format: "%08x", checksum) 301 | } 302 | 303 | /// Load `crc32()` from '/usr/lib/libz.dylib' if libz is installed. 304 | /// - returns: A function pointer to crc32() of zlib or nil if zlib can't be found 305 | private static func loadCrc32fromZLib() -> ZLibCrc32FuncPtr? 306 | { 307 | guard let libz = dlopen("/usr/lib/libz.dylib", RTLD_NOW) else { return nil } 308 | guard let fptr = dlsym(libz, "crc32") else { return nil } 309 | return unsafeBitCast(fptr, to: ZLibCrc32FuncPtr.self) 310 | } 311 | 312 | /// Rudimentary fallback implementation of the crc32 checksum. This is only a backup used 313 | /// when zlib can't be found under '/usr/lib/libz.dylib'. 314 | /// - returns: crc32 checksum (4 byte) 315 | private func slowCrc32(start: UInt32, data: Data) -> UInt32 316 | { 317 | return ~data.reduce(~start) { (crc: UInt32, next: UInt8) -> UInt32 in 318 | let tableOffset = (crc ^ UInt32(next)) & 0xff 319 | return lookUpTable[Int(tableOffset)] ^ crc >> 8 320 | } 321 | } 322 | 323 | /// Lookup table for faster crc32 calculation. 324 | /// table source: http://web.mit.edu/freebsd/head/sys/libkern/crc32.c 325 | private let lookUpTable: [UInt32] = [ 326 | 0x00000000, 0x77073096, 0xee0e612c, 0x990951ba, 0x076dc419, 0x706af48f, 0xe963a535, 0x9e6495a3, 327 | 0x0edb8832, 0x79dcb8a4, 0xe0d5e91e, 0x97d2d988, 0x09b64c2b, 0x7eb17cbd, 0xe7b82d07, 0x90bf1d91, 328 | 0x1db71064, 0x6ab020f2, 0xf3b97148, 0x84be41de, 0x1adad47d, 0x6ddde4eb, 0xf4d4b551, 0x83d385c7, 329 | 0x136c9856, 0x646ba8c0, 0xfd62f97a, 0x8a65c9ec, 0x14015c4f, 0x63066cd9, 0xfa0f3d63, 0x8d080df5, 330 | 0x3b6e20c8, 0x4c69105e, 0xd56041e4, 0xa2677172, 0x3c03e4d1, 0x4b04d447, 0xd20d85fd, 0xa50ab56b, 331 | 0x35b5a8fa, 0x42b2986c, 0xdbbbc9d6, 0xacbcf940, 0x32d86ce3, 0x45df5c75, 0xdcd60dcf, 0xabd13d59, 332 | 0x26d930ac, 0x51de003a, 0xc8d75180, 0xbfd06116, 0x21b4f4b5, 0x56b3c423, 0xcfba9599, 0xb8bda50f, 333 | 0x2802b89e, 0x5f058808, 0xc60cd9b2, 0xb10be924, 0x2f6f7c87, 0x58684c11, 0xc1611dab, 0xb6662d3d, 334 | 0x76dc4190, 0x01db7106, 0x98d220bc, 0xefd5102a, 0x71b18589, 0x06b6b51f, 0x9fbfe4a5, 0xe8b8d433, 335 | 0x7807c9a2, 0x0f00f934, 0x9609a88e, 0xe10e9818, 0x7f6a0dbb, 0x086d3d2d, 0x91646c97, 0xe6635c01, 336 | 0x6b6b51f4, 0x1c6c6162, 0x856530d8, 0xf262004e, 0x6c0695ed, 0x1b01a57b, 0x8208f4c1, 0xf50fc457, 337 | 0x65b0d9c6, 0x12b7e950, 0x8bbeb8ea, 0xfcb9887c, 0x62dd1ddf, 0x15da2d49, 0x8cd37cf3, 0xfbd44c65, 338 | 0x4db26158, 0x3ab551ce, 0xa3bc0074, 0xd4bb30e2, 0x4adfa541, 0x3dd895d7, 0xa4d1c46d, 0xd3d6f4fb, 339 | 0x4369e96a, 0x346ed9fc, 0xad678846, 0xda60b8d0, 0x44042d73, 0x33031de5, 0xaa0a4c5f, 0xdd0d7cc9, 340 | 0x5005713c, 0x270241aa, 0xbe0b1010, 0xc90c2086, 0x5768b525, 0x206f85b3, 0xb966d409, 0xce61e49f, 341 | 0x5edef90e, 0x29d9c998, 0xb0d09822, 0xc7d7a8b4, 0x59b33d17, 0x2eb40d81, 0xb7bd5c3b, 0xc0ba6cad, 342 | 0xedb88320, 0x9abfb3b6, 0x03b6e20c, 0x74b1d29a, 0xead54739, 0x9dd277af, 0x04db2615, 0x73dc1683, 343 | 0xe3630b12, 0x94643b84, 0x0d6d6a3e, 0x7a6a5aa8, 0xe40ecf0b, 0x9309ff9d, 0x0a00ae27, 0x7d079eb1, 344 | 0xf00f9344, 0x8708a3d2, 0x1e01f268, 0x6906c2fe, 0xf762575d, 0x806567cb, 0x196c3671, 0x6e6b06e7, 345 | 0xfed41b76, 0x89d32be0, 0x10da7a5a, 0x67dd4acc, 0xf9b9df6f, 0x8ebeeff9, 0x17b7be43, 0x60b08ed5, 346 | 0xd6d6a3e8, 0xa1d1937e, 0x38d8c2c4, 0x4fdff252, 0xd1bb67f1, 0xa6bc5767, 0x3fb506dd, 0x48b2364b, 347 | 0xd80d2bda, 0xaf0a1b4c, 0x36034af6, 0x41047a60, 0xdf60efc3, 0xa867df55, 0x316e8eef, 0x4669be79, 348 | 0xcb61b38c, 0xbc66831a, 0x256fd2a0, 0x5268e236, 0xcc0c7795, 0xbb0b4703, 0x220216b9, 0x5505262f, 349 | 0xc5ba3bbe, 0xb2bd0b28, 0x2bb45a92, 0x5cb36a04, 0xc2d7ffa7, 0xb5d0cf31, 0x2cd99e8b, 0x5bdeae1d, 350 | 0x9b64c2b0, 0xec63f226, 0x756aa39c, 0x026d930a, 0x9c0906a9, 0xeb0e363f, 0x72076785, 0x05005713, 351 | 0x95bf4a82, 0xe2b87a14, 0x7bb12bae, 0x0cb61b38, 0x92d28e9b, 0xe5d5be0d, 0x7cdcefb7, 0x0bdbdf21, 352 | 0x86d3d2d4, 0xf1d4e242, 0x68ddb3f8, 0x1fda836e, 0x81be16cd, 0xf6b9265b, 0x6fb077e1, 0x18b74777, 353 | 0x88085ae6, 0xff0f6a70, 0x66063bca, 0x11010b5c, 0x8f659eff, 0xf862ae69, 0x616bffd3, 0x166ccf45, 354 | 0xa00ae278, 0xd70dd2ee, 0x4e048354, 0x3903b3c2, 0xa7672661, 0xd06016f7, 0x4969474d, 0x3e6e77db, 355 | 0xaed16a4a, 0xd9d65adc, 0x40df0b66, 0x37d83bf0, 0xa9bcae53, 0xdebb9ec5, 0x47b2cf7f, 0x30b5ffe9, 356 | 0xbdbdf21c, 0xcabac28a, 0x53b39330, 0x24b4a3a6, 0xbad03605, 0xcdd70693, 0x54de5729, 0x23d967bf, 357 | 0xb3667a2e, 0xc4614ab8, 0x5d681b02, 0x2a6f2b94, 0xb40bbe37, 0xc30c8ea1, 0x5a05df1b, 0x2d02ef8d, 358 | ] 359 | } 360 | 361 | 362 | 363 | 364 | 365 | /// Struct based type representing a Adler32 checksum. 366 | public struct Adler32: CustomStringConvertible 367 | { 368 | private static let zLibAdler32: ZLibAdler32FuncPtr? = loadAdler32fromZLib() 369 | 370 | public init() {} 371 | 372 | // C convention function pointer type matching the signature of `libz::adler32` 373 | private typealias ZLibAdler32FuncPtr = @convention(c) ( 374 | _ cks: UInt32, 375 | _ buf: UnsafePointer, 376 | _ len: UInt32 377 | ) -> UInt32 378 | 379 | /// Raw checksum. Updated after a every call to `advance(withChunk:)` 380 | public var checksum: UInt32 = 1 381 | 382 | /// Advance the current checksum with a chunk of data. Designed t be called multiple times. 383 | /// - parameter chunk: data to advance the checksum 384 | public mutating func advance(withChunk chunk: Data) 385 | { 386 | if let fastAdler32 = Adler32.zLibAdler32 { 387 | checksum = chunk.withUnsafeBytes({ (ptr: UnsafePointer) -> UInt32 in 388 | return fastAdler32(checksum, ptr, UInt32(chunk.count)) 389 | }) 390 | } 391 | else { 392 | checksum = slowAdler32(start: checksum, data: chunk) 393 | } 394 | } 395 | 396 | /// Formatted checksum. 397 | public var description: String 398 | { 399 | return String(format: "%08x", checksum) 400 | } 401 | 402 | /// Load `adler32()` from '/usr/lib/libz.dylib' if libz is installed. 403 | /// - returns: A function pointer to adler32() of zlib or nil if zlib can't be found 404 | private static func loadAdler32fromZLib() -> ZLibAdler32FuncPtr? 405 | { 406 | guard let libz = dlopen("/usr/lib/libz.dylib", RTLD_NOW) else { return nil } 407 | guard let fptr = dlsym(libz, "adler32") else { return nil } 408 | return unsafeBitCast(fptr, to: ZLibAdler32FuncPtr.self) 409 | } 410 | 411 | /// Rudimentary fallback implementation of the adler32 checksum. This is only a backup used 412 | /// when zlib can't be found under '/usr/lib/libz.dylib'. 413 | /// - returns: adler32 checksum (4 byte) 414 | private func slowAdler32(start: UInt32, data: Data) -> UInt32 415 | { 416 | var s1: UInt32 = start & 0xffff 417 | var s2: UInt32 = (start >> 16) & 0xffff 418 | let prime: UInt32 = 65521 419 | 420 | for byte in data { 421 | s1 += UInt32(byte) 422 | if s1 >= prime { s1 = s1 % prime } 423 | s2 += s1 424 | if s2 >= prime { s2 = s2 % prime } 425 | } 426 | return (s2 << 16) | s1 427 | } 428 | } 429 | 430 | 431 | 432 | fileprivate extension Data 433 | { 434 | func withUnsafeBytes(_ body: (UnsafePointer) throws -> ResultType) rethrows -> ResultType 435 | { 436 | return try self.withUnsafeBytes({ (rawBufferPointer: UnsafeRawBufferPointer) -> ResultType in 437 | return try body(rawBufferPointer.bindMemory(to: ContentType.self).baseAddress!) 438 | }) 439 | } 440 | } 441 | 442 | fileprivate extension Data.CompressionAlgorithm 443 | { 444 | var lowLevelType: compression_algorithm { 445 | switch self { 446 | case .zlib : return COMPRESSION_ZLIB 447 | case .lzfse : return COMPRESSION_LZFSE 448 | case .lz4 : return COMPRESSION_LZ4 449 | case .lzma : return COMPRESSION_LZMA 450 | } 451 | } 452 | } 453 | 454 | 455 | fileprivate typealias Config = (operation: compression_stream_operation, algorithm: compression_algorithm) 456 | 457 | 458 | fileprivate func perform(_ config: Config, source: UnsafePointer, sourceSize: Int, preload: Data = Data()) -> Data? 459 | { 460 | guard config.operation == COMPRESSION_STREAM_ENCODE || sourceSize > 0 else { return nil } 461 | 462 | let streamBase = UnsafeMutablePointer.allocate(capacity: 1) 463 | defer { streamBase.deallocate() } 464 | var stream = streamBase.pointee 465 | 466 | let status = compression_stream_init(&stream, config.operation, config.algorithm) 467 | guard status != COMPRESSION_STATUS_ERROR else { return nil } 468 | defer { compression_stream_destroy(&stream) } 469 | 470 | var result = preload 471 | var flags: Int32 = Int32(COMPRESSION_STREAM_FINALIZE.rawValue) 472 | let blockLimit = 64 * 1024 473 | var bufferSize = Swift.max(sourceSize, 64) 474 | 475 | if sourceSize > blockLimit { 476 | bufferSize = blockLimit 477 | if config.algorithm == COMPRESSION_LZFSE && config.operation != COMPRESSION_STREAM_ENCODE { 478 | // This fixes a bug in Apples lzfse decompressor. it will sometimes fail randomly when the input gets 479 | // splitted into multiple chunks and the flag is not 0. Even though it should always work with FINALIZE... 480 | flags = 0 481 | } 482 | } 483 | 484 | let buffer = UnsafeMutablePointer.allocate(capacity: bufferSize) 485 | defer { buffer.deallocate() } 486 | 487 | stream.dst_ptr = buffer 488 | stream.dst_size = bufferSize 489 | stream.src_ptr = source 490 | stream.src_size = sourceSize 491 | 492 | while true { 493 | switch compression_stream_process(&stream, flags) { 494 | case COMPRESSION_STATUS_OK: 495 | guard stream.dst_size == 0 else { return nil } 496 | result.append(buffer, count: stream.dst_ptr - buffer) 497 | stream.dst_ptr = buffer 498 | stream.dst_size = bufferSize 499 | 500 | if flags == 0 && stream.src_size == 0 { // part of the lzfse bugfix above 501 | flags = Int32(COMPRESSION_STREAM_FINALIZE.rawValue) 502 | } 503 | 504 | case COMPRESSION_STATUS_END: 505 | result.append(buffer, count: stream.dst_ptr - buffer) 506 | return result 507 | 508 | default: 509 | return nil 510 | } 511 | } 512 | } 513 | --------------------------------------------------------------------------------