Skip to content

Faster enum -> string resolution #2418

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 1 commit into from
Nov 29, 2016
Merged
Show file tree
Hide file tree
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
156 changes: 115 additions & 41 deletions src/CodeGeneration/ApiGenerator/Views/Enums.Generated.cshtml
Original file line number Diff line number Diff line change
@@ -1,8 +1,8 @@
@using System
@using System.Collections.Generic
@using System.Linq
@using ApiGenerator.Domain
@using ApiGenerator

@functions {
private const string RawSize = "Raw";
private const string SizeEnum = "Size";
Expand All @@ -14,75 +14,149 @@
}
private string CreateCase(string e, string o)
{
var enumValue = (e == SizeEnum && o == string.Empty) ? RawSize : o.ToPascalCase(true);
var enumValue = GetEnumValue(e, o);
return string.Format("case {0}.{1}: return \"{2}\";", e, enumValue, o);
}
private bool IsFlag(string name)
{
return (name.EndsWith("Metric")) || name.EndsWith("Feature");
return name.EndsWith("Metric") || name.EndsWith("Feature");
}

private string CreateEnumKeyValue(string enumName, string value, int index)
{
var enumValue = GetEnumValue(enumName, value);
return string.Format("{3}{{ {0}.{1}, \"{2}\" }},", enumName, enumValue, value, index == 0 ? "\t\t\t\t" : string.Empty);
}

private string GetEnumValue(string enumName, string value)
{
return enumName == SizeEnum && value == string.Empty
? RawSize
: value.ToPascalCase(true);
}
}
using System;
using System.Collections.Generic;
using System.Collections.Concurrent;
using System.Linq;
using System.Text;
using System.Reflection;
using System.Runtime.Serialization;

///This file contains all the typed enums that the client rest api spec exposes.
///This file is automatically generated from https://github.com/elastic/elasticsearch/tree/@Model.Commit/rest-api-spec
///Generated of commit @Model.Commit
namespace Elasticsearch.Net
{
@foreach (EnumDescription e in Model.EnumsInTheSpec)
{
var isFlag = IsFlag(e.Name);
@foreach (EnumDescription e in Model.EnumsInTheSpec)
{
var isFlag = IsFlag(e.Name);
<text>
@(isFlag ? "[Flags]" : string.Empty)public enum @e.Name
@(isFlag ? "[Flags]" : string.Empty)public enum @e.Name
{
@Raw(string.Join(",\r\n\t\t", e.Options.OrderBy(s=>s == "_all" ? 1 : 0).Select((s, i) => CreateEnum(e.Name, s, isFlag ? (int?)i : null ))))
}
</text>
}
@Raw(string.Join(",\r\n\t\t", e.Options.OrderBy(s => s == "_all" ? 1 : 0).Select((s, i) => CreateEnum(e.Name, s, isFlag ? (int?)i : null))))
}</text>
}

public static class KnownEnums
{
private class EnumDictionary : @(Raw("Dictionary<Enum, string>"))
{
public EnumDictionary(int capacity) : base(capacity) {}
public @(Raw("Func<Enum, string>")) Resolver { get; set; }
}

@foreach (EnumDescription e in Model.EnumsInTheSpec)
{
public static string UnknownEnum { get; } = "_UNKNOWN_ENUM_";
public static string Resolve(Enum e)
var isFlag = IsFlag(e.Name);
<text>
public static string GetStringValue(this @(e.Name) enumValue)
{
</text>
if (isFlag)
{
var allOption = e.Options.FirstOrDefault(o => o == "_all");
if (allOption != null)
{
<text>if ((enumValue & @(e.Name).All) != 0) return "_all";</text>
}
<text>var list = new @(Raw("List<string>()"));</text>
foreach (var option in e.Options.Where(o => o != "_all"))
{
<text>if ((enumValue & @(e.Name).@(GetEnumValue(e.Name, option))) != 0) list.Add("@(option)");</text>
}
<text>return string.Join(",", list);
}</text>
}
else
{
<text>switch (enumValue)
{
@Raw(string.Join("\r\n\t\t\t\t", e.Options.Select(o => CreateCase(e.Name, o))))
}
throw new ArgumentException($"'{enumValue.ToString()}' is not a valid value for enum '@(e.Name)'");
}</text>
}
}

