From 24576d892a87015710a2815db382bd2b8ebc609d Mon Sep 17 00:00:00 2001 From: Timofey Solomko Date: Wed, 8 Feb 2017 19:41:02 +0300 Subject: [PATCH] Added function which allows creation of uncompressed deflate blocks, which in its turn allows us to enable test5 for deflation. --- Sources/Deflate.swift | 32 ++++++++++++++++++++++++++++++++ Tests/DeflateTests.swift | 4 +++- 2 files changed, 35 insertions(+), 1 deletion(-) diff --git a/Sources/Deflate.swift b/Sources/Deflate.swift index 588fad82..f99325ca 100644 --- a/Sources/Deflate.swift +++ b/Sources/Deflate.swift @@ -232,11 +232,43 @@ public final class Deflate: DecompressionAlgorithm { public static func compress(data: Data) throws -> Data { let bytes = data.toArray(type: UInt8.self) + + if bytes.count < 3 { + return Data(bytes: Deflate.createUncompressedBlock(bytes)) + } + let bldCodes = Deflate.lengthEncode(bytes) let huffmanEncodedBytes = Deflate.encodeHuffmanBlock(bldCodes) return Data(bytes: huffmanEncodedBytes) } + private static func createUncompressedBlock(_ bytes: [UInt8]) -> [UInt8] { + let bitWriter = BitToByteWriter(bitOrder: .reversed) + + // Write block header. + // Note: Only one block is supported for now. + bitWriter.write(bit: 1) + bitWriter.write(bits: [0, 0]) + + // Before writing lengths we need to discard remaining bits in current byte. + bitWriter.finish() + + // Write data's length. + bitWriter.write(number: bytes.count, bitsCount: 16) + // Write data's n-length. + bitWriter.write(number: bytes.count ^ (1 << 16 - 1), bitsCount: 16) + + // Finishing block header. + bitWriter.finish() + var out = bitWriter.buffer + + // Write actual data. + for byte in bytes { + out.append(byte) + } + + return out + } private static func encodeHuffmanBlock(_ bldCodes: [BLDCode]) -> [UInt8] { let bitWriter = BitToByteWriter(bitOrder: .reversed) diff --git a/Tests/DeflateTests.swift b/Tests/DeflateTests.swift index baa8cf5e..814bf7c0 100644 --- a/Tests/DeflateTests.swift +++ b/Tests/DeflateTests.swift @@ -103,7 +103,9 @@ class DeflateTests: XCTestCase { self.perform(compressionTest: "test4") } - // - Note: Comrepssion Test #5 is skipped intentionally: because of precondition() in Deflate.swift. + func testDeflate5() { + self.perform(compressionTest: "test5") + } func testDeflate6() { self.perform(compressionTest: "test6")