unbzip2.c revision 1.1.2.2 1 1.1.2.2 grant /* $NetBSD: unbzip2.c,v 1.1.2.2 2004/03/31 09:09:20 grant Exp $ */
2 1.1 mrg
3 1.1 mrg /* This file is #included by gzip.c */
4 1.1 mrg
5 1.1.2.2 grant #define INBUFSIZE (64 * 1024)
6 1.1.2.2 grant #define OUTBUFSIZE (64 * 1024)
7 1.1.2.2 grant
8 1.1 mrg static off_t
9 1.1 mrg unbzip2(int in, int out)
10 1.1 mrg {
11 1.1.2.2 grant int n, ret, end_of_file;
12 1.1 mrg off_t bytes_out = 0;
13 1.1.2.2 grant bz_stream bzs;
14 1.1.2.2 grant static char *inbuf, *outbuf;
15 1.1 mrg
16 1.1.2.2 grant if (inbuf == NULL && (inbuf = malloc(INBUFSIZE)) == NULL)
17 1.1.2.2 grant maybe_err(1, "malloc");
18 1.1.2.2 grant if (outbuf == NULL && (outbuf = malloc(OUTBUFSIZE)) == NULL)
19 1.1.2.2 grant maybe_err(1, "malloc");
20 1.1.2.2 grant
21 1.1.2.2 grant bzs.bzalloc = NULL;
22 1.1.2.2 grant bzs.bzfree = NULL;
23 1.1.2.2 grant bzs.opaque = NULL;
24 1.1.2.2 grant
25 1.1.2.2 grant end_of_file = 0;
26 1.1.2.2 grant ret = BZ2_bzDecompressInit(&bzs, 0, 0);
27 1.1.2.2 grant if (ret != BZ_OK)
28 1.1.2.2 grant maybe_errx(1, "bzip2 init");
29 1.1.2.2 grant
30 1.1.2.2 grant bzs.avail_in = 0;
31 1.1.2.2 grant
32 1.1.2.2 grant while (ret != BZ_STREAM_END) {
33 1.1.2.2 grant if (bzs.avail_in == 0 && !end_of_file) {
34 1.1.2.2 grant n = read(in, inbuf, INBUFSIZE);
35 1.1.2.2 grant if (n < 0)
36 1.1.2.2 grant maybe_err(1, "read");
37 1.1.2.2 grant if (n == 0)
38 1.1.2.2 grant end_of_file = 1;
39 1.1.2.2 grant bzs.next_in = inbuf;
40 1.1.2.2 grant bzs.avail_in = n;
41 1.1.2.2 grant } else
42 1.1.2.2 grant n = 0;
43 1.1.2.2 grant
44 1.1.2.2 grant bzs.next_out = outbuf;
45 1.1.2.2 grant bzs.avail_out = OUTBUFSIZE;
46 1.1.2.2 grant ret = BZ2_bzDecompress(&bzs);
47 1.1.2.2 grant
48 1.1.2.2 grant switch (ret) {
49 1.1.2.2 grant case BZ_STREAM_END:
50 1.1.2.2 grant case BZ_OK:
51 1.1.2.2 grant if (ret == BZ_OK && end_of_file)
52 1.1.2.2 grant maybe_err(1, "read");
53 1.1.2.2 grant if (!tflag) {
54 1.1.2.2 grant n = write(out, outbuf, OUTBUFSIZE - bzs.avail_out);
55 1.1.2.2 grant if (n < 0)
56 1.1.2.2 grant maybe_err(1, "write");
57 1.1.2.2 grant }
58 1.1.2.2 grant bytes_out += n;
59 1.1.2.2 grant break;
60 1.1.2.2 grant
61 1.1.2.2 grant case BZ_DATA_ERROR:
62 1.1.2.2 grant maybe_errx(1, "bzip2 data integrity error");
63 1.1.2.2 grant case BZ_DATA_ERROR_MAGIC:
64 1.1.2.2 grant maybe_errx(1, "bzip2 magic number error");
65 1.1.2.2 grant case BZ_MEM_ERROR:
66 1.1.2.2 grant maybe_errx(1, "bzip2 out of memory");
67 1.1.2.2 grant }
68 1.1.2.2 grant }
69 1.1 mrg
70 1.1.2.2 grant if (BZ2_bzDecompressEnd(&bzs) != BZ_OK)
71 1.1.2.2 grant return (0);
72 1.1 mrg
73 1.1 mrg return (bytes_out);
74 1.1 mrg }
75