#include <stdio.h>
#include <string.h>
#include <unistd.h>
#include "db_headers.h"
#include "db_pickle.h"
#include "nisdb_mt.h"
pickle_file::pickle_file(char* f, pickle_mode m)
{
if ((filename = strdup(f)) == NULL) {
FATAL("pickle_file::pickle_file: cannot allocate space",
DB_MEMORY_LIMIT);
}
INITRW(pickle);
mode = m;
}
bool_t
pickle_file::open()
{
WRITELOCK(this, FALSE, "w pickle_file::open");
if (mode == PICKLE_READ) {
file = fopen(filename, "r");
if (file)
xdrstdio_create(&(xdr), file, XDR_DECODE);
} else if (mode == PICKLE_WRITE) {
file = fopen(filename, "w");
if (file) {
setvbuf(file, NULL, _IOFBF, 81920);
xdrstdio_create(&(xdr), file, XDR_ENCODE);
}
} else if (mode == PICKLE_APPEND) {
file = fopen(filename, "a");
if (file)
xdrstdio_create(&(xdr), file, XDR_ENCODE);
}
if (file == NULL) {
WRITEUNLOCK(this, FALSE, "wu pickle_file::open");
return (FALSE);
}
WRITEUNLOCK(this, FALSE, "wu pickle_file::open");
return (TRUE);
}
int
pickle_file::close()
{
int ret;
WRITELOCK(this, EOF, "w pickle_file::close");
xdr_destroy(&(xdr));
ret = fclose(file);
WRITEUNLOCK(this, EOF, "wu pickle_file::close");
return (ret);
}
int
pickle_file::transfer(pptr p, bool_t (*f) (XDR*, pptr))
{
WRITELOCK(this, -1, "w pickle_file::transfer");
if (open()) {
if ((f)(&xdr, p) == FALSE) {
close();
WRITEUNLOCK(this, -1, "wu pickle_file::transfer");
return (-1);
} else {
fsync(fileno(file));
WRITEUNLOCK(this, -1, "wu pickle_file::transfer");
return (close());
}
}
WRITEUNLOCK(this, -1, "wu pickle_file::transfer");
return (1);
}