#include <fcntl.h>
#include <unistd.h>
+struct fb_file {
+ struct fastbuf fb;
+ int fd; /* File descriptor, -1 if not a real file */
+ int is_temp_file; /* 0=normal file, 1=temporary file, delete on close, -1=shared FD */
+};
+#define FB_FILE(f) ((struct fb_file *)(f)->is_fastbuf)
+
static int
bfd_refill(struct fastbuf *f)
{
static void
bfd_close(struct fastbuf *f)
{
- close(FB_FILE(f)->fd);
- if (FB_FILE(f)->is_temp_file && unlink(f->name) < 0)
- die("unlink(%s): %m", f->name);
+ switch (FB_FILE(f)->is_temp_file)
+ {
+ case 1:
+ if (unlink(f->name) < 0)
+ log(L_ERROR, "unlink(%s): %m", f->name);
+ case 0:
+ close(FB_FILE(f)->fd);
+ }
xfree(f);
}
+static int
+bfd_config(struct fastbuf *f, uns item, int value)
+{
+ switch (item)
+ {
+ case BCONFIG_IS_TEMP_FILE:
+ FB_FILE(f)->is_temp_file = value;
+ return 0;
+ default:
+ return -1;
+ }
+}
+
static struct fastbuf *
bfdopen_internal(int fd, uns buflen, byte *name)
{
f->spout = bfd_spout;
f->seek = bfd_seek;
f->close = bfd_close;
+ f->config = bfd_config;
return f;
}
bopen(byte *name, uns mode, uns buffer)
{
struct fastbuf *b;
- int fd = sh_open(name, mode, 0666);
+ int fd;
+
+ if (!buffer)
+ return bopen_mm(name, mode);
+ fd = sh_open(name, mode, 0666);
if (fd < 0)
die("Unable to %s file %s: %m",
(mode & O_CREAT) ? "create" : "open", name);
return bfdopen_internal(fd, buffer, x);
}
-void bbcopy(struct fastbuf *f, struct fastbuf *t, uns l)
+struct fastbuf *
+bfdopen_shared(int fd, uns buffer)
{
- uns rf = f->bstop - f->bptr;
- uns tbuflen = t->bufend - t->buffer;
-
- ASSERT(f->close == bfd_close);
- ASSERT(t->close == bfd_close);
- if (!l)
- return;
- if (rf)
- {
- uns k = MIN(rf, l);
- bwrite(t, f->bptr, k);
- f->bptr += k;
- l -= k;
- if (!l)
- return;
- }
- while (l >= tbuflen)
- {
- t->spout(t);
- if ((uns) read(FB_FILE(f)->fd, t->buffer, tbuflen) != tbuflen)
- die("bbcopy: %s exhausted", f->name);
- f->pos += tbuflen;
- f->bstop = f->bptr = f->buffer;
- t->bptr = t->bufend;
- l -= tbuflen;
- }
- while (l)
- {
- uns k = t->bufend - t->bptr;
-
- if (!k)
- {
- t->spout(t);
- k = t->bufend - t->bptr;
- }
- if (k > l)
- k = l;
- bread(f, t->bptr, k);
- t->bptr += k;
- l -= k;
- }
+ struct fastbuf *f = bfdopen(fd, buffer);
+ FB_FILE(f)->is_temp_file = -1;
+ return f;
}
#ifdef TEST