forked from cms-sw/cmssw
/
AtomicId.cc
75 lines (56 loc) · 1.6 KB
/
AtomicId.cc
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
75
#include <algorithm>
#include <cstdlib>
#include <cstddef>
#include <cstring>
#include <set>
#include <mutex>
#include "PhysicsTools/MVAComputer/interface/AtomicId.h"
namespace { // anonymous
struct StringLess {
bool operator()(const char *id1, const char *id2) const
{ return std::strcmp(id1, id2) < 0; }
};
class IdCache {
public:
~IdCache();
inline const char *findOrInsert(const char *string) throw();
private:
typedef std::multiset<const char *, StringLess> IdSet;
IdSet idSet;
static std::allocator<char> stringAllocator;
mutable std::mutex mutex;
};
} // anonymous namespace
std::allocator<char> IdCache::stringAllocator;
IdCache::~IdCache()
{
for(std::multiset<const char*, StringLess>::iterator iter =
idSet.begin(); iter != idSet.end(); iter++)
stringAllocator.deallocate(const_cast<char*>(*iter),
std::strlen(*iter));
}
const char *IdCache::findOrInsert(const char *string) throw()
{
std::lock_guard<std::mutex> scoped_lock(mutex);
IdSet::iterator pos = idSet.lower_bound(string);
if (pos != idSet.end() && std::strcmp(*pos, string) == 0)
return *pos;
std::size_t size = std::strlen(string) + 1;
char *unique = stringAllocator.allocate(size);
std::memcpy(unique, string, size);
idSet.insert(pos, unique);
return unique;
}
namespace PhysicsTools {
static IdCache &getAtomicIdCache()
{
[[cms::thread_safe]] static IdCache atomicIdCache;
return atomicIdCache;
}
const char *AtomicId::lookup(const char *string) throw()
{
if (string)
return getAtomicIdCache().findOrInsert(string);
return 0;
}
} // namespace PhysicsTools