chr
2026-04-05 fe750b791d5b517cc4e9bc8e99a9a75139a0cfba
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
using System;
using System.IO;
using System.Threading;
namespace OpenTap
{
    /// <summary> TeeStream allows many reader-streams to be created from one.
    /// If one reader is slower than the others, it will block until the slowest catches up. </summary>
    class TeeStream
    {
        /// <summary> Represents a client stream that reads from a shared TeeStream. </summary>
        class TeeStreamClient : Stream
        {
            /// <summary> Keeps track of the current position in the stream for this client. </summary>
            long globalOffset;
            
            /// <summary>  Reference to the host TeeStream that this client reads from. </summary>
            readonly TeeStream streamHost;
            public TeeStreamClient(TeeStream streamHost) => this.streamHost = streamHost;
            
            /// <summary> This stream is read-only. Flush does nothing. </summary>
            public override void Flush()
            {
                
            }
            
            /// <summary> Reads a sequence of bytes from the current stream and advances the position within the stream. </summary>
            public override int Read(byte[] buffer, int offset, int count)
            {
                int read = streamHost.Read(buffer, globalOffset, offset, count);
                globalOffset += read;
                return read;
            }
            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();
            }
            public override bool CanRead => true;
            public override bool CanSeek => false;
            public override bool CanWrite => false;
            public override long Length => streamHost.Length;
            public override long Position 
            { 
                get => globalOffset; 
                set  { } 
            }
 
            protected override void Dispose(bool disposing)
            {
                base.Dispose(disposing);
                
                // flush everything. There may be other peers so doing this makes sure that nobody waits for this client to read.
                this.CopyTo(Stream.Null);
            }
        }
 
        public long Length => mainStream.Length;
        public long Position => mainStreamPosition - blockLength;
        public long blockLength;
            
        readonly Stream mainStream;
        byte[] currentBlock;
 
        public TeeStream(Stream mainStream) => this.mainStream = mainStream;
        
        Stream CreateClientStream() => new TeeStreamClient(this);
 
        public Stream[] CreateClientStreams(int count)
        {
            if (count == 0)
            {
                mainStream.Dispose();
                return Array.Empty<Stream>();
            }
            currentBlock = new byte[4096 * count];
            clientCount = count;
            var result = new Stream[count];
            for (int i = 0; i < count; i++)
            {
                result[i] = CreateClientStream();
            }
            return result;
        }
        bool done;
        Exception readException = null;
        
        void ReadNextBlock()
        {
            // at this point everyone is waiting for the next block.
            int len;
            try
            {
                len = mainStream.Read(currentBlock, 0, currentBlock.Length);
            }
            catch(Exception exception)
            {
                this.readException = exception;
                len = 0;
            }
            
            // user interlocked.add to ensure that other threads will get the updated value.
            Interlocked.Add(ref mainStreamPosition, len);
            
            if (len == 0)
            {
                // We are done. let's stop.
                done = true;
                mainStream.Close();
                mainStream.Dispose();
            }
            blockLength = len;
            
            var oldEvt = evt;
            var w2 = waiting;
            evt = new SemaphoreSlim(0);
            Interlocked.Exchange(ref waiting, 0);
            oldEvt.Release(w2);
        }
        
        SemaphoreSlim evt = new SemaphoreSlim(0);
        int waiting;
        int clientCount;
        long mainStreamPosition;
        public int Read(byte[] buffer, long subStreamPosition, int bufferOffset, int count)
        {
            if (done) return 0;
            if (readException != null)
                throw readException;
            
            // Offset into the current block.
            long blockOffset = subStreamPosition - (mainStreamPosition - blockLength);
            if (blockOffset < 0) 
                throw new InvalidOperationException("Unexpected position calculated");
            
            var waitEvent = evt;
            
            // if the block offset is greater than the size of the block, we need to get/wait for the next block. 
            if (blockOffset >= blockLength)
            {
                if (Interlocked.Increment(ref waiting) == clientCount)
                {
                    // All clients are waiting - read the next block.
                    ReadNextBlock();
                }
                else
                {
                    // wait for a new block.
                    waitEvent.Wait();
                }
                // new blocks released. start over.
                return Read(buffer, subStreamPosition, bufferOffset, count);
            }
 
            // read the block byte-by-byte.
            for (int i = 0; i < count; i++)
            {
                long o2 = subStreamPosition - (mainStreamPosition - blockLength) + i;
                if (o2 >= blockLength)
                {
                    // End of the block reached.
                    // start Read over with new args.
                    int r = Read(buffer, subStreamPosition + i, bufferOffset + i, count - i);
                    if (r == 0) return i;
                    return r + i;
                }
                buffer[i + bufferOffset] = currentBlock[o2];
            }
            return count;
        }
    }
}