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;
101 bzero(F, sizeof(*F));
102 f->buffer = (byte *)(F+1);
103 f->bptr = f->bstop = f->buffer;
104 f->bufend = f->buffer + buflen;
106 memcpy(f->name, name, namelen);
108 f->refill = bfd_refill;
109 f->spout = bfd_spout;
111 f->close = bfd_close;
112 f->config = bfd_config;
113 f->can_overwrite_buffer = 2;
118 bopen_try(byte *name, uns mode, uns buflen)
120 int fd = sh_open(name, mode, 0666);
123 struct fastbuf *b = bfdopen_internal(fd, buflen, name);
125 bfd_seek(b, 0, SEEK_END);
130 bopen(byte *name, uns mode, uns buflen)
133 return bopen_mm(name, mode);
134 struct fastbuf *b = bopen_try(name, mode, buflen);
136 die("Unable to %s file %s: %m",
137 (mode & O_CREAT) ? "create" : "open", name);
142 bfdopen(int fd, uns buflen)
146 sprintf(x, "fd%d", fd);
147 return bfdopen_internal(fd, buflen, x);
151 bfdopen_shared(int fd, uns buflen)
153 struct fastbuf *f = bfdopen(fd, buflen);
154 FB_FILE(f)->is_temp_file = -1;
159 bfilesync(struct fastbuf *b)
162 if (fsync(FB_FILE(b)->fd) < 0)
163 log(L_ERROR, "fsync(%s) failed: %m", b->name);
168 int main(int argc UNUSED, char **argv UNUSED)
170 struct fastbuf *f, *t;
172 f = bopen("/etc/profile", O_RDONLY, 16);
175 printf("%d %d\n", (int)btell(f), (int)btell(t));