Skip to content

Commit

Permalink
Make sure that the type names are unique
Browse files Browse the repository at this point in the history
  • Loading branch information
alex-sparus committed Feb 20, 2024
1 parent cb9e0d2 commit 4cbd826
Show file tree
Hide file tree
Showing 2 changed files with 44 additions and 0 deletions.
13 changes: 13 additions & 0 deletions immer/experimental/immer-archive/json/json_with_archive.hpp
Original file line number Diff line number Diff line change
Expand Up @@ -142,6 +142,15 @@ inline auto generate_archives_save(auto type_names)
return archives_save<Storage, Names>{storage};
}

inline auto are_type_names_unique(auto type_names)
{
auto names_set =
hana::fold_left(type_names, hana::make_set(), [](auto set, auto pair) {
return hana::insert(set, hana::second(pair));
});
return hana::length(type_names) == hana::length(names_set);
}

inline auto generate_archives_load(auto type_names)
{
auto storage =
Expand Down Expand Up @@ -179,6 +188,10 @@ constexpr bool is_archive_empty(const Archives& archives)
template <typename T>
auto to_json_with_archive(const T& serializable)
{
using IsUnique = decltype(detail::are_type_names_unique(
get_archives_types(serializable)));
static_assert(boost::hana::value<IsUnique>(),
"Archive names for each type must be unique");
auto archives =
detail::generate_archives_save(get_archives_types(serializable));
using Archives = std::decay_t<decltype(archives)>;
Expand Down
31 changes: 31 additions & 0 deletions test/experimental/immer-archive/test_special_archive.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -743,3 +743,34 @@ TEST_CASE("Test saving a map that contains the same map")
json_str);
}
}

TEST_CASE("Test non-unique names in the map")
{
{
const auto names = hana::make_map(
hana::make_pair(hana::type_c<immer::box<int>>,
BOOST_HANA_STRING("box")),
hana::make_pair(hana::type_c<immer::box<std::string>>,
BOOST_HANA_STRING("box"))

);

using IsUnique =
decltype(immer_archive::detail::are_type_names_unique(names));
static_assert(boost::hana::value<IsUnique>() == false,
"Detect non-unique names");
}
{
const auto names = hana::make_map(
hana::make_pair(hana::type_c<immer::box<int>>,
BOOST_HANA_STRING("box_1")),
hana::make_pair(hana::type_c<immer::box<std::string>>,
BOOST_HANA_STRING("box_2"))

);

using IsUnique =
decltype(immer_archive::detail::are_type_names_unique(names));
static_assert(boost::hana::value<IsUnique>(), "Names are unique");
}
}

0 comments on commit 4cbd826

Please sign in to comment.