ocarina/include/core/database.h

157 lines
3.0 KiB
C
Raw Normal View History

/**
* @file
* Copyright 2013 (c) Anna Schumaker.
*/
#ifndef OCARINA_CORE_DATABASE_H
#define OCARINA_CORE_DATABASE_H
#include <core/file.h>
#include <map>
#include <vector>
/**
* Class representing a single item in a Database.
*/
class DatabaseEntry {
public:
/** The index of this item */
unsigned int id;
/**
* Constructor
*/
DatabaseEntry();
/**
* Destructor
*/
virtual ~DatabaseEntry() = 0;
/**
* Used to find the primary key of a database item.
* @return A uniqueue string identifying a single item in the database.
*/
virtual const std::string primary_key() const = 0;
/**
* Called to write a DatabaseItem to disk.
* @param file File to use when writing data.
*/
virtual void write(File &) = 0;
/**
* Called to read a DatabaseItem from disk.
* @param file File to use when reading data.
*/
virtual void read(File &) = 0;
};
/**
* Our custom database class.
*/
template <class T>
class Database {
private:
std::vector<T *> _db;
std::map<const std::string, unsigned int> _keys;
unsigned int _size;
bool _autosave;
File _file;
public:
/** Iterator access for our backing std::vector */
typedef typename std::vector<T *>::iterator iterator;
/** Const iterator access for our backing std::vector */
typedef typename std::vector<T *>::const_iterator const_iterator;
/**
* Database constructor.
* @param filepath File on disk that will be written to.
* @param autosave True if database should be saved on every modification.
*/
Database(std::string, bool);
/**
* Database destructor.
*/
~Database();
/**
* Called to write the database to disk.
*/
void save();
/**
* Called to save the database after modifications.
*/
void autosave();
/**
* Called to load the database from disk.
*/
void load();
/**
* Add a new item to the database.
* @param item The new item to be added.
* @return A pointer to the item in the database.
*/
T *insert(const T &);
/**
* Remove an item from the database.
* @param index The index of the item that should be removed.
*/
void remove(unsigned int);
/**
* Find the size of the database.
* @return The number of valid items in the database.
*/
unsigned int size();
/**
* Find the actual size of the backing vector.
* @return The number valid and invalid items in the database.
*/
unsigned int actual_size();
/**
* Returns an iterator pointing to the first entry in the database.
*/
iterator begin();
/**
* Returns an iterator pointing past the end of the database.
*/
iterator end();
/**
* Returns an iterator pointing to the next valid item in the database.
*/
iterator next(iterator &);
/**
* Returns the database item at index n.
* @param n The database index to access.
* @return A valid DatabaseItem or NULL.
*/
T *at(unsigned int);
/**
* Find a DatabaseItem with a specific primary key.
* @param key The key to search for.
* @return A valid DatabaseItem or NULL.
*/
T *find(const std::string &);
};
#include "database.hpp"
#endif /* OCARINA_CORE_DATABASE_H */