File: DeflaterManaged.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 (295 lines) | stat: -rw-r--r-- 13,362 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
// ==++==
//
//  Copyright (c) Microsoft Corporation.  All rights reserved.
//
//  zlib.h -- interface of the 'zlib' general purpose compression library
//  version 1.2.1, November 17th, 2003
//
//  Copyright (C) 1995-2003 Jean-loup Gailly and Mark Adler
//
//  This software is provided 'as-is', without any express or implied
//  warranty.  In no event will the authors be held liable for any damages
//  arising from the use of this software.
//
//  Permission is granted to anyone to use this software for any purpose,
//  including commercial applications, and to alter it and redistribute it
//  freely, subject to the following restrictions:
//
//  1. The origin of this software must not be misrepresented; you must not
//     claim that you wrote the original software. If you use this software
//     in a product, an acknowledgment in the product documentation would be
//     appreciated but is not required.
//  2. Altered source versions must be plainly marked as such, and must not be
//     misrepresented as being the original software.
//  3. This notice may not be removed or altered from any source distribution.
//
//
// ==--==
// Compression engine

using System;
using System.Diagnostics;
using System.Diagnostics.Contracts;

namespace System.IO.Compression {

    internal class DeflaterManaged : IDeflater {

        private const int MinBlockSize = 256;
        private const int MaxHeaderFooterGoo = 120;
        private const int CleanCopySize = DeflateStream.DefaultBufferSize - MaxHeaderFooterGoo;
        private const double BadCompressionThreshold = 1.0;

        private FastEncoder deflateEncoder;
        private CopyEncoder copyEncoder;
        
        private DeflateInput input;
        private OutputBuffer output;
        private DeflaterState processingState;
        private DeflateInput inputFromHistory;

        internal DeflaterManaged() {
            deflateEncoder = new FastEncoder();
            copyEncoder = new CopyEncoder();
            input = new DeflateInput();
            output = new OutputBuffer();

            processingState = DeflaterState.NotStarted;
        }

        private bool NeedsInput() {
            // Convenience method to call NeedsInput privately without a cast.
            return ((IDeflater) this).NeedsInput();
        }

        bool IDeflater.NeedsInput() {
            return input.Count == 0 && deflateEncoder.BytesInHistory == 0;
        }

        // Sets the input to compress. The only buffer copy occurs when the input is copied
        // to the FastEncoderWindow
        void IDeflater.SetInput(byte[] inputBuffer, int startIndex, int count) {

            Debug.Assert(input.Count == 0, "We have something left in previous input!");

            input.Buffer = inputBuffer;
            input.Count = count;
            input.StartIndex = startIndex;

            if (count > 0 && count < MinBlockSize) {
                // user is writing small buffers. If buffer size is below MinBlockSize, we
                // need to switch to a small data mode, to avoid block headers and footers 
                // dominating the output.
                switch (processingState) {
                    case DeflaterState.NotStarted :
                    case DeflaterState.CheckingForIncompressible:
                        // clean states, needs a block header first
                        processingState = DeflaterState.StartingSmallData;
                        break;
                    case DeflaterState.CompressThenCheck:
                        // already has correct block header
                        processingState = DeflaterState.HandlingSmallData;
                        break;
                }
            }
        }

