internal static string? ToCamelCase()

in src/StreamJsonRpc/Utilities.cs [88:134]


        internal static string? ToCamelCase(string? identifier)
        {
            if (identifier is null || identifier.Length == 0 || !char.IsUpper(identifier[0]))
            {
                return identifier;
            }

            char[] chars = ArrayPool<char>.Shared.Rent(identifier.Length);
            identifier.CopyTo(0, chars, 0, identifier.Length);
            try
            {
                for (int i = 0; i < identifier.Length; i++)
                {
                    if (i == 1 && !char.IsUpper(chars[i]))
                    {
                        break;
                    }

                    bool hasNext = i + 1 < identifier.Length;
                    if (i > 0 && hasNext && !char.IsUpper(chars[i + 1]))
                    {
                        // if the next character is a space, which is not considered uppercase
                        // (otherwise we wouldn't be here...)
                        // we want to ensure that the following:
                        // 'FOO bar' is rewritten as 'foo bar', and not as 'foO bar'
                        // The code was written in such a way that the first word in uppercase
                        // ends when if finds an uppercase letter followed by a lowercase letter.
                        // now a ' ' (space, (char)32) is considered not upper
                        // but in that case we still want our current character to become lowercase
                        if (char.IsSeparator(chars[i + 1]))
                        {
                            chars[i] = char.ToLowerInvariant(chars[i]);
                        }

                        break;
                    }

                    chars[i] = char.ToLowerInvariant(chars[i]);
                }

                return new string(chars, 0, identifier.Length);
            }
            finally
            {
                ArrayPool<char>.Shared.Return(chars);
            }
        }