Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- internal class StreamBuffer : Stream
- {
- private int _length;
- private BufferNode _tail;
- public StreamBuffer()
- {
- var node = new BufferNode();
- _head = node;
- _tail = node;
- }
- public override bool CanRead => true;
- public override bool CanSeek => false;
- public override bool CanWrite => true;
- public override long Length => _length;
- public override long Position { get; set; } = 0;
- public override void Flush()
- {
- }
- public override int Read(byte[] buffer, int offset, int count)
- {
- if (_length < count)
- count = _length;
- var bytesRead = count;
- while (count > 0)
- {
- var remaining = _tail.Buffer.Length - _tail.Offset;
- if (remaining > count)
- remaining = count;
- Buffer.BlockCopy(_tail.Buffer, _tail.Offset, buffer, offset, remaining);
- _tail.Offset += remaining;
- if (remaining <= count)
- _tail = _tail.Next;
- offset += remaining;
- count -= remaining;
- }
- _length -= bytesRead;
- return bytesRead;
- }
- public override long Seek(long offset, SeekOrigin origin)
- {
- throw new NotSupportedException();
- }
- public override void SetLength(long value)
- {
- throw new NotSupportedException();
- }
- public override void Write(byte[] buffer, int offset, int count)
- {
- var copy = new byte[count];
- Array.Copy(buffer, offset, copy, 0, count);
- var node = new BufferNode
- {
- Buffer = copy,
- Offset = 0,
- Next = null
- };
- _head.Next = node;
- _head = node;
- _length += count;
- }
- private class BufferNode
- {
- public byte[] Buffer;
- public BufferNode Next;
- public int Offset;
- }
- }
Add Comment
Please, Sign In to add comment