Description
Background and motivation
In .NET Core 2.1 we added an Encoding.GetBytes(ReadOnlySpan<char>, Span<byte>)
and Encoding.GetChars(ReadOnlySpan<byte>, Span<char>)
that will encode/decode the source into the destination and return how many chars/bytes it wrote. However, the destination span needs to be large enough to store all the written data; if it's too small, the method throws. Encoding doesn't provide a variant that allows for failing without exception when the destination is too small, and that's particularly useful when writing out a larger composed output where you loop to grow the buffer to accommodate more output.
Workarounds today are to first call GetByte/CharCount to determine how much space is required, or to use alternate APIs for the specific encoding in question, e.g. UTF8.FromUtf16 that's an OperationStatus-based API.
API Proposal
namespace System.Text;
public abstract class Encoding
{
public int GetBytes(ReadOnlySpan<char> chars, Span<byte> bytes);
+ public bool TryGetBytes(ReadOnlySpan<char> chars, Span<byte> bytes, out int bytesWritten);
public int GetChars(ReadOnlySpan<byte> bytes, Span<char> chars);
+ public bool TryGetChars(ReadOnlySpan<byte> bytes, Span<char> chars, out int charsWritten);
}
The base virtual implementation will use GetByte/CharCount and GetBytes/GetChars, but implementations like UTF8Encoding can then do better in their overrides.
API Usage
if (Encoding.UTF8.TryGetBytes(str, destination, out int bytesWritten))
{
_length += bytesWritten;
return true;
}
return false;
Alternative Designs
No response
Risks
No response