Spicy
uniquer.h
1 // Copyright (c) 2020-2021 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 = 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 = 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
bool has(const ID &key) const
Definition: cache.h:23
Definition: cache.h:11
void remove(const Key &key)
Definition: cache.h:72
std::string fmt(const char *fmt, const Args &... args)
Definition: util.h:80
Definition: cache.h:15
Definition: uniquer.h:15
Definition: id.h:18
std::string toIdentifier(const std::string &s, bool ensure_non_keyword=false)
Definition: util.cc:194
const bool & put(const ID &key, bool value)
Definition: cache.h:69