~ruther/NosSmooth

ref: 762fc34c97e8b1f6e9290426b8bc2a78122e28ba NosSmooth/Packets/NosSmooth.PacketSerializer.Abstractions/BaseStringConverter.cs -rw-r--r-- 1.5 KiB
762fc34c — Rutherther Merge pull request #82 from Rutherther/feat/serialize-stackalloc 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
//
//  BaseStringConverter.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.Errors;
using Remora.Results;

namespace NosSmooth.PacketSerializer.Abstractions;

/// <summary>
/// Base type for converting objects that maps object converting methods to the actual type.
/// </summary>
/// <typeparam name="TParseType">The type of the object that this converts.</typeparam>
public abstract class BaseStringConverter<TParseType> : IStringConverter<TParseType>
{
    /// <inheritdoc />
    public abstract Result Serialize(TParseType? obj, ref PacketStringBuilder builder);

    /// <inheritdoc />
    public abstract Result<TParseType?> Deserialize(ref PacketStringEnumerator stringEnumerator, DeserializeOptions options);

    /// <inheritdoc/>
    Result<object?> IStringConverter.Deserialize(ref PacketStringEnumerator stringEnumerator, DeserializeOptions options)
    {
        var result = Deserialize(ref stringEnumerator, options);
        if (!result.IsSuccess)
        {
            return Result<object?>.FromError(result);
        }

        return Result<object?>.FromSuccess(result.Entity);
    }

    /// <inheritdoc/>
    Result IStringConverter.Serialize(object? obj, ref PacketStringBuilder builder)
    {
        if (!(obj is TParseType parseType))
        {
            return new WrongTypeError(this, typeof(TParseType), obj);
        }

        return Serialize(parseType, ref builder);
    }
}
Do not follow this link