2 * @file unique_storage.h
3 * Unique storage of values
5 * @remark Copyright 2002 OProfile authors
6 * @remark Read the file COPYING
8 * @author Philippe Elie
12 #ifndef UNIQUE_STORAGE_H
13 #define UNIQUE_STORAGE_H
20 * Store values such that only one copy of the value
23 * I is an arbitrary typename that's never
26 * It is a required parameter in order to enforce
27 * type-safety for a collection.
29 * The value type "V" must be default-constructible,
30 * and this is the value returned by a stored id_value
31 * where .set() is false
33 template <typename I, typename V> class unique_storage {
38 values.push_back(V());
41 virtual ~unique_storage() {}
43 typedef std::vector<V> stored_values;
45 /// the actual ID type
47 /// id == 0 means "empty" / "undefined"
50 /// does this ID map to a non-default value ?
55 bool operator<(id_value const & rhs) const {
59 bool operator==(id_value const & rhs) const {
63 bool operator!=(id_value const & rhs) const {
64 return !(id == rhs.id);
68 friend class unique_storage<I, V>;
70 typedef typename stored_values::size_type size_type;
72 explicit id_value(size_type s) : id(s) {}
79 /// ensure this value is available
80 id_value const create(V const & value) {
81 typename id_map::value_type val(value, id_value(values.size()));
82 std::pair<typename id_map::iterator, bool>
83 inserted = ids.insert(val);
85 values.push_back(value);
87 return inserted.first->second;
91 /// return the stored value for the given ID
92 V const & get(id_value const & id) const {
93 // some stl lack at(), so we emulate it
94 if (id.id < values.size())
97 throw std::out_of_range("unique_storage::get(): out of bounds");
101 typedef std::map<V, id_value> id_map;
103 /// the contained values
104 stored_values values;
106 /// map from ID to value
110 #endif /* !UNIQUE_STORAGE_H */