2 // © Copyright Henrik Ravn 2004
4 // Use, modification and distribution are subject to the Boost Software License, Version 1.0.
5 // (See accompanying file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
9 using System
.Diagnostics
;
10 using System
.Runtime
.InteropServices
;
16 /// Implements a data compressor, using the deflate algorithm in the ZLib dll
18 public sealed class Deflater
: CodecBase
21 [DllImport("ZLIB1.dll", CallingConvention
=CallingConvention
.Cdecl
, CharSet
=CharSet
.Ansi
)]
22 private static extern int deflateInit_(ref ZStream sz
, int level
, string vs
, int size
);
24 [DllImport("ZLIB1.dll", CallingConvention
=CallingConvention
.Cdecl
)]
25 private static extern int deflate(ref ZStream sz
, int flush
);
27 [DllImport("ZLIB1.dll", CallingConvention
=CallingConvention
.Cdecl
)]
28 private static extern int deflateReset(ref ZStream sz
);
30 [DllImport("ZLIB1.dll", CallingConvention
=CallingConvention
.Cdecl
)]
31 private static extern int deflateEnd(ref ZStream sz
);
35 /// Constructs an new instance of the <c>Deflater</c>
37 /// <param name="level">The compression level to use for this <c>Deflater</c></param>
38 public Deflater(CompressLevel level
) : base()
40 int retval
= deflateInit_(ref _ztream
, (int)level
, Info
.Version
, Marshal
.SizeOf(_ztream
));
42 throw new ZLibException(retval
, "Could not initialize deflater");
48 /// Adds more data to the codec to be processed.
50 /// <param name="data">Byte array containing the data to be added to the codec</param>
51 /// <param name="offset">The index of the first byte to add from <c>data</c></param>
52 /// <param name="count">The number of bytes to add</param>
53 /// <remarks>Adding data may, or may not, raise the <c>DataAvailable</c> event</remarks>
54 public override void Add(byte[] data
, int offset
, int count
)
56 if (data
== null) throw new ArgumentNullException();
57 if (offset
< 0 || count
< 0) throw new ArgumentOutOfRangeException();
58 if ((offset
+count
) > data
.Length
) throw new ArgumentException();
61 int inputIndex
= offset
;
64 while (err
>= 0 && inputIndex
< total
)
66 copyInput(data
, inputIndex
, Math
.Min(total
- inputIndex
, kBufferSize
));
67 while (err
>= 0 && _ztream
.avail_in
> 0)
69 err
= deflate(ref _ztream
, (int)FlushTypes
.None
);
71 while (_ztream
.avail_out
== 0)
74 err
= deflate(ref _ztream
, (int)FlushTypes
.None
);
76 inputIndex
+= (int)_ztream
.total_in
;
79 setChecksum( _ztream
.adler
);
84 /// Finishes up any pending data that needs to be processed and handled.
86 public override void Finish()
91 err
= deflate(ref _ztream
, (int)FlushTypes
.Finish
);
95 setChecksum( _ztream
.adler
);
96 deflateReset(ref _ztream
);
101 /// Closes the internal zlib deflate stream
103 protected override void CleanUp() { deflateEnd(ref _ztream); }