//
// 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
///
/// Converter of nullable types.
///
/// The nonnullable underlying type.
public class NullableStringConverter : BaseStringConverter>
where T : struct
{
private readonly IStringSerializer _stringSerializer;
///
/// Initializes a new instance of the class.
///
/// The string serializer.
public NullableStringConverter(IStringSerializer stringSerializer)
{
_stringSerializer = stringSerializer;
}
///
public override Result Serialize(T? obj, PacketStringBuilder builder)
{
if (obj is null)
{
builder.Append('-');
return Result.FromSuccess();
}
return _stringSerializer.Serialize(obj.Value, builder);
}
///
public override Result Deserialize(ref PacketStringEnumerator stringEnumerator)
{
var result = _stringSerializer.Deserialize(ref stringEnumerator);
if (!result.IsSuccess)
{
return Result.FromError(result);
}
return Result.FromSuccess(result.Entity);
}
}
#pragma warning restore SA1125