Skip to content

Commit

Permalink
Code cleanup (#325)
Browse files Browse the repository at this point in the history
* Code cleanup

* spelling

* codeql format

* change conventions

* spaces

* Add this

* events
  • Loading branch information
sungam3r committed Feb 26, 2024
1 parent 5e7b845 commit 9362885
Show file tree
Hide file tree
Showing 19 changed files with 285 additions and 286 deletions.
8 changes: 8 additions & 0 deletions .editorconfig
Original file line number Diff line number Diff line change
Expand Up @@ -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
4 changes: 2 additions & 2 deletions .github/workflows/benchmark.yml
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
4 changes: 1 addition & 3 deletions BenchmarkTests/BenchmarkTests.csproj
Original file line number Diff line number Diff line change
Expand Up @@ -2,9 +2,7 @@

<PropertyGroup>
<OutputType>Exe</OutputType>
<TargetFramework>net7.0</TargetFramework>
<ImplicitUsings>enable</ImplicitUsings>
<Nullable>enable</Nullable>
<TargetFramework>net8.0</TargetFramework>
</PropertyGroup>

<ItemGroup>
Expand Down
4 changes: 2 additions & 2 deletions BenchmarkTests/Program.cs
Original file line number Diff line number Diff line change
Expand Up @@ -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);
45 changes: 23 additions & 22 deletions BenchmarkTests/WriteTests.cs
Original file line number Diff line number Diff line change
@@ -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());
}
}
}
}
22 changes: 11 additions & 11 deletions BenchmarkTests/combine-bechmarks.csx
Original file line number Diff line number Diff line change
Expand Up @@ -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()))!;
Expand All @@ -34,12 +34,12 @@ combinedReport["Title"] = $"{resultsFile}{title.GetValue<string>()[^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());
4 changes: 2 additions & 2 deletions CHANGES.md
Original file line number Diff line number Diff line change
Expand Up @@ -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

Expand Down
9 changes: 9 additions & 0 deletions Directory.Build.props
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
<Project>

<PropertyGroup>
<LangVersion>latest</LangVersion>
<Nullable>enable</Nullable>
<ImplicitUsings>enable</ImplicitUsings>
</PropertyGroup>

</Project>
3 changes: 0 additions & 3 deletions Examples/Examples.csproj
Original file line number Diff line number Diff line change
@@ -1,10 +1,7 @@
<Project Sdk="Microsoft.NET.Sdk">

<PropertyGroup>
<OutputType>Library</OutputType>
<TargetFramework>net8.0</TargetFramework>
<ImplicitUsings>enable</ImplicitUsings>
<Nullable>enable</Nullable>
<RootNamespace>Microsoft.IO.RecyclableMemoryStream.Examples</RootNamespace>
</PropertyGroup>

Expand Down
26 changes: 12 additions & 14 deletions Examples/Readme.cs
Original file line number Diff line number Diff line change
@@ -1,12 +1,11 @@
using Microsoft.VisualBasic;
using System.Numerics;
using System.Security.Cryptography;

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)
{
Expand All @@ -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
}
Expand Down Expand Up @@ -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<byte> buffer = stream.GetSpan(bigInt.GetByteCount());
bigInt.TryWriteBytes(buffer, out int bytesWritten);
Expand All @@ -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())
Expand All @@ -105,5 +104,4 @@ internal void Example()
//END EXAMPLE
}
}

}
2 changes: 2 additions & 0 deletions Microsoft.IO.RecyclableMemoryStream.sln
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand All @@ -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
Expand Down
16 changes: 8 additions & 8 deletions UnitTests/RecyclableMemoryStreamEventListener.cs
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
// The MIT License (MIT)
// The MIT License (MIT)
//
// Copyright (c) 2015-2016 Microsoft
//
Expand Down Expand Up @@ -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;
}
}
}
}
}
Loading

0 comments on commit 9362885

Please sign in to comment.