Skip to content

Commit 5a681f8

Browse files
authored
Merge pull request #729 from stebet/crossPlatformSerialization
Optimized cross-platform binary (de)serialization
2 parents da219fe + 31c35f3 commit 5a681f8

File tree

7 files changed

+238
-206
lines changed

7 files changed

+238
-206
lines changed

projects/client/RabbitMQ.Client/RabbitMQ.Client.csproj

+1
Original file line numberDiff line numberDiff line change
@@ -53,6 +53,7 @@
5353
<ItemGroup>
5454
<PackageReference Include="Microsoft.NETFramework.ReferenceAssemblies" Version="1.0.0" PrivateAssets="All" />
5555
<PackageReference Include="Microsoft.SourceLink.GitHub" Version="1.0.0" PrivateAssets="All"/>
56+
<PackageReference Include="System.Memory" Version="4.5.3" />
5657
</ItemGroup>
5758

5859
<ItemGroup Condition=" '$(Configuration)' == 'SignedRelease' ">

projects/client/RabbitMQ.Client/src/client/content/BytesWireFormatting.cs

+15-5
Original file line numberDiff line numberDiff line change
@@ -38,6 +38,7 @@
3838
// Copyright (c) 2007-2020 VMware, Inc. All rights reserved.
3939
//---------------------------------------------------------------------------
4040

41+
using System.Buffers;
4142
using System.Text;
4243

4344
using RabbitMQ.Util;
@@ -67,7 +68,7 @@ public static byte[] ReadBytes(NetworkBinaryReader reader, int count)
6768

6869
public static char ReadChar(NetworkBinaryReader reader)
6970
{
70-
return (char) reader.ReadUInt16();
71+
return (char)reader.ReadUInt16();
7172
}
7273

7374
public static double ReadDouble(NetworkBinaryReader reader)
@@ -119,7 +120,7 @@ public static void WriteBytes(NetworkBinaryWriter writer, byte[] source)
119120

120121
public static void WriteChar(NetworkBinaryWriter writer, char value)
121122
{
122-
writer.Write((ushort) value);
123+
writer.Write((ushort)value);
123124
}
124125

125126
public static void WriteDouble(NetworkBinaryWriter writer, double value)
@@ -149,9 +150,18 @@ public static void WriteSingle(NetworkBinaryWriter writer, float value)
149150

150151
public static void WriteString(NetworkBinaryWriter writer, string value)
151152
{
152-
byte[] bytes = Encoding.UTF8.GetBytes(value);
153-
writer.Write((ushort) bytes.Length);
154-
writer.Write(bytes);
153+
int maxLength = Encoding.UTF8.GetMaxByteCount(value.Length);
154+
byte[] bytes = ArrayPool<byte>.Shared.Rent(maxLength);
155+
try
156+
{
157+
int bytesUsed = Encoding.UTF8.GetBytes(value, 0, value.Length, bytes, 0);
158+
writer.Write((ushort)bytesUsed);
159+
writer.Write(bytes, 0, bytesUsed);
160+
}
161+
finally
162+
{
163+
ArrayPool<byte>.Shared.Return(bytes);
164+
}
155165
}
156166
}
157167
}

0 commit comments

Comments
 (0)