dotnet / runtime

.NET is a cross-platform runtime for cloud, mobile, desktop, and IoT apps.
https://docs.microsoft.com/dotnet/core/
MIT License
14.56k stars 4.54k forks source link

[API Proposal]: Add PeekByte() to BufferedStream #99454

Open fawzibr opened 4 months ago

fawzibr commented 4 months ago

Background and motivation

I don't understand why something as simple (and obvious) as PeekByte() was not added to BufferedStream. Everything is already there just removing a '++' from the ReadByte function? Maybe a Peek(byte[] arr,int offset,int count) could be possible as well.

API Proposal

namespace System.IO;

public class BufferedStream
{
    public Int32 PeekByte() { 
        EnsureNotClosed();
        EnsureCanRead();
        if (_readPos == _readLen) {
            if (_writePos > 0) FlushWrite();
            EnsureBufferAllocated();
            _readLen = _stream.Read(_buffer, 0, _bufferSize);
            _readPos = 0;
        }
        if (_readPos == _readLen) return -1;
        // same as ReadByte just changed '_readPos++' to '_readPos' to return the next char 
        // waiting to be read 
        Int32 b = _buffer[_readPos]; 
        return b;
    }
}

API Usage

BufferedStream stream = new BufferedStream(sourceStream,1024);
int peekValue=stream.PeekByte();

Alternative Designs

No response

Risks

No response

dotnet-policy-service[bot] commented 4 months ago

Tagging subscribers to this area: @dotnet/area-system-io See info in area-owners.md if you want to be subscribed.

Zintom commented 4 months ago

Peak(Span<byte> buffer) would be nice too.

colejohnson66 commented 4 months ago

BufferedStream.Peek is part of #58216

fawzibr commented 4 months ago

BufferedStream.Peek is part of #58216

Since 2021. Even though it's such a small/simple change.