Spicy
uniquer.h
1 // Copyright (c) 2020-now by the Zeek Project. See LICENSE for details.
2 
3 #pragma once
4 
5 #include <hilti/base/cache.h>
6 #include <hilti/base/util.h>
7 
8 namespace hilti::util {
9 
14 template<typename ID>
15 class Uniquer : private Cache<ID, bool> {
16 public:
25  ID get(ID name, bool normalize = true) {
26  if ( normalize )
27  name = ID(util::toIdentifier(name));
28 
29  auto x = name;
30  int i = 1;
31  while ( true ) {
32  if ( ! this->has(x) ) {
33  this->put(x, true);
34  return x;
35  }
36 
37  x = ID(util::fmt("%s_%d", name, ++i));
38  }
39  }
40 
42  void remove(const ID& id) { this->Cache<ID, bool>::remove(id); }
43 };
44 
45 } // namespace hilti::util
Definition: id.h:15
Definition: cache.h:13
bool has(const ID &key) const
Definition: cache.h:18
void remove(const Key &key)
Definition: cache.h:69
const bool & put(const ID &key, bool value)
Definition: cache.h:66
Definition: uniquer.h:15
void remove(const ID &id)
Definition: uniquer.h:42
ID get(ID name, bool normalize=true)
Definition: uniquer.h:25