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 sh_off_t l = sh_seek(FB_FILE(f)->fd, pos, whence);
68 bfd_close(struct fastbuf *f)
70 switch (FB_FILE(f)->is_temp_file)
73 if (unlink(f->name) < 0)
74 log(L_ERROR, "unlink(%s): %m", f->name);
76 close(FB_FILE(f)->fd);
82 bfd_config(struct fastbuf *f, uns item, int value)
86 case BCONFIG_IS_TEMP_FILE:
87 FB_FILE(f)->is_temp_file = value;
94 static struct fastbuf *
95 bfdopen_internal(int fd, uns buflen, byte *name)
97 int namelen = strlen(name) + 1;
98 struct fb_file *F = xmalloc(sizeof(struct fb_file) + buflen + namelen);
99 struct fastbuf *f = &F->fb;
102 bzero(F, sizeof(*F));
103 f->buffer = (byte *)(F+1);
104 f->bptr = f->bstop = f->buffer;
105 f->bufend = f->buffer + buflen;
107 memcpy(f->name, name, namelen);
109 f->refill = bfd_refill;
110 f->spout = bfd_spout;
112 f->close = bfd_close;
113 f->config = bfd_config;
114 f->can_overwrite_buffer = 2;
119 bopen_try(byte *name, uns mode, uns buflen)
121 int fd = sh_open(name, mode, 0666);
124 struct fastbuf *b = bfdopen_internal(fd, buflen, name);
126 bfd_seek(b, 0, SEEK_END);
131 bopen(byte *name, uns mode, uns buflen)
134 return bopen_mm(name, mode);
135 struct fastbuf *b = bopen_try(name, mode, buflen);
137 die("Unable to %s file %s: %m",
138 (mode & O_CREAT) ? "create" : "open", name);
143 bfdopen(int fd, uns buflen)
147 sprintf(x, "fd%d", fd);
148 return bfdopen_internal(fd, buflen, x);
152 bfdopen_shared(int fd, uns buflen)
154 struct fastbuf *f = bfdopen(fd, buflen);
155 FB_FILE(f)->is_temp_file = -1;
160 bfilesync(struct fastbuf *b)
163 if (fsync(FB_FILE(b)->fd) < 0)
164 log(L_ERROR, "fsync(%s) failed: %m", b->name);
169 int main(int argc UNUSED, char **argv UNUSED)
171 struct fastbuf *f, *t;
173 f = bopen("/etc/profile", O_RDONLY, 16);
176 printf("%d %d\n", (int)btell(f), (int)btell(t));