From be899bc3554149ec27419fa0b6fcb6af6063fc9d Mon Sep 17 00:00:00 2001 From: Timofey Solomko Date: Sat, 16 Oct 2021 16:25:15 +0300 Subject: [PATCH] [LZ4] Fix incorrect block checksums in case of incompressible blocks --- Sources/LZ4/LZ4+Compress.swift | 17 ++++++++++++----- 1 file changed, 12 insertions(+), 5 deletions(-) diff --git a/Sources/LZ4/LZ4+Compress.swift b/Sources/LZ4/LZ4+Compress.swift index 71e2b8ae..3e2b9aff 100644 --- a/Sources/LZ4/LZ4+Compress.swift +++ b/Sources/LZ4/LZ4+Compress.swift @@ -86,6 +86,13 @@ extension LZ4: CompressionAlgorithm { out.append(UInt8(truncatingIfNeeded: (blockSize & (0xFF << (i * 8))) >> (i * 8))) } out.append(contentsOf: blockData) + + if blockChecksums { + let blockChecksum = XxHash32.hash(data: blockData) + for i: UInt32 in 0..<4 { + out.append(UInt8(truncatingIfNeeded: (blockChecksum & (0xFF << (i * 8))) >> (i * 8))) + } + } } else { if compressedBlock.count > 0x7FFFFFFF { // TODO: In this case we cannot properly store uncompressed block, since either the highest bit of @@ -97,12 +104,12 @@ extension LZ4: CompressionAlgorithm { out.append(UInt8(truncatingIfNeeded: (blockSize & (0xFF << (i * 8))) >> (i * 8))) } out.append(contentsOf: compressedBlock) - } - if blockChecksums { - let blockChecksum = XxHash32.hash(data: Data(compressedBlock)) - for i: UInt32 in 0..<4 { - out.append(UInt8(truncatingIfNeeded: (blockChecksum & (0xFF << (i * 8))) >> (i * 8))) + if blockChecksums { + let blockChecksum = XxHash32.hash(data: Data(compressedBlock)) + for i: UInt32 in 0..<4 { + out.append(UInt8(truncatingIfNeeded: (blockChecksum & (0xFF << (i * 8))) >> (i * 8))) + } } } }