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)
67 if (f->is_temp_file && unlink(f->name) < 0)
68 die("unlink(%s): %m", f->name);
71 static struct fastbuf *
72 bfdopen_internal(int fd, uns buflen, byte *name)
74 int namelen = strlen(name) + 1;
75 struct fastbuf *b = xmalloc_zero(sizeof(struct fastbuf) + buflen + namelen);
78 b->buffer = (char *)(b+1);
79 b->bptr = b->bstop = b->buffer;
80 b->bufend = b->buffer + buflen;
82 strcpy(b->name, name);
84 b->refill = bfd_refill;
92 bopen(byte *name, uns mode, uns buffer)
94 int fd = sh_open(name, mode, 0666);
96 die("Unable to %s file %s: %m",
97 (mode & O_CREAT) ? "create" : "open", name);
98 return bfdopen_internal(fd, buffer, name);
102 bfdopen(int fd, uns buffer)
106 sprintf(x, "fd%d", fd);
107 return bfdopen_internal(fd, buffer, x);
110 void bbcopy(struct fastbuf *f, struct fastbuf *t, uns l)
112 uns rf = f->bstop - f->bptr;
118 uns k = (rf <= l) ? rf : l;
119 bwrite(t, f->bptr, k);
123 while (l >= t->buflen)
126 if ((uns) read(f->fd, t->buffer, t->buflen) != t->buflen)
127 die("bbcopy: %s exhausted", f->name);
129 f->fdpos += t->buflen;
130 f->bstop = f->bptr = f->buffer;
136 uns k = t->bufend - t->bptr;
141 k = t->bufend - t->bptr;
145 bread(f, t->bptr, k);
153 int main(int argc, char **argv)
155 struct fastbuf *f, *t;
158 f = bopen("/etc/profile", O_RDONLY, 16);