GodotTicTacToe/scripts/net/packethandling/PacketBuffer.cs

75 lines
2.6 KiB
C#

using Godot;
using System.Collections.Generic;
namespace Network.PacketHandling {
public class PacketBuffer {
private List<byte> ByteList = new List<byte>();
private int ReadCounter = 0;
public static byte[] SignatureBytes = { 154, 211 };
public byte[] ByteBuffer { get { return ByteList.ToArray(); } }
public int Length { get { return ByteList.Count; } }
public bool HasNext { get { return ReadCounter < ByteList.Count; } }
public byte Read() {
if (!HasNext) {
GD.printerr("Attempted to read byte; Impossible, byte buffer ended.");
return 0;
}
return ByteList[ReadCounter++];
}
public short ReadShort() { return PrimitiveSerializer.DeserializeShort(this); }
public int ReadInt() { return PrimitiveSerializer.DeserializeInt(this); }
public long ReadLong() { return PrimitiveSerializer.DeserializeLong(this); }
public float ReadFloat() { return PrimitiveSerializer.DeserializeFloat(this); }
public bool ReadBool() { return PrimitiveSerializer.DeserializeBool(this); }
public string ReadString() { return PrimitiveSerializer.DeserializeString(this); }
public void Write(byte toWrite) {
ByteList.Add(toWrite);
}
public void Write(short toWrite) { PrimitiveSerializer.SerializeShort(toWrite, this); }
public void Write(int toWrite) { PrimitiveSerializer.SerializeInt(toWrite, this); }
public void Write(long toWrite) { PrimitiveSerializer.SerializeLong(toWrite, this); }
public void Write(float toWrite) { PrimitiveSerializer.SerializeFloat(toWrite, this); }
public void Write(bool toWrite) { PrimitiveSerializer.SerializeBool(toWrite, this); }
public void Write(string toWrite) { PrimitiveSerializer.SerializeString(toWrite, this); }
public static PacketBuffer FromByteBuffer(byte[] byteBuffer) {
PacketBuffer PB = new PacketBuffer();
PB.ByteList = new List<byte>(byteBuffer);
return PB;
}
public static PacketBuffer WithSignature() {
PacketBuffer PB = new PacketBuffer();
foreach (byte B in SignatureBytes) {
PB.Write(B);
}
return PB;
}
public static PacketBuffer operator +(PacketBuffer first, PacketBuffer second) {
PacketBuffer PB = new PacketBuffer();
PB.ByteList.AddRange(first.ByteList);
PB.ByteList.AddRange(second.ByteList);
return PB;
}
}
}