dotnet / runtime

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

[API Proposal]: BinaryReader.ReadExactly #101614

Open terrajobst opened 2 weeks ago

terrajobst commented 2 weeks ago

Background and motivation

When reading custom binary formats one very often needs a specific number of bytes. The existing Read() method doesn't read a specific number of bytes, it reads as many bytes are currently available. Calling code has to handle this.

We had the same issue on Stream and solved this by exposing Stream.ReadExactly and Stream.ReadAtLeast.

API Proposal

namespace System.IO;

public partial class BinaryReader
{
    public virtual ReadExactly(Span<byte> buffer);
}

API Usage

BinaryReader binaryReader = GetReader();

Span<byte> guidBytes = (Span<byte>)stackalloc byte[16];
reader.ReadExactly(guidBytes);

Guid guid = new Guid(guidBytes);

Alternative Designs

No response

Risks

No response

dotnet-policy-service[bot] commented 2 weeks ago

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

PaulusParssinen commented 2 weeks ago

This would be equivalent to calling ReadExactly(Span<byte>) on the BinaryReader.BaseStream property, right? This method would be much nicer/accessible though.

terrajobst commented 2 weeks ago

Logically yes, but practically the challenge is that the reader has its own buffer. By passing that would be problematic.