2 * Sherlock Library -- Fast Buffered I/O on Files
4 * (c) 1997--2000 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"
20 bfd_refill(struct fastbuf *f)
22 int l = read(f->fd, f->buffer, f->buflen);
25 die("Error reading %s: %m", f->name);
27 f->bstop = f->buffer + l;
34 bfd_spout(struct fastbuf *f)
36 int l = f->bptr - f->buffer;
41 int z = write(f->fd, c, l);
43 die("Error writing %s: %m", f->name);
53 bfd_seek(struct fastbuf *f, sh_off_t pos, int whence)
57 if (whence == SEEK_SET && pos == f->fdpos)
60 l = sh_seek(f->fd, pos, whence);
62 die("lseek on %s: %m", f->name);
63 f->fdpos = f->pos = l;
67 bfd_close(struct fastbuf *f)
70 if (f->is_temp_file && unlink(f->name) < 0)
71 die("unlink(%s): %m", f->name);
74 static struct fastbuf *
75 bfdopen_internal(int fd, uns buflen, byte *name)
77 int namelen = strlen(name) + 1;
78 struct fastbuf *b = xmalloc_zero(sizeof(struct fastbuf) + buflen + namelen);
81 b->buffer = (char *)(b+1);
82 b->bptr = b->bstop = b->buffer;
83 b->bufend = b->buffer + buflen;
85 strcpy(b->name, name);
87 b->refill = bfd_refill;
95 bopen(byte *name, uns mode, uns buffer)
98 int fd = sh_open(name, mode, 0666);
100 die("Unable to %s file %s: %m",
101 (mode & O_CREAT) ? "create" : "open", name);
102 b = bfdopen_internal(fd, buffer, name);
104 bfd_seek(b, 0, SEEK_END);
109 bfdopen(int fd, uns buffer)
113 sprintf(x, "fd%d", fd);
114 return bfdopen_internal(fd, buffer, x);
117 void bbcopy(struct fastbuf *f, struct fastbuf *t, uns l)
119 uns rf = f->bstop - f->bptr;
125 uns k = (rf <= l) ? rf : l;
126 bwrite(t, f->bptr, k);
130 while (l >= t->buflen)
133 if ((uns) read(f->fd, t->buffer, t->buflen) != t->buflen)
134 die("bbcopy: %s exhausted", f->name);
136 f->fdpos += t->buflen;
137 f->bstop = f->bptr = f->buffer;
143 uns k = t->bufend - t->bptr;
148 k = t->bufend - t->bptr;
152 bread(f, t->bptr, k);
160 int main(int argc, char **argv)
162 struct fastbuf *f, *t;
165 f = bopen("/etc/profile", O_RDONLY, 16);