From ccf97c995bfbd65f2269029ec9cedfd33e4d389a Mon Sep 17 00:00:00 2001 From: Timofey Solomko Date: Thu, 26 Feb 2026 16:34:22 +0800 Subject: [PATCH] [Deflate] Check that 16 is not the first code length symbol This symbol in the dynamic Huffman block encodes copy of the previous code length. If this symbol is the first, then there is nothing to copy. Previously, this could cause a crash. --- Sources/Deflate/Deflate.swift | 7 ++++--- 1 file changed, 4 insertions(+), 3 deletions(-) diff --git a/Sources/Deflate/Deflate.swift b/Sources/Deflate/Deflate.swift index 5ba1eac7..8a1bf030 100644 --- a/Sources/Deflate/Deflate.swift +++ b/Sources/Deflate/Deflate.swift @@ -120,9 +120,10 @@ public class Deflate: DecompressionAlgorithm { // It is a raw code length. codeLengths[n] = symbol n += 1 - } else if symbol == 16 { - // Copy previous code length 3 to 6 times. - // Next two bits show how many times we need to copy. + } else if symbol == 16 && n > codeLengths.startIndex { + // Copy previous code length 3 to 6 times. Next two bits show how many times we need to copy. + // This symbol cannot be the first symbol encoding code lengths, since there is nothing to + // copy at this point. guard bitReader.bitsLeft >= 2 else { throw DeflateError.symbolNotFound } let copyCount = bitReader.int(fromBits: 2) + 3