aboutsummaryrefslogtreecommitdiff
path: root/src/Ryujinx.Horizon/Sdk/Ngc/Detail/Utf8Util.cs
blob: e2a027086668c1696fc89d56a476ea39d2cf2157 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
using System;
using System.Text;

namespace Ryujinx.Horizon.Sdk.Ngc.Detail
{
    static class Utf8Util
    {
        public static Utf8ParseResult NormalizeFormKC(Span<byte> output, ReadOnlySpan<byte> input)
        {
            int length = input.IndexOf((byte)0);
            if (length >= 0)
            {
                input = input[..length];
            }

            UTF8Encoding encoding = new(encoderShouldEmitUTF8Identifier: false, throwOnInvalidBytes: true);

            string text;

            try
            {
                text = encoding.GetString(input);
            }
            catch (ArgumentException)
            {
                return Utf8ParseResult.InvalidCharacter;
            }

            string normalizedText = text.Normalize(NormalizationForm.FormKC);

            int outputIndex = Encoding.UTF8.GetBytes(normalizedText, output);

            if (outputIndex < output.Length)
            {
                output[outputIndex] = 0;
            }

            return Utf8ParseResult.Success;
        }
    }
}