CMS 3D CMS Logo

AtomicId.cc
Go to the documentation of this file.
1 #include <algorithm>
2 #include <cstddef>
3 #include <cstdlib>
4 #include <cstring>
5 #include <mutex>
6 #include <set>
7 
10 
11 namespace { // anonymous
12  struct StringLess {
13  bool operator()(const char *id1, const char *id2) const { return std::strcmp(id1, id2) < 0; }
14  };
15 
16  class IdCache {
17  public:
18  ~IdCache();
19 
20  inline const char *findOrInsert(const char *string) throw();
21 
22  private:
23  typedef std::multiset<const char *, StringLess> IdSet;
24 
25  IdSet idSet;
26  std::allocator<char> stringAllocator;
28  };
29 } // anonymous namespace
30 
31 IdCache::~IdCache() {
32  for (std::multiset<const char *, StringLess>::iterator iter = idSet.begin(); iter != idSet.end(); iter++)
33  stringAllocator.deallocate(const_cast<char *>(*iter), std::strlen(*iter) + 1);
34 }
35 
36 const char *IdCache::findOrInsert(const char *string) throw() {
37  std::lock_guard<std::mutex> scoped_lock(mutex);
38 
39  IdSet::iterator pos = idSet.lower_bound(string);
40  if (pos != idSet.end() && std::strcmp(*pos, string) == 0)
41  return *pos;
42 
43  std::size_t size = std::strlen(string) + 1;
44  char *unique = stringAllocator.allocate(size);
45  std::memcpy(unique, string, size);
46 
47  idSet.insert(pos, unique);
48 
49  return unique;
50 }
51 
52 namespace PhysicsTools {
53 
54  static IdCache &getAtomicIdCache() {
55  CMS_THREAD_SAFE static IdCache atomicIdCache;
56  return atomicIdCache;
57  }
58 
59  const char *AtomicId::lookup(const char *string) throw() {
60  if (string)
61  return getAtomicIdCache().findOrInsert(string);
62 
63  return nullptr;
64  }
65 
66 } // namespace PhysicsTools
size
Write out results.
static std::mutex mutex
Definition: Proxy.cc:8
static IdCache & getAtomicIdCache()
Definition: AtomicId.cc:54
static const char * lookup(const char *arg)
Definition: AtomicId.cc:59
Value & findOrInsert(std::map< Key, Value > &m, Key const &k)
Definition: Map.h:16
def unique(seq, keepstr=True)
Definition: tier0.py:24
#define CMS_THREAD_SAFE