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