PluralKit/Myriad/Serialization/JsonSnakeCaseNamingPolicy.cs

86 lines
3.0 KiB
C#
Raw Normal View History

2020-12-22 12:15:26 +00:00
using System.Text;
using System.Text.Json;
namespace Myriad.Serialization;
// From https://github.com/J0rgeSerran0/JsonNamingPolicy/blob/master/JsonSnakeCaseNamingPolicy.cs, no NuGet :/
public class JsonSnakeCaseNamingPolicy: JsonNamingPolicy
2020-12-22 12:15:26 +00:00
{
private readonly string _separator = "_";
2020-12-22 12:15:26 +00:00
public override string ConvertName(string name)
{
if (string.IsNullOrEmpty(name) || string.IsNullOrWhiteSpace(name)) return string.Empty;
2020-12-22 12:15:26 +00:00
ReadOnlySpan<char> spanName = name.Trim();
2020-12-22 12:15:26 +00:00
var stringBuilder = new StringBuilder();
var addCharacter = true;
2020-12-22 12:15:26 +00:00
var isPreviousSpace = false;
var isPreviousSeparator = false;
var isCurrentSpace = false;
var isNextLower = false;
var isNextUpper = false;
var isNextSpace = false;
2020-12-22 12:15:26 +00:00
for (var position = 0; position < spanName.Length; position++)
{
if (position != 0)
2020-12-22 12:15:26 +00:00
{
isCurrentSpace = spanName[position] == 32;
isPreviousSpace = spanName[position - 1] == 32;
isPreviousSeparator = spanName[position - 1] == 95;
if (position + 1 != spanName.Length)
2020-12-22 12:15:26 +00:00
{
isNextLower = spanName[position + 1] > 96 && spanName[position + 1] < 123;
isNextUpper = spanName[position + 1] > 64 && spanName[position + 1] < 91;
isNextSpace = spanName[position + 1] == 32;
}
2020-12-22 12:15:26 +00:00
if (isCurrentSpace &&
(isPreviousSpace ||
isPreviousSeparator ||
isNextUpper ||
isNextSpace))
{
addCharacter = false;
}
else
{
var isCurrentUpper = spanName[position] > 64 && spanName[position] < 91;
var isPreviousLower = spanName[position - 1] > 96 && spanName[position - 1] < 123;
var isPreviousNumber = spanName[position - 1] > 47 && spanName[position - 1] < 58;
2020-12-22 12:15:26 +00:00
if (isCurrentUpper &&
(isPreviousLower ||
isPreviousNumber ||
isNextLower ||
isNextSpace ||
isNextLower && !isPreviousSpace))
2020-12-22 12:15:26 +00:00
{
stringBuilder.Append(_separator);
2020-12-22 12:15:26 +00:00
}
else
{
if (isCurrentSpace &&
!isPreviousSpace &&
!isNextSpace)
2020-12-22 12:15:26 +00:00
{
stringBuilder.Append(_separator);
addCharacter = false;
2020-12-22 12:15:26 +00:00
}
}
}
}
if (addCharacter)
stringBuilder.Append(spanName[position]);
else
addCharacter = true;
2020-12-22 12:15:26 +00:00
}
return stringBuilder.ToString().ToLower();
2020-12-22 12:15:26 +00:00
}
}