Meep

recycled memory stream

Jun 27th, 2022 (edited)
1,059
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. using System.IO;
  2. using System;
  3.  
  4. public sealed class RecycledMemoryStream : Stream
  5. {
  6.     private const ushort Capacity = 4 * 1024;
  7.  
  8.     [ThreadStatic]
  9.     private static MemoryStream Stream;
  10.  
  11.     public override bool CanRead => Stream.CanRead;
  12.     public override bool CanWrite => Stream.CanWrite;
  13.     public override bool CanSeek => Stream.CanSeek;
  14.     public override long Length => Stream.Length;
  15.  
  16.     public override long Position
  17.     {
  18.         get => Stream.Position;
  19.         set => Stream.Position = value;
  20.     }
  21.  
  22.     public RecycledMemoryStream(byte[] buffer, int offset, int count) : this()
  23.     {
  24.         Stream.Write(buffer, offset, count);
  25.         Stream.Position = 0L;
  26.     }
  27.  
  28.     public RecycledMemoryStream(byte[] buffer) : this()
  29.     {
  30.         Stream.Write(buffer, 0, buffer.Length);
  31.         Stream.Position = 0L;
  32.     }
  33.  
  34.     public RecycledMemoryStream()
  35.     {
  36.         if (Stream == null)
  37.         {
  38.             Stream = new MemoryStream();
  39.             return;
  40.         }
  41.  
  42.         Stream.Capacity = Capacity;
  43.     }
  44.  
  45.     public override int Read(byte[] buffer, int offset, int count)
  46.     {
  47.         return Stream.Read(buffer, offset, count);
  48.     }
  49.  
  50.     public override void Write(byte[] buffer, int offset, int count)
  51.     {
  52.         Stream.Write(buffer, offset, count);
  53.     }
  54.  
  55.     public override long Seek(long offset, SeekOrigin origin)
  56.     {
  57.         return Stream.Seek(offset, origin);
  58.     }
  59.  
  60.     public override void SetLength(long value)
  61.     {
  62.         Stream.SetLength(value);
  63.     }
  64.  
  65.     public override void Flush()
  66.     {
  67.         Stream.Flush();
  68.     }
  69.  
  70.     protected override void Dispose(bool disposing)
  71.     {
  72.         if (disposing)
  73.         {
  74.             Stream.SetLength(0L);
  75.         }
  76.     }
  77.  
  78.     public byte[] ToArray()
  79.     {
  80.         return Stream.ToArray();
  81.     }
  82.  
  83.     public MemoryStream GetUnderlyingMemoryStream()
  84.     {
  85.         return Stream;
  86.     }
  87. }
  88.  
RAW Paste Data Copied