Skip to content

Commit 9d06fc7

Browse files
committed
Use span overloads
1 parent d6d58d0 commit 9d06fc7

File tree

1 file changed

+29
-44
lines changed

1 file changed

+29
-44
lines changed

src/Shared/ServerInfrastructure/BufferExtensions.cs

Lines changed: 29 additions & 44 deletions
Original file line numberDiff line numberDiff line change
@@ -49,17 +49,12 @@ internal static unsafe void WriteAscii(ref this BufferWriter<PipeWriter> buffer,
4949

5050
var dataLength = data.Length;
5151
var bytes = buffer.Span;
52-
var bytesLength = bytes.Length;
5352

5453
// Fast path, try encoding to the available memory directly
55-
if (dataLength <= bytesLength)
54+
if (dataLength <= bytes.Length)
5655
{
57-
fixed (char* charsPtr = data)
58-
fixed (byte* bytesPtr = &MemoryMarshal.GetReference(bytes))
59-
{
60-
Encoding.ASCII.GetBytes(charsPtr, dataLength, bytesPtr, bytesLength);
61-
buffer.Advance(dataLength);
62-
}
56+
Encoding.ASCII.GetBytes(data, bytes);
57+
buffer.Advance(dataLength);
6358
}
6459
else
6560
{
@@ -141,44 +136,34 @@ private static void WriteNumericMultiWrite(ref this BufferWriter<PipeWriter> buf
141136
[MethodImpl(MethodImplOptions.NoInlining)]
142137
private unsafe static void WriteAsciiMultiWrite(ref this BufferWriter<PipeWriter> buffer, string data)
143138
{
144-
Debug.Assert(!string.IsNullOrEmpty(data));
145-
146-
fixed (char* charsPtr = data)
139+
var dataLength = data.Length;
140+
var offset = 0;
141+
var bytes = buffer.Span;
142+
do
147143
{
148-
var dataLength = data.Length;
149-
var offset = 0;
150-
var bytes = buffer.Span;
151-
var bytesLength = bytes.Length;
152-
do
144+
var writable = Math.Min(dataLength - offset, bytes.Length);
145+
// Zero length spans are possible
146+
if (writable > 0)
153147
{
154-
var writable = Math.Min(dataLength - offset, bytesLength);
155-
// Zero length spans are possible
156-
if (writable > 0)
157-
{
158-
fixed (byte* bytesPtr = &MemoryMarshal.GetReference(bytes))
159-
{
160-
Encoding.ASCII.GetBytes(charsPtr + offset, writable, bytesPtr, bytesLength);
161-
162-
buffer.Advance(writable);
163-
offset += writable;
164-
}
165-
}
166-
167-
// Get new span if more to encode, and reset bytesLength
168-
if (offset < dataLength)
169-
{
170-
buffer.Ensure();
171-
bytes = buffer.Span;
172-
bytesLength = bytes.Length;
173-
continue;
174-
}
175-
else
176-
{
177-
// Encoded everything
178-
break;
179-
}
180-
} while (true);
181-
}
148+
Encoding.ASCII.GetBytes(data.AsSpan(offset, writable), bytes);
149+
150+
buffer.Advance(writable);
151+
offset += writable;
152+
}
153+
154+
// Get new span if more to encode, and reset bytesLength
155+
if (offset < dataLength)
156+
{
157+
buffer.Ensure();
158+
bytes = buffer.Span;
159+
continue;
160+
}
161+
else
162+
{
163+
// Encoded everything
164+
break;
165+
}
166+
} while (true);
182167
}
183168

184169
private static byte[] NumericBytesScratch => _numericBytesScratch ?? CreateNumericBytesScratch();

0 commit comments

Comments
 (0)