Inflater.cs 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887
  1. using ICSharpCode.SharpZipLib.Checksum;
  2. using ICSharpCode.SharpZipLib.Zip.Compression.Streams;
  3. using System;
  4. namespace ICSharpCode.SharpZipLib.Zip.Compression
  5. {
  6. /// <summary>
  7. /// Inflater is used to decompress data that has been compressed according
  8. /// to the "deflate" standard described in rfc1951.
  9. ///
  10. /// By default Zlib (rfc1950) headers and footers are expected in the input.
  11. /// You can use constructor <code> public Inflater(bool noHeader)</code> passing true
  12. /// if there is no Zlib header information
  13. ///
  14. /// The usage is as following. First you have to set some input with
  15. /// <code>SetInput()</code>, then Inflate() it. If inflate doesn't
  16. /// inflate any bytes there may be three reasons:
  17. /// <ul>
  18. /// <li>IsNeedingInput() returns true because the input buffer is empty.
  19. /// You have to provide more input with <code>SetInput()</code>.
  20. /// NOTE: IsNeedingInput() also returns true when, the stream is finished.
  21. /// </li>
  22. /// <li>IsNeedingDictionary() returns true, you have to provide a preset
  23. /// dictionary with <code>SetDictionary()</code>.</li>
  24. /// <li>IsFinished returns true, the inflater has finished.</li>
  25. /// </ul>
  26. /// Once the first output byte is produced, a dictionary will not be
  27. /// needed at a later stage.
  28. ///
  29. /// author of the original java version : John Leuner, Jochen Hoenicke
  30. /// </summary>
  31. public class Inflater
  32. {
  33. #region Constants/Readonly
  34. /// <summary>
  35. /// Copy lengths for literal codes 257..285
  36. /// </summary>
  37. private static readonly int[] CPLENS = {
  38. 3, 4, 5, 6, 7, 8, 9, 10, 11, 13, 15, 17, 19, 23, 27, 31,
  39. 35, 43, 51, 59, 67, 83, 99, 115, 131, 163, 195, 227, 258
  40. };
  41. /// <summary>
  42. /// Extra bits for literal codes 257..285
  43. /// </summary>
  44. private static readonly int[] CPLEXT = {
  45. 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 2, 2, 2, 2,
  46. 3, 3, 3, 3, 4, 4, 4, 4, 5, 5, 5, 5, 0
  47. };
  48. /// <summary>
  49. /// Copy offsets for distance codes 0..29
  50. /// </summary>
  51. private static readonly int[] CPDIST = {
  52. 1, 2, 3, 4, 5, 7, 9, 13, 17, 25, 33, 49, 65, 97, 129, 193,
  53. 257, 385, 513, 769, 1025, 1537, 2049, 3073, 4097, 6145,
  54. 8193, 12289, 16385, 24577
  55. };
  56. /// <summary>
  57. /// Extra bits for distance codes
  58. /// </summary>
  59. private static readonly int[] CPDEXT = {
  60. 0, 0, 0, 0, 1, 1, 2, 2, 3, 3, 4, 4, 5, 5, 6, 6,
  61. 7, 7, 8, 8, 9, 9, 10, 10, 11, 11,
  62. 12, 12, 13, 13
  63. };
  64. /// <summary>
  65. /// These are the possible states for an inflater
  66. /// </summary>
  67. private const int DECODE_HEADER = 0;
  68. private const int DECODE_DICT = 1;
  69. private const int DECODE_BLOCKS = 2;
  70. private const int DECODE_STORED_LEN1 = 3;
  71. private const int DECODE_STORED_LEN2 = 4;
  72. private const int DECODE_STORED = 5;
  73. private const int DECODE_DYN_HEADER = 6;
  74. private const int DECODE_HUFFMAN = 7;
  75. private const int DECODE_HUFFMAN_LENBITS = 8;
  76. private const int DECODE_HUFFMAN_DIST = 9;
  77. private const int DECODE_HUFFMAN_DISTBITS = 10;
  78. private const int DECODE_CHKSUM = 11;
  79. private const int FINISHED = 12;
  80. #endregion Constants/Readonly
  81. #region Instance Fields
  82. /// <summary>
  83. /// This variable contains the current state.
  84. /// </summary>
  85. private int mode;
  86. /// <summary>
  87. /// The adler checksum of the dictionary or of the decompressed
  88. /// stream, as it is written in the header resp. footer of the
  89. /// compressed stream.
  90. /// Only valid if mode is DECODE_DICT or DECODE_CHKSUM.
  91. /// </summary>
  92. private int readAdler;
  93. /// <summary>
  94. /// The number of bits needed to complete the current state. This
  95. /// is valid, if mode is DECODE_DICT, DECODE_CHKSUM,
  96. /// DECODE_HUFFMAN_LENBITS or DECODE_HUFFMAN_DISTBITS.
  97. /// </summary>
  98. private int neededBits;
  99. private int repLength;
  100. private int repDist;
  101. private int uncomprLen;
  102. /// <summary>
  103. /// True, if the last block flag was set in the last block of the
  104. /// inflated stream. This means that the stream ends after the
  105. /// current block.
  106. /// </summary>
  107. private bool isLastBlock;
  108. /// <summary>
  109. /// The total number of inflated bytes.
  110. /// </summary>
  111. private long totalOut;
  112. /// <summary>
  113. /// The total number of bytes set with setInput(). This is not the
  114. /// value returned by the TotalIn property, since this also includes the
  115. /// unprocessed input.
  116. /// </summary>
  117. private long totalIn;
  118. /// <summary>
  119. /// This variable stores the noHeader flag that was given to the constructor.
  120. /// True means, that the inflated stream doesn't contain a Zlib header or
  121. /// footer.
  122. /// </summary>
  123. private bool noHeader;
  124. private readonly StreamManipulator input;
  125. private OutputWindow outputWindow;
  126. private InflaterDynHeader dynHeader;
  127. private InflaterHuffmanTree litlenTree, distTree;
  128. private Adler32 adler;
  129. #endregion Instance Fields
  130. #region Constructors
  131. /// <summary>
  132. /// Creates a new inflater or RFC1951 decompressor
  133. /// RFC1950/Zlib headers and footers will be expected in the input data
  134. /// </summary>
  135. public Inflater() : this(false)
  136. {
  137. }
  138. /// <summary>
  139. /// Creates a new inflater.
  140. /// </summary>
  141. /// <param name="noHeader">
  142. /// True if no RFC1950/Zlib header and footer fields are expected in the input data
  143. ///
  144. /// This is used for GZIPed/Zipped input.
  145. ///
  146. /// For compatibility with
  147. /// Sun JDK you should provide one byte of input more than needed in
  148. /// this case.
  149. /// </param>
  150. public Inflater(bool noHeader)
  151. {
  152. this.noHeader = noHeader;
  153. if (!noHeader)
  154. this.adler = new Adler32();
  155. input = new StreamManipulator();
  156. outputWindow = new OutputWindow();
  157. mode = noHeader ? DECODE_BLOCKS : DECODE_HEADER;
  158. }
  159. #endregion Constructors
  160. /// <summary>
  161. /// Resets the inflater so that a new stream can be decompressed. All
  162. /// pending input and output will be discarded.
  163. /// </summary>
  164. public void Reset()
  165. {
  166. mode = noHeader ? DECODE_BLOCKS : DECODE_HEADER;
  167. totalIn = 0;
  168. totalOut = 0;
  169. input.Reset();
  170. outputWindow.Reset();
  171. dynHeader = null;
  172. litlenTree = null;
  173. distTree = null;
  174. isLastBlock = false;
  175. adler?.Reset();
  176. }
  177. /// <summary>
  178. /// Decodes a zlib/RFC1950 header.
  179. /// </summary>
  180. /// <returns>
  181. /// False if more input is needed.
  182. /// </returns>
  183. /// <exception cref="SharpZipBaseException">
  184. /// The header is invalid.
  185. /// </exception>
  186. private bool DecodeHeader()
  187. {
  188. int header = input.PeekBits(16);
  189. if (header < 0)
  190. {
  191. return false;
  192. }
  193. input.DropBits(16);
  194. // The header is written in "wrong" byte order
  195. header = ((header << 8) | (header >> 8)) & 0xffff;
  196. if (header % 31 != 0)
  197. {
  198. throw new SharpZipBaseException("Header checksum illegal");
  199. }
  200. if ((header & 0x0f00) != (Deflater.DEFLATED << 8))
  201. {
  202. throw new SharpZipBaseException("Compression Method unknown");
  203. }
  204. /* Maximum size of the backwards window in bits.
  205. * We currently ignore this, but we could use it to make the
  206. * inflater window more space efficient. On the other hand the
  207. * full window (15 bits) is needed most times, anyway.
  208. int max_wbits = ((header & 0x7000) >> 12) + 8;
  209. */
  210. if ((header & 0x0020) == 0)
  211. { // Dictionary flag?
  212. mode = DECODE_BLOCKS;
  213. }
  214. else
  215. {
  216. mode = DECODE_DICT;
  217. neededBits = 32;
  218. }
  219. return true;
  220. }
  221. /// <summary>
  222. /// Decodes the dictionary checksum after the deflate header.
  223. /// </summary>
  224. /// <returns>
  225. /// False if more input is needed.
  226. /// </returns>
  227. private bool DecodeDict()
  228. {
  229. while (neededBits > 0)
  230. {
  231. int dictByte = input.PeekBits(8);
  232. if (dictByte < 0)
  233. {
  234. return false;
  235. }
  236. input.DropBits(8);
  237. readAdler = (readAdler << 8) | dictByte;
  238. neededBits -= 8;
  239. }
  240. return false;
  241. }
  242. /// <summary>
  243. /// Decodes the huffman encoded symbols in the input stream.
  244. /// </summary>
  245. /// <returns>
  246. /// false if more input is needed, true if output window is
  247. /// full or the current block ends.
  248. /// </returns>
  249. /// <exception cref="SharpZipBaseException">
  250. /// if deflated stream is invalid.
  251. /// </exception>
  252. private bool DecodeHuffman()
  253. {
  254. int free = outputWindow.GetFreeSpace();
  255. while (free >= 258)
  256. {
  257. int symbol;
  258. switch (mode)
  259. {
  260. case DECODE_HUFFMAN:
  261. // This is the inner loop so it is optimized a bit
  262. while (((symbol = litlenTree.GetSymbol(input)) & ~0xff) == 0)
  263. {
  264. outputWindow.Write(symbol);
  265. if (--free < 258)
  266. {
  267. return true;
  268. }
  269. }
  270. if (symbol < 257)
  271. {
  272. if (symbol < 0)
  273. {
  274. return false;
  275. }
  276. else
  277. {
  278. // symbol == 256: end of block
  279. distTree = null;
  280. litlenTree = null;
  281. mode = DECODE_BLOCKS;
  282. return true;
  283. }
  284. }
  285. try
  286. {
  287. repLength = CPLENS[symbol - 257];
  288. neededBits = CPLEXT[symbol - 257];
  289. }
  290. catch (Exception)
  291. {
  292. throw new SharpZipBaseException("Illegal rep length code");
  293. }
  294. goto case DECODE_HUFFMAN_LENBITS; // fall through
  295. case DECODE_HUFFMAN_LENBITS:
  296. if (neededBits > 0)
  297. {
  298. mode = DECODE_HUFFMAN_LENBITS;
  299. int i = input.PeekBits(neededBits);
  300. if (i < 0)
  301. {
  302. return false;
  303. }
  304. input.DropBits(neededBits);
  305. repLength += i;
  306. }
  307. mode = DECODE_HUFFMAN_DIST;
  308. goto case DECODE_HUFFMAN_DIST; // fall through
  309. case DECODE_HUFFMAN_DIST:
  310. symbol = distTree.GetSymbol(input);
  311. if (symbol < 0)
  312. {
  313. return false;
  314. }
  315. try
  316. {
  317. repDist = CPDIST[symbol];
  318. neededBits = CPDEXT[symbol];
  319. }
  320. catch (Exception)
  321. {
  322. throw new SharpZipBaseException("Illegal rep dist code");
  323. }
  324. goto case DECODE_HUFFMAN_DISTBITS; // fall through
  325. case DECODE_HUFFMAN_DISTBITS:
  326. if (neededBits > 0)
  327. {
  328. mode = DECODE_HUFFMAN_DISTBITS;
  329. int i = input.PeekBits(neededBits);
  330. if (i < 0)
  331. {
  332. return false;
  333. }
  334. input.DropBits(neededBits);
  335. repDist += i;
  336. }
  337. outputWindow.Repeat(repLength, repDist);
  338. free -= repLength;
  339. mode = DECODE_HUFFMAN;
  340. break;
  341. default:
  342. throw new SharpZipBaseException("Inflater unknown mode");
  343. }
  344. }
  345. return true;
  346. }
  347. /// <summary>
  348. /// Decodes the adler checksum after the deflate stream.
  349. /// </summary>
  350. /// <returns>
  351. /// false if more input is needed.
  352. /// </returns>
  353. /// <exception cref="SharpZipBaseException">
  354. /// If checksum doesn't match.
  355. /// </exception>
  356. private bool DecodeChksum()
  357. {
  358. while (neededBits > 0)
  359. {
  360. int chkByte = input.PeekBits(8);
  361. if (chkByte < 0)
  362. {
  363. return false;
  364. }
  365. input.DropBits(8);
  366. readAdler = (readAdler << 8) | chkByte;
  367. neededBits -= 8;
  368. }
  369. if ((int)adler?.Value != readAdler)
  370. {
  371. throw new SharpZipBaseException("Adler chksum doesn't match: " + (int)adler?.Value + " vs. " + readAdler);
  372. }
  373. mode = FINISHED;
  374. return false;
  375. }
  376. /// <summary>
  377. /// Decodes the deflated stream.
  378. /// </summary>
  379. /// <returns>
  380. /// false if more input is needed, or if finished.
  381. /// </returns>
  382. /// <exception cref="SharpZipBaseException">
  383. /// if deflated stream is invalid.
  384. /// </exception>
  385. private bool Decode()
  386. {
  387. switch (mode)
  388. {
  389. case DECODE_HEADER:
  390. return DecodeHeader();
  391. case DECODE_DICT:
  392. return DecodeDict();
  393. case DECODE_CHKSUM:
  394. return DecodeChksum();
  395. case DECODE_BLOCKS:
  396. if (isLastBlock)
  397. {
  398. if (noHeader)
  399. {
  400. mode = FINISHED;
  401. return false;
  402. }
  403. else
  404. {
  405. input.SkipToByteBoundary();
  406. neededBits = 32;
  407. mode = DECODE_CHKSUM;
  408. return true;
  409. }
  410. }
  411. int type = input.PeekBits(3);
  412. if (type < 0)
  413. {
  414. return false;
  415. }
  416. input.DropBits(3);
  417. isLastBlock |= (type & 1) != 0;
  418. switch (type >> 1)
  419. {
  420. case DeflaterConstants.STORED_BLOCK:
  421. input.SkipToByteBoundary();
  422. mode = DECODE_STORED_LEN1;
  423. break;
  424. case DeflaterConstants.STATIC_TREES:
  425. litlenTree = InflaterHuffmanTree.defLitLenTree;
  426. distTree = InflaterHuffmanTree.defDistTree;
  427. mode = DECODE_HUFFMAN;
  428. break;
  429. case DeflaterConstants.DYN_TREES:
  430. dynHeader = new InflaterDynHeader(input);
  431. mode = DECODE_DYN_HEADER;
  432. break;
  433. default:
  434. throw new SharpZipBaseException("Unknown block type " + type);
  435. }
  436. return true;
  437. case DECODE_STORED_LEN1:
  438. {
  439. if ((uncomprLen = input.PeekBits(16)) < 0)
  440. {
  441. return false;
  442. }
  443. input.DropBits(16);
  444. mode = DECODE_STORED_LEN2;
  445. }
  446. goto case DECODE_STORED_LEN2; // fall through
  447. case DECODE_STORED_LEN2:
  448. {
  449. int nlen = input.PeekBits(16);
  450. if (nlen < 0)
  451. {
  452. return false;
  453. }
  454. input.DropBits(16);
  455. if (nlen != (uncomprLen ^ 0xffff))
  456. {
  457. throw new SharpZipBaseException("broken uncompressed block");
  458. }
  459. mode = DECODE_STORED;
  460. }
  461. goto case DECODE_STORED; // fall through
  462. case DECODE_STORED:
  463. {
  464. int more = outputWindow.CopyStored(input, uncomprLen);
  465. uncomprLen -= more;
  466. if (uncomprLen == 0)
  467. {
  468. mode = DECODE_BLOCKS;
  469. return true;
  470. }
  471. return !input.IsNeedingInput;
  472. }
  473. case DECODE_DYN_HEADER:
  474. if (!dynHeader.AttemptRead())
  475. {
  476. return false;
  477. }
  478. litlenTree = dynHeader.LiteralLengthTree;
  479. distTree = dynHeader.DistanceTree;
  480. mode = DECODE_HUFFMAN;
  481. goto case DECODE_HUFFMAN; // fall through
  482. case DECODE_HUFFMAN:
  483. case DECODE_HUFFMAN_LENBITS:
  484. case DECODE_HUFFMAN_DIST:
  485. case DECODE_HUFFMAN_DISTBITS:
  486. return DecodeHuffman();
  487. case FINISHED:
  488. return false;
  489. default:
  490. throw new SharpZipBaseException("Inflater.Decode unknown mode");
  491. }
  492. }
  493. /// <summary>
  494. /// Sets the preset dictionary. This should only be called, if
  495. /// needsDictionary() returns true and it should set the same
  496. /// dictionary, that was used for deflating. The getAdler()
  497. /// function returns the checksum of the dictionary needed.
  498. /// </summary>
  499. /// <param name="buffer">
  500. /// The dictionary.
  501. /// </param>
  502. public void SetDictionary(byte[] buffer)
  503. {
  504. SetDictionary(buffer, 0, buffer.Length);
  505. }
  506. /// <summary>
  507. /// Sets the preset dictionary. This should only be called, if
  508. /// needsDictionary() returns true and it should set the same
  509. /// dictionary, that was used for deflating. The getAdler()
  510. /// function returns the checksum of the dictionary needed.
  511. /// </summary>
  512. /// <param name="buffer">
  513. /// The dictionary.
  514. /// </param>
  515. /// <param name="index">
  516. /// The index into buffer where the dictionary starts.
  517. /// </param>
  518. /// <param name="count">
  519. /// The number of bytes in the dictionary.
  520. /// </param>
  521. /// <exception cref="System.InvalidOperationException">
  522. /// No dictionary is needed.
  523. /// </exception>
  524. /// <exception cref="SharpZipBaseException">
  525. /// The adler checksum for the buffer is invalid
  526. /// </exception>
  527. public void SetDictionary(byte[] buffer, int index, int count)
  528. {
  529. if (buffer == null)
  530. {
  531. throw new ArgumentNullException(nameof(buffer));
  532. }
  533. if (index < 0)
  534. {
  535. throw new ArgumentOutOfRangeException(nameof(index));
  536. }
  537. if (count < 0)
  538. {
  539. throw new ArgumentOutOfRangeException(nameof(count));
  540. }
  541. if (!IsNeedingDictionary)
  542. {
  543. throw new InvalidOperationException("Dictionary is not needed");
  544. }
  545. adler?.Update(new ArraySegment<byte>(buffer, index, count));
  546. if (adler != null && (int)adler.Value != readAdler)
  547. {
  548. throw new SharpZipBaseException("Wrong adler checksum");
  549. }
  550. adler?.Reset();
  551. outputWindow.CopyDict(buffer, index, count);
  552. mode = DECODE_BLOCKS;
  553. }
  554. /// <summary>
  555. /// Sets the input. This should only be called, if needsInput()
  556. /// returns true.
  557. /// </summary>
  558. /// <param name="buffer">
  559. /// the input.
  560. /// </param>
  561. public void SetInput(byte[] buffer)
  562. {
  563. SetInput(buffer, 0, buffer.Length);
  564. }
  565. /// <summary>
  566. /// Sets the input. This should only be called, if needsInput()
  567. /// returns true.
  568. /// </summary>
  569. /// <param name="buffer">
  570. /// The source of input data
  571. /// </param>
  572. /// <param name="index">
  573. /// The index into buffer where the input starts.
  574. /// </param>
  575. /// <param name="count">
  576. /// The number of bytes of input to use.
  577. /// </param>
  578. /// <exception cref="System.InvalidOperationException">
  579. /// No input is needed.
  580. /// </exception>
  581. /// <exception cref="System.ArgumentOutOfRangeException">
  582. /// The index and/or count are wrong.
  583. /// </exception>
  584. public void SetInput(byte[] buffer, int index, int count)
  585. {
  586. input.SetInput(buffer, index, count);
  587. totalIn += (long)count;
  588. }
  589. /// <summary>
  590. /// Inflates the compressed stream to the output buffer. If this
  591. /// returns 0, you should check, whether IsNeedingDictionary(),
  592. /// IsNeedingInput() or IsFinished() returns true, to determine why no
  593. /// further output is produced.
  594. /// </summary>
  595. /// <param name="buffer">
  596. /// the output buffer.
  597. /// </param>
  598. /// <returns>
  599. /// The number of bytes written to the buffer, 0 if no further
  600. /// output can be produced.
  601. /// </returns>
  602. /// <exception cref="System.ArgumentOutOfRangeException">
  603. /// if buffer has length 0.
  604. /// </exception>
  605. /// <exception cref="System.FormatException">
  606. /// if deflated stream is invalid.
  607. /// </exception>
  608. public int Inflate(byte[] buffer)
  609. {
  610. if (buffer == null)
  611. {
  612. throw new ArgumentNullException(nameof(buffer));
  613. }
  614. return Inflate(buffer, 0, buffer.Length);
  615. }
  616. /// <summary>
  617. /// Inflates the compressed stream to the output buffer. If this
  618. /// returns 0, you should check, whether needsDictionary(),
  619. /// needsInput() or finished() returns true, to determine why no
  620. /// further output is produced.
  621. /// </summary>
  622. /// <param name="buffer">
  623. /// the output buffer.
  624. /// </param>
  625. /// <param name="offset">
  626. /// the offset in buffer where storing starts.
  627. /// </param>
  628. /// <param name="count">
  629. /// the maximum number of bytes to output.
  630. /// </param>
  631. /// <returns>
  632. /// the number of bytes written to the buffer, 0 if no further output can be produced.
  633. /// </returns>
  634. /// <exception cref="System.ArgumentOutOfRangeException">
  635. /// if count is less than 0.
  636. /// </exception>
  637. /// <exception cref="System.ArgumentOutOfRangeException">
  638. /// if the index and / or count are wrong.
  639. /// </exception>
  640. /// <exception cref="System.FormatException">
  641. /// if deflated stream is invalid.
  642. /// </exception>
  643. public int Inflate(byte[] buffer, int offset, int count)
  644. {
  645. if (buffer == null)
  646. {
  647. throw new ArgumentNullException(nameof(buffer));
  648. }
  649. if (count < 0)
  650. {
  651. throw new ArgumentOutOfRangeException(nameof(count), "count cannot be negative");
  652. }
  653. if (offset < 0)
  654. {
  655. throw new ArgumentOutOfRangeException(nameof(offset), "offset cannot be negative");
  656. }
  657. if (offset + count > buffer.Length)
  658. {
  659. throw new ArgumentException("count exceeds buffer bounds");
  660. }
  661. // Special case: count may be zero
  662. if (count == 0)
  663. {
  664. if (!IsFinished)
  665. { // -jr- 08-Nov-2003 INFLATE_BUG fix..
  666. Decode();
  667. }
  668. return 0;
  669. }
  670. int bytesCopied = 0;
  671. do
  672. {
  673. if (mode != DECODE_CHKSUM)
  674. {
  675. /* Don't give away any output, if we are waiting for the
  676. * checksum in the input stream.
  677. *
  678. * With this trick we have always:
  679. * IsNeedingInput() and not IsFinished()
  680. * implies more output can be produced.
  681. */
  682. int more = outputWindow.CopyOutput(buffer, offset, count);
  683. if (more > 0)
  684. {
  685. adler?.Update(new ArraySegment<byte>(buffer, offset, more));
  686. offset += more;
  687. bytesCopied += more;
  688. totalOut += (long)more;
  689. count -= more;
  690. if (count == 0)
  691. {
  692. return bytesCopied;
  693. }
  694. }
  695. }
  696. } while (Decode() || ((outputWindow.GetAvailable() > 0) && (mode != DECODE_CHKSUM)));
  697. return bytesCopied;
  698. }
  699. /// <summary>
  700. /// Returns true, if the input buffer is empty.
  701. /// You should then call setInput().
  702. /// NOTE: This method also returns true when the stream is finished.
  703. /// </summary>
  704. public bool IsNeedingInput
  705. {
  706. get
  707. {
  708. return input.IsNeedingInput;
  709. }
  710. }
  711. /// <summary>
  712. /// Returns true, if a preset dictionary is needed to inflate the input.
  713. /// </summary>
  714. public bool IsNeedingDictionary
  715. {
  716. get
  717. {
  718. return mode == DECODE_DICT && neededBits == 0;
  719. }
  720. }
  721. /// <summary>
  722. /// Returns true, if the inflater has finished. This means, that no
  723. /// input is needed and no output can be produced.
  724. /// </summary>
  725. public bool IsFinished
  726. {
  727. get
  728. {
  729. return mode == FINISHED && outputWindow.GetAvailable() == 0;
  730. }
  731. }
  732. /// <summary>
  733. /// Gets the adler checksum. This is either the checksum of all
  734. /// uncompressed bytes returned by inflate(), or if needsDictionary()
  735. /// returns true (and thus no output was yet produced) this is the
  736. /// adler checksum of the expected dictionary.
  737. /// </summary>
  738. /// <returns>
  739. /// the adler checksum.
  740. /// </returns>
  741. public int Adler
  742. {
  743. get
  744. {
  745. if (IsNeedingDictionary)
  746. {
  747. return readAdler;
  748. }
  749. else if (adler != null)
  750. {
  751. return (int)adler.Value;
  752. }
  753. else
  754. {
  755. return 0;
  756. }
  757. }
  758. }
  759. /// <summary>
  760. /// Gets the total number of output bytes returned by Inflate().
  761. /// </summary>
  762. /// <returns>
  763. /// the total number of output bytes.
  764. /// </returns>
  765. public long TotalOut
  766. {
  767. get
  768. {
  769. return totalOut;
  770. }
  771. }
  772. /// <summary>
  773. /// Gets the total number of processed compressed input bytes.
  774. /// </summary>
  775. /// <returns>
  776. /// The total number of bytes of processed input bytes.
  777. /// </returns>
  778. public long TotalIn
  779. {
  780. get
  781. {
  782. return totalIn - (long)RemainingInput;
  783. }
  784. }
  785. /// <summary>
  786. /// Gets the number of unprocessed input bytes. Useful, if the end of the
  787. /// stream is reached and you want to further process the bytes after
  788. /// the deflate stream.
  789. /// </summary>
  790. /// <returns>
  791. /// The number of bytes of the input which have not been processed.
  792. /// </returns>
  793. public int RemainingInput
  794. {
  795. // TODO: This should be a long?
  796. get
  797. {
  798. return input.AvailableBytes;
  799. }
  800. }
  801. }
  802. }