Guest User

Untitled

a guest
Jan 24th, 2018
72
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.86 KB | None | 0 0
  1. internal class StreamBuffer : Stream
  2. {
  3. private int _length;
  4. private BufferNode _tail;
  5.  
  6. public StreamBuffer()
  7. {
  8. var node = new BufferNode();
  9. _head = node;
  10. _tail = node;
  11. }
  12.  
  13. public override bool CanRead => true;
  14.  
  15. public override bool CanSeek => false;
  16.  
  17. public override bool CanWrite => true;
  18.  
  19. public override long Length => _length;
  20.  
  21. public override long Position { get; set; } = 0;
  22.  
  23. public override void Flush()
  24. {
  25. }
  26.  
  27. public override int Read(byte[] buffer, int offset, int count)
  28. {
  29. if (_length < count)
  30. count = _length;
  31.  
  32. var bytesRead = count;
  33. while (count > 0)
  34. {
  35. var remaining = _tail.Buffer.Length - _tail.Offset;
  36. if (remaining > count)
  37. remaining = count;
  38.  
  39. Buffer.BlockCopy(_tail.Buffer, _tail.Offset, buffer, offset, remaining);
  40.  
  41. _tail.Offset += remaining;
  42.  
  43. if (remaining <= count)
  44. _tail = _tail.Next;
  45.  
  46. offset += remaining;
  47. count -= remaining;
  48. }
  49.  
  50. _length -= bytesRead;
  51. return bytesRead;
  52. }
  53.  
  54. public override long Seek(long offset, SeekOrigin origin)
  55. {
  56. throw new NotSupportedException();
  57. }
  58.  
  59. public override void SetLength(long value)
  60. {
  61. throw new NotSupportedException();
  62. }
  63.  
  64. public override void Write(byte[] buffer, int offset, int count)
  65. {
  66. var copy = new byte[count];
  67. Array.Copy(buffer, offset, copy, 0, count);
  68. var node = new BufferNode
  69. {
  70. Buffer = copy,
  71. Offset = 0,
  72. Next = null
  73. };
  74.  
  75. _head.Next = node;
  76. _head = node;
  77.  
  78. _length += count;
  79. }
  80.  
  81. private class BufferNode
  82. {
  83. public byte[] Buffer;
  84. public BufferNode Next;
  85. public int Offset;
  86. }
  87. }
Add Comment
Please, Sign In to add comment