Program Listing for File registry.h#

↰ Return to documentation for file (include/nodes-graph/registry.h)

#pragma once


#include <cstddef>
#include <map>
#include <utility>
#include <vector>


namespace ng {

    template <typename Key, typename Value>
    class Registry {
    public:
        using map_type       = std::map<Key, Value>;
        using iterator       = typename map_type::iterator;
        using const_iterator = typename map_type::const_iterator;

    private:
        map_type entries_;

    public:
        Registry() = default;
        Registry(const Registry&) = delete;
        Registry& operator=(const Registry&) = delete;

        // --- Registration

        bool register_entry(Key key, Value value) {
            return entries_.emplace(std::move(key), std::move(value)).second;
        }

        bool register_entries(std::vector<std::pair<Key, Value>> list) {
            std::size_t count = 0;
            for (auto& item : list) {
                count += register_entry(std::move(item.first), std::move(item.second)) ? 1 : 0;
            }
            return count == list.size();
        }

        // --- Getters

        inline const Value& get(const Key& key) const { return entries_.at(key); }

        inline Value get_safe(const Key& key, Value default_value) const {
            auto it = entries_.find(key);
            return (it != entries_.end()) ? it->second : default_value;
        }

        inline bool contains(const Key& key) const { return entries_.find(key) != entries_.end(); }
        inline std::size_t size() const { return entries_.size(); }
        inline const map_type& get_all() const { return entries_; }

        // --- Iteration

        inline iterator find(const Key& key) { return entries_.find(key); }
        inline const_iterator find(const Key& key) const { return entries_.find(key); }

        inline iterator begin() { return entries_.begin(); }
        inline const_iterator begin() const { return entries_.begin(); }
        inline iterator end() { return entries_.end(); }
        inline const_iterator end() const { return entries_.end(); }

        // --- Singleton

        static Registry<Key, Value>& instance() {
            static Registry<Key, Value> registry;
            return registry;
        }
    };

} // namespace ng