AK: Make it possible to use HashMap<K, NonnullOwnPtr>::get()

Add the concept of a PeekType to Traits<T>. This is the type we'll
return (wrapped in an Optional) from HashMap::get().

The PeekType for OwnPtr<T> and NonnullOwnPtr<T> is const T*,
which means that HashMap::get() will return an Optional<const T*> for
maps-of-those.
This commit is contained in:
Andreas Kling 2019-08-14 11:47:38 +02:00
parent f75b1127b2
commit fdcff7d15e
Notes: sideshowbarker 2024-07-19 12:41:35 +09:00
6 changed files with 40 additions and 2 deletions

View File

@ -68,7 +68,7 @@ public:
void dump() const { m_table.dump(); }
Optional<V> get(const K& key) const
Optional<typename Traits<V>::PeekType> get(const K& key) const
{
auto it = find(key);
if (it == end())

View File

@ -142,6 +142,7 @@ make(Args&&... args)
template<typename T>
struct Traits<NonnullOwnPtr<T>> : public GenericTraits<NonnullOwnPtr<T>> {
using PeekType = const T*;
static unsigned hash(const NonnullOwnPtr<T>& p) { return (unsigned)p.ptr(); }
static void dump(const NonnullOwnPtr<T>& p) { kprintf("%p", p.ptr()); }
static bool equals(const NonnullOwnPtr<T>& a, const NonnullOwnPtr<T>& b) { return a.ptr() == b.ptr(); }

View File

@ -164,6 +164,7 @@ private:
template<typename T>
struct Traits<OwnPtr<T>> : public GenericTraits<OwnPtr<T>> {
using PeekType = const T*;
static unsigned hash(const OwnPtr<T>& p) { return (unsigned)p.ptr(); }
static void dump(const OwnPtr<T>& p) { kprintf("%p", p.ptr()); }
static bool equals(const OwnPtr<T>& a, const OwnPtr<T>& b) { return a.ptr() == b.ptr(); }

View File

@ -183,6 +183,12 @@ public:
return exchange(m_ptr, nullptr);
}
NonnullRefPtr<T> release_nonnull()
{
ASSERT(m_ptr);
return NonnullRefPtr<T>(NonnullRefPtr<T>::Adopt, *leak_ref());
}
T* ptr() { return m_ptr; }
const T* ptr() const { return m_ptr; }

View File

@ -76,4 +76,33 @@ TEST_CASE(assert_on_iteration_during_clear)
map.clear();
}
TEST_CASE(hashmap_of_nonnullownptr_get)
{
struct Object {
Object(const String& s) : string(s) {}
String string;
};
HashMap<int, NonnullOwnPtr<Object>> objects;
objects.set(1, make<Object>("One"));
objects.set(2, make<Object>("Two"));
objects.set(3, make<Object>("Three"));
{
auto x = objects.get(2);
EXPECT_EQ(x.has_value(), true);
EXPECT_EQ(x.value()->string, "Two");
}
{
// Do it again to make sure that peeking into the map above didn't
// remove the value from the map.
auto x = objects.get(2);
EXPECT_EQ(x.has_value(), true);
EXPECT_EQ(x.value()->string, "Two");
}
EXPECT_EQ(objects.size(), 3);
}
TEST_MAIN(HashMap)

View File

@ -7,6 +7,7 @@ namespace AK {
template<typename T>
struct GenericTraits {
using PeekType = T;
static constexpr bool is_trivial() { return false; }
static bool equals(const T& a, const T& b) { return a == b; }
};
@ -44,7 +45,7 @@ struct Traits<char> : public GenericTraits<char> {
};
template<typename T>
struct Traits<T*> {
struct Traits<T*> : public GenericTraits<T*> {
static unsigned hash(const T* p)
{
return int_hash((unsigned)(__PTRDIFF_TYPE__)p);