File: DeflateStream.cs

package info (click to toggle)
mono 6.8.0.105%2Bdfsg-3.3
  • links: PTS, VCS
  • area: main
  • in suites: bookworm
  • size: 1,284,512 kB
  • sloc: cs: 11,172,132; xml: 2,850,069; ansic: 671,653; cpp: 122,091; perl: 59,366; javascript: 30,841; asm: 22,168; makefile: 20,093; sh: 15,020; python: 4,827; pascal: 925; sql: 859; sed: 16; php: 1
file content (680 lines) | stat: -rw-r--r-- 24,412 bytes parent folder | download | duplicates (7)
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
///----------- ----------- ----------- ----------- ----------- ----------- -----------
/// <copyright file="DeflateStream.cs" company="Microsoft">
///     Copyright (c) Microsoft Corporation.  All rights reserved.
/// </copyright>                               
///
///----------- ----------- ----------- ----------- ----------- ----------- -----------
///

using System.Diagnostics;
using System.Threading;
using System.Security.Permissions;
using System.Diagnostics.Contracts;

namespace System.IO.Compression {
   
    public class DeflateStream : Stream {

        internal const int DefaultBufferSize = 8192;

        internal delegate void AsyncWriteDelegate(byte[] array, int offset, int count, bool isAsync);

        //private const String OrigStackTrace_ExceptionDataKey = "ORIGINAL_STACK_TRACE";

        private Stream _stream;
        private CompressionMode _mode;
        private bool _leaveOpen;
        private Inflater inflater;
        private IDeflater deflater;        
        private byte[] buffer;
        
        private int asyncOperations; 
        private readonly AsyncCallback m_CallBack;
        private readonly AsyncWriteDelegate m_AsyncWriterDelegate;

        private IFileFormatWriter formatWriter;
        private bool wroteHeader;
        private bool wroteBytes;

        private enum WorkerType : byte { Managed, ZLib, Unknown };
        private static volatile WorkerType deflaterType = WorkerType.Unknown;


        public DeflateStream(Stream stream, CompressionMode mode)
            : this(stream, mode, false) {
        }              
        
        public DeflateStream(Stream stream, CompressionMode mode, bool leaveOpen) {
           
            if(stream == null )
                throw new ArgumentNullException("stream");

            if (CompressionMode.Compress != mode && CompressionMode.Decompress != mode)
                throw new ArgumentException(SR.GetString(SR.ArgumentOutOfRange_Enum), "mode");

            _stream = stream;
            _mode = mode;
            _leaveOpen = leaveOpen;

            switch (_mode) {

                case CompressionMode.Decompress:

                    if (!_stream.CanRead) {
                        throw new ArgumentException(SR.GetString(SR.NotReadableStream), "stream");
                    }

                    inflater = new Inflater();

                    m_CallBack = new AsyncCallback(ReadCallback); 
                    break;

                case CompressionMode.Compress:

                    if (!_stream.CanWrite) {
                        throw new ArgumentException(SR.GetString(SR.NotWriteableStream), "stream");
                    }

                    deflater = CreateDeflater(null);
                    
                    m_AsyncWriterDelegate = new AsyncWriteDelegate(this.InternalWrite);
                    m_CallBack = new AsyncCallback(WriteCallback); 

                    break;                        

            }  // switch (_mode)

            buffer = new byte[DefaultBufferSize];
        }

        // Implies mode = Compress
        public DeflateStream(Stream stream, CompressionLevel compressionLevel)

            : this(stream, compressionLevel, false) {
        }

        // Implies mode = Compress
        public DeflateStream(Stream stream, CompressionLevel compressionLevel, bool leaveOpen) {

            if (stream == null)
                throw new ArgumentNullException("stream");

            if (!stream.CanWrite)
                throw new ArgumentException(SR.GetString(SR.NotWriteableStream), "stream");

            // Checking of compressionLevel is passed down to the IDeflater implementation as it
            // is a pluggable component that completely encapsulates the meaning of compressionLevel.
            
            Contract.EndContractBlock();

            _stream = stream;
            _mode = CompressionMode.Compress;
            _leaveOpen = leaveOpen;

            deflater = CreateDeflater(compressionLevel);

            m_AsyncWriterDelegate = new AsyncWriteDelegate(this.InternalWrite);
            m_CallBack = new AsyncCallback(WriteCallback);
           
            buffer = new byte[DefaultBufferSize];
        }        

