| | | 1 | | // Licensed to the .NET Foundation under one or more agreements. |
| | | 2 | | // The .NET Foundation licenses this file to you under the MIT license. |
| | | 3 | | |
| | | 4 | | using System.Buffers; |
| | | 5 | | using System.Collections.Concurrent; |
| | | 6 | | using System.Collections.Generic; |
| | | 7 | | using System.Diagnostics; |
| | | 8 | | using System.Reflection; |
| | | 9 | | using System.Runtime.CompilerServices; |
| | | 10 | | using System.Text.Encodings.Web; |
| | | 11 | | using System.Text.Json.Nodes; |
| | | 12 | | using System.Text.Json.Schema; |
| | | 13 | | |
| | | 14 | | namespace System.Text.Json.Serialization.Converters |
| | | 15 | | { |
| | | 16 | | internal sealed class EnumConverter<T> : JsonPrimitiveConverter<T> // Do not rename FQN (legacy schema generation) |
| | | 17 | | where T : struct, Enum |
| | | 18 | | { |
| | 2 | 19 | | private static readonly TypeCode s_enumTypeCode = Type.GetTypeCode(typeof(T)); |
| | | 20 | | |
| | | 21 | | // Odd type codes are conveniently signed types (for enum backing types). |
| | 2 | 22 | | private static readonly bool s_isSignedEnum = ((int)s_enumTypeCode % 2) == 1; |
| | 2 | 23 | | private static readonly bool s_isFlagsEnum = typeof(T).IsDefined(typeof(FlagsAttribute), inherit: false); |
| | | 24 | | |
| | | 25 | | private readonly EnumConverterOptions _converterOptions; // Do not rename (legacy schema generation) |
| | | 26 | | private readonly JsonNamingPolicy? _namingPolicy; // Do not rename (legacy schema generation) |
| | | 27 | | |
| | | 28 | | /// <summary> |
| | | 29 | | /// Stores metadata for the individual fields declared on the enum. |
| | | 30 | | /// </summary> |
| | | 31 | | private readonly EnumFieldInfo[] _enumFieldInfo; |
| | | 32 | | |
| | | 33 | | /// <summary> |
| | | 34 | | /// Defines a case-insensitive index of enum field names to their metadata. |
| | | 35 | | /// In case of casing conflicts, extra fields are appended to a list in the value. |
| | | 36 | | /// This is the main dictionary that is queried by the enum parser implementation. |
| | | 37 | | /// </summary> |
| | | 38 | | private readonly Dictionary<string, EnumFieldInfo> _enumFieldInfoIndex; |
| | | 39 | | |
| | | 40 | | /// <summary> |
| | | 41 | | /// Holds a cache from enum value to formatted UTF-8 text including flag combinations. |
| | | 42 | | /// <see cref="ulong"/> is as the key used rather than <typeparamref name="T"/> given measurements that |
| | | 43 | | /// show private memory savings when a single type is used https://github.com/dotnet/runtime/pull/36726#discussi |
| | | 44 | | /// </summary> |
| | | 45 | | private readonly ConcurrentDictionary<ulong, JsonEncodedText> _nameCacheForWriting; |
| | | 46 | | |
| | | 47 | | /// <summary> |
| | | 48 | | /// Holds a mapping from input text to enum values including flag combinations and alternative casings. |
| | | 49 | | /// </summary> |
| | | 50 | | private readonly ConcurrentDictionary<string, ulong> _nameCacheForReading; |
| | | 51 | | |
| | | 52 | | // This is used to prevent flooding the cache due to exponential bitwise combinations of flags. |
| | | 53 | | // Since multiple threads can add to the cache, a few more values might be added. |
| | | 54 | | private const int NameCacheSizeSoftLimit = 64; |
| | | 55 | | |
| | 538 | 56 | | public EnumConverter(EnumConverterOptions converterOptions, JsonNamingPolicy? namingPolicy, JsonSerializerOption |
| | 538 | 57 | | { |
| | 538 | 58 | | Debug.Assert(EnumConverterFactory.Helpers.IsSupportedTypeCode(s_enumTypeCode)); |
| | | 59 | | |
| | 538 | 60 | | _converterOptions = converterOptions; |
| | 538 | 61 | | _namingPolicy = namingPolicy; |
| | 538 | 62 | | _enumFieldInfo = ResolveEnumFields(namingPolicy); |
| | 538 | 63 | | _enumFieldInfoIndex = new(StringComparer.OrdinalIgnoreCase); |
| | | 64 | | |
| | 538 | 65 | | _nameCacheForWriting = new(); |
| | 538 | 66 | | _nameCacheForReading = new(StringComparer.Ordinal); |
| | | 67 | | |
| | 538 | 68 | | JavaScriptEncoder? encoder = options.Encoder; |
| | 1614 | 69 | | foreach (EnumFieldInfo fieldInfo in _enumFieldInfo) |
| | 0 | 70 | | { |
| | 0 | 71 | | AddToEnumFieldIndex(fieldInfo); |
| | | 72 | | |
| | 0 | 73 | | JsonEncodedText encodedName = JsonEncodedText.Encode(fieldInfo.JsonName, encoder); |
| | 0 | 74 | | _nameCacheForWriting.TryAdd(fieldInfo.Key, encodedName); |
| | 0 | 75 | | _nameCacheForReading.TryAdd(fieldInfo.JsonName, fieldInfo.Key); |
| | 0 | 76 | | } |
| | | 77 | | |
| | 538 | 78 | | if (namingPolicy != null) |
| | 0 | 79 | | { |
| | | 80 | | // Additionally populate the field index with the default names of fields that used a naming policy. |
| | | 81 | | // This is done to preserve backward compat: default names should still be recognized by the parser. |
| | 0 | 82 | | foreach (EnumFieldInfo fieldInfo in _enumFieldInfo) |
| | 0 | 83 | | { |
| | 0 | 84 | | if (fieldInfo.Kind is EnumFieldNameKind.NamingPolicy) |
| | 0 | 85 | | { |
| | 0 | 86 | | AddToEnumFieldIndex(new EnumFieldInfo(fieldInfo.Key, EnumFieldNameKind.Default, fieldInfo.Origin |
| | 0 | 87 | | } |
| | 0 | 88 | | } |
| | 0 | 89 | | } |
| | | 90 | | |
| | | 91 | | void AddToEnumFieldIndex(EnumFieldInfo fieldInfo) |
| | 0 | 92 | | { |
| | 0 | 93 | | if (!_enumFieldInfoIndex.TryAdd(fieldInfo.JsonName, fieldInfo)) |
| | 0 | 94 | | { |
| | | 95 | | // We have a casing conflict, append field to the existing entry. |
| | 0 | 96 | | EnumFieldInfo existingFieldInfo = _enumFieldInfoIndex[fieldInfo.JsonName]; |
| | 0 | 97 | | existingFieldInfo.AppendConflictingField(fieldInfo); |
| | 0 | 98 | | } |
| | 0 | 99 | | } |
| | 538 | 100 | | } |
| | | 101 | | |
| | | 102 | | public override T Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) |
| | 1430 | 103 | | { |
| | 1430 | 104 | | switch (reader.TokenType) |
| | | 105 | | { |
| | 630 | 106 | | case JsonTokenType.String when (_converterOptions & EnumConverterOptions.AllowStrings) != 0: |
| | 342 | 107 | | if (TryParseEnumFromString(ref reader, out T result)) |
| | 26 | 108 | | { |
| | 26 | 109 | | return result; |
| | | 110 | | } |
| | 198 | 111 | | break; |
| | | 112 | | |
| | 296 | 113 | | case JsonTokenType.Number when (_converterOptions & EnumConverterOptions.AllowNumbers) != 0: |
| | 296 | 114 | | switch (s_enumTypeCode) |
| | | 115 | | { |
| | 460 | 116 | | case TypeCode.Int32 when reader.TryGetInt32(out int int32): return (T)(object)int32; |
| | 0 | 117 | | case TypeCode.UInt32 when reader.TryGetUInt32(out uint uint32): return (T)(object)uint32; |
| | 0 | 118 | | case TypeCode.Int64 when reader.TryGetInt64(out long int64): return (T)(object)int64; |
| | 0 | 119 | | case TypeCode.UInt64 when reader.TryGetUInt64(out ulong uint64): return (T)(object)uint64; |
| | 0 | 120 | | case TypeCode.Byte when reader.TryGetByte(out byte ubyte8): return (T)(object)ubyte8; |
| | 0 | 121 | | case TypeCode.SByte when reader.TryGetSByte(out sbyte byte8): return (T)(object)byte8; |
| | 0 | 122 | | case TypeCode.Int16 when reader.TryGetInt16(out short int16): return (T)(object)int16; |
| | 0 | 123 | | case TypeCode.UInt16 when reader.TryGetUInt16(out ushort uint16): return (T)(object)uint16; |
| | | 124 | | } |
| | 132 | 125 | | break; |
| | | 126 | | } |
| | | 127 | | |
| | 1122 | 128 | | ThrowHelper.ThrowJsonException(); |
| | | 129 | | return default; |
| | 190 | 130 | | } |
| | | 131 | | |
| | | 132 | | public override void Write(Utf8JsonWriter writer, T value, JsonSerializerOptions options) |
| | 0 | 133 | | { |
| | 0 | 134 | | EnumConverterOptions converterOptions = _converterOptions; |
| | 0 | 135 | | if ((converterOptions & EnumConverterOptions.AllowStrings) != 0) |
| | 0 | 136 | | { |
| | 0 | 137 | | ulong key = ConvertToUInt64(value); |
| | | 138 | | |
| | 0 | 139 | | if (_nameCacheForWriting.TryGetValue(key, out JsonEncodedText formatted)) |
| | 0 | 140 | | { |
| | 0 | 141 | | writer.WriteStringValue(formatted); |
| | 0 | 142 | | return; |
| | | 143 | | } |
| | | 144 | | |
| | 0 | 145 | | if (IsDefinedValueOrCombinationOfValues(key)) |
| | 0 | 146 | | { |
| | 0 | 147 | | Debug.Assert(s_isFlagsEnum, "Should only be entered by flags enums."); |
| | 0 | 148 | | string stringValue = FormatEnumAsString(key, value, dictionaryKeyPolicy: null); |
| | 0 | 149 | | if (_nameCacheForWriting.Count < NameCacheSizeSoftLimit) |
| | 0 | 150 | | { |
| | 0 | 151 | | formatted = JsonEncodedText.Encode(stringValue, options.Encoder); |
| | 0 | 152 | | writer.WriteStringValue(formatted); |
| | 0 | 153 | | _nameCacheForWriting.TryAdd(key, formatted); |
| | 0 | 154 | | } |
| | | 155 | | else |
| | 0 | 156 | | { |
| | | 157 | | // We also do not create a JsonEncodedText instance here because passing the string |
| | | 158 | | // directly to the writer is cheaper than creating one and not caching it for reuse. |
| | 0 | 159 | | writer.WriteStringValue(stringValue); |
| | 0 | 160 | | } |
| | | 161 | | |
| | 0 | 162 | | return; |
| | | 163 | | } |
| | 0 | 164 | | } |
| | | 165 | | |
| | 0 | 166 | | if ((converterOptions & EnumConverterOptions.AllowNumbers) == 0) |
| | 0 | 167 | | { |
| | 0 | 168 | | ThrowHelper.ThrowJsonException(); |
| | | 169 | | } |
| | | 170 | | |
| | 0 | 171 | | if (s_isSignedEnum) |
| | 0 | 172 | | { |
| | 0 | 173 | | writer.WriteNumberValue(ConvertToInt64(value)); |
| | 0 | 174 | | } |
| | | 175 | | else |
| | 0 | 176 | | { |
| | 0 | 177 | | writer.WriteNumberValue(ConvertToUInt64(value)); |
| | 0 | 178 | | } |
| | 0 | 179 | | } |
| | | 180 | | |
| | | 181 | | internal override T ReadAsPropertyNameCore(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions |
| | 0 | 182 | | { |
| | | 183 | | // NB JsonSerializerOptions.DictionaryKeyPolicy is ignored on deserialization. |
| | | 184 | | // This is true for all converters that implement dictionary key serialization. |
| | | 185 | | |
| | 0 | 186 | | if (!TryParseEnumFromString(ref reader, out T result)) |
| | 0 | 187 | | { |
| | 0 | 188 | | ThrowHelper.ThrowJsonException(); |
| | | 189 | | } |
| | | 190 | | |
| | 0 | 191 | | return result; |
| | 0 | 192 | | } |
| | | 193 | | |
| | | 194 | | internal override void WriteAsPropertyNameCore(Utf8JsonWriter writer, T value, JsonSerializerOptions options, bo |
| | 0 | 195 | | { |
| | 0 | 196 | | JsonNamingPolicy? dictionaryKeyPolicy = options.DictionaryKeyPolicy is { } dkp && dkp != _namingPolicy ? dkp |
| | 0 | 197 | | ulong key = ConvertToUInt64(value); |
| | | 198 | | |
| | 0 | 199 | | if (dictionaryKeyPolicy is null && _nameCacheForWriting.TryGetValue(key, out JsonEncodedText formatted)) |
| | 0 | 200 | | { |
| | 0 | 201 | | writer.WritePropertyName(formatted); |
| | 0 | 202 | | return; |
| | | 203 | | } |
| | | 204 | | |
| | 0 | 205 | | if (IsDefinedValueOrCombinationOfValues(key)) |
| | 0 | 206 | | { |
| | 0 | 207 | | Debug.Assert(s_isFlagsEnum || dictionaryKeyPolicy != null, "Should only be entered by flags enums or dic |
| | 0 | 208 | | string stringValue = FormatEnumAsString(key, value, dictionaryKeyPolicy); |
| | 0 | 209 | | if (dictionaryKeyPolicy is null && _nameCacheForWriting.Count < NameCacheSizeSoftLimit) |
| | 0 | 210 | | { |
| | | 211 | | // Only attempt to cache if there is no dictionary key policy. |
| | 0 | 212 | | formatted = JsonEncodedText.Encode(stringValue, options.Encoder); |
| | 0 | 213 | | writer.WritePropertyName(formatted); |
| | 0 | 214 | | _nameCacheForWriting.TryAdd(key, formatted); |
| | 0 | 215 | | } |
| | | 216 | | else |
| | 0 | 217 | | { |
| | | 218 | | // We also do not create a JsonEncodedText instance here because passing the string |
| | | 219 | | // directly to the writer is cheaper than creating one and not caching it for reuse. |
| | 0 | 220 | | writer.WritePropertyName(stringValue); |
| | 0 | 221 | | } |
| | | 222 | | |
| | 0 | 223 | | return; |
| | | 224 | | } |
| | | 225 | | |
| | 0 | 226 | | if (s_isSignedEnum) |
| | 0 | 227 | | { |
| | 0 | 228 | | writer.WritePropertyName(ConvertToInt64(value)); |
| | 0 | 229 | | } |
| | | 230 | | else |
| | 0 | 231 | | { |
| | 0 | 232 | | writer.WritePropertyName(key); |
| | 0 | 233 | | } |
| | 0 | 234 | | } |
| | | 235 | | |
| | | 236 | | private bool TryParseEnumFromString(ref Utf8JsonReader reader, out T result) |
| | 342 | 237 | | { |
| | 342 | 238 | | Debug.Assert(reader.TokenType is JsonTokenType.String or JsonTokenType.PropertyName); |
| | | 239 | | |
| | 342 | 240 | | int bufferLength = reader.ValueLength; |
| | 342 | 241 | | char[]? rentedBuffer = null; |
| | | 242 | | bool success; |
| | | 243 | | |
| | 342 | 244 | | Span<char> charBuffer = bufferLength <= JsonConstants.StackallocCharThreshold |
| | 342 | 245 | | ? stackalloc char[JsonConstants.StackallocCharThreshold] |
| | 342 | 246 | | : (rentedBuffer = ArrayPool<char>.Shared.Rent(bufferLength)); |
| | | 247 | | |
| | 342 | 248 | | int charsWritten = reader.CopyString(charBuffer); |
| | 224 | 249 | | charBuffer = charBuffer.Slice(0, charsWritten); |
| | | 250 | | #if NET |
| | 224 | 251 | | ReadOnlySpan<char> source = charBuffer.Trim(); |
| | 224 | 252 | | ConcurrentDictionary<string, ulong>.AlternateLookup<ReadOnlySpan<char>> lookup = _nameCacheForReading.GetAlt |
| | | 253 | | #else |
| | | 254 | | string source = ((ReadOnlySpan<char>)charBuffer).Trim().ToString(); |
| | | 255 | | ConcurrentDictionary<string, ulong> lookup = _nameCacheForReading; |
| | | 256 | | #endif |
| | 224 | 257 | | if (lookup.TryGetValue(source, out ulong key)) |
| | 15 | 258 | | { |
| | 15 | 259 | | result = ConvertFromUInt64(key); |
| | 15 | 260 | | success = true; |
| | 15 | 261 | | goto End; |
| | | 262 | | } |
| | | 263 | | |
| | 209 | 264 | | if (JsonHelpers.IntegerRegex.IsMatch(source)) |
| | 11 | 265 | | { |
| | | 266 | | // We found an integer that is not an enum field name. |
| | 11 | 267 | | if ((_converterOptions & EnumConverterOptions.AllowNumbers) != 0) |
| | 11 | 268 | | { |
| | 11 | 269 | | success = Enum.TryParse(source, out result); |
| | 11 | 270 | | } |
| | | 271 | | else |
| | 0 | 272 | | { |
| | 0 | 273 | | result = default; |
| | 0 | 274 | | success = false; |
| | 0 | 275 | | } |
| | 11 | 276 | | } |
| | | 277 | | else |
| | 198 | 278 | | { |
| | 198 | 279 | | success = TryParseNamedEnum(source, out result); |
| | 198 | 280 | | } |
| | | 281 | | |
| | 209 | 282 | | if (success && _nameCacheForReading.Count < NameCacheSizeSoftLimit) |
| | 11 | 283 | | { |
| | 11 | 284 | | lookup.TryAdd(source, ConvertToUInt64(result)); |
| | 11 | 285 | | } |
| | | 286 | | |
| | 224 | 287 | | End: |
| | 224 | 288 | | if (rentedBuffer != null) |
| | 0 | 289 | | { |
| | 0 | 290 | | charBuffer.Clear(); |
| | 0 | 291 | | ArrayPool<char>.Shared.Return(rentedBuffer); |
| | 0 | 292 | | } |
| | | 293 | | |
| | 224 | 294 | | return success; |
| | 224 | 295 | | } |
| | | 296 | | |
| | | 297 | | private bool TryParseNamedEnum( |
| | | 298 | | #if NET |
| | | 299 | | ReadOnlySpan<char> source, |
| | | 300 | | #else |
| | | 301 | | string source, |
| | | 302 | | #endif |
| | | 303 | | out T result) |
| | 198 | 304 | | { |
| | | 305 | | #if NET |
| | 198 | 306 | | Dictionary<string, EnumFieldInfo>.AlternateLookup<ReadOnlySpan<char>> lookup = _enumFieldInfoIndex.GetAltern |
| | 198 | 307 | | ReadOnlySpan<char> rest = source; |
| | | 308 | | #else |
| | | 309 | | Dictionary<string, EnumFieldInfo> lookup = _enumFieldInfoIndex; |
| | | 310 | | ReadOnlySpan<char> rest = source.AsSpan(); |
| | | 311 | | #endif |
| | 198 | 312 | | ulong key = 0; |
| | | 313 | | |
| | | 314 | | do |
| | 198 | 315 | | { |
| | | 316 | | ReadOnlySpan<char> next; |
| | 198 | 317 | | int i = rest.IndexOf(','); |
| | 198 | 318 | | if (i == -1) |
| | 198 | 319 | | { |
| | 198 | 320 | | next = rest; |
| | 198 | 321 | | rest = default; |
| | 198 | 322 | | } |
| | | 323 | | else |
| | 0 | 324 | | { |
| | 0 | 325 | | next = rest.Slice(0, i).TrimEnd(); |
| | 0 | 326 | | rest = rest.Slice(i + 1).TrimStart(); |
| | 0 | 327 | | } |
| | | 328 | | |
| | 198 | 329 | | if (lookup.TryGetValue( |
| | 198 | 330 | | #if NET |
| | 198 | 331 | | next, |
| | 198 | 332 | | #else |
| | 198 | 333 | | next.ToString(), |
| | 198 | 334 | | #endif |
| | 198 | 335 | | out EnumFieldInfo? firstResult) && |
| | 198 | 336 | | firstResult.GetMatchingField(next) is EnumFieldInfo match) |
| | 0 | 337 | | { |
| | 0 | 338 | | key |= match.Key; |
| | 0 | 339 | | continue; |
| | | 340 | | } |
| | | 341 | | |
| | 198 | 342 | | result = default; |
| | 198 | 343 | | return false; |
| | | 344 | | |
| | 0 | 345 | | } while (!rest.IsEmpty); |
| | | 346 | | |
| | 0 | 347 | | result = ConvertFromUInt64(key); |
| | 0 | 348 | | return true; |
| | 198 | 349 | | } |
| | | 350 | | |
| | | 351 | | private static ulong ConvertToUInt64(T value) |
| | 11 | 352 | | { |
| | 11 | 353 | | return s_enumTypeCode switch |
| | 11 | 354 | | { |
| | 11 | 355 | | TypeCode.Int32 => (ulong)(int)(object)value, |
| | 0 | 356 | | TypeCode.UInt32 => (uint)(object)value, |
| | 0 | 357 | | TypeCode.Int64 => (ulong)(long)(object)value, |
| | 0 | 358 | | TypeCode.UInt64 => (ulong)(object)value, |
| | 0 | 359 | | TypeCode.Int16 => (ulong)(short)(object)value, |
| | 0 | 360 | | TypeCode.UInt16 => (ushort)(object)value, |
| | 0 | 361 | | TypeCode.SByte => (ulong)(sbyte)(object)value, |
| | 0 | 362 | | _ => (byte)(object)value |
| | 11 | 363 | | }; |
| | 11 | 364 | | } |
| | | 365 | | |
| | | 366 | | private static long ConvertToInt64(T value) |
| | 0 | 367 | | { |
| | 0 | 368 | | Debug.Assert(s_isSignedEnum); |
| | 0 | 369 | | return s_enumTypeCode switch |
| | 0 | 370 | | { |
| | 0 | 371 | | TypeCode.Int32 => (int)(object)value, |
| | 0 | 372 | | TypeCode.Int64 => (long)(object)value, |
| | 0 | 373 | | TypeCode.Int16 => (short)(object)value, |
| | 0 | 374 | | _ => (sbyte)(object)value, |
| | 0 | 375 | | }; |
| | 0 | 376 | | } |
| | | 377 | | |
| | | 378 | | private static T ConvertFromUInt64(ulong value) |
| | 15 | 379 | | { |
| | 15 | 380 | | return s_enumTypeCode switch |
| | 15 | 381 | | { |
| | 15 | 382 | | TypeCode.Int32 => (T)(object)(int)value, |
| | 0 | 383 | | TypeCode.UInt32 => (T)(object)(uint)value, |
| | 0 | 384 | | TypeCode.Int64 => (T)(object)(long)value, |
| | 0 | 385 | | TypeCode.UInt64 => (T)(object)value, |
| | 0 | 386 | | TypeCode.Int16 => (T)(object)(short)value, |
| | 0 | 387 | | TypeCode.UInt16 => (T)(object)(ushort)value, |
| | 0 | 388 | | TypeCode.SByte => (T)(object)(sbyte)value, |
| | 0 | 389 | | _ => (T)(object)(byte)value |
| | 15 | 390 | | }; |
| | 15 | 391 | | } |
| | | 392 | | |
| | | 393 | | /// <summary> |
| | | 394 | | /// Attempt to format the enum value as a comma-separated string of flag values, or returns false if not a valid |
| | | 395 | | /// </summary> |
| | | 396 | | private string FormatEnumAsString(ulong key, T value, JsonNamingPolicy? dictionaryKeyPolicy) |
| | 0 | 397 | | { |
| | 0 | 398 | | Debug.Assert(IsDefinedValueOrCombinationOfValues(key), "must only be invoked against valid enum values."); |
| | 0 | 399 | | Debug.Assert( |
| | 0 | 400 | | s_isFlagsEnum || (dictionaryKeyPolicy is not null && Enum.IsDefined(typeof(T), value)), |
| | 0 | 401 | | "must either be a flag type or computing a dictionary key policy."); |
| | | 402 | | |
| | 0 | 403 | | if (s_isFlagsEnum) |
| | 0 | 404 | | { |
| | 0 | 405 | | using ValueStringBuilder sb = new(stackalloc char[JsonConstants.StackallocCharThreshold]); |
| | 0 | 406 | | ulong remainingBits = key; |
| | | 407 | | |
| | 0 | 408 | | foreach (EnumFieldInfo enumField in _enumFieldInfo) |
| | 0 | 409 | | { |
| | 0 | 410 | | ulong fieldKey = enumField.Key; |
| | 0 | 411 | | if (fieldKey == 0 ? key == 0 : (remainingBits & fieldKey) == fieldKey) |
| | 0 | 412 | | { |
| | 0 | 413 | | remainingBits &= ~fieldKey; |
| | 0 | 414 | | string name = dictionaryKeyPolicy is not null |
| | 0 | 415 | | ? ResolveAndValidateJsonName(enumField.OriginalName, dictionaryKeyPolicy, enumField.Kind) |
| | 0 | 416 | | : enumField.JsonName; |
| | | 417 | | |
| | 0 | 418 | | if (sb.Length > 0) |
| | 0 | 419 | | { |
| | 0 | 420 | | sb.Append(", "); |
| | 0 | 421 | | } |
| | | 422 | | |
| | 0 | 423 | | sb.Append(name); |
| | | 424 | | |
| | 0 | 425 | | if (remainingBits == 0) |
| | 0 | 426 | | { |
| | 0 | 427 | | break; |
| | | 428 | | } |
| | 0 | 429 | | } |
| | 0 | 430 | | } |
| | | 431 | | |
| | 0 | 432 | | Debug.Assert(remainingBits == 0 && sb.Length > 0, "unexpected remaining bits or empty string."); |
| | 0 | 433 | | return sb.ToString(); |
| | | 434 | | } |
| | | 435 | | else |
| | 0 | 436 | | { |
| | 0 | 437 | | Debug.Assert(dictionaryKeyPolicy != null); |
| | | 438 | | |
| | 0 | 439 | | foreach (EnumFieldInfo enumField in _enumFieldInfo) |
| | 0 | 440 | | { |
| | | 441 | | // Search for an exact match and apply the key policy. |
| | 0 | 442 | | if (enumField.Key == key) |
| | 0 | 443 | | { |
| | 0 | 444 | | return ResolveAndValidateJsonName(enumField.OriginalName, dictionaryKeyPolicy, enumField.Kind); |
| | | 445 | | } |
| | 0 | 446 | | } |
| | | 447 | | |
| | 0 | 448 | | Debug.Fail("should not have been reached."); |
| | | 449 | | return null; |
| | | 450 | | } |
| | 0 | 451 | | } |
| | | 452 | | |
| | | 453 | | private bool IsDefinedValueOrCombinationOfValues(ulong key) |
| | 0 | 454 | | { |
| | 0 | 455 | | if (s_isFlagsEnum) |
| | 0 | 456 | | { |
| | 0 | 457 | | ulong remainingBits = key; |
| | | 458 | | |
| | 0 | 459 | | foreach (EnumFieldInfo fieldInfo in _enumFieldInfo) |
| | 0 | 460 | | { |
| | 0 | 461 | | ulong fieldKey = fieldInfo.Key; |
| | 0 | 462 | | if (fieldKey == 0 ? key == 0 : (remainingBits & fieldKey) == fieldKey) |
| | 0 | 463 | | { |
| | 0 | 464 | | remainingBits &= ~fieldKey; |
| | | 465 | | |
| | 0 | 466 | | if (remainingBits == 0) |
| | 0 | 467 | | { |
| | 0 | 468 | | return true; |
| | | 469 | | } |
| | 0 | 470 | | } |
| | 0 | 471 | | } |
| | | 472 | | |
| | 0 | 473 | | return false; |
| | | 474 | | } |
| | | 475 | | else |
| | 0 | 476 | | { |
| | 0 | 477 | | foreach (EnumFieldInfo fieldInfo in _enumFieldInfo) |
| | 0 | 478 | | { |
| | 0 | 479 | | if (fieldInfo.Key == key) |
| | 0 | 480 | | { |
| | 0 | 481 | | return true; |
| | | 482 | | } |
| | 0 | 483 | | } |
| | | 484 | | |
| | 0 | 485 | | return false; |
| | | 486 | | } |
| | 0 | 487 | | } |
| | | 488 | | |
| | | 489 | | internal override JsonSchema? GetSchema(JsonNumberHandling numberHandling) |
| | 0 | 490 | | { |
| | 0 | 491 | | if ((_converterOptions & EnumConverterOptions.AllowStrings) != 0) |
| | 0 | 492 | | { |
| | | 493 | | // This explicitly ignores the integer component in converters configured as AllowNumbers | AllowStrings |
| | | 494 | | // which is the default for JsonStringEnumConverter. This sacrifices some precision in the schema for si |
| | | 495 | | |
| | 0 | 496 | | if (s_isFlagsEnum) |
| | 0 | 497 | | { |
| | | 498 | | // Do not report enum values in case of flags. |
| | 0 | 499 | | return new() { Type = JsonSchemaType.String }; |
| | | 500 | | } |
| | | 501 | | |
| | 0 | 502 | | JsonArray enumValues = []; |
| | 0 | 503 | | foreach (EnumFieldInfo fieldInfo in _enumFieldInfo) |
| | 0 | 504 | | { |
| | 0 | 505 | | enumValues.Add((JsonNode)fieldInfo.JsonName); |
| | 0 | 506 | | } |
| | | 507 | | |
| | 0 | 508 | | return new() { Enum = enumValues }; |
| | | 509 | | } |
| | | 510 | | |
| | 0 | 511 | | return new() { Type = JsonSchemaType.Integer }; |
| | 0 | 512 | | } |
| | | 513 | | |
| | | 514 | | private static EnumFieldInfo[] ResolveEnumFields(JsonNamingPolicy? namingPolicy) |
| | 538 | 515 | | { |
| | | 516 | | #if NET |
| | 538 | 517 | | string[] names = Enum.GetNames<T>(); |
| | 538 | 518 | | T[] values = Enum.GetValues<T>(); |
| | | 519 | | #else |
| | | 520 | | string[] names = Enum.GetNames(typeof(T)); |
| | | 521 | | T[] values = (T[])Enum.GetValues(typeof(T)); |
| | | 522 | | #endif |
| | 538 | 523 | | Debug.Assert(names.Length == values.Length); |
| | | 524 | | |
| | 538 | 525 | | Dictionary<string, string>? enumMemberAttributes = null; |
| | 1614 | 526 | | foreach (FieldInfo field in typeof(T).GetFields(BindingFlags.Public | BindingFlags.Static)) |
| | 0 | 527 | | { |
| | 0 | 528 | | if (field.GetCustomAttribute<JsonStringEnumMemberNameAttribute>() is { } attribute) |
| | 0 | 529 | | { |
| | 0 | 530 | | (enumMemberAttributes ??= new(StringComparer.Ordinal)).Add(field.Name, attribute.Name); |
| | 0 | 531 | | } |
| | 0 | 532 | | } |
| | | 533 | | |
| | 538 | 534 | | var enumFields = new EnumFieldInfo[names.Length]; |
| | 1076 | 535 | | for (int i = 0; i < names.Length; i++) |
| | 0 | 536 | | { |
| | 0 | 537 | | string originalName = names[i]; |
| | 0 | 538 | | T value = values[i]; |
| | 0 | 539 | | ulong key = ConvertToUInt64(value); |
| | | 540 | | EnumFieldNameKind kind; |
| | | 541 | | |
| | 0 | 542 | | if (enumMemberAttributes != null && enumMemberAttributes.TryGetValue(originalName, out string? attribute |
| | 0 | 543 | | { |
| | 0 | 544 | | originalName = attributeName; |
| | 0 | 545 | | kind = EnumFieldNameKind.Attribute; |
| | 0 | 546 | | } |
| | | 547 | | else |
| | 0 | 548 | | { |
| | 0 | 549 | | kind = namingPolicy != null ? EnumFieldNameKind.NamingPolicy : EnumFieldNameKind.Default; |
| | 0 | 550 | | } |
| | | 551 | | |
| | 0 | 552 | | string jsonName = ResolveAndValidateJsonName(originalName, namingPolicy, kind); |
| | 0 | 553 | | enumFields[i] = new EnumFieldInfo(key, kind, originalName, jsonName); |
| | 0 | 554 | | } |
| | | 555 | | |
| | 538 | 556 | | if (s_isFlagsEnum) |
| | 0 | 557 | | { |
| | | 558 | | // Perform topological sort for flags enums to ensure values that are supersets of other values come fir |
| | | 559 | | // This is important for flags enums to ensure proper parsing and formatting. |
| | 0 | 560 | | enumFields = TopologicalSortEnumFields(enumFields); |
| | 0 | 561 | | } |
| | | 562 | | |
| | 538 | 563 | | return enumFields; |
| | 538 | 564 | | } |
| | | 565 | | |
| | | 566 | | private static string ResolveAndValidateJsonName(string name, JsonNamingPolicy? namingPolicy, EnumFieldNameKind |
| | 0 | 567 | | { |
| | 0 | 568 | | if (kind is not EnumFieldNameKind.Attribute && namingPolicy is not null) |
| | 0 | 569 | | { |
| | | 570 | | // Do not apply a naming policy to names that are explicitly set via attributes. |
| | | 571 | | // This is consistent with JsonPropertyNameAttribute semantics. |
| | 0 | 572 | | name = namingPolicy.ConvertName(name); |
| | 0 | 573 | | } |
| | | 574 | | |
| | 0 | 575 | | if (string.IsNullOrEmpty(name) || char.IsWhiteSpace(name[0]) || char.IsWhiteSpace(name[name.Length - 1]) || |
| | 0 | 576 | | (s_isFlagsEnum && name.Contains(','))) |
| | 0 | 577 | | { |
| | | 578 | | // Reject null or empty strings or strings with leading or trailing whitespace. |
| | | 579 | | // In the case of flags additionally reject strings containing commas. |
| | 0 | 580 | | ThrowHelper.ThrowInvalidOperationException_UnsupportedEnumIdentifier(typeof(T), name); |
| | | 581 | | } |
| | | 582 | | |
| | 0 | 583 | | return name; |
| | 0 | 584 | | } |
| | | 585 | | |
| | 0 | 586 | | private sealed class EnumFieldInfo(ulong key, EnumFieldNameKind kind, string originalName, string jsonName) |
| | | 587 | | { |
| | | 588 | | private List<EnumFieldInfo>? _conflictingFields; |
| | 0 | 589 | | public EnumFieldNameKind Kind { get; } = kind; |
| | 0 | 590 | | public ulong Key { get; } = key; |
| | 0 | 591 | | public string OriginalName { get; } = originalName; |
| | 0 | 592 | | public string JsonName { get; } = jsonName; |
| | | 593 | | |
| | | 594 | | /// <summary> |
| | | 595 | | /// Assuming we have field that conflicts with the current up to case sensitivity, |
| | | 596 | | /// append it to a list of trailing values for use by the enum value parser. |
| | | 597 | | /// </summary> |
| | | 598 | | public void AppendConflictingField(EnumFieldInfo other) |
| | 0 | 599 | | { |
| | 0 | 600 | | Debug.Assert(JsonName.Equals(other.JsonName, StringComparison.OrdinalIgnoreCase), "The conflicting entry |
| | | 601 | | |
| | 0 | 602 | | if (ConflictsWith(this, other)) |
| | 0 | 603 | | { |
| | | 604 | | // Silently discard if the preceding entry is the default or has identical name. |
| | 0 | 605 | | return; |
| | | 606 | | } |
| | | 607 | | |
| | 0 | 608 | | List<EnumFieldInfo> conflictingFields = _conflictingFields ??= []; |
| | | 609 | | |
| | | 610 | | // Walk the existing list to ensure we do not add duplicates. |
| | 0 | 611 | | foreach (EnumFieldInfo conflictingField in conflictingFields) |
| | 0 | 612 | | { |
| | 0 | 613 | | if (ConflictsWith(conflictingField, other)) |
| | 0 | 614 | | { |
| | 0 | 615 | | return; |
| | | 616 | | } |
| | 0 | 617 | | } |
| | | 618 | | |
| | 0 | 619 | | conflictingFields.Add(other); |
| | | 620 | | |
| | | 621 | | // Determines whether the first field info matches everything that the second field info matches, |
| | | 622 | | // in which case the second field info is redundant and doesn't need to be added to the list. |
| | | 623 | | static bool ConflictsWith(EnumFieldInfo current, EnumFieldInfo other) |
| | 0 | 624 | | { |
| | | 625 | | // The default name matches everything case-insensitively. |
| | 0 | 626 | | if (current.Kind is EnumFieldNameKind.Default) |
| | 0 | 627 | | { |
| | 0 | 628 | | return true; |
| | | 629 | | } |
| | | 630 | | |
| | | 631 | | // current matches case-sensitively since it's not the default name. |
| | | 632 | | // other matches case-insensitively, so it matches more than current. |
| | 0 | 633 | | if (other.Kind is EnumFieldNameKind.Default) |
| | 0 | 634 | | { |
| | 0 | 635 | | return false; |
| | | 636 | | } |
| | | 637 | | |
| | | 638 | | // Both are case-sensitive so they need to be identical. |
| | 0 | 639 | | return current.JsonName.Equals(other.JsonName, StringComparison.Ordinal); |
| | 0 | 640 | | } |
| | 0 | 641 | | } |
| | | 642 | | |
| | | 643 | | public EnumFieldInfo? GetMatchingField(ReadOnlySpan<char> input) |
| | 0 | 644 | | { |
| | 0 | 645 | | Debug.Assert(input.Equals(JsonName.AsSpan(), StringComparison.OrdinalIgnoreCase), "Must equal the field |
| | | 646 | | |
| | 0 | 647 | | if (Kind is EnumFieldNameKind.Default || input.SequenceEqual(JsonName.AsSpan())) |
| | 0 | 648 | | { |
| | | 649 | | // Default enum names use case insensitive parsing so are always a match. |
| | 0 | 650 | | return this; |
| | | 651 | | } |
| | | 652 | | |
| | 0 | 653 | | if (_conflictingFields is { } conflictingFields) |
| | 0 | 654 | | { |
| | 0 | 655 | | Debug.Assert(conflictingFields.Count > 0); |
| | 0 | 656 | | foreach (EnumFieldInfo matchingField in conflictingFields) |
| | 0 | 657 | | { |
| | 0 | 658 | | if (matchingField.Kind is EnumFieldNameKind.Default || input.SequenceEqual(matchingField.JsonNam |
| | 0 | 659 | | { |
| | 0 | 660 | | return matchingField; |
| | | 661 | | } |
| | 0 | 662 | | } |
| | 0 | 663 | | } |
| | | 664 | | |
| | 0 | 665 | | return null; |
| | 0 | 666 | | } |
| | | 667 | | } |
| | | 668 | | |
| | | 669 | | /// <summary> |
| | | 670 | | /// Performs a topological sort on enum fields to ensure values that are supersets of other values come first. |
| | | 671 | | /// </summary> |
| | | 672 | | private static EnumFieldInfo[] TopologicalSortEnumFields(EnumFieldInfo[] enumFields) |
| | 0 | 673 | | { |
| | 0 | 674 | | if (enumFields.Length <= 1) |
| | 0 | 675 | | { |
| | 0 | 676 | | return enumFields; |
| | | 677 | | } |
| | | 678 | | |
| | 0 | 679 | | var indices = new (int negativePopCount, int index)[enumFields.Length]; |
| | 0 | 680 | | for (int i = 0; i < enumFields.Length; i++) |
| | 0 | 681 | | { |
| | | 682 | | // We want values with more bits set to come first so negate the pop count. |
| | | 683 | | // Keep the index as a second comparand so that sorting stability is preserved. |
| | 0 | 684 | | indices[i] = (-PopCount(enumFields[i].Key), i); |
| | 0 | 685 | | } |
| | | 686 | | |
| | 0 | 687 | | Array.Sort(indices); |
| | | 688 | | |
| | 0 | 689 | | var sortedFields = new EnumFieldInfo[enumFields.Length]; |
| | 0 | 690 | | for (int i = 0; i < indices.Length; i++) |
| | 0 | 691 | | { |
| | | 692 | | // extract the index from the sorted tuple |
| | 0 | 693 | | int index = indices[i].index; |
| | 0 | 694 | | sortedFields[i] = enumFields[index]; |
| | 0 | 695 | | } |
| | | 696 | | |
| | 0 | 697 | | return sortedFields; |
| | 0 | 698 | | } |
| | | 699 | | |
| | | 700 | | private static int PopCount(ulong value) |
| | 0 | 701 | | { |
| | | 702 | | #if NET |
| | 0 | 703 | | return (int)ulong.PopCount(value); |
| | | 704 | | #else |
| | | 705 | | int count = 0; |
| | | 706 | | while (value != 0) |
| | | 707 | | { |
| | | 708 | | value &= value - 1; |
| | | 709 | | count++; |
| | | 710 | | } |
| | | 711 | | return count; |
| | | 712 | | #endif |
| | 0 | 713 | | } |
| | | 714 | | |
| | | 715 | | private enum EnumFieldNameKind |
| | | 716 | | { |
| | | 717 | | Default = 0, |
| | | 718 | | NamingPolicy = 1, |
| | | 719 | | Attribute = 2, |
| | | 720 | | } |
| | | 721 | | } |
| | | 722 | | } |