jubilant-funicular
IDFactory.h
1 #ifndef NTA_IDFACTORY_H_INCLUDED
2 #define NTA_IDFACTORY_H_INCLUDED
3 
4 #define NTA_INVALID_ID 0
5 
6 #include <vector>
7 
8 #include "nta/MyEngine.h"
9 
10 namespace nta {
11  namespace utils {
13  template<typename T>
14  class IDFactory {
15  private:
17  std::vector<T> m_free;
20  public:
21  IDFactory() : m_last_id(NTA_INVALID_ID) {}
23  void clear() { m_free.clear(); m_last_id = NTA_INVALID_ID; }
25  void reset() { clear(); }
26 
28  T gen_id();
32  void free_id(T id);
34  void free(T id) { free_id(id); }
36  bool is_free(T id) const;
38  bool is_in_use(T id) const { return id != NTA_INVALID_ID && !is_free(id); }
39 
41  std::size_t get_count() const { return (std::size_t)m_last_id - m_free.size() - NTA_INVALID_ID; }
43  T get_last_id() const { return m_last_id; }
44 
46  T operator()() { return gen_id(); }
47  };
48  template<typename T>
50  if (m_free.empty()) {
51  return ++m_last_id;
52  } else {
53  T ret = m_free.back();
54  m_free.pop_back();
55  return ret;
56  }
57  }
58  template<typename T>
59  void IDFactory<T>::free_id(T id) {
60  m_free.push_back(id);
61  }
62  template<typename T>
63  bool IDFactory<T>::is_free(T id) const {
64  if (id > m_last_id) return true;
65  for (const auto& id2 : m_free) {
66  if (id == id2) return true;
67  }
68  return false;
69  }
70  }
71 }
72 
73 #endif // NTA_IDFACTORY_H_INCLUDED
nta::utils::IDFactory::free_id
void free_id(T id)
Definition: IDFactory.h:59
nta::utils::IDFactory::is_free
bool is_free(T id) const
Returns whether or not an id is free.
Definition: IDFactory.h:63
nta::utils::IDFactory::get_last_id
T get_last_id() const
Returns m_last_id.
Definition: IDFactory.h:43
nta::utils::IDFactory::is_in_use
bool is_in_use(T id) const
Returns whether or not the id is in use.
Definition: IDFactory.h:38
nta::utils::IDFactory::m_free
std::vector< T > m_free
IDs that were previously active but have since been freed.
Definition: IDFactory.h:17
nta::utils::IDFactory::reset
void reset()
Resets this to a new IDFactory.
Definition: IDFactory.h:25
nta::utils::IDFactory::m_last_id
T m_last_id
The smallest id that has never been assigned.
Definition: IDFactory.h:19
nta::utils::IDFactory
Class for generating unique (integral) IDs.
Definition: IDFactory.h:14
nta::utils::IDFactory::free
void free(T id)
calls free_id
Definition: IDFactory.h:34
nta
Definition: Animation2D.h:6
nta::utils::IDFactory::gen_id
T gen_id()
Generates a new, unused ID.
Definition: IDFactory.h:49
nta::utils::IDFactory::clear
void clear()
Resets this to a new IDFactory.
Definition: IDFactory.h:23
nta::utils::IDFactory::get_count
std::size_t get_count() const
Returns the number of active ids.
Definition: IDFactory.h:41
nta::utils::IDFactory::operator()
T operator()()
Calls (and returns) gen_id.
Definition: IDFactory.h:46