|
Last change
on this file was
17909,
checked in by westram, 6 years ago
|
- refactored KeyOccur into new class StrUniquifier (in CORE).
- really compare strings (not only pointers to keys; did only work by luck).
- document restrictions.
- make_unique_key return pointer to static buffer (valid until next call).
- allow to define string to separate key and counter.
- only change key when duplicated.
|
|
File size:
1.9 KB
|
| Line | |
|---|
| 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 | {} |
|---|
| 38 | ~StrUniquifier() { |
|---|
| 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 |
|---|
Note: See
TracBrowser
for help on using the repository browser.