Skip to content

Commit 2fbb450

Browse files
Merge pull request #1225 from SixLabors/af/FixedCapacityPooledMemoryStream-use-allocator
Tests for FixedCapacityPooledMemoryStream
2 parents bbf3233 + be64e51 commit 2fbb450

File tree

2 files changed

+55
-0
lines changed

2 files changed

+55
-0
lines changed

src/ImageSharp/IO/FixedCapacityPooledMemoryStream.cs

Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,7 @@
11
// Copyright (c) Six Labors.
22
// Licensed under the Apache License, Version 2.0.
33

4+
using System;
45
using System.Buffers;
56
using System.IO;
67
using SixLabors.ImageSharp.Memory;
@@ -29,6 +30,18 @@ private FixedCapacityPooledMemoryStream(IManagedByteBuffer buffer)
2930
/// <inheritdoc/>
3031
public override long Length { get; }
3132

33+
/// <inheritdoc/>
34+
public override bool TryGetBuffer(out ArraySegment<byte> buffer)
35+
{
36+
if (this.isDisposed)
37+
{
38+
throw new ObjectDisposedException(this.GetType().Name);
39+
}
40+
41+
buffer = new ArraySegment<byte>(this.buffer.Array, 0, this.buffer.Length());
42+
return true;
43+
}
44+
3245
/// <inheritdoc/>
3346
protected override void Dispose(bool disposing)
3447
{
Lines changed: 42 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,42 @@
1+
// Copyright (c) Six Labors.
2+
// Licensed under the Apache License, Version 2.0.
3+
4+
using System;
5+
using System.IO;
6+
using System.Linq;
7+
using SixLabors.ImageSharp.Memory;
8+
using SixLabors.ImageSharp.Tests.Memory;
9+
using Xunit;
10+
11+
namespace SixLabors.ImageSharp.Tests.IO
12+
{
13+
public class FixedCapacityPooledMemoryStreamTests
14+
{
15+
private readonly TestMemoryAllocator memoryAllocator = new TestMemoryAllocator();
16+
17+
[Theory]
18+
[InlineData(1)]
19+
[InlineData(512)]
20+
public void RentsManagedBuffer(int length)
21+
{
22+
MemoryStream ms = this.memoryAllocator.AllocateFixedCapacityMemoryStream(length);
23+
Assert.Equal(length, this.memoryAllocator.AllocationLog.Single().Length);
24+
ms.Dispose();
25+
Assert.Equal(1, this.memoryAllocator.ReturnLog.Count);
26+
}
27+
28+
[Theory]
29+
[InlineData(42)]
30+
[InlineData(2999)]
31+
public void UsesRentedBuffer(int length)
32+
{
33+
using MemoryStream ms = this.memoryAllocator.AllocateFixedCapacityMemoryStream(length);
34+
ms.TryGetBuffer(out ArraySegment<byte> buffer);
35+
byte[] array = buffer.Array;
36+
Assert.Equal(array.GetHashCode(), this.memoryAllocator.AllocationLog.Single().HashCodeOfBuffer);
37+
38+
ms.Write(new byte[] { 123 });
39+
Assert.Equal(123, array[0]);
40+
}
41+
}
42+
}

0 commit comments

Comments
 (0)