WeakRef.cpp 1.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748
  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. WeakRef::~WeakRef()
  20. {
  21. }
  22. void WeakRef::remove_dead_cells(Badge<Heap>)
  23. {
  24. VERIFY(m_value);
  25. if (m_value->state() == Cell::State::Live)
  26. return;
  27. m_value = nullptr;
  28. // This is an optimization, we deregister from the garbage collector early (even if we were not garbage collected ourself yet)
  29. // to reduce the garbage collection overhead, which we can do because a cleared weak ref cannot be reused.
  30. WeakContainer::deregister();
  31. }
  32. void WeakRef::visit_edges(Visitor& visitor)
  33. {
  34. Base::visit_edges(visitor);
  35. if (vm().execution_generation() == m_last_execution_generation)
  36. visitor.visit(m_value);
  37. }
  38. }