2 * Sherlock Library -- Fast Buffered I/O on Files
4 * (c) 1997--2004 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 */
25 #define FB_FILE(f) ((struct fb_file *)(f)->is_fastbuf)
26 #define FB_BUFFER(f) (byte *)(FB_FILE(f) + 1)
29 bfd_refill(struct fastbuf *f)
31 f->bptr = f->buffer = FB_BUFFER(f);
32 int l = read(FB_FILE(f)->fd, f->buffer, f->bufend-f->buffer);
34 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);
55 f->bptr = f->buffer = FB_BUFFER(f);
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;
99 static struct fastbuf *
100 bfdopen_internal(int fd, uns buflen, byte *name)
102 int namelen = strlen(name) + 1;
103 struct fb_file *F = xmalloc(sizeof(struct fb_file) + buflen + namelen);
104 struct fastbuf *f = &F->fb;
106 bzero(F, sizeof(*F));
107 f->buffer = (byte *)(F+1);
108 f->bptr = f->bstop = f->buffer;
109 f->bufend = f->buffer + buflen;
111 memcpy(f->name, name, namelen);
113 f->refill = bfd_refill;
114 f->spout = bfd_spout;
116 f->close = bfd_close;
117 f->config = bfd_config;
118 f->can_overwrite_buffer = 2;
123 bopen(byte *name, uns mode, uns buflen)
129 return bopen_mm(name, mode);
130 fd = sh_open(name, mode, 0666);
132 die("Unable to %s file %s: %m",
133 (mode & O_CREAT) ? "create" : "open", name);
134 b = bfdopen_internal(fd, buflen, name);
136 bfd_seek(b, 0, SEEK_END);
141 bfdopen(int fd, uns buflen)
145 sprintf(x, "fd%d", fd);
146 return bfdopen_internal(fd, buflen, x);
150 bfdopen_shared(int fd, uns buflen)
152 struct fastbuf *f = bfdopen(fd, buflen);
153 FB_FILE(f)->is_temp_file = -1;
159 int main(int argc, char **argv)
161 struct fastbuf *f, *t;
163 f = bopen("/etc/profile", O_RDONLY, 16);
166 printf("%d %d\n", (int)btell(f), (int)btell(t));