/* NSData+ZLib.m created by nat on Fri 23-Jul-1999 */
//
// $Id: NSData+ZLib.m,v 1.2 1999/07/26 12:46:00 nat Exp $
// ---------------------------
// $Log: NSData+ZLib.m,v $
// Revision 1.2  1999/07/26 12:46:00  nat
// added dataWithZLibCompressedBytes:decompressedLength:
//
// Revision 1.1  1999/07/23 18:03:57  nat
// zLib support, some images inlined
//
// Revision 1.1.1.1  1999/07/23 16:24:06  nat
// Merciful release
//
//
#import <Foundation/NSString.h>
#import <Foundation/NSException.h>
#import "NSData+ZLib.h"
#include <zlib.h>


@implementation NSData ( ZLib)


- (NSData *) compressedDataUsingZLib
{
   NSMutableData   *dst;
   uLongf          len;    

   len = [self length] + [self length] / 500 + 128;
   dst = [[[NSMutableData allocWithZone: [self zone]] initWithLength:len] autorelease];
   switch( compress( [dst mutableBytes], &len, [self bytes], [self length]))
   {
   case Z_MEM_ERROR :
      [NSException raise:NSMallocException
                  format:@"out of memory"];
      break;
      
   case Z_BUF_ERROR :
      return( nil);
   }
   if( len >= [self length])
      return( nil);
   [dst setLength:len];
   return( dst);
}


+ (NSData *) dataWithZLibCompressedBytes:(void *) buf
                      decompressedLength:(unsigned long) decompressedSize
{
   NSMutableData      *dst;
   uLongf             len;

   len = decompressedSize * 2 + 8192;
   dst = [[[NSMutableData allocWithZone:[self zone]] initWithLength:len] autorelease];
   switch( uncompress( [dst mutableBytes], &len, buf, decompressedSize))
   {
   case Z_DATA_ERROR :
      [NSException raise:NSGenericException
                  format:@"Incoming ZLib data %@ was corrupted", self];
      break;

   case Z_MEM_ERROR :
      [NSException raise:NSMallocException
                  format:@"out of memory in decompression"];
      break;

   case Z_BUF_ERROR :
       return( nil);
   }
   [dst setLength:len];
   return( dst);
}


- (NSData *) decompressedDataUsingZLib:(unsigned long) decompressedSize
{
   NSMutableData      *dst;
   uLongf             len;

   len = decompressedSize * 2 + 8192;
   dst = [[[NSMutableData allocWithZone:[self zone]] initWithLength:len] autorelease];
   switch( uncompress( [dst mutableBytes], &len, [self bytes], [self length]))
   {
   case Z_DATA_ERROR :
      [NSException raise:NSGenericException
                  format:@"Incoming ZLib data %@ was corrupted", self];
      break;
      
   case Z_MEM_ERROR :
      [NSException raise:NSMallocException
                  format:@"out of memory in decompression"];
      break;

   case Z_BUF_ERROR :
       return( nil);
   }
   [dst setLength:len];
   return( dst);
}


@end