From c106489772adcaeaf1108267cfbda6baaa6e3aac Mon Sep 17 00:00:00 2001 From: vis2k Date: Fri, 18 Jun 2021 20:02:53 +0800 Subject: [PATCH] feature: MessagePacking.Pack returns bool to indicate if the message could be packed or not --- Assets/Mirror/Runtime/MessagePacking.cs | 22 ++++++++++++++++++++-- 1 file changed, 20 insertions(+), 2 deletions(-) diff --git a/Assets/Mirror/Runtime/MessagePacking.cs b/Assets/Mirror/Runtime/MessagePacking.cs index 9e6fd13f5..ded9ea74c 100644 --- a/Assets/Mirror/Runtime/MessagePacking.cs +++ b/Assets/Mirror/Runtime/MessagePacking.cs @@ -28,14 +28,32 @@ public static ushort GetId() where T : struct, NetworkMessage // pack message before sending // -> NetworkWriter passed as arg so that we can use .ToArraySegment // and do an allocation free send before recycling it. - public static void Pack(T message, NetworkWriter writer) + // -> true if message is of valid size, false if too big + public static bool Pack(T message, NetworkWriter writer) where T : struct, NetworkMessage { + // remember writer position + int backup = writer.Position; + + // writer header ushort msgType = GetId(); writer.WriteUShort(msgType); - // serialize message into writer + // writer content and calculate the size + int before = writer.Position; writer.Write(message); + int contentSize = writer.Position - before; + + // we only allow up to MaxContentSize. + // anything else can't be sent over transport. + if (contentSize > MaxContentSize) + { + // roll back writer (atomic), show useful message to the user + writer.Position = backup; + Debug.LogWarning($"Failed to Pack {typeof(T)} because it serialized into {contentSize} bytes, which exceeds the limit of {MaxContentSize} bytes."); + return false; + } + return true; } // unpack message after receiving