// ========================================================= //
//                                                           //
//   File      : StrUniquifier.h                             //
//   Purpose   : generate fast + quite unique IDs            //
//                                                           //
//   Coded by Ralf Westram (coder@reallysoft.de) in Jun 19   //
//   http://www.arb-home.de/                                 //
//                                                           //
// ========================================================= //

#ifndef STRUNIQUIFIER_H
#define STRUNIQUIFIER_H

#ifndef ARBTOOLS_H
#include <arbtools.h>
#endif
#ifndef ARB_STRBUF_H
#include "arb_strbuf.h"
#endif
#ifndef _GLIBCXX_MAP
#include <map>
#endif

class StrUniquifier : virtual Noncopyable {
    // keys passed to make_unique_key have to exist until destruction of StrUniquifier.
    // keys are NOT strongly guaranteed to be unique.

    typedef std::map<const char *, int, charpLess> KeyOccur;

    KeyOccur       occurred;
    char          *separator;
    GBS_strstruct  buffer;

public:
    StrUniquifier(const char *separator_ = "_") :
        separator(strdup(separator_))
    {}
    ~StrUniquifier() {
        free(separator);
    }

    const char *make_unique_key(const char *key) {
        KeyOccur::iterator found = occurred.find(key);
        int                count = 1;
        if (found == occurred.end()) {
            occurred[key] = count;
        }
        else {
            count = ++found->second;
        }

        buffer.erase();
        buffer.cat(key);
        if (count>1) {
            buffer.cat(separator);
            buffer.putlong(count);
        }
        return buffer.get_data(); // valid until next call of make_unique_key()
    }

    void clear() { occurred.clear(); }
};


#else
#error StrUniquifier.h included twice
#endif // STRUNIQUIFIER_H
