TreeNode.h 1.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061
  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);
  31. protected:
  32. TreeNode() { }
  33. private:
  34. int m_ref_count { 1 };
  35. T* m_parent { nullptr };
  36. T* m_first_child { nullptr };
  37. T* m_last_child { nullptr };
  38. T* m_next_sibling { nullptr };
  39. T* m_previous_sibling { nullptr };
  40. };
  41. template<typename T>
  42. inline void TreeNode<T>::append_child(NonnullRefPtr<T> node)
  43. {
  44. ASSERT(!node->m_parent);
  45. if (m_last_child)
  46. m_last_child->m_next_sibling = node.ptr();
  47. node->m_previous_sibling = m_last_child;
  48. node->m_parent = static_cast<T*>(this);
  49. m_last_child = &node.leak_ref();
  50. if (!m_first_child)
  51. m_first_child = m_last_child;
  52. }