123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144 |
- #if NETCORE
- using System;
- namespace SharpCompress.Buffers
- {
- internal sealed partial class DefaultArrayPool<T> : ArrayPool<T>
- {
-
- private const int DefaultMaxArrayLength = 1024 * 1024;
-
- private const int DefaultMaxNumberOfArraysPerBucket = 50;
-
- private static T[] s_emptyArray;
- private readonly Bucket[] _buckets;
- internal DefaultArrayPool() : this(DefaultMaxArrayLength, DefaultMaxNumberOfArraysPerBucket)
- {
- }
- internal DefaultArrayPool(int maxArrayLength, int maxArraysPerBucket)
- {
- if (maxArrayLength <= 0)
- {
- throw new ArgumentOutOfRangeException(nameof(maxArrayLength));
- }
- if (maxArraysPerBucket <= 0)
- {
- throw new ArgumentOutOfRangeException(nameof(maxArraysPerBucket));
- }
-
-
- const int MinimumArrayLength = 0x10, MaximumArrayLength = 0x40000000;
- if (maxArrayLength > MaximumArrayLength)
- {
- maxArrayLength = MaximumArrayLength;
- }
- else if (maxArrayLength < MinimumArrayLength)
- {
- maxArrayLength = MinimumArrayLength;
- }
-
- int poolId = Id;
- int maxBuckets = Utilities.SelectBucketIndex(maxArrayLength);
- var buckets = new Bucket[maxBuckets + 1];
- for (int i = 0; i < buckets.Length; i++)
- {
- buckets[i] = new Bucket(Utilities.GetMaxSizeForBucket(i), maxArraysPerBucket, poolId);
- }
- _buckets = buckets;
- }
-
- private int Id => GetHashCode();
- public override T[] Rent(int minimumLength)
- {
-
-
-
- if (minimumLength < 0)
- {
- throw new ArgumentOutOfRangeException(nameof(minimumLength));
- }
- else if (minimumLength == 0)
- {
-
-
- return s_emptyArray ?? (s_emptyArray = new T[0]);
- }
- T[] buffer = null;
- int index = Utilities.SelectBucketIndex(minimumLength);
- if (index < _buckets.Length)
- {
-
-
- const int MaxBucketsToTry = 2;
- int i = index;
- do
- {
-
- buffer = _buckets[i].Rent();
- if (buffer != null)
- {
- return buffer;
- }
- }
- while (++i < _buckets.Length && i != index + MaxBucketsToTry);
-
-
- buffer = new T[_buckets[index]._bufferLength];
- }
- else
- {
-
-
- buffer = new T[minimumLength];
- }
- return buffer;
- }
- public override void Return(T[] array, bool clearArray = false)
- {
- if (array == null)
- {
- throw new ArgumentNullException(nameof(array));
- }
- else if (array.Length == 0)
- {
-
-
- return;
- }
-
- int bucket = Utilities.SelectBucketIndex(array.Length);
-
- if (bucket < _buckets.Length)
- {
-
- if (clearArray)
- {
- Array.Clear(array, 0, array.Length);
- }
-
-
-
- _buckets[bucket].Return(array);
- }
- }
- }
- }
- #endif
|