ARB
StrUniquifier.h
Go to the documentation of this file.
1 // ========================================================= //
2 // //
3 // File : StrUniquifier.h //
4 // Purpose : generate fast + quite unique IDs //
5 // //
6 // Coded by Ralf Westram (coder@reallysoft.de) in Jun 19 //
7 // http://www.arb-home.de/ //
8 // //
9 // ========================================================= //
10 
11 #ifndef STRUNIQUIFIER_H
12 #define STRUNIQUIFIER_H
13 
14 #ifndef ARBTOOLS_H
15 #include <arbtools.h>
16 #endif
17 #ifndef ARB_STRBUF_H
18 #include "arb_strbuf.h"
19 #endif
20 #ifndef _GLIBCXX_MAP
21 #include <map>
22 #endif
23 
24 class StrUniquifier : virtual Noncopyable {
25  // keys passed to make_unique_key have to exist until destruction of StrUniquifier.
26  // keys are NOT strongly guaranteed to be unique.
27 
28  typedef std::map<const char *, int, charpLess> KeyOccur;
29 
30  KeyOccur occurred;
31  char *separator;
32  GBS_strstruct buffer;
33 
34 public:
35  StrUniquifier(const char *separator_ = "_") :
36  separator(strdup(separator_))
37  {}
39  free(separator);
40  }
41 
42  const char *make_unique_key(const char *key) {
43  KeyOccur::iterator found = occurred.find(key);
44  int count = 1;
45  if (found == occurred.end()) {
46  occurred[key] = count;
47  }
48  else {
49  count = ++found->second;
50  }
51 
52  buffer.erase();
53  buffer.cat(key);
54  if (count>1) {
55  buffer.cat(separator);
56  buffer.putlong(count);
57  }
58  return buffer.get_data(); // valid until next call of make_unique_key()
59  }
60 
61  void clear() { occurred.clear(); }
62 };
63 
64 
65 #else
66 #error StrUniquifier.h included twice
67 #endif // STRUNIQUIFIER_H
StrUniquifier(const char *separator_="_")
Definition: StrUniquifier.h:35
void erase()
Definition: arb_strbuf.h:141
void cat(const char *from)
Definition: arb_strbuf.h:199
void putlong(long l)
Definition: arb_strbuf.h:240
const char * get_data() const
Definition: arb_strbuf.h:120
const char * make_unique_key(const char *key)
Definition: StrUniquifier.h:42