ZlibCodec.cs 30 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719
  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 Ionic.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. #if !PCL
  80. [Interop.GuidAttribute("ebc25cf6-9120-4283-b972-0e5520d0000D")]
  81. [Interop.ComVisible(true)]
  82. #if !NETCF
  83. [Interop.ClassInterface(Interop.ClassInterfaceType.AutoDispatch)]
  84. #endif
  85. #endif
  86. sealed public class ZlibCodec
  87. {
  88. /// <summary>
  89. /// The buffer from which data is taken.
  90. /// </summary>
  91. public byte[] InputBuffer;
  92. /// <summary>
  93. /// An index into the InputBuffer array, indicating where to start reading.
  94. /// </summary>
  95. public int NextIn;
  96. /// <summary>
  97. /// The number of bytes available in the InputBuffer, starting at NextIn.
  98. /// </summary>
  99. /// <remarks>
  100. /// Generally you should set this to InputBuffer.Length before the first Inflate() or Deflate() call.
  101. /// The class will update this number as calls to Inflate/Deflate are made.
  102. /// </remarks>
  103. public int AvailableBytesIn;
  104. /// <summary>
  105. /// Total number of bytes read so far, through all calls to Inflate()/Deflate().
  106. /// </summary>
  107. public long TotalBytesIn;
  108. /// <summary>
  109. /// Buffer to store output data.
  110. /// </summary>
  111. public byte[] OutputBuffer;
  112. /// <summary>
  113. /// An index into the OutputBuffer array, indicating where to start writing.
  114. /// </summary>
  115. public int NextOut;
  116. /// <summary>
  117. /// The number of bytes available in the OutputBuffer, starting at NextOut.
  118. /// </summary>
  119. /// <remarks>
  120. /// Generally you should set this to OutputBuffer.Length before the first Inflate() or Deflate() call.
  121. /// The class will update this number as calls to Inflate/Deflate are made.
  122. /// </remarks>
  123. public int AvailableBytesOut;
  124. /// <summary>
  125. /// Total number of bytes written to the output so far, through all calls to Inflate()/Deflate().
  126. /// </summary>
  127. public long TotalBytesOut;
  128. /// <summary>
  129. /// used for diagnostics, when something goes wrong!
  130. /// </summary>
  131. public System.String Message;
  132. internal DeflateManager dstate;
  133. internal InflateManager istate;
  134. internal uint _Adler32;
  135. /// <summary>
  136. /// The compression level to use in this codec. Useful only in compression mode.
  137. /// </summary>
  138. public CompressionLevel CompressLevel = CompressionLevel.Default;
  139. /// <summary>
  140. /// The number of Window Bits to use.
  141. /// </summary>
  142. /// <remarks>
  143. /// This gauges the size of the sliding window, and hence the
  144. /// compression effectiveness as well as memory consumption. It's best to just leave this
  145. /// setting alone if you don't know what it is. The maximum value is 15 bits, which implies
  146. /// a 32k window.
  147. /// </remarks>
  148. public int WindowBits = ZlibConstants.WindowBitsDefault;
  149. /// <summary>
  150. /// The compression strategy to use.
  151. /// </summary>
  152. /// <remarks>
  153. /// This is only effective in compression. The theory offered by ZLIB is that different
  154. /// strategies could potentially produce significant differences in compression behavior
  155. /// for different data sets. Unfortunately I don't have any good recommendations for how
  156. /// to set it differently. When I tested changing the strategy I got minimally different
  157. /// compression performance. It's best to leave this property alone if you don't have a
  158. /// good feel for it. Or, you may want to produce a test harness that runs through the
  159. /// different strategy options and evaluates them on different file types. If you do that,
  160. /// let me know your results.
  161. /// </remarks>
  162. public CompressionStrategy Strategy = CompressionStrategy.Default;
  163. /// <summary>
  164. /// The Adler32 checksum on the data transferred through the codec so far. You probably don't need to look at this.
  165. /// </summary>
  166. public int Adler32 { get { return (int)_Adler32; } }
  167. /// <summary>
  168. /// Create a ZlibCodec.
  169. /// </summary>
  170. /// <remarks>
  171. /// If you use this default constructor, you will later have to explicitly call
  172. /// InitializeInflate() or InitializeDeflate() before using the ZlibCodec to compress
  173. /// or decompress.
  174. /// </remarks>
  175. public ZlibCodec() { }
  176. /// <summary>
  177. /// Create a ZlibCodec that either compresses or decompresses.
  178. /// </summary>
  179. /// <param name="mode">
  180. /// Indicates whether the codec should compress (deflate) or decompress (inflate).
  181. /// </param>
  182. public ZlibCodec(CompressionMode mode)
  183. {
  184. if (mode == CompressionMode.Compress)
  185. {
  186. int rc = InitializeDeflate();
  187. if (rc != ZlibConstants.Z_OK) throw new ZlibException("Cannot initialize for deflate.");
  188. }
  189. else if (mode == CompressionMode.Decompress)
  190. {
  191. int rc = InitializeInflate();
  192. if (rc != ZlibConstants.Z_OK) throw new ZlibException("Cannot initialize for inflate.");
  193. }
  194. else throw new ZlibException("Invalid ZlibStreamFlavor.");
  195. }
  196. /// <summary>
  197. /// Initialize the inflation state.
  198. /// </summary>
  199. /// <remarks>
  200. /// It is not necessary to call this before using the ZlibCodec to inflate data;
  201. /// It is implicitly called when you call the constructor.
  202. /// </remarks>
  203. /// <returns>Z_OK if everything goes well.</returns>
  204. public int InitializeInflate()
  205. {
  206. return InitializeInflate(this.WindowBits);
  207. }
  208. /// <summary>
  209. /// Initialize the inflation state with an explicit flag to
  210. /// govern the handling of RFC1950 header bytes.
  211. /// </summary>
  212. ///
  213. /// <remarks>
  214. /// By default, the ZLIB header defined in <see
  215. /// href="http://www.ietf.org/rfc/rfc1950.txt">RFC 1950</see> is expected. If
  216. /// you want to read a zlib stream you should specify true for
  217. /// expectRfc1950Header. If you have a deflate stream, you will want to specify
  218. /// false. It is only necessary to invoke this initializer explicitly if you
  219. /// want to specify false.
  220. /// </remarks>
  221. ///
  222. /// <param name="expectRfc1950Header">whether to expect an RFC1950 header byte
  223. /// pair when reading the stream of data to be inflated.</param>
  224. ///
  225. /// <returns>Z_OK if everything goes well.</returns>
  226. public int InitializeInflate(bool expectRfc1950Header)
  227. {
  228. return InitializeInflate(this.WindowBits, expectRfc1950Header);
  229. }
  230. /// <summary>
  231. /// Initialize the ZlibCodec for inflation, with the specified number of window bits.
  232. /// </summary>
  233. /// <param name="windowBits">The number of window bits to use. If you need to ask what that is,
  234. /// then you shouldn't be calling this initializer.</param>
  235. /// <returns>Z_OK if all goes well.</returns>
  236. public int InitializeInflate(int windowBits)
  237. {
  238. this.WindowBits = windowBits;
  239. return InitializeInflate(windowBits, true);
  240. }
  241. /// <summary>
  242. /// Initialize the inflation state with an explicit flag to govern the handling of
  243. /// RFC1950 header bytes.
  244. /// </summary>
  245. ///
  246. /// <remarks>
  247. /// If you want to read a zlib stream you should specify true for
  248. /// expectRfc1950Header. In this case, the library will expect to find a ZLIB
  249. /// header, as defined in <see href="http://www.ietf.org/rfc/rfc1950.txt">RFC
  250. /// 1950</see>, in the compressed stream. If you will be reading a DEFLATE or
  251. /// GZIP stream, which does not have such a header, you will want to specify
  252. /// false.
  253. /// </remarks>
  254. ///
  255. /// <param name="expectRfc1950Header">whether to expect an RFC1950 header byte pair when reading
  256. /// the stream of data to be inflated.</param>
  257. /// <param name="windowBits">The number of window bits to use. If you need to ask what that is,
  258. /// then you shouldn't be calling this initializer.</param>
  259. /// <returns>Z_OK if everything goes well.</returns>
  260. public int InitializeInflate(int windowBits, bool expectRfc1950Header)
  261. {
  262. this.WindowBits = windowBits;
  263. if (dstate != null) throw new ZlibException("You may not call InitializeInflate() after calling InitializeDeflate().");
  264. istate = new InflateManager(expectRfc1950Header);
  265. return istate.Initialize(this, windowBits);
  266. }
  267. /// <summary>
  268. /// Inflate the data in the InputBuffer, placing the result in the OutputBuffer.
  269. /// </summary>
  270. /// <remarks>
  271. /// You must have set InputBuffer and OutputBuffer, NextIn and NextOut, and AvailableBytesIn and
  272. /// AvailableBytesOut before calling this method.
  273. /// </remarks>
  274. /// <example>
  275. /// <code>
  276. /// private void InflateBuffer()
  277. /// {
  278. /// int bufferSize = 1024;
  279. /// byte[] buffer = new byte[bufferSize];
  280. /// ZlibCodec decompressor = new ZlibCodec();
  281. ///
  282. /// Console.WriteLine("\n============================================");
  283. /// Console.WriteLine("Size of Buffer to Inflate: {0} bytes.", CompressedBytes.Length);
  284. /// MemoryStream ms = new MemoryStream(DecompressedBytes);
  285. ///
  286. /// int rc = decompressor.InitializeInflate();
  287. ///
  288. /// decompressor.InputBuffer = CompressedBytes;
  289. /// decompressor.NextIn = 0;
  290. /// decompressor.AvailableBytesIn = CompressedBytes.Length;
  291. ///
  292. /// decompressor.OutputBuffer = buffer;
  293. ///
  294. /// // pass 1: inflate
  295. /// do
  296. /// {
  297. /// decompressor.NextOut = 0;
  298. /// decompressor.AvailableBytesOut = buffer.Length;
  299. /// rc = decompressor.Inflate(FlushType.None);
  300. ///
  301. /// if (rc != ZlibConstants.Z_OK &amp;&amp; rc != ZlibConstants.Z_STREAM_END)
  302. /// throw new Exception("inflating: " + decompressor.Message);
  303. ///
  304. /// ms.Write(decompressor.OutputBuffer, 0, buffer.Length - decompressor.AvailableBytesOut);
  305. /// }
  306. /// while (decompressor.AvailableBytesIn &gt; 0 || decompressor.AvailableBytesOut == 0);
  307. ///
  308. /// // pass 2: finish and flush
  309. /// do
  310. /// {
  311. /// decompressor.NextOut = 0;
  312. /// decompressor.AvailableBytesOut = buffer.Length;
  313. /// rc = decompressor.Inflate(FlushType.Finish);
  314. ///
  315. /// if (rc != ZlibConstants.Z_STREAM_END &amp;&amp; rc != ZlibConstants.Z_OK)
  316. /// throw new Exception("inflating: " + decompressor.Message);
  317. ///
  318. /// if (buffer.Length - decompressor.AvailableBytesOut &gt; 0)
  319. /// ms.Write(buffer, 0, buffer.Length - decompressor.AvailableBytesOut);
  320. /// }
  321. /// while (decompressor.AvailableBytesIn &gt; 0 || decompressor.AvailableBytesOut == 0);
  322. ///
  323. /// decompressor.EndInflate();
  324. /// }
  325. ///
  326. /// </code>
  327. /// </example>
  328. /// <param name="flush">The flush to use when inflating.</param>
  329. /// <returns>Z_OK if everything goes well.</returns>
  330. public int Inflate(FlushType flush)
  331. {
  332. if (istate == null)
  333. throw new ZlibException("No Inflate State!");
  334. return istate.Inflate(flush);
  335. }
  336. /// <summary>
  337. /// Ends an inflation session.
  338. /// </summary>
  339. /// <remarks>
  340. /// Call this after successively calling Inflate(). This will cause all buffers to be flushed.
  341. /// After calling this you cannot call Inflate() without a intervening call to one of the
  342. /// InitializeInflate() overloads.
  343. /// </remarks>
  344. /// <returns>Z_OK if everything goes well.</returns>
  345. public int EndInflate()
  346. {
  347. if (istate == null)
  348. throw new ZlibException("No Inflate State!");
  349. int ret = istate.End();
  350. istate = null;
  351. return ret;
  352. }
  353. /// <summary>
  354. /// I don't know what this does!
  355. /// </summary>
  356. /// <returns>Z_OK if everything goes well.</returns>
  357. public int SyncInflate()
  358. {
  359. if (istate == null)
  360. throw new ZlibException("No Inflate State!");
  361. return istate.Sync();
  362. }
  363. /// <summary>
  364. /// Initialize the ZlibCodec for deflation operation.
  365. /// </summary>
  366. /// <remarks>
  367. /// The codec will use the MAX window bits and the default level of compression.
  368. /// </remarks>
  369. /// <example>
  370. /// <code>
  371. /// int bufferSize = 40000;
  372. /// byte[] CompressedBytes = new byte[bufferSize];
  373. /// byte[] DecompressedBytes = new byte[bufferSize];
  374. ///
  375. /// ZlibCodec compressor = new ZlibCodec();
  376. ///
  377. /// compressor.InitializeDeflate(CompressionLevel.Default);
  378. ///
  379. /// compressor.InputBuffer = System.Text.ASCIIEncoding.ASCII.GetBytes(TextToCompress);
  380. /// compressor.NextIn = 0;
  381. /// compressor.AvailableBytesIn = compressor.InputBuffer.Length;
  382. ///
  383. /// compressor.OutputBuffer = CompressedBytes;
  384. /// compressor.NextOut = 0;
  385. /// compressor.AvailableBytesOut = CompressedBytes.Length;
  386. ///
  387. /// while (compressor.TotalBytesIn != TextToCompress.Length &amp;&amp; compressor.TotalBytesOut &lt; bufferSize)
  388. /// {
  389. /// compressor.Deflate(FlushType.None);
  390. /// }
  391. ///
  392. /// while (true)
  393. /// {
  394. /// int rc= compressor.Deflate(FlushType.Finish);
  395. /// if (rc == ZlibConstants.Z_STREAM_END) break;
  396. /// }
  397. ///
  398. /// compressor.EndDeflate();
  399. ///
  400. /// </code>
  401. /// </example>
  402. /// <returns>Z_OK if all goes well. You generally don't need to check the return code.</returns>
  403. public int InitializeDeflate()
  404. {
  405. return _InternalInitializeDeflate(true);
  406. }
  407. /// <summary>
  408. /// Initialize the ZlibCodec for deflation operation, using the specified CompressionLevel.
  409. /// </summary>
  410. /// <remarks>
  411. /// The codec will use the maximum window bits (15) and the specified
  412. /// CompressionLevel. It will emit a ZLIB stream as it compresses.
  413. /// </remarks>
  414. /// <param name="level">The compression level for the codec.</param>
  415. /// <returns>Z_OK if all goes well.</returns>
  416. public int InitializeDeflate(CompressionLevel level)
  417. {
  418. this.CompressLevel = level;
  419. return _InternalInitializeDeflate(true);
  420. }
  421. /// <summary>
  422. /// Initialize the ZlibCodec for deflation operation, using the specified CompressionLevel,
  423. /// and the explicit flag governing whether to emit an RFC1950 header byte pair.
  424. /// </summary>
  425. /// <remarks>
  426. /// The codec will use the maximum window bits (15) and the specified CompressionLevel.
  427. /// If you want to generate a zlib stream, you should specify true for
  428. /// wantRfc1950Header. In this case, the library will emit a ZLIB
  429. /// header, as defined in <see href="http://www.ietf.org/rfc/rfc1950.txt">RFC
  430. /// 1950</see>, in the compressed stream.
  431. /// </remarks>
  432. /// <param name="level">The compression level for the codec.</param>
  433. /// <param name="wantRfc1950Header">whether to emit an initial RFC1950 byte pair in the compressed stream.</param>
  434. /// <returns>Z_OK if all goes well.</returns>
  435. public int InitializeDeflate(CompressionLevel level, bool wantRfc1950Header)
  436. {
  437. this.CompressLevel = level;
  438. return _InternalInitializeDeflate(wantRfc1950Header);
  439. }
  440. /// <summary>
  441. /// Initialize the ZlibCodec for deflation operation, using the specified CompressionLevel,
  442. /// and the specified number of window bits.
  443. /// </summary>
  444. /// <remarks>
  445. /// The codec will use the specified number of window bits and the specified CompressionLevel.
  446. /// </remarks>
  447. /// <param name="level">The compression level for the codec.</param>
  448. /// <param name="bits">the number of window bits to use. If you don't know what this means, don't use this method.</param>
  449. /// <returns>Z_OK if all goes well.</returns>
  450. public int InitializeDeflate(CompressionLevel level, int bits)
  451. {
  452. this.CompressLevel = level;
  453. this.WindowBits = bits;
  454. return _InternalInitializeDeflate(true);
  455. }
  456. /// <summary>
  457. /// Initialize the ZlibCodec for deflation operation, using the specified
  458. /// CompressionLevel, the specified number of window bits, and the explicit flag
  459. /// governing whether to emit an RFC1950 header byte pair.
  460. /// </summary>
  461. ///
  462. /// <param name="level">The compression level for the codec.</param>
  463. /// <param name="wantRfc1950Header">whether to emit an initial RFC1950 byte pair in the compressed stream.</param>
  464. /// <param name="bits">the number of window bits to use. If you don't know what this means, don't use this method.</param>
  465. /// <returns>Z_OK if all goes well.</returns>
  466. public int InitializeDeflate(CompressionLevel level, int bits, bool wantRfc1950Header)
  467. {
  468. this.CompressLevel = level;
  469. this.WindowBits = bits;
  470. return _InternalInitializeDeflate(wantRfc1950Header);
  471. }
  472. private int _InternalInitializeDeflate(bool wantRfc1950Header)
  473. {
  474. if (istate != null) throw new ZlibException("You may not call InitializeDeflate() after calling InitializeInflate().");
  475. dstate = new DeflateManager();
  476. dstate.WantRfc1950HeaderBytes = wantRfc1950Header;
  477. return dstate.Initialize(this, this.CompressLevel, this.WindowBits, this.Strategy);
  478. }
  479. /// <summary>
  480. /// Deflate one batch of data.
  481. /// </summary>
  482. /// <remarks>
  483. /// You must have set InputBuffer and OutputBuffer before calling this method.
  484. /// </remarks>
  485. /// <example>
  486. /// <code>
  487. /// private void DeflateBuffer(CompressionLevel level)
  488. /// {
  489. /// int bufferSize = 1024;
  490. /// byte[] buffer = new byte[bufferSize];
  491. /// ZlibCodec compressor = new ZlibCodec();
  492. ///
  493. /// Console.WriteLine("\n============================================");
  494. /// Console.WriteLine("Size of Buffer to Deflate: {0} bytes.", UncompressedBytes.Length);
  495. /// MemoryStream ms = new MemoryStream();
  496. ///
  497. /// int rc = compressor.InitializeDeflate(level);
  498. ///
  499. /// compressor.InputBuffer = UncompressedBytes;
  500. /// compressor.NextIn = 0;
  501. /// compressor.AvailableBytesIn = UncompressedBytes.Length;
  502. ///
  503. /// compressor.OutputBuffer = buffer;
  504. ///
  505. /// // pass 1: deflate
  506. /// do
  507. /// {
  508. /// compressor.NextOut = 0;
  509. /// compressor.AvailableBytesOut = buffer.Length;
  510. /// rc = compressor.Deflate(FlushType.None);
  511. ///
  512. /// if (rc != ZlibConstants.Z_OK &amp;&amp; rc != ZlibConstants.Z_STREAM_END)
  513. /// throw new Exception("deflating: " + compressor.Message);
  514. ///
  515. /// ms.Write(compressor.OutputBuffer, 0, buffer.Length - compressor.AvailableBytesOut);
  516. /// }
  517. /// while (compressor.AvailableBytesIn &gt; 0 || compressor.AvailableBytesOut == 0);
  518. ///
  519. /// // pass 2: finish and flush
  520. /// do
  521. /// {
  522. /// compressor.NextOut = 0;
  523. /// compressor.AvailableBytesOut = buffer.Length;
  524. /// rc = compressor.Deflate(FlushType.Finish);
  525. ///
  526. /// if (rc != ZlibConstants.Z_STREAM_END &amp;&amp; rc != ZlibConstants.Z_OK)
  527. /// throw new Exception("deflating: " + compressor.Message);
  528. ///
  529. /// if (buffer.Length - compressor.AvailableBytesOut &gt; 0)
  530. /// ms.Write(buffer, 0, buffer.Length - compressor.AvailableBytesOut);
  531. /// }
  532. /// while (compressor.AvailableBytesIn &gt; 0 || compressor.AvailableBytesOut == 0);
  533. ///
  534. /// compressor.EndDeflate();
  535. ///
  536. /// ms.Seek(0, SeekOrigin.Begin);
  537. /// CompressedBytes = new byte[compressor.TotalBytesOut];
  538. /// ms.Read(CompressedBytes, 0, CompressedBytes.Length);
  539. /// }
  540. /// </code>
  541. /// </example>
  542. /// <param name="flush">whether to flush all data as you deflate. Generally you will want to
  543. /// use Z_NO_FLUSH here, in a series of calls to Deflate(), and then call EndDeflate() to
  544. /// flush everything.
  545. /// </param>
  546. /// <returns>Z_OK if all goes well.</returns>
  547. public int Deflate(FlushType flush)
  548. {
  549. if (dstate == null)
  550. throw new ZlibException("No Deflate State!");
  551. return dstate.Deflate(flush);
  552. }
  553. /// <summary>
  554. /// End a deflation session.
  555. /// </summary>
  556. /// <remarks>
  557. /// Call this after making a series of one or more calls to Deflate(). All buffers are flushed.
  558. /// </remarks>
  559. /// <returns>Z_OK if all goes well.</returns>
  560. public int EndDeflate()
  561. {
  562. if (dstate == null)
  563. throw new ZlibException("No Deflate State!");
  564. // TODO: dinoch Tue, 03 Nov 2009 15:39 (test this)
  565. //int ret = dstate.End();
  566. dstate = null;
  567. return ZlibConstants.Z_OK; //ret;
  568. }
  569. /// <summary>
  570. /// Reset a codec for another deflation session.
  571. /// </summary>
  572. /// <remarks>
  573. /// Call this to reset the deflation state. For example if a thread is deflating
  574. /// non-consecutive blocks, you can call Reset() after the Deflate(Sync) of the first
  575. /// block and before the next Deflate(None) of the second block.
  576. /// </remarks>
  577. /// <returns>Z_OK if all goes well.</returns>
  578. public void ResetDeflate()
  579. {
  580. if (dstate == null)
  581. throw new ZlibException("No Deflate State!");
  582. dstate.Reset();
  583. }
  584. /// <summary>
  585. /// Set the CompressionStrategy and CompressionLevel for a deflation session.
  586. /// </summary>
  587. /// <param name="level">the level of compression to use.</param>
  588. /// <param name="strategy">the strategy to use for compression.</param>
  589. /// <returns>Z_OK if all goes well.</returns>
  590. public int SetDeflateParams(CompressionLevel level, CompressionStrategy strategy)
  591. {
  592. if (dstate == null)
  593. throw new ZlibException("No Deflate State!");
  594. return dstate.SetParams(level, strategy);
  595. }
  596. /// <summary>
  597. /// Set the dictionary to be used for either Inflation or Deflation.
  598. /// </summary>
  599. /// <param name="dictionary">The dictionary bytes to use.</param>
  600. /// <returns>Z_OK if all goes well.</returns>
  601. public int SetDictionary(byte[] dictionary)
  602. {
  603. if (istate != null)
  604. return istate.SetDictionary(dictionary);
  605. if (dstate != null)
  606. return dstate.SetDictionary(dictionary);
  607. throw new ZlibException("No Inflate or Deflate state!");
  608. }
  609. // Flush as much pending output as possible. All deflate() output goes
  610. // through this function so some applications may wish to modify it
  611. // to avoid allocating a large strm->next_out buffer and copying into it.
  612. // (See also read_buf()).
  613. internal void flush_pending()
  614. {
  615. int len = dstate.pendingCount;
  616. if (len > AvailableBytesOut)
  617. len = AvailableBytesOut;
  618. if (len == 0)
  619. return;
  620. if (dstate.pending.Length <= dstate.nextPending ||
  621. OutputBuffer.Length <= NextOut ||
  622. dstate.pending.Length < (dstate.nextPending + len) ||
  623. OutputBuffer.Length < (NextOut + len))
  624. {
  625. throw new ZlibException(String.Format("Invalid State. (pending.Length={0}, pendingCount={1})",
  626. dstate.pending.Length, dstate.pendingCount));
  627. }
  628. Array.Copy(dstate.pending, dstate.nextPending, OutputBuffer, NextOut, len);
  629. NextOut += len;
  630. dstate.nextPending += len;
  631. TotalBytesOut += len;
  632. AvailableBytesOut -= len;
  633. dstate.pendingCount -= len;
  634. if (dstate.pendingCount == 0)
  635. {
  636. dstate.nextPending = 0;
  637. }
  638. }
  639. // Read a new buffer from the current input stream, update the adler32
  640. // and total number of bytes read. All deflate() input goes through
  641. // this function so some applications may wish to modify it to avoid
  642. // allocating a large strm->next_in buffer and copying from it.
  643. // (See also flush_pending()).
  644. internal int read_buf(byte[] buf, int start, int size)
  645. {
  646. int len = AvailableBytesIn;
  647. if (len > size)
  648. len = size;
  649. if (len == 0)
  650. return 0;
  651. AvailableBytesIn -= len;
  652. if (dstate.WantRfc1950HeaderBytes)
  653. {
  654. _Adler32 = Adler.Adler32(_Adler32, InputBuffer, NextIn, len);
  655. }
  656. Array.Copy(InputBuffer, NextIn, buf, start, len);
  657. NextIn += len;
  658. TotalBytesIn += len;
  659. return len;
  660. }
  661. }
  662. }