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"
21 int fd; /* File descriptor, -1 if not a real file */
22 int is_temp_file; /* 0=normal file, 1=temporary file, delete on close, -1=shared FD */
24 #define FB_FILE(f) ((struct fb_file *)(f)->is_fastbuf)
27 bfd_refill(struct fastbuf *f)
29 int l = read(FB_FILE(f)->fd, f->buffer, f->bufend-f->buffer);
31 die("Error reading %s: %m", f->name);
33 f->bstop = f->buffer + l;
39 bfd_spout(struct fastbuf *f)
41 int l = f->bptr - f->buffer;
47 int z = write(FB_FILE(f)->fd, c, l);
49 die("Error writing %s: %m", f->name);
57 bfd_seek(struct fastbuf *f, sh_off_t pos, int whence)
61 if (whence == SEEK_SET && pos == f->pos)
64 l = sh_seek(FB_FILE(f)->fd, pos, whence);
66 die("lseek on %s: %m", f->name);
71 bfd_close(struct fastbuf *f)
73 switch (FB_FILE(f)->is_temp_file)
76 if (unlink(f->name) < 0)
77 log(L_ERROR, "unlink(%s): %m", f->name);
79 close(FB_FILE(f)->fd);
85 bfd_config(struct fastbuf *f, uns item, int value)
89 case BCONFIG_IS_TEMP_FILE:
90 FB_FILE(f)->is_temp_file = value;
97 static struct fastbuf *
98 bfdopen_internal(int fd, uns buflen, byte *name)
100 int namelen = strlen(name) + 1;
101 struct fb_file *F = xmalloc(sizeof(struct fb_file) + buflen + namelen);
102 struct fastbuf *f = &F->fb;
104 bzero(F, sizeof(*F));
105 f->buffer = (char *)(F+1);
106 f->bptr = f->bstop = f->buffer;
107 f->bufend = f->buffer + buflen;
109 memcpy(f->name, name, namelen);
111 f->refill = bfd_refill;
112 f->spout = bfd_spout;
114 f->close = bfd_close;
115 f->config = bfd_config;
120 bopen(byte *name, uns mode, uns buffer)
124 #if 0 /* FIXME: Dirty hack for testing fb-mmap */
125 if (buffer >= 65536 && (mode == O_RDONLY))
127 log(L_DEBUG, "bopen_mm hack: %s", name);
129 mode = (mode & ~O_WRONLY) | O_RDWR;
130 return bopen_mm(name, mode);
134 int fd = sh_open(name, mode, 0666);
136 die("Unable to %s file %s: %m",
137 (mode & O_CREAT) ? "create" : "open", name);
138 b = bfdopen_internal(fd, buffer, name);
140 bfd_seek(b, 0, SEEK_END);
145 bfdopen(int fd, uns buffer)
149 sprintf(x, "fd%d", fd);
150 return bfdopen_internal(fd, buffer, x);
154 bfdopen_shared(int fd, uns buffer)
156 struct fastbuf *f = bfdopen(fd, buffer);
157 FB_FILE(f)->is_temp_file = -1;
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));