Gzip.swift 9.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290
  1. //
  2. // DataGzip.swift
  3. //
  4. /*
  5. The MIT License (MIT)
  6. © 2014-2019 1024jp <wolfrosch.com>
  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. The above copyright notice and this permission notice shall be included in
  14. all copies or substantial portions of the Software.
  15. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  16. IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  17. FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  18. AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  19. LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  20. OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
  21. THE SOFTWARE.
  22. */
  23. import Foundation
  24. import Binary
  25. #if os(Linux)
  26. import zlibLinux
  27. #else
  28. import zlib
  29. #endif
  30. /// Compression level whose rawValue is based on the zlib's constants.
  31. public struct CompressionLevel: RawRepresentable {
  32. public static let noCompression = CompressionLevel(rawValue: Z_NO_COMPRESSION)
  33. public static let bestSpeed = CompressionLevel(rawValue: Z_BEST_SPEED)
  34. public static let bestCompression = CompressionLevel(rawValue: Z_BEST_COMPRESSION)
  35. public static let defaultCompression = CompressionLevel(rawValue: Z_DEFAULT_COMPRESSION)
  36. /// Compression level in the range of `0` (no compression) to `9` (maximum compression).
  37. public let rawValue: Int32
  38. public init(rawValue: Int32) {
  39. self.rawValue = rawValue
  40. }
  41. }
  42. /// Errors on gzipping/gunzipping based on the zlib error codes.
  43. public struct GzipError: Swift.Error {
  44. // cf. http://www.zlib.net/manual.html
  45. public enum Kind: Equatable {
  46. /// The stream structure was inconsistent.
  47. ///
  48. /// - underlying zlib error: `Z_STREAM_ERROR` (-2)
  49. case stream
  50. /// The input data was corrupted
  51. /// (input stream not conforming to the zlib format or incorrect check value).
  52. ///
  53. /// - underlying zlib error: `Z_DATA_ERROR` (-3)
  54. case data
  55. /// There was not enough memory.
  56. ///
  57. /// - underlying zlib error: `Z_MEM_ERROR` (-4)
  58. case memory
  59. /// No progress is possible or there was not enough room in the output buffer.
  60. ///
  61. /// - underlying zlib error: `Z_BUF_ERROR` (-5)
  62. case buffer
  63. /// The zlib library version is incompatible with the version assumed by the caller.
  64. ///
  65. /// - underlying zlib error: `Z_VERSION_ERROR` (-6)
  66. case version
  67. /// An unknown error occurred.
  68. ///
  69. /// - parameter code: return error by zlib
  70. case unknown(code: Int)
  71. }
  72. /// Error kind.
  73. public let kind: Kind
  74. /// Returned message by zlib.
  75. public let message: String
  76. internal init(code: Int32, msg: UnsafePointer<CChar>?) {
  77. self.message = {
  78. guard let msg = msg, let message = String(validatingUTF8: msg) else {
  79. return "Unknown gzip error"
  80. }
  81. return message
  82. }()
  83. self.kind = {
  84. switch code {
  85. case Z_STREAM_ERROR:
  86. return .stream
  87. case Z_DATA_ERROR:
  88. return .data
  89. case Z_MEM_ERROR:
  90. return .memory
  91. case Z_BUF_ERROR:
  92. return .buffer
  93. case Z_VERSION_ERROR:
  94. return .version
  95. default:
  96. return .unknown(code: Int(code))
  97. }
  98. }()
  99. }
  100. public var localizedDescription: String { message }
  101. }
  102. extension Bytes {
  103. /// Whether the receiver is compressed in gzip format.
  104. public var isGzipped: Bool {
  105. starts(with: [0x1f, 0x8b]) // check magic number
  106. }
  107. /// Create a new `Data` object by compressing the receiver using zlib.
  108. /// Throws an error if compression failed.
  109. ///
  110. /// - Parameter level: Compression level.
  111. /// - Returns: Gzip-compressed `Data` object.
  112. /// - Throws: `GzipError`
  113. public func gzipped(level: CompressionLevel = .defaultCompression) throws -> Bytes {
  114. guard !isEmpty else { return Bytes() }
  115. var stream = z_stream()
  116. var status: Int32
  117. status = deflateInit2_(&stream,
  118. level.rawValue,
  119. Z_DEFLATED, MAX_WBITS + 16,
  120. MAX_MEM_LEVEL,
  121. Z_DEFAULT_STRATEGY,
  122. ZLIB_VERSION,
  123. Int32(DataSize.stream))
  124. guard status == Z_OK else {
  125. // deflateInit2 returns:
  126. // Z_VERSION_ERROR The zlib library version is incompatible with the version assumed by the caller.
  127. // Z_MEM_ERROR There was not enough memory.
  128. // Z_STREAM_ERROR A parameter is invalid.
  129. throw GzipError(code: status, msg: stream.msg)
  130. }
  131. var out = Bytes(lenght: DataSize.chunk)
  132. repeat {
  133. if Int(stream.total_out) >= out.count {
  134. out += Bytes(lenght: DataSize.chunk)
  135. }
  136. let outputCount = out.count
  137. try withUnsafeBytes { input in
  138. guard let pointer = input.bindMemory(to: Bytef.self).baseAddress else {
  139. throw GzipError.init(code: 0, msg: nil)
  140. }
  141. stream.next_in = UnsafeMutablePointer<Bytef>(mutating: pointer).advanced(by: Int(stream.total_in))
  142. stream.avail_in = uInt(count) - uInt(stream.total_in)
  143. try out.withUnsafeMutableBytes { output in
  144. guard let pointer = output.bindMemory(to: Bytef.self).baseAddress else {
  145. throw GzipError.init(code: 0, msg: nil)
  146. }
  147. stream.next_out = pointer.advanced(by: Int(stream.total_out))
  148. stream.avail_out = uInt(outputCount) - uInt(stream.total_out)
  149. status = deflate(&stream, Z_FINISH)
  150. stream.next_out = nil
  151. }
  152. stream.next_in = nil
  153. }
  154. } while stream.avail_out == 0
  155. guard deflateEnd(&stream) == Z_OK, status == Z_STREAM_END else {
  156. throw GzipError(code: status, msg: stream.msg)
  157. }
  158. return out.prefix(Int(stream.total_out))
  159. }
  160. /// Create a new `Data` object by decompressing the receiver using zlib.
  161. /// Throws an error if decompression failed.
  162. ///
  163. /// - Returns: Gzip-decompressed `Data` object.
  164. /// - Throws: `GzipError`
  165. public func gunzipped() throws -> Bytes {
  166. guard !isEmpty else { return Bytes() }
  167. var stream = z_stream()
  168. var status: Int32
  169. status = inflateInit2_(&stream, MAX_WBITS + 32, ZLIB_VERSION, Int32(DataSize.stream))
  170. guard status == Z_OK else {
  171. // inflateInit2 returns:
  172. // Z_VERSION_ERROR The zlib library version is incompatible with the version assumed by the caller.
  173. // Z_MEM_ERROR There was not enough memory.
  174. // Z_STREAM_ERROR A parameters are invalid.
  175. throw GzipError(code: status, msg: stream.msg)
  176. }
  177. var out = Bytes(lenght: count * 2)
  178. repeat {
  179. if Int(stream.total_out) >= out.count {
  180. out += Bytes(lenght: count * 2)
  181. }
  182. let outputCount = out.count
  183. try withUnsafeBytes { input in
  184. guard let pointer = input.bindMemory(to: Bytef.self).baseAddress else {
  185. throw GzipError.init(code: 0, msg: nil)
  186. }
  187. stream.next_in = UnsafeMutablePointer<Bytef>(mutating: pointer).advanced(by: Int(stream.total_in))
  188. stream.avail_in = uInt(count) - uInt(stream.total_in)
  189. try out.withUnsafeMutableBytes { output in
  190. guard let pointer = output.bindMemory(to: Bytef.self).baseAddress else {
  191. throw GzipError.init(code: 0, msg: nil)
  192. }
  193. stream.next_out = pointer.advanced(by: Int(stream.total_out))
  194. stream.avail_out = uInt(outputCount) - uInt(stream.total_out)
  195. status = inflate(&stream, Z_SYNC_FLUSH)
  196. stream.next_out = nil
  197. }
  198. stream.next_in = nil
  199. }
  200. } while status == Z_OK
  201. guard inflateEnd(&stream) == Z_OK, status == Z_STREAM_END else {
  202. // inflate returns:
  203. // Z_DATA_ERROR The input data was corrupted (input stream not conforming to the zlib format or incorrect check value).
  204. // Z_STREAM_ERROR The stream structure was inconsistent (for example if next_in or next_out was NULL).
  205. // Z_MEM_ERROR There was not enough memory.
  206. // Z_BUF_ERROR No progress is possible or there was not enough room in the output buffer when Z_FINISH is used.
  207. throw GzipError(code: status, msg: stream.msg)
  208. }
  209. return out.prefix(Int(stream.total_out))
  210. }
  211. }
  212. private struct DataSize {
  213. static let chunk = 1 << 14
  214. static let stream = MemoryLayout<z_stream>.size
  215. }