// The .NET Foundation licenses this file to you under the MIT license.
using System.Buffers;
-using System.Collections.Generic;
using System.Diagnostics;
using System.Runtime.CompilerServices;
using System.Threading;
// If we're using the default pool then mark it as null since we're just going to use the
// array pool under the covers
_pool = options.Pool == MemoryPool<byte>.Shared ? null : options.Pool;
- _maxPooledBufferSize = _pool?.MaxBufferSize ?? 0;
+ _maxPooledBufferSize = _pool?.MaxBufferSize ?? -1;
_minimumSegmentSize = options.MinimumSegmentSize;
_pauseWriterThreshold = options.PauseWriterThreshold;
_resumeWriterThreshold = options.ResumeWriterThreshold;
private BufferSegment AllocateSegment(int sizeHint)
{
+ Debug.Assert(sizeHint >= 0);
BufferSegment newSegment = CreateSegmentUnsynchronized();
int maxSize = _maxPooledBufferSize;
- if (_pool != null && sizeHint <= maxSize)
+ if (sizeHint <= maxSize)
{
- // Use the specified pool as it fits
- newSegment.SetOwnedMemory(_pool.Rent(GetSegmentSize(sizeHint, maxSize)));
+ // Use the specified pool as it fits. Specified pool is not null as maxSize == -1 if _pool is null.
+ newSegment.SetOwnedMemory(_pool!.Rent(GetSegmentSize(sizeHint, maxSize)));
}
else
{
private int _bytesBuffered;
private readonly MemoryPool<byte>? _pool;
+ private readonly int _maxPooledBufferSize;
private CancellationTokenSource? _internalTokenSource;
private bool _isCompleted;
_minimumBufferSize = options.MinimumBufferSize;
_pool = options.Pool == MemoryPool<byte>.Shared ? null : options.Pool;
+ _maxPooledBufferSize = _pool?.MaxBufferSize ?? -1;
_bufferSegmentPool = new BufferSegmentStack(InitialSegmentPoolSize);
_leaveOpen = options.LeaveOpen;
}
private BufferSegment AllocateSegment(int sizeHint)
{
+ Debug.Assert(sizeHint >= 0);
BufferSegment newSegment = CreateSegmentUnsynchronized();
- if (_pool is null || sizeHint > _pool.MaxBufferSize)
+ int maxSize = _maxPooledBufferSize;
+ if (sizeHint <= maxSize)
{
- // Use the array pool
- int sizeToRequest = GetSegmentSize(sizeHint);
- newSegment.SetOwnedMemory(ArrayPool<byte>.Shared.Rent(sizeToRequest));
+ // Use the specified pool as it fits. Specified pool is not null as maxSize == -1 if _pool is null.
+ newSegment.SetOwnedMemory(_pool!.Rent(GetSegmentSize(sizeHint, maxSize)));
}
else
{
- // Use the specified pool as it fits
- newSegment.SetOwnedMemory(_pool.Rent(GetSegmentSize(sizeHint, _pool.MaxBufferSize)));
+ // Use the array pool
+ int sizeToRequest = GetSegmentSize(sizeHint);
+ newSegment.SetOwnedMemory(ArrayPool<byte>.Shared.Rent(sizeToRequest));
}
_tailMemory = newSegment.AvailableMemory;