snappy壓縮/解壓庫
阿新 • • 發佈:2020-08-26
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; }