GPAK  1.0.0
A general-purpose archive library

◆ _gpak_compressor_deflate()

GPAK_API uint32_t _gpak_compressor_deflate ( gpak_t _pak,
FILE *  _infile,
FILE *  _outfile 
)
Brief Description:\n Compresses the input file using the Deflate algorithm.

This function compresses the input file using the Deflate algorithm and writes the compressed data to the output file.

Parameters
_pakA pointer to the gpak_t.
_infileA pointer to the input FILE.
_outfileA pointer to the output FILE.
Returns
The number of bytes written to the output file.

Definition at line 97 of file gpak_compressors.c.

98 {
99  z_stream strm;
100  strm.zalloc = Z_NULL;
101  strm.zfree = Z_NULL;
102  strm.opaque = Z_NULL;
103 
104  char* _bufferIn = (char*)malloc(_DEFAULT_BLOCK_SIZE);
105  char* _bufferOut = (char*)malloc(_DEFAULT_BLOCK_SIZE);
106 
107  fseek(_infile, 0, SEEK_END);
108  size_t _total_size = ftell(_infile);
109  fseek(_infile, 0, SEEK_SET);
110 
111  int ret = deflateInit(&strm, _pak->header_.compression_level_);
112  if (ret != Z_OK)
113  return _gpak_make_error(_pak, GPAK_ERROR_DEFLATE_INIT);
114 
115  uint32_t _crc32 = crc32(0L, Z_NULL, 0);
116 
117  int flush;
118  unsigned have;
119  size_t _total_readed = 0ull;
120  do
121  {
122  strm.avail_in = _freadb(_bufferIn, 1ull, _DEFAULT_BLOCK_SIZE, _infile);
123  _total_readed += strm.avail_in;
124  _crc32 = crc32(_crc32, _bufferIn, strm.avail_in);
125  _gpak_pass_progress(_pak, _total_readed, _total_size, GPAK_STAGE_COMPRESSION);
126 
127  if (ferror(_infile))
128  {
129  _gpak_make_error(_pak, GPAK_ERROR_READ);
130  goto end;
131  }
132 
133  flush = feof(_infile) ? Z_FINISH : Z_NO_FLUSH;
134  strm.next_in = _bufferIn;
135 
136  do
137  {
138  strm.avail_out = _DEFAULT_BLOCK_SIZE;
139  strm.next_out = _bufferOut;
140  ret = deflate(&strm, flush);
141  assert(ret != Z_STREAM_ERROR);
142 
143  have = _DEFAULT_BLOCK_SIZE - strm.avail_out;
144  if (_fwriteb(_bufferOut, 1ull, have, _outfile) != have || ferror(_outfile))
145  {
146  _gpak_make_error(_pak, GPAK_ERROR_WRITE);
147  goto end;
148  }
149  } while (strm.avail_out == 0);
150  assert(strm.avail_in == 0);
151 
152  } while (flush != Z_FINISH);
153 
154 end:
155  deflateEnd(&strm);
156  free(_bufferIn);
157  free(_bufferOut);
158 
159  return _crc32;
160 }
@ GPAK_ERROR_WRITE
Definition: gpak_data.h:161
@ GPAK_ERROR_READ
Definition: gpak_data.h:162
@ GPAK_ERROR_DEFLATE_INIT
Definition: gpak_data.h:166
@ GPAK_STAGE_COMPRESSION
Definition: gpak_data.h:226
char compression_level_
Definition: gpak_data.h:114
pak_header_t header_
Definition: gpak_data.h:258