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
22 changes: 15 additions & 7 deletions src/Microsoft.OpenApi/Extensions/StringExtensions.cs
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT license.

using System;
using System.Collections.Concurrent;
using System.Diagnostics.CodeAnalysis;
using System.Reflection;
using Microsoft.OpenApi.Attributes;
Expand All @@ -13,6 +13,8 @@ namespace Microsoft.OpenApi.Extensions
/// </summary>
public static class StringExtensions
{
private static readonly ConcurrentDictionary<Type, ConcurrentDictionary<string, object>> EnumDisplayCache = new();

/// <summary>
/// Gets the enum value based on the given enum type and display name.
/// </summary>
Expand All @@ -21,22 +23,28 @@ public static class StringExtensions
{
var type = typeof(T);
if (!type.IsEnum)
{
return default;
}

var displayMap = EnumDisplayCache.GetOrAdd(type, _ => new ConcurrentDictionary<string, object>(StringComparer.OrdinalIgnoreCase));

if (displayMap.TryGetValue(displayName, out var cachedValue))
return (T)cachedValue;


foreach (var field in type.GetFields(BindingFlags.Public | BindingFlags.Static))
{
var displayAttribute = (DisplayAttribute)field.GetCustomAttribute(typeof(DisplayAttribute));
if (displayAttribute != null && displayAttribute.Name == displayName)
var displayAttribute = field.GetCustomAttribute<DisplayAttribute>();
if (displayAttribute != null && displayAttribute.Name.Equals(displayName, StringComparison.OrdinalIgnoreCase))
{
return (T)field.GetValue(null);
var enumValue = (T)field.GetValue(null);
displayMap.TryAdd(displayName, enumValue);
return enumValue;
}
}

return default;
}
internal static string ToFirstCharacterLowerCase(this string input)
=> string.IsNullOrEmpty(input) ? string.Empty : char.ToLowerInvariant(input[0]) + input.Substring(1);
=> string.IsNullOrEmpty(input) ? string.Empty : char.ToLowerInvariant(input[0]) + input.Substring(1);
}
}