~ruther/NosSmooth

ref: 9b3c4959ad3a6b2792f86da54400b960f181788e NosSmooth/Packets/NosSmooth.PacketSerializer/Converters/Special/Converters/EnumStringConverter.cs -rw-r--r-- 1.6 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
//
//  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 System;
using NosSmooth.PacketSerializer.Abstractions;
using Remora.Results;

namespace NosSmooth.Packets.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, PacketStringBuilder builder)
    {
        builder.Append(((TUnderlyingType?)(object?)obj)?.ToString() ?? "-");
        return Result.FromSuccess();
    }

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

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