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
My code, which works is below. My question is, can it be improved?
Thanks in advance for any advice, Oz
public byte Peek()
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; // 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.