2 * Sherlock Library -- Fast Buffered I/O on Files
4 * (c) 1997--2002 Martin Mares <mj@ucw.cz>
5 * (c) 2004 Robert Spalek <robert@ucw.cz>
7 * This software may be freely distributed and used according to the terms
8 * of the GNU Lesser General Public License.
12 #include "lib/fastbuf.h"
22 int fd; /* File descriptor, -1 if not a real file */
23 int is_temp_file; /* 0=normal file, 1=temporary file, delete on close, -1=shared FD */
26 #define FB_FILE(f) ((struct fb_file *)(f)->is_fastbuf)
29 bfd_refill(struct fastbuf *f)
31 int l = read(FB_FILE(f)->fd, f->buffer, f->bufend-f->buffer);
33 die("Error reading %s: %m", f->name);
35 f->bstop = f->buffer + l;
41 bfd_spout(struct fastbuf *f)
43 int l = f->bptr - f->buffer;
49 int z = write(FB_FILE(f)->fd, c, l);
51 die("Error writing %s: %m", f->name);
59 bfd_seek(struct fastbuf *f, sh_off_t pos, int whence)
63 if (whence == SEEK_SET && pos == f->pos)
66 l = sh_seek(FB_FILE(f)->fd, pos, whence);
68 die("lseek on %s: %m", f->name);
73 bfd_close(struct fastbuf *f)
75 switch (FB_FILE(f)->is_temp_file)
78 if (unlink(f->name) < 0)
79 log(L_ERROR, "unlink(%s): %m", f->name);
81 close(FB_FILE(f)->fd);
87 bfd_config(struct fastbuf *f, uns item, int value)
91 case BCONFIG_IS_TEMP_FILE:
92 FB_FILE(f)->is_temp_file = value;
94 case BCONFIG_CAN_OVERWRITE: ;
95 int old_value = FB_FILE(f)->can_overwrite;
96 if (value >= 0 && value <= 2)
97 FB_FILE(f)->can_overwrite = value;
104 static struct fastbuf *
105 bfdopen_internal(int fd, uns buflen, byte *name)
107 int namelen = strlen(name) + 1;
108 struct fb_file *F = xmalloc(sizeof(struct fb_file) + buflen + namelen);
109 struct fastbuf *f = &F->fb;
111 bzero(F, sizeof(*F));
112 f->buffer = (char *)(F+1);
113 f->bptr = f->bstop = f->buffer;
114 f->bufend = f->buffer + buflen;
116 memcpy(f->name, name, namelen);
118 f->refill = bfd_refill;
119 f->spout = bfd_spout;
121 f->close = bfd_close;
122 f->config = bfd_config;
123 F->can_overwrite = 2;
128 bopen(byte *name, uns mode, uns buffer)
134 return bopen_mm(name, mode);
135 fd = sh_open(name, mode, 0666);
137 die("Unable to %s file %s: %m",
138 (mode & O_CREAT) ? "create" : "open", name);
139 b = bfdopen_internal(fd, buffer, name);
141 bfd_seek(b, 0, SEEK_END);
146 bfdopen(int fd, uns buffer)
150 sprintf(x, "fd%d", fd);
151 return bfdopen_internal(fd, buffer, x);
155 bfdopen_shared(int fd, uns buffer)
157 struct fastbuf *f = bfdopen(fd, buffer);
158 FB_FILE(f)->is_temp_file = -1;
164 int main(int argc, char **argv)
166 struct fastbuf *f, *t;
168 f = bopen("/etc/profile", O_RDONLY, 16);
171 printf("%d %d\n", (int)btell(f), (int)btell(t));