-
Notifications
You must be signed in to change notification settings - Fork 1
/
db.cc
65 lines (57 loc) · 1.65 KB
/
db.cc
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
#include <iostream>
#include "include/seastarkv.hh"
#include "include/db.hh"
#include "include/reply_builder.hh"
using namespace std;
unordered_map<string, database*> db_map;
void database::hashtable_init(uint32_t size) {
ht.table = (db_val**)calloc(size, sizeof(void*));
assert(ht.table != NULL);
ht.size = size;
return;
}
bool database::ht_set(db_val_t* val, int version) {
boost::upgrade_lock<boost::shared_mutex> lock(ht._access);
val->next = NULL;
uint32_t hash = get_hash(val->key, 0) % ht.size;
db_val_t* next = ht.table[hash];
db_val_t* before = NULL;
while (next != NULL && next->key != val->key) {
before = next;
next = before->next;
}
boost::upgrade_to_unique_lock<boost::shared_mutex> uniqueLock(lock);
if (next != NULL) {
int* v = (int*)next->data;
if (*v == version) {
free(next->data);
next->data = val->data;
next->length = val->length;
free(val);
} else
return false;
} else if (before != NULL){
before->next = val;
} else
ht.table[hash] = val;
return true;
}
db_val_t* database::ht_get(uint32_t key) {
boost::shared_lock<boost::shared_mutex> lock(ht._access);
uint32_t hash = get_hash(key, 0) % ht.size;
db_val_t* p = ht.table[hash];
while (p && p->key != key)
p = p->next;
db_val_t* ret = NULL;
if (p) {
ret = (db_val_t*) malloc(sizeof(db_val_t));
ret->length = p->length;
ret->data = malloc(ret->length);
memcpy(ret->data, p->data, ret->length);
}
return ret;
}
db_val** database::get_table_direct(void)
{
return ht.table;
}