赞
踩
基于google的brotli开源,实现Br算法。
#include <brotli/encode.h> #include <brotli/decode.h> namespace br { /* compress unsigned char* content,if ok return non empty unsigned char * */ std::string compress_string(const std::string& content) { size_t encoded_size = BrotliEncoderMaxCompressedSize(content.size()); std::string compressed_data(encoded_size,0); BROTLI_BOOL result = BrotliEncoderCompress(BROTLI_DEFAULT_QUALITY, BROTLI_DECODER_PARAM_LARGE_WINDOW, BrotliEncoderMode::BROTLI_DEFAULT_MODE, content.size(), (uint8_t *)&content[0],&encoded_size,(uint8_t *)&compressed_data[0]); if (result != BROTLI_TRUE) { return ""; } compressed_data.resize(encoded_size); return compressed_data; } /* decompress unsigned char* content,if ok return non empty unsigned char* */ std::string decompress_string(const std::string& compressed_data) { BrotliDecoderState* pstate = BrotliDecoderCreateInstance(nullptr, nullptr, nullptr); if (pstate == nullptr) return ""; size_t available_in = compressed_data.size(), total_out = 0; const uint8_t *next_in = (const uint8_t*)&compressed_data[0]; std::string uncompress_buf(4096, 0), uncompress_data; BrotliDecoderResult result; do { uint8_t* next_out = (uint8_t*)&uncompress_buf[0]; size_t available_out = uncompress_buf.size(); size_t temp_total_out = total_out; result = BrotliDecoderDecompressStream(pstate, &available_in, &next_in, &available_out, &next_out, &total_out); if(result != BROTLI_DECODER_RESULT_ERROR) uncompress_data.insert(uncompress_data.end(), uncompress_buf.begin(), uncompress_buf.begin() + (total_out - temp_total_out)); } while (result == BROTLI_DECODER_RESULT_NEEDS_MORE_OUTPUT); BrotliDecoderDestroyInstance(pstate); pstate = nullptr; if(result == BROTLI_DECODER_RESULT_SUCCESS) return uncompress_data; return ""; } }
使用brotli git加密数据验证算法:
int main()
{
std::cout << "Hello World!\n";
std::string str_src = "empty";
std::string u8en = br::compress_string(str_src);
std::fstream f("F:\\project\\brotli-master\\tests\\testdata\\ukkonooa.compressed",std::fstream::in|std::fstream::binary);
std::string stru8;
std::getline(f, stru8);
std::string u8_src = br::decompress_string(stru8);
}
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。