        private static IDeflater CreateDeflater(CompressionLevel? compressionLevel) {

            switch (GetDeflaterType()) {

                case WorkerType.Managed:
                    return new DeflaterManaged();

                case WorkerType.ZLib:
                    if (compressionLevel.HasValue)
                        return new DeflaterZLib(compressionLevel.Value);
                    else
                        return new DeflaterZLib();

                default:
                    // We do not expect this to ever be thrown.
                    // But this is better practice than returning null.
                    throw new SystemException("Program entered an unexpected state.");
            }
        }

        #if !SILVERLIGHT
        [System.Security.SecuritySafeCritical]
        #endif
        private static WorkerType GetDeflaterType() {

            // Let's not worry about race conditions:
            // Yes, we risk initialising the singleton multiple times.
            // However, initialising the singleton multiple times has no bad consequences, and is fairly cheap.

            if (WorkerType.Unknown != deflaterType)
                return deflaterType;
                        
            #if !SILVERLIGHT  // Do this on Desktop.  CLRConfig doesn't exist on CoreSys nor Silverlight.

            // CLRConfig is internal in mscorlib and is a friend
            if (System.CLRConfig.CheckLegacyManagedDeflateStream())
                return (deflaterType = WorkerType.Managed);

            #endif

            #if !SILVERLIGHT || FEATURE_NETCORE  // Only skip this for Silverlight, which doesn't ship ZLib.

            if (!CompatibilitySwitches.IsNetFx45LegacyManagedDeflateStream)
                return (deflaterType = WorkerType.ZLib);

            #endif

            return (deflaterType = WorkerType.Managed);
        }

        internal void SetFileFormatReader(IFileFormatReader reader) {
            if (reader != null) {
                inflater.SetFileFormatReader(reader);
            }
        }

        internal void SetFileFormatWriter(IFileFormatWriter writer) {
            if (writer != null) {
                formatWriter = writer;
            }
        }

        public Stream BaseStream {
            get {
                return _stream;
            }
        }

        public override bool CanRead { 
            get {
                if( _stream == null) {
                    return false;      
                }

                return (_mode == CompressionMode.Decompress && _stream.CanRead);
            }
        }

        public override bool CanWrite { 
            get {
                if( _stream == null) {
                    return false;                
                }
                
                return (_mode == CompressionMode.Compress && _stream.CanWrite);
            }
        }

        public override bool CanSeek { 
            get {                
                return false;
            }
        }

        public override long Length { 
            get {
                throw new NotSupportedException(SR.GetString(SR.NotSupported));            
            }
        }

        public override long Position { 
            get {
                throw new NotSupportedException(SR.GetString(SR.NotSupported));            
            } 
            
            set {
                throw new NotSupportedException(SR.GetString(SR.NotSupported));            
            }
        }
        
        public override void Flush() {            
            EnsureNotDisposed();
            return;
        }

        public override long Seek(long offset, SeekOrigin origin) {
            throw new NotSupportedException(SR.GetString(SR.NotSupported));            
        }

        public override void SetLength(long value) {
            throw new NotSupportedException(SR.GetString(SR.NotSupported));            
        }

        public override int Read(byte[] array, int offset, int count) {

            EnsureDecompressionMode();
            ValidateParameters(array, offset, count);
            EnsureNotDisposed();
            
            int bytesRead;
            int currentOffset = offset;
            int remainingCount = count;

            while(true) {
                bytesRead = inflater.Inflate(array, currentOffset, remainingCount); 
                currentOffset += bytesRead;
                remainingCount -= bytesRead;

                if( remainingCount == 0) {
                    break;
                }
               
                if (inflater.Finished() ) { 
                    // if we finished decompressing, we can't have anything left in the outputwindow.
                    Debug.Assert(inflater.AvailableOutput == 0, "We should have copied all stuff out!");
                    break;                    
                }                

                Debug.Assert(inflater.NeedsInput(), "We can only run into this case if we are short of input");

                int bytes = _stream.Read(buffer, 0, buffer.Length);
                if( bytes == 0) {
                    break;      //Do we want to throw an exception here?
                }

                inflater.SetInput(buffer, 0 , bytes);
            }

            return count - remainingCount;
        }        

