$darkmode
uid_tracker.hpp
Go to the documentation of this file.
1 /*
2  * Copyright 2020 Robert Bosch GmbH
3  *
4  * Licensed under the Apache License, Version 2.0 (the "License");
5  * you may not use this file except in compliance with the License.
6  * You may obtain a copy of the License at
7  *
8  * http://www.apache.org/licenses/LICENSE-2.0
9  *
10  * Unless required by applicable law or agreed to in writing, software
11  * distributed under the License is distributed on an "AS IS" BASIS,
12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  * See the License for the specific language governing permissions and
14  * limitations under the License.
15  *
16  * SPDX-License-Identifier: Apache-2.0
17  */
29 #pragma once
30 
31 #include <cassert> // for assert
32 #include <functional> // for std::function
33 #include <map> // for std::map
34 #include <memory> // for std::shared_ptr
35 #include <set> // for std::set
36 #include <vector> // for std::vector
37 
38 namespace cloe {
39 namespace utility {
40 
60  // Tracklet is used internally
61  struct Tracklet {
62  int in_id;
63  int out_id;
64  int age;
65  };
66 
67  int ttl_; // time to live before reusing
68  std::map<int, std::shared_ptr<Tracklet>> assigned_;
69  std::set<int> free_;
70  std::vector<std::function<void(int in_id, int out_id)>> observers_;
71 
72  public:
78  UniqueIDTracker(int min, int max, int ttl = 1) : ttl_(ttl) {
79  assert(min < max);
80  assert(ttl_ >= 1); // TODO(unknown): perhaps 0 is ok too
81 
82  for (int i = min; i <= max; i++) {
83  free_.insert(i);
84  }
85  }
86 
87  virtual ~UniqueIDTracker() = default;
88 
102  int assign(int id);
103 
108  void next_cycle();
109 
114  void add_delete_observer(void f(int in_id, int out_id)) { observers_.emplace_back(f); }
115 };
116 
117 } // namespace utility
118 } // namespace cloe
Definition: uid_tracker.hpp:59
UniqueIDTracker(int min, int max, int ttl=1)
Definition: uid_tracker.hpp:78
void next_cycle()
Definition: uid_tracker.cpp:62
void add_delete_observer(void f(int in_id, int out_id))
Definition: uid_tracker.hpp:114
int assign(int id)
Definition: uid_tracker.cpp:38