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);
if (!pipeHasData) throw new ArgumentException("Peek called on empty pipeline");
SequencePosition seqp = rr.Buffer.GetPosition(0);
readerPipe.Reader.AdvanceTo(seqp);
var roSeq = rr.Buffer.Slice(0, 1);
var roSpan = roSeq.First.Span;
return roSpan[0];
}
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.