        private void ValidateParameters(byte[] array, int offset, int count) {

            if (array==null)
                throw new ArgumentNullException("array");           
            
            if (offset < 0)
                throw new ArgumentOutOfRangeException("offset");          

            if (count < 0)
                throw new ArgumentOutOfRangeException("count");           

            if (array.Length - offset < count)
                throw new ArgumentException(SR.GetString(SR.InvalidArgumentOffsetCount));           
        }

        private void EnsureNotDisposed() {

            if (_stream == null)
                throw new ObjectDisposedException(null, SR.GetString(SR.ObjectDisposed_StreamClosed));           
        }

        private void EnsureDecompressionMode() {

            if( _mode != CompressionMode.Decompress)
                throw new InvalidOperationException(SR.GetString(SR.CannotReadFromDeflateStream));           
        }

        private void EnsureCompressionMode() {

            if( _mode != CompressionMode.Compress)
                throw new InvalidOperationException(SR.GetString(SR.CannotWriteToDeflateStream));           
        }

#if !FEATURE_NETCORE
        [HostProtection(ExternalThreading=true)]
#endif
        public override IAsyncResult BeginRead(byte[] array, int offset, int count, AsyncCallback asyncCallback, object asyncState) {
            
            EnsureDecompressionMode();

            // We use this checking order for compat to earlier versions:
            if (asyncOperations != 0)
                throw new InvalidOperationException(SR.GetString(SR.InvalidBeginCall));

            ValidateParameters(array, offset, count);
            EnsureNotDisposed();                       

            Interlocked.Increment(ref asyncOperations);

            try {                

                DeflateStreamAsyncResult userResult = new DeflateStreamAsyncResult(
                                                            this, asyncState, asyncCallback, array, offset, count);
                userResult.isWrite = false;

                // Try to read decompressed data in output buffer
                int bytesRead = inflater.Inflate(array, offset, count);
                if( bytesRead != 0) {
                    // If decompression output buffer is not empty, return immediately.
                    // 'true' means we complete synchronously.
                    userResult.InvokeCallback(true, (object) bytesRead);                      
                    return userResult;
                }

                if (inflater.Finished() ) {  
                    // end of compression stream
                    userResult.InvokeCallback(true, (object) 0);  
                    return userResult;
                }
                    
                // If there is no data on the output buffer and we are not at 
                // the end of the stream, we need to get more data from the base stream
                _stream.BeginRead(buffer, 0, buffer.Length, m_CallBack, userResult);   
                userResult.m_CompletedSynchronously &= userResult.IsCompleted;            
                
                return userResult;

            } catch {
                Interlocked.Decrement( ref asyncOperations);
                throw;
            }
        }

        // callback function for asynchrous reading on base stream
        private void ReadCallback(IAsyncResult baseStreamResult) {

            DeflateStreamAsyncResult outerResult = (DeflateStreamAsyncResult) baseStreamResult.AsyncState;
            outerResult.m_CompletedSynchronously &= baseStreamResult.CompletedSynchronously;
            int bytesRead = 0;

            try {

                EnsureNotDisposed();

                bytesRead = _stream.EndRead(baseStreamResult);

                if (bytesRead <= 0 ) {
                    // This indicates the base stream has received EOF
                    outerResult.InvokeCallback((object) 0);  
                    return;
                }
    
                // Feed the data from base stream into decompression engine
                inflater.SetInput(buffer, 0 , bytesRead);
                bytesRead = inflater.Inflate(outerResult.buffer, outerResult.offset, outerResult.count); 

                if (bytesRead == 0 && !inflater.Finished()) {  

                    // We could have read in head information and didn't get any data.
                    // Read from the base stream again.   
                    // Need to solve recusion.
                    _stream.BeginRead(buffer, 0, buffer.Length, m_CallBack, outerResult);                   

                } else {
                    outerResult.InvokeCallback((object) bytesRead);              
                }
            } catch (Exception exc) {
                // Defer throwing this until EndRead where we will likely have user code on the stack.
                outerResult.InvokeCallback(exc); 
                return;
            }
        }

