From 8fba1c8a02f8680e0d80279b8b6451fea4a40a62 Mon Sep 17 00:00:00 2001 From: Hop311 Date: Tue, 25 Apr 2023 00:03:15 +0100 Subject: Req comments + cleanup + c++ registry refactoring --- extension/src/openvic2/Types.hpp | 62 ++++++++++++++++++++++++++++++++++++++++ 1 file changed, 62 insertions(+) (limited to 'extension/src/openvic2/Types.hpp') diff --git a/extension/src/openvic2/Types.hpp b/extension/src/openvic2/Types.hpp index b20db10..226dd30 100644 --- a/extension/src/openvic2/Types.hpp +++ b/extension/src/openvic2/Types.hpp @@ -17,4 +17,66 @@ namespace OpenVic2 { public: std::string const& get_identifier() const; }; + + template::value>::type* = nullptr> + class IdentifierRegistry { + std::vector items; + bool locked = false; + public: + return_t add_item(T&& item) { + if (locked) { + Logger::error("Cannot add item to the ", name, " registry - locked!"); + return FAILURE; + } + if (item.get_identifier().empty()) { + Logger::error("Cannot add item to the ", name, " registry - empty identifier!"); + return FAILURE; + } + T const* old_item = get_item_by_identifier(item.get_identifier()); + if (old_item != nullptr) { + Logger::error("Cannot add item to the ", name, " registry - an item with the identifier \"", item.get_identifier(), "\" already exists!"); + return FAILURE; + } + items.push_back(item); + return SUCCESS; + } + void lock() { + if (locked) { + Logger::error("Failed to lock ", name, " registry - already locked!"); + } else { + locked = true; + Logger::info("Locked ", name, " registry after registering ", get_item_count(), " items"); + } + } + bool is_locked() const { + return locked; + } + size_t get_item_count() const { + return items.size(); + } + T* get_item_by_identifier(std::string const& identifier) { + if (!identifier.empty()) + for (T& item : items) + if (item.get_identifier() == identifier) return &item; + return nullptr; + } + T const* get_item_by_identifier(std::string const& identifier) const { + if (!identifier.empty()) + for (T const& item : items) + if (item.get_identifier() == identifier) return &item; + return nullptr; + } + T* get_item_by_index(size_t index) { + return index < items.size() ? &items[index] : nullptr; + } + T const* get_item_by_index(size_t index) const { + return index < items.size() ? &items[index] : nullptr; + } + std::vector& get_items() { + return items; + } + std::vector const& get_items() const { + return items; + } + }; } -- cgit v1.2.3-56-ga3b1