123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111 |
- #if NETCORE
- using System;
- using System.Diagnostics;
- using System.Threading;
- namespace SharpCompress.Buffers
- {
- internal sealed partial class DefaultArrayPool<T> : ArrayPool<T>
- {
-
- private sealed class Bucket
- {
- internal readonly int _bufferLength;
- private readonly T[][] _buffers;
- private readonly int _poolId;
- private SpinLock _lock;
- private int _index;
-
-
-
- internal Bucket(int bufferLength, int numberOfBuffers, int poolId)
- {
- _lock = new SpinLock(Debugger.IsAttached);
- _buffers = new T[numberOfBuffers][];
- _bufferLength = bufferLength;
- _poolId = poolId;
- }
-
- internal int Id => GetHashCode();
-
- internal T[] Rent()
- {
- T[][] buffers = _buffers;
- T[] buffer = null;
-
-
-
-
- bool lockTaken = false, allocateBuffer = false;
- try
- {
- _lock.Enter(ref lockTaken);
- if (_index < buffers.Length)
- {
- buffer = buffers[_index];
- buffers[_index++] = null;
- allocateBuffer = buffer == null;
- }
- }
- finally
- {
- if (lockTaken) _lock.Exit(false);
- }
-
-
-
- if (allocateBuffer)
- {
- buffer = new T[_bufferLength];
- }
- return buffer;
- }
-
-
-
-
-
- internal void Return(T[] array)
- {
-
- if (array.Length != _bufferLength)
- {
- throw new ArgumentException("Buffer not from pool", nameof(array));
- }
-
-
-
-
- bool lockTaken = false;
- try
- {
- _lock.Enter(ref lockTaken);
- if (_index != 0)
- {
- _buffers[--_index] = array;
- }
- }
- finally
- {
- if (lockTaken) _lock.Exit(false);
- }
- }
- }
- }
- }
- #endif
|