        public override int EndRead(IAsyncResult asyncResult) {

            EnsureDecompressionMode();
            CheckEndXxxxLegalStateAndParams(asyncResult);

            // We checked that this will work in CheckEndXxxxLegalStateAndParams:
            DeflateStreamAsyncResult deflateStrmAsyncResult = (DeflateStreamAsyncResult) asyncResult;

            AwaitAsyncResultCompletion(deflateStrmAsyncResult);

            Exception previousException = deflateStrmAsyncResult.Result as Exception;
            if (previousException != null) {
                // Rethrowing will delete the stack trace. Let's help future debuggers:                
                //previousException.Data.Add(OrigStackTrace_ExceptionDataKey, previousException.StackTrace);
                throw previousException;
            }

            return (int) deflateStrmAsyncResult.Result;
        }

        public override void Write(byte[] array, int offset, int count) {
            EnsureCompressionMode();
            ValidateParameters(array, offset, count);
            EnsureNotDisposed();
            InternalWrite(array, offset, count, false);
        }

        // isAsync always seems to be false. why do we have it?
        internal void InternalWrite(byte[] array, int offset, int count, bool isAsync) {

            DoMaintenance(array, offset, count);            

            // Write compressed the bytes we already passed to the deflater:

            WriteDeflaterOutput(isAsync);

            // Pass new bytes through deflater and write them too:

            deflater.SetInput(array, offset, count);
            WriteDeflaterOutput(isAsync);
        }


        private void WriteDeflaterOutput(bool isAsync) {

            while (!deflater.NeedsInput()) {

                int compressedBytes = deflater.GetDeflateOutput(buffer);
                if (compressedBytes > 0)
                    DoWrite(buffer, 0, compressedBytes, isAsync);
            }
        }

        private void DoWrite(byte[] array, int offset, int count, bool isAsync) {
            Debug.Assert(array != null);
            Debug.Assert(count != 0);

            if (isAsync) {
                IAsyncResult result = _stream.BeginWrite(array, offset, count, null, null);
                _stream.EndWrite(result);

            } else {
                _stream.Write(array, offset, count);
            }
        }

        // Perform deflate-mode maintenance required due to custom header and footer writers
        // (e.g. set by GZipStream):
        private void DoMaintenance(byte[] array, int offset, int count) {

            // If no bytes written, do nothing:
            if (count <= 0)
                return;

            // Note that stream contains more than zero data bytes:
            wroteBytes = true;

            // If no header/footer formatter present, nothing else to do:
            if (formatWriter == null)
                return;            

            // If formatter has not yet written a header, do it now:
            if (!wroteHeader) {
                byte[] b = formatWriter.GetHeader();
                _stream.Write(b, 0, b.Length);
                wroteHeader = true;
            }
            
            // Inform formatter of the data bytes written:
            formatWriter.UpdateWithBytesRead(array, offset, count);            
        }

        // This is called by Dispose:
        private void PurgeBuffers(bool disposing) {

            if (!disposing)
                return;

            if (_stream == null)
                return;

            Flush();

            if (_mode != CompressionMode.Compress)
                return;

            // Some deflaters (e.g. ZLib write more than zero bytes for zero bytes inpuits.
            // This round-trips and we should be ok with this, but our legacy managed deflater
            // always wrote zero output for zero input and upstack code (e.g. GZipStream)
            // took dependencies on it. Thus, make sure to only "flush" when we actually had
            // some input:
            if (wroteBytes) {

                // Compress any bytes left:                        
                WriteDeflaterOutput(false);

                // Pull out any bytes left inside deflater:
                bool finished;
                do {
                    int compressedBytes;
                    finished = deflater.Finish(buffer, out compressedBytes);

                    if (compressedBytes > 0)
                        DoWrite(buffer, 0, compressedBytes, false);

                } while (!finished);

            }

            // Write format footer:
            if (formatWriter != null && wroteHeader) {
                byte[] b = formatWriter.GetFooter();
                _stream.Write(b, 0, b.Length);
            }            
        }

