From 8f0dd2f63598196c09955aba91e2323018d4ad7c Mon Sep 17 00:00:00 2001 From: Brant Burnett Date: Sun, 22 Dec 2024 16:39:26 -0500 Subject: [PATCH] Ensure compression buffers do not overlap --- Snappier.Tests/SnappyTests.cs | 8 ++++++++ Snappier/Internal/SnappyCompressor.cs | 4 ++++ Snappier/Snappier.csproj | 2 +- 3 files changed, 13 insertions(+), 1 deletion(-) diff --git a/Snappier.Tests/SnappyTests.cs b/Snappier.Tests/SnappyTests.cs index 8db6a3a..e47bc56 100644 --- a/Snappier.Tests/SnappyTests.cs +++ b/Snappier.Tests/SnappyTests.cs @@ -205,6 +205,14 @@ public void CompressAndDecompressString(string str) Assert.Equal(input, output); } + [Fact] + public void Compress_OverlappingBuffers_InvalidOperationException() + { + var input = new byte[1024]; + + Assert.Throws(() => Snappy.Compress(input, input.AsSpan(input.Length - 1))); + } + [Fact] public void BadData_InsufficentOutputBuffer_ThrowsArgumentException() { diff --git a/Snappier/Internal/SnappyCompressor.cs b/Snappier/Internal/SnappyCompressor.cs index 530493f..87b64e7 100644 --- a/Snappier/Internal/SnappyCompressor.cs +++ b/Snappier/Internal/SnappyCompressor.cs @@ -26,6 +26,10 @@ public bool TryCompress(ReadOnlySpan input, Span output, out int byt { ThrowHelper.ThrowObjectDisposedException(nameof(SnappyCompressor)); } + if (input.Overlaps(output)) + { + ThrowHelper.ThrowInvalidOperationException("Input and output spans must not overlap"); + } _workingMemory.EnsureCapacity(input.Length); diff --git a/Snappier/Snappier.csproj b/Snappier/Snappier.csproj index 1503edb..048d6e9 100644 --- a/Snappier/Snappier.csproj +++ b/Snappier/Snappier.csproj @@ -20,7 +20,7 @@ from the official C++ implementation, with the addition of support for the framed stream format. By avoiding P/Invoke, Snappier is fully cross-platform and works on both Linux and Windows and against any CPU supported - by .NET Core. However, Snappier performs best in .NET Core 3.0 and later on little-endian x86/64 processors with the + by .NET. However, Snappier performs best in .NET 6 and later on little-endian x86/64 processors with the help of System.Runtime.Instrinsics. BSD-3-Clause