You are viewing a plain text version of this content. The canonical link for it is here.
Posted to dev@lucenenet.apache.org by J C <ro...@hotmail.com> on 2006/05/12 02:36:05 UTC

Compression/Decompression Implementation

1. Download the #ziplib (SharpZipLib) from http://www.icsharpcode.net/
(its net 1.1 compliant)

2. FieldsWriter.cs

using ICSharpCode.SharpZipLib.Zip.Compression; //For compression

sealed class FieldsWriter
{
   ...

		private byte[] Compress(byte[] input)
		{
			Deflater compressor = new Deflater();
			compressor.SetLevel(Deflater.BEST_COMPRESSION);
			compressor.SetInput(input);
			compressor.Finish();

			/*
			* Create an expandable byte array to hold the compressed data.
			* You cannot use an array that's the same size as the orginal because
			* there is no guarantee that the compressed data will be smaller than
			* the uncompressed data.
			*/
			System.IO.MemoryStream bos = new System.IO.MemoryStream(input.Length);

			// Compress the data
			byte[] buf = new byte[1024];
			while (!compressor.IsFinished) {
				int count = compressor.Deflate(buf);
				bos.Write(buf, 0, count);
			}

			// Get the compressed data
			return bos.ToArray();
}

}

3. FieldsReader.cs

using ICSharpCode.SharpZipLib.Zip.Compression; //For decompression

public sealed class FieldsReader
{
  ...
		private byte[] Uncompress(byte[] input)
		{
			Inflater decompressor = new Inflater();
			decompressor.SetInput(input);
			// Create an expandable byte array to hold the decompressed data
			System.IO.MemoryStream bos = new System.IO.MemoryStream(input.Length);
			byte[] buf = new byte[1024];

			while (!decompressor.IsFinished) {
				try {
					int count = decompressor.Inflate(buf);
					bos.Write(buf, 0, count);
				}
				catch (Exception e) {
					// this will happen if the field is not compressed
					throw new System.IO.IOException("field data are in wrong format: " + 
e.ToString());
				}
			}

			return bos.ToArray();
}

}



Regards
Johnny Chow

_________________________________________________________________
Be the one of the first to try the NEW Windows Live Mail. 
http://ideas.live.com/programPage.aspx?versionId=5d21c51a-b161-4314-9b0e-4911fb2b2e6d