        protected override void Dispose(bool disposing) {

            try {

                PurgeBuffers(disposing);

            } finally {

                // Close the underlying stream even if PurgeBuffers threw.
                // Stream.Close() may throw here (may or may not be due to the same error).
                // In this case, we still need to clean up internal resources, hence the inner finally blocks.
                try {                    

                    if(disposing && !_leaveOpen && _stream != null) 
                        _stream.Close();                    

                } finally {

                    _stream = null;

                    try {

                        if (deflater != null)
                            deflater.Dispose();

                    } finally {

                        deflater = null;
                        base.Dispose(disposing);
                    }
                }  // finally
            }  // finally
        }  // Dispose


#if !FEATURE_NETCORE
        [HostProtection(ExternalThreading=true)]
#endif
        public override IAsyncResult BeginWrite(byte[] array, int offset, int count, AsyncCallback asyncCallback, object asyncState) {

            EnsureCompressionMode();            

            // We use this checking order for compat to earlier versions:
            if (asyncOperations != 0 )
                throw new InvalidOperationException(SR.GetString(SR.InvalidBeginCall));

            ValidateParameters(array, offset, count);
            EnsureNotDisposed();
           
            Interlocked.Increment(ref asyncOperations);

            try {                

                DeflateStreamAsyncResult userResult = new DeflateStreamAsyncResult(
                                                            this, asyncState, asyncCallback, array, offset, count);
                userResult.isWrite = true;

                m_AsyncWriterDelegate.BeginInvoke(array, offset, count, true, m_CallBack, userResult);
                userResult.m_CompletedSynchronously &= userResult.IsCompleted;            
                                
                return userResult;

            } catch {
                Interlocked.Decrement(ref asyncOperations);
                throw;
            }
        }

        // Callback function for asynchrous reading on base stream
        private void WriteCallback(IAsyncResult asyncResult) {

            DeflateStreamAsyncResult outerResult = (DeflateStreamAsyncResult) asyncResult.AsyncState;
            outerResult.m_CompletedSynchronously &= asyncResult.CompletedSynchronously;            

            try {

                m_AsyncWriterDelegate.EndInvoke(asyncResult);

            } catch (Exception exc) {
                // Defer throwing this until EndWrite where there is user code on the stack:
                outerResult.InvokeCallback(exc); 
                return;
            }
            outerResult.InvokeCallback(null);              
        }

        public override void EndWrite(IAsyncResult asyncResult) {

            EnsureCompressionMode();
            CheckEndXxxxLegalStateAndParams(asyncResult);

            // We checked that this will work in CheckEndXxxxLegalStateAndParams:
            DeflateStreamAsyncResult deflateStrmAsyncResult = (DeflateStreamAsyncResult) asyncResult;

            AwaitAsyncResultCompletion(deflateStrmAsyncResult);

            Exception previousException = deflateStrmAsyncResult.Result as Exception;
            if (previousException != null) {
                // Rethrowing will delete the stack trace. Let's help future debuggers:                
                //previousException.Data.Add(OrigStackTrace_ExceptionDataKey, previousException.StackTrace);
                throw previousException;
            }
        }

        private void CheckEndXxxxLegalStateAndParams(IAsyncResult asyncResult) {

            if (asyncOperations != 1)
                throw new InvalidOperationException(SR.GetString(SR.InvalidEndCall));

            if (asyncResult == null)
                throw new ArgumentNullException("asyncResult");

            EnsureNotDisposed();
            
            DeflateStreamAsyncResult myResult = asyncResult as DeflateStreamAsyncResult;

            // This should really be an ArgumentException, but we keep this for compat to previous versions:
            if (myResult == null)
                throw new ArgumentNullException("asyncResult");
        }

        private void AwaitAsyncResultCompletion(DeflateStreamAsyncResult asyncResult) {

            try {

                if (!asyncResult.IsCompleted)
                    asyncResult.AsyncWaitHandle.WaitOne();

            } finally {

                Interlocked.Decrement(ref asyncOperations);
                asyncResult.Close();  // this will just close the wait handle
            }
        }

    }  // public class DeflateStream

}  // namespace System.IO.Compression