From f0c9a81c100141d5ec09c7ba8ce5ade75213b7c2 Mon Sep 17 00:00:00 2001 From: vis2k Date: Thu, 10 Mar 2022 19:37:21 +0800 Subject: [PATCH] breaking: NetworkReader/WriterPool API simplified: GetReader/Writer => Get; Recycle => Return; (#3112) * breaking: NetworkReader/WriterPool API simplified: GetReader/Writer => Take; Recycle => Return; * rename Take() to Get() * Pool Take() => Get() --- .../Discovery/NetworkDiscoveryBase.cs | 8 +++---- Assets/Mirror/Components/NetworkAnimator.cs | 12 +++++----- .../Weaver/Processors/CommandProcessor.cs | 4 ++-- .../Processors/NetworkBehaviourProcessor.cs | 8 +++---- .../Editor/Weaver/Processors/RpcProcessor.cs | 4 ++-- .../Weaver/Processors/TargetRpcProcessor.cs | 4 ++-- Assets/Mirror/Editor/Weaver/WeaverTypes.cs | 8 +++---- Assets/Mirror/Runtime/Batching/Batcher.cs | 4 ++-- Assets/Mirror/Runtime/Batching/Unbatcher.cs | 4 ++-- .../Mirror/Runtime/LocalConnectionToClient.cs | 2 +- .../Mirror/Runtime/LocalConnectionToServer.cs | 6 ++--- Assets/Mirror/Runtime/NetworkClient.cs | 6 ++--- Assets/Mirror/Runtime/NetworkConnection.cs | 4 ++-- Assets/Mirror/Runtime/NetworkReaderPool.cs | 24 ++++++++++++++----- Assets/Mirror/Runtime/NetworkServer.cs | 10 ++++---- Assets/Mirror/Runtime/NetworkWriterPool.cs | 16 +++++++++---- Assets/Mirror/Runtime/Pool.cs | 6 ++++- .../Mirror/Tests/Editor/MessagePackingTest.cs | 4 ++-- .../Editor/NetworkBehaviourSerializeTest.cs | 4 ++-- .../Mirror/Tests/Editor/NetworkReaderTest.cs | 2 +- Assets/Mirror/Tests/Editor/PoolTests.cs | 4 ++-- Assets/Mirror/Tests/Editor/SyncListTest.cs | 4 ++-- 22 files changed, 86 insertions(+), 62 deletions(-) diff --git a/Assets/Mirror/Components/Discovery/NetworkDiscoveryBase.cs b/Assets/Mirror/Components/Discovery/NetworkDiscoveryBase.cs index 6b64fffc7..8945a7e8c 100644 --- a/Assets/Mirror/Components/Discovery/NetworkDiscoveryBase.cs +++ b/Assets/Mirror/Components/Discovery/NetworkDiscoveryBase.cs @@ -175,7 +175,7 @@ async Task ReceiveRequestAsync(UdpClient udpClient) UdpReceiveResult udpReceiveResult = await udpClient.ReceiveAsync(); - using (PooledNetworkReader networkReader = NetworkReaderPool.GetReader(udpReceiveResult.Buffer)) + using (PooledNetworkReader networkReader = NetworkReaderPool.Get(udpReceiveResult.Buffer)) { long handshake = networkReader.ReadLong(); if (handshake != secretHandshake) @@ -206,7 +206,7 @@ protected virtual void ProcessClientRequest(Request request, IPEndPoint endpoint if (info == null) return; - using (PooledNetworkWriter writer = NetworkWriterPool.GetWriter()) + using (PooledNetworkWriter writer = NetworkWriterPool.Get()) { try { @@ -369,7 +369,7 @@ public void BroadcastDiscoveryRequest() IPEndPoint endPoint = new IPEndPoint(IPAddress.Broadcast, serverBroadcastListenPort); - using (PooledNetworkWriter writer = NetworkWriterPool.GetWriter()) + using (PooledNetworkWriter writer = NetworkWriterPool.Get()) { writer.WriteLong(secretHandshake); @@ -406,7 +406,7 @@ async Task ReceiveGameBroadcastAsync(UdpClient udpClient) UdpReceiveResult udpReceiveResult = await udpClient.ReceiveAsync(); - using (PooledNetworkReader networkReader = NetworkReaderPool.GetReader(udpReceiveResult.Buffer)) + using (PooledNetworkReader networkReader = NetworkReaderPool.Get(udpReceiveResult.Buffer)) { if (networkReader.ReadLong() != secretHandshake) return; diff --git a/Assets/Mirror/Components/NetworkAnimator.cs b/Assets/Mirror/Components/NetworkAnimator.cs index 23fc4ecd7..815be8a52 100644 --- a/Assets/Mirror/Components/NetworkAnimator.cs +++ b/Assets/Mirror/Components/NetworkAnimator.cs @@ -106,7 +106,7 @@ void FixedUpdate() continue; } - using (PooledNetworkWriter writer = NetworkWriterPool.GetWriter()) + using (PooledNetworkWriter writer = NetworkWriterPool.Get()) { WriteParameters(writer); SendAnimationMessage(stateHash, normalizedTime, i, layerWeight[i], writer.ToArray()); @@ -193,7 +193,7 @@ void CheckSendRate() { nextSendTime = now + syncInterval; - using (PooledNetworkWriter writer = NetworkWriterPool.GetWriter()) + using (PooledNetworkWriter writer = NetworkWriterPool.Get()) { if (WriteParameters(writer)) SendAnimationParametersMessage(writer.ToArray()); @@ -527,7 +527,7 @@ void CmdOnAnimationServerMessage(int stateHash, float normalizedTime, int layerI //Debug.Log($"OnAnimationMessage for netId {netId}"); // handle and broadcast - using (PooledNetworkReader networkReader = NetworkReaderPool.GetReader(parameters)) + using (PooledNetworkReader networkReader = NetworkReaderPool.Get(parameters)) { HandleAnimMsg(stateHash, normalizedTime, layerId, weight, networkReader); RpcOnAnimationClientMessage(stateHash, normalizedTime, layerId, weight, parameters); @@ -542,7 +542,7 @@ void CmdOnAnimationParametersServerMessage(byte[] parameters) return; // handle and broadcast - using (PooledNetworkReader networkReader = NetworkReaderPool.GetReader(parameters)) + using (PooledNetworkReader networkReader = NetworkReaderPool.Get(parameters)) { HandleAnimParamsMsg(networkReader); RpcOnAnimationParametersClientMessage(parameters); @@ -600,14 +600,14 @@ void CmdSetAnimatorSpeed(float newSpeed) [ClientRpc] void RpcOnAnimationClientMessage(int stateHash, float normalizedTime, int layerId, float weight, byte[] parameters) { - using (PooledNetworkReader networkReader = NetworkReaderPool.GetReader(parameters)) + using (PooledNetworkReader networkReader = NetworkReaderPool.Get(parameters)) HandleAnimMsg(stateHash, normalizedTime, layerId, weight, networkReader); } [ClientRpc] void RpcOnAnimationParametersClientMessage(byte[] parameters) { - using (PooledNetworkReader networkReader = NetworkReaderPool.GetReader(parameters)) + using (PooledNetworkReader networkReader = NetworkReaderPool.Get(parameters)) HandleAnimParamsMsg(networkReader); } diff --git a/Assets/Mirror/Editor/Weaver/Processors/CommandProcessor.cs b/Assets/Mirror/Editor/Weaver/Processors/CommandProcessor.cs index 35ba2533f..55893f756 100644 --- a/Assets/Mirror/Editor/Weaver/Processors/CommandProcessor.cs +++ b/Assets/Mirror/Editor/Weaver/Processors/CommandProcessor.cs @@ -38,7 +38,7 @@ public static MethodDefinition ProcessCommandCall(WeaverTypes weaverTypes, Write NetworkBehaviourProcessor.WriteSetupLocals(worker, weaverTypes); // NetworkWriter writer = new NetworkWriter(); - NetworkBehaviourProcessor.WriteCreateWriter(worker, weaverTypes); + NetworkBehaviourProcessor.WriteGetWriter(worker, weaverTypes); // write all the arguments that the user passed to the Cmd call if (!NetworkBehaviourProcessor.WriteArguments(worker, writers, Log, md, RemoteCallType.Command, ref WeavingFailed)) @@ -59,7 +59,7 @@ public static MethodDefinition ProcessCommandCall(WeaverTypes weaverTypes, Write worker.Emit(requiresAuthority ? OpCodes.Ldc_I4_1 : OpCodes.Ldc_I4_0); worker.Emit(OpCodes.Call, weaverTypes.sendCommandInternal); - NetworkBehaviourProcessor.WriteRecycleWriter(worker, weaverTypes); + NetworkBehaviourProcessor.WriteReturnWriter(worker, weaverTypes); worker.Emit(OpCodes.Ret); return cmd; diff --git a/Assets/Mirror/Editor/Weaver/Processors/NetworkBehaviourProcessor.cs b/Assets/Mirror/Editor/Weaver/Processors/NetworkBehaviourProcessor.cs index 06792d603..84e696f22 100644 --- a/Assets/Mirror/Editor/Weaver/Processors/NetworkBehaviourProcessor.cs +++ b/Assets/Mirror/Editor/Weaver/Processors/NetworkBehaviourProcessor.cs @@ -140,18 +140,18 @@ public static void WriteSetupLocals(ILProcessor worker, WeaverTypes weaverTypes) worker.Body.Variables.Add(new VariableDefinition(weaverTypes.Import())); } - public static void WriteCreateWriter(ILProcessor worker, WeaverTypes weaverTypes) + public static void WriteGetWriter(ILProcessor worker, WeaverTypes weaverTypes) { // create writer - worker.Emit(OpCodes.Call, weaverTypes.GetPooledWriterReference); + worker.Emit(OpCodes.Call, weaverTypes.GetWriterReference); worker.Emit(OpCodes.Stloc_0); } - public static void WriteRecycleWriter(ILProcessor worker, WeaverTypes weaverTypes) + public static void WriteReturnWriter(ILProcessor worker, WeaverTypes weaverTypes) { // NetworkWriterPool.Recycle(writer); worker.Emit(OpCodes.Ldloc_0); - worker.Emit(OpCodes.Call, weaverTypes.RecycleWriterReference); + worker.Emit(OpCodes.Call, weaverTypes.ReturnWriterReference); } public static bool WriteArguments(ILProcessor worker, Writers writers, Logger Log, MethodDefinition method, RemoteCallType callType, ref bool WeavingFailed) diff --git a/Assets/Mirror/Editor/Weaver/Processors/RpcProcessor.cs b/Assets/Mirror/Editor/Weaver/Processors/RpcProcessor.cs index 7413ce5b0..df44f205c 100644 --- a/Assets/Mirror/Editor/Weaver/Processors/RpcProcessor.cs +++ b/Assets/Mirror/Editor/Weaver/Processors/RpcProcessor.cs @@ -68,7 +68,7 @@ public static MethodDefinition ProcessRpcCall(WeaverTypes weaverTypes, Writers w //worker.Emit(OpCodes.Ldstr, $"Call ClientRpc function {md.Name}"); //worker.Emit(OpCodes.Call, WeaverTypes.logErrorReference); - NetworkBehaviourProcessor.WriteCreateWriter(worker, weaverTypes); + NetworkBehaviourProcessor.WriteGetWriter(worker, weaverTypes); // write all the arguments that the user passed to the Rpc call if (!NetworkBehaviourProcessor.WriteArguments(worker, writers, Log, md, RemoteCallType.ClientRpc, ref WeavingFailed)) @@ -89,7 +89,7 @@ public static MethodDefinition ProcessRpcCall(WeaverTypes weaverTypes, Writers w worker.Emit(includeOwner ? OpCodes.Ldc_I4_1 : OpCodes.Ldc_I4_0); worker.Emit(OpCodes.Callvirt, weaverTypes.sendRpcInternal); - NetworkBehaviourProcessor.WriteRecycleWriter(worker, weaverTypes); + NetworkBehaviourProcessor.WriteReturnWriter(worker, weaverTypes); worker.Emit(OpCodes.Ret); diff --git a/Assets/Mirror/Editor/Weaver/Processors/TargetRpcProcessor.cs b/Assets/Mirror/Editor/Weaver/Processors/TargetRpcProcessor.cs index fa2e2a28b..8afba94ec 100644 --- a/Assets/Mirror/Editor/Weaver/Processors/TargetRpcProcessor.cs +++ b/Assets/Mirror/Editor/Weaver/Processors/TargetRpcProcessor.cs @@ -100,7 +100,7 @@ public static MethodDefinition ProcessTargetRpcCall(WeaverTypes weaverTypes, Wri NetworkBehaviourProcessor.WriteSetupLocals(worker, weaverTypes); - NetworkBehaviourProcessor.WriteCreateWriter(worker, weaverTypes); + NetworkBehaviourProcessor.WriteGetWriter(worker, weaverTypes); // write all the arguments that the user passed to the TargetRpc call // (skip first one if first one is NetworkConnection) @@ -127,7 +127,7 @@ public static MethodDefinition ProcessTargetRpcCall(WeaverTypes weaverTypes, Wri worker.Emit(OpCodes.Ldc_I4, targetRpcAttr.GetField("channel", 0)); worker.Emit(OpCodes.Callvirt, weaverTypes.sendTargetRpcInternal); - NetworkBehaviourProcessor.WriteRecycleWriter(worker, weaverTypes); + NetworkBehaviourProcessor.WriteReturnWriter(worker, weaverTypes); worker.Emit(OpCodes.Ret); diff --git a/Assets/Mirror/Editor/Weaver/WeaverTypes.cs b/Assets/Mirror/Editor/Weaver/WeaverTypes.cs index 935bd36c3..173af58a8 100644 --- a/Assets/Mirror/Editor/Weaver/WeaverTypes.cs +++ b/Assets/Mirror/Editor/Weaver/WeaverTypes.cs @@ -11,8 +11,8 @@ public class WeaverTypes public MethodReference ScriptableObjectCreateInstanceMethod; public MethodReference NetworkBehaviourDirtyBitsReference; - public MethodReference GetPooledWriterReference; - public MethodReference RecycleWriterReference; + public MethodReference GetWriterReference; + public MethodReference ReturnWriterReference; public MethodReference NetworkClientConnectionReference; @@ -95,8 +95,8 @@ public WeaverTypes(AssemblyDefinition assembly, Logger Log, ref bool WeavingFail NetworkBehaviourDirtyBitsReference = Resolvers.ResolveProperty(NetworkBehaviourType, assembly, "syncVarDirtyBits"); TypeReference NetworkWriterPoolType = Import(typeof(NetworkWriterPool)); - GetPooledWriterReference = Resolvers.ResolveMethod(NetworkWriterPoolType, assembly, Log, "GetWriter", ref WeavingFailed); - RecycleWriterReference = Resolvers.ResolveMethod(NetworkWriterPoolType, assembly, Log, "Recycle", ref WeavingFailed); + GetWriterReference = Resolvers.ResolveMethod(NetworkWriterPoolType, assembly, Log, "Get", ref WeavingFailed); + ReturnWriterReference = Resolvers.ResolveMethod(NetworkWriterPoolType, assembly, Log, "Return", ref WeavingFailed); NetworkClientConnectionReference = Resolvers.ResolveMethod(NetworkClientType, assembly, Log, "get_connection", ref WeavingFailed); diff --git a/Assets/Mirror/Runtime/Batching/Batcher.cs b/Assets/Mirror/Runtime/Batching/Batcher.cs index b77e31250..3d5240550 100644 --- a/Assets/Mirror/Runtime/Batching/Batcher.cs +++ b/Assets/Mirror/Runtime/Batching/Batcher.cs @@ -52,7 +52,7 @@ public void AddMessage(ArraySegment message) // would add a size header. we want to write directly. // -> will be returned to pool when making the batch! // IMPORTANT: NOT adding a size header / msg saves LOTS of bandwidth - PooledNetworkWriter writer = NetworkWriterPool.GetWriter(); + PooledNetworkWriter writer = NetworkWriterPool.Get(); writer.WriteBytes(message.Array, message.Offset, message.Count); messages.Enqueue(writer); } @@ -83,7 +83,7 @@ public bool MakeNextBatch(NetworkWriter writer, double timeStamp) writer.WriteBytes(segment.Array, segment.Offset, segment.Count); // return the writer to pool - NetworkWriterPool.Recycle(message); + NetworkWriterPool.Return(message); } // keep going as long as we have more messages, // AND the next one would fit into threshold. diff --git a/Assets/Mirror/Runtime/Batching/Unbatcher.cs b/Assets/Mirror/Runtime/Batching/Unbatcher.cs index be3c77b07..dde7df006 100644 --- a/Assets/Mirror/Runtime/Batching/Unbatcher.cs +++ b/Assets/Mirror/Runtime/Batching/Unbatcher.cs @@ -55,7 +55,7 @@ public bool AddBatch(ArraySegment batch) // -> WriteBytes instead of WriteSegment because the latter // would add a size header. we want to write directly. // -> will be returned to pool when sending! - PooledNetworkWriter writer = NetworkWriterPool.GetWriter(); + PooledNetworkWriter writer = NetworkWriterPool.Get(); writer.WriteBytes(batch.Array, batch.Offset, batch.Count); // first batch? then point reader there @@ -112,7 +112,7 @@ public bool GetNextMessage(out NetworkReader message, out double remoteTimeStamp { // retire the batch PooledNetworkWriter writer = batches.Dequeue(); - NetworkWriterPool.Recycle(writer); + NetworkWriterPool.Return(writer); // do we have another batch? if (batches.Count > 0) diff --git a/Assets/Mirror/Runtime/LocalConnectionToClient.cs b/Assets/Mirror/Runtime/LocalConnectionToClient.cs index 0d816466a..627edc2da 100644 --- a/Assets/Mirror/Runtime/LocalConnectionToClient.cs +++ b/Assets/Mirror/Runtime/LocalConnectionToClient.cs @@ -21,7 +21,7 @@ internal override void Send(ArraySegment segment, int channelId = Channels // => WriteBytes instead of WriteArraySegment because the latter // includes a 4 bytes header. we just want to write raw. //Debug.Log($"Enqueue {BitConverter.ToString(segment.Array, segment.Offset, segment.Count)}"); - PooledNetworkWriter writer = NetworkWriterPool.GetWriter(); + PooledNetworkWriter writer = NetworkWriterPool.Get(); writer.WriteBytes(segment.Array, segment.Offset, segment.Count); connectionToServer.queue.Enqueue(writer); } diff --git a/Assets/Mirror/Runtime/LocalConnectionToServer.cs b/Assets/Mirror/Runtime/LocalConnectionToServer.cs index 86e539262..6bbbcd485 100644 --- a/Assets/Mirror/Runtime/LocalConnectionToServer.cs +++ b/Assets/Mirror/Runtime/LocalConnectionToServer.cs @@ -37,7 +37,7 @@ internal override void Send(ArraySegment segment, int channelId = Channels // flush it to the server's OnTransportData immediately. // local connection to server always invokes immediately. - using (PooledNetworkWriter writer = NetworkWriterPool.GetWriter()) + using (PooledNetworkWriter writer = NetworkWriterPool.Get()) { // make a batch with our local time (double precision) if (batcher.MakeNextBatch(writer, NetworkTime.localTime)) @@ -71,7 +71,7 @@ internal override void Update() Batcher batcher = GetBatchForChannelId(Channels.Reliable); batcher.AddMessage(message); - using (PooledNetworkWriter batchWriter = NetworkWriterPool.GetWriter()) + using (PooledNetworkWriter batchWriter = NetworkWriterPool.Get()) { // make a batch with our local time (double precision) if (batcher.MakeNextBatch(batchWriter, NetworkTime.localTime)) @@ -80,7 +80,7 @@ internal override void Update() } } - NetworkWriterPool.Recycle(writer); + NetworkWriterPool.Return(writer); } // should we still process a disconnected event? diff --git a/Assets/Mirror/Runtime/NetworkClient.cs b/Assets/Mirror/Runtime/NetworkClient.cs index 204695fa7..1e3859b64 100644 --- a/Assets/Mirror/Runtime/NetworkClient.cs +++ b/Assets/Mirror/Runtime/NetworkClient.cs @@ -1005,7 +1005,7 @@ internal static void ApplySpawnPayload(NetworkIdentity identity, SpawnMessage me // (Count is 0 if there were no components) if (message.payload.Count > 0) { - using (PooledNetworkReader payloadReader = NetworkReaderPool.GetReader(message.payload)) + using (PooledNetworkReader payloadReader = NetworkReaderPool.Get(message.payload)) { identity.OnDeserializeAllSafely(payloadReader, true); } @@ -1238,7 +1238,7 @@ static void OnEntityStateMessage(EntityStateMessage message) // Debug.Log($"NetworkClient.OnUpdateVarsMessage {msg.netId}"); if (spawned.TryGetValue(message.netId, out NetworkIdentity localObject) && localObject != null) { - using (PooledNetworkReader networkReader = NetworkReaderPool.GetReader(message.payload)) + using (PooledNetworkReader networkReader = NetworkReaderPool.Get(message.payload)) localObject.OnDeserializeAllSafely(networkReader, false); } else Debug.LogWarning($"Did not find target for sync message for {message.netId} . Note: this can be completely normal because UDP messages may arrive out of order, so this message might have arrived after a Destroy message."); @@ -1249,7 +1249,7 @@ static void OnRPCMessage(RpcMessage message) // Debug.Log($"NetworkClient.OnRPCMessage hash:{msg.functionHash} netId:{msg.netId}"); if (spawned.TryGetValue(message.netId, out NetworkIdentity identity)) { - using (PooledNetworkReader networkReader = NetworkReaderPool.GetReader(message.payload)) + using (PooledNetworkReader networkReader = NetworkReaderPool.Get(message.payload)) identity.HandleRemoteCall(message.componentIndex, message.functionHash, RemoteCallType.ClientRpc, networkReader); } } diff --git a/Assets/Mirror/Runtime/NetworkConnection.cs b/Assets/Mirror/Runtime/NetworkConnection.cs index 73ecbfe0c..298206046 100644 --- a/Assets/Mirror/Runtime/NetworkConnection.cs +++ b/Assets/Mirror/Runtime/NetworkConnection.cs @@ -129,7 +129,7 @@ protected static bool ValidatePacketSize(ArraySegment segment, int channel public void Send(T message, int channelId = Channels.Reliable) where T : struct, NetworkMessage { - using (PooledNetworkWriter writer = NetworkWriterPool.GetWriter()) + using (PooledNetworkWriter writer = NetworkWriterPool.Get()) { // pack message and send allocation free MessagePacking.Pack(message, writer); @@ -176,7 +176,7 @@ internal virtual void Update() // make and send as many batches as necessary from the stored // messages. Batcher batcher = kvp.Value; - using (PooledNetworkWriter writer = NetworkWriterPool.GetWriter()) + using (PooledNetworkWriter writer = NetworkWriterPool.Get()) { // make a batch with our local time (double precision) while (batcher.MakeNextBatch(writer, NetworkTime.localTime)) diff --git a/Assets/Mirror/Runtime/NetworkReaderPool.cs b/Assets/Mirror/Runtime/NetworkReaderPool.cs index beb867fff..1a4334039 100644 --- a/Assets/Mirror/Runtime/NetworkReaderPool.cs +++ b/Assets/Mirror/Runtime/NetworkReaderPool.cs @@ -8,7 +8,7 @@ public sealed class PooledNetworkReader : NetworkReader, IDisposable { internal PooledNetworkReader(byte[] bytes) : base(bytes) {} internal PooledNetworkReader(ArraySegment segment) : base(segment) {} - public void Dispose() => NetworkReaderPool.Recycle(this); + public void Dispose() => NetworkReaderPool.Return(this); } /// Pool of NetworkReaders to avoid allocations. @@ -24,29 +24,41 @@ public static class NetworkReaderPool 1000 ); + // DEPRECATED 2022-03-10 + [Obsolete("GetReader() was renamed to Get()")] + public static PooledNetworkReader GetReader(byte[] bytes) => Get(bytes); + /// Get the next reader in the pool. If pool is empty, creates a new Reader [MethodImpl(MethodImplOptions.AggressiveInlining)] - public static PooledNetworkReader GetReader(byte[] bytes) + public static PooledNetworkReader Get(byte[] bytes) { // grab from pool & set buffer - PooledNetworkReader reader = Pool.Take(); + PooledNetworkReader reader = Pool.Get(); reader.SetBuffer(bytes); return reader; } + // DEPRECATED 2022-03-10 + [Obsolete("GetReader() was renamed to Get()")] + public static PooledNetworkReader GetReader(ArraySegment segment) => Get(segment); + /// Get the next reader in the pool. If pool is empty, creates a new Reader [MethodImpl(MethodImplOptions.AggressiveInlining)] - public static PooledNetworkReader GetReader(ArraySegment segment) + public static PooledNetworkReader Get(ArraySegment segment) { // grab from pool & set buffer - PooledNetworkReader reader = Pool.Take(); + PooledNetworkReader reader = Pool.Get(); reader.SetBuffer(segment); return reader; } + // DEPRECATED 2022-03-10 + [Obsolete("Recycle() was renamed to Return()")] + public static void Recycle(PooledNetworkReader reader) => Return(reader); + /// Returns a reader to the pool. [MethodImpl(MethodImplOptions.AggressiveInlining)] - public static void Recycle(PooledNetworkReader reader) + public static void Return(PooledNetworkReader reader) { Pool.Return(reader); } diff --git a/Assets/Mirror/Runtime/NetworkServer.cs b/Assets/Mirror/Runtime/NetworkServer.cs index 9d51b75a7..a5715fb4b 100644 --- a/Assets/Mirror/Runtime/NetworkServer.cs +++ b/Assets/Mirror/Runtime/NetworkServer.cs @@ -282,7 +282,7 @@ public static void SendToAll(T message, int channelId = Channels.Reliable, bo } // Debug.Log($"Server.SendToAll {typeof(T)}"); - using (PooledNetworkWriter writer = NetworkWriterPool.GetWriter()) + using (PooledNetworkWriter writer = NetworkWriterPool.Get()) { // pack message only once MessagePacking.Pack(message, writer); @@ -328,7 +328,7 @@ static void SendToObservers(NetworkIdentity identity, T message, int channelI if (identity == null || identity.observers == null || identity.observers.Count == 0) return; - using (PooledNetworkWriter writer = NetworkWriterPool.GetWriter()) + using (PooledNetworkWriter writer = NetworkWriterPool.Get()) { // pack message into byte[] once MessagePacking.Pack(message, writer); @@ -352,7 +352,7 @@ public static void SendToReadyObservers(NetworkIdentity identity, T message, if (identity == null || identity.observers == null || identity.observers.Count == 0) return; - using (PooledNetworkWriter writer = NetworkWriterPool.GetWriter()) + using (PooledNetworkWriter writer = NetworkWriterPool.Get()) { // pack message only once MessagePacking.Pack(message, writer); @@ -960,7 +960,7 @@ static void OnCommandMessage(NetworkConnectionToClient conn, CommandMessage msg, // Debug.Log($"OnCommandMessage for netId:{msg.netId} conn:{conn}"); - using (PooledNetworkReader networkReader = NetworkReaderPool.GetReader(msg.payload)) + using (PooledNetworkReader networkReader = NetworkReaderPool.Get(msg.payload)) identity.HandleRemoteCall(msg.componentIndex, msg.functionHash, RemoteCallType.Command, networkReader, conn as NetworkConnectionToClient); } @@ -996,7 +996,7 @@ internal static void SendSpawnMessage(NetworkIdentity identity, NetworkConnectio //Debug.Log($"Server SendSpawnMessage: name:{identity.name} sceneId:{identity.sceneId:X} netid:{identity.netId}"); // one writer for owner, one for observers - using (PooledNetworkWriter ownerWriter = NetworkWriterPool.GetWriter(), observersWriter = NetworkWriterPool.GetWriter()) + using (PooledNetworkWriter ownerWriter = NetworkWriterPool.Get(), observersWriter = NetworkWriterPool.Get()) { bool isOwner = identity.connectionToClient == conn; ArraySegment payload = CreateSpawnMessagePayload(isOwner, identity, ownerWriter, observersWriter); diff --git a/Assets/Mirror/Runtime/NetworkWriterPool.cs b/Assets/Mirror/Runtime/NetworkWriterPool.cs index 608162d63..a7535b86b 100644 --- a/Assets/Mirror/Runtime/NetworkWriterPool.cs +++ b/Assets/Mirror/Runtime/NetworkWriterPool.cs @@ -6,7 +6,7 @@ namespace Mirror /// Pooled NetworkWriter, automatically returned to pool when using 'using' public sealed class PooledNetworkWriter : NetworkWriter, IDisposable { - public void Dispose() => NetworkWriterPool.Recycle(this); + public void Dispose() => NetworkWriterPool.Return(this); } /// Pool of NetworkWriters to avoid allocations. @@ -24,19 +24,27 @@ public static class NetworkWriterPool 1000 ); + // DEPRECATED 2022-03-10 + [Obsolete("GetWriter() was renamed to Get()")] + public static PooledNetworkWriter GetWriter() => Get(); + /// Get a writer from the pool. Creates new one if pool is empty. [MethodImpl(MethodImplOptions.AggressiveInlining)] - public static PooledNetworkWriter GetWriter() + public static PooledNetworkWriter Get() { // grab from pool & reset position - PooledNetworkWriter writer = Pool.Take(); + PooledNetworkWriter writer = Pool.Get(); writer.Reset(); return writer; } + // DEPRECATED 2022-03-10 + [Obsolete("Recycle() was renamed to Return()")] + public static void Recycle(PooledNetworkWriter writer) => Return(writer); + /// Return a writer to the pool. [MethodImpl(MethodImplOptions.AggressiveInlining)] - public static void Recycle(PooledNetworkWriter writer) + public static void Return(PooledNetworkWriter writer) { Pool.Return(writer); } diff --git a/Assets/Mirror/Runtime/Pool.cs b/Assets/Mirror/Runtime/Pool.cs index 230c1b78a..e3de19be4 100644 --- a/Assets/Mirror/Runtime/Pool.cs +++ b/Assets/Mirror/Runtime/Pool.cs @@ -24,9 +24,13 @@ public Pool(Func objectGenerator, int initialCapacity) objects.Push(objectGenerator()); } + // DEPRECATED 2022-03-10 + [Obsolete("Take() was renamed to Get()")] + public T Take() => Get(); + // take an element from the pool, or create a new one if empty [MethodImpl(MethodImplOptions.AggressiveInlining)] - public T Take() => objects.Count > 0 ? objects.Pop() : objectGenerator(); + public T Get() => objects.Count > 0 ? objects.Pop() : objectGenerator(); // return an element to the pool [MethodImpl(MethodImplOptions.AggressiveInlining)] diff --git a/Assets/Mirror/Tests/Editor/MessagePackingTest.cs b/Assets/Mirror/Tests/Editor/MessagePackingTest.cs index c473765e5..c435012e1 100644 --- a/Assets/Mirror/Tests/Editor/MessagePackingTest.cs +++ b/Assets/Mirror/Tests/Editor/MessagePackingTest.cs @@ -14,7 +14,7 @@ public struct EmptyMessage : NetworkMessage {} public static byte[] PackToByteArray(T message) where T : struct, NetworkMessage { - using (PooledNetworkWriter writer = NetworkWriterPool.GetWriter()) + using (PooledNetworkWriter writer = NetworkWriterPool.Get()) { MessagePacking.Pack(message, writer); return writer.ToArray(); @@ -25,7 +25,7 @@ public static byte[] PackToByteArray(T message) public static T UnpackFromByteArray(byte[] data) where T : struct, NetworkMessage { - using (PooledNetworkReader networkReader = NetworkReaderPool.GetReader(data)) + using (PooledNetworkReader networkReader = NetworkReaderPool.Get(data)) { int msgType = MessagePacking.GetId(); diff --git a/Assets/Mirror/Tests/Editor/NetworkBehaviourSerializeTest.cs b/Assets/Mirror/Tests/Editor/NetworkBehaviourSerializeTest.cs index e8cb4c3c8..626efe70a 100644 --- a/Assets/Mirror/Tests/Editor/NetworkBehaviourSerializeTest.cs +++ b/Assets/Mirror/Tests/Editor/NetworkBehaviourSerializeTest.cs @@ -125,11 +125,11 @@ public class NetworkBehaviourSerializeTest : MirrorEditModeTest { static void SyncNetworkBehaviour(NetworkBehaviour source, NetworkBehaviour target, bool initialState) { - using (PooledNetworkWriter writer = NetworkWriterPool.GetWriter()) + using (PooledNetworkWriter writer = NetworkWriterPool.Get()) { source.OnSerialize(writer, initialState); - using (PooledNetworkReader reader = NetworkReaderPool.GetReader(writer.ToArraySegment())) + using (PooledNetworkReader reader = NetworkReaderPool.Get(writer.ToArraySegment())) { target.OnDeserialize(reader, initialState); } diff --git a/Assets/Mirror/Tests/Editor/NetworkReaderTest.cs b/Assets/Mirror/Tests/Editor/NetworkReaderTest.cs index 49bf1bd48..964ba81ff 100644 --- a/Assets/Mirror/Tests/Editor/NetworkReaderTest.cs +++ b/Assets/Mirror/Tests/Editor/NetworkReaderTest.cs @@ -66,7 +66,7 @@ public void ReadBytesCountTooBigTest() // should throw an exception byte[] bytes = { 0x00, 0x01 }; - using (PooledNetworkReader reader = NetworkReaderPool.GetReader(bytes)) + using (PooledNetworkReader reader = NetworkReaderPool.Get(bytes)) { try { diff --git a/Assets/Mirror/Tests/Editor/PoolTests.cs b/Assets/Mirror/Tests/Editor/PoolTests.cs index 2002c8de5..2f6928561 100644 --- a/Assets/Mirror/Tests/Editor/PoolTests.cs +++ b/Assets/Mirror/Tests/Editor/PoolTests.cs @@ -22,7 +22,7 @@ public void TearDown() public void TakeFromEmpty() { // taking from an empty pool should give us a completely new string - Assert.That(pool.Take(), Is.EqualTo("new string")); + Assert.That(pool.Get(), Is.EqualTo("new string")); } [Test] @@ -31,7 +31,7 @@ public void ReturnAndTake() // returning and then taking should get the returned one, not a // newly generated one. pool.Return("returned"); - Assert.That(pool.Take(), Is.EqualTo("returned")); + Assert.That(pool.Get(), Is.EqualTo("returned")); } [Test] diff --git a/Assets/Mirror/Tests/Editor/SyncListTest.cs b/Assets/Mirror/Tests/Editor/SyncListTest.cs index 9e33ccec7..1c2118226 100644 --- a/Assets/Mirror/Tests/Editor/SyncListTest.cs +++ b/Assets/Mirror/Tests/Editor/SyncListTest.cs @@ -420,11 +420,11 @@ public static class SyncObjectTestMethods { public static uint GetChangeCount(this SyncObject syncObject) { - using (PooledNetworkWriter writer = NetworkWriterPool.GetWriter()) + using (PooledNetworkWriter writer = NetworkWriterPool.Get()) { syncObject.OnSerializeDelta(writer); - using (PooledNetworkReader reader = NetworkReaderPool.GetReader(writer.ToArraySegment())) + using (PooledNetworkReader reader = NetworkReaderPool.Get(writer.ToArraySegment())) { return reader.ReadUInt(); }