2 * Sherlock Library -- Fast Buffered I/O on Files
4 * (c) 1997--2002 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(FB_FILE(f)->fd, f->buffer, f->bufend-f->buffer);
24 die("Error reading %s: %m", f->name);
26 f->bstop = f->buffer + l;
32 bfd_spout(struct fastbuf *f)
34 int l = f->bptr - f->buffer;
40 int z = write(FB_FILE(f)->fd, c, l);
42 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->pos)
57 l = sh_seek(FB_FILE(f)->fd, pos, whence);
59 die("lseek on %s: %m", f->name);
64 bfd_close(struct fastbuf *f)
66 close(FB_FILE(f)->fd);
67 if (FB_FILE(f)->is_temp_file && unlink(f->name) < 0)
68 die("unlink(%s): %m", f->name);
72 static struct fastbuf *
73 bfdopen_internal(int fd, uns buflen, byte *name)
75 int namelen = strlen(name) + 1;
76 struct fb_file *F = xmalloc(sizeof(struct fb_file) + buflen + namelen);
77 struct fastbuf *f = &F->fb;
80 f->buffer = (char *)(F+1);
81 f->bptr = f->bstop = f->buffer;
82 f->bufend = f->buffer + buflen;
84 memcpy(f->name, name, namelen);
86 f->refill = bfd_refill;
94 bopen(byte *name, uns mode, uns buffer)
97 int fd = sh_open(name, mode, 0666);
99 die("Unable to %s file %s: %m",
100 (mode & O_CREAT) ? "create" : "open", name);
101 b = bfdopen_internal(fd, buffer, name);
103 bfd_seek(b, 0, SEEK_END);
108 bfdopen(int fd, uns buffer)
112 sprintf(x, "fd%d", fd);
113 return bfdopen_internal(fd, buffer, x);
116 void bbcopy(struct fastbuf *f, struct fastbuf *t, uns l)
118 uns rf = f->bstop - f->bptr;
119 uns tbuflen = t->bufend - t->buffer;
121 ASSERT(f->close == bfd_close);
122 ASSERT(t->close == bfd_close);
128 bwrite(t, f->bptr, k);
137 if ((uns) read(FB_FILE(f)->fd, t->buffer, tbuflen) != tbuflen)
138 die("bbcopy: %s exhausted", f->name);
140 f->bstop = f->bptr = f->buffer;
146 uns k = t->bufend - t->bptr;
151 k = t->bufend - t->bptr;
155 bread(f, t->bptr, k);
163 int main(int argc, char **argv)
165 struct fastbuf *f, *t;
167 f = bopen("/etc/profile", O_RDONLY, 16);
170 printf("%d %d\n", (int)btell(f), (int)btell(t));