2 * Sherlock 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 "lib/fastbuf.h"
18 int fd; /* File descriptor */
21 #define FB_LIMFD(f) ((struct fb_limfd *)(f)->is_fastbuf)
22 #define FB_BUFFER(f) (byte *)(FB_LIMFD(f) + 1)
25 bfl_refill(struct fastbuf *f)
27 f->bptr = f->buffer = FB_BUFFER(f);
28 int max = MIN(FB_LIMFD(f)->limit - f->pos, f->bufend - f->buffer);
29 int l = read(FB_LIMFD(f)->fd, f->buffer, max);
31 die("Error reading %s: %m", f->name);
32 f->bstop = f->buffer + l;
38 bfl_close(struct fastbuf *f)
44 bopen_limited_fd(int fd, uns buflen, uns limit)
46 struct fb_limfd *F = xmalloc(sizeof(struct fb_limfd) + buflen);
47 struct fastbuf *f = &F->fb;
50 f->buffer = (char *)(F+1);
51 f->bptr = f->bstop = f->buffer;
52 f->bufend = f->buffer + buflen;
53 f->name = "limited-fd";
56 f->refill = bfl_refill;
58 f->can_overwrite_buffer = 2;
64 int main(int argc, char **argv)
66 struct fastbuf *f = bopen_limited_fd(0, 3, 13);
67 struct fastbuf *o = bfdopen_shared(1, 16);
69 while ((c = bgetc(f)) >= 0)