Add util::resource_container - a simple name+id-based container
This commit is contained in:
parent
9b18e664e8
commit
55c3266343
1 changed files with 88 additions and 0 deletions
88
libs/util/include/psemek/util/resource_container.hpp
Normal file
88
libs/util/include/psemek/util/resource_container.hpp
Normal file
|
|
@ -0,0 +1,88 @@
|
|||
#pragma once
|
||||
|
||||
#include <psemek/util/hash.hpp>
|
||||
|
||||
#include <vector>
|
||||
#include <string>
|
||||
#include <string_view>
|
||||
#include <cstdint>
|
||||
#include <unordered_map>
|
||||
#include <optional>
|
||||
|
||||
namespace psemek::util
|
||||
{
|
||||
|
||||
template <typename T, typename Index = std::uint32_t>
|
||||
struct resource_container
|
||||
{
|
||||
using object_id = Index;
|
||||
using iterator = T *;
|
||||
using const_iterator = T const *;
|
||||
|
||||
struct object
|
||||
{
|
||||
std::string const name;
|
||||
T value;
|
||||
|
||||
object(std::string name, T value)
|
||||
: name(std::move(name))
|
||||
, value(std::move(value))
|
||||
{}
|
||||
};
|
||||
|
||||
object & operator[] (Index id)
|
||||
{
|
||||
return objects_[id];
|
||||
}
|
||||
|
||||
object const & operator[] (Index id) const
|
||||
{
|
||||
return objects_[id];
|
||||
}
|
||||
|
||||
Index add(std::string name, T value)
|
||||
{
|
||||
Index id = objects_.size();
|
||||
name_map_[name] = id;
|
||||
objects_.emplace_back(std::move(name), std::move(value));
|
||||
return id;
|
||||
}
|
||||
|
||||
std::optional<object_id> find(std::string_view const & name) const
|
||||
{
|
||||
if (auto it = name_map_.find(name); it != name_map_.end())
|
||||
return it->second;
|
||||
return std::nullopt;
|
||||
}
|
||||
|
||||
std::size_t size() const
|
||||
{
|
||||
return objects_.size();
|
||||
}
|
||||
|
||||
T * begin()
|
||||
{
|
||||
return objects_.data();
|
||||
}
|
||||
|
||||
T * end()
|
||||
{
|
||||
return begin() + size();
|
||||
}
|
||||
|
||||
T const * begin() const
|
||||
{
|
||||
return objects_.data();
|
||||
}
|
||||
|
||||
T const * end() const
|
||||
{
|
||||
return begin() + size();
|
||||
}
|
||||
|
||||
private:
|
||||
std::vector<object> objects_;
|
||||
std::unordered_map<std::string, Index, any_hash, std::equal_to<>> name_map_;
|
||||
};
|
||||
|
||||
}
|
||||
Loading…
Add table
Reference in a new issue