2014-11-15 15:16:18 +01:00
|
|
|
#pragma once
|
2014-11-16 00:05:28 +01:00
|
|
|
#ifndef FSPP_FUSE_IDLIST_H_
|
|
|
|
#define FSPP_FUSE_IDLIST_H_
|
2014-11-15 15:16:18 +01:00
|
|
|
|
|
|
|
#include <map>
|
|
|
|
#include <mutex>
|
2014-11-16 02:42:34 +01:00
|
|
|
#include <stdexcept>
|
2015-06-21 17:44:30 +02:00
|
|
|
#include <messmer/cpp-utils/pointer/unique_ref.h>
|
2014-11-15 15:16:18 +01:00
|
|
|
|
2014-11-16 00:05:28 +01:00
|
|
|
namespace fspp {
|
2014-11-15 15:16:18 +01:00
|
|
|
|
|
|
|
template<class Entry>
|
|
|
|
class IdList {
|
|
|
|
public:
|
|
|
|
IdList();
|
|
|
|
virtual ~IdList();
|
|
|
|
|
2015-06-18 19:30:52 +02:00
|
|
|
int add(cpputils::unique_ref<Entry> entry);
|
2014-11-15 15:16:18 +01:00
|
|
|
Entry *get(int id);
|
|
|
|
const Entry *get(int id) const;
|
|
|
|
void remove(int id);
|
|
|
|
private:
|
2015-06-18 19:30:52 +02:00
|
|
|
std::map<int, cpputils::unique_ref<Entry>> _entries;
|
2014-11-15 15:16:18 +01:00
|
|
|
int _id_counter;
|
|
|
|
mutable std::mutex _mutex;
|
|
|
|
|
|
|
|
DISALLOW_COPY_AND_ASSIGN(IdList<Entry>)
|
|
|
|
};
|
|
|
|
|
|
|
|
template<class Entry>
|
|
|
|
IdList<Entry>::IdList()
|
|
|
|
: _entries(), _id_counter(0), _mutex() {
|
|
|
|
}
|
|
|
|
|
|
|
|
template<class Entry>
|
|
|
|
IdList<Entry>::~IdList() {
|
|
|
|
}
|
|
|
|
|
|
|
|
template<class Entry>
|
2015-06-18 19:30:52 +02:00
|
|
|
int IdList<Entry>::add(cpputils::unique_ref<Entry> entry) {
|
2014-11-15 15:16:18 +01:00
|
|
|
std::lock_guard<std::mutex> lock(_mutex);
|
|
|
|
//TODO Reuse IDs (ids = descriptors)
|
|
|
|
int new_id = ++_id_counter;
|
2015-06-18 19:30:52 +02:00
|
|
|
_entries.insert(std::make_pair(new_id, std::move(entry)));
|
2014-11-15 15:16:18 +01:00
|
|
|
return new_id;
|
|
|
|
}
|
|
|
|
|
|
|
|
template<class Entry>
|
|
|
|
Entry *IdList<Entry>::get(int id) {
|
|
|
|
return const_cast<Entry*>(const_cast<const IdList<Entry>*>(this)->get(id));
|
|
|
|
}
|
|
|
|
|
|
|
|
template<class Entry>
|
|
|
|
const Entry *IdList<Entry>::get(int id) const {
|
|
|
|
std::lock_guard<std::mutex> lock(_mutex);
|
|
|
|
const Entry *result = _entries.at(id).get();
|
|
|
|
return result;
|
|
|
|
}
|
|
|
|
|
|
|
|
template<class Entry>
|
|
|
|
void IdList<Entry>::remove(int id) {
|
|
|
|
std::lock_guard<std::mutex> lock(_mutex);
|
2014-11-16 02:42:34 +01:00
|
|
|
auto found_iter = _entries.find(id);
|
|
|
|
if (found_iter == _entries.end()) {
|
|
|
|
throw std::out_of_range("Called IdList::remove() with an invalid ID");
|
|
|
|
}
|
|
|
|
_entries.erase(found_iter);
|
2014-11-15 15:16:18 +01:00
|
|
|
}
|
|
|
|
|
2014-11-16 00:10:29 +01:00
|
|
|
} /* namespace fspp */
|
2014-11-15 15:16:18 +01:00
|
|
|
|
2014-11-16 00:05:28 +01:00
|
|
|
#endif /* FSPP_FUSE_IDLIST_H_ */
|