Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion csharp-advanced-topics/MemoryInCSharp/App/App.csproj
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@

<PropertyGroup>
<OutputType>Exe</OutputType>
<TargetFramework>net8.0</TargetFramework>
<TargetFramework>net11.0</TargetFramework>
<ImplicitUsings>enable</ImplicitUsings>
<Nullable>enable</Nullable>
</PropertyGroup>
Expand Down
70 changes: 29 additions & 41 deletions csharp-advanced-topics/MemoryInCSharp/App/MemoryUseCases.cs
Original file line number Diff line number Diff line change
Expand Up @@ -4,102 +4,90 @@ namespace App;

public static class MemoryUseCases
{
/// <summary>
/// Memory can be allocated on both the stack and the heap, unlike Span which is restricted to the stack due to being a ref struct
/// </summary>
public static void WorksWithBothStackAndHeap()
public static void CreateMemoryFromArray()
{
var numbers = new int[] { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };
var memory = new Memory<int>(numbers);

Console.WriteLine(memory.Length);
}

public static void StackDataNeedsAnArray()
{
// Allocating Memory<T> on the stack
Span<int> stackSpan = stackalloc int[3];
stackSpan[0] = 1;
stackSpan[1] = 2;
stackSpan[2] = 3;

// Creating Memory<T> from stack Span<T>
var stackMemory = stackSpan.ToArray().AsMemory();

// Allocating Memory<T> on the heap
var heapArray = new[] { 4, 5, 6 };
var heapMemory = heapArray.AsMemory();

// Displaying contents of stack and heap Memory<T>
Console.WriteLine("Stack Memory:");
Console.WriteLine("Copied from the stack:");
foreach (var item in stackMemory.Span)
{
Console.WriteLine(item);
}

Console.WriteLine("\nHeap Memory:");
Console.WriteLine("\nHeap array:");
foreach (var item in heapMemory.Span)
{
Console.WriteLine(item);
}
}

/// <summary>
/// String.AsMemory extension method.
/// </summary>

public static async Task ProcessMemoryAsync(Memory<int> memory)
{
await Task.Delay(1000);
for (var index = 0; index < memory.Span.Length; index++)
{
var item = memory.Span[index];

Console.WriteLine(item);
}
}

public static void StringAsMemoryExtensionMethod()
{
const string str = "Hello Code Maze";
var memory = str.AsMemory();

// Slicing also works with the Memory<char>
var slice = memory.Slice(6, 8); // "Code Maze"
var slice = memory.Slice(6, 9);

// Displaying the slice
Console.WriteLine(slice.ToString());
Console.WriteLine(slice.ToString()); // "Code Maze"
}

/// <summary>
/// Ownership models, including the connection between Memory and the IMemoryOwner interface.
/// </summary>
public static void UseMemoryOwner()
{
// Rent a block of memory from the shared pool
using IMemoryOwner<int> owner = MemoryPool<int>.Shared.Rent(10);
// Get a Memory<T> that represents the rented block of memory
var memory = owner.Memory;
Console.WriteLine($"Rented {owner.Memory.Length} elements");
var memory = owner.Memory.Slice(0, 10);

// Use the Memory<T>
for (var i = 0; i < memory.Length; i++)
{
memory.Span[i] = i;
}

// Display the contents of the Memory<T>
foreach (var item in memory.Span)
{
Console.WriteLine(item);
}
}

/// <summary>
/// Practical usage scenarios such as utilizing MemoryPool, IMemoryOwner, and the IMemoryOwner.Memory property.
/// </summary>
/// <param name="filePath"></param>

public static async Task ProcessFileAsync(string filePath)
{
// Rent a block of memory from the shared pool
using var owner = MemoryPool<byte>.Shared.Rent(4096);

// Get a Memory<T> that represents the rented block of memory
Memory<byte> buffer = owner.Memory.Slice(0, 4096);

await using FileStream stream = File.OpenRead(filePath);

// Read data from the file into the rented block of memory
int bytesRead;
while ((bytesRead = await stream.ReadAsync(buffer)) > 0)
{
// Process the data in the buffer
var data = buffer.Slice(0, bytesRead);
for (var index = 0; index < data.Span.Length; index++)
{
var b = data.Span[index];
// Convert byte to char and display it
Console.Write((char)b);
}

Console.WriteLine();
}
}
Expand Down
20 changes: 6 additions & 14 deletions csharp-advanced-topics/MemoryInCSharp/App/Program.cs
Original file line number Diff line number Diff line change
@@ -1,16 +1,8 @@
using App;

public static class Program
{
public static async Task Main(string[] args)
{
// Call WorksWithBothStackAndHeap method
MemoryUseCases.WorksWithBothStackAndHeap();
// Call StringAsMemoryExtensionMethod method
MemoryUseCases.StringAsMemoryExtensionMethod();
// Call UseMemoryOwner method
MemoryUseCases.UseMemoryOwner();
// Call ProcessFileAsync method
await MemoryUseCases.ProcessFileAsync("./File.txt");
}
}
MemoryUseCases.CreateMemoryFromArray();
MemoryUseCases.StackDataNeedsAnArray();
await MemoryUseCases.ProcessMemoryAsync(new[] { 1, 2, 3 });
MemoryUseCases.StringAsMemoryExtensionMethod();
MemoryUseCases.UseMemoryOwner();
await MemoryUseCases.ProcessFileAsync("./File.txt");
40 changes: 28 additions & 12 deletions csharp-advanced-topics/MemoryInCSharp/Tests/MemoryUseCasesTest.cs
Original file line number Diff line number Diff line change
Expand Up @@ -14,38 +14,54 @@ public MemoryUseCasesTest()
}

