Skip to content

Commit

Permalink
Specialize std::hash for RecordRef
Browse files Browse the repository at this point in the history
  • Loading branch information
bernhardmgruber committed Aug 10, 2023
1 parent a3de119 commit 987417e
Show file tree
Hide file tree
Showing 2 changed files with 29 additions and 1 deletion.
16 changes: 15 additions & 1 deletion include/llama/RecordRef.hpp
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@
#include "View.hpp"
#include "macros.hpp"

#include <boost/functional/hash.hpp>
#include <iosfwd>
#include <type_traits>

Expand Down Expand Up @@ -853,7 +854,7 @@ namespace llama
template<typename T>
struct ValueOf<T&>
{
using type = T;
using type = std::remove_const_t<T>;
};
} // namespace internal

Expand Down Expand Up @@ -1011,6 +1012,19 @@ struct std::tuple_element<I, const llama::RecordRef<View, BoundRecordCoord, OwnV
using type = decltype(std::declval<const llama::RecordRef<View, BoundRecordCoord, OwnView>>().template get<I>());
};

template<typename View, typename BoundRecordCoord, bool OwnView>
struct std::hash<llama::RecordRef<View, BoundRecordCoord, OwnView>> // NOLINT(cert-dcl58-cpp)
{
auto operator()(const llama::RecordRef<View, BoundRecordCoord, OwnView>& rr) const -> std::size_t
{
std::size_t acc = 0;
llama::forEachLeaf(
rr,
[&](auto&& ref) LLAMA_LAMBDA_INLINE { boost::hash_combine(acc, llama::decayCopy(ref)); });
return acc;
}
};

#if CAN_USE_RANGES
template<
typename ViewA,
Expand Down
14 changes: 14 additions & 0 deletions tests/recordref.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -1108,6 +1108,20 @@ TEST_CASE("RecordRef.operator<<")
CHECK(ss.str() == expected);
}

TEST_CASE("RecordRef.hash")
{
llama::One<Vec3I> v;
llama::forEachLeaf(v, [i = 0](auto& ref) mutable { ref = ++i; });

std::size_t reference = 0;
boost::hash_combine(reference, v(tag::X{}));
boost::hash_combine(reference, v(tag::Y{}));
boost::hash_combine(reference, v(tag::Z{}));

CHECK(std::hash<decltype(v)>{}(v) == reference);
CHECK(std::hash<decltype(v())>{}(v()) == reference);
}

TEST_CASE("RecordRef.swap")
{
llama::One<Vec3I> p1{1};
Expand Down

0 comments on commit 987417e

Please sign in to comment.