/// <exception cref="ArgumentNullException"><paramref name="source"/> is null.</exception> /// <exception cref="ArgumentOutOfRangeException"><paramref name="byteCount"/> is negative.</exception> public int WriteBytes(Stream source, int byteCount) { if (source == null) { Throw.ArgumentNull(nameof(source)); } if (byteCount < 0) { Throw.ArgumentOutOfRange(nameof(byteCount)); } int start = Advance(byteCount); int bytesRead = source.TryReadAll(_buffer, start, byteCount); _position = start + bytesRead; return bytesRead; }
/// <exception cref="ArgumentNullException"><paramref name="source"/> is null.</exception> /// <exception cref="ArgumentOutOfRangeException"><paramref name="byteCount"/> is negative.</exception> /// <exception cref="InvalidOperationException">Builder is not writable, it has been linked with another one.</exception> /// <returns>Bytes successfully written from the <paramref name="source" />.</returns> public int TryWriteBytes(Stream source, int byteCount) { if (source == null) { throw new ArgumentNullException(nameof(source)); } if (byteCount < 0) { throw new ArgumentOutOfRangeException(nameof(byteCount)); } if (byteCount == 0) { return 0; } int bytesRead = 0; int bytesToCurrent = Math.Min(FreeBytes, byteCount); if (bytesToCurrent > 0) { bytesRead = source.TryReadAll(_buffer, Length, bytesToCurrent); AddLength(bytesRead); if (bytesRead != bytesToCurrent) { return bytesRead; } } int remaining = byteCount - bytesToCurrent; if (remaining > 0) { Expand(remaining); bytesRead = source.TryReadAll(_buffer, 0, remaining); AddLength(bytesRead); bytesRead += bytesToCurrent; } return bytesRead; }