Skip to content
This repository was archived by the owner on Dec 24, 2022. It is now read-only.

Commit 5654a94

Browse files
committed
fix usages of ReleaseBufferToPool
1 parent 51ebd7b commit 5654a94

File tree

1 file changed

+14
-7
lines changed

1 file changed

+14
-7
lines changed

src/ServiceStack.Text/DefaultMemory.cs

Lines changed: 14 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -460,23 +460,31 @@ public override void Write(Stream stream, ReadOnlyMemory<byte> value)
460460

461461
public override Task WriteAsync(Stream stream, ReadOnlySpan<char> value, CancellationToken token = default)
462462
{
463+
// encode the span into a buffer; this should never fail, so if it does: something
464+
// is very very ill; don't stress about returning to the pool
463465
byte[] bytes = BufferPool.GetBuffer(Encoding.UTF8.GetMaxByteCount(value.Length));
466+
var chars = value.ToArray();
467+
int bytesCount = Encoding.UTF8.GetBytes(chars, 0, chars.Length, bytes, 0);
468+
// now do the write async - this returns to the pool
469+
return WriteAsyncAndReturn(stream, bytes, 0, bytesCount, token);
470+
}
471+
472+
private static async Task WriteAsyncAndReturn(Stream stream, byte[] bytes, int offset, int count, CancellationToken token)
473+
{
464474
try
465475
{
466-
var chars = value.ToArray();
467-
int bytesCount = Encoding.UTF8.GetBytes(chars, 0, chars.Length, bytes, 0);
468-
return stream.WriteAsync(bytes, 0, bytesCount, token);
476+
await stream.WriteAsync(bytes, offset, count, token);
469477
}
470478
finally
471479
{
472480
BufferPool.ReleaseBufferToPool(ref bytes);
473481
}
474482
}
475-
483+
476484
public override Task WriteAsync(Stream stream, ReadOnlyMemory<char> value, CancellationToken token = default) =>
477485
WriteAsync(stream, value.Span, token);
478486

479-
public override Task WriteAsync(Stream stream, ReadOnlyMemory<byte> value, CancellationToken token = default)
487+
public override async Task WriteAsync(Stream stream, ReadOnlyMemory<byte> value, CancellationToken token = default)
480488
{
481489
byte[] bytes = BufferPool.GetBuffer(value.Length);
482490
try
@@ -485,11 +493,10 @@ public override Task WriteAsync(Stream stream, ReadOnlyMemory<byte> value, Cance
485493
if (stream is MemoryStream ms)
486494
{
487495
ms.Write(bytes, 0, value.Length);
488-
return TypeConstants.EmptyTask;
489496
}
490497
else
491498
{
492-
return stream.WriteAsync(bytes, 0, value.Length, token);
499+
await stream.WriteAsync(bytes, 0, value.Length, token);
493500
}
494501
}
495502
finally

0 commit comments

Comments
 (0)