Skip to content

Commit

Permalink
fix lint
Browse files Browse the repository at this point in the history
  • Loading branch information
marandaneto committed Oct 24, 2023
1 parent 37058c9 commit 53483ad
Show file tree
Hide file tree
Showing 3 changed files with 77 additions and 103 deletions.
6 changes: 2 additions & 4 deletions .swiftlint.yml
Original file line number Diff line number Diff line change
@@ -1,12 +1,10 @@
excluded: # case-sensitive paths to ignore during linting. Takes precedence over `included`
- PostHogExample
- PostHogExampleWithSPM
- PostHogTests
- PostHog/Recording
- PostHog/Utils/MethodSwizzler.swift
- PostHog/Utils/ReadWriteLock.swift
- PostHog/Utils/Reachability.swift
- PostHog/Utils/NSData+PHGGZIP.h
- PostHog/Utils/NSData+PHGGZIP.m
- PostHog/Utils/Data+Gzip.swift
- .build
- Pods

Expand Down
168 changes: 72 additions & 96 deletions PostHog/Utils/Data+Gzip.swift
Original file line number Diff line number Diff line change
Expand Up @@ -5,19 +5,19 @@

/*
The MIT License (MIT)

© 2014-2023 1024jp <wolfrosch.com>

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
Expand All @@ -36,100 +36,85 @@ import struct Foundation.Data
#endif

public enum Gzip {

/// Maximum value for windowBits (`MAX_WBITS`)
public static let maxWindowBits = MAX_WBITS
}


/// Compression level whose rawValue is based on the zlib's constants.
public struct CompressionLevel: RawRepresentable, Sendable {

/// Compression level in the range of `0` (no compression) to `9` (maximum compression).
public let rawValue: Int32

public static let noCompression = Self(Z_NO_COMPRESSION)
public static let bestSpeed = Self(Z_BEST_SPEED)
public static let bestCompression = Self(Z_BEST_COMPRESSION)

public static let defaultCompression = Self(Z_DEFAULT_COMPRESSION)



public init(rawValue: Int32) {

self.rawValue = rawValue
}



public init(_ rawValue: Int32) {

self.rawValue = rawValue
}
}


/// Errors on gzipping/gunzipping based on the zlib error codes.
public struct GzipError: Swift.Error, Sendable {
// cf. http://www.zlib.net/manual.html

public enum Kind: Equatable, Sendable {
/// The stream structure was inconsistent.
///
/// - underlying zlib error: `Z_STREAM_ERROR` (-2)
case stream

/// The input data was corrupted
/// (input stream not conforming to the zlib format or incorrect check value).
///
/// - underlying zlib error: `Z_DATA_ERROR` (-3)
case data

/// There was not enough memory.
///
/// - underlying zlib error: `Z_MEM_ERROR` (-4)
case memory

/// No progress is possible or there was not enough room in the output buffer.
///
/// - underlying zlib error: `Z_BUF_ERROR` (-5)
case buffer

/// The zlib library version is incompatible with the version assumed by the caller.
///
/// - underlying zlib error: `Z_VERSION_ERROR` (-6)
case version

/// An unknown error occurred.
///
/// - parameter code: return error by zlib
case unknown(code: Int)
}

/// Error kind.
public let kind: Kind

/// Returned message by zlib.
public let message: String


internal init(code: Int32, msg: UnsafePointer<CChar>?) {

self.message = msg.flatMap(String.init(validatingUTF8:)) ?? "Unknown gzip error"
self.kind = Kind(code: code)

init(code: Int32, msg: UnsafePointer<CChar>?) {
message = msg.flatMap(String.init(validatingUTF8:)) ?? "Unknown gzip error"
kind = Kind(code: code)
}



public var localizedDescription: String {

return self.message
message
}
}


private extension GzipError.Kind {

init(code: Int32) {

switch code {
case Z_STREAM_ERROR:
self = .stream
Expand All @@ -147,16 +132,12 @@ private extension GzipError.Kind {
}
}


extension Data {

public extension Data {
/// Whether the receiver is compressed in gzip format.
public var isGzipped: Bool {

return self.starts(with: [0x1f, 0x8b]) // check magic number
var isGzipped: Bool {
starts(with: [0x1F, 0x8B]) // check magic number
}



/// Create a new `Data` instance by compressing the receiver using zlib.
/// Throws an error if compression failed.
///
Expand All @@ -171,63 +152,61 @@ extension Data {
/// - Parameter wBits: Manage the size of the history buffer.
/// - Returns: Gzip-compressed `Data` instance.
/// - Throws: `GzipError`
public func gzipped(level: CompressionLevel = .defaultCompression, wBits: Int32 = Gzip.maxWindowBits + 16) throws -> Data {

guard !self.isEmpty else {
func gzipped(level: CompressionLevel = .defaultCompression, wBits: Int32 = Gzip.maxWindowBits + 16) throws -> Data {
guard !isEmpty else {
return Data()
}

var stream = z_stream()
var status: Int32

status = deflateInit2_(&stream, level.rawValue, Z_DEFLATED, wBits, MAX_MEM_LEVEL, Z_DEFAULT_STRATEGY, ZLIB_VERSION, Int32(DataSize.stream))

guard status == Z_OK else {
// deflateInit2 returns:
// Z_VERSION_ERROR The zlib library version is incompatible with the version assumed by the caller.
// Z_MEM_ERROR There was not enough memory.
// Z_STREAM_ERROR A parameter is invalid.

throw GzipError(code: status, msg: stream.msg)
}

var data = Data(capacity: DataSize.chunk)
repeat {
if Int(stream.total_out) >= data.count {
data.count += DataSize.chunk
}
let inputCount = self.count

let inputCount = count
let outputCount = data.count
self.withUnsafeBytes { (inputPointer: UnsafeRawBufferPointer) in

withUnsafeBytes { (inputPointer: UnsafeRawBufferPointer) in
stream.next_in = UnsafeMutablePointer<Bytef>(mutating: inputPointer.bindMemory(to: Bytef.self).baseAddress!).advanced(by: Int(stream.total_in))
stream.avail_in = uInt(inputCount) - uInt(stream.total_in)

data.withUnsafeMutableBytes { (outputPointer: UnsafeMutableRawBufferPointer) in
stream.next_out = outputPointer.bindMemory(to: Bytef.self).baseAddress!.advanced(by: Int(stream.total_out))
stream.avail_out = uInt(outputCount) - uInt(stream.total_out)

status = deflate(&stream, Z_FINISH)

stream.next_out = nil
}

stream.next_in = nil
}

} while stream.avail_out == 0 && status != Z_STREAM_END

guard deflateEnd(&stream) == Z_OK, status == Z_STREAM_END else {
throw GzipError(code: status, msg: stream.msg)
}

data.count = Int(stream.total_out)

return data
}



/// Create a new `Data` instance by decompressing the receiver using zlib.
/// Throws an error if decompression failed.
///
Expand All @@ -242,60 +221,59 @@ extension Data {
/// - Parameter wBits: Manage the size of the history buffer.
/// - Returns: Gzip-decompressed `Data` instance.
/// - Throws: `GzipError`
public func gunzipped(wBits: Int32 = Gzip.maxWindowBits + 32) throws -> Data {

guard !self.isEmpty else {
func gunzipped(wBits: Int32 = Gzip.maxWindowBits + 32) throws -> Data {
guard !isEmpty else {
return Data()
}
var data = Data(capacity: self.count * 2)

var data = Data(capacity: count * 2)
var totalIn: uLong = 0
var totalOut: uLong = 0

repeat {
var stream = z_stream()
var status: Int32

status = inflateInit2_(&stream, wBits, ZLIB_VERSION, Int32(DataSize.stream))

guard status == Z_OK else {
// inflateInit2 returns:
// Z_VERSION_ERROR The zlib library version is incompatible with the version assumed by the caller.
// Z_MEM_ERROR There was not enough memory.
// Z_STREAM_ERROR A parameters are invalid.

throw GzipError(code: status, msg: stream.msg)
}

repeat {
if Int(totalOut + stream.total_out) >= data.count {
data.count += self.count / 2
data.count += count / 2
}
let inputCount = self.count

let inputCount = count
let outputCount = data.count
self.withUnsafeBytes { (inputPointer: UnsafeRawBufferPointer) in

withUnsafeBytes { (inputPointer: UnsafeRawBufferPointer) in
let inputStartPosition = totalIn + stream.total_in
stream.next_in = UnsafeMutablePointer<Bytef>(mutating: inputPointer.bindMemory(to: Bytef.self).baseAddress!).advanced(by: Int(inputStartPosition))
stream.avail_in = uInt(inputCount) - uInt(inputStartPosition)

data.withUnsafeMutableBytes { (outputPointer: UnsafeMutableRawBufferPointer) in
let outputStartPosition = totalOut + stream.total_out
stream.next_out = outputPointer.bindMemory(to: Bytef.self).baseAddress!.advanced(by: Int(outputStartPosition))
stream.avail_out = uInt(outputCount) - uInt(outputStartPosition)

status = inflate(&stream, Z_SYNC_FLUSH)

stream.next_out = nil
}

stream.next_in = nil
}
} while (status == Z_OK)
} while status == Z_OK

totalIn += stream.total_in

guard inflateEnd(&stream) == Z_OK, status == Z_STREAM_END else {
// inflate returns:
// Z_DATA_ERROR The input data was corrupted (input stream not conforming to the zlib format or incorrect check value).
Expand All @@ -304,20 +282,18 @@ extension Data {
// Z_BUF_ERROR No progress is possible or there was not enough room in the output buffer when Z_FINISH is used.
throw GzipError(code: status, msg: stream.msg)
}

totalOut += stream.total_out
} while (totalIn < self.count)

} while totalIn < count

data.count = Int(totalOut)

return data
}
}


private enum DataSize {

static let chunk = 1 << 14
static let stream = MemoryLayout<z_stream>.size
}
6 changes: 3 additions & 3 deletions PostHogExample/AppDelegate.swift
Original file line number Diff line number Diff line change
Expand Up @@ -28,19 +28,19 @@ class AppDelegate: NSObject, UIApplicationDelegate {
// "iteration": iteration
// ])
// }

let defaultCenter = NotificationCenter.default

#if os(iOS) || os(tvOS)
defaultCenter.addObserver(self,
selector: #selector(self.receiveFeatureFlags),
selector: #selector(receiveFeatureFlags),
name: PostHogSDK.didReceiveFeatureFlags,
object: nil)
#endif

return true
}

@objc func receiveFeatureFlags() {
print("receiveFeatureFlags")
}
Expand Down

0 comments on commit 53483ad

Please sign in to comment.