Snowflake/RPG.Services.Core/Network/Command/ServiceCommandEncoder.cs

28 lines
999 B
C#
Raw Normal View History

2024-01-18 22:13:40 +00:00
using System.Buffers.Binary;
using RPG.Network.Proto;
namespace RPG.Services.Core.Network.Command;
public static class ServiceCommandEncoder
{
public static ServiceCommand DecodeCommand(ReadOnlyMemory<byte> buffer)
{
ReadOnlySpan<byte> span = buffer.Span;
RPGServiceType senderType = (RPGServiceType)span[0];
ServiceCommandType commandType = (ServiceCommandType)BinaryPrimitives.ReadUInt16BigEndian(span[1..3]);
ReadOnlyMemory<byte> body = buffer.Slice(7, BinaryPrimitives.ReadInt32BigEndian(span[3..7]));
return new(senderType, commandType, body);
}
public static void EncodeCommand(ServiceCommand command, Memory<byte> buffer)
{
Span<byte> span = buffer.Span;
span[0] = (byte)command.SenderType;
BinaryPrimitives.WriteUInt16BigEndian(span[1..3], (ushort)command.CommandType);
BinaryPrimitives.WriteInt32BigEndian(span[3..7], command.Body.Length);
command.Body.CopyTo(buffer[7..]);
}
}