From ce23b80a931a7ae904d618c4eaf737beb8076466 Mon Sep 17 00:00:00 2001 From: Nicollas Date: Sat, 22 Jul 2023 19:01:00 -0300 Subject: [PATCH] MemoryOwner copy buffer --- NetX/NetX.csproj | 2 +- NetX/NetXConnection.cs | 5 ++++- NetX/NetXMessage.cs | 17 +++++++++++++---- samples/ServerClientSample/Program.cs | 1 - 4 files changed, 18 insertions(+), 7 deletions(-) diff --git a/NetX/NetX.csproj b/NetX/NetX.csproj index 608b8be..56f4c6a 100644 --- a/NetX/NetX.csproj +++ b/NetX/NetX.csproj @@ -7,7 +7,7 @@ https://github.com/project-nevareth/NetX git true - 2.2.2 + 2.2.3 true snupkg diff --git a/NetX/NetXConnection.cs b/NetX/NetXConnection.cs index f4f5387..19156ea 100644 --- a/NetX/NetXConnection.cs +++ b/NetX/NetXConnection.cs @@ -480,7 +480,10 @@ private bool TryGetReceivedMessage( var next = buffer.GetPosition(size); buffer = buffer.Slice(next); - netXMessage = new NetXMessage(messageId, _options.CopyBuffer ? messageBuffer.ToArray() : messageBuffer); + var messageMemory = MemoryOwner.Allocate(messageBuffer.Length); + messageBuffer.CopyTo(messageMemory.Memory); + + netXMessage = new NetXMessage(messageId, messageMemory); return true; } diff --git a/NetX/NetXMessage.cs b/NetX/NetXMessage.cs index 84a56e1..b6f2511 100644 --- a/NetX/NetXMessage.cs +++ b/NetX/NetXMessage.cs @@ -1,16 +1,25 @@ using System; +using System.Buffers; +using CommunityToolkit.HighPerformance.Buffers; namespace NetX { - public readonly struct NetXMessage + public readonly struct NetXMessage : IDisposable { public Guid Id { get; } - public ReadOnlyMemory Buffer { get; } + public ReadOnlyMemory Buffer => _memoryOwner.Memory; - public NetXMessage(Guid id, ReadOnlyMemory buffer) + private readonly MemoryOwner _memoryOwner; + + public NetXMessage(Guid id, MemoryOwner memoryOwner) { Id = id; - Buffer = buffer; + _memoryOwner = memoryOwner; + } + + public void Dispose() + { + _memoryOwner.Dispose(); } } } diff --git a/samples/ServerClientSample/Program.cs b/samples/ServerClientSample/Program.cs index e805b36..aa5d980 100644 --- a/samples/ServerClientSample/Program.cs +++ b/samples/ServerClientSample/Program.cs @@ -7,7 +7,6 @@ using NetX; using NetX.Options; using Serilog; -using static System.Net.Mime.MediaTypeNames; namespace ServerClientSample {