Skip to content

API Proposal: Stream.ReadBlock / Stream.ReadBlockAsync #34129

@mikernet

Description

@mikernet

I use the following 2 methods more than I use the normal Read/ReadAsync methods (I have them implemented as extension methods) so I think it would be rather useful to have them in the runtime:

public abstract class Stream
{
    /// <summary>
    /// Reads until all the requested bytes have been loaded into the buffer.
    /// </summary>
    public int ReadBlock(Span<byte> buffer)
    {
        int totalBytes = 0;

        while (buffer.Length > 0) {
            int bytesRead = Read(buffer);

            if (bytesRead == 0)
                break;

            totalBytes += bytesRead;
            buffer = buffer.Slice(bytesRead);
        }

        return totalBytes;
    }

    /// <summary>
    /// Reads until all the requested bytes have been loaded into the buffer.
    /// </summary>
    public async ValueTask<int> ReadBlockAsync(Memory<byte> buffer)
    {
        int totalBytes = 0;

        while (buffer.Length > 0) {
            int bytesRead = await ReadAsync(buffer);

            if (bytesRead == 0)
                break;

            totalBytes += bytesRead;
            buffer = buffer.Slice(bytesRead);
        }

        return totalBytes;
    }
}

Thanks @jnm2 for suggesting the method names as they are analogous in behavior to TextReader.ReadBlock and TextReader.ReadBlockAsync.

Metadata

Metadata

Assignees

No one assigned

    Type

    No type
    No fields configured for issues without a type.

    Projects

    No projects

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions