Skip to content

Commit

Permalink
enforce unique constraint on property id
Browse files Browse the repository at this point in the history
  • Loading branch information
kr0ner committed Nov 26, 2024
1 parent 17d05cb commit 580912e
Showing 1 changed file with 23 additions and 18 deletions.
41 changes: 23 additions & 18 deletions src/property.h
Original file line number Diff line number Diff line change
Expand Up @@ -9,17 +9,18 @@

namespace detail {
struct Property;
struct Mapper {
Mapper(const Property* other);

protected:
class Mapper {
public:
Mapper() = default;
Mapper(const Property other);

protected:
static inline std::unordered_map<std::uint16_t, const Property*> map;
Property getProperty(const std::uint16_t id);

private:
static inline std::unordered_map<std::uint16_t, Property> map;
};

struct Property : public Mapper {
struct Property {
std::string_view name;
std::uint16_t id{0U};
Type type{Type::et_default};
Expand All @@ -38,28 +39,32 @@ struct Property : public Mapper {
}

protected:
Property getProperty(const std::uint16_t id) {
if (auto it = map.find(id); it != map.end()) {
return *(it->second);
}
return {"UNKNOWN", id};
}
Property getProperty(const std::uint16_t id) { return Mapper().getProperty(id); }
};

inline Mapper::Mapper(const Property* other) {
map.insert({other->id, other});
inline Mapper::Mapper(const Property other) {
map.insert({other.id, other});
}

Property Mapper::getProperty(const std::uint16_t id) {
if (auto it = map.find(id); it != map.end()) {
return it->second;
}
return {"UNKNOWN", id};
}

} // namespace detail

#define PROPERTY(NAME, VALUE, ...) \
static constexpr detail::Property k##NAME{#NAME, VALUE, ##__VA_ARGS__}; \
static constexpr bool unique##VALUE{true}; \
static inline detail::Mapper k##NAME##_MAPPING { \
&k##NAME \
k##NAME \
}

struct Property : public detail::Property {
Property(const Property& p) : detail::Property{p.name, p.id, p.type} {}
Property(const detail::Property& p) : detail::Property{p.name, p.id, p.type} {}
constexpr Property(const Property& p) : detail::Property{p.name, p.id, p.type} {}
constexpr Property(const detail::Property& p) : detail::Property{p.name, p.id, p.type} {}
Property(const std::uint16_t _id) : detail::Property{getProperty(_id)} {}

PROPERTY(INDEX_NOT_FOUND, 0x0000);
Expand Down

0 comments on commit 580912e

Please sign in to comment.