2021-06-12 14:38:34 +00:00
|
|
|
/*
|
2022-06-22 20:09:59 +00:00
|
|
|
* Copyright (c) 2021-2022, Idan Horowitz <idan.horowitz@serenityos.org>
|
2021-06-12 14:38:34 +00:00
|
|
|
*
|
|
|
|
* SPDX-License-Identifier: BSD-2-Clause
|
|
|
|
*/
|
|
|
|
|
|
|
|
#include <LibJS/Runtime/WeakRef.h>
|
|
|
|
|
|
|
|
namespace JS {
|
|
|
|
|
2024-11-14 15:01:23 +00:00
|
|
|
GC_DEFINE_ALLOCATOR(WeakRef);
|
2023-11-19 08:45:05 +00:00
|
|
|
|
2024-11-14 15:01:23 +00:00
|
|
|
GC::Ref<WeakRef> WeakRef::create(Realm& realm, Object& value)
|
2021-06-12 14:38:34 +00:00
|
|
|
{
|
2024-11-13 16:50:17 +00:00
|
|
|
return realm.create<WeakRef>(value, realm.intrinsics().weak_ref_prototype());
|
2021-06-12 14:38:34 +00:00
|
|
|
}
|
|
|
|
|
2024-11-14 15:01:23 +00:00
|
|
|
GC::Ref<WeakRef> WeakRef::create(Realm& realm, Symbol& value)
|
2022-06-22 20:09:59 +00:00
|
|
|
{
|
2024-11-13 16:50:17 +00:00
|
|
|
return realm.create<WeakRef>(value, realm.intrinsics().weak_ref_prototype());
|
2022-06-22 20:09:59 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
WeakRef::WeakRef(Object& value, Object& prototype)
|
2022-12-14 11:17:58 +00:00
|
|
|
: Object(ConstructWithPrototypeTag::Tag, prototype)
|
2022-06-22 20:09:59 +00:00
|
|
|
, WeakContainer(heap())
|
|
|
|
, m_value(&value)
|
|
|
|
, m_last_execution_generation(vm().execution_generation())
|
|
|
|
{
|
|
|
|
}
|
|
|
|
|
|
|
|
WeakRef::WeakRef(Symbol& value, Object& prototype)
|
2022-12-14 11:17:58 +00:00
|
|
|
: Object(ConstructWithPrototypeTag::Tag, prototype)
|
2021-06-12 14:38:34 +00:00
|
|
|
, WeakContainer(heap())
|
2022-06-22 20:09:59 +00:00
|
|
|
, m_value(&value)
|
2021-06-12 14:38:34 +00:00
|
|
|
, m_last_execution_generation(vm().execution_generation())
|
|
|
|
{
|
|
|
|
}
|
|
|
|
|
2024-11-14 15:01:23 +00:00
|
|
|
void WeakRef::remove_dead_cells(Badge<GC::Heap>)
|
2021-06-12 14:38:34 +00:00
|
|
|
{
|
2022-06-22 20:09:59 +00:00
|
|
|
if (m_value.visit([](Cell* cell) -> bool { return cell->state() == Cell::State::Live; }, [](Empty) -> bool { VERIFY_NOT_REACHED(); }))
|
2021-10-05 16:44:31 +00:00
|
|
|
return;
|
|
|
|
|
2022-06-22 20:09:59 +00:00
|
|
|
m_value = Empty {};
|
2021-10-05 16:44:31 +00:00
|
|
|
// This is an optimization, we deregister from the garbage collector early (even if we were not garbage collected ourself yet)
|
|
|
|
// to reduce the garbage collection overhead, which we can do because a cleared weak ref cannot be reused.
|
|
|
|
WeakContainer::deregister();
|
2021-06-12 14:38:34 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
void WeakRef::visit_edges(Visitor& visitor)
|
|
|
|
{
|
2021-09-11 12:05:12 +00:00
|
|
|
Base::visit_edges(visitor);
|
2021-06-12 14:38:34 +00:00
|
|
|
|
2022-06-22 20:09:59 +00:00
|
|
|
if (vm().execution_generation() == m_last_execution_generation) {
|
|
|
|
auto* cell = m_value.visit([](Cell* cell) -> Cell* { return cell; }, [](Empty) -> Cell* { return nullptr; });
|
|
|
|
visitor.visit(cell);
|
|
|
|
}
|
2021-06-12 14:38:34 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
}
|