DeflaterEngine.java 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699
  1. /* DeflaterEngine.java --
  2. Copyright (C) 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. class DeflaterEngine implements DeflaterConstants
  33. {
  34. private static final int TOO_FAR = 4096;
  35. private int ins_h;
  36. /**
  37. * Hashtable, hashing three characters to an index for window, so
  38. * that window[index]..window[index+2] have this hash code.
  39. * Note that the array should really be unsigned short, so you need
  40. * to and the values with 0xffff.
  41. */
  42. private short[] head;
  43. /**
  44. * prev[index & WMASK] points to the previous index that has the
  45. * same hash code as the string starting at index. This way
  46. * entries with the same hash code are in a linked list.
  47. * Note that the array should really be unsigned short, so you need
  48. * to and the values with 0xffff.
  49. */
  50. private short[] prev;
  51. private int matchStart, matchLen;
  52. private boolean prevAvailable;
  53. private int blockStart;
  54. /**
  55. * strstart points to the current character in window.
  56. */
  57. private int strstart;
  58. /**
  59. * lookahead is the number of characters starting at strstart in
  60. * window that are valid.
  61. * So window[strstart] until window[strstart+lookahead-1] are valid
  62. * characters.
  63. */
  64. private int lookahead;
  65. /**
  66. * This array contains the part of the uncompressed stream that
  67. * is of relevance. The current character is indexed by strstart.
  68. */
  69. private byte[] window;
  70. private int strategy, max_chain, max_lazy, niceLength, goodLength;
  71. /** The current compression function. */
  72. private int comprFunc;
  73. /** The input data for compression. */
  74. private byte[] inputBuf;
  75. /** The total bytes of input read. */
  76. private long totalIn;
  77. /** The offset into inputBuf, where input data starts. */
  78. private int inputOff;
  79. /** The end offset of the input data. */
  80. private int inputEnd;
  81. private DeflaterPending pending;
  82. private DeflaterHuffman huffman;
  83. /** The adler checksum */
  84. private Adler32 adler;
  85. /* DEFLATE ALGORITHM:
  86. *
  87. * The uncompressed stream is inserted into the window array. When
  88. * the window array is full the first half is thrown away and the
  89. * second half is copied to the beginning.
  90. *
  91. * The head array is a hash table. Three characters build a hash value
  92. * and they the value points to the corresponding index in window of
  93. * the last string with this hash. The prev array implements a
  94. * linked list of matches with the same hash: prev[index & WMASK] points
  95. * to the previous index with the same hash.
  96. *
  97. *
  98. */
  99. DeflaterEngine(DeflaterPending pending) {
  100. this.pending = pending;
  101. huffman = new DeflaterHuffman(pending);
  102. adler = new Adler32();
  103. window = new byte[2*WSIZE];
  104. head = new short[HASH_SIZE];
  105. prev = new short[WSIZE];
  106. /* We start at index 1, to avoid a implementation deficiency, that
  107. * we cannot build a repeat pattern at index 0.
  108. */
  109. blockStart = strstart = 1;
  110. }
  111. public void reset()
  112. {
  113. huffman.reset();
  114. adler.reset();
  115. blockStart = strstart = 1;
  116. lookahead = 0;
  117. totalIn = 0;
  118. prevAvailable = false;
  119. matchLen = MIN_MATCH - 1;
  120. for (int i = 0; i < HASH_SIZE; i++)
  121. head[i] = 0;
  122. for (int i = 0; i < WSIZE; i++)
  123. prev[i] = 0;
  124. }
  125. public final void resetAdler()
  126. {
  127. adler.reset();
  128. }
  129. public final int getAdler()
  130. {
  131. int chksum = (int) adler.getValue();
  132. return chksum;
  133. }
  134. public final long getTotalIn()
  135. {
  136. return totalIn;
  137. }
  138. public final void setStrategy(int strat)
  139. {
  140. strategy = strat;
  141. }
  142. public void setLevel(int lvl)
  143. {
  144. goodLength = DeflaterConstants.GOOD_LENGTH[lvl];
  145. max_lazy = DeflaterConstants.MAX_LAZY[lvl];
  146. niceLength = DeflaterConstants.NICE_LENGTH[lvl];
  147. max_chain = DeflaterConstants.MAX_CHAIN[lvl];
  148. if (DeflaterConstants.COMPR_FUNC[lvl] != comprFunc)
  149. {
  150. if (DeflaterConstants.DEBUGGING)
  151. System.err.println("Change from "+comprFunc +" to "
  152. + DeflaterConstants.COMPR_FUNC[lvl]);
  153. switch (comprFunc)
  154. {
  155. case DEFLATE_STORED:
  156. if (strstart > blockStart)
  157. {
  158. huffman.flushStoredBlock(window, blockStart,
  159. strstart - blockStart, false);
  160. blockStart = strstart;
  161. }
  162. updateHash();
  163. break;
  164. case DEFLATE_FAST:
  165. if (strstart > blockStart)
  166. {
  167. huffman.flushBlock(window, blockStart, strstart - blockStart,
  168. false);
  169. blockStart = strstart;
  170. }
  171. break;
  172. case DEFLATE_SLOW:
  173. if (prevAvailable)
  174. huffman.tallyLit(window[strstart-1] & 0xff);
  175. if (strstart > blockStart)
  176. {
  177. huffman.flushBlock(window, blockStart, strstart - blockStart,
  178. false);
  179. blockStart = strstart;
  180. }
  181. prevAvailable = false;
  182. matchLen = MIN_MATCH - 1;
  183. break;
  184. }
  185. comprFunc = COMPR_FUNC[lvl];
  186. }
  187. }
  188. private void updateHash() {
  189. if (DEBUGGING)
  190. System.err.println("updateHash: "+strstart);
  191. ins_h = (window[strstart] << HASH_SHIFT) ^ window[strstart + 1];
  192. }
  193. /**
  194. * Inserts the current string in the head hash and returns the previous
  195. * value for this hash.
  196. */
  197. private int insertString() {
  198. short match;
  199. int hash = ((ins_h << HASH_SHIFT) ^ window[strstart + (MIN_MATCH -1)])
  200. & HASH_MASK;
  201. if (DEBUGGING)
  202. {
  203. if (hash != (((window[strstart] << (2*HASH_SHIFT))
  204. ^ (window[strstart + 1] << HASH_SHIFT)
  205. ^ (window[strstart + 2])) & HASH_MASK))
  206. throw new InternalError("hash inconsistent: "+hash+"/"
  207. +window[strstart]+","
  208. +window[strstart+1]+","
  209. +window[strstart+2]+","+HASH_SHIFT);
  210. }
  211. prev[strstart & WMASK] = match = head[hash];
  212. head[hash] = (short) strstart;
  213. ins_h = hash;
  214. return match & 0xffff;
  215. }
  216. private void slideWindow()
  217. {
  218. System.arraycopy(window, WSIZE, window, 0, WSIZE);
  219. matchStart -= WSIZE;
  220. strstart -= WSIZE;
  221. blockStart -= WSIZE;
  222. /* Slide the hash table (could be avoided with 32 bit values
  223. * at the expense of memory usage).
  224. */
  225. for (int i = 0; i < HASH_SIZE; i++)
  226. {
  227. int m = head[i] & 0xffff;
  228. head[i] = m >= WSIZE ? (short) (m - WSIZE) : 0;
  229. }
  230. /* Slide the prev table.
  231. */
  232. for (int i = 0; i < WSIZE; i++)
  233. {
  234. int m = prev[i] & 0xffff;
  235. prev[i] = m >= WSIZE ? (short) (m - WSIZE) : 0;
  236. }
  237. }
  238. /**
  239. * Fill the window when the lookahead becomes insufficient.
  240. * Updates strstart and lookahead.
  241. *
  242. * OUT assertions: strstart + lookahead <= 2*WSIZE
  243. * lookahead >= MIN_LOOKAHEAD or inputOff == inputEnd
  244. */
  245. private void fillWindow()
  246. {
  247. /* If the window is almost full and there is insufficient lookahead,
  248. * move the upper half to the lower one to make room in the upper half.
  249. */
  250. if (strstart >= WSIZE + MAX_DIST)
  251. slideWindow();
  252. /* If there is not enough lookahead, but still some input left,
  253. * read in the input
  254. */
  255. while (lookahead < DeflaterConstants.MIN_LOOKAHEAD && inputOff < inputEnd)
  256. {
  257. int more = 2*WSIZE - lookahead - strstart;
  258. if (more > inputEnd - inputOff)
  259. more = inputEnd - inputOff;
  260. System.arraycopy(inputBuf, inputOff,
  261. window, strstart + lookahead, more);
  262. adler.update(inputBuf, inputOff, more);
  263. inputOff += more;
  264. totalIn += more;
  265. lookahead += more;
  266. }
  267. if (lookahead >= MIN_MATCH)
  268. updateHash();
  269. }
  270. /**
  271. * Find the best (longest) string in the window matching the
  272. * string starting at strstart.
  273. *
  274. * Preconditions:
  275. * strstart + MAX_MATCH <= window.length.
  276. *
  277. *
  278. * @param curMatch
  279. */
  280. private boolean findLongestMatch(int curMatch) {
  281. int chainLength = this.max_chain;
  282. int niceLength = this.niceLength;
  283. short[] prev = this.prev;
  284. int scan = this.strstart;
  285. int match;
  286. int best_end = this.strstart + matchLen;
  287. int best_len = Math.max(matchLen, MIN_MATCH - 1);
  288. int limit = Math.max(strstart - MAX_DIST, 0);
  289. int strend = scan + MAX_MATCH - 1;
  290. byte scan_end1 = window[best_end - 1];
  291. byte scan_end = window[best_end];
  292. /* Do not waste too much time if we already have a good match: */
  293. if (best_len >= this.goodLength)
  294. chainLength >>= 2;
  295. /* Do not look for matches beyond the end of the input. This is necessary
  296. * to make deflate deterministic.
  297. */
  298. if (niceLength > lookahead)
  299. niceLength = lookahead;
  300. if (DeflaterConstants.DEBUGGING
  301. && strstart > 2*WSIZE - MIN_LOOKAHEAD)
  302. throw new InternalError("need lookahead");
  303. do {
  304. if (DeflaterConstants.DEBUGGING && curMatch >= strstart)
  305. throw new InternalError("future match");
  306. if (window[curMatch + best_len] != scan_end
  307. || window[curMatch + best_len - 1] != scan_end1
  308. || window[curMatch] != window[scan]
  309. || window[curMatch+1] != window[scan + 1])
  310. continue;
  311. match = curMatch + 2;
  312. scan += 2;
  313. /* We check for insufficient lookahead only every 8th comparison;
  314. * the 256th check will be made at strstart+258.
  315. */
  316. while (window[++scan] == window[++match]
  317. && window[++scan] == window[++match]
  318. && window[++scan] == window[++match]
  319. && window[++scan] == window[++match]
  320. && window[++scan] == window[++match]
  321. && window[++scan] == window[++match]
  322. && window[++scan] == window[++match]
  323. && window[++scan] == window[++match]
  324. && scan < strend)
  325. ;
  326. if (scan > best_end) {
  327. // if (DeflaterConstants.DEBUGGING && ins_h == 0)
  328. // System.err.println("Found match: "+curMatch+"-"+(scan-strstart));
  329. matchStart = curMatch;
  330. best_end = scan;
  331. best_len = scan - strstart;
  332. if (best_len >= niceLength)
  333. break;
  334. scan_end1 = window[best_end-1];
  335. scan_end = window[best_end];
  336. }
  337. scan = strstart;
  338. } while ((curMatch = (prev[curMatch & WMASK] & 0xffff)) > limit
  339. && --chainLength != 0);
  340. matchLen = Math.min(best_len, lookahead);
  341. return matchLen >= MIN_MATCH;
  342. }
  343. void setDictionary(byte[] buffer, int offset, int length) {
  344. if (DeflaterConstants.DEBUGGING && strstart != 1)
  345. throw new IllegalStateException("strstart not 1");
  346. adler.update(buffer, offset, length);
  347. if (length < MIN_MATCH)
  348. return;
  349. if (length > MAX_DIST) {
  350. offset += length - MAX_DIST;
  351. length = MAX_DIST;
  352. }
  353. System.arraycopy(buffer, offset, window, strstart, length);
  354. updateHash();
  355. length--;
  356. while (--length > 0)
  357. {
  358. insertString();
  359. strstart++;
  360. }
  361. strstart += 2;
  362. blockStart = strstart;
  363. }
  364. private boolean deflateStored(boolean flush, boolean finish)
  365. {
  366. if (!flush && lookahead == 0)
  367. return false;
  368. strstart += lookahead;
  369. lookahead = 0;
  370. int storedLen = strstart - blockStart;
  371. if ((storedLen >= DeflaterConstants.MAX_BLOCK_SIZE)
  372. /* Block is full */
  373. || (blockStart < WSIZE && storedLen >= MAX_DIST)
  374. /* Block may move out of window */
  375. || flush)
  376. {
  377. boolean lastBlock = finish;
  378. if (storedLen > DeflaterConstants.MAX_BLOCK_SIZE)
  379. {
  380. storedLen = DeflaterConstants.MAX_BLOCK_SIZE;
  381. lastBlock = false;
  382. }
  383. if (DeflaterConstants.DEBUGGING)
  384. System.err.println("storedBlock["+storedLen+","+lastBlock+"]");
  385. huffman.flushStoredBlock(window, blockStart, storedLen, lastBlock);
  386. blockStart += storedLen;
  387. return !lastBlock;
  388. }
  389. return true;
  390. }
  391. private boolean deflateFast(boolean flush, boolean finish)
  392. {
  393. if (lookahead < MIN_LOOKAHEAD && !flush)
  394. return false;
  395. while (lookahead >= MIN_LOOKAHEAD || flush)
  396. {
  397. if (lookahead == 0)
  398. {
  399. /* We are flushing everything */
  400. huffman.flushBlock(window, blockStart, strstart - blockStart,
  401. finish);
  402. blockStart = strstart;
  403. return false;
  404. }
  405. if (strstart > 2 * WSIZE - MIN_LOOKAHEAD)
  406. {
  407. /* slide window, as findLongestMatch need this.
  408. * This should only happen when flushing and the window
  409. * is almost full.
  410. */
  411. slideWindow();
  412. }
  413. int hashHead;
  414. if (lookahead >= MIN_MATCH
  415. && (hashHead = insertString()) != 0
  416. && strategy != Deflater.HUFFMAN_ONLY
  417. && strstart - hashHead <= MAX_DIST
  418. && findLongestMatch(hashHead))
  419. {
  420. /* longestMatch sets matchStart and matchLen */
  421. if (DeflaterConstants.DEBUGGING)
  422. {
  423. for (int i = 0 ; i < matchLen; i++)
  424. {
  425. if (window[strstart+i] != window[matchStart + i])
  426. throw new InternalError();
  427. }
  428. }
  429. boolean full = huffman.tallyDist(strstart - matchStart, matchLen);
  430. lookahead -= matchLen;
  431. if (matchLen <= max_lazy && lookahead >= MIN_MATCH)
  432. {
  433. while (--matchLen > 0)
  434. {
  435. strstart++;
  436. insertString();
  437. }
  438. strstart++;
  439. }
  440. else
  441. {
  442. strstart += matchLen;
  443. if (lookahead >= MIN_MATCH - 1)
  444. updateHash();
  445. }
  446. matchLen = MIN_MATCH - 1;
  447. if (!full)
  448. continue;
  449. }
  450. else
  451. {
  452. /* No match found */
  453. huffman.tallyLit(window[strstart] & 0xff);
  454. strstart++;
  455. lookahead--;
  456. }
  457. if (huffman.isFull())
  458. {
  459. boolean lastBlock = finish && lookahead == 0;
  460. huffman.flushBlock(window, blockStart, strstart - blockStart,
  461. lastBlock);
  462. blockStart = strstart;
  463. return !lastBlock;
  464. }
  465. }
  466. return true;
  467. }
  468. private boolean deflateSlow(boolean flush, boolean finish)
  469. {
  470. if (lookahead < MIN_LOOKAHEAD && !flush)
  471. return false;
  472. while (lookahead >= MIN_LOOKAHEAD || flush)
  473. {
  474. if (lookahead == 0)
  475. {
  476. if (prevAvailable)
  477. huffman.tallyLit(window[strstart-1] & 0xff);
  478. prevAvailable = false;
  479. /* We are flushing everything */
  480. if (DeflaterConstants.DEBUGGING && !flush)
  481. throw new InternalError("Not flushing, but no lookahead");
  482. huffman.flushBlock(window, blockStart, strstart - blockStart,
  483. finish);
  484. blockStart = strstart;
  485. return false;
  486. }
  487. if (strstart >= 2 * WSIZE - MIN_LOOKAHEAD)
  488. {
  489. /* slide window, as findLongestMatch need this.
  490. * This should only happen when flushing and the window
  491. * is almost full.
  492. */
  493. slideWindow();
  494. }
  495. int prevMatch = matchStart;
  496. int prevLen = matchLen;
  497. if (lookahead >= MIN_MATCH)
  498. {
  499. int hashHead = insertString();
  500. if (strategy != Deflater.HUFFMAN_ONLY
  501. && hashHead != 0 && strstart - hashHead <= MAX_DIST
  502. && findLongestMatch(hashHead))
  503. {
  504. /* longestMatch sets matchStart and matchLen */
  505. /* Discard match if too small and too far away */
  506. if (matchLen <= 5
  507. && (strategy == Deflater.FILTERED
  508. || (matchLen == MIN_MATCH
  509. && strstart - matchStart > TOO_FAR))) {
  510. matchLen = MIN_MATCH - 1;
  511. }
  512. }
  513. }
  514. /* previous match was better */
  515. if (prevLen >= MIN_MATCH && matchLen <= prevLen)
  516. {
  517. if (DeflaterConstants.DEBUGGING)
  518. {
  519. for (int i = 0 ; i < matchLen; i++)
  520. {
  521. if (window[strstart-1+i] != window[prevMatch + i])
  522. throw new InternalError();
  523. }
  524. }
  525. huffman.tallyDist(strstart - 1 - prevMatch, prevLen);
  526. prevLen -= 2;
  527. do
  528. {
  529. strstart++;
  530. lookahead--;
  531. if (lookahead >= MIN_MATCH)
  532. insertString();
  533. }
  534. while (--prevLen > 0);
  535. strstart ++;
  536. lookahead--;
  537. prevAvailable = false;
  538. matchLen = MIN_MATCH - 1;
  539. }
  540. else
  541. {
  542. if (prevAvailable)
  543. huffman.tallyLit(window[strstart-1] & 0xff);
  544. prevAvailable = true;
  545. strstart++;
  546. lookahead--;
  547. }
  548. if (huffman.isFull())
  549. {
  550. int len = strstart - blockStart;
  551. if (prevAvailable)
  552. len--;
  553. boolean lastBlock = (finish && lookahead == 0 && !prevAvailable);
  554. huffman.flushBlock(window, blockStart, len, lastBlock);
  555. blockStart += len;
  556. return !lastBlock;
  557. }
  558. }
  559. return true;
  560. }
  561. public boolean deflate(boolean flush, boolean finish)
  562. {
  563. boolean progress;
  564. do
  565. {
  566. fillWindow();
  567. boolean canFlush = flush && inputOff == inputEnd;
  568. if (DeflaterConstants.DEBUGGING)
  569. System.err.println("window: ["+blockStart+","+strstart+","
  570. +lookahead+"], "+comprFunc+","+canFlush);
  571. switch (comprFunc)
  572. {
  573. case DEFLATE_STORED:
  574. progress = deflateStored(canFlush, finish);
  575. break;
  576. case DEFLATE_FAST:
  577. progress = deflateFast(canFlush, finish);
  578. break;
  579. case DEFLATE_SLOW:
  580. progress = deflateSlow(canFlush, finish);
  581. break;
  582. default:
  583. throw new InternalError();
  584. }
  585. }
  586. while (pending.isFlushed() /* repeat while we have no pending output */
  587. && progress); /* and progress was made */
  588. return progress;
  589. }
  590. public void setInput(byte[] buf, int off, int len)
  591. {
  592. if (inputOff < inputEnd)
  593. throw new IllegalStateException
  594. ("Old input was not completely processed");
  595. int end = off + len;
  596. /* We want to throw an ArrayIndexOutOfBoundsException early. The
  597. * check is very tricky: it also handles integer wrap around.
  598. */
  599. if (0 > off || off > end || end > buf.length)
  600. throw new ArrayIndexOutOfBoundsException();
  601. inputBuf = buf;
  602. inputOff = off;
  603. inputEnd = end;
  604. }
  605. public final boolean needsInput()
  606. {
  607. return inputEnd == inputOff;
  608. }
  609. }