Deflater.java 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538
  1. /* Deflater.java - Compress a data stream
  2. Copyright (C) 1999, 2000, 2001, 2004, 2005 Free Software Foundation, Inc.
  3. This file is part of GNU Classpath.
  4. GNU Classpath is free software; you can redistribute it and/or modify
  5. it under the terms of the GNU General Public License as published by
  6. the Free Software Foundation; either version 2, or (at your option)
  7. any later version.
  8. GNU Classpath is distributed in the hope that it will be useful, but
  9. WITHOUT ANY WARRANTY; without even the implied warranty of
  10. MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
  11. General Public License for more details.
  12. You should have received a copy of the GNU General Public License
  13. along with GNU Classpath; see the file COPYING. If not, write to the
  14. Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
  15. 02110-1301 USA.
  16. Linking this library statically or dynamically with other modules is
  17. making a combined work based on this library. Thus, the terms and
  18. conditions of the GNU General Public License cover the whole
  19. combination.
  20. As a special exception, the copyright holders of this library give you
  21. permission to link this library with independent modules to produce an
  22. executable, regardless of the license terms of these independent
  23. modules, and to copy and distribute the resulting executable under
  24. terms of your choice, provided that you also meet, for each linked
  25. independent module, the terms and conditions of the license of that
  26. module. An independent module is a module which is not derived from
  27. or based on this library. If you modify this library, you may extend
  28. this exception to your version of the library, but you are not
  29. obligated to do so. If you do not wish to do so, delete this
  30. exception statement from your version. */
  31. package java.util.zip;
  32. /**
  33. * This is the Deflater class. The deflater class compresses input
  34. * with the deflate algorithm described in RFC 1951. It has several
  35. * compression levels and three different strategies described below.
  36. *
  37. * This class is <i>not</i> thread safe. This is inherent in the API, due
  38. * to the split of deflate and setInput.
  39. *
  40. * @author Jochen Hoenicke
  41. * @author Tom Tromey
  42. */
  43. public class Deflater
  44. {
  45. /**
  46. * The best and slowest compression level. This tries to find very
  47. * long and distant string repetitions.
  48. */
  49. public static final int BEST_COMPRESSION = 9;
  50. /**
  51. * The worst but fastest compression level.
  52. */
  53. public static final int BEST_SPEED = 1;
  54. /**
  55. * The default compression level.
  56. */
  57. public static final int DEFAULT_COMPRESSION = -1;
  58. /**
  59. * This level won't compress at all but output uncompressed blocks.
  60. */
  61. public static final int NO_COMPRESSION = 0;
  62. /**
  63. * The default strategy.
  64. */
  65. public static final int DEFAULT_STRATEGY = 0;
  66. /**
  67. * This strategy will only allow longer string repetitions. It is
  68. * useful for random data with a small character set.
  69. */
  70. public static final int FILTERED = 1;
  71. /**
  72. * This strategy will not look for string repetitions at all. It
  73. * only encodes with Huffman trees (which means, that more common
  74. * characters get a smaller encoding.
  75. */
  76. public static final int HUFFMAN_ONLY = 2;
  77. /**
  78. * The compression method. This is the only method supported so far.
  79. * There is no need to use this constant at all.
  80. */
  81. public static final int DEFLATED = 8;
  82. /*
  83. * The Deflater can do the following state transitions:
  84. *
  85. * (1) -> INIT_STATE ----> INIT_FINISHING_STATE ---.
  86. * / | (2) (5) |
  87. * / v (5) |
  88. * (3)| SETDICT_STATE ---> SETDICT_FINISHING_STATE |(3)
  89. * \ | (3) | ,-------'
  90. * | | | (3) /
  91. * v v (5) v v
  92. * (1) -> BUSY_STATE ----> FINISHING_STATE
  93. * | (6)
  94. * v
  95. * FINISHED_STATE
  96. * \_____________________________________/
  97. * | (7)
  98. * v
  99. * CLOSED_STATE
  100. *
  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)
  114. *
  115. */
  116. private static final int IS_SETDICT = 0x01;
  117. private static final int IS_FLUSHING = 0x04;
  118. private static final int IS_FINISHING = 0x08;
  119. private static final int INIT_STATE = 0x00;
  120. private static final int SETDICT_STATE = 0x01;
  121. private static final int INIT_FINISHING_STATE = 0x08;
  122. private static final int SETDICT_FINISHING_STATE = 0x09;
  123. private static final int BUSY_STATE = 0x10;
  124. private static final int FLUSHING_STATE = 0x14;
  125. private static final int FINISHING_STATE = 0x1c;
  126. private static final int FINISHED_STATE = 0x1e;
  127. private static final int CLOSED_STATE = 0x7f;
  128. /** Compression level. */
  129. private int level;
  130. /** should we include a header. */
  131. private boolean noHeader;
  132. /** The current state. */
  133. private int state;
  134. /** The total bytes of output written. */
  135. private long totalOut;
  136. /** The pending output. */
  137. private DeflaterPending pending;
  138. /** The deflater engine. */
  139. private DeflaterEngine engine;
  140. /**
  141. * Creates a new deflater with default compression level.
  142. */
  143. public Deflater()
  144. {
  145. this(DEFAULT_COMPRESSION, false);
  146. }
  147. /**
  148. * Creates a new deflater with given compression level.
  149. * @param lvl the compression level, a value between NO_COMPRESSION
  150. * and BEST_COMPRESSION, or DEFAULT_COMPRESSION.
  151. * @exception IllegalArgumentException if lvl is out of range.
  152. */
  153. public Deflater(int lvl)
  154. {
  155. this(lvl, false);
  156. }
  157. /**
  158. * Creates a new deflater with given compression level.
  159. * @param lvl the compression level, a value between NO_COMPRESSION
  160. * and BEST_COMPRESSION.
  161. * @param nowrap true, iff we should suppress the deflate header at the
  162. * beginning and the adler checksum at the end of the output. This is
  163. * useful for the GZIP format.
  164. * @exception IllegalArgumentException if lvl is out of range.
  165. */
  166. public Deflater(int lvl, boolean nowrap)
  167. {
  168. if (lvl == DEFAULT_COMPRESSION)
  169. lvl = 6;
  170. else if (lvl < NO_COMPRESSION || lvl > BEST_COMPRESSION)
  171. throw new IllegalArgumentException();
  172. pending = new DeflaterPending();
  173. engine = new DeflaterEngine(pending);
  174. this.noHeader = nowrap;
  175. setStrategy(DEFAULT_STRATEGY);
  176. setLevel(lvl);
  177. reset();
  178. }
  179. /**
  180. * Resets the deflater. The deflater acts afterwards as if it was
  181. * just created with the same compression level and strategy as it
  182. * had before.
  183. */
  184. public void reset()
  185. {
  186. state = (noHeader ? BUSY_STATE : INIT_STATE);
  187. totalOut = 0;
  188. pending.reset();
  189. engine.reset();
  190. }
  191. /**
  192. * Frees all objects allocated by the compressor. There's no
  193. * reason to call this, since you can just rely on garbage
  194. * collection. Exists only for compatibility against Sun's JDK,
  195. * where the compressor allocates native memory.
  196. * If you call any method (even reset) afterwards the behaviour is
  197. * <i>undefined</i>.
  198. */
  199. public void end()
  200. {
  201. engine = null;
  202. pending = null;
  203. state = CLOSED_STATE;
  204. }
  205. /**
  206. * Gets the current adler checksum of the data that was processed so
  207. * far.
  208. */
  209. public int getAdler()
  210. {
  211. return engine.getAdler();
  212. }
  213. /**
  214. * Gets the number of input bytes processed so far.
  215. */
  216. public int getTotalIn()
  217. {
  218. return (int) engine.getTotalIn();
  219. }
  220. /**
  221. * Gets the number of input bytes processed so far.
  222. * @since 1.5
  223. */
  224. public long getBytesRead()
  225. {
  226. return engine.getTotalIn();
  227. }
  228. /**
  229. * Gets the number of output bytes so far.
  230. */
  231. public int getTotalOut()
  232. {
  233. return (int) totalOut;
  234. }
  235. /**
  236. * Gets the number of output bytes so far.
  237. * @since 1.5
  238. */
  239. public long getBytesWritten()
  240. {
  241. return totalOut;
  242. }
  243. /**
  244. * Finalizes this object.
  245. */
  246. protected void finalize()
  247. {
  248. /* Exists solely for compatibility. We don't have any native state. */
  249. }
  250. /**
  251. * Flushes the current input block. Further calls to deflate() will
  252. * produce enough output to inflate everything in the current input
  253. * block. This is not part of Sun's JDK so I have made it package
  254. * private. It is used by DeflaterOutputStream to implement
  255. * flush().
  256. */
  257. void flush() {
  258. state |= IS_FLUSHING;
  259. }
  260. /**
  261. * Finishes the deflater with the current input block. It is an error
  262. * to give more input after this method was called. This method must
  263. * be called to force all bytes to be flushed.
  264. */
  265. public void finish() {
  266. state |= IS_FLUSHING | IS_FINISHING;
  267. }
  268. /**
  269. * Returns true iff the stream was finished and no more output bytes
  270. * are available.
  271. */
  272. public boolean finished()
  273. {
  274. return state == FINISHED_STATE && pending.isFlushed();
  275. }
  276. /**
  277. * Returns true, if the input buffer is empty.
  278. * You should then call setInput(). <br>
  279. *
  280. * <em>NOTE</em>: This method can also return true when the stream
  281. * was finished.
  282. */
  283. public boolean needsInput()
  284. {
  285. return engine.needsInput();
  286. }
  287. /**
  288. * Sets the data which should be compressed next. This should be only
  289. * called when needsInput indicates that more input is needed.
  290. * If you call setInput when needsInput() returns false, the
  291. * previous input that is still pending will be thrown away.
  292. * The given byte array should not be changed, before needsInput() returns
  293. * true again.
  294. * This call is equivalent to <code>setInput(input, 0, input.length)</code>.
  295. * @param input the buffer containing the input data.
  296. * @exception IllegalStateException if the buffer was finished() or ended().
  297. */
  298. public void setInput(byte[] input)
  299. {
  300. setInput(input, 0, input.length);
  301. }
  302. /**
  303. * Sets the data which should be compressed next. This should be
  304. * only called when needsInput indicates that more input is needed.
  305. * The given byte array should not be changed, before needsInput() returns
  306. * true again.
  307. * @param input the buffer containing the input data.
  308. * @param off the start of the data.
  309. * @param len the length of the data.
  310. * @exception IllegalStateException if the buffer was finished() or ended()
  311. * or if previous input is still pending.
  312. */
  313. public void setInput(byte[] input, int off, int len)
  314. {
  315. if ((state & IS_FINISHING) != 0)
  316. throw new IllegalStateException("finish()/end() already called");
  317. engine.setInput(input, off, len);
  318. }
  319. /**
  320. * Sets the compression level. There is no guarantee of the exact
  321. * position of the change, but if you call this when needsInput is
  322. * true the change of compression level will occur somewhere near
  323. * before the end of the so far given input.
  324. * @param lvl the new compression level.
  325. */
  326. public void setLevel(int lvl)
  327. {
  328. if (lvl == DEFAULT_COMPRESSION)
  329. lvl = 6;
  330. else if (lvl < NO_COMPRESSION || lvl > BEST_COMPRESSION)
  331. throw new IllegalArgumentException();
  332. if (level != lvl)
  333. {
  334. level = lvl;
  335. engine.setLevel(lvl);
  336. }
  337. }
  338. /**
  339. * Sets the compression strategy. Strategy is one of
  340. * DEFAULT_STRATEGY, HUFFMAN_ONLY and FILTERED. For the exact
  341. * position where the strategy is changed, the same as for
  342. * setLevel() applies.
  343. * @param stgy the new compression strategy.
  344. */
  345. public void setStrategy(int stgy)
  346. {
  347. if (stgy != DEFAULT_STRATEGY && stgy != FILTERED
  348. && stgy != HUFFMAN_ONLY)
  349. throw new IllegalArgumentException();
  350. engine.setStrategy(stgy);
  351. }
  352. /**
  353. * Deflates the current input block to the given array. It returns
  354. * the number of bytes compressed, or 0 if either
  355. * needsInput() or finished() returns true or length is zero.
  356. * @param output the buffer where to write the compressed data.
  357. */
  358. public int deflate(byte[] output)
  359. {
  360. return deflate(output, 0, output.length);
  361. }
  362. /**
  363. * Deflates the current input block to the given array. It returns
  364. * the number of bytes compressed, or 0 if either
  365. * needsInput() or finished() returns true or length is zero.
  366. * @param output the buffer where to write the compressed data.
  367. * @param offset the offset into the output array.
  368. * @param length the maximum number of bytes that may be written.
  369. * @exception IllegalStateException if end() was called.
  370. * @exception IndexOutOfBoundsException if offset and/or length
  371. * don't match the array length.
  372. */
  373. public int deflate(byte[] output, int offset, int length)
  374. {
  375. int origLength = length;
  376. if (state == CLOSED_STATE)
  377. throw new IllegalStateException("Deflater closed");
  378. if (state < BUSY_STATE)
  379. {
  380. /* output header */
  381. int header = (DEFLATED +
  382. ((DeflaterConstants.MAX_WBITS - 8) << 4)) << 8;
  383. int level_flags = (level - 1) >> 1;
  384. if (level_flags < 0 || level_flags > 3)
  385. level_flags = 3;
  386. header |= level_flags << 6;
  387. if ((state & IS_SETDICT) != 0)
  388. /* Dictionary was set */
  389. header |= DeflaterConstants.PRESET_DICT;
  390. header += 31 - (header % 31);
  391. pending.writeShortMSB(header);
  392. if ((state & IS_SETDICT) != 0)
  393. {
  394. int chksum = engine.getAdler();
  395. engine.resetAdler();
  396. pending.writeShortMSB(chksum >> 16);
  397. pending.writeShortMSB(chksum & 0xffff);
  398. }
  399. state = BUSY_STATE | (state & (IS_FLUSHING | IS_FINISHING));
  400. }
  401. for (;;)
  402. {
  403. int count = pending.flush(output, offset, length);
  404. offset += count;
  405. totalOut += count;
  406. length -= count;
  407. if (length == 0 || state == FINISHED_STATE)
  408. break;
  409. if (!engine.deflate((state & IS_FLUSHING) != 0,
  410. (state & IS_FINISHING) != 0))
  411. {
  412. if (state == BUSY_STATE)
  413. /* We need more input now */
  414. return origLength - length;
  415. else if (state == FLUSHING_STATE)
  416. {
  417. if (level != NO_COMPRESSION)
  418. {
  419. /* We have to supply some lookahead. 8 bit lookahead
  420. * are needed by the zlib inflater, and we must fill
  421. * the next byte, so that all bits are flushed.
  422. */
  423. int neededbits = 8 + ((-pending.getBitCount()) & 7);
  424. while (neededbits > 0)
  425. {
  426. /* write a static tree block consisting solely of
  427. * an EOF:
  428. */
  429. pending.writeBits(2, 10);
  430. neededbits -= 10;
  431. }
  432. }
  433. state = BUSY_STATE;
  434. }
  435. else if (state == FINISHING_STATE)
  436. {
  437. pending.alignToByte();
  438. /* We have completed the stream */
  439. if (!noHeader)
  440. {
  441. int adler = engine.getAdler();
  442. pending.writeShortMSB(adler >> 16);
  443. pending.writeShortMSB(adler & 0xffff);
  444. }
  445. state = FINISHED_STATE;
  446. }
  447. }
  448. }
  449. return origLength - length;
  450. }
  451. /**
  452. * Sets the dictionary which should be used in the deflate process.
  453. * This call is equivalent to <code>setDictionary(dict, 0,
  454. * dict.length)</code>.
  455. * @param dict the dictionary.
  456. * @exception IllegalStateException if setInput () or deflate ()
  457. * were already called or another dictionary was already set.
  458. */
  459. public void setDictionary(byte[] dict)
  460. {
  461. setDictionary(dict, 0, dict.length);
  462. }
  463. /**
  464. * Sets the dictionary which should be used in the deflate process.
  465. * The dictionary should be a byte array containing strings that are
  466. * likely to occur in the data which should be compressed. The
  467. * dictionary is not stored in the compressed output, only a
  468. * checksum. To decompress the output you need to supply the same
  469. * dictionary again.
  470. * @param dict the dictionary.
  471. * @param offset an offset into the dictionary.
  472. * @param length the length of the dictionary.
  473. * @exception IllegalStateException if setInput () or deflate () were
  474. * already called or another dictionary was already set.
  475. */
  476. public void setDictionary(byte[] dict, int offset, int length)
  477. {
  478. if (state != INIT_STATE)
  479. throw new IllegalStateException();
  480. state = SETDICT_STATE;
  481. engine.setDictionary(dict, offset, length);
  482. }
  483. }