1/* compress.c -- compress a memory buffer
2 * Copyright (C) 1995-2005, 2014, 2016 Jean-loup Gailly, Mark Adler
3 * For conditions of distribution and use, see copyright notice in zlib.h
4 */
5
6/* @(#) $Id$ */
7
8#define ZLIB_INTERNAL
9#include "zbuild.h"
10#if defined(ZLIB_COMPAT)
11# include "zlib.h"
12#else
13# include "zlib-ng.h"
14#endif
15
16/* ===========================================================================
17 Compresses the source buffer into the destination buffer. The level
18 parameter has the same meaning as in deflateInit. sourceLen is the byte
19 length of the source buffer. Upon entry, destLen is the total size of the
20 destination buffer, which must be at least 0.1% larger than sourceLen plus
21 12 bytes. Upon exit, destLen is the actual size of the compressed buffer.
22
23 compress2 returns Z_OK if success, Z_MEM_ERROR if there was not enough
24 memory, Z_BUF_ERROR if there was not enough room in the output buffer,
25 Z_STREAM_ERROR if the level parameter is invalid.
26*/
27int ZEXPORT PREFIX(compress2)(unsigned char *dest, z_size_t *destLen, const unsigned char *source,
28 z_size_t sourceLen, int level) {
29 PREFIX3(stream) stream;
30 int err;
31 const unsigned int max = (unsigned int)-1;
32 z_size_t left;
33
34 left = *destLen;
35 *destLen = 0;
36
37 stream.zalloc = NULL;
38 stream.zfree = NULL;
39 stream.opaque = NULL;
40
41 err = PREFIX(deflateInit)(&stream, level);
42 if (err != Z_OK)
43 return err;
44
45 stream.next_out = dest;
46 stream.avail_out = 0;
47 stream.next_in = (const unsigned char *)source;
48 stream.avail_in = 0;
49
50 do {
51 if (stream.avail_out == 0) {
52 stream.avail_out = left > (unsigned long)max ? max : (unsigned int)left;
53 left -= stream.avail_out;
54 }
55 if (stream.avail_in == 0) {
56 stream.avail_in = sourceLen > (unsigned long)max ? max : (unsigned int)sourceLen;
57 sourceLen -= stream.avail_in;
58 }
59 err = PREFIX(deflate)(&stream, sourceLen ? Z_NO_FLUSH : Z_FINISH);
60 } while (err == Z_OK);
61
62 *destLen = (z_size_t)stream.total_out;
63 PREFIX(deflateEnd)(&stream);
64 return err == Z_STREAM_END ? Z_OK : err;
65}
66
67/* ===========================================================================
68 */
69int ZEXPORT PREFIX(compress)(unsigned char *dest, z_size_t *destLen, const unsigned char *source, z_size_t sourceLen) {
70 return PREFIX(compress2)(dest, destLen, source, sourceLen, Z_DEFAULT_COMPRESSION);
71}
72
73/* ===========================================================================
74 If the default memLevel or windowBits for deflateInit() is changed, then
75 this function needs to be updated.
76 */
77z_size_t ZEXPORT PREFIX(compressBound)(z_size_t sourceLen) {
78 return sourceLen + (sourceLen >> 12) + (sourceLen >> 14) + (sourceLen >> 25) + 13;
79}
80