[Fact]
public void WhenWorksWithBothStackAndHeapCalled_ThenShouldWriteToConsole()
public void WhenCreateMemoryFromArrayCalled_ThenShouldWriteTheLength()
{
MemoryUseCases.WorksWithBothStackAndHeap();

_mockTextWriter.Verify(tw => tw.WriteLine(It.IsAny<string>()), Times.AtLeastOnce);
MemoryUseCases.CreateMemoryFromArray();

_mockTextWriter.Verify(tw => tw.WriteLine(10), Times.Once);
}

[Fact]
public void WhenStackDataNeedsAnArrayCalled_ThenShouldWriteSixValues()
{
MemoryUseCases.StackDataNeedsAnArray();

_mockTextWriter.Verify(tw => tw.WriteLine(It.IsAny<int>()), Times.Exactly(6));
}

[Fact]
public void WhenStringAsMemoryExtensionMethodCalled_ThenShouldWriteToConsole()
public async Task WhenProcessMemoryAsyncCalled_ThenShouldWriteEveryValue()
{
await MemoryUseCases.ProcessMemoryAsync(new[] { 1, 2, 3 });

_mockTextWriter.Verify(tw => tw.WriteLine(It.IsAny<int>()), Times.Exactly(3));
}

[Fact]
public void WhenStringAsMemoryExtensionMethodCalled_ThenShouldWriteCodeMaze()
{
MemoryUseCases.StringAsMemoryExtensionMethod();
_mockTextWriter.Verify(tw => tw.WriteLine(It.IsAny<string>()), Times.AtLeastOnce);

_mockTextWriter.Verify(tw => tw.WriteLine("Code Maze"), Times.Once);
}

[Fact]
public void WhenUseMemoryOwnerCalled_ThenShouldWriteToConsole()
public void WhenUseMemoryOwnerCalled_ThenShouldWriteOnlyTheRequestedTenValues()
{
MemoryUseCases.UseMemoryOwner();

_mockTextWriter.Verify(tw => tw.WriteLine(It.IsAny<int>()), Times.AtLeastOnce);
_mockTextWriter.Verify(tw => tw.WriteLine(It.IsAny<int>()), Times.Exactly(10));
}

[Fact]
public async Task WhenProcessFileAsyncCalled_ThenShouldWriteToConsole()
public async Task WhenProcessFileAsyncCalled_ThenShouldWriteEveryCharacter()
{
var filePath = "test.txt";
var fileContent = "Hello World";
await File.WriteAllTextAsync(filePath, fileContent);
await MemoryUseCases.ProcessFileAsync(filePath);

_mockTextWriter.Verify(tw => tw.Write(It.IsAny<char>()), Times.AtLeastOnce);
_mockTextWriter.Verify(tw => tw.Write(It.IsAny<char>()), Times.Exactly(fileContent.Length));
File.Delete(filePath);
}
}
}
12 changes: 6 additions & 6 deletions csharp-advanced-topics/MemoryInCSharp/Tests/Tests.csproj
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
<Project Sdk="Microsoft.NET.Sdk">

<PropertyGroup>
<TargetFramework>net8.0</TargetFramework>
<TargetFramework>net11.0</TargetFramework>
<ImplicitUsings>enable</ImplicitUsings>
<Nullable>enable</Nullable>

Expand All @@ -10,11 +10,11 @@
</PropertyGroup>

<ItemGroup>
<PackageReference Include="coverlet.collector" Version="6.0.0"/>
<PackageReference Include="Microsoft.NET.Test.Sdk" Version="17.8.0"/>
<PackageReference Include="Moq" Version="4.20.70" />
<PackageReference Include="xunit" Version="2.5.3"/>
<PackageReference Include="xunit.runner.visualstudio" Version="2.5.3"/>
<PackageReference Include="coverlet.collector" Version="10.1.0"/>
<PackageReference Include="Microsoft.NET.Test.Sdk" Version="18.12.0"/>
<PackageReference Include="Moq" Version="4.21.0" />
<PackageReference Include="xunit" Version="2.9.3"/>
<PackageReference Include="xunit.runner.visualstudio" Version="4.0.1"/>
</ItemGroup>

<ItemGroup>
Expand Down
Loading