2015-02-23 127 views
1

我有一個std::vector<short>,並希望壓縮(並隨後解壓縮)與libzpaq從https://github.com/zpaq/zpaq/char* bufferC++壓縮libzpaq到char *緩衝區

但是我沒有看到頭文件中提到的ReaderWriter類的概念。我怎麼把我的std::vector得到壓縮buffer了?

目前我有類似下面的代碼。

#include <vector> 
#include <string> 
#include <stdio.h> 
#include "libzpaq.h" 

struct writer: public libzpaq::Writer { 

    void put(int c) { 

    } 
}; 


struct reader: public libzpaq::Reader { 

    int get() { 

    } 
}; 


void libzpaq::error(const char* msg) { 
    fprintf(stderr, "Oops: %s\n", msg); 
    exit(1); 
} 

int main() { 


    short a[] = {2,5,8,2,4,2,2,2,6,5,4,3,4,2,2}; 
    std::vector<short> v(a, a+15); 

    char* buffer; 


    reader in; 
    writer out; 

    libzpaq::compress(&in, &out, "5"); 

} 

我wan't到矢量v壓縮爲buffer。 (後來再次解壓縮。)

但我不明白ReaderWriter結構/類的概念。

的實況(http://mattmahoney.net/dc/libzpaq.3.html)也提到的功能爲ReaderWritervirtual int read(char* buf, int n)virtual void write(const char* buf, int n)。我怎麼能投到char* buf結束得到這個bufn字節的長度?

編輯1:我發現在libzpaq.h線1376。可是事情一類StringBuffer

buffer = reinterpret_cast<char*> (&v[0]); 
length = sizeof(short)*v.size(); 


libzpaq::StringBuffer inString, outString; 

inString.read(buffer, length); 

libzpaq::compress(&inString, &outString, "5"); 

std::cout << "size outstring: " << outString.size() << std::endl; 
std::cout << "size instring: " << inString.size() << std::endl; 

總是給我

size outstring: 0 
size instring: 0 

即使我嘗試用一​​個更大的矢量v一些thousend隨機元素。

回答

1

使用Reader您可以逐字節訪問要壓縮的數據。所以與std::vector<short>它看起來像這樣。

struct reader : public libzpaq::Reader { 
    reader(const std::vector<short>& v) : 
    m_v(v), 
    m_offset(0) { 

    } 
    int get() { 
     if (m_offset < m_v.size() * sizeof (short)) { 
      return *((char*) m_v.data() + m_offset++); 
     } else { 
      return -1; 
     } 
    } 
    int m_offset; 
    std::vector<short> m_v; 
}; 

Writer應該收集Reader的輸出數據。如果你想收集它在char陣列我可以推薦這樣做。

struct writer : public libzpaq::Writer { 
    void put(int c) { 
     m_buffer.push_back(c); 
    } 
    int size() { 
     m_buffer.size(); 
    } 
    void copy_to(char* dst) { 
     memcpy(dst, m_buffer.data(), m_buffer.size()); 
    } 
    std::vector<char> m_buffer; 
}; 

然後調用它:

writer w; 
reader r(v1); 

libzpaq::compress(&r, &w, "5"); 

char* buffer = new char[w.size()]; 
w.copy_to(buffer); 

如果你想使用StringBuffer,那麼你應該寫一些數據緩衝,前閱讀,那爲什麼它返回0請看例子:

char* buffer = reinterpret_cast<char*> (&v[0]); 
int length = sizeof (short)*v.size(); 

libzpaq::StringBuffer in, out1, out2; 

// fill buffer with source data 
in.write(buffer, length); 

// compress to out1 
libzpaq::compress(&in, &out1, "5"); 

// decompress out1 to out2 
libzpaq::decompress(&out1, &out2); 

// check result 
short* b = (short*)out2.data(); 

for(int i = 0; i < 15; ++i) { 
    std::cout << b[i] << std::endl; 
}