Source/zlib_helper.cpp
//This is the preferred method of Compressing data.
//It does not assume to much, and gives plents of options.
This is the preferred method of Compressing data.
It does not assume to much, and gives plents of options.
This is the preferred method of Compressing data . It does not assume to much and gives plents of options .
zlib::vector zlib::Compress(const char* data, size_t size, int type)
{
	z_stream strm{};
	memset(&strm, 0, sizeof(strm));
	strm.zalloc = Z_NULL;
	strm.zfree = Z_NULL;
	strm.opaque = Z_NULL;
	switch (type)
	{
	case zlib::ZLIB:
		type = 15;
		break;
	case zlib::GZIP:
		type = 31;
		break;
	default:
		type = 15;
		break;
	}
	if (deflateInit2(&strm, Z_DEFAULT_COMPRESSION, Z_DEFLATED, type, 9, Z_DEFAULT_STRATEGY) != Z_OK)
	{
		throw std::runtime_error("deflateInit2 failed.");
	}
	strm.next_in = reinterpret_cast<Bytef*>(const_cast<char*>(data));
	strm.avail_in = size;
	int ret;
	std::unique_ptr<std::byte[]> outbuffer = std::make_unique<std::byte[]>(zlib::CHUNK_SIZE);
	std::vector<std::byte> result;
	do {
		strm.next_out = reinterpret_cast<Bytef*>(&outbuffer[0]);
		strm.avail_out = zlib::CHUNK_SIZE;
		ret = deflate(&strm, Z_FINISH);
		if (result.size() < strm.total_out)
		{
			int write_size = strm.total_out - result.size();
			result.insert(result.end(), &outbuffer[0], &outbuffer[write_size]);
		}
	} while (ret == Z_OK);
	deflateEnd(&strm);
	if (ret != Z_STREAM_END) {
		throw std::runtime_error("Failed at end or something.");
	}
	return result;
}
zlib :: vector zlib :: Compress ( const char * data , size_t size , int type ) { z_stream strm { } ; memset ( & strm , 0 , sizeof ( strm ) ) ; strm . zalloc = Z_NULL ; strm . zfree = Z_NULL ; strm . opaque = Z_NULL ; switch ( type ) { case zlib :: ZLIB : type = 15 ; break ; case zlib :: GZIP : type = 31 ; break ; default : type = 15 ; break ; } if ( deflateInit2 ( & strm , Z_DEFAULT_COMPRESSION , Z_DEFLATED , type , 9 , Z_DEFAULT_STRATEGY ) != Z_OK ) { throw std :: runtime_error ( " " ) ; } strm . next_in = reinterpret_cast < Bytef * > ( const_cast < char * > ( data ) ) ; strm . avail_in = size ; int ret ; std :: unique_ptr < std :: byte [ ] > outbuffer = std :: make_unique < std :: byte [ ] > ( zlib :: CHUNK_SIZE ) ; std :: vector < std :: byte > result ; do { strm . next_out = reinterpret_cast < Bytef * > ( & outbuffer [ 0 ] ) ; strm . avail_out = zlib :: CHUNK_SIZE ; ret = deflate ( & strm , Z_FINISH ) ; if ( result . size ( ) < strm . total_out ) { int write_size = strm . total_out - result . size ( ) ; result . insert ( result . end ( ) , & outbuffer [ 0 ] , & outbuffer [ write_size ] ) ; } } while ( ret == Z_OK ) ; deflateEnd ( & strm ) ; if ( ret != Z_STREAM_END ) { throw std :: runtime_error ( " " ) ; } return result ; }
This is the preferred method of Compressing data.
This is the preferred method of Compressing data .
//result.insert(result.end(), data.begin(), data.end());