| | | 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.Diagnostics.CodeAnalysis; |
| | | 7 | | using System.Text.Json.Serialization.Metadata; |
| | | 8 | | |
| | | 9 | | namespace System.Text.Json.Serialization.Converters |
| | | 10 | | { |
| | | 11 | | // Converter for F# maps: https://fsharp.github.io/fsharp-core-docs/reference/fsharp-collections-fsharpmap-2.html |
| | | 12 | | internal sealed class FSharpMapConverter<TMap, TKey, TValue> : DictionaryDefaultConverter<TMap, TKey, TValue> |
| | | 13 | | where TMap : IEnumerable<KeyValuePair<TKey, TValue>> |
| | | 14 | | where TKey : notnull |
| | | 15 | | { |
| | | 16 | | private readonly Func<IEnumerable<Tuple<TKey, TValue>>, TMap> _mapConstructor; |
| | | 17 | | |
| | | 18 | | [RequiresUnreferencedCode(FSharpCoreReflectionProxy.FSharpCoreUnreferencedCodeMessage)] |
| | | 19 | | [RequiresDynamicCode(FSharpCoreReflectionProxy.FSharpCoreUnreferencedCodeMessage)] |
| | 0 | 20 | | public FSharpMapConverter() |
| | 0 | 21 | | { |
| | 0 | 22 | | _mapConstructor = FSharpCoreReflectionProxy.Instance.CreateFSharpMapConstructor<TMap, TKey, TValue>(); |
| | 0 | 23 | | } |
| | | 24 | | |
| | | 25 | | protected override void Add(TKey key, in TValue value, JsonSerializerOptions options, ref ReadStack state) |
| | 0 | 26 | | { |
| | 0 | 27 | | ((List<Tuple<TKey, TValue>>)state.Current.ReturnValue!).Add(new Tuple<TKey, TValue>(key, value)); |
| | 0 | 28 | | } |
| | | 29 | | |
| | 0 | 30 | | internal override bool CanHaveMetadata => false; |
| | | 31 | | |
| | 0 | 32 | | internal override bool SupportsCreateObjectDelegate => false; |
| | | 33 | | protected override void CreateCollection(ref Utf8JsonReader reader, scoped ref ReadStack state) |
| | 0 | 34 | | { |
| | 0 | 35 | | state.Current.ReturnValue = new List<Tuple<TKey, TValue>>(); |
| | 0 | 36 | | } |
| | | 37 | | |
| | 0 | 38 | | internal sealed override bool IsConvertibleCollection => true; |
| | | 39 | | protected override void ConvertCollection(ref ReadStack state, JsonSerializerOptions options) |
| | 0 | 40 | | { |
| | 0 | 41 | | List<Tuple<TKey, TValue>> listToConvert = (List<Tuple<TKey, TValue>>)state.Current.ReturnValue!; |
| | 0 | 42 | | TMap map = _mapConstructor(listToConvert); |
| | 0 | 43 | | state.Current.ReturnValue = map; |
| | | 44 | | |
| | 0 | 45 | | if (!options.AllowDuplicateProperties) |
| | 0 | 46 | | { |
| | 0 | 47 | | int totalItemsAdded = listToConvert.Count; |
| | 0 | 48 | | int mapCount = ((ICollection<KeyValuePair<TKey, TValue>>)map).Count; |
| | | 49 | | |
| | 0 | 50 | | if (mapCount != totalItemsAdded) |
| | 0 | 51 | | { |
| | 0 | 52 | | ThrowHelper.ThrowJsonException_DuplicatePropertyNotAllowed(); |
| | | 53 | | } |
| | 0 | 54 | | } |
| | 0 | 55 | | } |
| | | 56 | | } |
| | | 57 | | } |