2 * UCW Library -- Fast Buffered I/O on Files
4 * (c) 1997--2004 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 */
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)
25 #define FB_BUFFER(f) (byte *)(FB_FILE(f) + 1)
28 bfd_refill(struct fastbuf *f)
30 f->bptr = f->buffer = FB_BUFFER(f);
31 int l = read(FB_FILE(f)->fd, f->buffer, f->bufend-f->buffer);
33 die("Error reading %s: %m", f->name);
34 f->bstop = f->buffer + l;
40 bfd_spout(struct fastbuf *f)
42 int l = f->bptr - f->buffer;
48 int z = write(FB_FILE(f)->fd, c, l);
50 die("Error writing %s: %m", f->name);
54 f->bptr = f->buffer = FB_BUFFER(f);
58 bfd_seek(struct fastbuf *f, sh_off_t pos, int whence)
60 if (whence == SEEK_SET && pos == f->pos)
63 sh_off_t l = sh_seek(FB_FILE(f)->fd, pos, whence);
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 = (byte *)(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;
116 f->can_overwrite_buffer = 2;
121 bopen_try(byte *name, uns mode, uns buflen)
123 int fd = sh_open(name, mode, 0666);
126 struct fastbuf *b = bfdopen_internal(fd, buflen, name);
128 bfd_seek(b, 0, SEEK_END);
133 bopen(byte *name, uns mode, uns buflen)
136 return bopen_mm(name, mode);
137 struct fastbuf *b = bopen_try(name, mode, buflen);
139 die("Unable to %s file %s: %m",
140 (mode & O_CREAT) ? "create" : "open", name);
145 bfdopen(int fd, uns buflen)
149 sprintf(x, "fd%d", fd);
150 return bfdopen_internal(fd, buflen, x);
154 bfdopen_shared(int fd, uns buflen)
156 struct fastbuf *f = bfdopen(fd, buflen);
157 FB_FILE(f)->is_temp_file = -1;
162 bfilesync(struct fastbuf *b)
165 if (fsync(FB_FILE(b)->fd) < 0)
166 log(L_ERROR, "fsync(%s) failed: %m", b->name);
171 int main(int argc UNUSED, char **argv UNUSED)
173 struct fastbuf *f, *t;
175 f = bopen("/etc/profile", O_RDONLY, 16);
178 printf("%d %d\n", (int)btell(f), (int)btell(t));