Instrument Neutral Distributed Interface INDI 2.2.5
ConcurrentSet.hpp
Go to the documentation of this file.
1/* INDI Server for protocol version 1.7.
2 * Copyright (C) 2007 Elwood C. Downey <[email protected]>
3 2013 Jasem Mutlaq <[email protected]>
4 2022 Ludovic Pollet
5 This library is free software; you can redistribute it and/or
6 modify it under the terms of the GNU Lesser General Public
7 License as published by the Free Software Foundation; either
8 version 2.1 of the License, or (at your option) any later version.
9
10 This library is distributed in the hope that it will be useful,
11 but WITHOUT ANY WARRANTY; without even the implied warranty of
12 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
13 Lesser General Public License for more details.
14
15 You should have received a copy of the GNU Lesser General Public
16 License along with this library; if not, write to the Free Software
17 Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
18*/
19
20#pragma once
21
22#include <map>
23#include <vector>
24
25template<class M>
27{
28 unsigned long identifier = 1;
29 std::map<unsigned long, M*> items;
30
31 public:
32 void insert(M* item)
33 {
34 item->id = identifier++;
35 items[item->id] = item;
36 item->current = (ConcurrentSet<void>*)this;
37 }
38
39 void erase(M* item)
40 {
41 items.erase(item->id);
42 item->id = 0;
43 item->current = nullptr;
44 }
45
46 std::vector<unsigned long> ids() const
47 {
48 std::vector<unsigned long> result;
49 for(auto item : items)
50 {
51 result.push_back(item.first);
52 }
53 return result;
54 }
55
56 M* operator[](unsigned long id) const
57 {
58 auto e = items.find(id);
59 if (e == items.end())
60 {
61 return nullptr;
62 }
63 return e->second;
64 }
65
67 {
68 friend class ConcurrentSet<M>;
69 const ConcurrentSet<M> * parent;
70 std::vector<unsigned long> ids;
71 // Will be -1 when done
72 long int pos = 0;
73
74 void skip()
75 {
76 if (pos == -1) return;
77 while(pos < (long int)ids.size() && !(*parent)[ids[pos]])
78 {
79 pos++;
80 }
81 if (pos == (long int)ids.size())
82 {
83 pos = -1;
84 }
85 }
86 public:
87 iterator(const ConcurrentSet<M> * parent) : parent(parent) {}
88
89 bool operator!=(const iterator &o)
90 {
91 return pos != o.pos;
92 }
93
95 {
96 if (pos != -1)
97 {
98 pos++;
99 skip();
100 }
101 return *this;
102 }
103
104 M * operator*() const
105 {
106 return (*parent)[ids[pos]];
107 }
108 };
109
111 {
112 iterator result(this);
113 for(auto item : items)
114 {
115 result.ids.push_back(item.first);
116 }
117 result.skip();
118 return result;
119 }
120
121 iterator end() const
122 {
123 iterator result(nullptr);
124 result.pos = -1;
125 return result;
126 }
127};
128
bool operator!=(const iterator &o)
iterator(const ConcurrentSet< M > *parent)
iterator end() const
M * operator[](unsigned long id) const
iterator begin() const
void erase(M *item)
void insert(M *item)
std::vector< unsigned long > ids() const