t4301: fix broken &&-chains and add missing loop termination
[git/debian.git] / compat / zlib-uncompress2.c
blob77a1b08048463da25ba8d6b36031ccb7e8cce7b5
1 #include "git-compat-util.h"
3 #if ZLIB_VERNUM < 0x1290
4 /* taken from zlib's uncompr.c
6 commit cacf7f1d4e3d44d871b605da3b647f07d718623f
7 Author: Mark Adler <madler@alumni.caltech.edu>
8 Date: Sun Jan 15 09:18:46 2017 -0800
10 zlib 1.2.11
15 * Copyright (C) 1995-2003, 2010, 2014, 2016 Jean-loup Gailly, Mark Adler
16 * For conditions of distribution and use, see copyright notice in zlib.h
19 /* clang-format off */
21 /* ===========================================================================
22 Decompresses the source buffer into the destination buffer. *sourceLen is
23 the byte length of the source buffer. Upon entry, *destLen is the total size
24 of the destination buffer, which must be large enough to hold the entire
25 uncompressed data. (The size of the uncompressed data must have been saved
26 previously by the compressor and transmitted to the decompressor by some
27 mechanism outside the scope of this compression library.) Upon exit,
28 *destLen is the size of the decompressed data and *sourceLen is the number
29 of source bytes consumed. Upon return, source + *sourceLen points to the
30 first unused input byte.
32 uncompress returns Z_OK if success, Z_MEM_ERROR if there was not enough
33 memory, Z_BUF_ERROR if there was not enough room in the output buffer, or
34 Z_DATA_ERROR if the input data was corrupted, including if the input data is
35 an incomplete zlib stream.
37 int ZEXPORT uncompress2 (
38 Bytef *dest,
39 uLongf *destLen,
40 const Bytef *source,
41 uLong *sourceLen) {
42 z_stream stream;
43 int err;
44 const uInt max = (uInt)-1;
45 uLong len, left;
46 Byte buf[1]; /* for detection of incomplete stream when *destLen == 0 */
48 len = *sourceLen;
49 if (*destLen) {
50 left = *destLen;
51 *destLen = 0;
53 else {
54 left = 1;
55 dest = buf;
58 stream.next_in = (z_const Bytef *)source;
59 stream.avail_in = 0;
60 stream.zalloc = (alloc_func)0;
61 stream.zfree = (free_func)0;
62 stream.opaque = (voidpf)0;
64 err = inflateInit(&stream);
65 if (err != Z_OK) return err;
67 stream.next_out = dest;
68 stream.avail_out = 0;
70 do {
71 if (stream.avail_out == 0) {
72 stream.avail_out = left > (uLong)max ? max : (uInt)left;
73 left -= stream.avail_out;
75 if (stream.avail_in == 0) {
76 stream.avail_in = len > (uLong)max ? max : (uInt)len;
77 len -= stream.avail_in;
79 err = inflate(&stream, Z_NO_FLUSH);
80 } while (err == Z_OK);
82 *sourceLen -= len + stream.avail_in;
83 if (dest != buf)
84 *destLen = stream.total_out;
85 else if (stream.total_out && err == Z_BUF_ERROR)
86 left = 1;
88 inflateEnd(&stream);
89 return err == Z_STREAM_END ? Z_OK :
90 err == Z_NEED_DICT ? Z_DATA_ERROR :
91 err == Z_BUF_ERROR && left + stream.avail_out ? Z_DATA_ERROR :
92 err;
94 #else
95 static void *dummy_variable = &dummy_variable;
96 #endif