CMS 3D CMS Logo

 All Classes Namespaces Files Functions Variables Typedefs Enumerations Enumerator Properties Friends Macros Pages
AtomicId.cc
Go to the documentation of this file.
1 #include <algorithm>
2 #include <cstdlib>
3 #include <cstddef>
4 #include <cstring>
5 #include <set>
6 
7 #include <mutex>
8 
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  static std::allocator<char> stringAllocator;
28  mutable std::mutex mutex;
29  };
30 } // anonymous namespace
31 
32 std::allocator<char> IdCache::stringAllocator;
33 
34 IdCache::~IdCache()
35 {
36  for(std::multiset<const char*, StringLess>::iterator iter =
37  idSet.begin(); iter != idSet.end(); iter++)
38  stringAllocator.deallocate(const_cast<char*>(*iter),
39  std::strlen(*iter));
40 }
41 
42 const char *IdCache::findOrInsert(const char *string) throw()
43 {
44  std::lock_guard<std::mutex> scoped_lock(mutex);
45 
46  IdSet::iterator pos = idSet.lower_bound(string);
47  if (pos != idSet.end() && std::strcmp(*pos, string) == 0)
48  return *pos;
49 
50  std::size_t size = std::strlen(string) + 1;
51  char *unique = stringAllocator.allocate(size);
52  std::memcpy(unique, string, size);
53 
54  idSet.insert(pos, unique);
55 
56  return unique;
57 }
58 
59 namespace PhysicsTools {
60 
61 static IdCache &getAtomicIdCache()
62 {
63  [[cms::thread_safe]] static IdCache atomicIdCache;
64  return atomicIdCache;
65 }
66 
67 const char *AtomicId::lookup(const char *string) throw()
68 {
69  if (string)
70  return getAtomicIdCache().findOrInsert(string);
71 
72  return 0;
73 }
74 
75 } // namespace PhysicsTools
static boost::mutex mutex
Definition: LHEProxy.cc:11
static IdCache & getAtomicIdCache()
Definition: AtomicId.cc:61
static const char * lookup(const char *arg)
Definition: AtomicId.cc:67
Value & findOrInsert(std::map< Key, Value > &m, Key const &k)
Definition: Map.h:18
tuple size
Write out results.