-
Notifications
You must be signed in to change notification settings - Fork 6
/
Copy pathStringIdentifier.cpp
74 lines (64 loc) · 1.92 KB
/
StringIdentifier.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
/*
This file is part of the Util library.
Copyright (C) 2007-2014 Benjamin Eikel <[email protected]>
Copyright (C) 2007-2012 Claudius Jähn <[email protected]>
Copyright (C) 2007-2012 Ralf Petring <[email protected]>
This library is subject to the terms of the Mozilla Public License, v. 2.0.
You should have received a copy of the MPL along with this library; see the
file LICENSE. If not, you can obtain one at http://mozilla.org/MPL/2.0/.
*/
#include "StringIdentifier.h"
#include <memory>
#include <mutex>
#include <sstream>
#include <unordered_map>
namespace Util {
typedef std::unordered_map<uint32_t, std::string> stringIdTable_t;
static stringIdTable_t & getStringIdTable() {
static std::unique_ptr<stringIdTable_t> stringIdTable(new stringIdTable_t);
return *stringIdTable.get();
}
static std::mutex & getLookupTableMutex() {
static std::mutex mutex;
return mutex;
}
uint32_t StringIdentifier::calcId(const std::string & s) {
uint32_t id = calcHash(s);
std::lock_guard<std::mutex> lock(getLookupTableMutex());
stringIdTable_t & stringIdTable = getStringIdTable();
while (true) {
auto entry = stringIdTable.find(id);
if (entry == stringIdTable.cend()) {
// id not found -> insert it
stringIdTable.emplace(id, s);
break;
} else if (s == entry->second) {
// same string already inserted
break;
} else {
// collision
++id;
}
}
return id;
}
std::string StringIdentifier::toString() const {
std::lock_guard<std::mutex> lock(getLookupTableMutex());
stringIdTable_t & stringIdTable = getStringIdTable();
auto entry = stringIdTable.find(value);
if (entry == stringIdTable.cend()) {
std::stringstream s;
s << "_strId_" << value;
stringIdTable[value] = s.str();
return s.str();
}
return entry->second;
}
uint32_t StringIdentifier::calcHash(const std::string & s) {
uint32_t h = 0;
for(const auto & c : s) {
h ^= (((static_cast<uint32_t>(c) + h) * 1234393) % 0xffffff);
}
return h;
}
}