/* Checks if the given KEY, VALUE pair can be inserted into this server's * store. Returns 0 if it can, else a negative error code. */ int tpcfollower_put_check(tpcfollower_t *server, char *key, char *value) { int check; if (strlen(key) > MAX_KEYLEN || strlen(key) == 0) return ERR_KEYLEN; if (strlen(value) > MAX_VALLEN) return ERR_VALLEN; if ((check = kvstore_put_check(&server->store, key, value)) < 0) return check; return 0; }
/* Adds the given KEY, VALUE entry to STORE. Returns 0 if successful, else a * negative error code. See kvserver.h for a complete description of how * entries are stored. */ int kvstore_put(kvstore_t *store, char *key, char *value) { unsigned long hashval; int counter, check; size_t keylen = strlen(key), vallen = strlen(value); char filename[MAX_FILENAME]; struct stat st; FILE *file; kventry_t *entry; if ((check = kvstore_put_check(store, key, value)) < 0) return check; hashval = hash(key); counter = find_entry(store, key, NULL); pthread_rwlock_wrlock(&store->lock); if (counter >= 0) { /* Entry already exists, just update it. */ sprintf(filename, "%s/%lu-%u%s", store->dirname, hashval, counter, KVSTORE_FILETYPE); } else { /* Search for the end of the hash chain to insert. */ counter = 0; sprintf(filename, "%s/%lu-%u%s", store->dirname, hashval, counter++, KVSTORE_FILETYPE); while (stat(filename, &st) != -1) sprintf(filename, "%s/%lu-%u%s", store->dirname, hashval, counter++, KVSTORE_FILETYPE); } if ((file = fopen(filename, "w")) == NULL) { pthread_rwlock_unlock(&store->lock); return ERRFILACCESS; } entry = malloc(sizeof(kventry_t) + keylen + vallen + 2); entry->length = keylen + vallen + 2; strcpy(entry->data, key); strcpy(entry->data + keylen + 1, value); fwrite(entry, sizeof(kventry_t) + entry->length, 1, file); fclose(file); pthread_rwlock_unlock(&store->lock); free(entry); return 0; }
/* Checks if the given KEY, VALUE pair can be inserted into this server's * store. Returns 0 if it can, else a negative error code. */ int kvserver_put_check(kvserver_t *server, char *key, char *value) { // OUR CODE HERE return kvstore_put_check(&server->store, key, value); }