2 * UCW Library -- Fast Buffered Input on Limited File Descriptors
4 * (c) 2003--2004 Martin Mares <mj@ucw.cz>
6 * This software may be freely distributed and used according to the terms
7 * of the GNU Lesser General Public License.
11 #include "ucw/fastbuf.h"
17 int fd; /* File descriptor */
20 #define FB_LIMFD(f) ((struct fb_limfd *)(f)->is_fastbuf)
21 #define FB_BUFFER(f) (byte *)(FB_LIMFD(f) + 1)
24 bfl_refill(struct fastbuf *f)
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);
30 bthrow(f, "fb.read", "Error reading %s: %m", f->name);
31 f->bstop = f->buffer + l;
37 bfl_close(struct fastbuf *f)
43 bopen_limited_fd(int fd, uns buflen, uns limit)
45 struct fb_limfd *F = xmalloc(sizeof(struct fb_limfd) + buflen);
46 struct fastbuf *f = &F->fb;
49 f->buffer = (char *)(F+1);
50 f->bptr = f->bstop = f->buffer;
51 f->bufend = f->buffer + buflen;
52 f->name = "limited-fd";
55 f->refill = bfl_refill;
57 f->can_overwrite_buffer = 2;
63 int main(int UNUSED argc, char UNUSED **argv)
65 struct fastbuf *f = bopen_limited_fd(0, 3, 13);
66 struct fastbuf *o = bfdopen_shared(1, 16);
68 while ((c = bgetc(f)) >= 0)