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
13 changes: 13 additions & 0 deletions src/ImageSharp/IO/FixedCapacityPooledMemoryStream.cs
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
// Copyright (c) Six Labors.
// Licensed under the Apache License, Version 2.0.

using System;
using System.Buffers;
using System.IO;
using SixLabors.ImageSharp.Memory;
Expand Down Expand Up @@ -29,6 +30,18 @@ private FixedCapacityPooledMemoryStream(IManagedByteBuffer buffer)
/// <inheritdoc/>
public override long Length { get; }

/// <inheritdoc/>
public override bool TryGetBuffer(out ArraySegment<byte> buffer)
{
if (this.isDisposed)
{
throw new ObjectDisposedException(this.GetType().Name);
}

buffer = new ArraySegment<byte>(this.buffer.Array, 0, this.buffer.Length());
return true;
}

/// <inheritdoc/>
protected override void Dispose(bool disposing)
{
Expand Down
42 changes: 42 additions & 0 deletions tests/ImageSharp.Tests/IO/FixedCapacityPooledMemoryStreamTests.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,42 @@
// Copyright (c) Six Labors.
// Licensed under the Apache License, Version 2.0.

using System;
using System.IO;
using System.Linq;
using SixLabors.ImageSharp.Memory;
using SixLabors.ImageSharp.Tests.Memory;
using Xunit;

namespace SixLabors.ImageSharp.Tests.IO
{
public class FixedCapacityPooledMemoryStreamTests
{
private readonly TestMemoryAllocator memoryAllocator = new TestMemoryAllocator();

[Theory]
[InlineData(1)]
[InlineData(512)]
public void RentsManagedBuffer(int length)
{
MemoryStream ms = this.memoryAllocator.AllocateFixedCapacityMemoryStream(length);
Assert.Equal(length, this.memoryAllocator.AllocationLog.Single().Length);
ms.Dispose();
Assert.Equal(1, this.memoryAllocator.ReturnLog.Count);
}

[Theory]
[InlineData(42)]
[InlineData(2999)]
public void UsesRentedBuffer(int length)
{
using MemoryStream ms = this.memoryAllocator.AllocateFixedCapacityMemoryStream(length);
ms.TryGetBuffer(out ArraySegment<byte> buffer);
byte[] array = buffer.Array;
Assert.Equal(array.GetHashCode(), this.memoryAllocator.AllocationLog.Single().HashCodeOfBuffer);

ms.Write(new byte[] { 123 });
Assert.Equal(123, array[0]);
}
}
}