TreeNode.h 2.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283
  1. #pragma once
  2. #include <AK/Assertions.h>
  3. #include <AK/NonnullRefPtr.h>
  4. template<typename T>
  5. class TreeNode {
  6. public:
  7. void ref()
  8. {
  9. ASSERT(m_ref_count);
  10. ++m_ref_count;
  11. }
  12. void deref()
  13. {
  14. ASSERT(m_ref_count);
  15. if (!--m_ref_count)
  16. delete static_cast<T*>(this);
  17. }
  18. int ref_count() const { return m_ref_count; }
  19. T* parent() { return m_parent; }
  20. const T* parent() const { return m_parent; }
  21. bool has_children() const { return m_first_child; }
  22. T* next_sibling() { return m_next_sibling; }
  23. T* previous_sibling() { return m_previous_sibling; }
  24. T* first_child() { return m_first_child; }
  25. T* last_child() { return m_last_child; }
  26. const T* next_sibling() const { return m_next_sibling; }
  27. const T* previous_sibling() const { return m_previous_sibling; }
  28. const T* first_child() const { return m_first_child; }
  29. const T* last_child() const { return m_last_child; }
  30. void append_child(NonnullRefPtr<T> node, bool call_inserted_into = true);
  31. void donate_all_children_to(T& node);
  32. protected:
  33. TreeNode() { }
  34. private:
  35. int m_ref_count { 1 };
  36. T* m_parent { nullptr };
  37. T* m_first_child { nullptr };
  38. T* m_last_child { nullptr };
  39. T* m_next_sibling { nullptr };
  40. T* m_previous_sibling { nullptr };
  41. };
  42. template<typename T>
  43. inline void TreeNode<T>::append_child(NonnullRefPtr<T> node, bool call_inserted_into)
  44. {
  45. ASSERT(!node->m_parent);
  46. if (m_last_child)
  47. m_last_child->m_next_sibling = node.ptr();
  48. node->m_previous_sibling = m_last_child;
  49. node->m_parent = static_cast<T*>(this);
  50. m_last_child = node.ptr();
  51. if (!m_first_child)
  52. m_first_child = m_last_child;
  53. if (call_inserted_into)
  54. node->inserted_into(static_cast<T&>(*this));
  55. (void)node.leak_ref();
  56. }
  57. template<typename T>
  58. inline void TreeNode<T>::donate_all_children_to(T& node)
  59. {
  60. for (T* child = m_first_child; child != nullptr;) {
  61. T* next_child = child->m_next_sibling;
  62. child->m_parent = nullptr;
  63. child->m_next_sibling = nullptr;
  64. child->m_previous_sibling = nullptr;
  65. node.append_child(adopt(*child));
  66. child = next_child;
  67. }
  68. m_first_child = nullptr;
  69. m_last_child = nullptr;
  70. }