1 /* $NetBSD: compress.c,v 1.3 2017/01/10 01:27:41 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: compress.c,v 1.3 2017/01/10 01:27:41 christos Exp $ */ 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 (dest, destLen, source, sourceLen, level) 25 Bytef *dest; 26 uLongf *destLen; 27 const Bytef *source; 28 uLong sourceLen; 29 int level; 30 { 31 z_stream stream; 32 int err; 33 const uInt max = (uInt)-1; 34 uLong left; 35 36 left = *destLen; 37 *destLen = 0; 38 39 stream.zalloc = (alloc_func)0; 40 stream.zfree = (free_func)0; 41 stream.opaque = (voidpf)0; 42 43 err = deflateInit(&stream, level); 44 if (err != Z_OK) return err; 45 46 stream.next_out = dest; 47 stream.avail_out = 0; 48 stream.next_in = __UNCONST(source); 49 stream.avail_in = 0; 50 51 do { 52 if (stream.avail_out == 0) { 53 stream.avail_out = left > (uLong)max ? max : (uInt)left; 54 left -= stream.avail_out; 55 } 56 if (stream.avail_in == 0) { 57 stream.avail_in = sourceLen > (uLong)max ? max : (uInt)sourceLen; 58 sourceLen -= stream.avail_in; 59 } 60 err = deflate(&stream, sourceLen ? Z_NO_FLUSH : Z_FINISH); 61 } while (err == Z_OK); 62 63 *destLen = stream.total_out; 64 deflateEnd(&stream); 65 return err == Z_STREAM_END ? Z_OK : err; 66 } 67 68 /* =========================================================================== 69 */ 70 int ZEXPORT compress (dest, destLen, source, sourceLen) 71 Bytef *dest; 72 uLongf *destLen; 73 const Bytef *source; 74 uLong sourceLen; 75 { 76 return compress2(dest, destLen, source, sourceLen, Z_DEFAULT_COMPRESSION); 77 } 78 79 /* =========================================================================== 80 If the default memLevel or windowBits for deflateInit() is changed, then 81 this function needs to be updated. 82 */ 83 uLong ZEXPORT compressBound (sourceLen) 84 uLong sourceLen; 85 { 86 return sourceLen + (sourceLen >> 12) + (sourceLen >> 14) + 87 (sourceLen >> 25) + 13; 88 } 89