| | | 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.Reflection; |
| | | 8 | | using System.Text.Json.Serialization.Converters; |
| | | 9 | | |
| | | 10 | | namespace System.Text.Json.Serialization |
| | | 11 | | { |
| | | 12 | | /// <summary> |
| | | 13 | | /// Converter for streaming <see cref="IAsyncEnumerable{T}" /> values. |
| | | 14 | | /// </summary> |
| | | 15 | | [RequiresDynamicCode(JsonSerializer.SerializationRequiresDynamicCodeMessage)] |
| | | 16 | | internal sealed class IAsyncEnumerableConverterFactory : JsonConverterFactory |
| | | 17 | | { |
| | 3 | 18 | | public IAsyncEnumerableConverterFactory() { } |
| | | 19 | | |
| | 2301 | 20 | | public override bool CanConvert(Type typeToConvert) => GetAsyncEnumerableInterface(typeToConvert) is not null; |
| | | 21 | | |
| | | 22 | | public override JsonConverter CreateConverter(Type typeToConvert, JsonSerializerOptions options) |
| | 0 | 23 | | { |
| | 0 | 24 | | Type? asyncEnumerableInterface = GetAsyncEnumerableInterface(typeToConvert); |
| | 0 | 25 | | Debug.Assert(asyncEnumerableInterface is not null, $"{typeToConvert} not supported by converter."); |
| | | 26 | | |
| | 0 | 27 | | Type elementType = asyncEnumerableInterface.GetGenericArguments()[0]; |
| | 0 | 28 | | Type converterType = typeof(IAsyncEnumerableOfTConverter<,>).MakeGenericType(typeToConvert, elementType); |
| | 0 | 29 | | return (JsonConverter)Activator.CreateInstance(converterType)!; |
| | 0 | 30 | | } |
| | | 31 | | |
| | | 32 | | private static Type? GetAsyncEnumerableInterface(Type type) |
| | 2301 | 33 | | => type.GetCompatibleGenericInterface(typeof(IAsyncEnumerable<>)); |
| | | 34 | | } |
| | | 35 | | } |