Skip to content

Instantly share code, notes, and snippets.

@aniltv06
Created September 12, 2016 06:23
Show Gist options
  • Save aniltv06/4658d489e80975a1dd9f11b7627d2237 to your computer and use it in GitHub Desktop.
Save aniltv06/4658d489e80975a1dd9f11b7627d2237 to your computer and use it in GitHub Desktop.
Compress the passed chunk of data
@interface compressBytes : NSObject {
z_stream zStream;
}
- (NSData *)compressBytes:(Bytef *)bytes length:(NSUInteger)length error:(NSError **)err shouldFinish:(BOOL)shouldFinish;
@implementation compressBytes
- (NSData *)compressBytes:(Bytef *)bytes length:(NSUInteger)length error:(NSError **)err shouldFinish:(BOOL)shouldFinish
{
if (length == 0) return nil;
NSUInteger halfLength = length/2;
NSMutableData *outputData = [NSMutableData dataWithLength:length/2];
int status;
zStream.next_in = bytes;
zStream.avail_in = (unsigned int)length;
zStream.avail_out = 0;
NSUInteger bytesProcessedAlready = zStream.total_out;
while (zStream.avail_out == 0) {
if (zStream.total_out-bytesProcessedAlready >= [outputData length]) {
[outputData increaseLengthBy:halfLength];
}
zStream.next_out = (Bytef*)[outputData mutableBytes] + zStream.total_out-bytesProcessedAlready;
zStream.avail_out = (unsigned int)([outputData length] - (zStream.total_out-bytesProcessedAlready));
status = deflate(&zStream, shouldFinish ? Z_FINISH : Z_NO_FLUSH);
if (status == Z_STREAM_END) {
break;
} else if (status != Z_OK) {
if (err) {
*err = [[self class] deflateErrorWithCode:status];
}
return NO;
}
}
//length of data
[outputData setLength: zStream.total_out-bytesProcessedAlready];
return outputData;
}
@end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment