Skip to content
Merged
Show file tree
Hide file tree
Changes from 3 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
39 changes: 39 additions & 0 deletions PowerKit.Tests/ArrayPoolExtensionsTests.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,39 @@
using System.Buffers;
using FluentAssertions;
using PowerKit.Extensions;
using Xunit;

namespace PowerKit.Tests;

public class ArrayPoolExtensionsTests
{
[Fact]
public void RentOwner_Test()
{
// Arrange
var pool = ArrayPool<byte>.Shared;

// Act
using var owner = pool.RentOwner(16);

// Assert
owner.Memory.Length.Should().Be(16);
}

[Fact]
public void RentOwner_Dispose_Test()
{
// Arrange
var pool = ArrayPool<byte>.Create(16, 1);

// Act & assert
using (var owner = pool.RentOwner(16))
{
owner.Memory.Length.Should().Be(16);
}

// Should be able to rent again after the previous owner was disposed
using var owner2 = pool.RentOwner(16);
owner2.Memory.Length.Should().Be(16);
}
Comment thread
Tyrrrz marked this conversation as resolved.
Outdated
}
37 changes: 37 additions & 0 deletions PowerKit/Extensions/ArrayPoolExtensions.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,37 @@
using System;
using System.Buffers;

namespace PowerKit.Extensions;

internal static class ArrayPoolExtensions
{
extension<T>(ArrayPool<T> pool)
{
/// <summary>
/// Rents a buffer of at least <paramref name="minimumLength" /> elements from the pool
/// and wraps it in an <see cref="IMemoryOwner{T}" /> that returns the buffer to the pool
/// when disposed.
/// </summary>
public IMemoryOwner<T> RentOwner(int minimumLength = 1) =>
new ArrayPoolMemoryOwner<T>(pool, pool.Rent(minimumLength), minimumLength);
}
}

file sealed class ArrayPoolMemoryOwner<T>(ArrayPool<T> pool, T[] buffer, int minimumLength)
: IMemoryOwner<T>
{
private bool _disposed;

public Memory<T> Memory { get; } = buffer.AsMemory(0, minimumLength);

Comment thread
Tyrrrz marked this conversation as resolved.
Outdated
public void Dispose()
{
if (_disposed)
{
return;
}

_disposed = true;
pool.Return(buffer);
}
Comment thread
Tyrrrz marked this conversation as resolved.
Outdated
}