Skip to content

Instantly share code, notes, and snippets.

@CodaFi
Last active December 10, 2015 23:08
Show Gist options
  • Save CodaFi/4507650 to your computer and use it in GitHub Desktop.
Save CodaFi/4507650 to your computer and use it in GitHub Desktop.
- (NSData*)dataBySnappyCompression {
size_t compressedLen = snappy_max_compressed_length(self.length);
NSMutableData *result = [NSMutableData dataWithLength:(snappy_max_compressed_length(compressedLen + 0x4))];
snappy_status opCode = snappy_compress([self bytes], [self length], [result mutableBytes], &compressedLen);
if (opCode != SNAPPY_OK) {
LEPLog(@"Failed snappy compress: tried to compress %lu bytes", result.length);
NSAssert(nil, @"Failed Snappy compress");
result = nil;
} else {
[result setLength:compressedLen + 4];
}
return result;
}
- (NSData*)dataBySnappyUncompression {
NSMutableData *result = nil;
if (self.length < 4) {
return [self dataByGZipInflation];
}
if (self.bytes != NULL) {
size_t uncompress_result = 0;
snappy_status opCode = snappy_uncompressed_length(self.bytes, self.length + 0xffffffffffffc, &uncompress_result);
if (opCode == SNAPPY_OK) {
result = [NSMutableData dataWithLength:uncompress_result];
opCode = snappy_uncompress(self.bytes, (self.length + 0xffffffffffffc), [result mutableBytes], &uncompress_result);
if (opCode == SNAPPY_OK) {
[result setLength:uncompress_result];
return result;
}
}
}
NSLog(@"Failed snappy de-compress: tried to de-compress %lu bytes", self.length);
NSAssert(nil, @"Failed Snappy de-compress");
result = nil;
return result;
}
@CodaFi
Copy link
Author

CodaFi commented Jan 11, 2013

My apologies for the weird 0xffffffffffffc, but Snappy complained about a small buffer without it (may as well feed the thing all the memory it wants).

@avaidyam
Copy link

Wow! Nifty!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment