libpromeki 1.0.0-alpha
PROfessional MEdia toolKIt
 
Loading...
Searching...
No Matches
structdatabase.h
Go to the documentation of this file.
1
8#pragma once
9
10
11#include <promeki/config.h>
12#if PROMEKI_ENABLE_CORE
13#include <promeki/namespace.h>
14#include <promeki/string.h>
15#include <promeki/map.h>
16#include <promeki/result.h>
17#include <promeki/error.h>
18
19PROMEKI_NAMESPACE_BEGIN
20
42template <typename KeyType, typename StructType> class StructDatabase {
43 public:
44 using Database = ::promeki::Map<KeyType, StructType>;
45 using NameDatabase = ::promeki::Map<String, KeyType>;
46
48 StructDatabase() = default;
49
52 StructDatabase(std::initializer_list<StructType> list) { load(list); }
53
56 void add(const StructType &val) {
57 _db[val.id] = val;
58 _nameDb[val.name] = val.id;
59 return;
60 }
61
65 const StructType &get(const KeyType &id) const {
66 auto it = _db.find(id);
67 if (it != _db.end()) return it->second;
68 it = _db.find(static_cast<KeyType>(0));
69 if (it != _db.end()) return it->second;
70 static const StructType fallback{};
71 return fallback;
72 }
73
78 Result<KeyType> lookupKeyByName(const String &name) const {
79 auto it = _nameDb.find(name);
80 if (it == _nameDb.end()) return Result<KeyType>(KeyType{}, Error::NotFound);
81 return Result<KeyType>(it->second, Error::Ok);
82 }
83
86 void load(std::initializer_list<StructType> list) {
87 for (const auto &item : list) add(item);
88 return;
89 }
90
92 const Database &database() const { return _db; }
94 Database &database() { return _db; }
95
96 private:
97 Database _db;
98 NameDatabase _nameDb;
99};
100
101PROMEKI_NAMESPACE_END
102
103#endif // PROMEKI_ENABLE_CORE