index: Add in save and load functionality

Signed-off-by: Anna Schumaker <schumaker.anna@gmail.com>
This commit is contained in:
Anna Schumaker 2013-08-25 10:31:33 -04:00 committed by Anna Schumaker
parent be0d3f3da4
commit 379a96fe13
5 changed files with 101 additions and 0 deletions

View File

@ -30,6 +30,7 @@ Index: (lib/index.cpp)
const set<unsigned int> &operator[](string);
};
File << keys.size() << endl;
File << key << endl;
File << map[key].size() << int_0 << int_1 << ... << int_n << endl;

View File

@ -18,6 +18,8 @@ private:
public:
Index(std::string);
void save();
void load();
void insert(std::string, unsigned int);
void remove(std::string);

View File

@ -10,6 +10,48 @@ Index :: Index(std::string filepath)
}
void Index :: save()
{
std::set<std::string>::iterator k_it;
std::set<unsigned int>::iterator u_it;
if (file.open(OPEN_WRITE) == false)
return;
file << keys.size();
for (k_it = keys.begin(); k_it != keys.end(); k_it++) {
file << *k_it << std::endl;
file << index[*k_it].size() << " ";
for (u_it = index[*k_it].begin(); u_it != index[*k_it].end(); u_it++)
file << *u_it << " ";
file << std::endl;
}
file.close();
}
void Index :: load()
{
std::string key;
unsigned int num_keys, num_values, value;
if (file.open(OPEN_READ) == false)
return;
file >> num_keys;
for (unsigned int i = 0; i < num_keys; i++) {
file >> key >> num_values;
for (unsigned int j = 0; j < num_values; j++) {
file >> value;
insert(key, value);
}
}
file.close();
}
void Index :: insert(std::string key, unsigned int value)
{
if (index.find(key) == index.end()) {

View File

@ -113,10 +113,37 @@ void test_2()
print_index(index);
}
/*
* Save the database to disk
*/
void test_3()
{
print("Test 3\n");
Index index("test.idx");
populate_index(index);
remove_values(index);
index.save();
}
/*
* Reload the database from disk
*/
void test_4()
{
print("Test 4\n");
Index index("test.idx");
index.load();
print_index(index);
}
int main(int argc, char **argv)
{
test_0();
test_1();
test_2();
test_3();
test_4();
return 0;
}

View File

@ -73,3 +73,32 @@ index[x] = {1 2 3 4 5 6 7 8 9}
index[y] = {2 3 4 5 6 7 8 9}
index[z] = {3 4 5 6 7 8 9}
Test 3
Test 4
=== Printing index ===
Found keys: a b c d e f g h i j l m n o p q r s t u w x y z
index[a] = {0 1 2 3 4 5 6 7 8 9}
index[b] = {1 2 3 4 5 6 7 8 9}
index[c] = {2 3 4 5 6 7 8 9}
index[d] = {3 4 5 6 7 8 9}
index[e] = {4 5 6 7 8 9}
index[f] = {5 6 7 8 9}
index[g] = {6 7 8 9}
index[h] = {7 8 9}
index[i] = {8 9}
index[j] = {9}
index[l] = {0 1 2 3 4 5 6 7 8 9}
index[m] = {1 2 3 4 5 6 7 8 9}
index[n] = {2 3 4 5 6 7 8 9}
index[o] = {3 4 5 6 7 8 9}
index[p] = {4 5 6 7 8 9}
index[q] = {5 6 7 8 9}
index[r] = {6 7 8 9}
index[s] = {7 8 9}
index[t] = {8 9}
index[u] = {9}
index[w] = {0 1 2 3 4 5 6 7 8 9}
index[x] = {1 2 3 4 5 6 7 8 9}
index[y] = {2 3 4 5 6 7 8 9}
index[z] = {3 4 5 6 7 8 9}