|
| 1 | +using System; |
| 2 | +using System.Buffers; |
| 3 | + |
| 4 | +namespace Open.Database.Extensions |
| 5 | +{ |
| 6 | + static class LocalArrayPool<T> |
| 7 | + { |
| 8 | + public const int MaxArrayLength = 1024 * 1024; |
| 9 | + static LocalArrayPool() |
| 10 | + { |
| 11 | + Instance = ArrayPool<T>.Create(MaxArrayLength, 4); |
| 12 | + } |
| 13 | + public static readonly ArrayPool<T> Instance; |
| 14 | + |
| 15 | + public static void Rent( |
| 16 | + int minimumLength, |
| 17 | + Action<Memory<T>> handler) |
| 18 | + { |
| 19 | + if (minimumLength < 0) |
| 20 | + throw new ArgumentOutOfRangeException(nameof(minimumLength), minimumLength, "Must be at least 0."); |
| 21 | + |
| 22 | + if (minimumLength > MaxArrayLength) |
| 23 | + { |
| 24 | + handler(new T[minimumLength]); |
| 25 | + } |
| 26 | + else |
| 27 | + { |
| 28 | + var array = Instance.Rent(minimumLength); |
| 29 | + try |
| 30 | + { |
| 31 | + handler(new Memory<T>(array, 0, minimumLength)); |
| 32 | + } |
| 33 | + finally |
| 34 | + { |
| 35 | + Instance.Return(array, false); |
| 36 | + } |
| 37 | + } |
| 38 | + } |
| 39 | + |
| 40 | + public static TResult Rent<TResult>( |
| 41 | + long minimumLength, |
| 42 | + bool clearAfter, |
| 43 | + Func<Memory<T>, TResult> handler) |
| 44 | + { |
| 45 | + if (minimumLength < 0) |
| 46 | + throw new ArgumentOutOfRangeException(nameof(minimumLength), minimumLength, "Must be at least 0."); |
| 47 | + |
| 48 | + if (minimumLength > MaxArrayLength) |
| 49 | + { |
| 50 | + return handler(new T[minimumLength]); |
| 51 | + } |
| 52 | + else |
| 53 | + { |
| 54 | + var array = Instance.Rent((int)(minimumLength)); |
| 55 | + try |
| 56 | + { |
| 57 | + return handler(array); |
| 58 | + } |
| 59 | + finally |
| 60 | + { |
| 61 | + Instance.Return(array, clearAfter); |
| 62 | + } |
| 63 | + } |
| 64 | + } |
| 65 | + } |
| 66 | + |
| 67 | +} |
0 commit comments