Exemplo n.º 1
0
        // TODO: This should return Utf16CodeUnits which should wrap byte[]/Span<byte>, same for other encoders
        private static byte[] GetUtf8BytesFromString(string str)
        {
            var utf16 = str.AsSpan();

            int needed;

            if (!Utf8Encoder.TryComputeEncodedBytes(utf16, out needed))
            {
                return(null);
            }

            var data   = new byte[needed];
            var buffer = new Span <byte>(data);

            int written;
            int consumed;

            if (!Utf8Encoder.TryEncode(utf16, buffer, out consumed, out written))
            {
                // This shouldn't happen...
                return(null);
            }

            return(data);
        }
Exemplo n.º 2
0
        // TODO: This should return Utf16CodeUnits which should wrap byte[]/Span<byte>, same for other encoders
        private static byte[] GetUtf8BytesFromString(string str)
        {
            ReadOnlySpan <char> characters = str.Slice();
            int utf8Length = Utf8Encoder.ComputeEncodedBytes(characters);

            byte[] utf8Buffer = new byte[utf8Length];

            int encodedBytes;

            if (!Utf8Encoder.TryEncode(characters, utf8Buffer, out encodedBytes))
            {
                throw new Exception(); // this should not happen
            }

            return(utf8Buffer);
        }