public static TryEncodeCodePoint ( UnicodeCodePoint codePoint, Span |
||
codePoint | UnicodeCodePoint | |
buffer | Span |
|
encodedBytes | int | |
return | bool |
public static bool TryEncodeCodePoint(UnicodeCodePoint codePoint, Span<byte> buffer, out int encodedBytes)
{
if (!UnicodeCodePoint.IsSupportedCodePoint(codePoint))
{
encodedBytes = 0;
return false;
}
encodedBytes = GetNumberOfEncodedBytes(codePoint);
if (encodedBytes > buffer.Length)
{
encodedBytes = 0;
return false;
}
switch (encodedBytes)
{
case 1:
buffer[0] = (byte)(b0111_1111U & codePoint.Value);
return true;
case 2:
byte b0 = (byte)(((codePoint.Value >> 6) & b0001_1111U) | b1100_0000U);
byte b1 = (byte)(((codePoint.Value >> 0) & b0011_1111U) | b1000_0000U);
buffer.Write((ushort)(b0 | b1 << 8));
return true;
case 3:
b0 = (byte)(((codePoint.Value >> 12) & b0000_1111U) | b1110_0000U);
b1 = (byte)(((codePoint.Value >> 6) & b0011_1111U) | b1000_0000U);
buffer.Write((ushort)(b0 | b1 << 8));
buffer[2] = (byte)(((codePoint.Value >> 0) & b0011_1111U) | b1000_0000U);
return true;
case 4:
b0 = (byte)(((codePoint.Value >> 18) & b0000_0111U) | b1111_0000U);
b1 = (byte)(((codePoint.Value >> 12) & b0011_1111U) | b1000_0000U);
byte b2 = (byte)(((codePoint.Value >> 6) & b0011_1111U) | b1000_0000U);
byte b3 = (byte)(((codePoint.Value >> 0) & b0011_1111U) | b1000_0000U);
buffer.Write((uint)(b0 | b1 << 8 | b2 << 16 | b3 << 24));
return true;
default:
return false;
}
}
#endregion
public unsafe Utf8EncodedCodePoint(char highSurrogate, char lowSurrogate) : this() { UnicodeCodePoint codePoint = (UnicodeCodePoint)(uint)char.ConvertToUtf32(highSurrogate, lowSurrogate); fixed(byte *encodedData = &_byte0) { Span <byte> buffer = new Span <byte>(encodedData, 4); if (!Utf8Encoder.TryEncodeCodePoint(codePoint, buffer, out _length)) { // TODO: Change exception type throw new Exception("Internal error: this should never happen as codePoint should be within acceptable range"); } } }