Skip to content

Commit 517be5c

Browse files
committed
Added Write ReadOnlySpan of char override to HttpResponseStreamWriter
1 parent c848c33 commit 517be5c

File tree

2 files changed

+61
-0
lines changed

2 files changed

+61
-0
lines changed

src/Http/WebUtilities/src/HttpResponseStreamWriter.cs

Lines changed: 38 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -127,6 +127,25 @@ public override void Write(char[] values, int index, int count)
127127
}
128128
}
129129

130+
public override void Write(ReadOnlySpan<char> values)
131+
{
132+
if (_disposed)
133+
{
134+
throw new ObjectDisposedException(nameof(HttpResponseStreamWriter));
135+
}
136+
137+
bool completed;
138+
do
139+
{
140+
if (_charBufferCount == _charBufferSize)
141+
{
142+
FlushInternal(flushEncoder: false);
143+
}
144+
145+
completed = CopyToCharBuffer(ref values);
146+
} while (!completed);
147+
}
148+
130149
public override void Write(string value)
131150
{
132151
if (_disposed)
@@ -423,6 +442,25 @@ private void CopyToCharBuffer(char[] values, ref int index, ref int count)
423442
count -= remaining;
424443
}
425444

445+
private bool CopyToCharBuffer(ref ReadOnlySpan<char> values)
446+
{
447+
var remaining = Math.Min(_charBufferSize - _charBufferCount, values.Length);
448+
449+
var source = values.Slice(0, remaining);
450+
var destination = new Span<char>(_charBuffer, _charBufferCount, remaining);
451+
source.CopyTo(destination);
452+
453+
_charBufferCount += remaining;
454+
455+
if (remaining < values.Length)
456+
{
457+
values = values.Slice(remaining);
458+
return false;
459+
}
460+
461+
return true;
462+
}
463+
426464
[MethodImpl(MethodImplOptions.NoInlining)]
427465
private static Task GetObjectDisposedTask()
428466
{

src/Http/WebUtilities/test/HttpResponseStreamWriterTest.cs

Lines changed: 23 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -253,6 +253,29 @@ public void WriteCharArray_WritesToStream(int byteLength)
253253
Assert.Equal(byteLength, stream.Length);
254254
}
255255

256+
[Theory]
257+
[InlineData(1023)]
258+
[InlineData(1024)]
259+
[InlineData(1050)]
260+
[InlineData(2048)]
261+
public void WriteReadOnlySpanChar_WritesToStream(int byteLength)
262+
{
263+
// Arrange
264+
var stream = new TestMemoryStream();
265+
var writer = new HttpResponseStreamWriter(stream, Encoding.UTF8);
266+
267+
// Act
268+
using (writer)
269+
{
270+
var array = new string('a', byteLength).ToCharArray();
271+
var span = new ReadOnlySpan<char>(array);
272+
writer.Write(span);
273+
}
274+
275+
// Assert
276+
Assert.Equal(byteLength, stream.Length);
277+
}
278+
256279
[Theory]
257280
[InlineData(1023)]
258281
[InlineData(1024)]

0 commit comments

Comments
 (0)