snappy
snappy是由google开发的压缩/解压C++库,注重压缩速度,压缩后文件大小比其它算法大一些
snappy在64位x86并且是小端的cpu上性能最佳
- 在Intel(R) Core(TM)2 2.4GHz中测试数据:
压缩速率:~200-500MB/s
解压速率:~400-800MB/s - 压缩比(压缩数据大小/原始数据大小):
对于HTML:~25%
对于普通文本(plain text):~50%
对于JPEG等已经压缩过的文件:~100%
压缩/解压demo
/**
* 压缩数据
* @param bs 输入的字节数组
* @return 经过压缩的数据
*/
Bytes SnappyCompress::compress(BytesConstRef bs) {
// 提前分配足够的空间
Bytes ret(snappy::MaxCompressedLength(bs.size()));
size_t compressedLen = 0;
// 进行压缩
snappy::RawCompress(
reinterpret_cast<const char*>(bs.data()),
bs.size(),
reinterpret_cast<char*>(ret.data()),
&compressedLen
);
// 调整为实际的压缩长度
ret.resize(compressedLen);
return ret;
}
/**
* 解压数据
* @param bs 经过压缩的字节数组
* @return 经过解压的数据
* @throw 输入的压缩数据损坏抛出CorruptedInput异常
*/
Bytes SnappyCompress::uncompress(BytesConstRef bs) {
// 解析出解压数据的长度(花费O(1)时间)
size_t uncompressedLen = 0;
bool status = snappy::GetUncompressedLength(
reinterpret_cast<const char*>(bs.data()),
bs.size(),
&uncompressedLen
);
if (!status) {
// 解析长度编码出错
throw CorruptedInput();
}
// 提前分配空间
Bytes ret(uncompressedLen);
// 进行解压
status = snappy::RawUncompress(
reinterpret_cast<const char*>(bs.data()),
bs.size(),
reinterpret_cast<char*>(ret.data())
);
if (!status) {
// 压缩数据损坏
throw CorruptedInput();
}
return ret;
}