-
Notifications
You must be signed in to change notification settings - Fork 1.2k
/
Copy pathStringExtensions.cs
64 lines (54 loc) · 1.41 KB
/
StringExtensions.cs
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
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
// Licensed to Elasticsearch B.V under one or more agreements.
// Elasticsearch B.V licenses this file to you under the Apache 2.0 License.
// See the LICENSE file in the project root for more information.
using System;
#if ELASTICSEARCH_SERVERLESS
namespace Elastic.Clients.Elasticsearch.Serverless;
#else
namespace Elastic.Clients.Elasticsearch;
#endif
internal static class StringExtensions
{
// Taken from:
// https://github.com/dotnet/runtime/blob/main/src/libraries/System.Text.Json/Common/JsonCamelCaseNamingPolicy.cs
internal static string ToCamelCase(this string name)
{
if (string.IsNullOrEmpty(name) || !char.IsUpper(name[0]))
{
return name;
}
#if NET
return string.Create(name.Length, name, (chars, name) =>
{
name.CopyTo(chars);
FixCasing(chars);
});
#else
var chars = name.ToCharArray();
FixCasing(chars);
return new string(chars);
#endif
}
private static void FixCasing(Span<char> chars)
{
for (var i = 0; i < chars.Length; i++)
{
if (i == 1 && !char.IsUpper(chars[i]))
{
break;
}
var hasNext = (i + 1 < chars.Length);
// Stop when next char is already lowercase.
if (i > 0 && hasNext && !char.IsUpper(chars[i + 1]))
{
// If the next char is a space, lowercase current char before exiting.
if (chars[i + 1] == ' ')
{
chars[i] = char.ToLowerInvariant(chars[i]);
}
break;
}
chars[i] = char.ToLowerInvariant(chars[i]);
}
}
}