// // ISpecificPacketSerializer.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.Reflection; using NosCore.Packets.Attributes; using NosCore.Packets.Interfaces; using Remora.Results; namespace NosSmooth.Core.Packets.Converters; /// /// Converts packets that cannot be handled easily by the default serializer. /// public interface ISpecificPacketSerializer { /// /// Gets whether this is a serializer. /// public bool Serializer { get; } /// /// Gets whether this is a deserializer. /// public bool Deserializer { get; } /// /// Whether the current packet serializer should handle the packet. /// /// The string of the packet. /// If this serializer should be used for handling. public bool ShouldHandle(string packetString); /// /// Whether the current packet serializer should handle the packet. /// /// The packet object. /// If this serializer should be used for handling. public bool ShouldHandle(IPacket packet); /// /// Serialize the given packet into string. /// /// The string of the packet. /// The serialized packet or an error. public Result Serialize(IPacket packet); /// /// Deserialize the given packet to its type. /// /// The string of the packet. /// The deserialized packet or an error. public Result Deserialize(string packetString); } /// /// Converts packets that cannot be handled easily by the default serializer. /// /// The packet. public abstract class SpecificPacketSerializer : ISpecificPacketSerializer where TPacket : IPacket { private string? _packetHeader; /// /// Gets the packet header identifier. /// public string PacketHeader { get { if (_packetHeader is null) { _packetHeader = typeof(TPacket).GetCustomAttribute()!.Identification + " "; } return _packetHeader; } } /// public abstract bool Serializer { get; } /// public abstract bool Deserializer { get; } /// public bool ShouldHandle(string packetString) { return packetString.StartsWith(PacketHeader); } /// public bool ShouldHandle(IPacket packet) { return typeof(TPacket) == packet.GetType(); } /// Result ISpecificPacketSerializer.Serialize(IPacket packet) { return Serialize((TPacket)packet); } /// Result ISpecificPacketSerializer.Deserialize(string packetString) { var result = Deserialize(packetString); if (!result.IsSuccess) { return Result.FromError(result); } return Result.FromSuccess(result.Entity); } /// /// Serialize the given packet into string. /// /// The string of the packet. /// The serialized packet or an error. public abstract Result Serialize(TPacket packet); /// /// Deserialize the given packet to its type. /// /// The string of the packet. /// The deserialized packet or an error. public abstract Result Deserialize(string packetString); }