Click here to Skip to main content
15,886,258 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
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.
Posted
Updated 10-Sep-19 14:40pm
v2
Comments
[no name] 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, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900