WeakRef.cpp 1.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950
  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_swept_cells(Badge<Heap>, Span<Cell*> cells)
  23. {
  24. VERIFY(m_value);
  25. for (auto* cell : cells) {
  26. if (m_value != cell)
  27. continue;
  28. m_value = nullptr;
  29. // This is an optimization, we deregister from the garbage collector early (even if we were not garbage collected ourself yet)
  30. // to reduce the garbage collection overhead, which we can do because a cleared weak ref cannot be reused.
  31. WeakContainer::deregister();
  32. break;
  33. }
  34. }
  35. void WeakRef::visit_edges(Visitor& visitor)
  36. {
  37. Base::visit_edges(visitor);
  38. if (vm().execution_generation() == m_last_execution_generation)
  39. visitor.visit(m_value);
  40. }
  41. }