| | | 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.Collections.Generic; |
| | | 5 | | using System.Diagnostics; |
| | | 6 | | using System.Text.Json.Serialization.Metadata; |
| | | 7 | | |
| | | 8 | | namespace System.Text.Json.Serialization.Converters |
| | | 9 | | { |
| | | 10 | | internal class ImmutableDictionaryOfTKeyTValueConverter<TDictionary, TKey, TValue> |
| | | 11 | | : DictionaryDefaultConverter<TDictionary, TKey, TValue> |
| | | 12 | | where TDictionary : IReadOnlyDictionary<TKey, TValue> |
| | | 13 | | where TKey : notnull |
| | | 14 | | { |
| | | 15 | | protected sealed override void Add(TKey key, in TValue value, JsonSerializerOptions options, ref ReadStack state |
| | 0 | 16 | | { |
| | 0 | 17 | | Dictionary<TKey, TValue> dictionary = (Dictionary<TKey, TValue>)state.Current.ReturnValue!; |
| | | 18 | | |
| | 0 | 19 | | if (options.AllowDuplicateProperties) |
| | 0 | 20 | | { |
| | 0 | 21 | | dictionary[key] = value; |
| | 0 | 22 | | } |
| | | 23 | | else |
| | 0 | 24 | | { |
| | 0 | 25 | | if (!dictionary.TryAdd(key, value)) |
| | 0 | 26 | | { |
| | 0 | 27 | | ThrowHelper.ThrowJsonException_DuplicatePropertyNotAllowed(); |
| | | 28 | | } |
| | 0 | 29 | | } |
| | 0 | 30 | | } |
| | | 31 | | |
| | 0 | 32 | | internal sealed override bool CanHaveMetadata => false; |
| | | 33 | | |
| | 0 | 34 | | internal override bool SupportsCreateObjectDelegate => false; |
| | | 35 | | protected sealed override void CreateCollection(ref Utf8JsonReader reader, scoped ref ReadStack state) |
| | 0 | 36 | | { |
| | 0 | 37 | | state.Current.ReturnValue = new Dictionary<TKey, TValue>(); |
| | 0 | 38 | | } |
| | | 39 | | |
| | 0 | 40 | | internal sealed override bool IsConvertibleCollection => true; |
| | | 41 | | protected sealed override void ConvertCollection(ref ReadStack state, JsonSerializerOptions options) |
| | 0 | 42 | | { |
| | 0 | 43 | | Func<IEnumerable<KeyValuePair<TKey, TValue>>, TDictionary>? creator = |
| | 0 | 44 | | (Func<IEnumerable<KeyValuePair<TKey, TValue>>, TDictionary>?)state.Current.JsonTypeInfo.CreateObjectWith |
| | 0 | 45 | | Debug.Assert(creator != null); |
| | 0 | 46 | | state.Current.ReturnValue = creator((Dictionary<TKey, TValue>)state.Current.ReturnValue!); |
| | 0 | 47 | | } |
| | | 48 | | } |
| | | 49 | | } |