Skip to content
This repository has been archived by the owner on May 26, 2023. It is now read-only.

Commit

Permalink
Fix throws exception when enum has same value Cysharp#32
Browse files Browse the repository at this point in the history
  • Loading branch information
neuecc committed Jan 14, 2021
1 parent f71823d commit 8639a96
Showing 1 changed file with 15 additions and 4 deletions.
19 changes: 15 additions & 4 deletions EnumUtil.cs
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,8 @@ namespace Cysharp.Text
{
internal static class EnumUtil<T>
{
const string InvalidName = "$";

static readonly Dictionary<T, string> names;
static readonly Dictionary<T, byte[]> utf8names;

Expand All @@ -18,14 +20,23 @@ static EnumUtil()
utf8names = new Dictionary<T, byte[]>(enumNames.Length);
for (int i = 0; i < enumNames.Length; i++)
{
names.Add((T)values.GetValue(i), enumNames[i]);
utf8names.Add((T)values.GetValue(i), Encoding.UTF8.GetBytes(enumNames[i]));
if (names.ContainsKey((T)values.GetValue(i)))
{
// already registered = invalid.
names[(T)values.GetValue(i)] = InvalidName;
utf8names[(T)values.GetValue(i)] = Array.Empty<byte>(); // byte[0] == Invalid.
}
else
{
names.Add((T)values.GetValue(i), enumNames[i]);
utf8names.Add((T)values.GetValue(i), Encoding.UTF8.GetBytes(enumNames[i]));
}
}
}

public static bool TryFormatUtf16(T value, Span<char> dest, out int written, ReadOnlySpan<char> _)
{
if (!names.TryGetValue(value, out var v))
if (!names.TryGetValue(value, out var v) || v == InvalidName)
{
v = value.ToString();
}
Expand All @@ -36,7 +47,7 @@ public static bool TryFormatUtf16(T value, Span<char> dest, out int written, Rea

public static bool TryFormatUtf8(T value, Span<byte> dest, out int written, StandardFormat _)
{
if (!utf8names.TryGetValue(value, out var v))
if (!utf8names.TryGetValue(value, out var v) || v.Length == 0)
{
v = Encoding.UTF8.GetBytes(value.ToString());
}
Expand Down

0 comments on commit 8639a96

Please sign in to comment.