IMemoryOwner with partially filled Memory buffer

90 Views Asked by At

I have a parser that takes an IAsyncEnumerable<IMemoryOwner<char>>. This allows it to enumerate over pages of buffered data. The reason the parser enumerates over IMemoryOwner<char> rather than Memory<char> is so that it can call Dispose on the IMemoryOwner, which will (I think!) release its internal Memory<char> back to the caller's MemoryPool.

So the caller of the parser utilises a method like this to create the IAsyncEnumerable:

private async IAsyncEnumerable<IMemoryOwner<char>> GetPagesAsync(int bufferSize, StreamReader reader)
{
    int charactersRead;
    do
    {
        var bufferOwner = MemoryPool<char>.Shared.Rent(bufferSize);
        var buffer = bufferOwner.Memory;

        charactersRead = await reader.ReadBlockAsync(buffer);

        yield return bufferOwner;
    } while (charactersRead > 0);
}

This is all fine until the final read when charactersRead might be less than bufferSize. Normally, I would just use buffer.Slice(0, charactersRead), but I need to return the IMemoryOwner rather than the Memory. Is there a built-in way around this, or is it necessary to either implement your own IMemoryPool and IMemoryOwner, or create your own type to wrap both the sliced Memory and the IMemoryOwner?

0

There are 0 best solutions below