LargeMemoryStream.cs 6.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274
  1. using System;
  2. using System.Buffers;
  3. using System.IO;
  4. using System.Runtime.CompilerServices;
  5. namespace Masuit.Tools.Systems;
  6. /// <summary>
  7. /// 大型内存流,最大可支持1TB数据,推荐当数据流大于2GB时使用
  8. /// </summary>
  9. public class LargeMemoryStream : Stream
  10. {
  11. /// <summary>
  12. /// 终结器
  13. /// </summary>
  14. ~LargeMemoryStream()
  15. {
  16. Dispose(true);
  17. }
  18. private const int PageSize = 1024000000;
  19. private const int AllocStep = 1024;
  20. private byte[][] _streamBuffers;
  21. private int _pageCount = 0;
  22. private long _allocatedBytes = 0;
  23. private long _position = 0;
  24. private long _length = 0;
  25. private bool _isDisposed;
  26. private int GetPageCount(long length)
  27. {
  28. int pageCount = (int)(length / PageSize) + 1;
  29. if ((length % PageSize) == 0)
  30. pageCount--;
  31. return pageCount;
  32. }
  33. private void ExtendPages()
  34. {
  35. if (_streamBuffers == null)
  36. {
  37. _streamBuffers = new byte[AllocStep][];
  38. }
  39. else
  40. {
  41. var streamBuffers = new byte[_streamBuffers.Length + AllocStep][];
  42. Array.Copy(_streamBuffers, streamBuffers, _streamBuffers.Length);
  43. _streamBuffers = streamBuffers;
  44. }
  45. _pageCount = _streamBuffers.Length;
  46. }
  47. private void AllocSpaceIfNeeded(long value)
  48. {
  49. if (value < 0)
  50. throw new InvalidOperationException("AllocSpaceIfNeeded < 0");
  51. if (value == 0)
  52. return;
  53. int currentPageCount = GetPageCount(_allocatedBytes);
  54. int neededPageCount = GetPageCount(value);
  55. while (currentPageCount < neededPageCount)
  56. {
  57. if (currentPageCount == _pageCount)
  58. ExtendPages();
  59. _streamBuffers[currentPageCount++] = ArrayPool<byte>.Shared.Rent(PageSize);
  60. }
  61. _allocatedBytes = (long)currentPageCount * PageSize;
  62. value = Math.Max(value, _length);
  63. if (_position > (_length = value))
  64. {
  65. _position = _length;
  66. }
  67. }
  68. public override bool CanRead => true;
  69. public override bool CanSeek => true;
  70. public override bool CanWrite => true;
  71. public override long Length => _length;
  72. public override long Position
  73. {
  74. get => _position;
  75. set
  76. {
  77. if (value > _length)
  78. {
  79. throw new InvalidOperationException("Position > Length");
  80. }
  81. if (value < 0)
  82. {
  83. throw new InvalidOperationException("Position < 0");
  84. }
  85. _position = value;
  86. }
  87. }
  88. #if NETCOREAPP || NET452
  89. public Span<byte[]> GetSpan()
  90. {
  91. return _streamBuffers.AsSpan(0, _streamBuffers.Length);
  92. }
  93. public Memory<byte[]> GetMemory()
  94. {
  95. return _streamBuffers.AsMemory(0, _streamBuffers.Length);
  96. }
  97. public ArraySegment<byte[]> ToArraySegment()
  98. {
  99. return new ArraySegment<byte[]>(_streamBuffers, 0, _streamBuffers.Length);
  100. }
  101. #endif
  102. public override void Flush()
  103. {
  104. AssertNotDisposed();
  105. }
  106. public override int Read(byte[] buffer, int offset, int count)
  107. {
  108. AssertNotDisposed();
  109. int currentPage = (int)(_position / PageSize);
  110. int currentOffset = (int)(_position % PageSize);
  111. int currentLength = PageSize - currentOffset;
  112. long startPosition = _position;
  113. if (startPosition + count > _length)
  114. {
  115. count = (int)(_length - startPosition);
  116. }
  117. while (count != 0 && _position < _length)
  118. {
  119. if (currentLength > count)
  120. {
  121. currentLength = count;
  122. }
  123. Array.Copy(_streamBuffers[currentPage++], currentOffset, buffer, offset, currentLength);
  124. offset += currentLength;
  125. _position += currentLength;
  126. count -= currentLength;
  127. currentOffset = 0;
  128. currentLength = PageSize;
  129. }
  130. return (int)(_position - startPosition);
  131. }
  132. public override long Seek(long offset, SeekOrigin origin)
  133. {
  134. AssertNotDisposed();
  135. switch (origin)
  136. {
  137. case SeekOrigin.Begin:
  138. break;
  139. case SeekOrigin.Current:
  140. offset += _position;
  141. break;
  142. case SeekOrigin.End:
  143. offset = _length - offset;
  144. break;
  145. default:
  146. throw new ArgumentOutOfRangeException("origin");
  147. }
  148. return Position = offset;
  149. }
  150. public override void SetLength(long value)
  151. {
  152. switch (value)
  153. {
  154. case < 0:
  155. throw new InvalidOperationException("SetLength < 0");
  156. case 0:
  157. _streamBuffers = null;
  158. _allocatedBytes = _position = _length = 0;
  159. _pageCount = 0;
  160. return;
  161. }
  162. int currentPageCount = GetPageCount(_allocatedBytes);
  163. int neededPageCount = GetPageCount(value);
  164. while (currentPageCount > neededPageCount)
  165. {
  166. ArrayPool<byte>.Shared.Return(_streamBuffers[--currentPageCount], true);
  167. _streamBuffers[currentPageCount] = null;
  168. }
  169. AllocSpaceIfNeeded(value);
  170. if (_position > (_length = value))
  171. {
  172. _position = _length;
  173. }
  174. }
  175. public override void Write(byte[] buffer, int offset, int count)
  176. {
  177. AssertNotDisposed();
  178. int currentPage = (int)(_position / PageSize);
  179. int currentOffset = (int)(_position % PageSize);
  180. int currentLength = PageSize - currentOffset;
  181. AllocSpaceIfNeeded(_position + count);
  182. while (count != 0)
  183. {
  184. if (currentLength > count)
  185. {
  186. currentLength = count;
  187. }
  188. Array.Copy(buffer, offset, _streamBuffers[currentPage++], currentOffset, currentLength);
  189. offset += currentLength;
  190. _position += currentLength;
  191. count -= currentLength;
  192. currentOffset = 0;
  193. currentLength = PageSize;
  194. }
  195. }
  196. [MethodImpl(MethodImplOptions.AggressiveInlining)]
  197. protected override void Dispose(bool disposing)
  198. {
  199. if (disposing)
  200. {
  201. _isDisposed = true;
  202. Position = 0;
  203. _length = 0;
  204. if (_streamBuffers != null)
  205. {
  206. foreach (var bytes in _streamBuffers)
  207. {
  208. if (bytes != null)
  209. {
  210. ArrayPool<byte>.Shared.Return(bytes);
  211. }
  212. }
  213. _streamBuffers = null;
  214. }
  215. }
  216. base.Dispose(disposing);
  217. }
  218. [MethodImpl(MethodImplOptions.AggressiveInlining)]
  219. private void AssertNotDisposed()
  220. {
  221. if (_isDisposed)
  222. {
  223. throw new ObjectDisposedException(nameof(PooledMemoryStream));
  224. }
  225. }
  226. }