uncompr.c revision 1.5 1 /* $NetBSD: uncompr.c,v 1.5 2024/09/22 19:12:27 christos Exp $ */
2
3 /* uncompr.c -- decompress a memory buffer
4 * Copyright (C) 1995-2003, 2010, 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 Decompresses the source buffer into the destination buffer. *sourceLen is
15 the byte length of the source buffer. Upon entry, *destLen is the total size
16 of the destination buffer, which must be large enough to hold the entire
17 uncompressed data. (The size of the uncompressed data must have been saved
18 previously by the compressor and transmitted to the decompressor by some
19 mechanism outside the scope of this compression library.) Upon exit,
20 *destLen is the size of the decompressed data and *sourceLen is the number
21 of source bytes consumed. Upon return, source + *sourceLen points to the
22 first unused input byte.
23
24 uncompress returns Z_OK if success, Z_MEM_ERROR if there was not enough
25 memory, Z_BUF_ERROR if there was not enough room in the output buffer, or
26 Z_DATA_ERROR if the input data was corrupted, including if the input data is
27 an incomplete zlib stream.
28 */
29 int ZEXPORT uncompress2(Bytef *dest, uLongf *destLen, const Bytef *source,
30 uLong *sourceLen) {
31 z_stream stream;
32 int err;
33 const uInt max = (uInt)-1;
34 uLong len, left;
35 Byte buf[1]; /* for detection of incomplete stream when *destLen == 0 */
36
37 len = *sourceLen;
38 if (*destLen) {
39 left = *destLen;
40 *destLen = 0;
41 }
42 else {
43 left = 1;
44 dest = buf;
45 }
46
47 stream.next_in = __UNCONST(source);
48 stream.avail_in = 0;
49 stream.zalloc = (alloc_func)0;
50 stream.zfree = (free_func)0;
51 stream.opaque = (voidpf)0;
52
53 err = inflateInit(&stream);
54 if (err != Z_OK) return err;
55
56 stream.next_out = dest;
57 stream.avail_out = 0;
58
59 do {
60 if (stream.avail_out == 0) {
61 stream.avail_out = left > (uLong)max ? max : (uInt)left;
62 left -= stream.avail_out;
63 }
64 if (stream.avail_in == 0) {
65 stream.avail_in = len > (uLong)max ? max : (uInt)len;
66 len -= stream.avail_in;
67 }
68 err = inflate(&stream, Z_NO_FLUSH);
69 } while (err == Z_OK);
70
71 *sourceLen -= len + stream.avail_in;
72 if (dest != buf)
73 *destLen = stream.total_out;
74 else if (stream.total_out && err == Z_BUF_ERROR)
75 left = 1;
76
77 inflateEnd(&stream);
78 return err == Z_STREAM_END ? Z_OK :
79 err == Z_NEED_DICT ? Z_DATA_ERROR :
80 err == Z_BUF_ERROR && left + stream.avail_out ? Z_DATA_ERROR :
81 err;
82 }
83
84 int ZEXPORT uncompress(Bytef *dest, uLongf *destLen, const Bytef *source,
85 uLong sourceLen) {
86 return uncompress2(dest, destLen, source, &sourceLen);
87 }
88