2 * Sherlock Library -- Fast Buffered I/O on Files
4 * (c) 1997--2000 Martin Mares <mj@ucw.cz>
8 #include "lib/fastbuf.h"
17 bfd_refill(struct fastbuf *f)
19 int l = read(f->fd, f->buffer, f->buflen);
22 die("Error reading %s: %m", f->name);
24 f->bstop = f->buffer + l;
31 bfd_spout(struct fastbuf *f)
33 int l = f->bptr - f->buffer;
38 int z = write(f->fd, c, l);
40 die("Error writing %s: %m", f->name);
50 bfd_seek(struct fastbuf *f, sh_off_t pos, int whence)
54 if (whence == SEEK_SET && pos == f->fdpos)
57 l = sh_seek(f->fd, pos, whence);
59 die("lseek on %s: %m", f->name);
60 f->fdpos = f->pos = l;
64 bfd_close(struct fastbuf *f)
69 static struct fastbuf *
70 bfdopen_internal(int fd, uns buflen, byte *name)
72 int namelen = strlen(name) + 1;
73 struct fastbuf *b = xmalloc_zero(sizeof(struct fastbuf) + buflen + namelen);
76 b->buffer = (char *)(b+1);
77 b->bptr = b->bstop = b->buffer;
78 b->bufend = b->buffer + buflen;
80 strcpy(b->name, name);
82 b->refill = bfd_refill;
90 bopen(byte *name, uns mode, uns buffer)
92 int fd = sh_open(name, mode, 0666);
94 die("Unable to %s file %s: %m",
95 (mode & O_CREAT) ? "create" : "open", name);
96 return bfdopen_internal(fd, buffer, name);
100 bfdopen(int fd, uns buffer)
104 sprintf(x, "fd%d", fd);
105 return bfdopen_internal(fd, buffer, x);
108 void bbcopy(struct fastbuf *f, struct fastbuf *t, uns l)
110 uns rf = f->bstop - f->bptr;
116 uns k = (rf <= l) ? rf : l;
117 bwrite(t, f->bptr, k);
121 while (l >= t->buflen)
124 if ((uns) read(f->fd, t->buffer, t->buflen) != t->buflen)
125 die("bbcopy: %s exhausted", f->name);
127 f->fdpos += t->buflen;
128 f->bstop = f->bptr = f->buffer;
134 uns k = t->bufend - t->bptr;
139 k = t->bufend - t->bptr;
143 bread(f, t->bptr, k);
151 int main(int argc, char **argv)
153 struct fastbuf *f, *t;
156 f = bopen("/etc/profile", O_RDONLY, 16);