File indexing completed on 2024-04-14 03:46:45

0001 /* compress.c -- compress a memory buffer
0002  * Copyright (C) 1995-2005 Jean-loup Gailly.
0003  * For conditions of distribution and use, see copyright notice in zlib.h
0004  */
0005 
0006 /* @(#) $Id$ */
0007 
0008 #define ZLIB_INTERNAL
0009 #include "zlib.h"
0010 
0011 /* ===========================================================================
0012      Compresses the source buffer into the destination buffer. The level
0013    parameter has the same meaning as in deflateInit.  sourceLen is the byte
0014    length of the source buffer. Upon entry, destLen is the total size of the
0015    destination buffer, which must be at least 0.1% larger than sourceLen plus
0016    12 bytes. Upon exit, destLen is the actual size of the compressed buffer.
0017 
0018      compress2 returns Z_OK if success, Z_MEM_ERROR if there was not enough
0019    memory, Z_BUF_ERROR if there was not enough room in the output buffer,
0020    Z_STREAM_ERROR if the level parameter is invalid.
0021 */
0022 int ZEXPORT compress2 (dest, destLen, source, sourceLen, level)
0023     Bytef *dest;
0024     uLongf *destLen;
0025     const Bytef *source;
0026     uLong sourceLen;
0027     int level;
0028 {
0029     z_stream stream;
0030     int err;
0031 
0032     stream.next_in = (z_const Bytef *)source;
0033     stream.avail_in = (uInt)sourceLen;
0034 #ifdef MAXSEG_64K
0035     /* Check for source > 64K on 16-bit machine: */
0036     if ((uLong)stream.avail_in != sourceLen) return Z_BUF_ERROR;
0037 #endif
0038     stream.next_out = dest;
0039     stream.avail_out = (uInt)*destLen;
0040     if ((uLong)stream.avail_out != *destLen) return Z_BUF_ERROR;
0041 
0042     stream.zalloc = (alloc_func)0;
0043     stream.zfree = (free_func)0;
0044     stream.opaque = (voidpf)0;
0045 
0046     err = deflateInit(&stream, level);
0047     if (err != Z_OK) return err;
0048 
0049     err = deflate(&stream, Z_FINISH);
0050     if (err != Z_STREAM_END) {
0051         deflateEnd(&stream);
0052         return err == Z_OK ? Z_BUF_ERROR : err;
0053     }
0054     *destLen = stream.total_out;
0055 
0056     err = deflateEnd(&stream);
0057     return err;
0058 }
0059 
0060 /* ===========================================================================
0061  */
0062 int ZEXPORT compress (dest, destLen, source, sourceLen)
0063     Bytef *dest;
0064     uLongf *destLen;
0065     const Bytef *source;
0066     uLong sourceLen;
0067 {
0068     return compress2(dest, destLen, source, sourceLen, Z_DEFAULT_COMPRESSION);
0069 }
0070 
0071 /* ===========================================================================
0072      If the default memLevel or windowBits for deflateInit() is changed, then
0073    this function needs to be updated.
0074  */
0075 uLong ZEXPORT compressBound (sourceLen)
0076     uLong sourceLen;
0077 {
0078     return sourceLen + (sourceLen >> 12) + (sourceLen >> 14) +
0079            (sourceLen >> 25) + 13;
0080 }