Bitstream Interpretation Library (BIL)  0.1
DeviceRegistry.cpp
Go to the documentation of this file.
1 
6 #include <iterator>
7 #include <utility>
10 
11 using namespace bil;
12 
13 
15 {
16 
17 }
18 
19 
20 void DeviceRegistry::insert(DeviceID::ID_t deviceID, const std::string& deviceName)
21 {
22  // device name must not be empty
23  if (0 == deviceID) throw Exception();
24  if (deviceName.empty()) throw Exception();
25 
26  // check if ID is already in use
27  IDMap_t::iterator lbID = m_idMap.lower_bound(deviceID);
28  if ((m_idMap.end() != lbID) && (deviceID == lbID->first)) throw Exception();
29 
30  // check if name is already in use
31  NameMap_t::iterator lbName = m_nameMap.lower_bound(deviceName);
32  if ((m_nameMap.end() != lbName) && (deviceName == lbName->first)) throw Exception();
33 
34  // insert device info into both maps
35  m_idMap.insert(lbID, std::make_pair(deviceID, deviceName));
36  m_nameMap.insert(lbName, std::make_pair(deviceName, deviceID));
37 }
38 
39 
41 {
42  // search given ID in ID map
43  IDMap_t::iterator itID = m_idMap.find(deviceID);
44  if (m_idMap.end() == itID) return false;
45 
46  // search for ID's name in name map
47  NameMap_t::iterator itName = m_nameMap.find(itID->second);
48 
49  // delete entries from both maps
50  m_idMap.erase(itID);
51  m_nameMap.erase(itName);
52  return true;
53 }
54 
55 
56 bool DeviceRegistry::erase(const std::string& deviceName)
57 {
58  // search given name in name map
59  NameMap_t::iterator itName = m_nameMap.find(deviceName);
60  if (m_nameMap.end() == itName) return false;
61 
62  // search for name's ID in ID map
63  IDMap_t::iterator itID = m_idMap.find(itName->second);
64 
65  // delete entries from both maps
66  m_idMap.erase(itID);
67  m_nameMap.erase(itName);
68  return true;
69 }
70 
71 
73 {
74  m_idMap.clear();
75  m_nameMap.clear();
76 }
77 
78 
79 size_t DeviceRegistry::size() const
80 {
81  return m_idMap.size();
82 }
83 
84 
85 const DeviceRegistry::pair_t& DeviceRegistry::at(size_t index) const
86 {
87  // check if index is in valid range
88  if (m_idMap.size() <= index) throw Exception();
89  // get map entry at index
90  IDMap_t::const_iterator it = m_idMap.begin();
91  std::advance(it, index);
92  return *it;
93 }
94 
95 
96 std::string DeviceRegistry::lookup(DeviceID::ID_t deviceID) const
97 {
98  // search for ID in map
99  IDMap_t::const_iterator it = m_idMap.find(deviceID);
100  // if found, return device name copy; else return an empty string
101  if (m_idMap.end() == it) return std::string();
102  return it->second;
103 }
104 
105 
106 DeviceID::ID_t DeviceRegistry::lookup(const std::string& deviceName) const
107 {
108  // search for ID in map
109  NameMap_t::const_iterator it = m_nameMap.find(deviceName);
110  // if found, return device ID; else return 0
111  if (m_nameMap.end() == it) return 0;
112  return it->second;
113 }