WeakRef.cpp 1.8 KB

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