Skip to content

Commit

Permalink
Log error message
Browse files Browse the repository at this point in the history
  • Loading branch information
1024jp committed Aug 2, 2015
1 parent 286f537 commit 2ff34fa
Show file tree
Hide file tree
Showing 3 changed files with 29 additions and 3 deletions.
3 changes: 3 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -8,3 +8,6 @@ Change Log
### Changes

- Change to return just empty NSData instead nil if given data is empty
- Log error message if compression/decompression is failed.
- [Note] This is a temporaly improvement.
I'll migrate functions to throw NSError when Swift 2.0 becomes stable.
8 changes: 8 additions & 0 deletions Project/Tests/NSData_GZIPTests.swift
Original file line number Diff line number Diff line change
Expand Up @@ -54,4 +54,12 @@ class NSData_GZIPTests: XCTestCase
XCTAssertEqual(zeroLengthData.gzippedData()!, zeroLengthData)
XCTAssertEqual(zeroLengthData.gunzippedData()!, zeroLengthData)
}

func testWrongUngzip()
{
// data not compressed
let data = ("testString" as NSString).dataUsingEncoding(NSUTF8StringEncoding, allowLossyConversion: true)!

XCTAssertNil(data.gunzippedData())
}
}
21 changes: 18 additions & 3 deletions Sources/NSData+GZIP.swift
Original file line number Diff line number Diff line change
Expand Up @@ -43,8 +43,15 @@ public extension NSData
}

var stream = self.createZStream()
var status : Int32

if deflateInit2_(&stream, Z_DEFAULT_COMPRESSION, Z_DEFLATED, 31, 8, Z_DEFAULT_STRATEGY, ZLIB_VERSION, STREAM_SIZE) != Z_OK {
status = deflateInit2_(&stream, Z_DEFAULT_COMPRESSION, Z_DEFLATED, 31, 8, Z_DEFAULT_STRATEGY, ZLIB_VERSION, STREAM_SIZE)

if status != Z_OK {
if let errorMessage = String.fromCString(stream.msg) {
println(String(format: "Compression failed: %@", errorMessage))
}

return nil
}

Expand Down Expand Up @@ -75,13 +82,18 @@ public extension NSData
}

var stream = self.createZStream()
var status : Int32

if inflateInit2_(&stream, 47, ZLIB_VERSION, STREAM_SIZE) != Z_OK {
status = inflateInit2_(&stream, 47, ZLIB_VERSION, STREAM_SIZE)

if status != Z_OK {
if let errorMessage = String.fromCString(stream.msg) {
println(String(format: "Decompression failed: %@", errorMessage))
}
return nil
}

var data = NSMutableData(length: self.length * 2)!
var status : Int32
do {
if Int(stream.total_out) >= data.length {
data.length += self.length / 2;
Expand All @@ -94,6 +106,9 @@ public extension NSData
} while status == Z_OK

if inflateEnd(&stream) != Z_OK || status != Z_STREAM_END {
if let errorMessage = String.fromCString(stream.msg) {
println(String(format: "Decompression failed: %@", errorMessage))
}
return nil
}

Expand Down

0 comments on commit 2ff34fa

Please sign in to comment.