Skip to content

Commit

Permalink
removed multiple returns from bf_storage routines and introduced comm…
Browse files Browse the repository at this point in the history
…it function
  • Loading branch information
Vladislav Yarmak committed Jul 2, 2016
1 parent f8dfaf0 commit 1f69de9
Showing 1 changed file with 36 additions and 24 deletions.
60 changes: 36 additions & 24 deletions bf_storage.c
Original file line number Diff line number Diff line change
@@ -1,58 +1,70 @@
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/types.h>
#include <unistd.h>
#include "bf_types.h"

const char inprogress_sf[] = ".inprogress";
#define BYTES_FOR_PID sizeof('.') + sizeof('-') + 2.5 * sizeof(pid_t) + sizeof('\0') + 1
/* bytes for decimal record of int :=
:= ceil(log10(INT_MAX)) + sign + zero-byte (+ 1 to avoid real ceil call)
*/

//Storage operations
int _bf_commit_snapshot(const char *src, const char *dst) {
int ret = -1;
if (rename(src, dst) == 0) {
ret = 0;
} else {
fputs("Unable to rename inprogress snapshot into actual location.\n",
stderr);
}
return ret;
}

int bf_dump_to_file(const bloom_filter_t *bf, const char *fname)
{
int ret = -1;
fputs("Saving snapshot...\n", stderr);

char *inprogress_fn = malloc(strlen(fname) + sizeof(inprogress_sf));
strcpy(inprogress_fn, fname);
strcat(inprogress_fn, inprogress_sf);
char *inprogress_fn = malloc(strlen(fname) + BYTES_FOR_PID);
sprintf(inprogress_fn, "%s.%d", fname, getpid());

size_t shouldwrite = (bf->m + (CHAR_BIT - 1)) / CHAR_BIT;
FILE *f = fopen(inprogress_fn, "wb");

if (f) {
size_t bwritten = fwrite(bf->space, 1, shouldwrite, f);
if (bwritten != shouldwrite) {
fprintf(stderr, "Should write: %ld bytes. Written %ld bytes.\n", shouldwrite, bwritten);
free(inprogress_fn);
return -1;
}
fclose(f);
if (rename(inprogress_fn, fname) == 0) {
free(inprogress_fn);
return 0;
if (bwritten == shouldwrite) {
fclose(f);
ret = _bf_commit_snapshot(inprogress_fn, fname);
} else {
free(inprogress_fn);
fputs("Unable to rename inprogress snapshot into actual location.\n", stderr);
return -1;
fprintf(stderr, "Should write: %ld bytes. Written %ld bytes.\n",
shouldwrite, bwritten);
}
} else {
fputs("Error opening file for writting.\n", stderr);
free(inprogress_fn);
return -1;
}
free(inprogress_fn);
return ret;
}

int bf_load_from_file(bloom_filter_t *bf, const char *fname)
{
int ret = -1;
FILE *f = fopen(fname, "rb");
if (f) {
size_t shouldread = (bf->m + (CHAR_BIT - 1)) / CHAR_BIT;
size_t bread = fread(bf->space, 1, shouldread, f);
if (bread != shouldread) {
fprintf(stderr, "Should read: %ld bytes. Read %ld bytes.\n", shouldread, bread);
return -1;
if (bread == shouldread) {
fclose(f);
ret = 0;
} else {
fprintf(stderr, "Should read: %ld bytes. Read %ld bytes.\n",
shouldread, bread);
}
fclose(f);
return 0;
} else {
fputs("Error opening file for reading.\n", stderr);
return -1;
}
return ret;
}

0 comments on commit 1f69de9

Please sign in to comment.