ZlibCodec.cs 29 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712
  1. // ZlibCodec.cs
  2. // ------------------------------------------------------------------
  3. //
  4. // Copyright (c) 2009 Dino Chiesa and Microsoft Corporation.
  5. // All rights reserved.
  6. //
  7. // This code module is part of DotNetZip, a zipfile class library.
  8. //
  9. // ------------------------------------------------------------------
  10. //
  11. // This code is licensed under the Microsoft Public License.
  12. // See the file License.txt for the license details.
  13. // More info on: http://dotnetzip.codeplex.com
  14. //
  15. // ------------------------------------------------------------------
  16. //
  17. // last saved (in emacs):
  18. // Time-stamp: <2009-November-03 15:40:51>
  19. //
  20. // ------------------------------------------------------------------
  21. //
  22. // This module defines a Codec for ZLIB compression and
  23. // decompression. This code extends code that was based the jzlib
  24. // implementation of zlib, but this code is completely novel. The codec
  25. // class is new, and encapsulates some behaviors that are new, and some
  26. // that were present in other classes in the jzlib code base. In
  27. // keeping with the license for jzlib, the copyright to the jzlib code
  28. // is included below.
  29. //
  30. // ------------------------------------------------------------------
  31. //
  32. // Copyright (c) 2000,2001,2002,2003 ymnk, JCraft,Inc. All rights reserved.
  33. //
  34. // Redistribution and use in source and binary forms, with or without
  35. // modification, are permitted provided that the following conditions are met:
  36. //
  37. // 1. Redistributions of source code must retain the above copyright notice,
  38. // this list of conditions and the following disclaimer.
  39. //
  40. // 2. Redistributions in binary form must reproduce the above copyright
  41. // notice, this list of conditions and the following disclaimer in
  42. // the documentation and/or other materials provided with the distribution.
  43. //
  44. // 3. The names of the authors may not be used to endorse or promote products
  45. // derived from this software without specific prior written permission.
  46. //
  47. // THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED WARRANTIES,
  48. // INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND
  49. // FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL JCRAFT,
  50. // INC. OR ANY CONTRIBUTORS TO THIS SOFTWARE BE LIABLE FOR ANY DIRECT, INDIRECT,
  51. // INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
  52. // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA,
  53. // OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
  54. // LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
  55. // NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE,
  56. // EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  57. //
  58. // -----------------------------------------------------------------------
  59. //
  60. // This program is based on zlib-1.1.3; credit to authors
  61. // Jean-loup Gailly(jloup@gzip.org) and Mark Adler(madler@alumni.caltech.edu)
  62. // and contributors of zlib.
  63. //
  64. // -----------------------------------------------------------------------
  65. using System;
  66. using Interop=System.Runtime.InteropServices;
  67. namespace BestHTTP.Decompression.Zlib
  68. {
  69. /// <summary>
  70. /// Encoder and Decoder for ZLIB and DEFLATE (IETF RFC1950 and RFC1951).
  71. /// </summary>
  72. ///
  73. /// <remarks>
  74. /// This class compresses and decompresses data according to the Deflate algorithm
  75. /// and optionally, the ZLIB format, as documented in <see
  76. /// href="http://www.ietf.org/rfc/rfc1950.txt">RFC 1950 - ZLIB</see> and <see
  77. /// href="http://www.ietf.org/rfc/rfc1951.txt">RFC 1951 - DEFLATE</see>.
  78. /// </remarks>
  79. sealed internal class ZlibCodec
  80. {
  81. /// <summary>
  82. /// The buffer from which data is taken.
  83. /// </summary>
  84. public byte[] InputBuffer;
  85. /// <summary>
  86. /// An index into the InputBuffer array, indicating where to start reading.
  87. /// </summary>
  88. public int NextIn;
  89. /// <summary>
  90. /// The number of bytes available in the InputBuffer, starting at NextIn.
  91. /// </summary>
  92. /// <remarks>
  93. /// Generally you should set this to InputBuffer.Length before the first Inflate() or Deflate() call.
  94. /// The class will update this number as calls to Inflate/Deflate are made.
  95. /// </remarks>
  96. public int AvailableBytesIn;
  97. /// <summary>
  98. /// Total number of bytes read so far, through all calls to Inflate()/Deflate().
  99. /// </summary>
  100. public long TotalBytesIn;
  101. /// <summary>
  102. /// Buffer to store output data.
  103. /// </summary>
  104. public byte[] OutputBuffer;
  105. /// <summary>
  106. /// An index into the OutputBuffer array, indicating where to start writing.
  107. /// </summary>
  108. public int NextOut;
  109. /// <summary>
  110. /// The number of bytes available in the OutputBuffer, starting at NextOut.
  111. /// </summary>
  112. /// <remarks>
  113. /// Generally you should set this to OutputBuffer.Length before the first Inflate() or Deflate() call.
  114. /// The class will update this number as calls to Inflate/Deflate are made.
  115. /// </remarks>
  116. public int AvailableBytesOut;
  117. /// <summary>
  118. /// Total number of bytes written to the output so far, through all calls to Inflate()/Deflate().
  119. /// </summary>
  120. public long TotalBytesOut;
  121. /// <summary>
  122. /// used for diagnostics, when something goes wrong!
  123. /// </summary>
  124. public System.String Message;
  125. internal DeflateManager dstate;
  126. internal InflateManager istate;
  127. internal uint _Adler32;
  128. /// <summary>
  129. /// The compression level to use in this codec. Useful only in compression mode.
  130. /// </summary>
  131. public CompressionLevel CompressLevel = CompressionLevel.Default;
  132. /// <summary>
  133. /// The number of Window Bits to use.
  134. /// </summary>
  135. /// <remarks>
  136. /// This gauges the size of the sliding window, and hence the
  137. /// compression effectiveness as well as memory consumption. It's best to just leave this
  138. /// setting alone if you don't know what it is. The maximum value is 15 bits, which implies
  139. /// a 32k window.
  140. /// </remarks>
  141. public int WindowBits = ZlibConstants.WindowBitsDefault;
  142. /// <summary>
  143. /// The compression strategy to use.
  144. /// </summary>
  145. /// <remarks>
  146. /// This is only effective in compression. The theory offered by ZLIB is that different
  147. /// strategies could potentially produce significant differences in compression behavior
  148. /// for different data sets. Unfortunately I don't have any good recommendations for how
  149. /// to set it differently. When I tested changing the strategy I got minimally different
  150. /// compression performance. It's best to leave this property alone if you don't have a
  151. /// good feel for it. Or, you may want to produce a test harness that runs through the
  152. /// different strategy options and evaluates them on different file types. If you do that,
  153. /// let me know your results.
  154. /// </remarks>
  155. public CompressionStrategy Strategy = CompressionStrategy.Default;
  156. /// <summary>
  157. /// The Adler32 checksum on the data transferred through the codec so far. You probably don't need to look at this.
  158. /// </summary>
  159. public int Adler32 { get { return (int)_Adler32; } }
  160. /// <summary>
  161. /// Create a ZlibCodec.
  162. /// </summary>
  163. /// <remarks>
  164. /// If you use this default constructor, you will later have to explicitly call
  165. /// InitializeInflate() or InitializeDeflate() before using the ZlibCodec to compress
  166. /// or decompress.
  167. /// </remarks>
  168. public ZlibCodec() { }
  169. /// <summary>
  170. /// Create a ZlibCodec that either compresses or decompresses.
  171. /// </summary>
  172. /// <param name="mode">
  173. /// Indicates whether the codec should compress (deflate) or decompress (inflate).
  174. /// </param>
  175. public ZlibCodec(CompressionMode mode)
  176. {
  177. if (mode == CompressionMode.Compress)
  178. {
  179. int rc = InitializeDeflate();
  180. if (rc != ZlibConstants.Z_OK) throw new ZlibException("Cannot initialize for deflate.");
  181. }
  182. else if (mode == CompressionMode.Decompress)
  183. {
  184. int rc = InitializeInflate();
  185. if (rc != ZlibConstants.Z_OK) throw new ZlibException("Cannot initialize for inflate.");
  186. }
  187. else throw new ZlibException("Invalid ZlibStreamFlavor.");
  188. }
  189. /// <summary>
  190. /// Initialize the inflation state.
  191. /// </summary>
  192. /// <remarks>
  193. /// It is not necessary to call this before using the ZlibCodec to inflate data;
  194. /// It is implicitly called when you call the constructor.
  195. /// </remarks>
  196. /// <returns>Z_OK if everything goes well.</returns>
  197. public int InitializeInflate()
  198. {
  199. return InitializeInflate(this.WindowBits);
  200. }
  201. /// <summary>
  202. /// Initialize the inflation state with an explicit flag to
  203. /// govern the handling of RFC1950 header bytes.
  204. /// </summary>
  205. ///
  206. /// <remarks>
  207. /// By default, the ZLIB header defined in <see
  208. /// href="http://www.ietf.org/rfc/rfc1950.txt">RFC 1950</see> is expected. If
  209. /// you want to read a zlib stream you should specify true for
  210. /// expectRfc1950Header. If you have a deflate stream, you will want to specify
  211. /// false. It is only necessary to invoke this initializer explicitly if you
  212. /// want to specify false.
  213. /// </remarks>
  214. ///
  215. /// <param name="expectRfc1950Header">whether to expect an RFC1950 header byte
  216. /// pair when reading the stream of data to be inflated.</param>
  217. ///
  218. /// <returns>Z_OK if everything goes well.</returns>
  219. public int InitializeInflate(bool expectRfc1950Header)
  220. {
  221. return InitializeInflate(this.WindowBits, expectRfc1950Header);
  222. }
  223. /// <summary>
  224. /// Initialize the ZlibCodec for inflation, with the specified number of window bits.
  225. /// </summary>
  226. /// <param name="windowBits">The number of window bits to use. If you need to ask what that is,
  227. /// then you shouldn't be calling this initializer.</param>
  228. /// <returns>Z_OK if all goes well.</returns>
  229. public int InitializeInflate(int windowBits)
  230. {
  231. this.WindowBits = windowBits;
  232. return InitializeInflate(windowBits, true);
  233. }
  234. /// <summary>
  235. /// Initialize the inflation state with an explicit flag to govern the handling of
  236. /// RFC1950 header bytes.
  237. /// </summary>
  238. ///
  239. /// <remarks>
  240. /// If you want to read a zlib stream you should specify true for
  241. /// expectRfc1950Header. In this case, the library will expect to find a ZLIB
  242. /// header, as defined in <see href="http://www.ietf.org/rfc/rfc1950.txt">RFC
  243. /// 1950</see>, in the compressed stream. If you will be reading a DEFLATE or
  244. /// GZIP stream, which does not have such a header, you will want to specify
  245. /// false.
  246. /// </remarks>
  247. ///
  248. /// <param name="expectRfc1950Header">whether to expect an RFC1950 header byte pair when reading
  249. /// the stream of data to be inflated.</param>
  250. /// <param name="windowBits">The number of window bits to use. If you need to ask what that is,
  251. /// then you shouldn't be calling this initializer.</param>
  252. /// <returns>Z_OK if everything goes well.</returns>
  253. public int InitializeInflate(int windowBits, bool expectRfc1950Header)
  254. {
  255. this.WindowBits = windowBits;
  256. if (dstate != null) throw new ZlibException("You may not call InitializeInflate() after calling InitializeDeflate().");
  257. istate = new InflateManager(expectRfc1950Header);
  258. return istate.Initialize(this, windowBits);
  259. }
  260. /// <summary>
  261. /// Inflate the data in the InputBuffer, placing the result in the OutputBuffer.
  262. /// </summary>
  263. /// <remarks>
  264. /// You must have set InputBuffer and OutputBuffer, NextIn and NextOut, and AvailableBytesIn and
  265. /// AvailableBytesOut before calling this method.
  266. /// </remarks>
  267. /// <example>
  268. /// <code>
  269. /// private void InflateBuffer()
  270. /// {
  271. /// int bufferSize = 1024;
  272. /// byte[] buffer = new byte[bufferSize];
  273. /// ZlibCodec decompressor = new ZlibCodec();
  274. ///
  275. /// Console.WriteLine("\n============================================");
  276. /// Console.WriteLine("Size of Buffer to Inflate: {0} bytes.", CompressedBytes.Length);
  277. /// MemoryStream ms = new MemoryStream(DecompressedBytes);
  278. ///
  279. /// int rc = decompressor.InitializeInflate();
  280. ///
  281. /// decompressor.InputBuffer = CompressedBytes;
  282. /// decompressor.NextIn = 0;
  283. /// decompressor.AvailableBytesIn = CompressedBytes.Length;
  284. ///
  285. /// decompressor.OutputBuffer = buffer;
  286. ///
  287. /// // pass 1: inflate
  288. /// do
  289. /// {
  290. /// decompressor.NextOut = 0;
  291. /// decompressor.AvailableBytesOut = buffer.Length;
  292. /// rc = decompressor.Inflate(FlushType.None);
  293. ///
  294. /// if (rc != ZlibConstants.Z_OK &amp;&amp; rc != ZlibConstants.Z_STREAM_END)
  295. /// throw new Exception("inflating: " + decompressor.Message);
  296. ///
  297. /// ms.Write(decompressor.OutputBuffer, 0, buffer.Length - decompressor.AvailableBytesOut);
  298. /// }
  299. /// while (decompressor.AvailableBytesIn &gt; 0 || decompressor.AvailableBytesOut == 0);
  300. ///
  301. /// // pass 2: finish and flush
  302. /// do
  303. /// {
  304. /// decompressor.NextOut = 0;
  305. /// decompressor.AvailableBytesOut = buffer.Length;
  306. /// rc = decompressor.Inflate(FlushType.Finish);
  307. ///
  308. /// if (rc != ZlibConstants.Z_STREAM_END &amp;&amp; rc != ZlibConstants.Z_OK)
  309. /// throw new Exception("inflating: " + decompressor.Message);
  310. ///
  311. /// if (buffer.Length - decompressor.AvailableBytesOut &gt; 0)
  312. /// ms.Write(buffer, 0, buffer.Length - decompressor.AvailableBytesOut);
  313. /// }
  314. /// while (decompressor.AvailableBytesIn &gt; 0 || decompressor.AvailableBytesOut == 0);
  315. ///
  316. /// decompressor.EndInflate();
  317. /// }
  318. ///
  319. /// </code>
  320. /// </example>
  321. /// <param name="flush">The flush to use when inflating.</param>
  322. /// <returns>Z_OK if everything goes well.</returns>
  323. public int Inflate(FlushType flush)
  324. {
  325. if (istate == null)
  326. throw new ZlibException("No Inflate State!");
  327. return istate.Inflate(flush);
  328. }
  329. /// <summary>
  330. /// Ends an inflation session.
  331. /// </summary>
  332. /// <remarks>
  333. /// Call this after successively calling Inflate(). This will cause all buffers to be flushed.
  334. /// After calling this you cannot call Inflate() without a intervening call to one of the
  335. /// InitializeInflate() overloads.
  336. /// </remarks>
  337. /// <returns>Z_OK if everything goes well.</returns>
  338. public int EndInflate()
  339. {
  340. if (istate == null)
  341. throw new ZlibException("No Inflate State!");
  342. int ret = istate.End();
  343. istate = null;
  344. return ret;
  345. }
  346. /// <summary>
  347. /// I don't know what this does!
  348. /// </summary>
  349. /// <returns>Z_OK if everything goes well.</returns>
  350. public int SyncInflate()
  351. {
  352. if (istate == null)
  353. throw new ZlibException("No Inflate State!");
  354. return istate.Sync();
  355. }
  356. /// <summary>
  357. /// Initialize the ZlibCodec for deflation operation.
  358. /// </summary>
  359. /// <remarks>
  360. /// The codec will use the MAX window bits and the default level of compression.
  361. /// </remarks>
  362. /// <example>
  363. /// <code>
  364. /// int bufferSize = 40000;
  365. /// byte[] CompressedBytes = new byte[bufferSize];
  366. /// byte[] DecompressedBytes = new byte[bufferSize];
  367. ///
  368. /// ZlibCodec compressor = new ZlibCodec();
  369. ///
  370. /// compressor.InitializeDeflate(CompressionLevel.Default);
  371. ///
  372. /// compressor.InputBuffer = System.Text.ASCIIEncoding.ASCII.GetBytes(TextToCompress);
  373. /// compressor.NextIn = 0;
  374. /// compressor.AvailableBytesIn = compressor.InputBuffer.Length;
  375. ///
  376. /// compressor.OutputBuffer = CompressedBytes;
  377. /// compressor.NextOut = 0;
  378. /// compressor.AvailableBytesOut = CompressedBytes.Length;
  379. ///
  380. /// while (compressor.TotalBytesIn != TextToCompress.Length &amp;&amp; compressor.TotalBytesOut &lt; bufferSize)
  381. /// {
  382. /// compressor.Deflate(FlushType.None);
  383. /// }
  384. ///
  385. /// while (true)
  386. /// {
  387. /// int rc= compressor.Deflate(FlushType.Finish);
  388. /// if (rc == ZlibConstants.Z_STREAM_END) break;
  389. /// }
  390. ///
  391. /// compressor.EndDeflate();
  392. ///
  393. /// </code>
  394. /// </example>
  395. /// <returns>Z_OK if all goes well. You generally don't need to check the return code.</returns>
  396. public int InitializeDeflate()
  397. {
  398. return _InternalInitializeDeflate(true);
  399. }
  400. /// <summary>
  401. /// Initialize the ZlibCodec for deflation operation, using the specified CompressionLevel.
  402. /// </summary>
  403. /// <remarks>
  404. /// The codec will use the maximum window bits (15) and the specified
  405. /// CompressionLevel. It will emit a ZLIB stream as it compresses.
  406. /// </remarks>
  407. /// <param name="level">The compression level for the codec.</param>
  408. /// <returns>Z_OK if all goes well.</returns>
  409. public int InitializeDeflate(CompressionLevel level)
  410. {
  411. this.CompressLevel = level;
  412. return _InternalInitializeDeflate(true);
  413. }
  414. /// <summary>
  415. /// Initialize the ZlibCodec for deflation operation, using the specified CompressionLevel,
  416. /// and the explicit flag governing whether to emit an RFC1950 header byte pair.
  417. /// </summary>
  418. /// <remarks>
  419. /// The codec will use the maximum window bits (15) and the specified CompressionLevel.
  420. /// If you want to generate a zlib stream, you should specify true for
  421. /// wantRfc1950Header. In this case, the library will emit a ZLIB
  422. /// header, as defined in <see href="http://www.ietf.org/rfc/rfc1950.txt">RFC
  423. /// 1950</see>, in the compressed stream.
  424. /// </remarks>
  425. /// <param name="level">The compression level for the codec.</param>
  426. /// <param name="wantRfc1950Header">whether to emit an initial RFC1950 byte pair in the compressed stream.</param>
  427. /// <returns>Z_OK if all goes well.</returns>
  428. public int InitializeDeflate(CompressionLevel level, bool wantRfc1950Header)
  429. {
  430. this.CompressLevel = level;
  431. return _InternalInitializeDeflate(wantRfc1950Header);
  432. }
  433. /// <summary>
  434. /// Initialize the ZlibCodec for deflation operation, using the specified CompressionLevel,
  435. /// and the specified number of window bits.
  436. /// </summary>
  437. /// <remarks>
  438. /// The codec will use the specified number of window bits and the specified CompressionLevel.
  439. /// </remarks>
  440. /// <param name="level">The compression level for the codec.</param>
  441. /// <param name="bits">the number of window bits to use. If you don't know what this means, don't use this method.</param>
  442. /// <returns>Z_OK if all goes well.</returns>
  443. public int InitializeDeflate(CompressionLevel level, int bits)
  444. {
  445. this.CompressLevel = level;
  446. this.WindowBits = bits;
  447. return _InternalInitializeDeflate(true);
  448. }
  449. /// <summary>
  450. /// Initialize the ZlibCodec for deflation operation, using the specified
  451. /// CompressionLevel, the specified number of window bits, and the explicit flag
  452. /// governing whether to emit an RFC1950 header byte pair.
  453. /// </summary>
  454. ///
  455. /// <param name="level">The compression level for the codec.</param>
  456. /// <param name="wantRfc1950Header">whether to emit an initial RFC1950 byte pair in the compressed stream.</param>
  457. /// <param name="bits">the number of window bits to use. If you don't know what this means, don't use this method.</param>
  458. /// <returns>Z_OK if all goes well.</returns>
  459. public int InitializeDeflate(CompressionLevel level, int bits, bool wantRfc1950Header)
  460. {
  461. this.CompressLevel = level;
  462. this.WindowBits = bits;
  463. return _InternalInitializeDeflate(wantRfc1950Header);
  464. }
  465. private int _InternalInitializeDeflate(bool wantRfc1950Header)
  466. {
  467. if (istate != null) throw new ZlibException("You may not call InitializeDeflate() after calling InitializeInflate().");
  468. dstate = new DeflateManager();
  469. dstate.WantRfc1950HeaderBytes = wantRfc1950Header;
  470. return dstate.Initialize(this, this.CompressLevel, this.WindowBits, this.Strategy);
  471. }
  472. /// <summary>
  473. /// Deflate one batch of data.
  474. /// </summary>
  475. /// <remarks>
  476. /// You must have set InputBuffer and OutputBuffer before calling this method.
  477. /// </remarks>
  478. /// <example>
  479. /// <code>
  480. /// private void DeflateBuffer(CompressionLevel level)
  481. /// {
  482. /// int bufferSize = 1024;
  483. /// byte[] buffer = new byte[bufferSize];
  484. /// ZlibCodec compressor = new ZlibCodec();
  485. ///
  486. /// Console.WriteLine("\n============================================");
  487. /// Console.WriteLine("Size of Buffer to Deflate: {0} bytes.", UncompressedBytes.Length);
  488. /// MemoryStream ms = new MemoryStream();
  489. ///
  490. /// int rc = compressor.InitializeDeflate(level);
  491. ///
  492. /// compressor.InputBuffer = UncompressedBytes;
  493. /// compressor.NextIn = 0;
  494. /// compressor.AvailableBytesIn = UncompressedBytes.Length;
  495. ///
  496. /// compressor.OutputBuffer = buffer;
  497. ///
  498. /// // pass 1: deflate
  499. /// do
  500. /// {
  501. /// compressor.NextOut = 0;
  502. /// compressor.AvailableBytesOut = buffer.Length;
  503. /// rc = compressor.Deflate(FlushType.None);
  504. ///
  505. /// if (rc != ZlibConstants.Z_OK &amp;&amp; rc != ZlibConstants.Z_STREAM_END)
  506. /// throw new Exception("deflating: " + compressor.Message);
  507. ///
  508. /// ms.Write(compressor.OutputBuffer, 0, buffer.Length - compressor.AvailableBytesOut);
  509. /// }
  510. /// while (compressor.AvailableBytesIn &gt; 0 || compressor.AvailableBytesOut == 0);
  511. ///
  512. /// // pass 2: finish and flush
  513. /// do
  514. /// {
  515. /// compressor.NextOut = 0;
  516. /// compressor.AvailableBytesOut = buffer.Length;
  517. /// rc = compressor.Deflate(FlushType.Finish);
  518. ///
  519. /// if (rc != ZlibConstants.Z_STREAM_END &amp;&amp; rc != ZlibConstants.Z_OK)
  520. /// throw new Exception("deflating: " + compressor.Message);
  521. ///
  522. /// if (buffer.Length - compressor.AvailableBytesOut &gt; 0)
  523. /// ms.Write(buffer, 0, buffer.Length - compressor.AvailableBytesOut);
  524. /// }
  525. /// while (compressor.AvailableBytesIn &gt; 0 || compressor.AvailableBytesOut == 0);
  526. ///
  527. /// compressor.EndDeflate();
  528. ///
  529. /// ms.Seek(0, SeekOrigin.Begin);
  530. /// CompressedBytes = new byte[compressor.TotalBytesOut];
  531. /// ms.Read(CompressedBytes, 0, CompressedBytes.Length);
  532. /// }
  533. /// </code>
  534. /// </example>
  535. /// <param name="flush">whether to flush all data as you deflate. Generally you will want to
  536. /// use Z_NO_FLUSH here, in a series of calls to Deflate(), and then call EndDeflate() to
  537. /// flush everything.
  538. /// </param>
  539. /// <returns>Z_OK if all goes well.</returns>
  540. public int Deflate(FlushType flush)
  541. {
  542. if (dstate == null)
  543. throw new ZlibException("No Deflate State!");
  544. return dstate.Deflate(flush);
  545. }
  546. /// <summary>
  547. /// End a deflation session.
  548. /// </summary>
  549. /// <remarks>
  550. /// Call this after making a series of one or more calls to Deflate(). All buffers are flushed.
  551. /// </remarks>
  552. /// <returns>Z_OK if all goes well.</returns>
  553. public int EndDeflate()
  554. {
  555. if (dstate == null)
  556. throw new ZlibException("No Deflate State!");
  557. // TODO: dinoch Tue, 03 Nov 2009 15:39 (test this)
  558. //int ret = dstate.End();
  559. dstate = null;
  560. return ZlibConstants.Z_OK; //ret;
  561. }
  562. /// <summary>
  563. /// Reset a codec for another deflation session.
  564. /// </summary>
  565. /// <remarks>
  566. /// Call this to reset the deflation state. For example if a thread is deflating
  567. /// non-consecutive blocks, you can call Reset() after the Deflate(Sync) of the first
  568. /// block and before the next Deflate(None) of the second block.
  569. /// </remarks>
  570. /// <returns>Z_OK if all goes well.</returns>
  571. public void ResetDeflate()
  572. {
  573. if (dstate == null)
  574. throw new ZlibException("No Deflate State!");
  575. dstate.Reset();
  576. }
  577. /// <summary>
  578. /// Set the CompressionStrategy and CompressionLevel for a deflation session.
  579. /// </summary>
  580. /// <param name="level">the level of compression to use.</param>
  581. /// <param name="strategy">the strategy to use for compression.</param>
  582. /// <returns>Z_OK if all goes well.</returns>
  583. public int SetDeflateParams(CompressionLevel level, CompressionStrategy strategy)
  584. {
  585. if (dstate == null)
  586. throw new ZlibException("No Deflate State!");
  587. return dstate.SetParams(level, strategy);
  588. }
  589. /// <summary>
  590. /// Set the dictionary to be used for either Inflation or Deflation.
  591. /// </summary>
  592. /// <param name="dictionary">The dictionary bytes to use.</param>
  593. /// <returns>Z_OK if all goes well.</returns>
  594. public int SetDictionary(byte[] dictionary)
  595. {
  596. if (istate != null)
  597. return istate.SetDictionary(dictionary);
  598. if (dstate != null)
  599. return dstate.SetDictionary(dictionary);
  600. throw new ZlibException("No Inflate or Deflate state!");
  601. }
  602. // Flush as much pending output as possible. All deflate() output goes
  603. // through this function so some applications may wish to modify it
  604. // to avoid allocating a large strm->next_out buffer and copying into it.
  605. // (See also read_buf()).
  606. internal void flush_pending()
  607. {
  608. int len = dstate.pendingCount;
  609. if (len > AvailableBytesOut)
  610. len = AvailableBytesOut;
  611. if (len == 0)
  612. return;
  613. if (dstate.pending.Length <= dstate.nextPending ||
  614. OutputBuffer.Length <= NextOut ||
  615. dstate.pending.Length < (dstate.nextPending + len) ||
  616. OutputBuffer.Length < (NextOut + len))
  617. {
  618. throw new ZlibException(String.Format("Invalid State. (pending.Length={0}, pendingCount={1})",
  619. dstate.pending.Length, dstate.pendingCount));
  620. }
  621. Array.Copy(dstate.pending, dstate.nextPending, OutputBuffer, NextOut, len);
  622. NextOut += len;
  623. dstate.nextPending += len;
  624. TotalBytesOut += len;
  625. AvailableBytesOut -= len;
  626. dstate.pendingCount -= len;
  627. if (dstate.pendingCount == 0)
  628. {
  629. dstate.nextPending = 0;
  630. }
  631. }
  632. // Read a new buffer from the current input stream, update the adler32
  633. // and total number of bytes read. All deflate() input goes through
  634. // this function so some applications may wish to modify it to avoid
  635. // allocating a large strm->next_in buffer and copying from it.
  636. // (See also flush_pending()).
  637. internal int read_buf(byte[] buf, int start, int size)
  638. {
  639. int len = AvailableBytesIn;
  640. if (len > size)
  641. len = size;
  642. if (len == 0)
  643. return 0;
  644. AvailableBytesIn -= len;
  645. if (dstate.WantRfc1950HeaderBytes)
  646. {
  647. _Adler32 = Adler.Adler32(_Adler32, InputBuffer, NextIn, len);
  648. }
  649. Array.Copy(InputBuffer, NextIn, buf, start, len);
  650. NextIn += len;
  651. TotalBytesIn += len;
  652. return len;
  653. }
  654. }
  655. }