forked from SixLabors/ImageSharp.Web
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathEnumConverter.cs
More file actions
70 lines (61 loc) · 2.25 KB
/
Copy pathEnumConverter.cs
File metadata and controls
70 lines (61 loc) · 2.25 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
// Copyright (c) Six Labors.
// Licensed under the Six Labors Split License.
using System.Globalization;
using System.Runtime.CompilerServices;
namespace SixLabors.ImageSharp.Web.Commands.Converters;
/// <summary>
/// The enum converter. Allows conversion to enumerations.
/// </summary>
public sealed class EnumConverter : ICommandConverter<object>
{
/// <inheritdoc/>
public Type Type => typeof(Enum);
/// <inheritdoc/>
/// <remarks>
/// Unlike other converters the <see cref="Type"/> property does not
/// match the <paramref name="propertyType"/> value.
/// This allows us to reuse the same converter for infinite enum types.
/// </remarks>
[MethodImpl(MethodImplOptions.NoInlining)]
public object? ConvertFrom(
CommandParser parser,
CultureInfo culture,
string? value,
Type propertyType)
{
if (string.IsNullOrWhiteSpace(value))
{
return Enum.ToObject(propertyType, 0);
}
try
{
char separator = ConverterUtility.GetListSeparator(culture);
if (value.Contains(separator))
{
long convertedValue = 0;
foreach (string pill in GetStringArray(value, separator))
{
convertedValue |= Convert.ToInt64((Enum)Enum.Parse(propertyType, pill, true), culture);
}
return Enum.ToObject(propertyType, convertedValue);
}
return Enum.Parse(propertyType, value, true);
}
catch
{
// Just return the default value
return Enum.ToObject(propertyType, 0);
}
}
/// <summary>
/// Splits a string by separator to return an array of string values.
/// </summary>
/// <param name="input">The input string to split.</param>
/// <param name="separator">The separator to split string by.</param>
/// <returns>The <see cref="T:String[]"/>.</returns>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
private static string[] GetStringArray(string input, char separator)
// TODO: Can we use StringSplit Enumerator here?
// https://github.com/dotnet/runtime/issues/934
=> input.Split(separator).Select(s => s.Trim()).ToArray();
}