using System; using System.IO; namespace YGOLegacy.Protocol.Framing { public static class FrameCodec { public const int HeaderSize = 2; public const int MaxFrame = 0xFFFE; public static void Write(BinaryWriter writer, byte id, byte[] payload) { var payloadLength = payload == null ? 0 : payload.Length; WriteHeader(writer, payloadLength + 1); writer.Write(id); if (payloadLength > 0) writer.Write(payload, 0, payloadLength); } public static void Write(BinaryWriter writer, byte[] packet) { if (packet == null || packet.Length == 0) throw new ArgumentException("A frame needs at least the id byte", nameof(packet)); WriteHeader(writer, packet.Length); writer.Write(packet, 0, packet.Length); } public static int ReadLength(byte[] header) { if (header == null || header.Length < HeaderSize) throw new ArgumentException("A frame header is two bytes", nameof(header)); return header[0] | (header[1] << 8); } private static void WriteHeader(BinaryWriter writer, int length) { if (length > MaxFrame) throw new ArgumentException("Frame of " + length + " bytes exceeds the " + MaxFrame + "-byte ceiling"); writer.Write((byte)length); writer.Write((byte)(length >> 8)); } } public sealed class FrameExtractor { private byte[] _buffer = new byte[4096]; private int _start; private int _count; public int DroppedEmpty { get; private set; } public bool Faulted { get; private set; } public int Buffered => _count; public void Feed(byte[] chunk, int count) { if (Faulted || chunk == null || count <= 0) return; if (count > chunk.Length) count = chunk.Length; Reserve(count); Array.Copy(chunk, 0, _buffer, _start + _count, count); _count += count; } public bool TryTake(out byte[] packet) { packet = null; while (!Faulted && _count >= FrameCodec.HeaderSize) { var length = _buffer[_start] | (_buffer[_start + 1] << 8); if (length > FrameCodec.MaxFrame) { Faulted = true; return false; } if (length == 0) { Consume(FrameCodec.HeaderSize); DroppedEmpty++; continue; } if (_count < FrameCodec.HeaderSize + length) return false; packet = new byte[length]; Array.Copy(_buffer, _start + FrameCodec.HeaderSize, packet, 0, length); Consume(FrameCodec.HeaderSize + length); return true; } return false; } private void Consume(int bytes) { _start += bytes; _count -= bytes; if (_count == 0) _start = 0; } private void Reserve(int extra) { if (_start + _count + extra <= _buffer.Length) return; if (_count + extra <= _buffer.Length) { Array.Copy(_buffer, _start, _buffer, 0, _count); _start = 0; return; } var grown = new byte[Math.Max(_buffer.Length * 2, _count + extra)]; Array.Copy(_buffer, _start, grown, 0, _count); _buffer = grown; _start = 0; } } }