WeakRef.cpp 1.7 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758
  1. /*
  2. * Copyright (c) 2021-2022, 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. NonnullGCPtr<WeakRef> WeakRef::create(Realm& realm, Object& value)
  9. {
  10. return realm.heap().allocate<WeakRef>(realm, value, realm.intrinsics().weak_ref_prototype());
  11. }
  12. NonnullGCPtr<WeakRef> WeakRef::create(Realm& realm, Symbol& value)
  13. {
  14. return realm.heap().allocate<WeakRef>(realm, value, realm.intrinsics().weak_ref_prototype());
  15. }
  16. WeakRef::WeakRef(Object& value, Object& prototype)
  17. : Object(ConstructWithPrototypeTag::Tag, prototype)
  18. , WeakContainer(heap())
  19. , m_value(&value)
  20. , m_last_execution_generation(vm().execution_generation())
  21. {
  22. }
  23. WeakRef::WeakRef(Symbol& value, Object& prototype)
  24. : Object(ConstructWithPrototypeTag::Tag, prototype)
  25. , WeakContainer(heap())
  26. , m_value(&value)
  27. , m_last_execution_generation(vm().execution_generation())
  28. {
  29. }
  30. void WeakRef::remove_dead_cells(Badge<Heap>)
  31. {
  32. if (m_value.visit([](Cell* cell) -> bool { return cell->state() == Cell::State::Live; }, [](Empty) -> bool { VERIFY_NOT_REACHED(); }))
  33. return;
  34. m_value = Empty {};
  35. // This is an optimization, we deregister from the garbage collector early (even if we were not garbage collected ourself yet)
  36. // to reduce the garbage collection overhead, which we can do because a cleared weak ref cannot be reused.
  37. WeakContainer::deregister();
  38. }
  39. void WeakRef::visit_edges(Visitor& visitor)
  40. {
  41. Base::visit_edges(visitor);
  42. if (vm().execution_generation() == m_last_execution_generation) {
  43. auto* cell = m_value.visit([](Cell* cell) -> Cell* { return cell; }, [](Empty) -> Cell* { return nullptr; });
  44. visitor.visit(cell);
  45. }
  46. }
  47. }