mirror of
https://github.com/adamhathcock/sharpcompress.git
synced 2026-11-15 17:02:03 +00:00
Return pooled memory stream blocks when construction fails
This commit is contained in:
@@ -54,7 +54,15 @@ public sealed class PooledMemoryStream : MemoryStream
|
||||
_length = 0;
|
||||
_capacity = capacity;
|
||||
|
||||
EnsureSegmentedAllocated(capacity);
|
||||
try
|
||||
{
|
||||
EnsureSegmentedAllocated(capacity);
|
||||
}
|
||||
catch
|
||||
{
|
||||
ReturnPooledBuffers();
|
||||
throw;
|
||||
}
|
||||
}
|
||||
|
||||
public override bool CanRead => _isOpen;
|
||||
@@ -565,7 +573,17 @@ public sealed class PooledMemoryStream : MemoryStream
|
||||
|
||||
while (_blocks.Count < requiredBlocks)
|
||||
{
|
||||
_blocks.Add(_arrayPool.Rent(_blockSize));
|
||||
var block = _arrayPool.Rent(_blockSize);
|
||||
try
|
||||
{
|
||||
_blocks.Add(block);
|
||||
}
|
||||
catch
|
||||
{
|
||||
// A failed list expansion must not lose the rental either.
|
||||
_arrayPool.Return(block);
|
||||
throw;
|
||||
}
|
||||
}
|
||||
|
||||
while (_blocks.Count > requiredBlocks)
|
||||
|
||||
@@ -8,6 +8,31 @@ namespace SharpCompress.Test.Streams;
|
||||
|
||||
public class PooledMemoryStreamTests
|
||||
{
|
||||
[Fact]
|
||||
public void FailedConstructorReturnsPreviouslyRentedBlocks()
|
||||
{
|
||||
var pool = new FailingArrayPool();
|
||||
Assert.Throws<IOException>(() => new PooledMemoryStream(16, 8, pool));
|
||||
Assert.Equal(1, pool.ReturnCount);
|
||||
}
|
||||
|
||||
private sealed class FailingArrayPool : ArrayPool<byte>
|
||||
{
|
||||
private int rentCount;
|
||||
public int ReturnCount { get; private set; }
|
||||
|
||||
public override byte[] Rent(int minimumLength)
|
||||
{
|
||||
if (++rentCount == 2)
|
||||
{
|
||||
throw new IOException("Injected rental failure");
|
||||
}
|
||||
return new byte[minimumLength];
|
||||
}
|
||||
|
||||
public override void Return(byte[] array, bool clearArray = false) => ReturnCount++;
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void GrowsUsingFixedSizeBlocks()
|
||||
{
|
||||
|
||||
Reference in New Issue
Block a user