WeakRef.cpp 1.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344
  1. /*
  2. * Copyright (c) 2021, Idan Horowitz <idan.horowitz@serenityos.org>
  3. *
  4. * SPDX-License-Identifier: BSD-2-Clause
  5. */
  6. #include <LibJS/Runtime/WeakRef.h>
  7. namespace JS {
  8. WeakRef* WeakRef::create(GlobalObject& global_object, Object* object)
  9. {
  10. return global_object.heap().allocate<WeakRef>(global_object, object, *global_object.weak_ref_prototype());
  11. }
  12. WeakRef::WeakRef(Object* object, Object& prototype)
  13. : Object(prototype)
  14. , WeakContainer(heap())
  15. , m_value(object)
  16. , m_last_execution_generation(vm().execution_generation())
  17. {
  18. }
  19. void WeakRef::remove_dead_cells(Badge<Heap>)
  20. {
  21. VERIFY(m_value);
  22. if (m_value->state() == Cell::State::Live)
  23. return;
  24. m_value = nullptr;
  25. // This is an optimization, we deregister from the garbage collector early (even if we were not garbage collected ourself yet)
  26. // to reduce the garbage collection overhead, which we can do because a cleared weak ref cannot be reused.
  27. WeakContainer::deregister();
  28. }
  29. void WeakRef::visit_edges(Visitor& visitor)
  30. {
  31. Base::visit_edges(visitor);
  32. if (vm().execution_generation() == m_last_execution_generation)
  33. visitor.visit(m_value);
  34. }
  35. }