Click here to Skip to main content
14,303,648 members
Rate this:
Please Sign up or sign in to vote.
See more:
I have an existing project using an interface, which cannot be easily changed, declaring a method called Peek().
The original implementation of Peek looked at the first element of internal List<byte>, filled in by a socket, byte by byte,and returned the byte.

I have been experimenting with Pipelines and wanted a corresponding Peek() that would return the first byte of a PipeReader.Reader with no memory allocations and also not disturb/remove anything from the Reader pipe, i.e., you can call it all day long and it would return the same byte.

After much Googling, I didn't find anything, except that it should be possible.

My code, which works is below. My question is, can it be improved?
Thanks in advance for any advice, Oz
Code follows:

public byte Peek()
    ReadResult rr;
    var pipeHasData = readerPipe.Reader.TryRead(out rr);  // try to get a buffer in rr
    if (!pipeHasData) throw new ArgumentException("Peek called on empty pipeline");
    SequencePosition seqp = rr.Buffer.GetPosition(0);     // get sequence position to start of buffer
    readerPipe.Reader.AdvanceTo(seqp);                    // reset pipe position to beginning of buffer
    var roSeq = rr.Buffer.Slice(0, 1);                    // obtain ReadOnlySequence of 1 byte, not indexable
    var roSpan = roSeq.First.Span;                        // obtain ReadOnlySpan from sequence's ReadOnlyMemory (.First)
    return roSpan[0];                                     // return first byte of the Span, which is indexable

What I have tried:

Googling for a solution, but all documents on the web do not supply an actual implementation of how to do t this.
Updated 10-Sep-19 14:40pm
Gerry Schmitz 11-Sep-19 0:44am
Make one in blue.

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

CodeProject, 503-250 Ferrand Drive Toronto Ontario, M3C 3G8 Canada +1 416-849-8900 x 100