// Copyright (C) 2024, The Duplicati Team // https://duplicati.com, hello@duplicati.com // // Permission is hereby granted, free of charge, to any person obtaining a // copy of this software and associated documentation files (the "Software"), // to deal in the Software without restriction, including without limitation // the rights to use, copy, modify, merge, publish, distribute, sublicense, // and/or sell copies of the Software, and to permit persons to whom the // Software is furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING // FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER // DEALINGS IN THE SOFTWARE. using System; using System.Collections.Generic; using System.IO; namespace Duplicati.Library.Utility; /// /// A stream that combines multiple streams into one. /// public class CombinedStream : Stream { /// /// The streams to combine /// private readonly Queue _streams; /// /// Flag keeping track of whether to leave the streams open when the combined stream is closed /// private readonly bool _leaveOpen; /// /// Creates a new combined stream /// /// The streams to combine /// True to leave the streams open when the combined stream is closed public CombinedStream(IEnumerable streams, bool leaveOpen = false) { _streams = new Queue(streams); _leaveOpen = leaveOpen; } /// public override bool CanRead => true; /// public override bool CanSeek => false; /// public override bool CanWrite => false; /// public override long Length => throw new NotSupportedException(); /// public override long Position { get => throw new NotSupportedException(); set => throw new NotSupportedException(); } /// public override void Flush() { } /// public override int Read(byte[] buffer, int offset, int count) { if (_streams.Count == 0) return 0; var bytesRead = _streams.Peek().Read(buffer, offset, count); if (bytesRead == 0) { var prev = _streams.Dequeue(); if (!_leaveOpen) prev.Dispose(); return Read(buffer, offset, count); } return bytesRead; } /// public override long Seek(long offset, SeekOrigin origin) { throw new NotSupportedException(); } /// public override void SetLength(long value) { throw new NotSupportedException(); } /// public override void Write(byte[] buffer, int offset, int count) { throw new NotSupportedException(); } /// protected override void Dispose(bool disposing) { if (!disposing) return; if (!_leaveOpen) foreach (var stream in _streams) stream.Dispose(); _streams.Clear(); } }