2 * Sherlock Library -- Fast Buffered I/O on Files
4 * (c) 1997--2000 Martin Mares <mj@ucw.cz>
13 #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(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);
81 b->pos = b->fdpos = 0;
83 b->refill = bfd_refill;
91 bopen(byte *name, uns mode, uns buffer)
93 int fd = sh_open(name, mode, 0666);
95 die("Unable to %s file %s: %m",
96 (mode & O_CREAT) ? "create" : "open", name);
97 return bfdopen_internal(fd, buffer, name);
101 bfdopen(int fd, uns buffer)
105 sprintf(x, "fd%d", fd);
106 return bfdopen_internal(fd, buffer, x);
109 void bbcopy(struct fastbuf *f, struct fastbuf *t, uns l)
111 uns rf = f->bstop - f->bptr;
117 uns k = (rf <= l) ? rf : l;
118 bwrite(t, f->bptr, k);
122 while (l >= t->buflen)
125 if ((uns) read(f->fd, t->buffer, t->buflen) != t->buflen)
126 die("bbcopy: %s exhausted", f->name);
128 f->fdpos += t->buflen;
129 f->bstop = f->bptr = f->buffer;
135 uns k = t->bufend - t->bptr;
140 k = t->bufend - t->bptr;
144 bread(f, t->bptr, k);
152 int main(int argc, char **argv)
154 struct fastbuf *f, *t;
157 f = bopen("/etc/profile", O_RDONLY, 16);