GodotTicTacToe/scripts/net/packethandling/PrimitiveSerializer.cs

90 lines
3.0 KiB
C#

using Godot;
using System;
using System.Collections.Generic;
using System.Text;
namespace Network.PacketHandling {
public static class PrimitiveSerializer {
public static byte[] GetBytes(PacketBuffer packetBuffer, int size) {
List<byte> Bytes = new List<byte>();
for (int i = 0; i < size; i++) {
Bytes.Add(packetBuffer.Read());
}
return Bytes.ToArray();
}
public static void SerializeShort(short serializable, PacketBuffer packetBuffer) {
byte[] Bytes = BitConverter.GetBytes(serializable);
foreach (byte B in Bytes) {
packetBuffer.Write(B);
}
}
public static short DeserializeShort(PacketBuffer packetBuffer) {
return BitConverter.ToInt16(GetBytes(packetBuffer, 2), 0);
}
public static void SerializeInt(int serializable, PacketBuffer packetBuffer) {
byte[] Bytes = BitConverter.GetBytes(serializable);
foreach (byte B in Bytes) {
packetBuffer.Write(B);
}
}
public static int DeserializeInt(PacketBuffer packetBuffer) {
return BitConverter.ToInt32(GetBytes(packetBuffer, 4), 0);
}
public static void SerializeLong(long serializable, PacketBuffer packetBuffer) {
byte[] Bytes = BitConverter.GetBytes(serializable);
foreach (byte B in Bytes) {
packetBuffer.Write(B);
}
}
public static long DeserializeLong(PacketBuffer packetBuffer) {
return BitConverter.ToInt64(GetBytes(packetBuffer, 8), 0);
}
public static void SerializeFloat(float serializable, PacketBuffer packetBuffer) {
byte[] Bytes = BitConverter.GetBytes(serializable);
foreach (byte B in Bytes) {
packetBuffer.Write(B);
}
}
public static float DeserializeFloat(PacketBuffer packetBuffer) {
return BitConverter.ToSingle(GetBytes(packetBuffer, 4), 0);
}
public static void SerializeBool(bool serializable, PacketBuffer packetBuffer) {
packetBuffer.Write((byte) (serializable ? 1 : 0));
}
public static bool DeserializeBool(PacketBuffer packetBuffer) {
return packetBuffer.Read() == 1;
}
public static void SerializeString(string serializable, PacketBuffer packetBuffer) {
byte[] Bytes = Encoding.Unicode.GetBytes(serializable);
packetBuffer.Write((byte) Bytes.Length);
foreach (byte B in Bytes) {
packetBuffer.Write(B);
}
}
public static string DeserializeString(PacketBuffer packetBuffer) {
int length = packetBuffer.Read();
List<byte> Bytes = new List<byte>();
for (int i = 0; i < length; i++) {
Bytes.Add(packetBuffer.Read());
}
return Encoding.Unicode.GetString(Bytes.ToArray());
}
}
}