From 9e88447bb64c67f80f1a373bc97ea52f4e335d8c Mon Sep 17 00:00:00 2001 From: Timofey Solomko Date: Tue, 1 Nov 2016 23:49:26 +0300 Subject: [PATCH] ExtraLength and extraDistance calculations are now done inside decompress function. --- Sources/Deflate.swift | 11 +++++------ Sources/HuffmanTable.swift | 22 +--------------------- 2 files changed, 6 insertions(+), 27 deletions(-) diff --git a/Sources/Deflate.swift b/Sources/Deflate.swift index 5e0a82c5..d5e9668e 100644 --- a/Sources/Deflate.swift +++ b/Sources/Deflate.swift @@ -169,10 +169,10 @@ public class Deflate: DecompressionAlgorithm { break } else if symbol >= 257 && symbol <= 285 { let start = (index, shift) - let addBits = HuffmanTable.Constants.extraLengthBits(n: symbol) - guard addBits != -1 else { throw DeflateError.HuffmanTableError } - index += shift + addBits >= 8 ? 1 : 0 - shift = shift + addBits >= 8 ? shift - (8 - addBits) : shift + addBits + let extraLength = (257 <= symbol && symbol <= 260) || symbol == 285 ? + 0 : ((symbol - 257) >> 2) - 1 + index += shift + extraLength >= 8 ? 1 : 0 + shift = shift + extraLength >= 8 ? shift - (8 - extraLength) : shift + extraLength let end = (index, shift) var length = HuffmanTable.Constants.lengthBase[symbol - 257] + convertToInt(reversedUint8Array: data.bits(from: start, to: end)) @@ -186,8 +186,7 @@ public class Deflate: DecompressionAlgorithm { if newSymbol >= 0 && newSymbol <= 29 { let start = (index, shift) - let extraDistance = HuffmanTable.Constants.extraDistanceBits(n: newSymbol) - guard extraDistance != -1 else { throw DeflateError.HuffmanTableError } + let extraDistance = newSymbol == 0 || newSymbol == 1 ? 0 : (newSymbol >> 1) - 1 if shift + extraDistance >= 16 { index += 2 shift = shift - (16 - extraDistance) diff --git a/Sources/HuffmanTable.swift b/Sources/HuffmanTable.swift index b91997b9..52fdd179 100644 --- a/Sources/HuffmanTable.swift +++ b/Sources/HuffmanTable.swift @@ -14,7 +14,7 @@ class HuffmanTable: CustomStringConvertible { static let codeLengthOrders: [Int] = [16, 17, 18, 0, 8, 7, 9, 6, 10, 5, 11, 4, 12, 3, 13, 2, 14, 1, 15] - // Substract 257 from index! + /// - Warning: Substract 257 from index! static let lengthBase: [Int] = [3, 4, 5, 6, 7, 8, 9, 10, 11, 13, 15, 17, 19, 23, 27, 31, 35, 43, 51, 59, 67, 83, 99, 115, 131, 163, 195, 227, 258] @@ -24,26 +24,6 @@ class HuffmanTable: CustomStringConvertible { 257, 385, 513, 769, 1025, 1537, 2049, 3073, 4097, 6145, 8193, 12289, 16385, 24577] - static func extraLengthBits(n: Int) -> Int { - if (n >= 257 && n <= 260) || n == 285 { - return 0 - } else if n >= 261 && n <= 284 { - return ((n - 257) >> 2) - 1 - } else { - return -1 - } - } - - static func extraDistanceBits(n: Int) -> Int { - if n >= 0 && n <= 1 { - return 0 - } else if n >= 2 && n <= 29 { - return (n >> 1) - 1 - } else { - return -1 - } - } - } var lengths: [HuffmanLength]