using System.Buffers.Binary; using RailEnterprise.Protocol.Messages; namespace RailEnterprise.Protocol; /// /// Frame [u32 length][u16 messageId][payload], little endian; length conta messageId e /// payload. Un messaggio WebSocket binario contiene esattamente un frame. /// public static class Frame { public const int HeaderSize = 6; public const int MaxFrameBytes = 4 * 1024 * 1024; public const int MaxLength = MaxFrameBytes - 4; /// Versione del protocollo: cresce solo per modifiche incompatibili. public const ushort ProtocolVersion = 1; public static byte[] Encode(IMessage message) { var w = new SpanWriter(256); w.U32(0); w.U16((ushort)message.Id); message.Write(ref w); int length = w.Length - 4; if (length > MaxLength) throw new ProtocolException($"frame troppo grande: {w.Length} byte"); w.PatchU32(0, (uint)length); return w.ToArray(); } /// Lunghezza totale del frame che inizia in data, se l'intestazione รจ completa. public static bool TryReadLength(ReadOnlySpan data, out int frameBytes) { frameBytes = 0; if (data.Length < 4) return false; uint length = BinaryPrimitives.ReadUInt32LittleEndian(data); if (length < 2 || length > MaxLength) throw new ProtocolException($"lunghezza del frame non valida: {length}"); frameBytes = (int)length + 4; return true; } public static IMessage Decode(ReadOnlySpan frame) { if (frame.Length < HeaderSize) throw new ProtocolException("frame troppo corto"); uint length = BinaryPrimitives.ReadUInt32LittleEndian(frame); if (length > MaxLength || length + 4 != frame.Length) throw new ProtocolException($"lunghezza del frame incoerente: {length} su {frame.Length} byte"); var id = (MessageId)BinaryPrimitives.ReadUInt16LittleEndian(frame[4..]); var r = new SpanReader(frame[HeaderSize..]); return MessageCodec.Read(id, ref r); } }