Пример #1
0
        // TODO: this should be moved to System.Text.Primitives. Probably to Utf8 class
        static string Utf8ToString(ReadOnlySpan <byte> utf8)
        {
            var result = Utf8.ToUtf16Length(utf8, out int bytesNeeded);

            if (result == TransformationStatus.InvalidData || result == TransformationStatus.NeedMoreSourceData)
            {
                throw new Exception("invalid UTF8 byte");
            }
            var str = new string(' ', bytesNeeded / sizeof(char));

            unsafe
            {
                fixed(char *pStr = str)
                {
                    var strSpan = new Span <char>(pStr, str.Length);

                    if (Utf8.ToUtf16(utf8, strSpan.AsBytes(), out int consumed, out int written) != TransformationStatus.Done)
                    {
                        throw new Exception();
                    }
                }
            }
            return(str);
        }
Пример #2
0
 /// <summary>
 /// Calculates the byte count needed to encode the UTF-16 bytes from the specified UTF-8 sequence.
 ///
 /// This method will consume as many of the input bytes as possible.
 /// </summary>
 /// <param name="source">A span containing a sequence of UTF-8 bytes.</param>
 /// <param name="bytesNeeded">On exit, contains the number of bytes required for encoding from the <paramref name="source"/>.</param>
 /// <returns>A <see cref="OperationStatus"/> value representing the expected state of the conversion.</returns>
 public static OperationStatus FromUtf8Length(ReadOnlySpan <byte> source, out int bytesNeeded)
 => Utf8.ToUtf16Length(source, out bytesNeeded);