arena.rs 6.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193
  1. use std::ptr::NonNull;
  2. use crate::{
  3. innerlude::DirtyScope, nodes::RenderReturn, nodes::VNode, virtual_dom::VirtualDom,
  4. AttributeValue, DynamicNode, ScopeId,
  5. };
  6. use bumpalo::boxed::Box as BumpBox;
  7. /// An Element's unique identifier.
  8. ///
  9. /// `ElementId` is a `usize` that is unique across the entire VirtualDOM - but not unique across time. If a component is
  10. /// unmounted, then the `ElementId` will be reused for a new component.
  11. #[cfg_attr(feature = "serialize", derive(serde::Serialize, serde::Deserialize))]
  12. #[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash, Default)]
  13. pub struct ElementId(pub usize);
  14. pub(crate) struct ElementRef {
  15. // the pathway of the real element inside the template
  16. pub path: ElementPath,
  17. // The actual template
  18. pub template: Option<NonNull<VNode<'static>>>,
  19. }
  20. #[derive(Clone, Copy)]
  21. pub enum ElementPath {
  22. Deep(&'static [u8]),
  23. Root(usize),
  24. }
  25. impl ElementRef {
  26. pub(crate) fn none() -> Self {
  27. Self {
  28. template: None,
  29. path: ElementPath::Root(0),
  30. }
  31. }
  32. }
  33. impl VirtualDom {
  34. pub(crate) fn next_element(&mut self, template: &VNode, path: &'static [u8]) -> ElementId {
  35. self.next_reference(template, ElementPath::Deep(path))
  36. }
  37. pub(crate) fn next_root(&mut self, template: &VNode, path: usize) -> ElementId {
  38. self.next_reference(template, ElementPath::Root(path))
  39. }
  40. pub(crate) fn next_null(&mut self) -> ElementId {
  41. let entry = self.elements.vacant_entry();
  42. let id = entry.key();
  43. entry.insert(ElementRef::none());
  44. ElementId(id)
  45. }
  46. fn next_reference(&mut self, template: &VNode, path: ElementPath) -> ElementId {
  47. let entry = self.elements.vacant_entry();
  48. let id = entry.key();
  49. entry.insert(ElementRef {
  50. // We know this is non-null because it comes from a reference
  51. template: Some(unsafe { NonNull::new_unchecked(template as *const _ as *mut _) }),
  52. path,
  53. });
  54. ElementId(id)
  55. }
  56. pub(crate) fn reclaim(&mut self, el: ElementId) {
  57. self.try_reclaim(el)
  58. .unwrap_or_else(|| panic!("cannot reclaim {:?}", el));
  59. }
  60. pub(crate) fn try_reclaim(&mut self, el: ElementId) -> Option<ElementRef> {
  61. if el.0 == 0 {
  62. panic!(
  63. "Cannot reclaim the root element - {:#?}",
  64. std::backtrace::Backtrace::force_capture()
  65. );
  66. }
  67. self.elements.try_remove(el.0)
  68. }
  69. pub(crate) fn update_template(&mut self, el: ElementId, node: &VNode) {
  70. let node: *const VNode = node as *const _;
  71. self.elements[el.0].template = unsafe { std::mem::transmute(node) };
  72. }
  73. // Drop a scope and all its children
  74. //
  75. // Note: This will not remove any ids from the arena
  76. pub(crate) fn drop_scope(&mut self, id: ScopeId, recursive: bool) {
  77. self.dirty_scopes.remove(&DirtyScope {
  78. height: self.scopes[id.0].height,
  79. id,
  80. });
  81. self.ensure_drop_safety(id);
  82. if recursive {
  83. if let Some(root) = self.scopes[id.0].as_ref().try_root_node() {
  84. if let RenderReturn::Ready(node) = unsafe { root.extend_lifetime_ref() } {
  85. self.drop_scope_inner(node)
  86. }
  87. }
  88. }
  89. let scope = &mut self.scopes[id.0];
  90. // Drop all the hooks once the children are dropped
  91. // this means we'll drop hooks bottom-up
  92. for hook in scope.hook_list.get_mut().drain(..) {
  93. drop(unsafe { BumpBox::from_raw(hook) });
  94. }
  95. // Drop all the futures once the hooks are dropped
  96. for task_id in scope.spawned_tasks.borrow_mut().drain() {
  97. scope.tasks.remove(task_id);
  98. }
  99. self.scopes.remove(id.0);
  100. }
  101. fn drop_scope_inner(&mut self, node: &VNode) {
  102. node.dynamic_nodes.iter().for_each(|node| match node {
  103. DynamicNode::Component(c) => {
  104. if let Some(f) = c.scope.get() {
  105. self.drop_scope(f, true);
  106. }
  107. c.props.take();
  108. }
  109. DynamicNode::Fragment(nodes) => {
  110. nodes.iter().for_each(|node| self.drop_scope_inner(node))
  111. }
  112. DynamicNode::Placeholder(_) => {}
  113. DynamicNode::Text(_) => {}
  114. });
  115. }
  116. /// Descend through the tree, removing any borrowed props and listeners
  117. pub(crate) fn ensure_drop_safety(&self, scope_id: ScopeId) {
  118. let scope = &self.scopes[scope_id.0];
  119. // make sure we drop all borrowed props manually to guarantee that their drop implementation is called before we
  120. // run the hooks (which hold an &mut Reference)
  121. // recursively call ensure_drop_safety on all children
  122. let mut props = scope.borrowed_props.borrow_mut();
  123. props.drain(..).for_each(|comp| {
  124. let comp = unsafe { &*comp };
  125. match comp.scope.get() {
  126. Some(child) if child != scope_id => self.ensure_drop_safety(child),
  127. _ => (),
  128. }
  129. if let Ok(mut props) = comp.props.try_borrow_mut() {
  130. *props = None;
  131. }
  132. });
  133. // Now that all the references are gone, we can safely drop our own references in our listeners.
  134. let mut listeners = scope.attributes_to_drop.borrow_mut();
  135. listeners.drain(..).for_each(|listener| {
  136. let listener = unsafe { &*listener };
  137. match &listener.value {
  138. AttributeValue::Listener(l) => {
  139. _ = l.take();
  140. }
  141. AttributeValue::Any(a) => {
  142. _ = a.take();
  143. }
  144. _ => (),
  145. }
  146. });
  147. }
  148. }
  149. impl ElementPath {
  150. pub(crate) fn is_ascendant(&self, big: &&[u8]) -> bool {
  151. match *self {
  152. ElementPath::Deep(small) => small.len() <= big.len() && small == &big[..small.len()],
  153. ElementPath::Root(r) => big.len() == 1 && big[0] == r as u8,
  154. }
  155. }
  156. }
  157. impl PartialEq<&[u8]> for ElementPath {
  158. fn eq(&self, other: &&[u8]) -> bool {
  159. match *self {
  160. ElementPath::Deep(deep) => deep.eq(*other),
  161. ElementPath::Root(r) => other.len() == 1 && other[0] == r as u8,
  162. }
  163. }
  164. }