Skip to content

Commit 3942648

Browse files
committed
Betterize
1 parent 9d06fc7 commit 3942648

File tree

1 file changed

+20
-25
lines changed

1 file changed

+20
-25
lines changed

src/Shared/ServerInfrastructure/BufferExtensions.cs

Lines changed: 20 additions & 25 deletions
Original file line numberDiff line numberDiff line change
@@ -40,21 +40,20 @@ public static ArraySegment<byte> GetArray(this ReadOnlyMemory<byte> memory)
4040
return result;
4141
}
4242

43-
internal static unsafe void WriteAscii(ref this BufferWriter<PipeWriter> buffer, string data)
43+
internal static void WriteAscii(ref this BufferWriter<PipeWriter> buffer, string data)
4444
{
4545
if (string.IsNullOrEmpty(data))
4646
{
4747
return;
4848
}
4949

50-
var dataLength = data.Length;
51-
var bytes = buffer.Span;
52-
50+
var dest = buffer.Span;
51+
var sourceLength = data.Length;
5352
// Fast path, try encoding to the available memory directly
54-
if (dataLength <= bytes.Length)
53+
if (sourceLength <= dest.Length)
5554
{
56-
Encoding.ASCII.GetBytes(data, bytes);
57-
buffer.Advance(dataLength);
55+
Encoding.ASCII.GetBytes(data, dest);
56+
buffer.Advance(sourceLength);
5857
}
5958
else
6059
{
@@ -134,35 +133,31 @@ private static void WriteNumericMultiWrite(ref this BufferWriter<PipeWriter> buf
134133
}
135134

136135
[MethodImpl(MethodImplOptions.NoInlining)]
137-
private unsafe static void WriteAsciiMultiWrite(ref this BufferWriter<PipeWriter> buffer, string data)
136+
private static void WriteAsciiMultiWrite(ref this BufferWriter<PipeWriter> buffer, string data)
138137
{
139138
var dataLength = data.Length;
140139
var offset = 0;
141140
var bytes = buffer.Span;
142141
do
143142
{
144143
var writable = Math.Min(dataLength - offset, bytes.Length);
145-
// Zero length spans are possible
146-
if (writable > 0)
147-
{
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
144+
// Zero length spans are possible, though unlikely.
145+
// ASCII.GetBytes and .Advance will both handle them so we won't special case for them.
146+
Encoding.ASCII.GetBytes(data.AsSpan(offset, writable), bytes);
147+
buffer.Advance(writable);
148+
149+
// The `add` will macro-op fuse with `if` test.
150+
offset += writable;
151+
if (offset >= dataLength)
162152
{
153+
Debug.Assert(offset == dataLength);
163154
// Encoded everything
164155
break;
165156
}
157+
158+
// Get new span, more to encode.
159+
buffer.Ensure();
160+
bytes = buffer.Span;
166161
} while (true);
167162
}
168163

0 commit comments

Comments
 (0)