MemoryBuffer.cs 1.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566
  1. using System;
  2. using System.Buffers;
  3. using System.IO;
  4. namespace ET
  5. {
  6. public class MemoryBuffer : MemoryStream, IBufferWriter<byte>
  7. {
  8. private int origin;
  9. public MemoryBuffer()
  10. {
  11. }
  12. public MemoryBuffer(int capacity) : base(capacity)
  13. {
  14. }
  15. public MemoryBuffer(byte[] buffer) : base(buffer)
  16. {
  17. }
  18. public MemoryBuffer(byte[] buffer, int index, int length) : base(buffer, index, length)
  19. {
  20. this.origin = index;
  21. }
  22. public ReadOnlyMemory<byte> WrittenMemory => this.GetBuffer().AsMemory(this.origin, (int)this.Position);
  23. public ReadOnlySpan<byte> WrittenSpan => this.GetBuffer().AsSpan(this.origin, (int)this.Position);
  24. public void Advance(int count)
  25. {
  26. long newLength = this.Position + count;
  27. if (newLength > this.Length)
  28. {
  29. this.SetLength(newLength);
  30. }
  31. this.Position = newLength;
  32. }
  33. public Memory<byte> GetMemory(int sizeHint = 0)
  34. {
  35. if (this.Length - this.Position < sizeHint)
  36. {
  37. this.SetLength(this.Position + sizeHint);
  38. }
  39. var memory = this.GetBuffer()
  40. .AsMemory((int)this.Position + this.origin, (int)(this.Length - this.Position));
  41. return memory;
  42. }
  43. public Span<byte> GetSpan(int sizeHint = 0)
  44. {
  45. if (this.Length - this.Position < sizeHint)
  46. {
  47. this.SetLength(this.Position + sizeHint);
  48. }
  49. var span = this.GetBuffer().AsSpan((int)this.Position + this.origin, (int)(this.Length - this.Position));
  50. return span;
  51. }
  52. }
  53. }