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
14  { return std::strcmp(id1, id2) < 0; }
15  };
16 
17  class IdCache {
18  public:
19  ~IdCache();
20 
21  inline const char *findOrInsert(const char *string) throw();
22 
23  private:
24  typedef std::multiset<const char *, StringLess> IdSet;
25 
26  IdSet idSet;
27  std::allocator<char> stringAllocator;
29  };
30 } // anonymous namespace
31 
32 IdCache::~IdCache()
33 {
34  for(std::multiset<const char*, StringLess>::iterator iter =
35  idSet.begin(); iter != idSet.end(); iter++)
36  stringAllocator.deallocate(const_cast<char*>(*iter),
37  std::strlen(*iter));
38 }
39 
40 const char *IdCache::findOrInsert(const char *string) throw()
41 {
42  std::lock_guard<std::mutex> scoped_lock(mutex);
43 
44  IdSet::iterator pos = idSet.lower_bound(string);
45  if (pos != idSet.end() && std::strcmp(*pos, string) == 0)
46  return *pos;
47 
48  std::size_t size = std::strlen(string) + 1;
49  char *unique = stringAllocator.allocate(size);
50  std::memcpy(unique, string, size);
51 
52  idSet.insert(pos, unique);
53 
54  return unique;
55 }
56 
57 namespace PhysicsTools {
58 
59 static IdCache &getAtomicIdCache()
60 {
61  CMS_THREAD_SAFE static IdCache atomicIdCache;
62  return atomicIdCache;
63 }
64 
65 const char *AtomicId::lookup(const char *string) throw()
66 {
67  if (string)
68  return getAtomicIdCache().findOrInsert(string);
69 
70  return nullptr;
71 }
72 
73 } // namespace PhysicsTools
size
Write out results.
static boost::mutex mutex
Definition: Proxy.cc:11
static IdCache & getAtomicIdCache()
Definition: AtomicId.cc:59
Value & findOrInsert(std::map< Key, Value > &m, Key const &k)
Definition: Map.h:18
def unique(seq, keepstr=True)
Definition: tier0.py:24
#define CMS_THREAD_SAFE