From c7a66d58ea91045b0c3ffddb8bb43b473cd3bc7f Mon Sep 17 00:00:00 2001 From: Timofey Solomko Date: Fri, 28 Oct 2016 21:02:31 +0300 Subject: [PATCH] Apparently, I've missed extraDistanceBits array and was reading a value from wrong array. This was fixed. --- Sources/Deflate.swift | 18 +++++++++++------- Sources/HuffmanTable.swift | 10 ++++++++++ 2 files changed, 21 insertions(+), 7 deletions(-) diff --git a/Sources/Deflate.swift b/Sources/Deflate.swift index a76278ca..391b7326 100644 --- a/Sources/Deflate.swift +++ b/Sources/Deflate.swift @@ -223,23 +223,27 @@ public class Deflate { index += shift + addBits >= 8 ? 1 : 0 shift = shift + addBits >= 8 ? shift - (8 - addBits) : shift + addBits let end = (index, shift) - let extraLength = convertToInt(uint8Array: data.bits(from: start, to: end)) - var length = HuffmanTable.Constants.lengthBase[symbol - 257] + extraLength + var length = HuffmanTable.Constants.lengthBase[symbol - 257] + + convertToInt(uint8Array: data.bits(from: start, to: end)) let newSymbolTuple = mainDistances.findNextSymbol(in: Data(data[index...index + 1]), withShift: shift) let newSymbol = newSymbolTuple.symbol + guard newSymbol != -1 else { throw DeflateError.HuffmanTableError } index += newSymbolTuple.addToIndex + shift = newSymbolTuple.newShift if newSymbol >= 0 && newSymbol <= 29 { let start = (index, shift) - index += shift + newSymbol >= 8 ? 1 : 0 - shift = shift + newSymbol >= 8 ? shift - (8 - newSymbol) : shift + newSymbol + let extraDistance = HuffmanTable.Constants.extraDistanceBits(n: newSymbol) + guard extraDistance != -1 else { throw DeflateError.HuffmanTableError } + index += shift + extraDistance >= 8 ? 1 : 0 + shift = shift + extraDistance >= 8 ? + shift - (8 - extraDistance) : shift + extraDistance let end = (index, shift) - let dstBase = HuffmanTable.Constants.distanceBase[newSymbol] - let distance = dstBase + + let distance = HuffmanTable.Constants.distanceBase[newSymbol] + convertToInt(uint8Array: data.bits(from: start, to: end)) - print("distance: \(distance), dstBase: \(dstBase), newSymbol: \(newSymbol)") + while length > distance { out.append(contentsOf: Array(out[out.count - distance.. Int { + if n >= 0 && n <= 1 { + return 0 + } else if n >= 2 && n <= 29 { + return (n >> 1) - 1 + } else { + return -1 + } + } + } var lengths: [HuffmanLength]