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