]> mj.ucw.cz Git - libucw.git/blob - lib/fb-limfd.c
added buck2obj_realloc(), it is automatically called when needed
[libucw.git] / lib / fb-limfd.c
1 /*
2  *      Sherlock Library -- Fast Buffered Input on Limited File Descriptors
3  *
4  *      (c) 2003 Martin Mares <mj@ucw.cz>
5  *
6  *      This software may be freely distributed and used according to the terms
7  *      of the GNU Lesser General Public License.
8  */
9
10 #include "lib/lib.h"
11 #include "lib/fastbuf.h"
12
13 #include <stdlib.h>
14 #include <unistd.h>
15
16 struct fb_limfd {
17   struct fastbuf fb;
18   int fd;                               /* File descriptor */
19   int limit;
20 };
21 #define FB_LIMFD(f) ((struct fb_limfd *)(f)->is_fastbuf)
22
23 static int
24 bfl_refill(struct fastbuf *f)
25 {
26   int max = MIN(FB_LIMFD(f)->limit - f->pos, f->bufend - f->buffer);
27   int l = read(FB_LIMFD(f)->fd, f->buffer, max);
28   if (l < 0)
29     die("Error reading %s: %m", f->name);
30   f->bptr = f->buffer;
31   f->bstop = f->buffer + l;
32   f->pos += l;
33   return l;
34 }
35
36 static void
37 bfl_close(struct fastbuf *f)
38 {
39   xfree(f);
40 }
41
42 static int
43 bfl_config(struct fastbuf *f UNUSED, uns item, int value UNUSED)
44 {
45   switch (item)
46     {
47     case BCONFIG_CAN_OVERWRITE:
48       return 2;
49     default:
50       return -1;
51     }
52 }
53
54 struct fastbuf *
55 bopen_limited_fd(int fd, uns buflen, uns limit)
56 {
57   struct fb_limfd *F = xmalloc(sizeof(struct fb_limfd) + buflen);
58   struct fastbuf *f = &F->fb;
59
60   bzero(F, sizeof(*F));
61   f->buffer = (char *)(F+1);
62   f->bptr = f->bstop = f->buffer;
63   f->bufend = f->buffer + buflen;
64   f->name = "limited-fd";
65   F->fd = fd;
66   F->limit = limit;
67   f->refill = bfl_refill;
68   f->close = bfl_close;
69   f->config = bfl_config;
70   return f;
71 }
72
73 #ifdef TEST
74
75 int main(int argc, char **argv)
76 {
77   struct fastbuf *f = bopen_limited_fd(0, 3, 13);
78   struct fastbuf *o = bfdopen_shared(1, 16);
79   int c;
80   while ((c = bgetc(f)) >= 0)
81     bputc(o, c);
82   bclose(o);
83   bclose(f);
84   return 0;
85 }
86
87 #endif