/* * Copyright 2013 (c) Anna Schumaker. * * DO NOT INCLUDE THIS FILE DIRECTLY. THIS IS A TEMPLATE DEFINITION FILE * AND ONLY MEANT TO BE INCLUDED BY include/database.h! */ #ifndef OCARINA_DATABASE_HPP #define OCARINA_DATABASE_HPP #include template Database :: Database(std::string filepath, bool autosave) : _size(0), _autosave(autosave), _file(filepath, FILE_TYPE_DATA) { } template Database :: ~Database() { } template void Database :: save() { if (_file.open(OPEN_WRITE) == false) return; _file << _db.size() << std::endl; for (unsigned int i = 0; i < _db.size(); i++) { _file << _db[i].valid; if (_db[i].valid == true) { _file << " "; _db[i].write(_file); } _file << std::endl; } _file.close(); } template void Database :: autosave() { if (_autosave == true) save(); } template void Database :: load() { unsigned int db_size; if (_file.exists() == false) return; else if (_file.open(OPEN_READ) == false) return; _file >> db_size; _db.resize(db_size); for (unsigned int i = 0; i < db_size; i++) { _file >> _db[i].valid; if (_db[i].valid == true) { _db[i].read(_file); _db[i].id = i; _keys.insert(std::pair(_db[i].primary_key(), i)); _size++; } } _file.close(); } template T *Database :: insert(T val) { T *t = find(val.primary_key()); if (t != NULL) return t; iterator it = _db.insert(_db.end(), val); it->valid = true; it->id = it - _db.begin(); _keys[it->primary_key()] = it->id; _size++; autosave(); return &_db[it->id]; } template void Database :: remove(unsigned int id) { if (id >= actual_size()) return; if (_db[id].valid == false) return; _keys.erase(_db[id].primary_key()); _db[id].valid = false; _size--; autosave(); } template unsigned int Database :: size() { return _size; } template unsigned int Database :: actual_size() { return _db.size(); } template typename Database::iterator Database :: begin() { if (size() == 0) return end(); iterator it = _db.begin(); if ( (*it).valid == true ) return it; return next(it); } template typename Database::iterator Database :: end() { return _db.end(); } template typename Database::iterator Database :: next(iterator &it) { do { it++; } while ((it != end()) && ((*it).valid == false)); return it; } template T *Database :: at(unsigned int id) { if (id >= actual_size()) return NULL; if (_db[id].valid == false) return NULL; return &_db[id]; } template T *Database :: find(const std::string &key) { std::map::iterator it; it = _keys.find(key); if (it == _keys.end()) return NULL; return &_db[it->second]; } #endif /* OCARINA_DATABASE_HPP */