MarkedVector.h 1.8 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980
  1. /*
  2. * Copyright (c) 2021, Andreas Kling <kling@serenityos.org>
  3. * Copyright (c) 2022, Linus Groh <linusg@serenityos.org>
  4. *
  5. * SPDX-License-Identifier: BSD-2-Clause
  6. */
  7. #pragma once
  8. #include <AK/HashTable.h>
  9. #include <AK/IntrusiveList.h>
  10. #include <AK/Vector.h>
  11. #include <LibJS/Forward.h>
  12. #include <LibJS/Heap/Cell.h>
  13. namespace JS {
  14. class MarkedVectorBase {
  15. public:
  16. virtual void gather_roots(HashTable<Cell*>&) const = 0;
  17. protected:
  18. explicit MarkedVectorBase(Heap&);
  19. ~MarkedVectorBase();
  20. MarkedVectorBase& operator=(MarkedVectorBase const&);
  21. Heap* m_heap { nullptr };
  22. IntrusiveListNode<MarkedVectorBase> m_list_node;
  23. public:
  24. using List = IntrusiveList<&MarkedVectorBase::m_list_node>;
  25. };
  26. template<typename T, size_t inline_capacity>
  27. class MarkedVector
  28. : public MarkedVectorBase
  29. , public Vector<T, inline_capacity> {
  30. public:
  31. explicit MarkedVector(Heap& heap)
  32. : MarkedVectorBase(heap)
  33. {
  34. }
  35. virtual ~MarkedVector() = default;
  36. MarkedVector(MarkedVector const& other)
  37. : MarkedVectorBase(*other.m_heap)
  38. , Vector<T, inline_capacity>(other)
  39. {
  40. }
  41. MarkedVector(MarkedVector&& other)
  42. : MarkedVectorBase(*other.m_heap)
  43. , Vector<T, inline_capacity>(move(static_cast<Vector<T, inline_capacity>&>(other)))
  44. {
  45. }
  46. MarkedVector& operator=(MarkedVector const& other)
  47. {
  48. Vector<T, inline_capacity>::operator=(other);
  49. MarkedVectorBase::operator=(other);
  50. return *this;
  51. }
  52. virtual void gather_roots(HashTable<Cell*>& roots) const override
  53. {
  54. for (auto& value : *this) {
  55. if constexpr (IsSame<Value, T>) {
  56. if (value.is_cell())
  57. roots.set(&const_cast<T&>(value).as_cell());
  58. } else {
  59. roots.set(value);
  60. }
  61. }
  62. };
  63. };
  64. }