System.Text.Utf8.Utf8Encoder.TryDecodeCodePoint C# (CSharp) Method

TryDecodeCodePoint() public static method

public static TryDecodeCodePoint ( Span buffer, UnicodeCodePoint &codePoint, int &encodedBytes ) : bool
buffer Span
codePoint UnicodeCodePoint
encodedBytes int
return bool
        public static bool TryDecodeCodePoint(Span<byte> buffer, out UnicodeCodePoint codePoint, out int encodedBytes)
        {
            if (buffer.Length == 0)
            {
                codePoint = default(UnicodeCodePoint);
                encodedBytes = default(int);
                return false;
            }

            byte first = buffer[0];
            if (!TryGetFirstByteCodePointValue(first, out codePoint, out encodedBytes))
                return false;

            if (buffer.Length < encodedBytes)
                return false;

            // TODO: Should we manually inline this for values 1-4 or will compiler do this for us?
            for (int i = 1; i < encodedBytes; i++)
            {
                if (!TryReadCodePointByte(buffer[i], ref codePoint))
                    return false;
            }

            return true;
        }

Usage Example

示例#1
0
        private static IEnumerator <UnicodeCodePoint> GetCodePointsEnumerator(ByteSpan buffer)
        {
            while (buffer.Length > 0)
            {
                UnicodeCodePoint codePoint;
                int encodedBytes;
                if (Utf8Encoder.TryDecodeCodePoint(buffer, out codePoint, out encodedBytes))
                {
                    yield return(codePoint);

                    buffer = buffer.Slice(encodedBytes);
                }
                else
                {
                    // TODO: change exception type
                    throw new Exception("Invalid character");
                }
            }
        }