8
votes

I want to emulate a network-type stream on a single PC.

I've done this by creating a Stream that takes in 2 underlying streams, one to read from and another to write to.

I then create 2 instances of this class swapping the 2 streams. Currently I'm using MemoryStreams as the 2 underlying streams.

The trouble i have now is that if I write X bytes to a MemoryStream then its position will be X and if i then do a Read I get no data, as i'm at the end of the stream.

Given that I'll typically be doing a couple of reads/writes (so can't just reset the postion to 0 after every write) what Stream can i use to get this behaviour?

Effectively I want a sort of byte queue that I can write to and read to in the form of a stream.

i.e. (ignoring actual method arguments)

MyStream.Write({ 1, 2, 3, 4, 5, 6 });
MyStream.Write({ 7, 8 });
MyStream.Read(3) // Returns { 1, 2, 3 }
MyStream.Read(4) // Returns { 4, 5, 6, 7 }
1

1 Answers

11
votes

It's actually a lot simpler than I thought (in my case anyway).
I simply restore/record the read/write positions before performing any operation:

public class QueueStream : MemoryStream
{
    long ReadPosition;
    long WritePosition;

    public QueueStream() : base() { }

    public override int Read(byte[] buffer, int offset, int count)
    {
        Position = ReadPosition;

        var temp = base.Read(buffer, offset, count);

        ReadPosition = Position;

        return temp;
    }

    public override void Write(byte[] buffer, int offset, int count)
    {
        Position = WritePosition;

        base.Write(buffer, offset, count);

        WritePosition = Position;
    }
}