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.
I use the following 2 methods more than I use the normal
Read/ReadAsyncmethods (I have them implemented as extension methods) so I think it would be rather useful to have them in the runtime:Thanks @jnm2 for suggesting the method names as they are analogous in behavior to
TextReader.ReadBlockandTextReader.ReadBlockAsync.