nn::nlib::ZlibOutputStream
とnn::nlib::ZlibInputStream
を利用して 圧縮されたデータをストリーミングで読み書きするサンプルです。
DATA_SIZE
バイトのデータを圧縮してそれを伸張しています。 DATA_SIZE
が大きい場合でも比較的少量のメモリで圧縮・伸張することができます。
const int DATA_SIZE = 10000000;
bool Compress(ReallocOutputStream::UniquePtrType* vec, size_t* n) {
ReallocOutputStream base_out;
{
ZlibOutputStream ostr;
if (0 != ostr.Init()) return false;
if (0 != ostr.SetStream(&base_out)) return false;
nlib_printf(
"compress %d bytes: [0, ... 255, 0, ... 255, ....]\n", DATA_SIZE);
for (int i = 0; i < DATA_SIZE; ++i) {
if (!ostr.Write(i % 256)) {
return false;
}
}
if (!ostr.Close()) return false;
if (ostr.GetErrorValue() != 0) return false;
}
if (!base_out.Flush()) return false;
*n = base_out.Release(vec);
return true;
}
bool UnCompress(const uint8_t* vec, size_t n) {
MemoryInputStream base_in(&vec[0], n);
{
ZlibInputStream istr;
if (0 != istr.Init()) return false;
if (0 != istr.SetStream(&base_in)) return false;
for (int i = 0; i < DATA_SIZE; ++i) {
int c = istr.Read();
if (c != i % 256) {
return false;
}
}
if (!istr.IsEos()) return false;
if (!istr.Close()) return false;
}
if (!base_in.Close()) return false;
return true;
}
bool SampleMain(int, char**) {
ReallocOutputStream::UniquePtrType vec;
size_t n;
return Compress(&vec, &n) && UnCompress(vec.get(), n);
}
NLIB_MAINFUNC