|
38 | 38 | // Copyright (c) 2007-2020 VMware, Inc. All rights reserved. |
39 | 39 | //--------------------------------------------------------------------------- |
40 | 40 |
|
| 41 | +using System.Buffers; |
41 | 42 | using System.Text; |
42 | 43 |
|
43 | 44 | using RabbitMQ.Util; |
@@ -67,7 +68,7 @@ public static byte[] ReadBytes(NetworkBinaryReader reader, int count) |
67 | 68 |
|
68 | 69 | public static char ReadChar(NetworkBinaryReader reader) |
69 | 70 | { |
70 | | - return (char) reader.ReadUInt16(); |
| 71 | + return (char)reader.ReadUInt16(); |
71 | 72 | } |
72 | 73 |
|
73 | 74 | public static double ReadDouble(NetworkBinaryReader reader) |
@@ -119,7 +120,7 @@ public static void WriteBytes(NetworkBinaryWriter writer, byte[] source) |
119 | 120 |
|
120 | 121 | public static void WriteChar(NetworkBinaryWriter writer, char value) |
121 | 122 | { |
122 | | - writer.Write((ushort) value); |
| 123 | + writer.Write((ushort)value); |
123 | 124 | } |
124 | 125 |
|
125 | 126 | public static void WriteDouble(NetworkBinaryWriter writer, double value) |
@@ -149,9 +150,18 @@ public static void WriteSingle(NetworkBinaryWriter writer, float value) |
149 | 150 |
|
150 | 151 | public static void WriteString(NetworkBinaryWriter writer, string value) |
151 | 152 | { |
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 | + } |
155 | 165 | } |
156 | 166 | } |
157 | 167 | } |
0 commit comments