Truly independent web browser
/*
* Copyright (c) 2025, Andreas Kling <[email protected]>
*
* SPDX-License-Identifier: BSD-2-Clause
*/
#pragma once
#include <AK/HashMap.h>
#include <AK/IntrusiveList.h>
#include <LibGC/Cell.h>
#include <LibGC/Forward.h>
#include <LibGC/HeapRoot.h>
#include <LibGC/Rootable.h>
namespace GC {
class GC_API RootHashMapBase {
AK_MAKE_NONCOPYABLE(RootHashMapBase);
public:
virtual void gather_roots(HashMap<Cell*, GC::HeapRoot>&) const = 0;
protected:
RootHashMapBase();
explicit RootHashMapBase(Heap&);
~RootHashMapBase();
void assign_heap(Heap*);
Heap* m_heap { nullptr };
IntrusiveListNode<RootHashMapBase> m_list_node;
public:
using List = IntrusiveList<&RootHashMapBase::m_list_node>;
};
template<typename K, typename V, typename KeyTraits = Traits<K>, typename ValueTraits = Traits<V>, bool IsOrdered = false>
class RootHashMap final
: public RootHashMapBase
, public HashMap<K, V, KeyTraits, ValueTraits, IsOrdered> {
using HashMapBase = HashMap<K, V, KeyTraits, ValueTraits, IsOrdered>;
public:
RootHashMap()
: RootHashMapBase()
{
}
~RootHashMap() = default;
RootHashMap(RootHashMap const& other)
: RootHashMapBase(*other.m_heap)
, HashMapBase(static_cast<HashMapBase const&>(other))
{
}
RootHashMap(RootHashMap&& other)
: RootHashMapBase(*other.m_heap)
, HashMapBase(move(static_cast<HashMapBase&>(other)))
{
}
RootHashMap& operator=(RootHashMap const& other)
{
if (&other == this)
return *this;
assign_heap(other.m_heap);
HashMapBase::operator=(static_cast<HashMapBase const&>(other));
return *this;
}
RootHashMap& operator=(RootHashMap&& other)
{
assign_heap(other.m_heap);
HashMapBase::operator=(move(static_cast<HashMapBase&>(other)));
return *this;
}
virtual void gather_roots(HashMap<Cell*, GC::HeapRoot>& roots) const override
{
static constexpr bool KeyIsGCType = Detail::IsRootableValue<K>;
static constexpr bool ValueIsGCType = Detail::IsRootableValue<V>;
static_assert(KeyIsGCType || ValueIsGCType,
"RootHashMap requires its key or value type to be a cell, derive from NanBoxedValue, or be a traced value");
for (auto& [key, value] : *this) {
if constexpr (KeyIsGCType)
Detail::gather_root(roots, key, HeapRoot::Type::RootHashMap);
if constexpr (ValueIsGCType)
Detail::gather_root(roots, value, HeapRoot::Type::RootHashMap);
}
}
};
template<typename K, typename V, typename KeyTraits = Traits<K>, typename ValueTraits = Traits<V>>
using OrderedRootHashMap = RootHashMap<K, V, KeyTraits, ValueTraits, true>;
}