diff --git a/.editorconfig b/.editorconfig index 5e47bcd8..be433963 100644 --- a/.editorconfig +++ b/.editorconfig @@ -34,3 +34,11 @@ indent_size = 4 csharp_prefer_simple_using_statement = true:warning csharp_style_prefer_switch_expression = true:warning + +dotnet_style_qualification_for_field = true:warning +dotnet_style_qualification_for_property = true:warning +dotnet_style_qualification_for_method = true:warning +dotnet_style_qualification_for_event = true:warning +csharp_style_namespace_declarations = block_scoped:warning + +csharp_style_expression_bodied_properties = when_on_single_line:warning diff --git a/.github/workflows/benchmark.yml b/.github/workflows/benchmark.yml index 5a3a6c5a..8b0696f0 100644 --- a/.github/workflows/benchmark.yml +++ b/.github/workflows/benchmark.yml @@ -16,9 +16,9 @@ jobs: - uses: actions/checkout@v4 - uses: actions/setup-dotnet@v4 with: - dotnet-version: '7.0.x' + dotnet-version: 8.0.100 - name: Run benchmark - run: cd BenchmarkTests && dotnet run -c Release --framework net7.0 --exporters json --filter '*' + run: cd BenchmarkTests && dotnet run -c Release --framework net8.0 --exporters json --filter '*' - name: Combine benchmark results run: dotnet tool install -g dotnet-script && cd BenchmarkTests && dotnet script combine-bechmarks.csx diff --git a/BenchmarkTests/BenchmarkTests.csproj b/BenchmarkTests/BenchmarkTests.csproj index dc63aa5b..7e8b7756 100644 --- a/BenchmarkTests/BenchmarkTests.csproj +++ b/BenchmarkTests/BenchmarkTests.csproj @@ -2,9 +2,7 @@ Exe - net7.0 - enable - enable + net8.0 diff --git a/BenchmarkTests/Program.cs b/BenchmarkTests/Program.cs index d0029e70..4d58ac3e 100644 --- a/BenchmarkTests/Program.cs +++ b/BenchmarkTests/Program.cs @@ -3,7 +3,7 @@ using BenchmarkDotNet.Running; var config = ManualConfig - .Create(DefaultConfig.Instance) - .AddDiagnoser(MemoryDiagnoser.Default); + .Create(DefaultConfig.Instance) + .AddDiagnoser(MemoryDiagnoser.Default); BenchmarkSwitcher.FromAssembly(typeof(Program).Assembly).Run(args, config); diff --git a/BenchmarkTests/WriteTests.cs b/BenchmarkTests/WriteTests.cs index 42172bdd..0229e1ee 100644 --- a/BenchmarkTests/WriteTests.cs +++ b/BenchmarkTests/WriteTests.cs @@ -1,35 +1,36 @@ using BenchmarkDotNet.Attributes; using Microsoft.IO; -namespace BenchmarkTests; - -public class WriteTest +namespace BenchmarkTests { - private RecyclableMemoryStream? subject; - private readonly byte[] bytes = new byte[] { 1, 2, 3, 4, 5, 6 }; - - [IterationSetup] - public void IterationSetup() + public class WriteTest { - var manager = new RecyclableMemoryStreamManager(); - this.subject = new RecyclableMemoryStream(manager); - } + private RecyclableMemoryStream? subject; + private readonly byte[] bytes = [1, 2, 3, 4, 5, 6]; - [Benchmark] - public void WriteByte() - { - for (int i = 0; i < 10_000_000; i++) + [IterationSetup] + public void IterationSetup() { - this.subject!.WriteByte(1); + var manager = new RecyclableMemoryStreamManager(); + this.subject = new RecyclableMemoryStream(manager); } - } - [Benchmark] - public void WriteSpan() - { - for (int i = 0; i < 10_000_000; i++) + [Benchmark] + public void WriteByte() + { + for (int i = 0; i < 10_000_000; i++) + { + this.subject!.WriteByte(1); + } + } + + [Benchmark] + public void WriteSpan() { - this.subject!.Write(bytes.AsSpan()); + for (int i = 0; i < 10_000_000; i++) + { + this.subject!.Write(this.bytes.AsSpan()); + } } } } diff --git a/BenchmarkTests/combine-bechmarks.csx b/BenchmarkTests/combine-bechmarks.csx index b12c2514..69783083 100644 --- a/BenchmarkTests/combine-bechmarks.csx +++ b/BenchmarkTests/combine-bechmarks.csx @@ -10,20 +10,20 @@ var resultsPath = Path.Combine(resultsDir, resultsFile + ".json"); if (!Directory.Exists(resultsDir)) { - throw new DirectoryNotFoundException($"Directory not found '{resultsDir}'"); + throw new DirectoryNotFoundException($"Directory not found '{resultsDir}'"); } if (File.Exists(resultsPath)) { - File.Delete(resultsPath); + File.Delete(resultsPath); } var reports = Directory - .GetFiles(resultsDir, searchPattern, SearchOption.TopDirectoryOnly) - .ToArray(); + .GetFiles(resultsDir, searchPattern, SearchOption.TopDirectoryOnly) + .ToArray(); if (!reports.Any()) { - throw new FileNotFoundException($"Reports not found '{searchPattern}'"); + throw new FileNotFoundException($"Reports not found '{searchPattern}'"); } var combinedReport = JsonNode.Parse(File.ReadAllText(reports.First()))!; @@ -34,12 +34,12 @@ combinedReport["Title"] = $"{resultsFile}{title.GetValue()[^16..]}"; foreach (var report in reports.Skip(1)) { - var array = JsonNode.Parse(File.ReadAllText(report))!["Benchmarks"]!.AsArray(); - foreach (var benchmark in array) - { - // Double parse avoids "The node already has a parent" exception - benchmarks.Add(JsonNode.Parse(benchmark!.ToJsonString())!); - } + var array = JsonNode.Parse(File.ReadAllText(report))!["Benchmarks"]!.AsArray(); + foreach (var benchmark in array) + { + // Double parse avoids "The node already has a parent" exception + benchmarks.Add(JsonNode.Parse(benchmark!.ToJsonString())!); + } } File.WriteAllText(resultsPath, combinedReport.ToString()); diff --git a/CHANGES.md b/CHANGES.md index 79adddb5..e08a6ee6 100644 --- a/CHANGES.md +++ b/CHANGES.md @@ -28,9 +28,9 @@ **Optimizations** -* Caculating blocks and offsets was made more efficient by using `Math.DivRem`. +* Calculating blocks and offsets was made more efficient by using `Math.DivRem`. * Reading and writing to the stream was made more efficient with fewer array accesses. -* `CopyTo` was overriden to avoid using the slower default implementation. +* `CopyTo` was overridden to avoid using the slower default implementation. # Version 2.3.1 diff --git a/Directory.Build.props b/Directory.Build.props new file mode 100644 index 00000000..45fa00a4 --- /dev/null +++ b/Directory.Build.props @@ -0,0 +1,9 @@ + + + + latest + enable + enable + + + diff --git a/Examples/Examples.csproj b/Examples/Examples.csproj index 4f0f2d27..7e75fb6d 100644 --- a/Examples/Examples.csproj +++ b/Examples/Examples.csproj @@ -1,10 +1,7 @@ - Library net8.0 - enable - enable Microsoft.IO.RecyclableMemoryStream.Examples diff --git a/Examples/Readme.cs b/Examples/Readme.cs index a6ad8b22..793dd4eb 100644 --- a/Examples/Readme.cs +++ b/Examples/Readme.cs @@ -1,4 +1,3 @@ -using Microsoft.VisualBasic; using System.Numerics; using System.Security.Cryptography; @@ -6,7 +5,7 @@ namespace Microsoft.IO.RecyclableMemoryStream.Examples { class Program { - private static readonly RecyclableMemoryStreamManager manager = new RecyclableMemoryStreamManager(); + private static readonly RecyclableMemoryStreamManager manager = new(); static void Main(string[] args) { @@ -21,25 +20,25 @@ static void Main(string[] args) internal class WriteExample { - RecyclableMemoryStreamManager manager = new RecyclableMemoryStreamManager(); - byte[] sourceBuffer = new byte[100]; + readonly RecyclableMemoryStreamManager manager = new(); + readonly byte[] sourceBuffer = new byte[100]; internal void Example() { // Writing an buffer to a stream // START EXAMPLE - using (var stream = manager.GetStream("Program.Main")) + using (var stream = this.manager.GetStream("Program.Main")) { - stream.Write(sourceBuffer, 0, sourceBuffer.Length); + stream.Write(this.sourceBuffer, 0, this.sourceBuffer.Length); } // END EXAMPLE // Provide buffer in GetStream // START EXAMPLE - using (var stream = manager.GetStream("Program.Main", sourceBuffer, - 0, sourceBuffer.Length)) + using (var stream = this.manager.GetStream("Program.Main", this.sourceBuffer, + 0, this.sourceBuffer.Length)) { - + } // END EXAMPLE } @@ -68,14 +67,14 @@ internal void Example() internal class IBufferWriterExample { - RecyclableMemoryStreamManager manager = new RecyclableMemoryStreamManager(); + readonly RecyclableMemoryStreamManager manager = new(); internal void Example() { // START EXAMPLE var bigInt = BigInteger.Parse("123456789013374299100987654321"); - using (var stream = manager.GetStream()) + using (var stream = this.manager.GetStream()) { Span buffer = stream.GetSpan(bigInt.GetByteCount()); bigInt.TryWriteBytes(buffer, out int bytesWritten); @@ -87,12 +86,12 @@ internal void Example() internal class GetReadOnlySequenceExample { - RecyclableMemoryStreamManager manager = new RecyclableMemoryStreamManager(); + readonly RecyclableMemoryStreamManager manager = new(); internal void Example() { // START EXAMPLE - using (var stream = manager.GetStream()) + using (var stream = this.manager.GetStream()) using (var sha256Hasher = IncrementalHash.CreateHash(HashAlgorithmName.SHA256)) { foreach (var memory in stream.GetReadOnlySequence()) @@ -105,5 +104,4 @@ internal void Example() //END EXAMPLE } } - } diff --git a/Microsoft.IO.RecyclableMemoryStream.sln b/Microsoft.IO.RecyclableMemoryStream.sln index 128de502..093d031b 100644 --- a/Microsoft.IO.RecyclableMemoryStream.sln +++ b/Microsoft.IO.RecyclableMemoryStream.sln @@ -11,6 +11,7 @@ Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "Solution Items", "Solution ProjectSection(SolutionItems) = preProject .editorconfig = .editorconfig CHANGES.md = CHANGES.md + Directory.Build.props = Directory.Build.props global.json = global.json LICENSE = LICENSE README.md = README.md @@ -23,6 +24,7 @@ Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = ".github", ".github", "{937E EndProject Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "workflows", "workflows", "{0ED3EBE5-1575-4649-A1F9-3D24BFFC4A9B}" ProjectSection(SolutionItems) = preProject + .github\workflows\benchmark.yml = .github\workflows\benchmark.yml .github\workflows\ci-cd.yml = .github\workflows\ci-cd.yml .github\workflows\codeql-analysis.yml = .github\workflows\codeql-analysis.yml EndProjectSection diff --git a/UnitTests/RecyclableMemoryStreamEventListener.cs b/UnitTests/RecyclableMemoryStreamEventListener.cs index 69365670..6bf80a78 100644 --- a/UnitTests/RecyclableMemoryStreamEventListener.cs +++ b/UnitTests/RecyclableMemoryStreamEventListener.cs @@ -1,4 +1,4 @@ -// The MIT License (MIT) +// The MIT License (MIT) // // Copyright (c) 2015-2016 Microsoft // @@ -52,13 +52,13 @@ protected override void OnEventWritten(EventWrittenEventArgs eventData) switch (eventId) { - case MemoryStreamDisposed: - Thread.Sleep(10); - break; - case MemoryStreamDoubleDispose: - MemoryStreamDoubleDisposeCalled = true; - break; + case MemoryStreamDisposed: + Thread.Sleep(10); + break; + case MemoryStreamDoubleDispose: + this.MemoryStreamDoubleDisposeCalled = true; + break; } } } -} \ No newline at end of file +} diff --git a/UnitTests/Tests.cs b/UnitTests/Tests.cs index b6d4a3b1..b2f788fc 100644 --- a/UnitTests/Tests.cs +++ b/UnitTests/Tests.cs @@ -56,9 +56,9 @@ public abstract class BaseRecyclableMemoryStreamTests public void OneTimeTearDown() { // Make sure we saw ETW events for each event -- just a rough test to ensure they're being sent. - for (int i = 1; i < eventListener.EventCounts.Length; i++) + for (int i = 1; i < this.eventListener.EventCounts.Length; i++) { - Assert.That(eventListener.EventCounts[i], Is.GreaterThan(0), $"No events recorded for eventId {i}"); + Assert.That(this.eventListener.EventCounts[i], Is.GreaterThan(0), $"No events recorded for eventId {i}"); } this.eventListener.Dispose(); } @@ -209,7 +209,7 @@ public void GetVeryLargeBufferRecordsCallStack() public void ReturnLargerBufferWithNullBufferThrowsException() { var memMgr = this.GetMemoryManager(); - Assert.Throws(() => memMgr.ReturnLargeBuffer(null, DefaultId, DefaultTag)); + Assert.Throws(() => memMgr.ReturnLargeBuffer(null!, DefaultId, DefaultTag)); } [Test] @@ -224,14 +224,14 @@ public void ReturnLargeBufferWithWrongSizedBufferThrowsException() public void ReturnNullBlockThrowsException() { var memMgr = this.GetMemoryManager(); - Assert.Throws(() => memMgr.ReturnBlock(null, Guid.Empty, string.Empty)); + Assert.Throws(() => memMgr.ReturnBlock(null!, Guid.Empty, string.Empty)); } [Test] public void ReturnNullBlocksThrowsException() { var memMgr = this.GetMemoryManager(); - Assert.Throws(() => memMgr.ReturnBlocks(null, Guid.Empty, string.Empty)); + Assert.Throws(() => memMgr.ReturnBlocks(null!, Guid.Empty, string.Empty)); } [Test] @@ -259,7 +259,7 @@ public void ReturnBlocksWithNullBufferThrowsException() var buffers = new List(3); var memMgr = this.GetMemoryManager(); buffers.Add(memMgr.GetBlock()); - buffers.Add(null); + buffers.Add(null!); buffers.Add(memMgr.GetBlock()); Assert.Throws(() => memMgr.ReturnBlocks(buffers, Guid.Empty, string.Empty)); } @@ -329,7 +329,7 @@ public void ReturningBlocksAreDroppedIfEnoughFree() // Only allow 2 blocks in the free pool at a time memMgr.options.MaximumSmallPoolFreeBytes = MaxFreeBuffersAllowed * memMgr.options.BlockSize; var buffers = new List(BuffersToTest); - for (var i = buffers.Capacity; i>0 ; --i) + for (var i = buffers.Capacity; i > 0; --i) { buffers.Add(memMgr.GetBlock()); } @@ -354,7 +354,7 @@ public void ReturningBlocksNeverDroppedIfMaxFreeSizeZero() var buffers = new List(BuffersToTest); for (var i = buffers.Capacity; i > 0; --i) { - buffers.Add( memMgr.GetBlock()); + buffers.Add(memMgr.GetBlock()); } Assert.That(memMgr.SmallPoolFreeSize, Is.EqualTo(0)); @@ -435,7 +435,7 @@ public void GettingBlockAdjustsFreeAndInUseSize() Assert.That(memMgr.SmallPoolFreeSize, Is.EqualTo(0)); Assert.That(memMgr.SmallPoolInUseSize, Is.EqualTo(memMgr.options.BlockSize)); - memMgr.ReturnBlocks(new List {block}, Guid.Empty, string.Empty); + memMgr.ReturnBlocks([block], Guid.Empty, string.Empty); Assert.That(memMgr.SmallPoolFreeSize, Is.EqualTo(memMgr.options.BlockSize)); Assert.That(memMgr.SmallPoolInUseSize, Is.EqualTo(0)); @@ -446,7 +446,7 @@ public void GettingBlockAdjustsFreeAndInUseSize() Assert.That(memMgr.SmallPoolFreeSize, Is.EqualTo(0)); Assert.That(memMgr.SmallPoolInUseSize, Is.EqualTo(memMgr.options.BlockSize)); - memMgr.ReturnBlocks(new List {block}, Guid.Empty, string.Empty); + memMgr.ReturnBlocks([block], Guid.Empty, string.Empty); Assert.That(memMgr.SmallPoolFreeSize, Is.EqualTo(memMgr.options.BlockSize)); Assert.That(memMgr.SmallPoolInUseSize, Is.EqualTo(0)); @@ -530,7 +530,7 @@ public void GetBufferAdjustsLargePoolFreeSize() [Test] public void TryGetBufferFailsOnLargeStream() { - var stream = GetMultiGBStream(); + var stream = this.GetMultiGBStream(); // Exception path -- no content, but GetBuffer will throw Assert.That(stream.TryGetBuffer(out ArraySegment seg), Is.False); Assert.That(seg.Offset, Is.Zero); @@ -961,7 +961,7 @@ public void WritePastEndIncreasesCapacity() stream.Write(buffer, 0, buffer.Length); Assert.That(stream.Capacity, Is.EqualTo(DefaultBlockSize)); Assert.That(stream.MemoryManager.SmallPoolInUseSize, Is.EqualTo(DefaultBlockSize)); - stream.Write(new byte[] {0}, 0, 1); + stream.Write([0], 0, 1); Assert.That(stream.Capacity, Is.EqualTo(2 * DefaultBlockSize)); Assert.That(stream.MemoryManager.SmallPoolInUseSize, Is.EqualTo(2 * DefaultBlockSize)); } @@ -1002,35 +1002,35 @@ public void WriteAfterLargeBufferDoesNotAllocateMoreBlocks() public void WriteNullBufferThrowsException() { var stream = this.GetDefaultStream(); - Assert.Throws(() => stream.Write(null, 0, 0)); + Assert.Throws(() => stream.Write(null!, 0, 0)); } [Test] public void WriteStartPastBufferThrowsException() { var stream = this.GetDefaultStream(); - Assert.Throws(() => stream.Write(new byte[] {0, 1}, 2, 1)); + Assert.Throws(() => stream.Write([0, 1], 2, 1)); } [Test] public void WriteStartBeforeBufferThrowsException() { var stream = this.GetDefaultStream(); - Assert.Throws(() => stream.Write(new byte[] {0, 1}, -1, 0)); + Assert.Throws(() => stream.Write([0, 1], -1, 0)); } [Test] public void WriteNegativeCountThrowsException() { var stream = this.GetDefaultStream(); - Assert.Throws(() => stream.Write(new byte[] {0, 1}, 0, -1)); + Assert.Throws(() => stream.Write([0, 1], 0, -1)); } [Test] public void WriteCountOutOfRangeThrowsException() { var stream = this.GetDefaultStream(); - Assert.Throws(() => stream.Write(new byte[] {0, 1}, 0, 3)); + Assert.Throws(() => stream.Write([0, 1], 0, 3)); } // This is a valid test, but it's too resource-intensive to run on a regular basis. @@ -1132,7 +1132,7 @@ public void WriteSpanPastEndIncreasesCapacity() stream.Write(buffer.AsSpan()); Assert.That(stream.Capacity, Is.EqualTo(DefaultBlockSize)); Assert.That(stream.MemoryManager.SmallPoolInUseSize, Is.EqualTo(DefaultBlockSize)); - stream.Write(new byte[] {0}.AsSpan()); + stream.Write([0]); Assert.That(stream.Capacity, Is.EqualTo(2 * DefaultBlockSize)); Assert.That(stream.MemoryManager.SmallPoolInUseSize, Is.EqualTo(2 * DefaultBlockSize)); } @@ -1700,7 +1700,7 @@ void read() public void ReadNullBufferThrowsException() { var stream = this.GetDefaultStream(); - Assert.Throws(() => stream.Read(null, 0, 1)); + Assert.Throws(() => stream.Read(null!, 0, 1)); } [Test] @@ -2093,7 +2093,7 @@ public void EnsureCapacityOperatesOnLargeBufferWhenNeeded() [Test] public void CapacityThrowsOnTooLargeStream() { - var stream = GetDefaultStream(); + var stream = this.GetDefaultStream(); stream.Capacity64 = (long)Int32.MaxValue + 1; Assert.That(stream.Capacity64, Is.EqualTo((long)Int32.MaxValue + 1)); Assert.Throws(() => { var cap = stream.Capacity; }); @@ -2622,7 +2622,7 @@ public void AccessingObjectAfterDisposeThrowsObjectDisposedException() [Test] public void DisposeReportsStreamLength() { - var stream = GetDefaultStream(); + var stream = this.GetDefaultStream(); stream.WriteByte(255); bool handlerTriggered = false; stream.MemoryManager.StreamLength += (obj, args) => @@ -2776,7 +2776,7 @@ public void GetStreamWithOnlyReadOnlySpan() public void WriteToNullStreamThrowsException() { var stream = this.GetDefaultStream(); - Assert.Throws(() => stream.WriteTo(null)); + Assert.Throws(() => stream.WriteTo(null!)); } [Test] @@ -2855,7 +2855,7 @@ public void WriteToOtherStreamOffsetCountHasEqualContentsFullStream(int bufferSi public void WriteToOtherStreamOffsetCountThrowException() { var stream = this.GetDefaultStream(); - Assert.Throws(() => stream.WriteTo((Stream)null, 0, (int)stream.Length)); + Assert.Throws(() => stream.WriteTo((Stream)null!, 0, (int)stream.Length)); Assert.Throws(() => stream.WriteTo(stream, -1, (int)stream.Length)); Assert.Throws(() => stream.WriteTo(stream, 1, (int)stream.Length)); Assert.Throws(() => stream.WriteTo(stream, 0, (int)stream.Length + 1)); @@ -2864,15 +2864,15 @@ public void WriteToOtherStreamOffsetCountThrowException() [Test] public void WriteToByteArray_NullTarget() { - using var stream = GetDefaultStream(); - Assert.Throws(() => stream.WriteTo(null)); + using var stream = this.GetDefaultStream(); + Assert.Throws(() => stream.WriteTo(null!)); } [Test] public void WriteToByteArray_FullArray_Small() { - byte[] sourceBuffer = GetRandomBuffer(100); - using var stream = GetDefaultStream(); + byte[] sourceBuffer = this.GetRandomBuffer(100); + using var stream = this.GetDefaultStream(); stream.Write(sourceBuffer); byte[] targetBuffer = new byte[sourceBuffer.Length]; stream.WriteTo(targetBuffer); @@ -2882,8 +2882,8 @@ public void WriteToByteArray_FullArray_Small() [Test] public void WriteToByteArrayDoesNotChangePosition() { - byte[] sourceBuffer = GetRandomBuffer(100); - using var stream = GetDefaultStream(); + byte[] sourceBuffer = this.GetRandomBuffer(100); + using var stream = this.GetDefaultStream(); stream.Write(sourceBuffer); stream.Position = sourceBuffer.Length / 2; byte[] targetBuffer = new byte[sourceBuffer.Length]; @@ -2895,8 +2895,8 @@ public void WriteToByteArrayDoesNotChangePosition() [Test] public void WriteToByteArray_Full_Array_Large() { - byte[] sourceBuffer = GetRandomBuffer(25 * DefaultBlockSize); - using var stream = GetDefaultStream(); + byte[] sourceBuffer = this.GetRandomBuffer(25 * DefaultBlockSize); + using var stream = this.GetDefaultStream(); stream.Write(sourceBuffer); stream.GetBuffer(); byte[] targetBuffer = new byte[sourceBuffer.Length]; @@ -2907,8 +2907,8 @@ public void WriteToByteArray_Full_Array_Large() [Test] public void WriteToByteArray_OffsetCount() { - byte[] sourceBuffer = GetRandomBuffer(100); - using var stream = GetDefaultStream(); + byte[] sourceBuffer = this.GetRandomBuffer(100); + using var stream = this.GetDefaultStream(); stream.Write(sourceBuffer); byte[] targetBuffer = new byte[sourceBuffer.Length]; stream.WriteTo(targetBuffer, sourceBuffer.Length / 2, sourceBuffer.Length / 2); @@ -2918,8 +2918,8 @@ public void WriteToByteArray_OffsetCount() [Test] public void WriteToByteArray_CountLargerThanSourceWithZeroOffset() { - byte[] sourceBuffer = GetRandomBuffer(100); - using var stream = GetDefaultStream(); + byte[] sourceBuffer = this.GetRandomBuffer(100); + using var stream = this.GetDefaultStream(); stream.Write(sourceBuffer); byte[] targetBuffer = new byte[sourceBuffer.Length]; Assert.Throws(() => stream.WriteTo(targetBuffer, 0, sourceBuffer.Length + 1)); @@ -2928,8 +2928,8 @@ public void WriteToByteArray_CountLargerThanSourceWithZeroOffset() [Test] public void WriteToByteArray_CountLargerThanSourceWithNonZeroOffset() { - byte[] sourceBuffer = GetRandomBuffer(100); - using var stream = GetDefaultStream(); + byte[] sourceBuffer = this.GetRandomBuffer(100); + using var stream = this.GetDefaultStream(); stream.Write(sourceBuffer); byte[] targetBuffer = new byte[sourceBuffer.Length]; Assert.Throws(() => stream.WriteTo(targetBuffer, 1, sourceBuffer.Length)); @@ -2938,8 +2938,8 @@ public void WriteToByteArray_CountLargerThanSourceWithNonZeroOffset() [Test] public void WriteToByteArray_CountLargerThanTargetZeroOffset() { - byte[] sourceBuffer = GetRandomBuffer(100); - using var stream = GetDefaultStream(); + byte[] sourceBuffer = this.GetRandomBuffer(100); + using var stream = this.GetDefaultStream(); stream.Write(sourceBuffer); byte[] targetBuffer = new byte[sourceBuffer.Length]; Assert.Throws(() => stream.WriteTo(targetBuffer, 0, sourceBuffer.Length, 1)); @@ -2948,8 +2948,8 @@ public void WriteToByteArray_CountLargerThanTargetZeroOffset() [Test] public void WriteToByteArray_CountLargerThanTargetNonZeroOffset() { - byte[] sourceBuffer = GetRandomBuffer(100); - using var stream = GetDefaultStream(); + byte[] sourceBuffer = this.GetRandomBuffer(100); + using var stream = this.GetDefaultStream(); stream.Write(sourceBuffer); byte[] targetBuffer = new byte[sourceBuffer.Length]; Assert.Throws(() => stream.WriteTo(targetBuffer, 1, sourceBuffer.Length - 1, 2)); @@ -2958,8 +2958,8 @@ public void WriteToByteArray_CountLargerThanTargetNonZeroOffset() [Test] public void WriteToByteArray_TargetOffsetLargerThanTarget() { - byte[] sourceBuffer = GetRandomBuffer(100); - using var stream = GetDefaultStream(); + byte[] sourceBuffer = this.GetRandomBuffer(100); + using var stream = this.GetDefaultStream(); stream.Write(sourceBuffer); byte[] targetBuffer = new byte[sourceBuffer.Length]; Assert.Throws(() => stream.WriteTo(targetBuffer, 0, 1, sourceBuffer.Length)); @@ -2968,8 +2968,8 @@ public void WriteToByteArray_TargetOffsetLargerThanTarget() [Test] public void WriteToByteArray_NegativeOffsetThrowsException() { - byte[] sourceBuffer = GetRandomBuffer(100); - using var stream = GetDefaultStream(); + byte[] sourceBuffer = this.GetRandomBuffer(100); + using var stream = this.GetDefaultStream(); stream.Write(sourceBuffer); byte[] targetBuffer = new byte[sourceBuffer.Length]; Assert.Throws(() => stream.WriteTo(targetBuffer, -1, sourceBuffer.Length)); @@ -2979,8 +2979,8 @@ public void WriteToByteArray_NegativeOffsetThrowsException() [Test] public void WriteToByteArray_NegativeTargetOffsetThrowsException() { - byte[] sourceBuffer = GetRandomBuffer(100); - using var stream = GetDefaultStream(); + byte[] sourceBuffer = this.GetRandomBuffer(100); + using var stream = this.GetDefaultStream(); stream.Write(sourceBuffer); byte[] targetBuffer = new byte[sourceBuffer.Length]; Assert.Throws(() => stream.WriteTo(targetBuffer, 0, sourceBuffer.Length, -1)); @@ -3045,8 +3045,8 @@ public void MaximumStreamCapacity_StreamUnchangedAfterWriteOverLimit() [Test] public void CopyTo() { - using var stream = GetDefaultStream(); - var buffer = GetRandomBuffer(100); + using var stream = this.GetDefaultStream(); + var buffer = this.GetRandomBuffer(100); stream.Write(buffer); using var memoryStream = new MemoryStream(); @@ -3055,7 +3055,7 @@ public void CopyTo() var destinationBuffer = memoryStream.GetBuffer(); - RMSAssert.BuffersAreEqual(destinationBuffer, buffer, 100); + RMSAssert.BuffersAreEqual(destinationBuffer, buffer, 100); } #endregion @@ -3064,15 +3064,15 @@ public void CopyTo() [Test] public void CopyToAsyncThrowsOnNullDestination() { - using var stream = GetDefaultStream(); - Assert.Throws(() => stream.CopyToAsync(null, DefaultBlockSize, CancellationToken.None)); + using var stream = this.GetDefaultStream(); + Assert.Throws(() => stream.CopyToAsync(null!, DefaultBlockSize, CancellationToken.None)); } [Test] public void CopyToAsyncThrowsIfDisposed() { - var stream = GetDefaultStream(); - using var otherStream = GetDefaultStream(); + var stream = this.GetDefaultStream(); + using var otherStream = this.GetDefaultStream(); stream.Dispose(); Assert.Throws(() => stream.CopyToAsync(otherStream, DefaultBlockSize, CancellationToken.None)); } @@ -3081,11 +3081,11 @@ public void CopyToAsyncThrowsIfDisposed() [TestCase(100)] public void CopyToAsyncSmallerThanBlock(int offset) { - using var stream = GetDefaultStream(); - var buffer = GetRandomBuffer(DefaultBlockSize / 2); + using var stream = this.GetDefaultStream(); + var buffer = this.GetRandomBuffer(DefaultBlockSize / 2); stream.Write(buffer, 0, buffer.Length); stream.Position = offset; - var otherStream = GetDefaultStream(); + var otherStream = this.GetDefaultStream(); stream.CopyToAsync(otherStream); Assert.That(otherStream.Length, Is.EqualTo(stream.Length - offset)); RMSAssert.BuffersAreEqual(new ReadOnlySpan(stream.GetBuffer(), offset, buffer.Length - offset), otherStream.GetBuffer(), buffer.Length - offset); @@ -3094,8 +3094,8 @@ public void CopyToAsyncSmallerThanBlock(int offset) [Test] public void CopyToAsyncZeroBlocks() { - using var stream = GetDefaultStream(); - var otherStream = GetDefaultStream(); + using var stream = this.GetDefaultStream(); + var otherStream = this.GetDefaultStream(); stream.CopyToAsync(otherStream); Assert.That(otherStream.Length, Is.EqualTo(0)); } @@ -3103,7 +3103,7 @@ public void CopyToAsyncZeroBlocks() [Test] public void CopyToAsyncZeroBlocksNonMemoryStream() { - using var stream = GetDefaultStream(); + using var stream = this.GetDefaultStream(); var filename = Path.GetRandomFileName(); using (var fileStream = new FileStream(filename, FileMode.Create, FileAccess.ReadWrite, FileShare.ReadWrite, DefaultBlockSize, FileOptions.Asynchronous)) { @@ -3117,11 +3117,11 @@ public void CopyToAsyncZeroBlocksNonMemoryStream() [TestCase(100)] public void CopyToAsyncOneBlock(int offset) { - using var stream = GetDefaultStream(); - var buffer = GetRandomBuffer(DefaultBlockSize); + using var stream = this.GetDefaultStream(); + var buffer = this.GetRandomBuffer(DefaultBlockSize); stream.Write(buffer, 0, buffer.Length); stream.Position = offset; - var otherStream = GetDefaultStream(); + var otherStream = this.GetDefaultStream(); stream.CopyToAsync(otherStream); Assert.That(otherStream.Length, Is.EqualTo(stream.Length - offset)); RMSAssert.BuffersAreEqual(new ReadOnlySpan(stream.GetBuffer(), offset, buffer.Length - offset), otherStream.GetBuffer(), buffer.Length - offset); @@ -3131,8 +3131,8 @@ public void CopyToAsyncOneBlock(int offset) [TestCase(100)] public void CopyToAsyncOneBlockNonMemoryStream(int offset) { - using var stream = GetDefaultStream(); - var buffer = GetRandomBuffer(DefaultBlockSize); + using var stream = this.GetDefaultStream(); + var buffer = this.GetRandomBuffer(DefaultBlockSize); stream.Write(buffer, 0, buffer.Length); stream.Position = offset; var filename = Path.GetRandomFileName(); @@ -3149,11 +3149,11 @@ public void CopyToAsyncOneBlockNonMemoryStream(int offset) [TestCase(100)] public void CopyToAsyncMultipleBlocks(int offset) { - using var stream = GetDefaultStream(); - var buffer = GetRandomBuffer(DefaultBlockSize * 25); + using var stream = this.GetDefaultStream(); + var buffer = this.GetRandomBuffer(DefaultBlockSize * 25); stream.Write(buffer, 0, buffer.Length); stream.Position = offset; - var otherStream = GetDefaultStream(); + var otherStream = this.GetDefaultStream(); stream.CopyToAsync(otherStream); Assert.That(otherStream.Length, Is.EqualTo(stream.Length - offset)); RMSAssert.BuffersAreEqual(new ReadOnlySpan(stream.GetBuffer(), offset, buffer.Length - offset), otherStream.GetBuffer(), buffer.Length - offset); @@ -3163,8 +3163,8 @@ public void CopyToAsyncMultipleBlocks(int offset) [TestCase(100)] public void CopyToAsyncMultipleBlocksNonMemoryStream(int offset) { - using var stream = GetDefaultStream(); - var buffer = GetRandomBuffer(DefaultBlockSize * 25); + using var stream = this.GetDefaultStream(); + var buffer = this.GetRandomBuffer(DefaultBlockSize * 25); stream.Write(buffer, 0, buffer.Length); stream.Position = offset; var filename = Path.GetRandomFileName(); @@ -3181,10 +3181,10 @@ public void CopyToAsyncMultipleBlocksNonMemoryStream(int offset) [TestCase(100)] public void CopyToAsyncLargeBuffer(int offset) { - using var stream = GetDefaultStream(); - var buffer = GetRandomBuffer(DefaultBlockSize * 25); + using var stream = this.GetDefaultStream(); + var buffer = this.GetRandomBuffer(DefaultBlockSize * 25); stream.Write(buffer, 0, buffer.Length); - var otherStream = GetDefaultStream(); + var otherStream = this.GetDefaultStream(); stream.Position = offset; stream.GetBuffer(); stream.CopyToAsync(otherStream); @@ -3196,8 +3196,8 @@ public void CopyToAsyncLargeBuffer(int offset) [TestCase(100)] public void CopyToAsyncLargeBufferNonMemoryStream(int offset) { - using var stream = GetDefaultStream(); - var buffer = GetRandomBuffer(DefaultBlockSize * 25); + using var stream = this.GetDefaultStream(); + var buffer = this.GetRandomBuffer(DefaultBlockSize * 25); stream.Write(buffer, 0, buffer.Length); stream.GetBuffer(); stream.Position = offset; @@ -3218,8 +3218,8 @@ public void CopyToAsyncLargeBufferNonMemoryStream(int offset) public void CopyToAsyncChangesSourcePosition(bool fileStreamTarget, bool largeBuffer) { using var targetStream = fileStreamTarget ? File.OpenWrite(Path.GetRandomFileName()) : (Stream)new MemoryStream(); - using var stream = GetDefaultStream(); - var buffer = GetRandomBuffer(largeBuffer ? DefaultBlockSize * 25 : 100); + using var stream = this.GetDefaultStream(); + var buffer = this.GetRandomBuffer(largeBuffer ? DefaultBlockSize * 25 : 100); stream.Write(buffer); Assert.That(stream.Position, Is.EqualTo(buffer.Length)); stream.Position = buffer.Length / 2; @@ -3234,12 +3234,13 @@ public void CopyToAsyncChangesSourcePosition(bool fileStreamTarget, bool largeBu [Test] public void VeryLargeStream_Write() { - if(this.ZeroOutBuffer) { - Assert.Ignore("Disable test due to increased memory consumption that currently does not work with the hardware limits of the gitlab runners."); + if (this.ZeroOutBuffer) + { + Assert.Ignore("Disable test due to increased memory consumption that currently does not work with the hardware limits of the GitHub runners."); } - var stream = GetMultiGBStream(); + var stream = this.GetMultiGBStream(); Assert.That(stream.Capacity64, Is.GreaterThanOrEqualTo(DefaultVeryLargeStreamSize)); - var buffer = GetRandomBuffer(1 << 20); + var buffer = this.GetRandomBuffer(1 << 20); while (stream.Length < DefaultVeryLargeStreamSize) { stream.Write(buffer); @@ -3259,12 +3260,13 @@ public void VeryLargeStream_Write() [Test] public void VeryLargeStream_WriteOffsetCount() { - if(this.ZeroOutBuffer) { - Assert.Ignore("Disable test due to increased memory consumption that currently does not work with the hardware limits of the gitlab runners."); + if (this.ZeroOutBuffer) + { + Assert.Ignore("Disable test due to increased memory consumption that currently does not work with the hardware limits of the GitHub runners."); } - var stream = GetMultiGBStream(); + var stream = this.GetMultiGBStream(); Assert.That(stream.Capacity64, Is.GreaterThanOrEqualTo(DefaultVeryLargeStreamSize)); - var buffer = GetRandomBuffer(1 << 20); + var buffer = this.GetRandomBuffer(1 << 20); while (stream.Length < DefaultVeryLargeStreamSize) { stream.Write(buffer, 0, buffer.Length); @@ -3284,10 +3286,11 @@ public void VeryLargeStream_WriteOffsetCount() [Test] public void VeryLargeStream_SetLength() { - if(this.ZeroOutBuffer) { - Assert.Ignore("Disable test due to increased memory consumption that currently does not work with the hardware limits of the gitlab runners."); + if (this.ZeroOutBuffer) + { + Assert.Ignore("Disable test due to increased memory consumption that currently does not work with the hardware limits of the GitHub runners."); } - var stream = GetMultiGBStream(); + var stream = this.GetMultiGBStream(); stream.SetLength(DefaultVeryLargeStreamSize); Assert.That(stream.Length, Is.EqualTo(DefaultVeryLargeStreamSize)); Assert.That(stream.Capacity64, Is.AtLeast(DefaultVeryLargeStreamSize)); @@ -3299,11 +3302,12 @@ public void VeryLargeStream_SetLength() [Test] public void VeryLargeStream_ExistingLargeBufferThrowsOnMultiGBLength() { - if(this.ZeroOutBuffer) { - Assert.Ignore("Disable test due to increased memory consumption that currently does not work with the hardware limits of the gitlab runners."); + if (this.ZeroOutBuffer) + { + Assert.Ignore("Disable test due to increased memory consumption that currently does not work with the hardware limits of the GitHub runners."); } - var stream = GetDefaultStream(); - var data = GetRandomBuffer(1 << 20); + var stream = this.GetDefaultStream(); + var data = this.GetRandomBuffer(1 << 20); stream.Write(data); var buffer = stream.GetBuffer(); Assert.Throws(() => stream.SetLength(DefaultVeryLargeStreamSize)); @@ -3312,20 +3316,22 @@ public void VeryLargeStream_ExistingLargeBufferThrowsOnMultiGBLength() [Test] public void VeryLargeStream_GetBufferThrows() { - if(this.ZeroOutBuffer) { - Assert.Ignore("Disable test due to increased memory consumption that currently does not work with the hardware limits of the gitlab runners."); + if (this.ZeroOutBuffer) + { + Assert.Ignore("Disable test due to increased memory consumption that currently does not work with the hardware limits of the GitHub runners."); } - var stream = GetMultiGBStream(); + var stream = this.GetMultiGBStream(); Assert.Throws(() => stream.GetBuffer()); } [Test] public void VeryLargeStream_SetPositionThrowsIfLargeBuffer() { - if(this.ZeroOutBuffer) { - Assert.Ignore("Disable test due to increased memory consumption that currently does not work with the hardware limits of the gitlab runners."); + if (this.ZeroOutBuffer) + { + Assert.Ignore("Disable test due to increased memory consumption that currently does not work with the hardware limits of the GitHub runners."); } - var stream = GetDefaultStream(); + var stream = this.GetDefaultStream(); stream.SetLength(1 << 20); var buffer = stream.GetBuffer(); Assert.Throws(() => stream.Position = DefaultVeryLargeStreamSize); @@ -3334,10 +3340,11 @@ public void VeryLargeStream_SetPositionThrowsIfLargeBuffer() [Test] public void VeryLargeStream_WriteByte() { - if(this.ZeroOutBuffer) { - Assert.Ignore("Disable test due to increased memory consumption that currently does not work with the hardware limits of the gitlab runners."); + if (this.ZeroOutBuffer) + { + Assert.Ignore("Disable test due to increased memory consumption that currently does not work with the hardware limits of the GitHub runners."); } - var stream = GetMultiGBStream(); + var stream = this.GetMultiGBStream(); var buffer = new byte[100 << 20]; while (stream.Length < DefaultVeryLargeStreamSize) { @@ -3353,10 +3360,11 @@ public void VeryLargeStream_WriteByte() [Test] public void VeryLargeStream_GetReadOnlySequence() { - if(this.ZeroOutBuffer) { - Assert.Ignore("Disable test due to increased memory consumption that currently does not work with the hardware limits of the gitlab runners."); + if (this.ZeroOutBuffer) + { + Assert.Ignore("Disable test due to increased memory consumption that currently does not work with the hardware limits of the GitHub runners."); } - var stream = GetMultiGBStream(); + var stream = this.GetMultiGBStream(); var buffer = new byte[100 << 20]; while (stream.Length < DefaultVeryLargeStreamSize) { @@ -3374,8 +3382,9 @@ public void VeryLargeStream_GetReadOnlySequence() private RecyclableMemoryStream GetMultiGBStream() { - if(this.ZeroOutBuffer) { - Assert.Ignore("Disable test due to increased memory consumption that currently does not work with the hardware limits of the gitlab runners."); + if (this.ZeroOutBuffer) + { + Assert.Ignore("Disable test due to increased memory consumption that currently does not work with the hardware limits of the GitHub runners."); } return new RecyclableMemoryStream(this.GetMemoryManager(), "GetMultiGBStream", DefaultVeryLargeStreamSize); } @@ -3386,7 +3395,7 @@ private RecyclableMemoryStream GetMultiGBStream() [Test] public void EventStreamCreated() { - var mgr = GetMemoryManager(); + var mgr = this.GetMemoryManager(); bool raised = false; mgr.StreamCreated += (obj, args) => { @@ -3402,7 +3411,7 @@ public void EventStreamCreated() [Test] public void EventStreamDisposed() { - var mgr = GetMemoryManager(); + var mgr = this.GetMemoryManager(); mgr.options.GenerateCallStacks = true; bool raised = false; mgr.StreamDisposed += (obj, args) => @@ -3424,7 +3433,7 @@ public void EventStreamDisposed() [Test] public void EventStreamDoubleDisposed() { - var mgr = GetMemoryManager(); + var mgr = this.GetMemoryManager(); mgr.options.GenerateCallStacks = true; bool raised = false; mgr.StreamDoubleDisposed += (obj, args) => @@ -3445,7 +3454,7 @@ public void EventStreamDoubleDisposed() [Test] public void EventStreamConvertedToArray() { - var mgr = GetMemoryManager(); + var mgr = this.GetMemoryManager(); mgr.options.GenerateCallStacks = true; bool raised = false; mgr.StreamConvertedToArray += (obj, args) => @@ -3465,7 +3474,7 @@ public void EventStreamConvertedToArray() [Test] public void EventStreamOverCapacity() { - var mgr = GetMemoryManager(); + var mgr = this.GetMemoryManager(); mgr.options.MaximumStreamCapacity = mgr.options.BlockSize; mgr.options.GenerateCallStacks = true; bool raised = false; @@ -3480,14 +3489,14 @@ public void EventStreamOverCapacity() }; var stream = mgr.GetStream("UnitTest", 13); - Assert.Throws(()=>stream.Capacity = mgr.options.BlockSize * 2); + Assert.Throws(() => stream.Capacity = mgr.options.BlockSize * 2); Assert.That(raised, Is.True); } [Test] public void EventBlockCreated() { - var mgr = GetMemoryManager(); + var mgr = this.GetMemoryManager(); bool raised = false; mgr.BlockCreated += (obj, args) => { @@ -3501,7 +3510,7 @@ public void EventBlockCreated() [Test] public void EventLargeBufferCreated() { - var mgr = GetMemoryManager(); + var mgr = this.GetMemoryManager(); bool raised = false; long requestedSize = mgr.options.LargeBufferMultiple; mgr.LargeBufferCreated += (obj, args) => @@ -3516,7 +3525,7 @@ public void EventLargeBufferCreated() raised = true; }; var stream = mgr.GetStream("UnitTest", 13); - var buffer = GetRandomBuffer((int)requestedSize); + var buffer = this.GetRandomBuffer((int)requestedSize); stream.Write(buffer); var buf2 = stream.GetBuffer(); Assert.That(raised, Is.True); @@ -3525,7 +3534,7 @@ public void EventLargeBufferCreated() [Test] public void EventUnpooledLargeBufferCreated() { - var mgr = GetMemoryManager(); + var mgr = this.GetMemoryManager(); mgr.options.GenerateCallStacks = true; bool raised = false; long requestedSize = mgr.options.MaximumBufferSize + 1; @@ -3541,7 +3550,7 @@ public void EventUnpooledLargeBufferCreated() raised = true; }; var stream = mgr.GetStream("UnitTest", 13); - var buffer = GetRandomBuffer((int)requestedSize); + var buffer = this.GetRandomBuffer((int)requestedSize); stream.Write(buffer); var buf2 = stream.GetBuffer(); Assert.That(raised, Is.True); @@ -3550,7 +3559,7 @@ public void EventUnpooledLargeBufferCreated() [Test] public void EventBlockDiscarded() { - var mgr = GetMemoryManager(); + var mgr = this.GetMemoryManager(); mgr.options.MaximumSmallPoolFreeBytes = mgr.options.BlockSize; int raisedCount = 0; long requestedSize = mgr.options.BlockSize; @@ -3565,7 +3574,7 @@ public void EventBlockDiscarded() }; var stream1 = mgr.GetStream("UnitTest", 13); var stream2 = mgr.GetStream("UnitTest", 13); - var buffer = GetRandomBuffer((int)requestedSize); + var buffer = this.GetRandomBuffer((int)requestedSize); stream1.Write(buffer); stream2.Write(buffer); stream1.Dispose(); @@ -3576,7 +3585,7 @@ public void EventBlockDiscarded() [Test] public void EventLargeBufferDiscardedEnoughFree() { - var mgr = GetMemoryManager(); + var mgr = this.GetMemoryManager(); mgr.options.MaximumLargePoolFreeBytes = mgr.options.LargeBufferMultiple; int raisedCount = 0; long requestedSize = mgr.options.LargeBufferMultiple; @@ -3591,7 +3600,7 @@ public void EventLargeBufferDiscardedEnoughFree() }; var stream1 = mgr.GetStream("UnitTest", 13); var stream2 = mgr.GetStream("UnitTest", 13); - var buffer = GetRandomBuffer((int)requestedSize); + var buffer = this.GetRandomBuffer((int)requestedSize); stream1.Write(buffer); stream2.Write(buffer); stream1.GetBuffer(); @@ -3604,7 +3613,7 @@ public void EventLargeBufferDiscardedEnoughFree() [Test] public void EventLargeBufferDiscardedTooLarge() { - var mgr = GetMemoryManager(); + var mgr = this.GetMemoryManager(); int raisedCount = 0; long requestedSize = mgr.options.MaximumBufferSize + 1; @@ -3619,7 +3628,7 @@ public void EventLargeBufferDiscardedTooLarge() }; var stream = mgr.GetStream("UnitTest", 13); - var buffer = GetRandomBuffer((int)requestedSize); + var buffer = this.GetRandomBuffer((int)requestedSize); stream.Write(buffer); stream.GetBuffer(); stream.Dispose(); @@ -3630,7 +3639,7 @@ public void EventLargeBufferDiscardedTooLarge() [Test] public void EventUsageReport() { - var mgr = GetMemoryManager(); + var mgr = this.GetMemoryManager(); int raisedCount = 0; long requestedSize = mgr.options.BlockSize; @@ -3645,7 +3654,7 @@ public void EventUsageReport() }; var stream = mgr.GetStream("UnitTest", 13); - var buffer = GetRandomBuffer((int)requestedSize); + var buffer = this.GetRandomBuffer((int)requestedSize); stream.Write(buffer); stream.GetBuffer(); stream.Dispose(); @@ -3664,7 +3673,7 @@ protected RecyclableMemoryStream GetDefaultStream() protected byte[] GetRandomBuffer(int length) { var buffer = new byte[length]; - random.NextBytes(buffer); + this.random.NextBytes(buffer); return buffer; } @@ -3706,7 +3715,7 @@ public void Issue176_PoolInUseSizeDoesNotDecrease() LargeBufferMultiple = 1 << 20, MaximumBufferSize = 8 * (1 << 20), MaximumSmallPoolFreeBytes = maximumFreeSmallPoolBytes, - MaximumLargePoolFreeBytes = maximumFreeLargePoolBytes + MaximumLargePoolFreeBytes = maximumFreeLargePoolBytes }); MemoryStream fillStream = mgr.GetStream("pool", requiredSize: 128000, asContiguousBuffer: true); @@ -3729,7 +3738,8 @@ public void Issue176_PoolInUseSizeDoesNotDecrease() #region ZeroOutBuffer [Test] - public void BlockZeroedBeforeReturn() { + public void BlockZeroedBeforeReturn() + { var memMgr = this.GetMemoryManager(); memMgr.ReturnBlock(this.GetRandomBuffer(memMgr.options.BlockSize), DefaultId, DefaultTag); Assert.That(memMgr.SmallBlocksFree, Is.EqualTo(1)); @@ -3738,23 +3748,27 @@ public void BlockZeroedBeforeReturn() { } [Test] - public void BlocksZeroedBeforeReturn() { + public void BlocksZeroedBeforeReturn() + { const int numBlocks = 5; var memMgr = this.GetMemoryManager(); var blocks = new List(numBlocks); - for (var blockId = 0; blockId < numBlocks; ++blockId) { + for (var blockId = 0; blockId < numBlocks; ++blockId) + { blocks.Add(this.GetRandomBuffer(memMgr.options.BlockSize)); } memMgr.ReturnBlocks(blocks, DefaultId, DefaultTag); Assert.That(memMgr.SmallBlocksFree, Is.EqualTo(blocks.Count)); - for (var blockId = 0; blockId < blocks.Count; ++blockId) { + for (var blockId = 0; blockId < blocks.Count; ++blockId) + { var block = memMgr.GetBlock(); Assert.That(block, this.ZeroOutBuffer ? Is.All.EqualTo(0) : Is.Not.All.EqualTo(0)); } } [Test] - public void LargeBufferZeroedBeforeReturn() { + public void LargeBufferZeroedBeforeReturn() + { var memMgr = this.GetMemoryManager(); memMgr.ReturnLargeBuffer(this.GetRandomBuffer(memMgr.options.LargeBufferMultiple), DefaultId, DefaultTag); Assert.That(memMgr.LargeBuffersFree, Is.EqualTo(1)); @@ -3767,10 +3781,7 @@ public void LargeBufferZeroedBeforeReturn() { protected abstract bool AggressiveBufferRelease { get; } protected virtual bool ZeroOutBuffer => false; - protected virtual bool UseExponentialLargeBuffer - { - get { return false; } - } + protected virtual bool UseExponentialLargeBuffer => false; protected static class RMSAssert { @@ -3861,10 +3872,7 @@ internal static void StreamContainsExactCopies(RecyclableMemoryStream stream, Re [TestFixture] public sealed class RecyclableMemoryStreamTestsWithPassiveBufferRelease : BaseRecyclableMemoryStreamTests { - protected override bool AggressiveBufferRelease - { - get { return false; } - } + protected override bool AggressiveBufferRelease => false; [Test] public void OldBuffersAreKeptInStreamUntilDispose() @@ -3906,18 +3914,12 @@ public void OldBuffersAreKeptInStreamUntilDispose() [TestFixture] public sealed class RecyclableMemoryStreamTestsWithAggressiveBufferRelease : BaseRecyclableMemoryStreamTests { - protected override bool AggressiveBufferRelease - { - get { return true; } - } + protected override bool AggressiveBufferRelease => true; } public abstract class BaseRecyclableMemoryStreamTestsUsingExponentialLargeBuffer : BaseRecyclableMemoryStreamTests { - protected override bool UseExponentialLargeBuffer - { - get { return true; } - } + protected override bool UseExponentialLargeBuffer => true; [Test] public override void RecyclableMemoryManagerUsingMultipleOrExponentialLargeBuffer() @@ -3962,14 +3964,15 @@ public override void AllMultiplesOrExponentialUpToMaxCanBePooled() for (var size = LargeBufferMultiple; size <= MaxBufferSize; size *= 2) { var memMgr = new RecyclableMemoryStreamManager( - new RecyclableMemoryStreamManager.Options { + new RecyclableMemoryStreamManager.Options + { BlockSize = BlockSize, LargeBufferMultiple = LargeBufferMultiple, MaximumBufferSize = MaxBufferSize, UseExponentialLargeBuffer = this.UseExponentialLargeBuffer, AggressiveBufferReturn = this.AggressiveBufferRelease }); - + var buffer = memMgr.GetLargeBuffer(size, DefaultId, DefaultTag); Assert.That(memMgr.LargePoolFreeSize, Is.EqualTo(0)); Assert.That(memMgr.LargePoolInUseSize, Is.EqualTo(size)); @@ -4059,10 +4062,7 @@ protected override void TestDroppingLargeBuffer(long maxFreeLargeBufferSize) [TestFixture] public sealed class RecyclableMemoryStreamTestsWithPassiveBufferReleaseUsingExponentialLargeBuffer : BaseRecyclableMemoryStreamTestsUsingExponentialLargeBuffer { - protected override bool AggressiveBufferRelease - { - get { return false; } - } + protected override bool AggressiveBufferRelease => false; [Test] public void OldBuffersAreKeptInStreamUntilDispose() @@ -4104,20 +4104,14 @@ public void OldBuffersAreKeptInStreamUntilDispose() [TestFixture] public sealed class RecyclableMemoryStreamTestsWithAggressiveBufferReleaseUsingExponentialLargeBuffer : BaseRecyclableMemoryStreamTestsUsingExponentialLargeBuffer { - protected override bool AggressiveBufferRelease - { - get { return true; } - } + protected override bool AggressiveBufferRelease => true; } [TestFixture] - public sealed class RecyclableMemoryStreamTestsWithZeroOutBuffer : BaseRecyclableMemoryStreamTests { + public sealed class RecyclableMemoryStreamTestsWithZeroOutBuffer : BaseRecyclableMemoryStreamTests + { protected override bool AggressiveBufferRelease => false; - protected override bool ZeroOutBuffer - { - get { return true; } - } - + protected override bool ZeroOutBuffer => true; } } diff --git a/UnitTests/UnitTests.csproj b/UnitTests/UnitTests.csproj index 551afd97..01186420 100644 --- a/UnitTests/UnitTests.csproj +++ b/UnitTests/UnitTests.csproj @@ -2,7 +2,7 @@ Microsoft.IO.RecyclableMemoryStream.UnitTests Microsoft.IO.UnitTests - net7.0 + net8.0 true @@ -17,7 +17,4 @@ - - - \ No newline at end of file diff --git a/src/Events.cs b/src/Events.cs index f2b37199..076685bf 100644 --- a/src/Events.cs +++ b/src/Events.cs @@ -80,7 +80,7 @@ public void MemoryStreamCreated(Guid guid, string? tag, long requestedSize, long { if (this.IsEnabled(EventLevel.Verbose, EventKeywords.None)) { - WriteEvent(1, guid, tag ?? string.Empty, requestedSize, actualSize); + this.WriteEvent(1, guid, tag ?? string.Empty, requestedSize, actualSize); } } @@ -97,7 +97,7 @@ public void MemoryStreamDisposed(Guid guid, string? tag, long lifetimeMs, string { if (this.IsEnabled(EventLevel.Verbose, EventKeywords.None)) { - WriteEvent(2, guid, tag ?? string.Empty, lifetimeMs, allocationStack ?? string.Empty, disposeStack ?? string.Empty); + this.WriteEvent(2, guid, tag ?? string.Empty, lifetimeMs, allocationStack ?? string.Empty, disposeStack ?? string.Empty); } } @@ -133,7 +133,7 @@ public void MemoryStreamFinalized(Guid guid, string? tag, string? allocationStac { if (this.IsEnabled()) { - WriteEvent(4, guid, tag ?? string.Empty, allocationStack ?? string.Empty); + this.WriteEvent(4, guid, tag ?? string.Empty, allocationStack ?? string.Empty); } } @@ -150,7 +150,7 @@ public void MemoryStreamToArray(Guid guid, string? tag, string? stack, long size { if (this.IsEnabled(EventLevel.Verbose, EventKeywords.None)) { - WriteEvent(5, guid, tag ?? string.Empty, stack ?? string.Empty, size); + this.WriteEvent(5, guid, tag ?? string.Empty, stack ?? string.Empty, size); } } @@ -165,7 +165,7 @@ public void MemoryStreamManagerInitialized(int blockSize, int largeBufferMultipl { if (this.IsEnabled()) { - WriteEvent(6, blockSize, largeBufferMultiple, maximumBufferSize); + this.WriteEvent(6, blockSize, largeBufferMultiple, maximumBufferSize); } } @@ -178,7 +178,7 @@ public void MemoryStreamNewBlockCreated(long smallPoolInUseBytes) { if (this.IsEnabled(EventLevel.Warning, EventKeywords.None)) { - WriteEvent(7, smallPoolInUseBytes); + this.WriteEvent(7, smallPoolInUseBytes); } } @@ -192,7 +192,7 @@ public void MemoryStreamNewLargeBufferCreated(long requiredSize, long largePoolI { if (this.IsEnabled(EventLevel.Warning, EventKeywords.None)) { - WriteEvent(8, requiredSize, largePoolInUseBytes); + this.WriteEvent(8, requiredSize, largePoolInUseBytes); } } @@ -209,7 +209,7 @@ public void MemoryStreamNonPooledLargeBufferCreated(Guid guid, string? tag, long { if (this.IsEnabled(EventLevel.Verbose, EventKeywords.None)) { - WriteEvent(9, guid, tag ?? string.Empty, requiredSize, allocationStack ?? string.Empty); + this.WriteEvent(9, guid, tag ?? string.Empty, requiredSize, allocationStack ?? string.Empty); } } @@ -232,7 +232,7 @@ public void MemoryStreamDiscardBuffer(Guid guid, string? tag, MemoryStreamBuffer { if (this.IsEnabled(EventLevel.Warning, EventKeywords.None)) { - WriteEvent(10, guid, tag ?? string.Empty, bufferType, reason, smallBlocksFree, smallPoolBytesFree, smallPoolBytesInUse, largeBlocksFree, largePoolBytesFree, largePoolBytesInUse); + this.WriteEvent(10, guid, tag ?? string.Empty, bufferType, reason, smallBlocksFree, smallPoolBytesFree, smallPoolBytesInUse, largeBlocksFree, largePoolBytesFree, largePoolBytesInUse); } } @@ -250,7 +250,7 @@ public void MemoryStreamOverCapacity(Guid guid, string? tag, long requestedCapac { if (this.IsEnabled()) { - WriteEvent(11, guid, tag ?? string.Empty, requestedCapacity, maxCapacity, allocationStack ?? string.Empty); + this.WriteEvent(11, guid, tag ?? string.Empty, requestedCapacity, maxCapacity, allocationStack ?? string.Empty); } } } diff --git a/src/Microsoft.IO.RecyclableMemoryStream.csproj b/src/Microsoft.IO.RecyclableMemoryStream.csproj index 46ef72e7..0b467cf5 100644 --- a/src/Microsoft.IO.RecyclableMemoryStream.csproj +++ b/src/Microsoft.IO.RecyclableMemoryStream.csproj @@ -20,8 +20,6 @@ git https://github.com/Microsoft/Microsoft.IO.RecyclableMemoryStream true - latest - enable true @@ -40,11 +38,7 @@ $(AllowedOutputExtensionsInPackageBuildOutputFolder);.pdb - - true - - - + true diff --git a/src/Properties/AssemblyInfo.cs b/src/Properties/AssemblyInfo.cs index fae2b24b..c72ca513 100644 --- a/src/Properties/AssemblyInfo.cs +++ b/src/Properties/AssemblyInfo.cs @@ -1,4 +1,3 @@ -using System; using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; diff --git a/src/RecyclableMemoryStream.cs b/src/RecyclableMemoryStream.cs index c350a367..42f16431 100644 --- a/src/RecyclableMemoryStream.cs +++ b/src/RecyclableMemoryStream.cs @@ -291,7 +291,7 @@ protected override void Dispose(bool disposing) this.disposed = true; var lifetime = TimeSpan.FromTicks((Stopwatch.GetTimestamp() - this.creationTimestamp) * TimeSpan.TicksPerSecond / Stopwatch.Frequency); - + if (this.memoryManager.options.GenerateCallStacks) { this.DisposeStack = Environment.StackTrace; @@ -384,7 +384,7 @@ public override int Capacity long size = (long)this.blocks.Count * this.memoryManager.options.BlockSize; if (size > int.MaxValue) { - throw new InvalidOperationException($"{nameof(Capacity)} is larger than int.MaxValue. Use {nameof(Capacity64)} instead."); + throw new InvalidOperationException($"{nameof(this.Capacity)} is larger than int.MaxValue. Use {nameof(this.Capacity64)} instead."); } return (int)size; } @@ -534,7 +534,7 @@ public override byte[] GetBuffer() /// public override void CopyTo(Stream destination, int bufferSize) { - WriteTo(destination, this.position, this.length - this.position); + this.WriteTo(destination, this.position, this.length - this.position); } #endif @@ -577,7 +577,7 @@ public override Task CopyToAsync(Stream destination, int bufferSize, Cancellatio { if (this.blocks.Count == 1) { - AssertLengthIsSmall(); + this.AssertLengthIsSmall(); return destination.WriteAsync(this.blocks[0], (int)startPos, (int)count, cancellationToken); } else @@ -587,7 +587,7 @@ public override Task CopyToAsync(Stream destination, int bufferSize, Cancellatio } else { - AssertLengthIsSmall(); + this.AssertLengthIsSmall(); return destination.WriteAsync(this.largeBuffer, (int)startPos, (int)count, cancellationToken); } } @@ -736,13 +736,13 @@ public ReadOnlySequence GetReadOnlySequence() if (this.largeBuffer != null) { - AssertLengthIsSmall(); + this.AssertLengthIsSmall(); return new ReadOnlySequence(this.largeBuffer, 0, (int)this.length); } if (this.blocks.Count == 1) { - AssertLengthIsSmall(); + this.AssertLengthIsSmall(); return new ReadOnlySequence(this.blocks[0], 0, (int)this.length); } @@ -759,12 +759,12 @@ public ReadOnlySequence GetReadOnlySequence() private sealed class BlockSegment : ReadOnlySequenceSegment { - public BlockSegment(Memory memory) => Memory = memory; + public BlockSegment(Memory memory) => this.Memory = memory; public BlockSegment Append(Memory memory) { - var nextSegment = new BlockSegment(memory) { RunningIndex = RunningIndex + Memory.Length }; - Next = nextSegment; + var nextSegment = new BlockSegment(memory) { RunningIndex = this.RunningIndex + this.Memory.Length }; + this.Next = nextSegment; return nextSegment; } } @@ -951,7 +951,7 @@ public override void Write(byte[] buffer, int offset, int count) } int blockSize = this.memoryManager.options.BlockSize; - long end = position + count; + long end = this.position + count; this.EnsureCapacity(end); @@ -1001,7 +1001,7 @@ public override void Write(ReadOnlySpan source) this.CheckDisposed(); int blockSize = this.memoryManager.options.BlockSize; - long end = position + source.Length; + long end = this.position + source.Length; this.EnsureCapacity(end); @@ -1057,7 +1057,7 @@ public override void WriteByte(byte value) { this.CheckDisposed(); - long end = position + 1; + long end = this.position + 1; if (this.largeBuffer == null) { @@ -1307,7 +1307,7 @@ public void WriteTo(byte[] buffer, long offset, long count, int targetOffset) if (this.largeBuffer == null) { - var blockAndOffset = GetBlockAndRelativeOffset(offset); + var blockAndOffset = this.GetBlockAndRelativeOffset(offset); long bytesRemaining = count; int currentBlock = blockAndOffset.Block; int currentOffset = blockAndOffset.Offset; @@ -1328,7 +1328,7 @@ public void WriteTo(byte[] buffer, long offset, long count, int targetOffset) } else { - AssertLengthIsSmall(); + this.AssertLengthIsSmall(); Buffer.BlockCopy(this.largeBuffer, (int)offset, buffer, targetOffset, (int)count); } } @@ -1499,6 +1499,6 @@ private void AssertLengthIsSmall() { Debug.Assert(this.length <= Int32.MaxValue, "this.length was assumed to be <= Int32.MaxValue, but was larger."); } -#endregion + #endregion } } diff --git a/src/RecyclableMemoryStreamManager.cs b/src/RecyclableMemoryStreamManager.cs index 078f5882..c378ea64 100644 --- a/src/RecyclableMemoryStreamManager.cs +++ b/src/RecyclableMemoryStreamManager.cs @@ -85,7 +85,7 @@ public partial class RecyclableMemoryStreamManager /// /// Settings for controlling the behavior of RecyclableMemoryStream /// - public Options Settings { get { return this.options; } } + public Options Settings => this.options; /// /// Number of bytes in small pool not currently in use. @@ -246,7 +246,7 @@ public class Options /// public Options() { - + } /// @@ -357,7 +357,7 @@ internal byte[] GetBlock() #else block = new byte[this.options.BlockSize]; #endif - ReportBlockCreated(); + this.ReportBlockCreated(); } else { @@ -426,7 +426,7 @@ internal byte[] GetLargeBuffer(long requiredSize, Guid id, string? tag) Interlocked.Add(ref this.largeBufferInUseSize[poolIndex], buffer.Length); if (createdNew) { - ReportLargeBufferCreated(id, tag, requiredSize, pooled: pooled, callStack); + this.ReportLargeBufferCreated(id, tag, requiredSize, pooled: pooled, callStack); } return buffer; @@ -460,7 +460,7 @@ private long RoundToLargeBufferSize(long requiredSize) private bool IsLargeBufferSize(int value) { return (value != 0) && (this.options.UseExponentialLargeBuffer - ? (value == RoundToLargeBufferSize(value)) + ? (value == this.RoundToLargeBufferSize(value)) : (value % this.options.LargeBufferMultiple) == 0); } @@ -514,7 +514,7 @@ internal void ReturnLargeBuffer(byte[] buffer, Guid id, string? tag) } else { - ReportBufferDiscarded(id, tag, Events.MemoryStreamBufferType.Large, Events.MemoryStreamDiscardReason.EnoughFree); + this.ReportBufferDiscarded(id, tag, Events.MemoryStreamBufferType.Large, Events.MemoryStreamDiscardReason.EnoughFree); } } else @@ -523,7 +523,7 @@ internal void ReturnLargeBuffer(byte[] buffer, Guid id, string? tag) // analysis. We have space in the InUse array for this. poolIndex = this.largeBufferInUseSize.Length - 1; - ReportBufferDiscarded(id, tag, Events.MemoryStreamBufferType.Large, Events.MemoryStreamDiscardReason.TooLarge); + this.ReportBufferDiscarded(id, tag, Events.MemoryStreamBufferType.Large, Events.MemoryStreamDiscardReason.TooLarge); } Interlocked.Add(ref this.largeBufferInUseSize[poolIndex], -buffer.Length); @@ -565,7 +565,7 @@ internal void ReturnBlocks(List blocks, Guid id, string? tag) } else { - ReportBufferDiscarded(id, tag, Events.MemoryStreamBufferType.Small, Events.MemoryStreamDiscardReason.EnoughFree); + this.ReportBufferDiscarded(id, tag, Events.MemoryStreamBufferType.Small, Events.MemoryStreamDiscardReason.EnoughFree); break; } } @@ -601,13 +601,15 @@ internal void ReturnBlock(byte[] block, Guid id, string? tag) } else { - ReportBufferDiscarded(id, tag, Events.MemoryStreamBufferType.Small, Events.MemoryStreamDiscardReason.EnoughFree); + this.ReportBufferDiscarded(id, tag, Events.MemoryStreamBufferType.Small, Events.MemoryStreamDiscardReason.EnoughFree); } } [MethodImpl(MethodImplOptions.AggressiveInlining)] - private void ZeroOutMemoryIfEnabled(byte[] buffer) { - if (this.options.ZeroOutBuffer) { + private void ZeroOutMemoryIfEnabled(byte[] buffer) + { + if (this.options.ZeroOutBuffer) + { #if NET6_0_OR_GREATER Array.Clear(buffer); #else @@ -658,7 +660,7 @@ internal void ReportStreamDisposed(Guid id, string? tag, TimeSpan lifetime, stri internal void ReportStreamDoubleDisposed(Guid id, string? tag, string? allocationStack, string? disposeStack1, string? disposeStack2) { Events.Writer.MemoryStreamDoubleDispose(id, tag, allocationStack, disposeStack1, disposeStack2); - this.StreamDoubleDisposed?.Invoke(this, new StreamDoubleDisposedEventArgs(id, tag, allocationStack,disposeStack1, disposeStack2)); + this.StreamDoubleDisposed?.Invoke(this, new StreamDoubleDisposedEventArgs(id, tag, allocationStack, disposeStack1, disposeStack2)); } internal void ReportStreamFinalized(Guid id, string? tag, string? allocationStack) @@ -789,7 +791,7 @@ public RecyclableMemoryStream GetStream(Guid id, string? tag, long requiredSize, /// A . public RecyclableMemoryStream GetStream(string? tag, long requiredSize, bool asContiguousBuffer) { - return GetStream(Guid.NewGuid(), tag, requiredSize, asContiguousBuffer); + return this.GetStream(Guid.NewGuid(), tag, requiredSize, asContiguousBuffer); } /// @@ -829,7 +831,7 @@ public RecyclableMemoryStream GetStream(Guid id, string? tag, byte[] buffer, int /// A . public RecyclableMemoryStream GetStream(byte[] buffer) { - return GetStream(null, buffer, 0, buffer.Length); + return this.GetStream(null, buffer, 0, buffer.Length); } /// @@ -844,7 +846,7 @@ public RecyclableMemoryStream GetStream(byte[] buffer) /// A . public RecyclableMemoryStream GetStream(string? tag, byte[] buffer, int offset, int count) { - return GetStream(Guid.NewGuid(), tag, buffer, offset, count); + return this.GetStream(Guid.NewGuid(), tag, buffer, offset, count); } /// @@ -882,7 +884,7 @@ public RecyclableMemoryStream GetStream(Guid id, string? tag, ReadOnlySpan /// A . public RecyclableMemoryStream GetStream(ReadOnlySpan buffer) { - return GetStream(null, buffer); + return this.GetStream(null, buffer); } /// @@ -895,7 +897,7 @@ public RecyclableMemoryStream GetStream(ReadOnlySpan buffer) /// A . public RecyclableMemoryStream GetStream(string? tag, ReadOnlySpan buffer) { - return GetStream(Guid.NewGuid(), tag, buffer); + return this.GetStream(Guid.NewGuid(), tag, buffer); } ///