Skip to content

Commit e8d1517

Browse files
committedSep 9, 2020
🐍 Add JsonSnakeCaseNamingPolicy
- For the use of online configuration generation - Source: dotnet/corefx#40003 - See also: dotnet/runtime#782
1 parent 8d21d84 commit e8d1517

File tree

1 file changed

+87
-0
lines changed

1 file changed

+87
-0
lines changed
 
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,87 @@
1+
// Licensed to the .NET Foundation under one or more agreements.
2+
// The .NET Foundation licenses this file to you under the MIT license.
3+
4+
// Source: https://github.com/dotnet/corefx/pull/40003
5+
// See also: https://github.com/dotnet/runtime/issues/782
6+
7+
using System;
8+
using System.Text;
9+
using System.Text.Json;
10+
11+
namespace shadowsocks_uri_generator
12+
{
13+
public class JsonSnakeCaseNamingPolicy : JsonNamingPolicy
14+
{
15+
internal enum SnakeCaseState
16+
{
17+
Start,
18+
Lower,
19+
Upper,
20+
NewWord
21+
}
22+
23+
public override string ConvertName(string name)
24+
{
25+
if (string.IsNullOrEmpty(name))
26+
{
27+
return name;
28+
}
29+
30+
var sb = new StringBuilder();
31+
var state = SnakeCaseState.Start;
32+
33+
var nameSpan = name.AsSpan();
34+
35+
for (int i = 0; i < nameSpan.Length; i++)
36+
{
37+
if (nameSpan[i] == ' ')
38+
{
39+
if (state != SnakeCaseState.Start)
40+
{
41+
state = SnakeCaseState.NewWord;
42+
}
43+
}
44+
else if (char.IsUpper(nameSpan[i]))
45+
{
46+
switch (state)
47+
{
48+
case SnakeCaseState.Upper:
49+
bool hasNext = (i + 1 < nameSpan.Length);
50+
if (i > 0 && hasNext)
51+
{
52+
char nextChar = nameSpan[i + 1];
53+
if (!char.IsUpper(nextChar) && nextChar != '_')
54+
{
55+
sb.Append('_');
56+
}
57+
}
58+
break;
59+
case SnakeCaseState.Lower:
60+
case SnakeCaseState.NewWord:
61+
sb.Append('_');
62+
break;
63+
}
64+
sb.Append(char.ToLowerInvariant(nameSpan[i]));
65+
state = SnakeCaseState.Upper;
66+
}
67+
else if (nameSpan[i] == '_')
68+
{
69+
sb.Append('_');
70+
state = SnakeCaseState.Start;
71+
}
72+
else
73+
{
74+
if (state == SnakeCaseState.NewWord)
75+
{
76+
sb.Append('_');
77+
}
78+
79+
sb.Append(nameSpan[i]);
80+
state = SnakeCaseState.Lower;
81+
}
82+
}
83+
84+
return sb.ToString();
85+
}
86+
}
87+
}

0 commit comments

Comments
 (0)