Lumiera  0.pre.03
»edit your freedom«
index-table.hpp
Go to the documentation of this file.
1 /*
2  INDEX-TABLE.hpp - helper for lookup and membership check of sequence like data
3 
4  Copyright (C)
5  2015, Hermann Vosseler <Ichthyostega@web.de>
6 
7   **Lumiera** is free software; you can redistribute it and/or modify it
8   under the terms of the GNU General Public License as published by the
9   Free Software Foundation; either version 2 of the License, or (at your
10   option) any later version. See the file COPYING for further details.
11 
12 */
13 
14 
29 #ifndef LIB_DIFF_INDEX_TABLE_H
30 #define LIB_DIFF_INDEX_TABLE_H
31 
32 
33 #include "lib/error.hpp"
34 #include "lib/util.hpp"
35 #include "lib/format-string.hpp"
36 
37 #include <vector>
38 #include <map>
39 
40 
41 namespace lib {
42 namespace diff{
43 
44  namespace error = lumiera::error;
45 
46  using util::_Fmt;
47 
48 
49 
51  template<typename VAL>
52  class IndexTable
53  {
54  std::vector<VAL> data_;
55  std::map<VAL,size_t> idx_;
56 
57  public:
58  template<class SEQ>
59  IndexTable(SEQ const& seq)
60  {
61  size_t i = 0;
62  for (auto const& elm : seq)
63  {
64  __rejectDuplicate(elm);
65  data_.push_back (elm);
66  idx_[elm] = i++;
67  }
68  }
69 
70  /* === forwarded sequence access === */
71 
72  using iterator = typename std::vector<VAL>::iterator;
73  using const_iterator = typename std::vector<VAL>::const_iterator;
74 
75  iterator begin() { return data_.begin(); }
76  iterator end() { return data_.end(); }
77  const_iterator begin() const { return data_.begin(); }
78  const_iterator end() const { return data_.end(); }
79 
80  size_t size() const { return data_.size(); }
81 
82 
83 
84 
85  VAL const&
86  getElement (size_t i) const
87  {
88  REQUIRE (i < size());
89  return data_[i];
90  }
91 
92 
93  bool
94  contains (VAL const& elm) const
95  {
96  return pos(elm) != size();
97  }
98 
99 
100  size_t
101  pos (VAL const& elm) const
102  {
103  auto entry = idx_.find (elm);
104  return entry==idx_.end()? size()
105  : entry->second;
106  }
107 
108  private:
109  void
110  __rejectDuplicate (VAL const& elm)
111  {
112  if (util::contains (idx_, elm))
113  throw error::Logic(_Fmt("Attempt to add duplicate %s to index table") % elm);
114  }
115  };
116 
117 
118 
119 
120 }} // namespace lib::diff
121 #endif /*LIB_DIFF_INDEX_TABLE_H*/
AnyPair entry(Query< TY > const &query, typename WrapReturn< TY >::Wrapper &obj)
helper to simplify creating mock table entries, wrapped correctly
Front-end for printf-style string template interpolation.
A front-end for using printf-style formatting.
Implementation namespace for support and library code.
Derived specific exceptions within Lumiera&#39;s exception hierarchy.
Definition: error.hpp:190
data snapshot and lookup table
Definition: index-table.hpp:52
Tiny helper functions and shortcuts to be used everywhere Consider this header to be effectively incl...
Lumiera error handling (C++ interface).