PageRenderTime 51ms CodeModel.GetById 26ms RepoModel.GetById 1ms app.codeStats 0ms

/Common/SharpZipLib/Zip/Compression/Deflater.cs

http://tsanie-shellextension.googlecode.com/
C# | 557 lines | 204 code | 46 blank | 307 comment | 47 complexity | d7d5e8b9fc4372a2e30469495252881d MD5 | raw file
  1. // Deflater.cs
  2. //
  3. // Copyright (C) 2001 Mike Krueger
  4. // Copyright (C) 2004 John Reilly
  5. //
  6. // This file was translated from java, it was part of the GNU Classpath
  7. // Copyright (C) 2001 Free Software Foundation, Inc.
  8. //
  9. // This program is free software; you can redistribute it and/or
  10. // modify it under the terms of the GNU General Public License
  11. // as published by the Free Software Foundation; either version 2
  12. // of the License, or (at your option) any later version.
  13. //
  14. // This program is distributed in the hope that it will be useful,
  15. // but WITHOUT ANY WARRANTY; without even the implied warranty of
  16. // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  17. // GNU General Public License for more details.
  18. //
  19. // You should have received a copy of the GNU General Public License
  20. // along with this program; if not, write to the Free Software
  21. // Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
  22. //
  23. // Linking this library statically or dynamically with other modules is
  24. // making a combined work based on this library. Thus, the terms and
  25. // conditions of the GNU General Public License cover the whole
  26. // combination.
  27. //
  28. // As a special exception, the copyright holders of this library give you
  29. // permission to link this library with independent modules to produce an
  30. // executable, regardless of the license terms of these independent
  31. // modules, and to copy and distribute the resulting executable under
  32. // terms of your choice, provided that you also meet, for each linked
  33. // independent module, the terms and conditions of the license of that
  34. // module. An independent module is a module which is not derived from
  35. // or based on this library. If you modify this library, you may extend
  36. // this exception to your version of the library, but you are not
  37. // obligated to do so. If you do not wish to do so, delete this
  38. // exception statement from your version.
  39. using System;
  40. namespace SharpZipLib.Zip.Compression
  41. {
  42. /// <summary>
  43. /// This is the Deflater class. The deflater class compresses input
  44. /// with the deflate algorithm described in RFC 1951. It has several
  45. /// compression levels and three different strategies described below.
  46. ///
  47. /// This class is <i>not</i> thread safe. This is inherent in the API, due
  48. /// to the split of deflate and setInput.
  49. ///
  50. /// author of the original java version : Jochen Hoenicke
  51. /// </summary>
  52. public class Deflater
  53. {
  54. #region Deflater Documentation
  55. /*
  56. * The Deflater can do the following state transitions:
  57. *
  58. * (1) -> INIT_STATE ----> INIT_FINISHING_STATE ---.
  59. * / | (2) (5) |
  60. * / v (5) |
  61. * (3)| SETDICT_STATE ---> SETDICT_FINISHING_STATE |(3)
  62. * \ | (3) | ,--------'
  63. * | | | (3) /
  64. * v v (5) v v
  65. * (1) -> BUSY_STATE ----> FINISHING_STATE
  66. * | (6)
  67. * v
  68. * FINISHED_STATE
  69. * \_____________________________________/
  70. * | (7)
  71. * v
  72. * CLOSED_STATE
  73. *
  74. * (1) If we should produce a header we start in INIT_STATE, otherwise
  75. * we start in BUSY_STATE.
  76. * (2) A dictionary may be set only when we are in INIT_STATE, then
  77. * we change the state as indicated.
  78. * (3) Whether a dictionary is set or not, on the first call of deflate
  79. * we change to BUSY_STATE.
  80. * (4) -- intentionally left blank -- :)
  81. * (5) FINISHING_STATE is entered, when flush() is called to indicate that
  82. * there is no more INPUT. There are also states indicating, that
  83. * the header wasn't written yet.
  84. * (6) FINISHED_STATE is entered, when everything has been flushed to the
  85. * internal pending output buffer.
  86. * (7) At any time (7)
  87. *
  88. */
  89. #endregion
  90. #region Public Constants
  91. /// <summary>
  92. /// The best and slowest compression level. This tries to find very
  93. /// long and distant string repetitions.
  94. /// </summary>
  95. public const int BEST_COMPRESSION = 9;
  96. /// <summary>
  97. /// The worst but fastest compression level.
  98. /// </summary>
  99. public const int BEST_SPEED = 1;
  100. /// <summary>
  101. /// The default compression level.
  102. /// </summary>
  103. public const int DEFAULT_COMPRESSION = -1;
  104. /// <summary>
  105. /// This level won't compress at all but output uncompressed blocks.
  106. /// </summary>
  107. public const int NO_COMPRESSION = 0;
  108. /// <summary>
  109. /// The compression method. This is the only method supported so far.
  110. /// There is no need to use this constant at all.
  111. /// </summary>
  112. public const int DEFLATED = 8;
  113. #endregion
  114. #region Local Constants
  115. private const int IS_SETDICT = 0x01;
  116. private const int IS_FLUSHING = 0x04;
  117. private const int IS_FINISHING = 0x08;
  118. private const int INIT_STATE = 0x00;
  119. private const int SETDICT_STATE = 0x01;
  120. // private static int INIT_FINISHING_STATE = 0x08;
  121. // private static int SETDICT_FINISHING_STATE = 0x09;
  122. private const int BUSY_STATE = 0x10;
  123. private const int FLUSHING_STATE = 0x14;
  124. private const int FINISHING_STATE = 0x1c;
  125. private const int FINISHED_STATE = 0x1e;
  126. private const int CLOSED_STATE = 0x7f;
  127. #endregion
  128. #region Constructors
  129. /// <summary>
  130. /// Creates a new deflater with default compression level.
  131. /// </summary>
  132. public Deflater() : this(DEFAULT_COMPRESSION, false)
  133. {
  134. }
  135. /// <summary>
  136. /// Creates a new deflater with given compression level.
  137. /// </summary>
  138. /// <param name="level">
  139. /// the compression level, a value between NO_COMPRESSION
  140. /// and BEST_COMPRESSION, or DEFAULT_COMPRESSION.
  141. /// </param>
  142. /// <exception cref="System.ArgumentOutOfRangeException">if lvl is out of range.</exception>
  143. public Deflater(int level) : this(level, false)
  144. {
  145. }
  146. /// <summary>
  147. /// Creates a new deflater with given compression level.
  148. /// </summary>
  149. /// <param name="level">
  150. /// the compression level, a value between NO_COMPRESSION
  151. /// and BEST_COMPRESSION.
  152. /// </param>
  153. /// <param name="noZlibHeaderOrFooter">
  154. /// true, if we should suppress the Zlib/RFC1950 header at the
  155. /// beginning and the adler checksum at the end of the output. This is
  156. /// useful for the GZIP/PKZIP formats.
  157. /// </param>
  158. /// <exception cref="System.ArgumentOutOfRangeException">if lvl is out of range.</exception>
  159. public Deflater(int level, bool noZlibHeaderOrFooter)
  160. {
  161. if (level == DEFAULT_COMPRESSION) {
  162. level = 6;
  163. } else if (level < NO_COMPRESSION || level > BEST_COMPRESSION) {
  164. throw new ArgumentOutOfRangeException("level");
  165. }
  166. pending = new DeflaterPending();
  167. engine = new DeflaterEngine(pending);
  168. this.noZlibHeaderOrFooter = noZlibHeaderOrFooter;
  169. SetStrategy(DeflateStrategy.Default);
  170. SetLevel(level);
  171. Reset();
  172. }
  173. #endregion
  174. /// <summary>
  175. /// Resets the deflater. The deflater acts afterwards as if it was
  176. /// just created with the same compression level and strategy as it
  177. /// had before.
  178. /// </summary>
  179. public void Reset()
  180. {
  181. state = (noZlibHeaderOrFooter ? BUSY_STATE : INIT_STATE);
  182. totalOut = 0;
  183. pending.Reset();
  184. engine.Reset();
  185. }
  186. /// <summary>
  187. /// Gets the current adler checksum of the data that was processed so far.
  188. /// </summary>
  189. public int Adler {
  190. get {
  191. return engine.Adler;
  192. }
  193. }
  194. /// <summary>
  195. /// Gets the number of input bytes processed so far.
  196. /// </summary>
  197. public long TotalIn {
  198. get {
  199. return engine.TotalIn;
  200. }
  201. }
  202. /// <summary>
  203. /// Gets the number of output bytes so far.
  204. /// </summary>
  205. public long TotalOut {
  206. get {
  207. return totalOut;
  208. }
  209. }
  210. /// <summary>
  211. /// Flushes the current input block. Further calls to deflate() will
  212. /// produce enough output to inflate everything in the current input
  213. /// block. This is not part of Sun's JDK so I have made it package
  214. /// private. It is used by DeflaterOutputStream to implement
  215. /// flush().
  216. /// </summary>
  217. public void Flush()
  218. {
  219. state |= IS_FLUSHING;
  220. }
  221. /// <summary>
  222. /// Finishes the deflater with the current input block. It is an error
  223. /// to give more input after this method was called. This method must
  224. /// be called to force all bytes to be flushed.
  225. /// </summary>
  226. public void Finish()
  227. {
  228. state |= (IS_FLUSHING | IS_FINISHING);
  229. }
  230. /// <summary>
  231. /// Returns true if the stream was finished and no more output bytes
  232. /// are available.
  233. /// </summary>
  234. public bool IsFinished {
  235. get {
  236. return (state == FINISHED_STATE) && pending.IsFlushed;
  237. }
  238. }
  239. /// <summary>
  240. /// Returns true, if the input buffer is empty.
  241. /// You should then call setInput().
  242. /// NOTE: This method can also return true when the stream
  243. /// was finished.
  244. /// </summary>
  245. public bool IsNeedingInput {
  246. get {
  247. return engine.NeedsInput();
  248. }
  249. }
  250. /// <summary>
  251. /// Sets the data which should be compressed next. This should be only
  252. /// called when needsInput indicates that more input is needed.
  253. /// If you call setInput when needsInput() returns false, the
  254. /// previous input that is still pending will be thrown away.
  255. /// The given byte array should not be changed, before needsInput() returns
  256. /// true again.
  257. /// This call is equivalent to <code>setInput(input, 0, input.length)</code>.
  258. /// </summary>
  259. /// <param name="input">
  260. /// the buffer containing the input data.
  261. /// </param>
  262. /// <exception cref="System.InvalidOperationException">
  263. /// if the buffer was finished() or ended().
  264. /// </exception>
  265. public void SetInput(byte[] input)
  266. {
  267. SetInput(input, 0, input.Length);
  268. }
  269. /// <summary>
  270. /// Sets the data which should be compressed next. This should be
  271. /// only called when needsInput indicates that more input is needed.
  272. /// The given byte array should not be changed, before needsInput() returns
  273. /// true again.
  274. /// </summary>
  275. /// <param name="input">
  276. /// the buffer containing the input data.
  277. /// </param>
  278. /// <param name="offset">
  279. /// the start of the data.
  280. /// </param>
  281. /// <param name="count">
  282. /// the number of data bytes of input.
  283. /// </param>
  284. /// <exception cref="System.InvalidOperationException">
  285. /// if the buffer was Finish()ed or if previous input is still pending.
  286. /// </exception>
  287. public void SetInput(byte[] input, int offset, int count)
  288. {
  289. if ((state & IS_FINISHING) != 0) {
  290. throw new InvalidOperationException("Finish() already called");
  291. }
  292. engine.SetInput(input, offset, count);
  293. }
  294. /// <summary>
  295. /// Sets the compression level. There is no guarantee of the exact
  296. /// position of the change, but if you call this when needsInput is
  297. /// true the change of compression level will occur somewhere near
  298. /// before the end of the so far given input.
  299. /// </summary>
  300. /// <param name="level">
  301. /// the new compression level.
  302. /// </param>
  303. public void SetLevel(int level)
  304. {
  305. if (level == DEFAULT_COMPRESSION) {
  306. level = 6;
  307. } else if (level < NO_COMPRESSION || level > BEST_COMPRESSION) {
  308. throw new ArgumentOutOfRangeException("level");
  309. }
  310. if (this.level != level) {
  311. this.level = level;
  312. engine.SetLevel(level);
  313. }
  314. }
  315. /// <summary>
  316. /// Get current compression level
  317. /// </summary>
  318. /// <returns>Returns the current compression level</returns>
  319. public int GetLevel() {
  320. return level;
  321. }
  322. /// <summary>
  323. /// Sets the compression strategy. Strategy is one of
  324. /// DEFAULT_STRATEGY, HUFFMAN_ONLY and FILTERED. For the exact
  325. /// position where the strategy is changed, the same as for
  326. /// SetLevel() applies.
  327. /// </summary>
  328. /// <param name="strategy">
  329. /// The new compression strategy.
  330. /// </param>
  331. public void SetStrategy(DeflateStrategy strategy)
  332. {
  333. engine.Strategy = strategy;
  334. }
  335. /// <summary>
  336. /// Deflates the current input block with to the given array.
  337. /// </summary>
  338. /// <param name="output">
  339. /// The buffer where compressed data is stored
  340. /// </param>
  341. /// <returns>
  342. /// The number of compressed bytes added to the output, or 0 if either
  343. /// IsNeedingInput() or IsFinished returns true or length is zero.
  344. /// </returns>
  345. public int Deflate(byte[] output)
  346. {
  347. return Deflate(output, 0, output.Length);
  348. }
  349. /// <summary>
  350. /// Deflates the current input block to the given array.
  351. /// </summary>
  352. /// <param name="output">
  353. /// Buffer to store the compressed data.
  354. /// </param>
  355. /// <param name="offset">
  356. /// Offset into the output array.
  357. /// </param>
  358. /// <param name="length">
  359. /// The maximum number of bytes that may be stored.
  360. /// </param>
  361. /// <returns>
  362. /// The number of compressed bytes added to the output, or 0 if either
  363. /// needsInput() or finished() returns true or length is zero.
  364. /// </returns>
  365. /// <exception cref="System.InvalidOperationException">
  366. /// If Finish() was previously called.
  367. /// </exception>
  368. /// <exception cref="System.ArgumentOutOfRangeException">
  369. /// If offset or length don't match the array length.
  370. /// </exception>
  371. public int Deflate(byte[] output, int offset, int length)
  372. {
  373. int origLength = length;
  374. if (state == CLOSED_STATE) {
  375. throw new InvalidOperationException("Deflater closed");
  376. }
  377. if (state < BUSY_STATE) {
  378. // output header
  379. int header = (DEFLATED +
  380. ((DeflaterConstants.MAX_WBITS - 8) << 4)) << 8;
  381. int level_flags = (level - 1) >> 1;
  382. if (level_flags < 0 || level_flags > 3) {
  383. level_flags = 3;
  384. }
  385. header |= level_flags << 6;
  386. if ((state & IS_SETDICT) != 0) {
  387. // Dictionary was set
  388. header |= DeflaterConstants.PRESET_DICT;
  389. }
  390. header += 31 - (header % 31);
  391. pending.WriteShortMSB(header);
  392. if ((state & IS_SETDICT) != 0) {
  393. int chksum = engine.Adler;
  394. engine.ResetAdler();
  395. pending.WriteShortMSB(chksum >> 16);
  396. pending.WriteShortMSB(chksum & 0xffff);
  397. }
  398. state = BUSY_STATE | (state & (IS_FLUSHING | IS_FINISHING));
  399. }
  400. for (;;) {
  401. int count = pending.Flush(output, offset, length);
  402. offset += count;
  403. totalOut += count;
  404. length -= count;
  405. if (length == 0 || state == FINISHED_STATE) {
  406. break;
  407. }
  408. if (!engine.Deflate((state & IS_FLUSHING) != 0, (state & IS_FINISHING) != 0)) {
  409. if (state == BUSY_STATE) {
  410. // We need more input now
  411. return origLength - length;
  412. } else if (state == FLUSHING_STATE) {
  413. if (level != NO_COMPRESSION) {
  414. /* We have to supply some lookahead. 8 bit lookahead
  415. * is needed by the zlib inflater, and we must fill
  416. * the next byte, so that all bits are flushed.
  417. */
  418. int neededbits = 8 + ((-pending.BitCount) & 7);
  419. while (neededbits > 0) {
  420. /* write a static tree block consisting solely of
  421. * an EOF:
  422. */
  423. pending.WriteBits(2, 10);
  424. neededbits -= 10;
  425. }
  426. }
  427. state = BUSY_STATE;
  428. } else if (state == FINISHING_STATE) {
  429. pending.AlignToByte();
  430. // Compressed data is complete. Write footer information if required.
  431. if (!noZlibHeaderOrFooter) {
  432. int adler = engine.Adler;
  433. pending.WriteShortMSB(adler >> 16);
  434. pending.WriteShortMSB(adler & 0xffff);
  435. }
  436. state = FINISHED_STATE;
  437. }
  438. }
  439. }
  440. return origLength - length;
  441. }
  442. /// <summary>
  443. /// Sets the dictionary which should be used in the deflate process.
  444. /// This call is equivalent to <code>setDictionary(dict, 0, dict.Length)</code>.
  445. /// </summary>
  446. /// <param name="dictionary">
  447. /// the dictionary.
  448. /// </param>
  449. /// <exception cref="System.InvalidOperationException">
  450. /// if SetInput () or Deflate () were already called or another dictionary was already set.
  451. /// </exception>
  452. public void SetDictionary(byte[] dictionary)
  453. {
  454. SetDictionary(dictionary, 0, dictionary.Length);
  455. }
  456. /// <summary>
  457. /// Sets the dictionary which should be used in the deflate process.
  458. /// The dictionary is a byte array containing strings that are
  459. /// likely to occur in the data which should be compressed. The
  460. /// dictionary is not stored in the compressed output, only a
  461. /// checksum. To decompress the output you need to supply the same
  462. /// dictionary again.
  463. /// </summary>
  464. /// <param name="dictionary">
  465. /// The dictionary data
  466. /// </param>
  467. /// <param name="index">
  468. /// The index where dictionary information commences.
  469. /// </param>
  470. /// <param name="count">
  471. /// The number of bytes in the dictionary.
  472. /// </param>
  473. /// <exception cref="System.InvalidOperationException">
  474. /// If SetInput () or Deflate() were already called or another dictionary was already set.
  475. /// </exception>
  476. public void SetDictionary(byte[] dictionary, int index, int count)
  477. {
  478. if (state != INIT_STATE) {
  479. throw new InvalidOperationException();
  480. }
  481. state = SETDICT_STATE;
  482. engine.SetDictionary(dictionary, index, count);
  483. }
  484. #region Instance Fields
  485. /// <summary>
  486. /// Compression level.
  487. /// </summary>
  488. int level;
  489. /// <summary>
  490. /// If true no Zlib/RFC1950 headers or footers are generated
  491. /// </summary>
  492. bool noZlibHeaderOrFooter;
  493. /// <summary>
  494. /// The current state.
  495. /// </summary>
  496. int state;
  497. /// <summary>
  498. /// The total bytes of output written.
  499. /// </summary>
  500. long totalOut;
  501. /// <summary>
  502. /// The pending output.
  503. /// </summary>
  504. DeflaterPending pending;
  505. /// <summary>
  506. /// The deflater engine.
  507. /// </summary>
  508. DeflaterEngine engine;
  509. #endregion
  510. }
  511. }