/**
* GZip压缩数据
*
* @param aUnData 未压缩数据
*
* @return 已压缩数据
*/
+ (NSData *)toGZipCompressData:(NSData *)aUnData {
if (![aUnData isKindOfClass:[NSData class]]) {
return nil;
}
@try {
if (aUnData.length == 0 || [self isGzippedData:aUnData]) {
return aUnData;
}
z_stream stream;
stream.zalloc = Z_NULL;
stream.zfree = Z_NULL;
stream.opaque = Z_NULL;
stream.avail_in = (uint) aUnData.length;
stream.next_in = (Bytef *) (void *) aUnData.bytes;
stream.total_out = 0;
stream.avail_out = 0;
static const NSUInteger ChunkSize = 16384;
NSMutableData *output = nil;
if (deflateInit2(&stream, Z_DEFAULT_COMPRESSION, Z_DEFLATED, 31, 8, Z_DEFAULT_STRATEGY) == Z_OK) {
output = [NSMutableData dataWithLength:ChunkSize];
while (stream.avail_out == 0) {
if (stream.total_out >= output.length) {
output.length += ChunkSize;
}
stream.next_out = (uint8_t *) output.mutableBytes + stream.total_out;
stream.avail_out = (uInt)(output.length - stream.total_out);
deflate(&stream, Z_FINISH);
}
deflateEnd(&stream);
output.length = stream.total_out;
}
return output;
}
@catch (NSException *exception) {
NSLog(@"%@", exception);
return nil;
}
}
+ (BOOL)isGzippedData:(NSData *)aData {
const UInt8 *bytes = (const UInt8 *) aData.bytes;
return (aData.length >= 2 && bytes[0] == 0x1f && bytes[1] == 0x8b);
}
网友评论