snappy压缩/解压库

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;
}

原文链接: https://www.cnblogs.com/HachikoT/p/13567012.html

欢迎关注

微信关注下方公众号,第一时间获取干货硬货;公众号内回复【pdf】免费获取数百本计算机经典书籍

    snappy压缩/解压库

原创文章受到原创版权保护。转载请注明出处:https://www.ccppcoding.com/archives/202017

非原创文章文中已经注明原地址,如有侵权,联系删除

关注公众号【高性能架构探索】,第一时间获取最新文章

转载文章受原作者版权保护。转载请注明原作者出处!

(0)
上一篇 2023年2月12日 下午9:01
下一篇 2023年2月12日 下午9:01

相关推荐