diff --git a/.gitattributes b/.gitattributes new file mode 100644 index 0000000..09d7c60 --- /dev/null +++ b/.gitattributes @@ -0,0 +1,4 @@ +# Store text files with LF in the repository and check them out with the platform's line ending (CRLF on Windows). +* text=auto + +*.png binary diff --git a/.github/workflows/build-test-publish.yml b/.github/workflows/build-test-publish.yml index cd88685..bf43c5e 100644 --- a/.github/workflows/build-test-publish.yml +++ b/.github/workflows/build-test-publish.yml @@ -4,6 +4,9 @@ on: push: branches: - master + pull_request: + branches: + - master defaults: run: @@ -17,8 +20,9 @@ jobs: - name: Setup .NET uses: actions/setup-dotnet@v5 with: - dotnet-version: | + dotnet-version: | 10.0.x + 11.0.x - name: Restore dependencies run: dotnet restore @@ -30,15 +34,18 @@ jobs: run: dotnet test -c Release --no-restore --no-build -v normal - name: Pack NuGet Package(s) + if: github.event_name == 'push' run: dotnet pack -c Release --no-restore --no-build --output ~/nuget-packages - name: Upload Build Artifact(s) + if: github.event_name == 'push' uses: actions/upload-artifact@v7 with: name: nuget-packages path: ~/nuget-packages - name: Push NuGet Package(s) + if: github.event_name == 'push' run: | dotnet nuget push ~/nuget-packages/*.nupkg \ --source https://api.nuget.org/v3/index.json \ diff --git a/src/Directory.Build.props b/src/Directory.Build.props index 5840b06..facde53 100644 --- a/src/Directory.Build.props +++ b/src/Directory.Build.props @@ -1,6 +1,6 @@ - net10.0 + net10.0;net11.0 enable enable true diff --git a/src/Directory.Packages.props b/src/Directory.Packages.props index a55c957..b01e2cb 100644 --- a/src/Directory.Packages.props +++ b/src/Directory.Packages.props @@ -5,9 +5,9 @@ - - - - + + + + - + \ No newline at end of file diff --git a/src/OffiUtils.Tests/IDecompressorTests.cs b/src/OffiUtils.Tests/IDecompressorTests.cs index 6773645..bd4d38b 100644 --- a/src/OffiUtils.Tests/IDecompressorTests.cs +++ b/src/OffiUtils.Tests/IDecompressorTests.cs @@ -13,6 +13,43 @@ private static ReadOnlySpan RawData private static IDecompressor DefaultDecompressor => DecompressorBuilder.Default.Build(); + public static TheoryData DefaultAlgorithms => + [ + CompressionAlgorithm.Deflate, + CompressionAlgorithm.Gzip, + CompressionAlgorithm.Zlib, + CompressionAlgorithm.Brotli, +#if NET11_0_OR_GREATER + CompressionAlgorithm.Zstd, +#endif + ]; + + private static byte[] Compress(CompressionAlgorithm algorithm, ReadOnlySpan data) + { + using MemoryStream output = new(); + using (Stream compressor = algorithm switch + { + CompressionAlgorithm.Deflate => new DeflateStream(output, CompressionLevel.Optimal, leaveOpen: true), + CompressionAlgorithm.Gzip => new GZipStream(output, CompressionLevel.Optimal, leaveOpen: true), + CompressionAlgorithm.Zlib => new ZLibStream(output, CompressionLevel.Optimal, leaveOpen: true), + CompressionAlgorithm.Brotli => new BrotliStream(output, CompressionLevel.Optimal, leaveOpen: true), +#if NET11_0_OR_GREATER + CompressionAlgorithm.Zstd => new ZstandardStream(output, CompressionLevel.Optimal, leaveOpen: true), +#endif + _ => throw new ArgumentOutOfRangeException(nameof(algorithm), algorithm, null), + }) + { + compressor.Write(data); + } + return output.ToArray(); + } + + private static void AssertFails(CompressionAlgorithm algorithm, ReadOnlySpan source, Span destination) + { + Assert.False(DefaultDecompressor.TryDecompress(algorithm, source, destination, out int bytesWritten)); + Assert.Equal(0, bytesWritten); + } + [Fact] public void NotSupported() { @@ -115,4 +152,114 @@ public void TryBrotliStateful() ReadOnlySpan decompressedData = stackBuffer.Slice(64, decompressedDataSize); Assert.Equal(RawData, decompressedData); } + + [Theory] + [MemberData(nameof(DefaultAlgorithms))] + public void TryLargeData(CompressionAlgorithm algorithm) + { + // Big enough that the net10.0 stream fallback reads the source in many chunks. Half random, half zeros. + byte[] data = new byte[256 * 1024]; + new Random(1337).NextBytes(data.AsSpan(0, data.Length / 2)); + byte[] destination = new byte[data.Length]; + + Assert.Equal(data.Length, DefaultDecompressor.Decompress(algorithm, Compress(algorithm, data), destination)); + Assert.Equal(data, destination); + } + + [Theory] + [MemberData(nameof(DefaultAlgorithms))] + public void TryTrailingBytes(CompressionAlgorithm algorithm) + { + byte[] source = [.. Compress(algorithm, RawData), .. "bytes after the compressed data are ignored"u8]; + Span destination = stackalloc byte[128]; + + Assert.True(DefaultDecompressor.TryDecompress(algorithm, source, destination, out int bytesWritten)); + Assert.Equal(RawData, destination.Slice(0, bytesWritten)); + } + + [Theory] + [MemberData(nameof(DefaultAlgorithms))] + public void TryInvalid(CompressionAlgorithm algorithm) + { + byte[] compressed = Compress(algorithm, RawData); + byte[] destination = new byte[RawData.Length]; + + AssertFails(algorithm, "not compressed"u8, destination); + AssertFails(algorithm, [], destination); + AssertFails(algorithm, compressed.AsSpan(..^1), destination); // incomplete source + AssertFails(algorithm, compressed, destination.AsSpan(..^1)); // destination too small + + Assert.Throws(() + => DefaultDecompressor.Decompress(algorithm, compressed, destination.AsSpan(..^1))); + } + + [Fact] + public void TryGzipMembers() + { + // Like GZipStream, every gzip member is decompressed (RFC 1952, section 2.2). + byte[] member = Compress(CompressionAlgorithm.Gzip, RawData); + // Header, an empty fixed Huffman block, then CRC32 and ISIZE of 0. + byte[] emptyMember = [0x1F, 0x8B, 0x08, 0, 0, 0, 0, 0, 0, 0xFF, 0x03, 0, 0, 0, 0, 0, 0, 0, 0, 0]; + byte[] expected = [.. RawData, .. RawData]; + Span destination = stackalloc byte[expected.Length]; + + Assert.True(DefaultDecompressor.TryDecompress(CompressionAlgorithm.Gzip, [.. member, .. member], destination, out int bytesWritten)); + Assert.Equal(expected, destination.Slice(0, bytesWritten)); + + // An empty member still fits into a full destination. + Assert.True(DefaultDecompressor.TryDecompress(CompressionAlgorithm.Gzip, [.. member, .. emptyMember], destination.Slice(0, RawData.Length), out bytesWritten)); + Assert.Equal(RawData, destination.Slice(0, bytesWritten)); + + // Bytes that start like a member are decompressed as one, so they have to be complete. + AssertFails(CompressionAlgorithm.Gzip, [.. member, 0x1F, 0x8B], destination); + } + +#if NET11_0_OR_GREATER + + [Fact] + public void TryZstdFrames() + { + // Like ZstandardStream, every frame is decompressed, skippable frames included (RFC 8878, section 3.1). + byte[] frame = Compress(CompressionAlgorithm.Zstd, RawData); + byte[] skippableFrame = [0x5E, 0x2A, 0x4D, 0x18, 0x04, 0x00, 0x00, 0x00, .. "meta"u8]; + byte[] expected = [.. RawData, .. RawData]; + Span destination = stackalloc byte[expected.Length]; + + Assert.True(DefaultDecompressor.TryDecompress(CompressionAlgorithm.Zstd, + [.. skippableFrame, .. frame, .. skippableFrame, .. frame, .. skippableFrame], destination, out int bytesWritten)); + Assert.Equal(expected, destination.Slice(0, bytesWritten)); + + AssertFails(CompressionAlgorithm.Zstd, [.. frame, .. frame.AsSpan(..^1)], destination); + } + + [Theory] + [InlineData(CompressionAlgorithm.Deflate)] + [InlineData(CompressionAlgorithm.Gzip)] + [InlineData(CompressionAlgorithm.Zlib)] + [InlineData(CompressionAlgorithm.Zstd)] + public void TryEncoder(CompressionAlgorithm algorithm) + { + Span stackBuffer = stackalloc byte[128]; + + int compressedDataSize = 0; + Assert.True(algorithm switch + { + CompressionAlgorithm.Deflate => DeflateEncoder.TryCompress(RawData, stackBuffer.Slice(0, 64), out compressedDataSize), + CompressionAlgorithm.Gzip => GZipEncoder.TryCompress(RawData, stackBuffer.Slice(0, 64), out compressedDataSize), + CompressionAlgorithm.Zlib => ZLibEncoder.TryCompress(RawData, stackBuffer.Slice(0, 64), out compressedDataSize), + CompressionAlgorithm.Zstd => ZstandardEncoder.TryCompress(RawData, stackBuffer.Slice(0, 64), out compressedDataSize), + _ => false, + }); + ReadOnlySpan compressedData = stackBuffer.Slice(0, compressedDataSize); + + Assert.True(DefaultDecompressor.TryDecompress( + algorithm, + compressedData, stackBuffer.Slice(64), + out int decompressedDataSize)); + + ReadOnlySpan decompressedData = stackBuffer.Slice(64, decompressedDataSize); + Assert.Equal(RawData, decompressedData); + } + +#endif } diff --git a/src/OffiUtils/IDecompressor.cs b/src/OffiUtils/IDecompressor.cs index f7de17d..8ad7104 100644 --- a/src/OffiUtils/IDecompressor.cs +++ b/src/OffiUtils/IDecompressor.cs @@ -1,4 +1,8 @@ -using System.Collections; +#if NET11_0_OR_GREATER +using System.Buffers; +using System.Buffers.Binary; +#endif +using System.Collections; using System.Collections.Frozen; using System.Diagnostics.CodeAnalysis; using System.IO.Compression; @@ -14,7 +18,7 @@ public interface IDecompressor : IReadOnlyDictionaryThe algorithm to use. /// The compressed data. /// The buffer to write decompressed data to. - /// The number of bytes successfully written to the destination. + /// The number of bytes successfully written to the destination, or 0 if decompression failed. /// True if decompression succeeded; otherwise, false. bool TryDecompress( CompressionAlgorithm algorithm, @@ -87,10 +91,19 @@ public sealed class DecompressorBuilder { private readonly Dictionary _handlers = new(); + /// + /// Creates a builder with the built-in algorithms registered. On every target framework, their decoders succeed + /// only if the compressed data is complete and its entire output fits into the destination. + /// Bytes after the end of the compressed data are ignored, except that further gzip members + /// and Zstandard frames are decompressed as well. + /// public static DecompressorBuilder Default => new DecompressorBuilder() .Add(CompressionAlgorithm.Deflate, TryDecompressDeflate) .Add(CompressionAlgorithm.Gzip, TryDecompressGzip) .Add(CompressionAlgorithm.Zlib, TryDecompressZlib) +#if NET11_0_OR_GREATER + .Add(CompressionAlgorithm.Zstd, TryDecompressZstd) +#endif .Add(CompressionAlgorithm.Brotli, BrotliDecoder.TryDecompress); public DecompressorBuilder AddRange(IEnumerable> values, bool replace = false) @@ -142,60 +155,164 @@ public IDecompressor Build() return new FastDecompressor(_handlers.ToFrozenDictionary()); } - internal static bool TryDecompressDeflate( +#if NET11_0_OR_GREATER + + // The static TryDecompress methods of the span decoders also fail when bytes follow the compressed data. + // The instance API stops at the end of the data, so these use it to get the same results as the stream fallback. + + private static bool TryDecompressDeflate( + ReadOnlySpan source, + Span destination, + out int bytesWritten) + { + using DeflateDecoder decoder = new(); + return decoder.Decompress(source, destination, out _, out bytesWritten) == OperationStatus.Done; + } + + private static bool TryDecompressGzip( + ReadOnlySpan source, + Span destination, + out int bytesWritten) + { + using GZipDecoder decoder = new(); + Span scratch = stackalloc byte[1]; + bytesWritten = 0; + + while (true) + { + // The decoders report DestinationTooSmall for an empty buffer even if nothing is left to write, + // so once the destination is full they get a one-byte buffer that has to stay empty. + bool full = bytesWritten == destination.Length; + Span output = full ? scratch : destination[bytesWritten..]; + if (decoder.Decompress(source, output, out int bytesConsumed, out int written) != OperationStatus.Done || (full && written != 0)) + return false; + + bytesWritten += written; + source = source[bytesConsumed..]; + + // Like GZipStream, decompress the next member if the remaining input starts like one (RFC 1952, section 2.2). + if (source.IsEmpty || source[0] != 0x1F || (source.Length > 1 && source[1] != 0x8B)) + return true; + + decoder.Reset(); + } + } + + private static bool TryDecompressZlib( + ReadOnlySpan source, + Span destination, + out int bytesWritten) + { + using ZLibDecoder decoder = new(); + return decoder.Decompress(source, destination, out _, out bytesWritten) == OperationStatus.Done; + } + + private static bool TryDecompressZstd( ReadOnlySpan source, Span destination, out int bytesWritten) { - return TryDecompressStream(source, destination, out bytesWritten, + const uint FrameMagic = 0xFD2FB528; + const uint SkippableFrameMagic = 0x184D2A50; // the lowest 4 bits can have any value + + using ZstandardDecoder decoder = new(); + Span scratch = stackalloc byte[1]; + bytesWritten = 0; + + while (true) + { + // Like in TryDecompressGzip, a full destination gets a one-byte buffer that has to stay empty. + bool full = bytesWritten == destination.Length; + Span output = full ? scratch : destination[bytesWritten..]; + if (decoder.Decompress(source, output, out int bytesConsumed, out int written) != OperationStatus.Done || (full && written != 0)) + return false; + + bytesWritten += written; + source = source[bytesConsumed..]; + + // Like ZstandardStream, decompress the next frame if the remaining input starts with a frame magic number + // (RFC 8878, sections 3.1.1 and 3.1.2). + if (source.Length < sizeof(uint)) + return true; + + uint magic = BinaryPrimitives.ReadUInt32LittleEndian(source); + if (magic != FrameMagic && (magic & ~0xFu) != SkippableFrameMagic) + return true; + + decoder.Reset(); + } + } + +#else + + private static bool TryDecompressDeflate( + ReadOnlySpan source, + Span destination, + out int bytesWritten) + { + return TryDecompressStream(source, destination, out bytesWritten, appendSentinel: false, static s => new DeflateStream(s, CompressionMode.Decompress, leaveOpen: true)); } - internal static bool TryDecompressGzip( + private static bool TryDecompressGzip( ReadOnlySpan source, Span destination, out int bytesWritten) { - return TryDecompressStream(source, destination, out bytesWritten, + return TryDecompressStream(source, destination, out bytesWritten, appendSentinel: true, static s => new GZipStream(s, CompressionMode.Decompress, leaveOpen: true)); } - internal static bool TryDecompressZlib( + private static bool TryDecompressZlib( ReadOnlySpan source, Span destination, out int bytesWritten) { - return TryDecompressStream(source, destination, out bytesWritten, + return TryDecompressStream(source, destination, out bytesWritten, appendSentinel: false, static s => new ZLibStream(s, CompressionMode.Decompress, leaveOpen: true)); } - internal static unsafe bool TryDecompressStream( + private static unsafe bool TryDecompressStream( ReadOnlySpan source, Span destination, out int bytesWritten, - Func createDecompressionStream) + bool appendSentinel, + Func createDecompressionStream) { bytesWritten = 0; if (source.IsEmpty) - return true; + return false; try { fixed (byte* sourcePtr = source) { - using UnmanagedMemoryStream sourceStream = new(sourcePtr, source.Length); + using SourceStream sourceStream = new(sourcePtr, source.Length, appendSentinel); using Stream decompressionStream = createDecompressionStream(sourceStream); - bytesWritten = 0; - while (bytesWritten < destination.Length) + int written = 0; + while (written < destination.Length) { - int read = decompressionStream.Read(destination[bytesWritten..]); + int read = decompressionStream.Read(destination[written..]); if (read == 0) break; - bytesWritten += read; + written += read; } + // A full destination is only enough if no output is left. + // Reading into an empty buffer doesn't decompress anything, so this reads one byte. + if (written == destination.Length) + { + Span probe = stackalloc byte[1]; + if (decompressionStream.Read(probe) != 0) + return false; + } + + if (sourceStream.ReadPastEnd) + return false; + + bytesWritten = written; return true; } } @@ -205,7 +322,50 @@ internal static unsafe bool TryDecompressStream( } } - internal sealed class DelegateStateWrapper + /// + /// The source as a stream that records whether the decompression stream wanted more input than the source holds. + /// + /// + /// DeflateStream only reads while the inflater is unfinished and out of input (DeflateStream.ReadCore in .NET 10), + /// so with complete data it never reads past the end, and with incomplete data it always does. + /// GZipStream also reads once more after a member that ends exactly at the end of the source, to look for the next one. + /// The optional sentinel byte answers that read. 0xFF can't start a member, so GZipStream stops there. + /// If an incomplete member uses up the sentinel as data instead, GZipStream reads again after it, + /// which counts as a read past the end like any other. + /// + private sealed unsafe class SourceStream : UnmanagedMemoryStream + { + private bool _sentinelPending; + + public SourceStream(byte* source, int length, bool appendSentinel) : base(source, length) + { + _sentinelPending = appendSentinel; + } + + public bool ReadPastEnd { get; private set; } + + // DeflateStream reads through this overload, and UnmanagedMemoryStream.Read(Span) forwards to it in derived types. + public override int Read(byte[] buffer, int offset, int count) + { + int read = base.Read(buffer, offset, count); + if (read != 0 || count == 0) + return read; + + if (_sentinelPending) + { + _sentinelPending = false; + buffer[offset] = 0xFF; + return 1; + } + + ReadPastEnd = true; + return 0; + } + } + +#endif + + private sealed class DelegateStateWrapper { private readonly TState _state; private readonly DecompressDelegate _method; @@ -222,7 +382,7 @@ public bool Invoke(ReadOnlySpan source, Span destination, out int by } } - internal sealed class FastDecompressor : IDecompressor + private sealed class FastDecompressor : IDecompressor { private readonly FrozenDictionary _decompressors; @@ -237,9 +397,15 @@ public bool TryDecompress( Span destination, out int bytesWritten) { + if (_decompressors.TryGetValue(algorithm, out DecompressDelegate? handler) && + handler(source, destination, out bytesWritten) && bytesWritten != 0) + { + return true; + } + + // A handler may report partial output when it fails. bytesWritten = 0; - return _decompressors.TryGetValue(algorithm, out DecompressDelegate? handler) && - handler(source, destination, out bytesWritten) && bytesWritten != 0; + return false; } public int Decompress( diff --git a/src/OffiUtils/JsonUtils.cs b/src/OffiUtils/JsonUtils.cs index 4e9be64..4f09429 100644 --- a/src/OffiUtils/JsonUtils.cs +++ b/src/OffiUtils/JsonUtils.cs @@ -4,7 +4,7 @@ namespace OffiUtils; -public static unsafe class JsonUtils +public static class JsonUtils { public const int StackallocByteThreshold = 256; public static readonly UTF8Encoding Encoding = new(encoderShouldEmitUTF8Identifier: false, throwOnInvalidBytes: true); diff --git a/src/global.json b/src/global.json new file mode 100644 index 0000000..3140116 --- /dev/null +++ b/src/global.json @@ -0,0 +1,5 @@ +{ + "test": { + "runner": "Microsoft.Testing.Platform" + } +}