/** * 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 template Database :: Database(std::string filepath, bool autosave) : _size(0), _autosave(autosave), _file(filepath, 0) { } template Database :: ~Database() { iterator it; for (it = begin(); it != end(); it = next(it)) delete (*it); } template void Database :: save() { if (_file.open(OPEN_WRITE) == false) return; _file << actual_size() << std::endl; for (unsigned int i = 0; i < _db.size(); i++) { if (_db[i] == NULL) _file << false; else { _file << true << " "; _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; bool valid; 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 >> valid; if (valid == false) _db[i] = NULL; else { _db[i] = new T; _db[i]->_index = i; _db[i]->read(_file); _keys[_db[i]->primary_key()] = i; _size++; } } _file.close(); } template T *Database :: insert(const T &item) { T *t = find(item.primary_key()); if (t != NULL) return NULL; t = new T(item); t->_index = actual_size(); _db.push_back(t); _keys[t->primary_key()] = t->index(); _size++; autosave(); return t; } template void Database :: remove(unsigned int index) { if (index >= actual_size()) return; if (_db[index] == NULL) return; _keys.erase(_db[index]->primary_key()); delete _db[index]; _db[index] = NULL; _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) != NULL ) 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) == NULL); return it; } template T *Database :: at(unsigned int index) { if (index >= actual_size()) return NULL; return _db[index]; } 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 */