当前位置:   article > 正文

Br 算法

Br 算法

基于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 "";
	}
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36
  • 37
  • 38
  • 39
  • 40
  • 41
  • 42
  • 43
  • 44
  • 45
  • 46
  • 47
  • 48
  • 49
  • 50
  • 51
  • 52
  • 53
  • 54
  • 55
  • 56

使用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);

}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/繁依Fanyi0/article/detail/224336?site
推荐阅读
相关标签
  

闽ICP备14008679号