]> mj.ucw.cz Git - libucw.git/blob - ucw/fb-limfd.c
Logger: Fixed use of unitialized flags
[libucw.git] / ucw / fb-limfd.c
1 /*
2  *      UCW Library -- Fast Buffered Input on Limited File Descriptors
3  *
4  *      (c) 2003--2004 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 <ucw/lib.h>
11 #include <ucw/fastbuf.h>
12
13 #include <unistd.h>
14
15 struct fb_limfd {
16   struct fastbuf fb;
17   int fd;                               /* File descriptor */
18   int limit;
19 };
20 #define FB_LIMFD(f) ((struct fb_limfd *)(f))
21 #define FB_BUFFER(f) (byte *)(FB_LIMFD(f) + 1)
22
23 static int
24 bfl_refill(struct fastbuf *f)
25 {
26   f->bptr = f->buffer = FB_BUFFER(f);
27   int max = MIN(FB_LIMFD(f)->limit - f->pos, f->bufend - f->buffer);
28   int l = read(FB_LIMFD(f)->fd, f->buffer, max);
29   if (l < 0)
30     bthrow(f, "read", "Error reading %s: %m", f->name);
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 struct fastbuf *
43 bopen_limited_fd(int fd, uint buflen, uint limit)
44 {
45   struct fb_limfd *F = xmalloc(sizeof(struct fb_limfd) + buflen);
46   struct fastbuf *f = &F->fb;
47
48   bzero(F, sizeof(*F));
49   f->buffer = (char *)(F+1);
50   f->bptr = f->bstop = f->buffer;
51   f->bufend = f->buffer + buflen;
52   f->name = "limited-fd";
53   F->fd = fd;
54   F->limit = limit;
55   f->refill = bfl_refill;
56   f->close = bfl_close;
57   f->can_overwrite_buffer = 2;
58   return f;
59 }
60
61 #ifdef TEST
62
63 int main(int UNUSED argc, char UNUSED **argv)
64 {
65   struct fastbuf *f = bopen_limited_fd(0, 3, 13);
66   struct fastbuf *o = bfdopen_shared(1, 16);
67   int c;
68   while ((c = bgetc(f)) >= 0)
69     bputc(o, c);
70   bclose(o);
71   bclose(f);
72   return 0;
73 }
74
75 #endif