2 * Copyright (c) 2019 Stefan Sperling <stsp@openbsd.org>
4 * Permission to use, copy, modify, and distribute this software for any
5 * purpose with or without fee is hereby granted, provided that the above
6 * copyright notice and this permission notice appear in all copies.
8 * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
9 * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
10 * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
11 * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
12 * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
13 * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
14 * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
17 #include <sys/queue.h>
27 #include "got_error.h"
28 #include "got_object.h"
31 #include "got_lib_deflate.h"
34 #define MIN(_a,_b) ((_a) < (_b) ? (_a) : (_b))
37 const struct got_error *
38 got_deflate_init(struct got_deflate_buf *zb, uint8_t *outbuf, size_t bufsize)
40 const struct got_error *err = NULL;
43 memset(&zb->z, 0, sizeof(zb->z));
45 zb->z.zalloc = Z_NULL;
47 zerr = deflateInit(&zb->z, Z_DEFAULT_COMPRESSION);
50 return got_error_from_errno("deflateInit");
51 if (zerr == Z_MEM_ERROR) {
53 return got_error_from_errno("deflateInit");
55 return got_error(GOT_ERR_COMPRESSION);
58 zb->inlen = zb->outlen = bufsize;
60 zb->inbuf = calloc(1, zb->inlen);
61 if (zb->inbuf == NULL) {
62 err = got_error_from_errno("calloc");
68 zb->outbuf = calloc(1, zb->outlen);
69 if (zb->outbuf == NULL) {
70 err = got_error_from_errno("calloc");
73 zb->flags |= GOT_DEFLATE_F_OWN_OUTBUF;
83 const struct got_error *
84 got_deflate_read(struct got_deflate_buf *zb, FILE *f, size_t *outlenp)
86 size_t last_total_out = zb->z.total_out;
90 z->next_out = zb->outbuf;
91 z->avail_out = zb->outlen;
95 if (z->avail_in == 0) {
96 size_t n = fread(zb->inbuf, 1, zb->inlen, f);
99 return got_ferror(f, GOT_ERR_IO);
101 ret = deflate(z, Z_FINISH);
104 z->next_in = zb->inbuf;
107 ret = deflate(z, Z_NO_FLUSH);
108 } while (ret == Z_OK && z->avail_out > 0);
111 zb->flags |= GOT_DEFLATE_F_HAVE_MORE;
113 if (ret != Z_STREAM_END)
114 return got_error(GOT_ERR_COMPRESSION);
115 zb->flags &= ~GOT_DEFLATE_F_HAVE_MORE;
118 *outlenp = z->total_out - last_total_out;
123 got_deflate_end(struct got_deflate_buf *zb)
126 if (zb->flags & GOT_DEFLATE_F_OWN_OUTBUF)
131 const struct got_error *
132 got_deflate_to_file(size_t *outlen, FILE *infile, FILE *outfile)
134 const struct got_error *err;
136 struct got_deflate_buf zb;
138 err = got_deflate_init(&zb, NULL, GOT_DEFLATE_BUFSIZE);
145 err = got_deflate_read(&zb, infile, &avail);
150 n = fwrite(zb.outbuf, avail, 1, outfile);
152 err = got_ferror(outfile, GOT_ERR_IO);
157 } while (zb.flags & GOT_DEFLATE_F_HAVE_MORE);
162 got_deflate_end(&zb);