2018-10-24 23:31:26 +11:00
|
|
|
#include "zlib.h"
|
|
|
|
#include <string>
|
|
|
|
#include <stdexcept>
|
|
|
|
#include <zlib/zlib.h>
|
|
|
|
#include <vector>
|
|
|
|
|
2020-02-10 14:05:04 +11:00
|
|
|
namespace xiv::utils::zlib
|
2018-10-24 23:31:26 +11:00
|
|
|
{
|
|
|
|
|
2020-02-10 14:05:04 +11:00
|
|
|
void compress( const std::vector< char >& in, std::vector< char >& out )
|
|
|
|
{
|
2018-10-24 23:31:26 +11:00
|
|
|
// Fetching upper bound for out size
|
2021-11-27 00:53:57 +01:00
|
|
|
auto out_size = compressBound( static_cast< uLong >( in.size() ) );
|
2020-02-10 14:05:04 +11:00
|
|
|
out.resize( out_size );
|
2018-10-24 23:31:26 +11:00
|
|
|
|
2021-11-27 00:53:57 +01:00
|
|
|
auto ret = compress2( reinterpret_cast< uint8_t* >( out.data() ), &out_size,
|
|
|
|
reinterpret_cast< const uint8_t* >( in.data() ), static_cast< uLong >( in.size() ), Z_BEST_COMPRESSION );
|
2018-10-24 23:31:26 +11:00
|
|
|
|
2020-02-10 14:05:04 +11:00
|
|
|
if( ret != Z_OK )
|
2018-10-24 23:31:26 +11:00
|
|
|
{
|
2020-02-10 14:05:04 +11:00
|
|
|
throw std::runtime_error( "Error at zlib uncompress: " + std::to_string( ret ) );
|
2018-10-24 23:31:26 +11:00
|
|
|
}
|
|
|
|
|
2020-02-10 14:05:04 +11:00
|
|
|
out.resize( out_size );
|
|
|
|
}
|
2018-10-24 23:31:26 +11:00
|
|
|
|
2021-11-27 00:53:57 +01:00
|
|
|
void no_header_decompress( uint8_t* in, size_t in_size, uint8_t* out, size_t out_size )
|
2020-02-10 14:05:04 +11:00
|
|
|
{
|
2018-10-24 23:31:26 +11:00
|
|
|
z_stream strm;
|
|
|
|
strm.zalloc = Z_NULL;
|
|
|
|
strm.zfree = Z_NULL;
|
|
|
|
strm.opaque = Z_NULL;
|
2021-11-27 00:53:57 +01:00
|
|
|
strm.avail_in = static_cast< uInt >( in_size );
|
2018-10-24 23:31:26 +11:00
|
|
|
strm.next_in = Z_NULL;
|
|
|
|
|
|
|
|
// Init with -15 because we do not have header in this compressed data
|
2020-02-10 14:05:04 +11:00
|
|
|
auto ret = inflateInit2( &strm, -15 );
|
|
|
|
if( ret != Z_OK )
|
2018-10-24 23:31:26 +11:00
|
|
|
{
|
2020-02-10 14:05:04 +11:00
|
|
|
throw std::runtime_error( "Error at zlib init: " + std::to_string( ret ) );
|
2018-10-24 23:31:26 +11:00
|
|
|
}
|
|
|
|
|
|
|
|
// Set pointers to the right addresses
|
|
|
|
strm.next_in = in;
|
2021-11-27 00:53:57 +01:00
|
|
|
strm.avail_out = static_cast< uInt >( out_size );
|
2018-10-24 23:31:26 +11:00
|
|
|
strm.next_out = out;
|
|
|
|
|
|
|
|
// Effectively decompress data
|
2020-02-10 14:05:04 +11:00
|
|
|
ret = inflate( &strm, Z_NO_FLUSH );
|
|
|
|
if( ret != Z_STREAM_END )
|
2018-10-24 23:31:26 +11:00
|
|
|
{
|
2020-02-10 14:05:04 +11:00
|
|
|
throw std::runtime_error( "Error at zlib inflate: " + std::to_string( ret ) );
|
2018-10-24 23:31:26 +11:00
|
|
|
}
|
|
|
|
|
|
|
|
// Clean up
|
2020-02-10 14:05:04 +11:00
|
|
|
inflateEnd( &strm );
|
|
|
|
}
|
2018-10-24 23:31:26 +11:00
|
|
|
|
|
|
|
}
|