using System; using System.IO; using InABox.Core; namespace InABox.Rpc { // Note that this implements both ISerializeBinary and ICoreFormattable, which is annoying duplicate code. The reason that these can't be combined // is that ICoreFormattable *must* be able to be used by netstandard2.0 for Logikal, and therefore must live outside of InABox.Core. Hence, we need // two interfaces. If we wanted to combine them, the interface for the ISerializeBinary would need to be changed to be able to just use a // CoreBinaryWriter/Reader, and this would introduce version inconsistency for communications. Hence, this would only be able to be done once we // switch from old mobile app and therefore can introduce a breaking change for a version (e.g., version 9). [Serializable] public partial class RpcMessage : ISerializeBinary, ICoreFormattable { public Guid Id { get; set; } public String Command { get; set; } public byte[] Payload { get; set; } public RpcError Error { get; set; } public override string ToString() => $"{Command} [{Error}]"; public RpcMessage() { Id = Guid.NewGuid(); Command = ""; Payload = Array.Empty(); Error = RpcError.NONE; } public RpcMessage(Guid id, string command, byte[] payload) : this() { Id = id; Command = command; Payload = payload; Error = RpcError.NONE; } public void SerializeBinary(CoreBinaryWriter writer) { writer.Write(Id); writer.Write(Command); writer.WriteBinaryValue(Payload); writer.Write(Error.ToString()); } public void DeserializeBinary(CoreBinaryReader reader) { Id = reader.ReadGuid(); Command = reader.ReadString(); Payload = reader.ReadBinaryValue(); if (Enum.TryParse(reader.ReadString(), out var error)) Error = error; } public void Write(BinaryWriter writer) { writer.Write(Id); writer.Write(Command); writer.Write(Payload.Length); writer.Write(Payload); writer.Write((Int32)Error); } public void Read(BinaryReader reader) { Id = reader.ReadGuid(); Command = reader.ReadString(); var _length = reader.ReadInt32(); Payload = reader.ReadBytes(_length); Error = (RpcError)reader.ReadInt32(); } } }