| | | 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 sealed class IReadOnlySetOfTConverter<TCollection, TElement> |
| | | 11 | | : IEnumerableDefaultConverter<TCollection, TElement> |
| | | 12 | | where TCollection : IReadOnlySet<TElement> |
| | | 13 | | { |
| | 0 | 14 | | private readonly bool _isDeserializable = typeof(TCollection).IsAssignableFrom(typeof(HashSet<TElement>)); |
| | | 15 | | |
| | | 16 | | protected override void Add(in TElement value, ref ReadStack state) |
| | 0 | 17 | | { |
| | | 18 | | // Directly convert to HashSet<TElement> since IReadOnlySet<T> does not have an Add method. |
| | 0 | 19 | | HashSet<TElement> collection = (HashSet<TElement>)state.Current.ReturnValue!; |
| | 0 | 20 | | collection.Add(value); |
| | 0 | 21 | | if (IsValueType) |
| | 0 | 22 | | { |
| | 0 | 23 | | state.Current.ReturnValue = collection; |
| | 0 | 24 | | } |
| | 0 | 25 | | } |
| | | 26 | | |
| | | 27 | | protected override void CreateCollection(ref Utf8JsonReader reader, scoped ref ReadStack state, JsonSerializerOp |
| | 0 | 28 | | { |
| | 0 | 29 | | if (!_isDeserializable) |
| | 0 | 30 | | { |
| | 0 | 31 | | ThrowHelper.ThrowNotSupportedException_CannotPopulateCollection(Type, ref reader, ref state); |
| | | 32 | | } |
| | | 33 | | |
| | 0 | 34 | | state.Current.ReturnValue = new HashSet<TElement>(); |
| | 0 | 35 | | } |
| | | 36 | | |
| | | 37 | | internal override void ConfigureJsonTypeInfo(JsonTypeInfo jsonTypeInfo, JsonSerializerOptions options) |
| | 0 | 38 | | { |
| | | 39 | | // Deserialize as HashSet<TElement> for interface types that support it. |
| | 0 | 40 | | if (jsonTypeInfo.CreateObject is null && Type.IsAssignableFrom(typeof(HashSet<TElement>))) |
| | 0 | 41 | | { |
| | 0 | 42 | | Debug.Assert(Type.IsInterface); |
| | 0 | 43 | | jsonTypeInfo.CreateObject = () => new HashSet<TElement>(); |
| | 0 | 44 | | } |
| | 0 | 45 | | } |
| | | 46 | | } |
| | | 47 | | } |