Skip to content
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
27 changes: 17 additions & 10 deletions src/Argon/Utilities/EnumUtils.cs
Original file line number Diff line number Diff line change
Expand Up @@ -74,10 +74,12 @@ public static bool TryToString(Type enumType, object value, NamingStrategy? nami
var values = entry.Values;

var index = values.Length - 1;
var stringBuilder = new StringBuilder();
var firstTime = true;
var saveResult = result;

// Collect matched names in forward order to avoid O(n²) StringBuilder.Insert(0, ...)
var matchedCount = 0;
Span<int> matchedIndices = stackalloc int[values.Length];

// We will not optimize this code further to keep it maintainable. There are some boundary checks that can be applied
// to minimize the comparisons required. This code works the same for the best/worst case. In general the number of
// items in an enum are sufficiently small and not worth the optimization.
Expand All @@ -92,14 +94,7 @@ public static bool TryToString(Type enumType, object value, NamingStrategy? nami
if ((result & value) == value)
{
result -= value;
if (!firstTime)
{
stringBuilder.Insert(0, EnumSeparatorString);
}

var resolvedName = resolvedNames[index];
stringBuilder.Insert(0, resolvedName);
firstTime = false;
matchedIndices[matchedCount++] = index;
}

index--;
Expand All @@ -122,6 +117,18 @@ public static bool TryToString(Type enumType, object value, NamingStrategy? nami
return null;
}

var stringBuilder = new StringBuilder();
// matched indices are in reverse order (high-to-low), iterate backwards for forward order
for (var i = matchedCount - 1; i >= 0; i--)
{
if (i < matchedCount - 1)
{
stringBuilder.Append(EnumSeparatorString);
}

stringBuilder.Append(resolvedNames[matchedIndices[i]]);
}

return stringBuilder.ToString(); // Return the string representation
}

Expand Down