| | | 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.Diagnostics; |
| | | 5 | | using System.Diagnostics.CodeAnalysis; |
| | | 6 | | using System.Reflection; |
| | | 7 | | |
| | | 8 | | namespace System.Text.Json.Serialization.Converters |
| | | 9 | | { |
| | | 10 | | [RequiresDynamicCode(JsonSerializer.SerializationRequiresDynamicCodeMessage)] |
| | | 11 | | internal sealed class MemoryConverterFactory : JsonConverterFactory |
| | | 12 | | { |
| | | 13 | | public override bool CanConvert(Type typeToConvert) |
| | 2301 | 14 | | { |
| | 2301 | 15 | | if (!typeToConvert.IsGenericType || !typeToConvert.IsValueType) |
| | 2301 | 16 | | { |
| | 2301 | 17 | | return false; |
| | | 18 | | } |
| | | 19 | | |
| | 0 | 20 | | Type typeDef = typeToConvert.GetGenericTypeDefinition(); |
| | 0 | 21 | | return typeDef == typeof(Memory<>) || typeDef == typeof(ReadOnlyMemory<>); |
| | 2301 | 22 | | } |
| | | 23 | | |
| | | 24 | | public override JsonConverter? CreateConverter(Type typeToConvert, JsonSerializerOptions options) |
| | 0 | 25 | | { |
| | 0 | 26 | | Debug.Assert(CanConvert(typeToConvert)); |
| | | 27 | | |
| | 0 | 28 | | Type converterType = typeToConvert.GetGenericTypeDefinition() == typeof(Memory<>) ? |
| | 0 | 29 | | typeof(MemoryConverter<>) : typeof(ReadOnlyMemoryConverter<>); |
| | | 30 | | |
| | 0 | 31 | | Type elementType = typeToConvert.GetGenericArguments()[0]; |
| | | 32 | | |
| | 0 | 33 | | return (JsonConverter)Activator.CreateInstance( |
| | 0 | 34 | | converterType.MakeGenericType(elementType))!; |
| | 0 | 35 | | } |
| | | 36 | | } |
| | | 37 | | } |