/* -*- mia-c++ -*-
* Copyright (c) 2007 Gert Wollny <gert dot wollny at acm dot org>
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*
*/
#ifndef mia_core_dictmap_hh
#define mia_core_dictmap_hh
#include <string>
#include <set>
#include <stdexcept>
#include <mia/core/defines.hh>
/**
A mapper from emums to string values. - usefull for names flags
*/
template <typename T>
class TDictMap {
public:
/**
The initialisation table. The last entry must have the name pointer pointing to 0.
*/
typedef struct {
const char *name;
const T value;
} Table;
/// Create the map by providing an initialisation map
TDictMap(const Table *table);
/**
\param name
\returns corresponding flag
\remark throws std::invalid_argument if the name is unknown
*/
T get_value(const char *name) const;
/**
\param name
\returns corresponding flag
\remark throws std::invalid_argument if the value is unknown
*/
const char *get_name(T value) const;
/// \returns a set of all available names
const std::set<std::string> get_name_set() const;
private:
const Table *_M_table;
};
template <typename T>
TDictMap<T>::TDictMap(const Table *table):
_M_table(table)
{
}
template <typename T>
T TDictMap<T>::get_value(const char *name) const
{
const Table *t = _M_table;
while (t->name && strcmp(t->name, name))
++t;
if ( !t->name) {
throw std::invalid_argument(std::string("TDictMap<T>::get_name: unknown name '")+std::string(name)+std::string("' provided"));
}
return t->value;
}
template <typename T>
const char *TDictMap<T>::get_name(T value) const
{
const Table *t = _M_table;
while (t->name && t->value != value)
++t;
if (!t->name)
throw std::invalid_argument("TDictMap<T>::get_name: unknown value provided");
return t->name;
}
template <typename T>
const std::set<std::string> TDictMap<T>::get_name_set() const
{
std::set<std::string> result;
const Table *t = _M_table;
while (t->name != NULL) {
result.insert(t->name);
++t;
}
return result;
}
#endif