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
38 changes: 38 additions & 0 deletions PowerKit.Tests/ArrayPoolExtensionsTests.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,38 @@
using System;
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>.Shared;
var owner = pool.RentOwner(16);

// Act
owner.Dispose();
var act = () => owner.Memory;

// Assert
act.Should().Throw<ObjectDisposedException>();
}
}
44 changes: 44 additions & 0 deletions PowerKit/Extensions/ArrayPoolExtensions.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,44 @@
using System;
using System.Buffers;
using System.Threading;

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 int _disposed;

public Memory<T> Memory
{
get
{
ObjectDisposedException.ThrowIf(_disposed != 0, this);
return buffer.AsMemory(0, minimumLength);
}
}

public void Dispose()
{
if (Interlocked.Exchange(ref _disposed, 1) != 0)
{
return;
}

pool.Return(buffer);
}
}