nlib
misc/usezlib/usezlib.cpp

nn::nlib::ZlibOutputStreamnn::nlib::ZlibInputStreamを利用して 圧縮されたデータをストリーミングで読み書きするサンプルです。

DATA_SIZEバイトのデータを圧縮してそれを伸張しています。 DATA_SIZEが大きい場合でも比較的少量のメモリで圧縮・伸張することができます。

/*---------------------------------------------------------------------------*
Project: CrossRoad
Copyright (C)2012-2016 Nintendo. All rights reserved.
These coded instructions, statements, and computer programs contain
proprietary information of Nintendo of America Inc. and/or Nintendo
Company Ltd., and are protected by Federal copyright law. They may
not be disclosed to third parties or copied or duplicated in any form,
in whole or in part, without the prior written consent of Nintendo.
*---------------------------------------------------------------------------*/
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 (nlib_is_error(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 (nlib_is_error(ostr.Write(i % 256))) {
return false;
}
}
// Fails if an error occurs somewhere.
if (nlib_is_error(ostr)) return false;
// Closes ZlibOutputStream and detaches the base stream(base_out).
// ostr.Close() does not close base_out.
if (nlib_is_error(ostr.Close())) return false;
}
// Flushes the base stream.
if (nlib_is_error(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 (nlib_is_error(istr.Init())) return false;
nlib_printf("uncompress and veryfying ... \n");
// Set the base stream and initializes z_stream.
if (nlib_is_error(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 (nlib_is_error(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