private static readonly @(Raw("ConcurrentDictionary<Type, Func<Enum, string>>")) EnumStringResolvers =
new @(Raw("ConcurrentDictionary<Type, Func<Enum, string>>"))();

static KnownEnums()
{
@foreach (EnumDescription e in Model.EnumsInTheSpec)
{
<text>EnumStringResolvers.TryAdd(typeof(@(e.Name)), (e) => GetStringValue((@(e.Name))e));</text>
}
}

public static string GetStringValue(this Enum e)
{
var type = e.GetType();
var resolver = EnumStringResolvers.GetOrAdd(type, GetEnumStringResolver);
return resolver(e);
}

private static @Raw("Func<Enum, string>") GetEnumStringResolver(Type type)
{
@foreach (EnumDescription e in Model.EnumsInTheSpec)
var values = Enum.GetValues(type);
var dictionary = new EnumDictionary(values.Length);

for (int index = 0; index < values.Length; index++)
{
var isFlag = IsFlag(e.Name);
<text>if (e is @e.Name)
{ </text>
if (isFlag)
var value = values.GetValue(index);
#if DOTNETCORE
var info = type.GetTypeInfo().GetDeclaredField(value.ToString());
#else
var info = type.GetField(value.ToString());
#endif
var da = (EnumMemberAttribute[])info.GetCustomAttributes(typeof(EnumMemberAttribute), false);
var stringValue = da.Length > 0 ? da[0].Value : Enum.GetName(type, value);
dictionary.Add((Enum)value, stringValue);
}

#if DOTNETCORE
var isFlag = type.GetTypeInfo().GetCustomAttributes(typeof(FlagsAttribute), false).Any();
#else
var isFlag = type.GetCustomAttributes(typeof(FlagsAttribute), false).Length > 0;
#endif

return (e) =>
{
<text>var list = new @(Raw("List<string>()"));</text>
foreach(var option in e.Options.OrderBy(s=>s == "_all" ? 1 : 0))
if (isFlag)
{
if (option != "_all")
var list = new @(Raw("List<string>()"));
foreach(var kv in dictionary)
{
<text>if (e.HasFlag(@(e.Name).@(option.ToPascalCase(true)))) list.Add("@(option)");</text>
}
else
{
<text>if (e.HasFlag(@(e.Name).@(option.ToPascalCase(true)))) return "@(option)";</text>
if (e.HasFlag(kv.Key)) list.Add(kv.Value);
}
return string.Join(",", list);
}
<text>return string.Join(",", list);</text>
}
else
{
<text>switch((@e.Name)e)
else
{
@Raw(string.Join("\r\n\t\t\t\t\t", e.Options.Select(o =>CreateCase(e.Name,o))))
}</text>
}
<text>
}
</text>
}
return UnknownEnum;
return dictionary[e];
}
};
}
}
}

}
2 changes: 1 addition & 1 deletion src/Elasticsearch.Net/Connection/HttpConnection.cs
Original file line number Diff line number Diff line change
Expand Up @@ -66,7 +66,7 @@ protected virtual HttpWebRequest CreateWebRequest(RequestData requestData)
//see: https://github.com/elasticsearch/elasticsearch-net/issues/562
var m = requestData.Method.GetStringValue();
request.Method = m;
if (m != "head" && m != "get" && (requestData.PostData == null))
if (m != "HEAD" && m != "GET" && (requestData.PostData == null))
request.ContentLength = 0;

return request;
Expand Down
2 changes: 1 addition & 1 deletion src/Elasticsearch.Net/Connection/HttpMethod.cs
Original file line number Diff line number Diff line change
Expand Up @@ -17,4 +17,4 @@ public enum HttpMethod
[EnumMember(Value = "HEAD")]
HEAD
}
}
}
Loading