/// <inheritdoc/> public void Dispose() { if (!this.leaveOpen) { this.stream.Dispose(); } this.sequenceRental.Dispose(); this.sequenceRental = default; }
internal BufferWriter(SequencePool sequencePool, byte[] array) { _buffered = 0; _bytesCommitted = 0; _sequencePool = sequencePool ?? throw new ArgumentNullException(nameof(sequencePool)); _rental = default; _output = null; _segment = new ArraySegment <byte>(array); _span = _segment.AsSpan(); }
private void MigrateToSequence() { if (this._sequencePool != null) { // We were writing to our private scratch memory, so we have to copy it into the actual writer. _rental = _sequencePool.Rent(); _output = _rental.Value; var realSpan = _output.GetSpan(_buffered); _segment.AsSpan(0, _buffered).CopyTo(realSpan); _sequencePool = null; } }
public BufferWriter(IBufferWriter <byte> output) { _buffered = 0; _bytesCommitted = 0; _output = output ?? throw new ArgumentNullException(nameof(output)); _sequencePool = default; _rental = default; var memory = _output.GetMemoryCheckResult(); MemoryMarshal.TryGetArray(memory, out _segment); _span = memory.Span; }
/// <summary> /// Serializes a given value to the specified stream. /// </summary> /// <param name="stream">The stream to serialize to.</param> /// <param name="value">The value to serialize.</param> /// <param name="options">The options. Use <c>null</c> to use default options.</param> /// <param name="cancellationToken">A cancellation token.</param> /// <returns>A task that completes with the result of the async serialization operation.</returns> /// <exception cref="MessagePackSerializationException">Thrown when any error occurs during serialization.</exception> public static async Task SerializeAsync <T>(Stream stream, T value, MessagePackSerializerOptions options = null, CancellationToken cancellationToken = default) { cancellationToken.ThrowIfCancellationRequested(); using (SequencePool.Rental sequenceRental = SequencePool.Shared.Rent()) { Serialize <T>(sequenceRental.Value, value, options, cancellationToken); try { foreach (ReadOnlyMemory <byte> segment in sequenceRental.Value.AsReadOnlySequence) { cancellationToken.ThrowIfCancellationRequested(); await stream.WriteAsync(segment, cancellationToken).ConfigureAwait(false); } } catch (Exception ex) { throw new MessagePackSerializationException("Error occurred while writing the serialized data to the stream.", ex); } } }