2 // Copyright (C) 2001 Mike Krueger
4 // This file was translated from java, it was part of the GNU Classpath
5 // Copyright (C) 2001 Free Software Foundation, Inc.
7 // This program is free software; you can redistribute it and/or
8 // modify it under the terms of the GNU General Public License
9 // as published by the Free Software Foundation; either version 2
10 // of the License, or (at your option) any later version.
12 // This program is distributed in the hope that it will be useful,
13 // but WITHOUT ANY WARRANTY; without even the implied warranty of
14 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15 // GNU General Public License for more details.
17 // You should have received a copy of the GNU General Public License
18 // along with this program; if not, write to the Free Software
19 // Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
21 // Linking this library statically or dynamically with other modules is
22 // making a combined work based on this library. Thus, the terms and
23 // conditions of the GNU General Public License cover the whole
26 // As a special exception, the copyright holders of this library give you
27 // permission to link this library with independent modules to produce an
28 // executable, regardless of the license terms of these independent
29 // modules, and to copy and distribute the resulting executable under
30 // terms of your choice, provided that you also meet, for each linked
31 // independent module, the terms and conditions of the license of that
32 // module. An independent module is a module which is not derived from
33 // or based on this library. If you modify this library, you may extend
34 // this exception to your version of the library, but you are not
35 // obligated to do so. If you do not wish to do so, delete this
36 // exception statement from your version.
40 namespace ICSharpCode
.SharpZipLib
.Zip
.Compression
44 /// This is the Deflater class. The deflater class compresses input
45 /// with the deflate algorithm described in RFC 1951. It has several
46 /// compression levels and three different strategies described below.
48 /// This class is <i>not</i> thread safe. This is inherent in the API, due
49 /// to the split of deflate and setInput.
51 /// author of the original java version : Jochen Hoenicke
56 /// The best and slowest compression level. This tries to find very
57 /// long and distant string repetitions.
59 public static int BEST_COMPRESSION
= 9;
62 /// The worst but fastest compression level.
64 public static int BEST_SPEED
= 1;
67 /// The default compression level.
69 public static int DEFAULT_COMPRESSION
= -1;
72 /// This level won't compress at all but output uncompressed blocks.
74 public static int NO_COMPRESSION
= 0;
77 /// The compression method. This is the only method supported so far.
78 /// There is no need to use this constant at all.
80 public static int DEFLATED
= 8;
83 * The Deflater can do the following state transitions:
85 * (1) -> INIT_STATE ----> INIT_FINISHING_STATE ---.
88 * (3)| SETDICT_STATE ---> SETDICT_FINISHING_STATE |(3)
92 * (1) -> BUSY_STATE ----> FINISHING_STATE
96 * \_____________________________________/
101 * (1) If we should produce a header we start in INIT_STATE, otherwise
102 * we start in BUSY_STATE.
103 * (2) A dictionary may be set only when we are in INIT_STATE, then
104 * we change the state as indicated.
105 * (3) Whether a dictionary is set or not, on the first call of deflate
106 * we change to BUSY_STATE.
107 * (4) -- intentionally left blank -- :)
108 * (5) FINISHING_STATE is entered, when flush() is called to indicate that
109 * there is no more INPUT. There are also states indicating, that
110 * the header wasn't written yet.
111 * (6) FINISHED_STATE is entered, when everything has been flushed to the
112 * internal pending output buffer.
113 * (7) At any time (7)
117 private static int IS_SETDICT
= 0x01;
118 private static int IS_FLUSHING
= 0x04;
119 private static int IS_FINISHING
= 0x08;
121 private static int INIT_STATE
= 0x00;
122 private static int SETDICT_STATE
= 0x01;
123 // private static int INIT_FINISHING_STATE = 0x08;
124 // private static int SETDICT_FINISHING_STATE = 0x09;
125 private static int BUSY_STATE
= 0x10;
126 private static int FLUSHING_STATE
= 0x14;
127 private static int FINISHING_STATE
= 0x1c;
128 private static int FINISHED_STATE
= 0x1e;
129 private static int CLOSED_STATE
= 0x7f;
132 /// Compression level.
137 /// should we include a header.
139 private bool noHeader
;
142 // /// Compression strategy.
144 // private int strategy;
147 /// The current state.
152 /// The total bytes of output written.
154 private int totalOut
;
157 /// The pending output.
159 private DeflaterPending pending
;
162 /// The deflater engine.
164 private DeflaterEngine engine
;
167 /// Creates a new deflater with default compression level.
169 public Deflater() : this(DEFAULT_COMPRESSION
, false)
175 /// Creates a new deflater with given compression level.
177 /// <param name="lvl">
178 /// the compression level, a value between NO_COMPRESSION
179 /// and BEST_COMPRESSION, or DEFAULT_COMPRESSION.
181 /// <exception cref="System.ArgumentOutOfRangeException">if lvl is out of range.</exception>
182 public Deflater(int lvl
) : this(lvl
, false)
188 /// Creates a new deflater with given compression level.
190 /// <param name="lvl">
191 /// the compression level, a value between NO_COMPRESSION
192 /// and BEST_COMPRESSION.
194 /// <param name="nowrap">
195 /// true, if we should suppress the deflate header at the
196 /// beginning and the adler checksum at the end of the output. This is
197 /// useful for the GZIP format.
199 /// <exception cref="System.ArgumentOutOfRangeException">if lvl is out of range.</exception>
200 public Deflater(int lvl
, bool nowrap
)
202 if (lvl
== DEFAULT_COMPRESSION
) {
204 } else if (lvl
< NO_COMPRESSION
|| lvl
> BEST_COMPRESSION
) {
205 throw new ArgumentOutOfRangeException("lvl");
208 pending
= new DeflaterPending();
209 engine
= new DeflaterEngine(pending
);
210 this.noHeader
= nowrap
;
211 SetStrategy(DeflateStrategy
.Default
);
218 /// Resets the deflater. The deflater acts afterwards as if it was
219 /// just created with the same compression level and strategy as it
224 state
= (noHeader
? BUSY_STATE
: INIT_STATE
);
231 /// Gets the current adler checksum of the data that was processed so far.
240 /// Gets the number of input bytes processed so far.
244 return engine
.TotalIn
;
249 /// Gets the number of output bytes so far.
251 public int TotalOut
{
258 /// Flushes the current input block. Further calls to deflate() will
259 /// produce enough output to inflate everything in the current input
260 /// block. This is not part of Sun's JDK so I have made it package
261 /// private. It is used by DeflaterOutputStream to implement
266 state
|= IS_FLUSHING
;
270 /// Finishes the deflater with the current input block. It is an error
271 /// to give more input after this method was called. This method must
272 /// be called to force all bytes to be flushed.
276 state
|= IS_FLUSHING
| IS_FINISHING
;
280 /// Returns true if the stream was finished and no more output bytes
283 public bool IsFinished
{
285 return state
== FINISHED_STATE
&& pending
.IsFlushed
;
290 /// Returns true, if the input buffer is empty.
291 /// You should then call setInput().
292 /// NOTE: This method can also return true when the stream
295 public bool IsNeedingInput
{
297 return engine
.NeedsInput();
302 /// Sets the data which should be compressed next. This should be only
303 /// called when needsInput indicates that more input is needed.
304 /// If you call setInput when needsInput() returns false, the
305 /// previous input that is still pending will be thrown away.
306 /// The given byte array should not be changed, before needsInput() returns
308 /// This call is equivalent to <code>setInput(input, 0, input.length)</code>.
310 /// <param name="input">
311 /// the buffer containing the input data.
313 /// <exception cref="System.InvalidOperationException">
314 /// if the buffer was finished() or ended().
316 public void SetInput(byte[] input
)
318 SetInput(input
, 0, input
.Length
);
322 /// Sets the data which should be compressed next. This should be
323 /// only called when needsInput indicates that more input is needed.
324 /// The given byte array should not be changed, before needsInput() returns
327 /// <param name="input">
328 /// the buffer containing the input data.
330 /// <param name="off">
331 /// the start of the data.
333 /// <param name="len">
334 /// the length of the data.
336 /// <exception cref="System.InvalidOperationException">
337 /// if the buffer was finished() or ended() or if previous input is still pending.
339 public void SetInput(byte[] input
, int off
, int len
)
341 if ((state
& IS_FINISHING
) != 0) {
342 throw new InvalidOperationException("finish()/end() already called");
344 engine
.SetInput(input
, off
, len
);
348 /// Sets the compression level. There is no guarantee of the exact
349 /// position of the change, but if you call this when needsInput is
350 /// true the change of compression level will occur somewhere near
351 /// before the end of the so far given input.
353 /// <param name="lvl">
354 /// the new compression level.
356 public void SetLevel(int lvl
)
358 if (lvl
== DEFAULT_COMPRESSION
) {
360 } else if (lvl
< NO_COMPRESSION
|| lvl
> BEST_COMPRESSION
) {
361 throw new ArgumentOutOfRangeException("lvl");
366 engine
.SetLevel(lvl
);
371 /// Sets the compression strategy. Strategy is one of
372 /// DEFAULT_STRATEGY, HUFFMAN_ONLY and FILTERED. For the exact
373 /// position where the strategy is changed, the same as for
374 /// setLevel() applies.
376 /// <param name="stgy">
377 /// the new compression strategy.
379 public void SetStrategy(DeflateStrategy stgy
)
381 engine
.Strategy
= stgy
;
385 /// Deflates the current input block to the given array. It returns
386 /// the number of bytes compressed, or 0 if either
387 /// needsInput() or finished() returns true or length is zero.
389 /// <param name="output">
390 /// the buffer where to write the compressed data.
392 public int Deflate(byte[] output
)
394 return Deflate(output
, 0, output
.Length
);
398 /// Deflates the current input block to the given array. It returns
399 /// the number of bytes compressed, or 0 if either
400 /// needsInput() or finished() returns true or length is zero.
402 /// <param name="output">
403 /// the buffer where to write the compressed data.
405 /// <param name="offset">
406 /// the offset into the output array.
408 /// <param name="length">
409 /// the maximum number of bytes that may be written.
411 /// <exception cref="System.InvalidOperationException">
412 /// if end() was called.
414 /// <exception cref="System.ArgumentOutOfRangeException">
415 /// if offset and/or length don't match the array length.
417 public int Deflate(byte[] output
, int offset
, int length
)
419 int origLength
= length
;
421 if (state
== CLOSED_STATE
) {
422 throw new InvalidOperationException("Deflater closed");
425 if (state
< BUSY_STATE
) {
427 int header
= (DEFLATED
+
428 ((DeflaterConstants
.MAX_WBITS
- 8) << 4)) << 8;
429 int level_flags
= (level
- 1) >> 1;
430 if (level_flags
< 0 || level_flags
> 3) {
433 header
|= level_flags
<< 6;
434 if ((state
& IS_SETDICT
) != 0) {
435 /* Dictionary was set */
436 header
|= DeflaterConstants
.PRESET_DICT
;
438 header
+= 31 - (header
% 31);
441 pending
.WriteShortMSB(header
);
442 if ((state
& IS_SETDICT
) != 0) {
443 int chksum
= engine
.Adler
;
445 pending
.WriteShortMSB(chksum
>> 16);
446 pending
.WriteShortMSB(chksum
& 0xffff);
449 state
= BUSY_STATE
| (state
& (IS_FLUSHING
| IS_FINISHING
));
453 int count
= pending
.Flush(output
, offset
, length
);
458 if (length
== 0 || state
== FINISHED_STATE
) {
462 if (!engine
.Deflate((state
& IS_FLUSHING
) != 0, (state
& IS_FINISHING
) != 0)) {
463 if (state
== BUSY_STATE
) {
464 /* We need more input now */
465 return origLength
- length
;
466 } else if (state
== FLUSHING_STATE
) {
467 if (level
!= NO_COMPRESSION
) {
468 /* We have to supply some lookahead. 8 bit lookahead
469 * are needed by the zlib inflater, and we must fill
470 * the next byte, so that all bits are flushed.
472 int neededbits
= 8 + ((-pending
.BitCount
) & 7);
473 while (neededbits
> 0) {
474 /* write a static tree block consisting solely of
477 pending
.WriteBits(2, 10);
482 } else if (state
== FINISHING_STATE
) {
483 pending
.AlignToByte();
484 /* We have completed the stream */
486 int adler
= engine
.Adler
;
487 pending
.WriteShortMSB(adler
>> 16);
488 pending
.WriteShortMSB(adler
& 0xffff);
490 state
= FINISHED_STATE
;
494 return origLength
- length
;
498 /// Sets the dictionary which should be used in the deflate process.
499 /// This call is equivalent to <code>setDictionary(dict, 0, dict.Length)</code>.
501 /// <param name="dict">
504 /// <exception cref="System.InvalidOperationException">
505 /// if setInput () or deflate () were already called or another dictionary was already set.
507 public void SetDictionary(byte[] dict
)
509 SetDictionary(dict
, 0, dict
.Length
);
513 /// Sets the dictionary which should be used in the deflate process.
514 /// The dictionary should be a byte array containing strings that are
515 /// likely to occur in the data which should be compressed. The
516 /// dictionary is not stored in the compressed output, only a
517 /// checksum. To decompress the output you need to supply the same
518 /// dictionary again.
520 /// <param name="dict">
523 /// <param name="offset">
524 /// an offset into the dictionary.
526 /// <param name="length">
527 /// the length of the dictionary.
529 /// <exception cref="System.InvalidOperationException">
530 /// if setInput () or deflate () were already called or another dictionary was already set.
532 public void SetDictionary(byte[] dict
, int offset
, int length
)
534 if (state
!= INIT_STATE
) {
535 throw new InvalidOperationException();
538 state
= SETDICT_STATE
;
539 engine
.SetDictionary(dict
, offset
, length
);