Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
50 changes: 34 additions & 16 deletions src/Microsoft.OData.Core/Json/ODataJsonValueSerializer.cs
Original file line number Diff line number Diff line change
Expand Up @@ -382,15 +382,24 @@ public virtual void WriteUntypedValue(

public virtual void WriteStreamValue(ODataBinaryStreamValue streamValue)
{
Stream stream = this.JsonWriter.StartStreamValueScope();
streamValue.Stream.CopyTo(stream);
stream.Flush();
stream.Dispose();
this.JsonWriter.EndStreamValueScope();

if (!streamValue.LeaveOpen)
try
{
streamValue.Stream.Dispose();
Stream stream = this.JsonWriter.StartStreamValueScope();
try
{
streamValue.Stream.CopyTo(stream);
}
finally
{
this.JsonWriter.EndStreamValueScope();
}
}
finally
{
if (!streamValue.LeaveOpen)
{
streamValue.Stream.Dispose();
}
}
}

Expand Down Expand Up @@ -722,15 +731,24 @@ public virtual Task WriteUntypedValueAsync(
/// <returns>A task that represents the asynchronous write operation.</returns>
public virtual async Task WriteStreamValueAsync(ODataBinaryStreamValue streamValue)
{
Stream stream = await this.JsonWriter.StartStreamValueScopeAsync().ConfigureAwait(false);
await streamValue.Stream.CopyToAsync(stream).ConfigureAwait(false);
await stream.FlushAsync().ConfigureAwait(false);
await stream.DisposeAsync().ConfigureAwait(false);
await this.JsonWriter.EndStreamValueScopeAsync().ConfigureAwait(false);

if (!streamValue.LeaveOpen)
try
{
await streamValue.Stream.DisposeAsync().ConfigureAwait(false);
Stream stream = await this.JsonWriter.StartStreamValueScopeAsync().ConfigureAwait(false);
try
{
await streamValue.Stream.CopyToAsync(stream).ConfigureAwait(false);
}
finally
{
await this.JsonWriter.EndStreamValueScopeAsync().ConfigureAwait(false);
}
}
finally
{
if (!streamValue.LeaveOpen)
{
await streamValue.Stream.DisposeAsync().ConfigureAwait(false);
}
}
}

Expand Down
96 changes: 67 additions & 29 deletions src/Microsoft.OData.Core/Json/ODataUtf8JsonWriter.Stream.cs
Original file line number Diff line number Diff line change
Expand Up @@ -43,8 +43,9 @@ public Stream StartStreamValueScope()
/// </summary>
public void EndStreamValueScope()
{
this.binaryValueStream?.Dispose();
Stream stream = this.binaryValueStream;
this.binaryValueStream = null;
stream?.Dispose();
this.Flush();

this.bufferWriter.Write(this.DoubleQuote.Slice(0, 1).Span);
Expand Down Expand Up @@ -76,10 +77,11 @@ public async Task<Stream> StartStreamValueScopeAsync()
/// <returns>A task representing the asynchronous operation.</returns>
public async Task EndStreamValueScopeAsync()
{
if (this.binaryValueStream != null)
Stream stream = this.binaryValueStream;
this.binaryValueStream = null;
if (stream != null)
{
await this.binaryValueStream.DisposeAsync().ConfigureAwait(false);
this.binaryValueStream = null;
await stream.DisposeAsync().ConfigureAwait(false);
}

await this.DrainBufferIfThresholdReachedAsync().ConfigureAwait(false);
Expand All @@ -96,16 +98,24 @@ public async Task EndStreamValueScopeAsync()
internal sealed class ODataUtf8JsonWriteStream : Stream
{
private readonly ODataUtf8JsonWriter jsonWriter = null;
private readonly ArrayPool<byte> arrayPool;
private byte[] buffer;
int numBytesNotWrittenFromPreviousChunk = 0;
private int disposed;
private int numBytesNotWrittenFromPreviousChunk = 0;

/// <summary>
/// Initializes a new instance of the <see cref="ODataUtf8JsonWriter"> class with the specified ODataUtf8JsonWriter.
/// </summary>
/// <param name="writer">The OData UTF-8 JSON writer to write to.</param>
internal ODataUtf8JsonWriteStream(ODataUtf8JsonWriter writer)
: this(writer, ArrayPool<byte>.Shared)
{
}

internal ODataUtf8JsonWriteStream(ODataUtf8JsonWriter writer, ArrayPool<byte> arrayPool)
{
this.jsonWriter = writer;
this.arrayPool = arrayPool;
}

public override bool CanRead => false;
Expand Down Expand Up @@ -147,22 +157,35 @@ public override async Task FlushAsync(CancellationToken cancellationToken)
/// <param name="disposing">true if called from Dispose; false if called form the finalizer.</param>
protected override void Dispose(bool disposing)
{
if (this.numBytesNotWrittenFromPreviousChunk > 0)
if (Interlocked.Exchange(ref this.disposed, 1) != 0)
{
// If there are unprocessed bytes, encode and write them as the final block.
ReadOnlySpan<byte> bytesNotProcessedFromPreviousChunk = this.buffer.AsSpan().Slice(0, this.numBytesNotWrittenFromPreviousChunk);

this.jsonWriter.Base64EncodeAndWriteChunk(bytesNotProcessedFromPreviousChunk, isFinalBlock: true, out this.numBytesNotWrittenFromPreviousChunk);
Debug.Assert(numBytesNotWrittenFromPreviousChunk == 0, "numBytesNotWrittenFromPreviousChunk == 0");
return;
}

if (this.buffer != null)
byte[] buffer = Interlocked.Exchange(ref this.buffer, null);

try
{
ArrayPool<byte>.Shared.Return(this.buffer);
if (buffer != null && this.numBytesNotWrittenFromPreviousChunk > 0)
{
// If there are unprocessed bytes, encode and write them as the final block.
ReadOnlySpan<byte> bytesNotProcessedFromPreviousChunk = buffer.AsSpan().Slice(0, this.numBytesNotWrittenFromPreviousChunk);

this.jsonWriter.Base64EncodeAndWriteChunk(bytesNotProcessedFromPreviousChunk, isFinalBlock: true, out this.numBytesNotWrittenFromPreviousChunk);
Debug.Assert(numBytesNotWrittenFromPreviousChunk == 0, "numBytesNotWrittenFromPreviousChunk == 0");
}

this.Flush();
}
finally
{
if (buffer != null)
{
this.arrayPool.Return(buffer);
}

this.Flush();
base.Dispose(disposing);
base.Dispose(disposing);
}
}

/// <summary>
Expand All @@ -171,21 +194,36 @@ protected override void Dispose(bool disposing)
/// <returns>A <see cref="ValueTask"/> representing the asynchronous operation.</returns>
public override async ValueTask DisposeAsync()
{
if (this.numBytesNotWrittenFromPreviousChunk > 0)
if (Interlocked.Exchange(ref this.disposed, 1) != 0)
{
// If there are unprocessed bytes, encode and write them as the final block.
ReadOnlyMemory<byte> bytesNotProcessedFromPreviousChunk = this.buffer.AsMemory().Slice(0, this.numBytesNotWrittenFromPreviousChunk);

this.jsonWriter.Base64EncodeAndWriteChunk(bytesNotProcessedFromPreviousChunk.Span, isFinalBlock: true, out this.numBytesNotWrittenFromPreviousChunk);
Debug.Assert(numBytesNotWrittenFromPreviousChunk == 0, "numBytesNotWrittenFromPreviousChunk == 0");
return;
}

if (this.buffer != null)
byte[] buffer = Interlocked.Exchange(ref this.buffer, null);

try
{
ArrayPool<byte>.Shared.Return(this.buffer);
if (buffer != null && this.numBytesNotWrittenFromPreviousChunk > 0)
{
// If there are unprocessed bytes, encode and write them as the final block.
ReadOnlyMemory<byte> bytesNotProcessedFromPreviousChunk = buffer.AsMemory().Slice(0, this.numBytesNotWrittenFromPreviousChunk);

this.jsonWriter.Base64EncodeAndWriteChunk(bytesNotProcessedFromPreviousChunk.Span, isFinalBlock: true, out this.numBytesNotWrittenFromPreviousChunk);
Debug.Assert(numBytesNotWrittenFromPreviousChunk == 0, "numBytesNotWrittenFromPreviousChunk == 0");
}

await this.jsonWriter.FlushAsync().ConfigureAwait(false);
}
finally
{
if (buffer != null)
{
this.arrayPool.Return(buffer);
}

await this.jsonWriter.FlushAsync().ConfigureAwait(false);
base.Dispose(true);
GC.SuppressFinalize(this);
}
}

/// <summary>
Expand Down Expand Up @@ -263,7 +301,7 @@ private void WriteByteValueInChunks(ReadOnlySpan<byte> value)
int totalLength = bytesNotProcessedFromPreviousChunk.Length + chunk.Length;

// Rent an array to hold bytes from both previous and current chunks.
byte[] combinedArray = ArrayPool<byte>.Shared.Rent(totalLength);
byte[] combinedArray = this.arrayPool.Rent(totalLength);

// Copy bytes from bytesNotProcessedFromPreviousChunk to the combined array
bytesNotProcessedFromPreviousChunk.CopyTo(combinedArray);
Expand All @@ -273,7 +311,7 @@ private void WriteByteValueInChunks(ReadOnlySpan<byte> value)

WriteChunk(combinedArray.AsSpan().Slice(0, totalLength), totalLength, isFinalBlock);

ArrayPool<byte>.Shared.Return(combinedArray);
this.arrayPool.Return(combinedArray);
}
else
{
Expand Down Expand Up @@ -309,7 +347,7 @@ private async ValueTask WriteByteValueInChunksAsync(ReadOnlyMemory<byte> value)
int totalLength = bytesNotProcessedFromPreviousChunk.Length + chunk.Length;

// Rent an array to hold bytes from both previous and current chunks.
byte[] combinedArray = ArrayPool<byte>.Shared.Rent(totalLength);
byte[] combinedArray = this.arrayPool.Rent(totalLength);

// Copy bytes from bytesNotProcessedFromPreviousChunk to the combined array
bytesNotProcessedFromPreviousChunk.Span.CopyTo(combinedArray);
Expand All @@ -319,7 +357,7 @@ private async ValueTask WriteByteValueInChunksAsync(ReadOnlyMemory<byte> value)

WriteChunk(combinedArray.AsSpan().Slice(0, totalLength), totalLength, isFinalBlock);

ArrayPool<byte>.Shared.Return(combinedArray);
this.arrayPool.Return(combinedArray);
}
else
{
Expand All @@ -345,7 +383,7 @@ private void WriteChunk(ReadOnlySpan<byte> chunk, int chunkLength, bool isFinalB
{
if (this.buffer == null)
{
this.buffer = ArrayPool<byte>.Shared.Rent(ODataUtf8JsonWriter.chunkSize);
this.buffer = this.arrayPool.Rent(ODataUtf8JsonWriter.chunkSize);
}

// Update the buffer with unprocessed bytes from the current chunk.
Expand Down
Loading