        int IDeflater.GetDeflateOutput(byte[] outputBuffer) {

            Debug.Assert(outputBuffer != null, "Can't pass in a null output buffer!");
            Debug.Assert(!NeedsInput(), "GetDeflateOutput should only be called after providing input");

            output.UpdateBuffer(outputBuffer);

            switch(processingState) {

                case DeflaterState.NotStarted: {
                        // first call. Try to compress but if we get bad compression ratio, switch to uncompressed blocks. 
                        Debug.Assert(deflateEncoder.BytesInHistory == 0, "have leftover bytes in window");

                        // save these in case we need to switch to uncompressed format
                        DeflateInput.InputState initialInputState = input.DumpState();
                        OutputBuffer.BufferState initialOutputState = output.DumpState();

                        deflateEncoder.GetBlockHeader(output);
                        deflateEncoder.GetCompressedData(input, output);

                        if (!UseCompressed(deflateEncoder.LastCompressionRatio)) {
                            // we're expanding; restore state and switch to uncompressed
                            input.RestoreState(initialInputState);
                            output.RestoreState(initialOutputState);
                            copyEncoder.GetBlock(input, output, false);
                            FlushInputWindows();
                            processingState = DeflaterState.CheckingForIncompressible;
                        }
                        else {
                            processingState = DeflaterState.CompressThenCheck;
                        }

                        break;
                    }
                case DeflaterState.CompressThenCheck: {
                        // continue assuming data is compressible. If we reach data that indicates otherwise
                        // finish off remaining data in history and decide whether to compress on a 
                        // block-by-block basis
                        deflateEncoder.GetCompressedData(input, output);

                        if (!UseCompressed(deflateEncoder.LastCompressionRatio)) {
                            processingState = DeflaterState.SlowDownForIncompressible1;
                            inputFromHistory = deflateEncoder.UnprocessedInput;
                        }
                        break;
                    }
                case DeflaterState.SlowDownForIncompressible1: {
                        // finish off previous compressed block
                        deflateEncoder.GetBlockFooter(output);

                        processingState = DeflaterState.SlowDownForIncompressible2;
                        goto case DeflaterState.SlowDownForIncompressible2; // yeah I know, but there's no fallthrough
                    }

                case DeflaterState.SlowDownForIncompressible2: {
                        // clear out data from history, but add them as uncompressed blocks
                        if (inputFromHistory.Count > 0) {
                            copyEncoder.GetBlock(inputFromHistory, output, false);
                        }

                        if (inputFromHistory.Count == 0) {
                            // now we're clean
                            deflateEncoder.FlushInput();
                            processingState = DeflaterState.CheckingForIncompressible;
                        }
                        break;
                    }

                case DeflaterState.CheckingForIncompressible: {
                        // decide whether to compress on a block-by-block basis
                        Debug.Assert(deflateEncoder.BytesInHistory == 0, "have leftover bytes in window");

                        // save these in case we need to store as uncompressed
                        DeflateInput.InputState initialInputState = input.DumpState();
                        OutputBuffer.BufferState initialOutputState = output.DumpState();

                        // enforce max so we can ensure state between calls
                        deflateEncoder.GetBlock(input, output, CleanCopySize);

                        if (!UseCompressed(deflateEncoder.LastCompressionRatio)) {
                            // we're expanding; restore state and switch to uncompressed
                            input.RestoreState(initialInputState);
                            output.RestoreState(initialOutputState);
                            copyEncoder.GetBlock(input, output, false);
                            FlushInputWindows();
                        }

                        break;
                    }

                case DeflaterState.StartingSmallData: {
                        // add compressed header and data, but not footer. Subsequent calls will keep 
                        // adding compressed data (no header and no footer). We're doing this to 
                        // avoid overhead of header and footer size relative to compressed payload.
                        deflateEncoder.GetBlockHeader(output);

                        processingState = DeflaterState.HandlingSmallData;
                        goto case DeflaterState.HandlingSmallData; // yeah I know, but there's no fallthrough
                    }

                case DeflaterState.HandlingSmallData: {
                        // continue adding compressed data
                        deflateEncoder.GetCompressedData(input, output);
                        break;
                    }
            }

            return output.BytesWritten;
        }

        bool IDeflater.Finish(byte[] outputBuffer, out int bytesRead) {
            Debug.Assert(outputBuffer != null, "Can't pass in a null output buffer!");
            Debug.Assert(processingState == DeflaterState.NotStarted ||
                            processingState == DeflaterState.CheckingForIncompressible ||
                            processingState == DeflaterState.HandlingSmallData ||
                            processingState == DeflaterState.CompressThenCheck ||
                            processingState == DeflaterState.SlowDownForIncompressible1,
                            "got unexpected processing state = " + processingState);

            Debug.Assert(NeedsInput());

            // no need to add end of block info if we didn't write anything
            if (processingState == DeflaterState.NotStarted) {
                bytesRead = 0;
                return true;
            }

            output.UpdateBuffer(outputBuffer);

            if (processingState == DeflaterState.CompressThenCheck || 
                        processingState == DeflaterState.HandlingSmallData ||
                        processingState == DeflaterState.SlowDownForIncompressible1) {

                // need to finish off block
                deflateEncoder.GetBlockFooter(output);
            }

            // write final block
            WriteFinal();
            bytesRead = output.BytesWritten;
            return true;
        }

        void IDisposable.Dispose() { }
        protected void Dispose(bool disposing) { }

        // Is compression ratio under threshold?
        private bool UseCompressed(double ratio) {
            return (ratio <= BadCompressionThreshold);
        }

        private void FlushInputWindows() {
            deflateEncoder.FlushInput();
        }

        private void WriteFinal() {
            copyEncoder.GetBlock(null, output, true);
        }

        // These states allow us to assume that data is compressible and keep compression ratios at least
        // as good as historical values, but switch to different handling if that approach may increase the
        // data. If we detect we're getting a bad compression ratio, we switch to CheckingForIncompressible
        // state and decide to compress on a block by block basis. 
        //
        // If we're getting small data buffers, we want to avoid overhead of excessive header and footer 
        // info, so we add one header and keep adding blocks as compressed. This means that if the user uses
        // small buffers, they won't get the "don't increase size" improvements.
        //
        // An earlier iteration of this fix handled that data separately by buffering this data until it 
        // reached a reasonable size, but given that Flush is not implemented on DeflateStream, this meant
        // data could be flushed only on Dispose. In the future, it would be reasonable to revisit this, in
        // case this isn't breaking.
        //
        // NotStarted                 -> CheckingForIncompressible, CompressThenCheck, StartingSmallData
        // CompressThenCheck          -> SlowDownForIncompressible1
        // SlowDownForIncompressible1 -> SlowDownForIncompressible2
        // SlowDownForIncompressible2 -> CheckingForIncompressible
        // StartingSmallData          -> HandlingSmallData
        private enum DeflaterState {

            // no bytes to write yet
            NotStarted,
            
            // transient states
            SlowDownForIncompressible1,
            SlowDownForIncompressible2,
            StartingSmallData,

            // stable state: may transition to CheckingForIncompressible (via transient states) if it 
            // appears we're expanding data
            CompressThenCheck,

            // sink states
            CheckingForIncompressible,
            HandlingSmallData
        }

    }  // internal class DeflaterManaged
}  // namespace System.IO.Compression