当我尝试解压缩大小大于 2048 的数据时,zlib 解压缩调用返回 Z_OK。因此,为了澄清如果我解压缩大小为 2980 的数据,它将解压缩到 2048(两个循环),然后返回 Z_OK。我错过了什么?
字节是一个向量< unsigned char >;
Bytes uncompressIt( const Bytes& data )
{
size_t buffer_length = 1024;
Byte* buffer = nullptr;
int status = 0;
do
{
buffer = ( Byte* ) calloc( buffer_length + 1, sizeof( Byte ) );
int status = uncompress( buffer, &buffer_length, &data[ 0 ], data.size( ) );
if ( status == Z_OK )
{
break;
}
else if ( status == Z_MEM_ERROR )
{
throw runtime_error( "GZip decompress ran out of memory." );
}
else if ( status == Z_DATA_ERROR )
{
throw runtime_error( "GZip decompress input data was corrupted or incomplete." );
}
else //if ( status == Z_BUF_ERROR )
{
free( buffer );
buffer_length *= 2;
}
} while ( status == Z_BUF_ERROR ); //then the output buffer wasn't large enough
Bytes result;
for( size_t index = 0; index != buffer_length; index++ )
{
result.push_back( buffer[ index ] );
}
return result;
}
编辑:
感谢@Michael 赶上 realloc。我一直在搞砸实施并错过了它;在发布之前仍然没有任何借口。