Skip to content

Commit

Permalink
Better type for integrals or enumerations for id variant.
Browse files Browse the repository at this point in the history
  • Loading branch information
eyalz800 committed Dec 23, 2021
1 parent a5668f0 commit 255f5e4
Show file tree
Hide file tree
Showing 2 changed files with 13 additions and 3 deletions.
6 changes: 5 additions & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -472,7 +472,9 @@ using serialize_id = zpp::bits::id<"v1::person"_sha256, 4>; // First 4 bytes of

The type is then converted to bytes at compile time using (... wait for it) `zpp::bits::out`
at compile time, so as long as your literal type is serializable according to the above,
you can use it as a serialization id.
you can use it as a serialization id. The id is serialized to `std::array<std::byte, N>` however
for 1, 2, 4, and 8 bytes its underlying type is `std::byte` `std::uint16_t`, `std::uin32_t` and
`std::uint64_t` respectively for ease of use and efficiency.

* If you want to serialize the variant without an id, or if you know that a variant is going to
have a particular ID upon deserialize, you may do it using `zpp::bits::known_id` to wrap your variant:
Expand All @@ -485,6 +487,8 @@ in(zpp::bits::known_id<"v2::person"_sha256, 4>(v));

// When deserializing you can pass the id as function parameter, to be able
// to use outside of compile time context. `id_v` stands for "id value".
// In our case 4 bytes translates to a plain std::uint32_t, so any dynamic
// integer could fit as the first parameter to `known_id` below.
in(zpp::bits::known_id(zpp::bits::id_v<"v2::person"_sha256, 4>, v));
```
Expand Down
10 changes: 8 additions & 2 deletions zpp_bits.h
Original file line number Diff line number Diff line change
Expand Up @@ -1767,7 +1767,13 @@ constexpr auto known_id(Variant && variant)
template <typename Id, concepts::variant Variant>
struct known_dynamic_id_variant
{
constexpr explicit known_dynamic_id_variant(Variant & variant, Id & id) :
using id_type =
std::conditional_t<std::is_integral_v<std::remove_cvref_t<Id>> ||
std::is_enum_v<std::remove_cvref_t<Id>>,
std::remove_cvref_t<Id>,
Id &>;

constexpr explicit known_dynamic_id_variant(Variant & variant, id_type id) :
variant(variant),
id(id)
{
Expand All @@ -1779,7 +1785,7 @@ struct known_dynamic_id_variant
}

Variant & variant;
Id & id;
id_type id;
};

template <typename Id, typename Variant>
Expand Down

0 comments on commit 255f5e4

Please sign in to comment.