nlib
misc/usezlib/usezlib.cpp

This sample reads and writes streams of data compressed with nn::nlib::ZlibOutputStream and nn::nlib::ZlibInputStream.

DATA_SIZE bytes of data are compressed and then expanded. Even if DATA_SIZE is large, this process can compress and expand the data using a relatively small amount of memory.

const int DATA_SIZE = 10000000;
bool Compress(ReallocOutputStream::UniquePtrType* vec, size_t* n) {
ReallocOutputStream base_out;
base_out.Reserve(50000);
{
ZlibOutputStream ostr;
// Initializes ZlibOutputStream.
// You can customize the size of the internal buffers or etc. by ZlibOutputStreamSettings.
// If the size of the buffers is too small, ZlibOutputStream may invoke ENOBUFS(Z_BUF_ERROR).
if (0 != ostr.Init()) return false;
// Set the base stream and initializes z_stream.
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;
}
}
// Closes ZlibOutputStream and detaches the base stream(base_out).
// ostr.Close() does not close base_out.
if (!ostr.Close()) return false;
// Fails if an error occurs somewhere.
if (ostr.GetErrorValue() != 0) return false;
}
// Flushes the base stream.
if (!base_out.Flush()) return false;
nlib_printf("compressed into %" PRIuS " bytes\n", base_out.Pos());
*n = base_out.Release(vec);
return true;
}
bool UnCompress(const uint8_t* vec, size_t n) {
MemoryInputStream base_in(&vec[0], n);
{
ZlibInputStream istr;
// Initializes ZlibInputStream.
// You can customize the size of the internal buffers or etc. by ZlibInputStreamSettings.
// If the size of the buffers is too small, ZlibInputStream may invoke ENOBUFS(Z_BUF_ERROR).
if (0 != istr.Init()) return false;
nlib_printf("uncompress and veryfying ... \n");
// Set the base stream and initializes z_stream.
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;
// Closes ZlibInputStream and detaches the base stream(base_in).
// istr.Close() does not close base_in.
if (!istr.Close()) return false;
}
// Closes the base stream
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