diff --git a/Sources/Deflate.swift b/Sources/Deflate.swift index 5ab077ef..9b2ef25b 100644 --- a/Sources/Deflate.swift +++ b/Sources/Deflate.swift @@ -330,11 +330,45 @@ public final class Deflate: DecompressionAlgorithm { // TODO: We shouldn't discard arrays shorter than 3 elements. Or maybe we should? precondition(rawBytes.count >= 3, "Too small array!") - var buffer = [BLDCode]() - for byte in rawBytes { - buffer.append(.byte(byte)) - } + var buffer: [BLDCode] = [] + var inputIndex = 0 + while inputIndex < rawBytes.count { + let byte = rawBytes[inputIndex] + + if let matchStartIndex = rawBytes[0..= 258 { + break + } + matchLength += 1 + repeatIndex += 1 + if repeatIndex > inputIndex { + repeatIndex = matchStartIndex + 1 + } + } + } + + if matchLength >= 3 { + buffer.append(BLDCode.lengthDistance(matchLength, distance)) + inputIndex += matchLength + } else { + buffer.append(BLDCode.byte(byte)) + inputIndex += 1 + } + } else { + buffer.append(BLDCode.byte(byte)) + inputIndex += 1 + } + } + return buffer }