| | 1 | | // Copyright (c) Microsoft Corporation. All rights reserved. |
| | 2 | | // Licensed under the MIT License. |
| | 3 | |
|
| | 4 | | using System; |
| | 5 | | using System.Buffers; |
| | 6 | | using System.IO; |
| | 7 | | using System.Threading; |
| | 8 | | using System.Threading.Tasks; |
| | 9 | |
|
| | 10 | | namespace Azure.Storage |
| | 11 | | { |
| | 12 | | /// <summary> |
| | 13 | | /// Private memory pool specific to Azure storage transfers, based on ArrayPool. |
| | 14 | | /// </summary> |
| | 15 | | internal class StorageMemoryPool : MemoryPool<byte> |
| | 16 | | { |
| | 17 | | private ArrayPool<byte> _arrayPool; |
| | 18 | |
|
| 0 | 19 | | public StorageMemoryPool(int maxArrayLength, int maxArraysPerBucket) |
| | 20 | | { |
| 0 | 21 | | MaxBufferSize = maxArrayLength; |
| 0 | 22 | | _arrayPool = ArrayPool<byte>.Create(maxArrayLength, maxArraysPerBucket); |
| 0 | 23 | | } |
| | 24 | |
|
| 0 | 25 | | public override int MaxBufferSize { get; } |
| | 26 | |
|
| | 27 | | public override IMemoryOwner<byte> Rent(int minBufferSize = -1) |
| | 28 | | { |
| 0 | 29 | | lock (_arrayPool) |
| | 30 | | { |
| 0 | 31 | | return new StorageMemoryOwner(this, minBufferSize); |
| | 32 | | } |
| 0 | 33 | | } |
| | 34 | |
|
| 0 | 35 | | protected override void Dispose(bool disposing) => _arrayPool = default; |
| | 36 | |
|
| | 37 | | private class StorageMemoryOwner : IMemoryOwner<byte> |
| | 38 | | { |
| 0 | 39 | | public StorageMemoryOwner(StorageMemoryPool pool, int minimumLength) |
| | 40 | | { |
| 0 | 41 | | _arrayPool = pool._arrayPool; |
| 0 | 42 | | Memory = _arrayPool.Rent(minimumLength); |
| 0 | 43 | | } |
| | 44 | |
|
| | 45 | | private ArrayPool<byte> _arrayPool; |
| | 46 | |
|
| 0 | 47 | | public Memory<byte> Memory { get; private set; } |
| | 48 | |
|
| | 49 | | #region IDisposable Support |
| | 50 | | private bool _disposedValue = false; // To detect redundant calls |
| | 51 | |
|
| | 52 | | public void Dispose() |
| | 53 | | { |
| 0 | 54 | | if (!_disposedValue) |
| | 55 | | { |
| 0 | 56 | | _disposedValue = true; |
| | 57 | |
|
| 0 | 58 | | _arrayPool.Return(Memory.ToArray()); |
| 0 | 59 | | _arrayPool = null; |
| 0 | 60 | | Memory = null; |
| | 61 | | } |
| 0 | 62 | | } |
| | 63 | | #endregion |
| | 64 | | } |
| | 65 | | } |
| | 66 | | } |