name: Add std::hash<Name> to support unordered_map container
Change-Id: I1edda483340fc5a891b6ae3a9cc4baf39b859621
Refs: #2147
diff --git a/src/name.cpp b/src/name.cpp
index acad1d1..9090176 100644
--- a/src/name.cpp
+++ b/src/name.cpp
@@ -31,6 +31,8 @@
#include "encoding/block.hpp"
#include "encoding/encoding-buffer.hpp"
+#include <boost/functional/hash.hpp>
+
namespace ndn {
BOOST_CONCEPT_ASSERT((boost::EqualityComparable<Name>));
@@ -341,3 +343,13 @@
}
} // namespace ndn
+
+namespace std {
+size_t
+hash<ndn::Name>::operator()(const ndn::Name& name) const
+{
+ return boost::hash_range(name.wireEncode().wire(),
+ name.wireEncode().wire() + name.wireEncode().size());
+}
+
+} // namespace std
diff --git a/src/name.hpp b/src/name.hpp
index f4b1411..1719e92 100644
--- a/src/name.hpp
+++ b/src/name.hpp
@@ -597,4 +597,14 @@
} // namespace ndn
+namespace std {
+template<>
+struct hash<ndn::Name>
+{
+ size_t
+ operator()(const ndn::Name& name) const;
+};
+
+} // namespace std
+
#endif
diff --git a/tests/unit-tests/test-name.cpp b/tests/unit-tests/test-name.cpp
index 785321a..f10cf0a 100644
--- a/tests/unit-tests/test-name.cpp
+++ b/tests/unit-tests/test-name.cpp
@@ -24,6 +24,7 @@
#include "boost-test.hpp"
#include <boost/tuple/tuple.hpp>
#include <boost/mpl/vector.hpp>
+#include <unordered_map>
namespace ndn {
@@ -274,6 +275,21 @@
BOOST_CHECK_EQUAL(number, 11676);
}
+BOOST_AUTO_TEST_CASE(UnorderedMap)
+{
+ std::unordered_map<Name, int> map;
+ Name name1("/1");
+ Name name2("/2");
+ Name name3("/3");
+ map[name1] = 1;
+ map[name2] = 2;
+ map[name3] = 3;
+
+ BOOST_CHECK_EQUAL(map[name1], 1);
+ BOOST_CHECK_EQUAL(map[name2], 2);
+ BOOST_CHECK_EQUAL(map[name3], 3);
+}
+
BOOST_AUTO_TEST_SUITE_END()
} // namespace ndn