1. 程式人生 > >使用 redis 中的 lzf 壓縮演算法

使用 redis 中的 lzf 壓縮演算法

lzfP.h:對 lzf.h 和 lzfP.h 的合併
lzfP.cpp:對 lzf_c.c 和 lzf_d.c 的合併

lzf.h:https://github.com/huangz1990/redis-3.0-annotated/blob/unstable/src/lzf.h
lzfP.h:https://github.com/huangz1990/redis-3.0-annotated/blob/unstable/src/lzfP.h
lzf_c.c:https://github.com/huangz1990/redis-3.0-annotated/blob/unstable/src/lzf_c.h
lzf_d.c:https://github.com/huangz1990/redis-3.0-annotated/blob/unstable/src/lzf_d.h

#include <iostream>
#include <string>
#include "lzfP.h"
using namespace std;

int main() 
{
	string value = "hello world hello world hello world hello world"; 
	size_t len = value.size();  // 字串未壓縮前的長度
	cout << "壓縮前:val = " << value << endl;
	cout << "壓縮前:len = " << len << endl << endl;

	// -------------------壓縮---------------------------------
	size_t comprlen;  // 壓縮後的長度
	size_t outlen;    // 輸出快取的最大長度
	unsigned char byte;
	int n, nwritten = 0;
	void *out;
	
	/* We require at least four bytes compression for this to be worth it */
	if (len <= 4) 
	{
		cout << "len <= 4" << endl;
		return 0;
	}
	
	outlen = len-4;
	
	if ((out = malloc(outlen+1)) == NULL) 
	{
		cout << "out = malloc(outlen+1)" << endl;
		return 0;
	}
	
	comprlen = lzf_compress(value.data(), len, out, outlen);  
	
	if (comprlen == 0) 
	{
		cout << "outlen == " << outlen << endl;
		cout << "comprlen == 0" << endl;
        		free(out);
        		return 0;
	}

	cout << "壓縮後:val = " << out << endl;
	cout << "壓縮後:len = " << comprlen << endl << endl;
	
	// -------------------解壓縮---------------------------------
	char  *val = NULL;

   	 // 字串空間
    	if ((val = (char*)malloc(len)) == NULL) 
	{
		cout << "lzf_decompress" << endl;
		return 0;
	}

   	 // 解壓,得出字串
   	 if (lzf_decompress(out, comprlen, val, len) == 0) 
	{
		cout << "lzf_decompress" << endl;
		return 0;
	}

	cout << "解壓後:val = " << val << endl;
	cout << "解壓後:len = " << len << endl;

   	 free(out);
	free(val);
	
	getchar();
	getchar();
	getchar();
	getchar();
   	return 0;
}

在這裡插入圖片描述