/// <summary> /// Deserialize UTF8 JSON bytes from the supplied stream onto a <typeparamref name="T"/> instance. /// </summary> /// <typeparam name="T">The type being deserialized.</typeparam> /// <param name="stream"><see cref="Stream"/>.</param> /// <param name="instance">Instance to deserialize onto.</param> /// <param name="stateMachine"><see cref="DeserializeStateMachine{T}"/>.</param> /// <param name="bufferSize">Initial size of the buffer to use when reading from the <paramref name="stream"/>.</param> /// <param name="cancellationToken"><see cref="CancellationToken"/>.</param> /// <returns>Task to await the operation.</returns> public static async Task DeserializeAsync <T>(Stream stream, T instance, DeserializeStateMachine <T> stateMachine, int bufferSize = 8192, CancellationToken cancellationToken = default) { if (stream == null) { throw new ArgumentNullException(nameof(stream)); } if (instance == null) { throw new ArgumentNullException(nameof(instance)); } if (stateMachine == null) { throw new ArgumentNullException(nameof(stateMachine)); } byte[] buffer = RentBufferFunc(bufferSize); try { int state = 0; JsonReaderState?readerState = null; ContinueSingleBuffer: int offset = 0; int bytesRead; while (true) { Memory <byte> data = new(buffer); #if NETSTANDARD2_0 bytesRead = await stream.ReadAsync(buffer, offset, buffer.Length - offset, cancellationToken).ConfigureAwait(false); #else bytesRead = await stream.ReadAsync(offset > 0?data[offset..] : data, cancellationToken).ConfigureAwait(false);
/// <summary> /// Deserialize UTF8 JSON bytes from the supplied stream into a <typeparamref name="T"/> instance. /// </summary> /// <typeparam name="T">The type being deserialized.</typeparam> /// <param name="stream"><see cref="Stream"/>.</param> /// <param name="stateMachine"><see cref="DeserializeStateMachine{T}"/>.</param> /// <param name="bufferSize">Initial size of the buffer to use when reading from the <paramref name="stream"/>.</param> /// <param name="cancellationToken"><see cref="CancellationToken"/>.</param> /// <returns>Deserialized instance of <typeparamref name="T"/>.</returns> public static async Task <T> DeserializeAsync <T>(Stream stream, DeserializeStateMachine <T> stateMachine, int bufferSize = 8192, CancellationToken cancellationToken = default) where T : new() { T instance = new(); await DeserializeAsync(stream, instance, stateMachine, bufferSize, cancellationToken).ConfigureAwait(false); return(instance); }