~ruther/NosSmooth

ref: d734ef022245fd0486eb265eab64b515d10966c6 NosSmooth/Packets/NosSmooth.PacketSerializer/Converters/Special/Converters/EnumStringConverter.cs -rw-r--r-- 1.6 KiB
d734ef02 — František Boháček Revert "feat: use "in" instead of "ref" in packet serializer" 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
//
//  EnumStringConverter.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 NosSmooth.PacketSerializer.Abstractions;
using Remora.Results;

namespace NosSmooth.PacketSerializer.Converters.Special.Converters;

/// <summary>
/// Converts enum with the given underlying type.
/// </summary>
/// <typeparam name="TEnum">The enum.</typeparam>
/// <typeparam name="TUnderlyingType">The enum's underlying type.</typeparam>
public class EnumStringConverter<TEnum, TUnderlyingType> : BaseStringConverter<TEnum>
{
    private readonly IStringSerializer _serializer;

    /// <summary>
    /// Initializes a new instance of the <see cref="EnumStringConverter{TEnum, TUnderlyingType}"/> class.
    /// </summary>
    /// <param name="serializer">The string serializer.</param>
    public EnumStringConverter(IStringSerializer serializer)
    {
        _serializer = serializer;
    }

    /// <inheritdoc />
    public override Result Serialize(TEnum? obj, ref PacketStringBuilder builder)
    {
        builder.Append(((TUnderlyingType?)(object?)obj)?.ToString() ?? "-");
        return Result.FromSuccess();
    }

    /// <inheritdoc />
    public override Result<TEnum?> Deserialize(ref PacketStringEnumerator stringEnumerator, DeserializeOptions options)
    {
        var result = _serializer.Deserialize<TUnderlyingType>(ref stringEnumerator, options);
        if (!result.IsSuccess)
        {
            return Result<TEnum?>.FromError(result);
        }

        return (TEnum?)(object?)result.Entity;
    }
}
Do not follow this link