~ruther/NosSmooth

ref: d45a01445b7eeeb9fbbb8dc14c5e046612a765d0 NosSmooth/Packets/NosSmooth.PacketSerializer/Converters/Special/Converters/NullableStringConverter.cs -rw-r--r-- 1.6 KiB
d45a0144 — František Boháček feat(localbinding): add follow and unfollow (attack) entity methods 3 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
//
//  NullableStringConverter.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;

#pragma warning disable SA1125
/// <summary>
/// Converter of nullable types.
/// </summary>
/// <typeparam name="T">The nonnullable underlying type.</typeparam>
public class NullableStringConverter<T> : BaseStringConverter<Nullable<T>>
    where T : struct
{
    private readonly IStringSerializer _stringSerializer;

    /// <summary>
    /// Initializes a new instance of the <see cref="NullableStringConverter{T}"/> class.
    /// </summary>
    /// <param name="stringSerializer">The string serializer.</param>
    public NullableStringConverter(IStringSerializer stringSerializer)
    {
        _stringSerializer = stringSerializer;

    }

    /// <inheritdoc />
    public override Result Serialize(T? obj, PacketStringBuilder builder)
    {
        if (obj is null)
        {
            builder.Append('-');
            return Result.FromSuccess();
        }

        return _stringSerializer.Serialize<T>(obj.Value, builder);
    }

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

        return Result<T?>.FromSuccess(result.Entity);
    }
}
#pragma warning restore SA1125