Br 算法

本文介绍了如何使用Google开源的Brotli库在C++中实现数据的压缩和解压缩功能,包括compress_string和decompress_string函数的详细实现过程。
摘要由CSDN通过智能技术生成

基于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);

}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值