~ruther/NosSmooth

ref: 9b3c4959ad3a6b2792f86da54400b960f181788e NosSmooth/Packets/NosSmooth.PacketSerializer/Converters/Special/NullableStringConverterFactory.cs -rw-r--r-- 1.9 KiB
9b3c4959 — Rutherther feat(packets): add support for st buff vnums with levels 2 years ago
                                                                                
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
//
//  NullableStringConverterFactory.cs
//
//  Copyright (c) František Boháček. All rights reserved.
//  Licensed under the MIT license. See LICENSE file in the project root for full license information.

using System;
using Microsoft.Extensions.DependencyInjection;
using NosSmooth.Packets.Converters.Special.Converters;
using NosSmooth.Packets.Extensions;
using NosSmooth.PacketSerializer.Abstractions;
using Remora.Results;

namespace NosSmooth.Packets.Converters.Special;

/// <inheritdoc />
public class NullableStringConverterFactory : IStringConverterFactory
{
    private readonly IServiceProvider _serviceProvider;

    /// <summary>
    /// Initializes a new instance of the <see cref="NullableStringConverterFactory"/> class.
    /// </summary>
    /// <param name="serviceProvider">The service provider.</param>
    public NullableStringConverterFactory(IServiceProvider serviceProvider)
    {
        _serviceProvider = serviceProvider;
    }

    /// <inheritdoc />
    public bool ShouldHandle(Type type)
        => Nullable.GetUnderlyingType(type) != null;

    /// <inheritdoc />
    public Result<IStringConverter> CreateTypeSerializer(Type type)
    {
        var underlyingType = Nullable.GetUnderlyingType(type);
        if (underlyingType is null)
        {
            throw new InvalidOperationException("Accepts only nullable types.");
        }

        var nullableConverterType = typeof(NullableStringConverter<>).MakeGenericType(underlyingType);
        try
        {
            return Result<IStringConverter>
                .FromSuccess
                    ((IStringConverter)ActivatorUtilities.CreateInstance(_serviceProvider, nullableConverterType));
        }
        catch (Exception e)
        {
            return e;
        }
    }

    /// <inheritdoc />
    public Result<IStringConverter<T>> CreateTypeSerializer<T>()
    {
        return CreateTypeSerializer(typeof(T))
            .Cast<IStringConverter<T>, IStringConverter>();
    }
}
Do not follow this link