-
Notifications
You must be signed in to change notification settings - Fork 10
/
DataStream.cs
871 lines (757 loc) · 31.5 KB
/
DataStream.cs
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
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
// Copyright (c) 2019 SceneGate
// 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.
namespace Yarhl.IO
{
using System;
using System.Buffers;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using System.IO;
using System.Linq;
using Yarhl.IO.StreamFormat;
/// <summary>
/// Virtual <see cref="Stream" /> with substream capabilities and read/write
/// abstraction layer.
/// </summary>
/// <remarks>
/// The type is thread-safe at the level of the substream. For instance, it
/// is safe to use several DataStream over the same base stream in parallel.
/// The type is not thread-safe for its method. For instance, it is NOT safe
/// to use the same DataStream in different threads at the same time.
/// </remarks>
[SuppressMessage(
"",
"S3881",
Justification = "Historical reasons: https://docs.microsoft.com/en-us/dotnet/api/system.io.stream.dispose")]
[DebuggerDisplay(
"pos={\"0x\" + Position.ToString(\"X\")}, " +
"len={\"0x\" + Length.ToString(\"X\")}, " +
"offset={\"0x\" + Offset.ToString(\"X\")}")]
public partial class DataStream : Stream
{
static readonly ConcurrentDictionary<Stream, StreamInfo> Instances = new ConcurrentDictionary<Stream, StreamInfo>();
readonly Stack<long> positionStack = new Stack<long>();
readonly bool canExpand;
readonly bool hasOwnsership;
readonly StreamInfo streamInfo;
readonly Stream baseStream;
bool disposed;
long offset;
long position;
long length;
/// <summary>
/// Initializes a new instance of the <see cref="DataStream"/> class.
/// A new stream is created in memory.
/// </summary>
public DataStream()
: this(new RecyclableMemoryStream())
{
}
/// <summary>
/// Initializes a new instance of the <see cref="DataStream" /> class.
/// </summary>
/// <remarks>
/// <p>The dispose ownership is transferred to this stream.</p>
/// </remarks>
/// <param name="stream">Base stream.</param>
public DataStream(Stream stream)
: this(stream, 0, stream?.Length ?? -1, true)
{
canExpand = true;
}
/// <summary>
/// Initializes a new instance of the <see cref="DataStream" /> class
/// from a substream transferring the ownership of the life-cycle. In the
/// case the stream is another <see cref="DataStream" /> the ownership
/// is inherited.
/// </summary>
/// <param name="stream">Base stream.</param>
/// <param name="offset">Offset from the base stream.</param>
/// <param name="length">Length of this substream.</param>
[SuppressMessage("", "S1125: remove unnecessary boolean", Justification = "Readability")]
public DataStream(Stream stream, long offset, long length)
: this(stream, offset, length, (stream is not DataStream dataStream) || dataStream.hasOwnsership)
{
}
/// <summary>
/// Initializes a new instance of the <see cref="DataStream" /> class.
/// </summary>
/// <param name="stream">Base stream.</param>
/// <param name="offset">Offset from the base stream.</param>
/// <param name="length">Length of this substream.</param>
/// <param name="transferOwnership">
/// Transfer the ownsership of the stream argument to this class so
/// it can dispose it.
/// </param>
public DataStream(Stream stream, long offset, long length, bool transferOwnership)
{
if (stream == null)
throw new ArgumentNullException(nameof(stream));
if (offset < 0 || offset > stream.Length)
throw new ArgumentOutOfRangeException(nameof(offset));
if (length < 0 || offset + length > stream.Length)
throw new ArgumentOutOfRangeException(nameof(length));
this.length = length;
canExpand = false;
hasOwnsership = transferOwnership;
if (stream is DataStream dataStream) {
ParentDataStream = dataStream;
baseStream = dataStream.BaseStream;
Offset = dataStream.Offset + offset;
if (transferOwnership && !dataStream.hasOwnsership) {
throw new ArgumentException(
"Cannot transfer ownership from another datastream that doesn't have ownership",
nameof(transferOwnership));
}
} else {
ParentDataStream = null;
baseStream = stream;
Offset = offset;
}
streamInfo = GetOrCreateStreamInfo();
}
/// <summary>
/// Gets the number of streams in use.
/// </summary>
public static int ActiveStreams => Instances.Values.Count(i => i.NumInstances > 0);
/// <summary>
/// Gets a value indicating whether this <see cref="DataStream"/> is disposed.
/// </summary>
public bool Disposed {
get => disposed;
private set => disposed = value;
}
/// <summary>
/// Gets the offset from the BaseStream.
/// </summary>
public long Offset {
get => offset;
private set => offset = value;
}
/// <summary>
/// Gets or sets the position from the start of this stream.
/// </summary>
public override long Position {
get => position;
set {
if (Disposed)
throw new ObjectDisposedException(nameof(DataStream));
if (value < 0 || value > Length)
throw new ArgumentOutOfRangeException(nameof(value));
position = value;
}
}
/// <summary>
/// Gets the length of this stream.
/// </summary>
public override long Length {
get => length;
}
/// <summary>
/// Gets the parent DataStream only if this stream was initialized from
/// a DataStream.
/// </summary>
public DataStream? ParentDataStream {
get;
private set;
}
/// <summary>
/// Gets the base stream.
/// </summary>
public Stream BaseStream {
get => baseStream;
}
/// <summary>
/// Gets a value indicating whether the position is at end of the stream.
/// </summary>
public bool EndOfStream {
get => Position >= Length;
}
/// <summary>
/// Gets the position from the base stream.
/// </summary>
public long AbsolutePosition {
get => Offset + Position;
}
/// <summary>
/// Gets a value indicating whether the current stream supports reading.
/// </summary>
public override bool CanRead {
get => true;
}
/// <summary>
/// Gets a value indicating whether the current stream supports writing.
/// </summary>
public override bool CanWrite {
get => true;
}
/// <summary>
/// Gets a value indicating whether the current stream supports seeking.
/// </summary>
public override bool CanSeek {
get => true;
}
/// <summary>
/// Gets a value indicating whether the current stream support timeouts.
/// </summary>
public override bool CanTimeout => false;
/// <summary>
/// Gets or sets an invalid value as read time is not supported.
/// </summary>
public override int ReadTimeout {
get => -1;
set => throw new InvalidOperationException("Read timeout is not supported");
}
/// <summary>
/// Gets or sets an invalid value as write time is not supported.
/// </summary>
public override int WriteTimeout {
get => -1;
set => throw new InvalidOperationException("Write timeout is not supported");
}
/// <summary>
/// Gets the internal stream information for testing pourpose only.
/// </summary>
internal StreamInfo InternalInfo {
get => streamInfo;
}
/// <summary>
/// Sets the length of the current stream.
/// </summary>
/// <param name="value">The new length value.</param>
public override void SetLength(long value)
{
if (Disposed)
throw new ObjectDisposedException(nameof(DataStream));
if (value < 0)
throw new ArgumentOutOfRangeException(nameof(value));
if (value > length) {
if (!canExpand) {
throw new InvalidOperationException(
"Cannot change the size of sub-streams.");
}
lock (streamInfo.LockObj) {
if (value > BaseStream.Length) {
// If we can expand, it's not a substream so forget
// about offset (always 0). Increase base stream too.
BaseStream.SetLength(value);
}
}
}
length = value;
if (Position > Length) {
Position = Length;
}
}
/// <summary>
/// Clears all buffers for this stream and causes any buffered data
/// to be written to the underlying device.
/// </summary>
public override void Flush()
{
if (Disposed)
throw new ObjectDisposedException(nameof(DataStream));
BaseStream.Flush();
}
/// <summary>
/// Move the position of the stream.
/// </summary>
/// <param name="offset">Distance to move position.</param>
/// <param name="origin">Mode to move position.</param>
/// <returns>The new position of the stream.</returns>
[SuppressMessage("", "S1006", Justification = "It's an good improvement")]
public override long Seek(long offset, SeekOrigin origin = SeekOrigin.Begin)
{
if (Disposed)
throw new ObjectDisposedException(nameof(DataStream));
switch (origin) {
case SeekOrigin.Current:
Position += offset;
break;
case SeekOrigin.Begin:
Position = offset;
break;
case SeekOrigin.End:
Position = Length + offset;
break;
default:
throw new ArgumentOutOfRangeException(nameof(origin));
}
return Position;
}
/// <summary>
/// Push the current position into a stack and move to a new one.
/// </summary>
/// <param name="shift">Distance to move position.</param>
/// <param name="mode">Mode to move position.</param>
public void PushToPosition(long shift, SeekOrigin mode = SeekOrigin.Begin)
{
if (Disposed)
throw new ObjectDisposedException(nameof(DataStream));
positionStack.Push(Position);
_ = Seek(shift, mode);
}
/// <summary>
/// Push the current position into a stack.
/// </summary>
public void PushCurrentPosition()
{
if (Disposed)
throw new ObjectDisposedException(nameof(DataStream));
positionStack.Push(Position);
}
/// <summary>
/// Pop the last position from the stack and move to it.
/// </summary>
public void PopPosition()
{
if (Disposed)
throw new ObjectDisposedException(nameof(DataStream));
if (positionStack.Count == 0)
throw new InvalidOperationException("Position stack is empty");
Position = positionStack.Pop();
}
/// <summary>
/// Run a method in a specific position.
/// This command will move into the position, run the method and return
/// to the current position.
/// </summary>
/// <param name="action">Action to run.</param>
/// <param name="position">Position to move.</param>
/// <param name="mode">Mode to move position.</param>
public void RunInPosition(Action action, long position, SeekOrigin mode = SeekOrigin.Begin)
{
if (action == null)
throw new ArgumentNullException(nameof(action));
PushToPosition(position, mode);
action();
PopPosition();
}
/// <summary>
/// Reads a byte from the stream and advances the position within the
/// stream by one byte, or returns -1 if at the end of the stream.
/// </summary>
/// <returns>The unsigned byte cast to an Int32, or -1 if at the end of the stream.</returns>
public override int ReadByte()
{
if (disposed)
throw new ObjectDisposedException(nameof(DataStream));
if (position >= length)
return -1;
lock (streamInfo.LockObj) {
baseStream.Position = AbsolutePosition;
position++;
return baseStream.ReadByte();
}
}
/// <summary>
/// Reads a sequence of bytes from the current stream and advances the
/// position within the stream by the number of bytes read.
/// </summary>
/// <returns>
/// The total number of bytes read into the buffer. This can be less than
/// the number of bytes requested if that many bytes are not currently
/// available, or zero (0) if the end of the stream has been reached.
/// </returns>
/// <param name="buffer">Buffer to copy data.</param>
/// <param name="offset">Index to start copying in buffer.</param>
/// <param name="count">Maximum number of bytes to read.</param>
public override int Read(byte[] buffer, int offset, int count)
{
if (Disposed)
throw new ObjectDisposedException(nameof(DataStream));
if (buffer == null)
throw new ArgumentNullException(nameof(buffer));
if (offset + count > buffer.Length)
throw new ArgumentOutOfRangeException(nameof(offset));
if (count == 0)
return 0;
long pos = Position;
long len = Length;
if (pos + count > len) {
count = (int)(len - pos);
}
int read = 0;
lock (streamInfo.LockObj) {
BaseStream.Position = AbsolutePosition;
read = BaseStream.Read(buffer, offset, count);
}
position = pos + read;
return read;
}
/// <summary>
/// Writes a byte.
/// </summary>
/// <param name="value">Byte value.</param>
public override void WriteByte(byte value)
{
if (Disposed)
throw new ObjectDisposedException(nameof(DataStream));
if (Position == Length && !canExpand)
throw new InvalidOperationException("Cannot expand stream");
lock (streamInfo.LockObj) {
BaseStream.Position = AbsolutePosition;
BaseStream.WriteByte(value);
}
if (Position == Length) {
SetLength(Length + 1);
}
Position++;
}
/// <summary>
/// Writes the a portion of the buffer to the stream.
/// </summary>
/// <param name="buffer">Buffer to write.</param>
/// <param name="offset">Index in the buffer.</param>
/// <param name="count">Bytes to write.</param>
public override void Write(byte[] buffer, int offset, int count)
{
if (Disposed)
throw new ObjectDisposedException(nameof(DataStream));
if (buffer == null)
throw new ArgumentNullException(nameof(buffer));
if (offset + count > buffer.Length)
throw new ArgumentOutOfRangeException(nameof(offset));
long pos = Position;
long len = Length;
if (pos + count > len && !canExpand)
throw new InvalidOperationException("Cannot expand stream");
if (count == 0)
return;
lock (streamInfo.LockObj) {
BaseStream.Position = AbsolutePosition;
BaseStream.Write(buffer, offset, count);
}
if (pos + count > len) {
SetLength(pos + count);
}
position = pos + count;
}
/// <summary>
/// Writes the complete stream into a file.
/// </summary>
/// <param name="fileOut">Output file path.</param>
/// <remarks>
/// It preserves the current position and creates any required directory.
/// </remarks>
public void WriteTo(string fileOut)
{
if (Disposed)
throw new ObjectDisposedException(nameof(DataStream));
if (string.IsNullOrEmpty(fileOut))
throw new ArgumentNullException(nameof(fileOut));
WriteSegmentTo(0, Length, fileOut);
}
/// <summary>
/// Writes the complete stream into another stream preserving the current position.
/// </summary>
/// <param name="stream">The stream to write.</param>
/// <remarks>
/// This method is similar to <see cref="Stream.CopyTo(Stream)" />.
/// The difference is that it copies always from the position 0 of the
/// current stream, and it preserves the current position afterwards.
/// It writes into the current position of the destination stream.
/// </remarks>
public void WriteTo(Stream stream)
{
if (Disposed)
throw new ObjectDisposedException(nameof(DataStream));
if (stream == null)
throw new ArgumentNullException(nameof(stream));
WriteSegmentTo(0, Length, stream);
}
/// <summary>
/// Writes a segment of the stream into a file from a defined position to the end.
/// </summary>
/// <param name="start">Starting position to read from the current stream.</param>
/// <param name="fileOut">Output file path.</param>
/// <remarks>
/// It preserves the current position and creates any required directory.
/// </remarks>
public void WriteSegmentTo(long start, string fileOut)
{
if (Disposed)
throw new ObjectDisposedException(nameof(DataStream));
if (string.IsNullOrEmpty(fileOut))
throw new ArgumentNullException(nameof(fileOut));
if (start < 0 || start > Length)
throw new ArgumentOutOfRangeException(nameof(start), start, "Invalid offset");
WriteSegmentTo(start, Length - start, fileOut);
}
/// <summary>
/// Writes a segment of the stream into another stream from a defined position to the end.
/// </summary>
/// <param name="start">Starting position to read from the current stream.</param>
/// <param name="stream">Output stream.</param>
/// <remarks>
/// It preserves the current position and writes to the current position
/// of the destination stream.
/// </remarks>
public void WriteSegmentTo(long start, Stream stream)
{
if (Disposed)
throw new ObjectDisposedException(nameof(DataStream));
if (stream == null)
throw new ArgumentNullException(nameof(stream));
if (start < 0 || start > Length)
throw new ArgumentOutOfRangeException(nameof(start), start, "Invalid offset");
WriteSegmentTo(start, Length - start, stream);
}
/// <summary>
/// Writes a segment of the stream into a file.
/// </summary>
/// <param name="start">Starting position to read from the current stream.</param>
/// <param name="length">Length of the segment to read.</param>
/// <param name="fileOut">Output file path.</param>
/// <remarks>
/// It preserves the current position and creates any required directory.
/// </remarks>
public void WriteSegmentTo(long start, long length, string fileOut)
{
if (Disposed)
throw new ObjectDisposedException(nameof(DataStream));
if (string.IsNullOrEmpty(fileOut))
throw new ArgumentNullException(nameof(fileOut));
if (start < 0 || start > Length)
throw new ArgumentOutOfRangeException(nameof(start), start, "Invalid offset");
if (length < 0 || length > Length)
throw new ArgumentOutOfRangeException(nameof(length), length, "Invalid length");
if (start + length > Length)
throw new ArgumentOutOfRangeException(nameof(start), start + length, "Invalid segment boundary");
// Parent dir can be empty if we just specified the file name.
// In that case, the folder (cwd) already exists.
string? parentDir = Path.GetDirectoryName(fileOut);
if (!string.IsNullOrEmpty(parentDir)) {
_ = Directory.CreateDirectory(parentDir);
}
// We use FileStream so it creates a file even when the length is zero
using var segment = new FileStream(fileOut, FileMode.Create, FileAccess.Write);
WriteSegmentTo(start, length, segment);
}
/// <summary>
/// Writes a segment of the stream into another stream.
/// </summary>
/// <param name="start">Starting position to read from the current stream.</param>
/// <param name="length">Length of the segment to read.</param>
/// <param name="stream">Output stream.</param>
/// <remarks>
/// It preserves the current position and writes to the current position
/// of the destination stream.
/// </remarks>
public void WriteSegmentTo(long start, long length, Stream stream)
{
if (Disposed)
throw new ObjectDisposedException(nameof(DataStream));
if (stream == null)
throw new ArgumentNullException(nameof(stream));
if (start < 0 || start > Length)
throw new ArgumentOutOfRangeException(nameof(start), start, "Invalid offset");
if (length < 0 || length > Length)
throw new ArgumentOutOfRangeException(nameof(length), length, "Invalid length");
if (start + length > Length)
throw new ArgumentOutOfRangeException(nameof(start), start + length, "Invalid segment boundary");
PushToPosition(start);
const int MaxBufferSize = 70 * 1024;
int bufferSize = (length > MaxBufferSize) ? MaxBufferSize : (int)length;
byte[] buffer = ArrayPool<byte>.Shared.Rent(bufferSize);
try {
if (length > buffer.Length) {
long endPos = start + length;
while (Position < endPos) {
int read = BlockRead(this, buffer, endPos);
stream.Write(buffer, 0, read);
}
} else {
int read = Read(buffer, 0, (int)length);
stream.Write(buffer, 0, read);
}
} finally {
ArrayPool<byte>.Shared.Return(buffer);
}
PopPosition();
}
/// <summary>
/// Compare the content of the stream with another one.
/// </summary>
/// <returns>The result of the comparison.</returns>
/// <param name="otherStream">Stream to compare with.</param>
public bool Compare(Stream otherStream)
{
if (otherStream == null) {
throw new ArgumentNullException(nameof(otherStream));
}
// We can't check if the other stream is disposed because Stream
// doesn't provide the property, so we delay it to the Seek method.
if (Disposed) {
throw new ObjectDisposedException(nameof(DataStream));
}
if (this == otherStream) {
return true;
}
long startPosition = Position;
long otherStreamStartPosition = otherStream.Position;
_ = Seek(0, SeekOrigin.Begin);
_ = otherStream.Seek(0, SeekOrigin.Begin);
if (Length != otherStream.Length) {
return false;
}
const int BufferSize = 70 * 1024;
byte[] buffer1 = new byte[Length > BufferSize ? BufferSize : Length];
byte[] buffer2 = new byte[buffer1.Length];
bool result = true;
while (!EndOfStream && result) {
// As we have checked the length before, we assume we read the same
int loopLength = Read(buffer1, 0, buffer1.Length);
_ = otherStream.Read(buffer2, 0, buffer2.Length);
for (int i = 0; i < loopLength && result; i++) {
if (buffer1[i] != buffer2[i]) {
result = false;
}
}
}
_ = Seek(startPosition, SeekOrigin.Begin);
_ = otherStream.Seek(otherStreamStartPosition, SeekOrigin.Begin);
return result;
}
/// <summary>
/// Creates a substream starting in a defined position.
/// </summary>
/// <returns>The substream defined by offset and length parameters.</returns>
/// <param name="start">Defined starting position.</param>
public DataStream Slice(long start)
{
if (start < 0 || start > Length) {
throw new ArgumentOutOfRangeException(nameof(start));
}
return new DataStream(this, start, Length - start);
}
/// <summary>
/// Creates a substream starting in a defined position and with a defined length.
/// </summary>
/// <returns>The substream defined by offset and length parameters.</returns>
/// <param name="start">Defined starting position.</param>
/// <param name="length">Defined length to be written.</param>
public DataStream Slice(long start, long length)
{
if (start < 0 || start > Length) {
throw new ArgumentOutOfRangeException(nameof(start));
}
if (length < 0 || start + length > Length) {
throw new ArgumentOutOfRangeException(nameof(length));
}
return new DataStream(this, start, length);
}
/// <summary>
/// Releases all resource used by the <see cref="DataStream"/>
/// object.
/// </summary>
/// <param name="disposing">If set to
/// <see langword="true" /> free managed resources also.</param>
protected override void Dispose(bool disposing)
{
if (Disposed)
return;
Disposed = true;
// We have only managed resources, so if it's a finalizer call stop.
// If we don't have the ownership no need to decrease counter or dispose
if (!disposing || !hasOwnsership) {
return;
}
streamInfo.DecreaseInstancesAndRun(
info => {
if (info.NumInstances == 0) {
BaseStream.Dispose();
_ = Instances.TryRemove(BaseStream, out _);
}
});
}
private static int BlockRead(Stream stream, byte[] buffer, long endPosition)
{
int read;
if (stream.Position + buffer.Length > endPosition) {
read = (int)(endPosition - stream.Position);
} else {
read = buffer.Length;
}
_ = stream.Read(buffer, 0, read);
return read;
}
private StreamInfo GetOrCreateStreamInfo()
{
StreamInfo info = Instances.GetOrAdd(BaseStream, new StreamInfo());
// If we have ownership, we increase the counter so we take into
// account for disposing. We create always the entry for the lock.
if (hasOwnsership) {
info.IncreaseInstances();
}
return info;
}
/// <summary>
/// Information of the stream for the DataStream class.
/// </summary>
internal sealed class StreamInfo
{
/// <summary>
/// Initializes a new instance of the <see cref=" StreamInfo"/> class.
/// </summary>
public StreamInfo()
{
LockObj = new object();
NumInstances = 0;
}
/// <summary>
/// Gets the number of DataStream instances for the base stream.
/// </summary>
public int NumInstances { get; private set; }
/// <summary>
/// Gets the lock object for the base stream operations.
/// </summary>
public object LockObj { get; }
/// <summary>
/// Increase the number of instances using the base stream.
/// </summary>
public void IncreaseInstances()
{
lock (LockObj) {
NumInstances++;
}
}
/// <summary>
/// Decrease the number of instances using the base stream.
/// </summary>
public void DecreaseInstances()
{
lock (LockObj) {
NumInstances--;
}
}
/// <summary>
/// Decrease the number of instances and run the action.
/// </summary>
/// <param name="action">The action to run.</param>
public void DecreaseInstancesAndRun(Action<StreamInfo> action)
{
lock (LockObj) {
DecreaseInstances();
action(this);
}
}
}
}
}