]> git.notmuchmail.org Git - notmuch/blob - util/zlib-extra.c
Merge tag 'debian/0.25_rc0-2'
[notmuch] / util / zlib-extra.c
1 /* zlib-extra.c -  Extra or enhanced routines for compressed I/O.
2  *
3  * Copyright (c) 2014 David Bremner
4  *
5  * This program is free software: you can redistribute it and/or modify
6  * it under the terms of the GNU General Public License as published by
7  * the Free Software Foundation, either version 3 of the License, or
8  * (at your option) any later version.
9  *
10  * This program is distributed in the hope that it will be useful,
11  * but WITHOUT ANY WARRANTY; without even the implied warranty of
12  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
13  * GNU General Public License for more details.
14  *
15  * You should have received a copy of the GNU General Public License
16  * along with this program.  If not, see https://www.gnu.org/licenses/ .
17  *
18  * Author: David Bremner <david@tethera.net>
19  */
20
21 #include "zlib-extra.h"
22 #include <talloc.h>
23 #include <stdio.h>
24 #include <string.h>
25
26 /* mimic POSIX/glibc getline, but on a zlib gzFile stream, and using talloc */
27 util_status_t
28 gz_getline (void *talloc_ctx, char **bufptr, ssize_t *bytes_read, gzFile stream)
29 {
30     char *buf = *bufptr;
31     unsigned int len;
32     size_t offset = 0;
33
34     if (buf) {
35         len = talloc_array_length (buf);
36     } else {
37         /* same as getdelim from gnulib */
38         len = 120;
39         buf = talloc_array (talloc_ctx, char, len);
40         if (buf == NULL)
41             return UTIL_OUT_OF_MEMORY;
42     }
43
44     while (1) {
45         if (! gzgets (stream, buf + offset, len - offset)) {
46             /* Null indicates EOF or error */
47             int zlib_status = 0;
48             (void) gzerror (stream, &zlib_status);
49             switch (zlib_status) {
50             case Z_OK:
51                 /* no data read before EOF */
52                 if (offset == 0)
53                     return UTIL_EOF;
54                 else
55                     goto SUCCESS;
56             case Z_ERRNO:
57                 return UTIL_ERRNO;
58             default:
59                 return UTIL_GZERROR;
60             }
61         }
62
63         offset += strlen (buf + offset);
64
65         if (buf[offset - 1] == '\n')
66             goto SUCCESS;
67
68         len *= 2;
69         buf = talloc_realloc (talloc_ctx, buf, char, len);
70         if (buf == NULL)
71             return UTIL_OUT_OF_MEMORY;
72     }
73  SUCCESS:
74     *bufptr = buf;
75     *bytes_read = offset;
76     return UTIL_SUCCESS;
77 }
78
79 const char *gz_error_string (util_status_t status, gzFile file)
80 {
81     if (status == UTIL_GZERROR)
82         return gzerror (file, NULL);
83     else
84         return util_error_string (status);
85 }