ocarina/lib/index.cpp

121 lines
2.2 KiB
C++

/*
* Copyright 2013 (c) Anna Schumaker.
*/
#include <index.h>
Index :: Index(std::string filepath)
: file(filepath, FILE_TYPE_DATA)
{
}
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 :: print()
{
std::set<std::string>::iterator s_it;
std::set<unsigned int>::iterator u_it;
for (s_it = keys.begin(); s_it != keys.end(); s_it++) {
std::string key = *s_it;
:: print("index[%s] = {", key.c_str());
for (u_it = index[key].begin(); u_it != index[key].end(); u_it++) {
if (u_it != index[key].begin())
:: print(" ");
:: print("%d", *u_it);
}
:: print("}\n");
}
:: print("\n");
}
void Index :: print_keys()
{
std::set<std::string>::iterator it;
:: print("Keys:");
for (it = keys.begin(); it != keys.end(); it++)
:: print(" %s", it->c_str());
:: print("\n");
}
void Index :: insert(std::string key, unsigned int value)
{
if (index.find(key) == index.end()) {
index[key] = std::set<unsigned int>();
keys.insert(key);
}
index[key].insert(value);
}
void Index :: remove(std::string key)
{
index.erase(key);
keys.erase(key);
}
void Index :: remove(std::string key, unsigned int value)
{
index[key].erase(value);
if (index[key].size() == 0)
remove(key);
}
const std::set<std::string>::iterator Index :: keys_begin()
{
return keys.begin();
}
const std::set<std::string>::iterator Index :: keys_end()
{
return keys.end();
}
const std::set<unsigned int> &Index :: operator[](const std::string &key)
{
return index[key];
}