chiark / gitweb /
9bcc808d9203041a68dab85db73ff180ced1dc3c
[disorder] / lib / hreader.c
1 /*
2  * This file is part of DisOrder
3  * Copyright (C) 2010 Richard Kettlewell
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 <http://www.gnu.org/licenses/>.
17  */
18 /** @file lib/hreader.c
19  * @brief Hands-off reader - read files without keeping them open
20  */
21 #include "hreader.h"
22 #include "mem.h"
23 #include <string.h>
24 #include <fcntl.h>
25
26 static int hreader_fill(struct hreader *h, off_t offset);
27
28 void hreader_init(const char *path, struct hreader *h) {
29   memset(h, 0, sizeof *h);
30   h->path = xstrdup(path);
31   h->bufsize = 65536;
32   h->buffer = xmalloc_noptr(h->bufsize);
33 }
34
35 int hreader_read(struct hreader *h, void *buffer, size_t n) {
36   int r = hreader_pread(h, buffer, n, h->read_offset);
37   if(r > 0)
38     h->read_offset += r;
39   return r;
40 }
41
42 int hreader_pread(struct hreader *h, void *buffer, size_t n, off_t offset) {
43   size_t bytes_read = 0;
44
45   while(bytes_read < n) {
46     // If the desired byte range is outside the file, fetch new contents
47     if(offset < h->buf_offset || offset >= h->buf_offset + (off_t)h->bytes) {
48       int r = hreader_fill(h, offset);
49       if(r < 0)
50         return -1;                      /* disaster! */
51       else if(r == 0)
52         break;                          /* end of file */
53     }
54     // Figure out how much we can read this time round
55     size_t left = h->bytes - (offset - h->buf_offset);
56     // Truncate the read if we don't want that much
57     if(left > (n - bytes_read))
58       left = n - bytes_read;
59     memcpy((char *)buffer + bytes_read,
60            h->buffer + (offset - h->buf_offset),
61            left);
62     offset += left;
63     bytes_read += left;
64   }
65   return bytes_read;
66 }
67
68 static int hreader_fill(struct hreader *h, off_t offset) {
69   int fd = open(h->path, O_RDONLY);
70   if(fd < 0)
71     return -1;
72   int n = pread(fd, h->buffer, h->bufsize, offset);
73   close(fd);
74   if(n < 0)
75     return -1;
76   h->buf_offset = offset;
77   h->bytes = n;
78   return n;
79 }
80
81 /*
82 Local Variables:
83 c-basic-offset:2
84 comment-column:40
85 fill-column:79
86 indent-tabs-mode:nil
87 End:
88 */