1#[cfg(any(feature = "inspector", debug_assertions))]
35use crate::InspectorElementPath;
36use crate::{
37 A11ySubtreeBuilder, App, ArenaBox, AvailableSpace, Bounds, Context, DispatchNodeId, ElementId,
38 FocusHandle, InspectorElementId, LayoutId, Pixels, Point, Size, Style, Window,
39 util::FluentBuilder, window::with_element_arena,
40};
41use std::{
42 any::Any,
43 fmt::{self, Debug, Display},
44 mem, panic,
45 sync::Arc,
46};
47
48pub trait Element: 'static + Sized {
53 type RequestLayoutState: 'static;
56
57 type PrepaintState: 'static;
60
61 fn id(&self) -> Option<ElementId>;
67
68 fn source_location(&self) -> Option<&'static panic::Location<'static>>;
71
72 fn request_layout(
75 &mut self,
76 id: Option<&GlobalElementId>,
77 inspector_id: Option<&InspectorElementId>,
78 window: &mut Window,
79 cx: &mut App,
80 ) -> (LayoutId, Self::RequestLayoutState);
81
82 fn prepaint(
85 &mut self,
86 id: Option<&GlobalElementId>,
87 inspector_id: Option<&InspectorElementId>,
88 bounds: Bounds<Pixels>,
89 request_layout: &mut Self::RequestLayoutState,
90 window: &mut Window,
91 cx: &mut App,
92 ) -> Self::PrepaintState;
93
94 fn paint(
97 &mut self,
98 id: Option<&GlobalElementId>,
99 inspector_id: Option<&InspectorElementId>,
100 bounds: Bounds<Pixels>,
101 request_layout: &mut Self::RequestLayoutState,
102 prepaint: &mut Self::PrepaintState,
103 window: &mut Window,
104 cx: &mut App,
105 );
106
107 fn a11y_role(&self) -> Option<accesskit::Role> {
114 None
115 }
116
117 fn write_a11y_info(&self, _node: &mut accesskit::Node) {}
122
123 fn a11y_synthetic_children(
133 &mut self,
134 _prepaint: &mut Self::PrepaintState,
135 _builder: &mut A11ySubtreeBuilder,
136 ) {
137 }
138
139 fn into_any(self) -> AnyElement {
141 AnyElement::new_please_call_into_any_to_avoid_double_box(self)
142 }
143}
144
145impl<T: Element> IntoElement for T {
146 type Element = Self;
147
148 fn into_element(self) -> Self::Element {
149 self
150 }
151}
152
153pub trait IntoElement: Sized {
155 type Element: Element;
158
159 fn into_element(self) -> Self::Element;
161
162 fn into_any_element(self) -> AnyElement {
164 self.into_element().into_any()
165 }
166}
167
168impl<T: IntoElement> FluentBuilder for T {}
169
170pub trait Render: 'static + Sized {
173 fn render(&mut self, window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement;
175}
176
177impl Render for Empty {
178 fn render(&mut self, _window: &mut Window, _cx: &mut Context<Self>) -> impl IntoElement {
179 Empty
180 }
181}
182
183pub trait RenderOnce: 'static {
189 fn render(self, window: &mut Window, cx: &mut App) -> impl IntoElement;
193}
194
195pub trait ParentElement {
198 fn extend(&mut self, elements: impl IntoIterator<Item = AnyElement>);
200
201 fn child(mut self, child: impl IntoElement) -> Self
203 where
204 Self: Sized,
205 {
206 self.extend(std::iter::once(child.into_any_element()));
207 self
208 }
209
210 fn children(mut self, children: impl IntoIterator<Item = impl IntoElement>) -> Self
212 where
213 Self: Sized,
214 {
215 self.extend(children.into_iter().map(|child| child.into_any_element()));
216 self
217 }
218}
219
220#[derive(Clone, Debug)]
228pub struct GlobalElementId {
229 ids: Arc<[ElementId]>,
230 hash: u64,
231}
232
233pub(crate) const EMPTY_PATH_HASH: u64 = 0;
237
238pub(crate) fn extend_path_hash(prefix: u64, id: &ElementId) -> u64 {
240 use std::hash::{Hash, Hasher};
241 let mut hasher = collections::FxHasher::with_seed(prefix as usize);
242 id.hash(&mut hasher);
243 hasher.finish()
244}
245
246impl GlobalElementId {
247 pub(crate) fn new(ids: &[ElementId]) -> Self {
248 let hash = ids.iter().fold(EMPTY_PATH_HASH, extend_path_hash);
249 Self::with_hash(ids, hash)
250 }
251
252 pub(crate) fn with_hash(ids: &[ElementId], hash: u64) -> Self {
254 debug_assert_eq!(hash, ids.iter().fold(EMPTY_PATH_HASH, extend_path_hash));
255 Self {
256 ids: Arc::from(ids),
257 hash,
258 }
259 }
260
261 pub(crate) fn accesskit_node_id(&self) -> accesskit::NodeId {
262 accesskit::NodeId(self.hash)
263 }
264}
265
266impl Default for GlobalElementId {
267 fn default() -> Self {
268 Self::new(&[])
269 }
270}
271
272impl std::ops::Deref for GlobalElementId {
273 type Target = [ElementId];
274
275 fn deref(&self) -> &Self::Target {
276 &self.ids
277 }
278}
279
280impl PartialEq for GlobalElementId {
281 fn eq(&self, other: &Self) -> bool {
282 self.hash == other.hash && (Arc::ptr_eq(&self.ids, &other.ids) || self.ids == other.ids)
283 }
284}
285
286impl Eq for GlobalElementId {}
287
288impl std::hash::Hash for GlobalElementId {
289 fn hash<H: std::hash::Hasher>(&self, state: &mut H) {
290 state.write_u64(self.hash);
291 }
292}
293
294impl Display for GlobalElementId {
295 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
296 for (i, element_id) in self.ids.iter().enumerate() {
297 if i > 0 {
298 write!(f, ".")?;
299 }
300 write!(f, "{}", element_id)?;
301 }
302 Ok(())
303 }
304}
305
306trait ElementObject {
307 fn inner_element(&mut self) -> &mut dyn Any;
308
309 fn request_layout(&mut self, window: &mut Window, cx: &mut App) -> LayoutId;
310
311 fn prepaint(&mut self, window: &mut Window, cx: &mut App);
312
313 fn paint(&mut self, window: &mut Window, cx: &mut App);
314
315 fn layout_as_root(
316 &mut self,
317 available_space: Size<AvailableSpace>,
318 window: &mut Window,
319 cx: &mut App,
320 ) -> Size<Pixels>;
321}
322
323pub struct Drawable<E: Element> {
325 pub element: E,
327 phase: ElementDrawPhase<E::RequestLayoutState, E::PrepaintState>,
328}
329
330#[derive(Default)]
331enum ElementDrawPhase<RequestLayoutState, PrepaintState> {
332 #[default]
333 Start,
334 RequestLayout {
335 layout_id: LayoutId,
336 global_id: Option<GlobalElementId>,
337 inspector_id: Option<InspectorElementId>,
338 request_layout: RequestLayoutState,
339 },
340 LayoutComputed {
341 layout_id: LayoutId,
342 global_id: Option<GlobalElementId>,
343 inspector_id: Option<InspectorElementId>,
344 available_space: Size<AvailableSpace>,
345 request_layout: RequestLayoutState,
346 },
347 Prepaint {
348 node_id: DispatchNodeId,
349 global_id: Option<GlobalElementId>,
350 inspector_id: Option<InspectorElementId>,
351 bounds: Bounds<Pixels>,
352 request_layout: RequestLayoutState,
353 prepaint: PrepaintState,
354 },
355 Painted,
356}
357
358impl<E: Element> Drawable<E> {
360 pub(crate) fn new(element: E) -> Self {
361 Drawable {
362 element,
363 phase: ElementDrawPhase::Start,
364 }
365 }
366
367 fn request_layout(&mut self, window: &mut Window, cx: &mut App) -> LayoutId {
368 match mem::take(&mut self.phase) {
369 ElementDrawPhase::Start => {
370 let global_id = self
371 .element
372 .id()
373 .map(|element_id| prepare_element_id(element_id, window));
374
375 let inspector_id;
376 #[cfg(any(feature = "inspector", debug_assertions))]
377 {
378 inspector_id = if window.inspector_enabled() {
379 self.element
380 .source_location()
381 .map(|source| prepare_inspector_id(source, window))
382 } else {
383 None
384 };
385 }
386 #[cfg(not(any(feature = "inspector", debug_assertions)))]
387 {
388 inspector_id = None;
389 }
390
391 let (layout_id, request_layout) = self.element.request_layout(
392 global_id.as_ref(),
393 inspector_id.as_ref(),
394 window,
395 cx,
396 );
397
398 if global_id.is_some() {
399 window.element_id_stack.pop();
400 }
401
402 self.phase = ElementDrawPhase::RequestLayout {
403 layout_id,
404 global_id,
405 inspector_id,
406 request_layout,
407 };
408 layout_id
409 }
410 _ => panic!("must call request_layout only once"),
411 }
412 }
413
414 pub(crate) fn prepaint(&mut self, window: &mut Window, cx: &mut App) {
415 match mem::take(&mut self.phase) {
416 ElementDrawPhase::RequestLayout {
417 layout_id,
418 global_id,
419 inspector_id,
420 mut request_layout,
421 }
422 | ElementDrawPhase::LayoutComputed {
423 layout_id,
424 global_id,
425 inspector_id,
426 mut request_layout,
427 ..
428 } => {
429 if let Some(element_id) = self.element.id() {
430 window.element_id_stack.push(element_id);
431 debug_assert_eq!(&**global_id.as_ref().unwrap(), &*window.element_id_stack);
432 }
433
434 let bounds = window.layout_bounds(layout_id);
435 let mut pushed_a11y_node = false;
436 if window.a11y.is_active() {
437 if let Some(global_id) = global_id.as_ref() {
438 if let Some(role) = self.element.a11y_role() {
439 let node_id = global_id.accesskit_node_id();
440 let mut node = accesskit::Node::new(role);
441 let scale = window.scale_factor();
442 node.set_bounds(accesskit::Rect {
443 x0: (bounds.origin.x.0 * scale) as f64,
444 y0: (bounds.origin.y.0 * scale) as f64,
445 x1: ((bounds.origin.x.0 + bounds.size.width.0) * scale) as f64,
446 y1: ((bounds.origin.y.0 + bounds.size.height.0) * scale) as f64,
447 });
448 self.element.write_a11y_info(&mut node);
449 window.a11y.node_bounds.insert(node_id, bounds);
450 pushed_a11y_node = window.a11y.nodes.push(node_id, node);
451 #[cfg(debug_assertions)]
452 if pushed_a11y_node {
453 let view = window
454 .a11y
455 .view_type_names
456 .get(&window.current_view())
457 .copied();
458 let source_location = self.element.source_location();
459 window.a11y.nodes.record_node_info(
460 node_id,
461 crate::window::a11y::debug::NodeDebugInfo {
462 synthetic: false,
463 view,
464 element_id: global_id.last().map(|id| format!("{id:?}")),
465 source_location,
466 },
467 );
468 }
469 }
470 }
471 }
472
473 let node_id = window.next_frame.dispatch_tree.push_node();
474 let mut prepaint = self.element.prepaint(
475 global_id.as_ref(),
476 inspector_id.as_ref(),
477 bounds,
478 &mut request_layout,
479 window,
480 cx,
481 );
482 window.next_frame.dispatch_tree.pop_node();
483
484 if pushed_a11y_node {
485 if let Some(global_id) = global_id.as_ref() {
486 #[cfg(debug_assertions)]
487 let creator = crate::window::a11y::debug::NodeCreator {
488 view: window
489 .a11y
490 .view_type_names
491 .get(&window.current_view())
492 .copied(),
493 element_id: global_id.last().map(|id| format!("{id:?}")),
494 source_location: self.element.source_location(),
495 };
496 let mut builder = A11ySubtreeBuilder::new(
497 global_id.accesskit_node_id(),
498 &mut window.a11y.nodes,
499 );
500 #[cfg(debug_assertions)]
501 {
502 builder = builder.with_creator(creator);
503 }
504 self.element
505 .a11y_synthetic_children(&mut prepaint, &mut builder);
506 }
507 window.a11y.nodes.pop();
508 }
509
510 if global_id.is_some() {
511 window.element_id_stack.pop();
512 }
513
514 self.phase = ElementDrawPhase::Prepaint {
515 node_id,
516 global_id,
517 inspector_id,
518 bounds,
519 request_layout,
520 prepaint,
521 };
522 }
523 _ => panic!("must call request_layout before prepaint"),
524 }
525 }
526
527 pub(crate) fn paint(
528 &mut self,
529 window: &mut Window,
530 cx: &mut App,
531 ) -> (E::RequestLayoutState, E::PrepaintState) {
532 match mem::take(&mut self.phase) {
533 ElementDrawPhase::Prepaint {
534 node_id,
535 global_id,
536 inspector_id,
537 bounds,
538 mut request_layout,
539 mut prepaint,
540 ..
541 } => {
542 if let Some(element_id) = self.element.id() {
543 window.element_id_stack.push(element_id);
544 debug_assert_eq!(&**global_id.as_ref().unwrap(), &*window.element_id_stack);
545 }
546
547 window.next_frame.dispatch_tree.set_active_node(node_id);
548 self.element.paint(
549 global_id.as_ref(),
550 inspector_id.as_ref(),
551 bounds,
552 &mut request_layout,
553 &mut prepaint,
554 window,
555 cx,
556 );
557
558 if global_id.is_some() {
559 window.element_id_stack.pop();
560 }
561
562 self.phase = ElementDrawPhase::Painted;
563 (request_layout, prepaint)
564 }
565 _ => panic!("must call prepaint before paint"),
566 }
567 }
568
569 pub(crate) fn layout_as_root(
570 &mut self,
571 available_space: Size<AvailableSpace>,
572 window: &mut Window,
573 cx: &mut App,
574 ) -> Size<Pixels> {
575 if matches!(&self.phase, ElementDrawPhase::Start) {
576 self.request_layout(window, cx);
577 }
578
579 let layout_id = match mem::take(&mut self.phase) {
580 ElementDrawPhase::RequestLayout {
581 layout_id,
582 global_id,
583 inspector_id,
584 request_layout,
585 } => {
586 window.compute_layout(layout_id, available_space, cx);
587 self.phase = ElementDrawPhase::LayoutComputed {
588 layout_id,
589 global_id,
590 inspector_id,
591 available_space,
592 request_layout,
593 };
594 layout_id
595 }
596 ElementDrawPhase::LayoutComputed {
597 layout_id,
598 global_id,
599 inspector_id,
600 available_space: prev_available_space,
601 request_layout,
602 } => {
603 if available_space != prev_available_space {
604 window.compute_layout(layout_id, available_space, cx);
605 }
606 self.phase = ElementDrawPhase::LayoutComputed {
607 layout_id,
608 global_id,
609 inspector_id,
610 available_space,
611 request_layout,
612 };
613 layout_id
614 }
615 _ => panic!("cannot measure after painting"),
616 };
617
618 window.layout_bounds(layout_id).size
619 }
620}
621
622impl<E> ElementObject for Drawable<E>
623where
624 E: Element,
625 E::RequestLayoutState: 'static,
626{
627 fn inner_element(&mut self) -> &mut dyn Any {
628 &mut self.element
629 }
630
631 #[inline]
632 fn request_layout(&mut self, window: &mut Window, cx: &mut App) -> LayoutId {
633 Drawable::request_layout(self, window, cx)
634 }
635
636 #[inline]
637 fn prepaint(&mut self, window: &mut Window, cx: &mut App) {
638 Drawable::prepaint(self, window, cx);
639 }
640
641 #[inline]
642 fn paint(&mut self, window: &mut Window, cx: &mut App) {
643 Drawable::paint(self, window, cx);
644 }
645
646 #[inline]
647 fn layout_as_root(
648 &mut self,
649 available_space: Size<AvailableSpace>,
650 window: &mut Window,
651 cx: &mut App,
652 ) -> Size<Pixels> {
653 Drawable::layout_as_root(self, available_space, window, cx)
654 }
655}
656
657pub struct AnyElement(ArenaBox<dyn ElementObject>);
659
660impl AnyElement {
661 fn new_please_call_into_any_to_avoid_double_box<E>(element: E) -> Self
667 where
668 E: 'static + Element,
669 E::RequestLayoutState: Any,
670 {
671 let element = with_element_arena(|arena| arena.alloc(|| Drawable::new(element)))
672 .map(|element| element as &mut dyn ElementObject);
673 AnyElement(element)
674 }
675
676 pub fn downcast_mut<T: 'static>(&mut self) -> Option<&mut T> {
678 self.0.inner_element().downcast_mut::<T>()
679 }
680
681 pub fn request_layout(&mut self, window: &mut Window, cx: &mut App) -> LayoutId {
684 self.0.request_layout(window, cx)
685 }
686
687 pub fn prepaint(&mut self, window: &mut Window, cx: &mut App) -> Option<FocusHandle> {
690 let focus_assigned = window.next_frame.focus.is_some();
691
692 self.0.prepaint(window, cx);
693
694 if !focus_assigned && let Some(focus_id) = window.next_frame.focus {
695 return FocusHandle::for_id(focus_id, &cx.focus_handles);
696 }
697
698 None
699 }
700
701 pub fn paint(&mut self, window: &mut Window, cx: &mut App) {
703 self.0.paint(window, cx);
704 }
705
706 pub fn layout_as_root(
708 &mut self,
709 available_space: Size<AvailableSpace>,
710 window: &mut Window,
711 cx: &mut App,
712 ) -> Size<Pixels> {
713 self.0.layout_as_root(available_space, window, cx)
714 }
715
716 pub fn prepaint_at(
719 &mut self,
720 origin: Point<Pixels>,
721 window: &mut Window,
722 cx: &mut App,
723 ) -> Option<FocusHandle> {
724 window.with_absolute_element_offset(origin, |window| self.prepaint(window, cx))
725 }
726
727 pub fn prepaint_as_root(
730 &mut self,
731 origin: Point<Pixels>,
732 available_space: Size<AvailableSpace>,
733 window: &mut Window,
734 cx: &mut App,
735 ) -> Option<FocusHandle> {
736 self.layout_as_root(available_space, window, cx);
737 window.with_absolute_element_offset(origin, |window| self.prepaint(window, cx))
738 }
739}
740
741impl Element for AnyElement {
742 type RequestLayoutState = ();
743 type PrepaintState = ();
744
745 fn id(&self) -> Option<ElementId> {
746 None
747 }
748
749 fn source_location(&self) -> Option<&'static panic::Location<'static>> {
750 None
751 }
752
753 fn request_layout(
754 &mut self,
755 _: Option<&GlobalElementId>,
756 _inspector_id: Option<&InspectorElementId>,
757 window: &mut Window,
758 cx: &mut App,
759 ) -> (LayoutId, Self::RequestLayoutState) {
760 let layout_id = self.request_layout(window, cx);
761 (layout_id, ())
762 }
763
764 fn prepaint(
765 &mut self,
766 _: Option<&GlobalElementId>,
767 _inspector_id: Option<&InspectorElementId>,
768 _: Bounds<Pixels>,
769 _: &mut Self::RequestLayoutState,
770 window: &mut Window,
771 cx: &mut App,
772 ) {
773 self.prepaint(window, cx);
774 }
775
776 fn paint(
777 &mut self,
778 _: Option<&GlobalElementId>,
779 _inspector_id: Option<&InspectorElementId>,
780 _: Bounds<Pixels>,
781 _: &mut Self::RequestLayoutState,
782 _: &mut Self::PrepaintState,
783 window: &mut Window,
784 cx: &mut App,
785 ) {
786 self.paint(window, cx);
787 }
788
789 fn into_any(self) -> AnyElement {
790 self
791 }
792}
793
794pub struct Empty;
796
797impl Element for Empty {
798 type RequestLayoutState = ();
799 type PrepaintState = ();
800
801 fn id(&self) -> Option<ElementId> {
802 None
803 }
804
805 fn source_location(&self) -> Option<&'static panic::Location<'static>> {
806 None
807 }
808
809 fn request_layout(
810 &mut self,
811 _id: Option<&GlobalElementId>,
812 _inspector_id: Option<&InspectorElementId>,
813 window: &mut Window,
814 cx: &mut App,
815 ) -> (LayoutId, Self::RequestLayoutState) {
816 (
817 window.request_layout(
818 Style {
819 display: crate::Display::None,
820 ..Default::default()
821 },
822 None,
823 cx,
824 ),
825 (),
826 )
827 }
828
829 fn prepaint(
830 &mut self,
831 _id: Option<&GlobalElementId>,
832 _inspector_id: Option<&InspectorElementId>,
833 _bounds: Bounds<Pixels>,
834 _state: &mut Self::RequestLayoutState,
835 _window: &mut Window,
836 _cx: &mut App,
837 ) {
838 }
839
840 fn paint(
841 &mut self,
842 _id: Option<&GlobalElementId>,
843 _inspector_id: Option<&InspectorElementId>,
844 _bounds: Bounds<Pixels>,
845 _request_layout: &mut Self::RequestLayoutState,
846 _prepaint: &mut Self::PrepaintState,
847 _window: &mut Window,
848 _cx: &mut App,
849 ) {
850 }
851}
852
853#[inline(never)]
854fn prepare_element_id(element_id: ElementId, window: &mut Window) -> GlobalElementId {
855 window.element_id_stack.push(element_id);
856 window.element_id_stack.global_id()
857}
858
859#[cfg(any(feature = "inspector", debug_assertions))]
860#[inline(never)]
861fn prepare_inspector_id(
862 source: &'static panic::Location<'static>,
863 window: &mut Window,
864) -> InspectorElementId {
865 let path = InspectorElementPath {
866 global_id: window.element_id_stack.global_id(),
867 source_location: source,
868 };
869 window.build_inspector_element_id(path)
870}
871
872#[cfg(test)]
873mod global_element_id_tests {
874 use super::*;
875 use std::hash::{Hash, Hasher};
876
877 fn path(depth: usize, leaf: u64) -> Vec<ElementId> {
878 let mut ids: Vec<ElementId> = (0..depth as u64)
879 .map(|level| ElementId::NamedInteger("some-container-element".into(), level))
880 .collect();
881 ids.push(ElementId::NamedInteger("leaf".into(), leaf));
882 ids
883 }
884
885 fn fx_hash(value: &impl Hash) -> u64 {
886 let mut hasher = collections::FxHasher::default();
887 value.hash(&mut hasher);
888 hasher.finish()
889 }
890
891 #[test]
892 fn equal_paths_are_equal_and_hash_alike() {
893 let a = GlobalElementId::new(&path(8, 1));
894 let b = GlobalElementId::new(&path(8, 1));
895 let c = GlobalElementId::new(&path(8, 2));
896 let shallower = GlobalElementId::new(&path(7, 1));
897 assert_eq!(a, b);
898 assert_eq!(fx_hash(&a), fx_hash(&b));
899 assert_eq!(a.accesskit_node_id(), b.accesskit_node_id());
900 assert_ne!(a, c);
901 assert_ne!(a, shallower);
902 assert_ne!(fx_hash(&a), fx_hash(&c));
903 assert_eq!(&*a, path(8, 1).as_slice());
904 assert_eq!(a.to_string(), b.to_string());
905 assert_eq!(GlobalElementId::default(), GlobalElementId::new(&[]));
906 }
907
908 struct DeepStatefulTree {
911 items: usize,
912 depth: usize,
913 }
914
915 impl crate::Render for DeepStatefulTree {
916 fn render(&mut self, _: &mut Window, _: &mut crate::Context<Self>) -> impl IntoElement {
917 use crate::{InteractiveElement as _, ParentElement as _, Styled as _, div, px};
918 let depth = self.depth;
919 div()
920 .flex()
921 .flex_wrap()
922 .size_full()
923 .children((0..self.items).map(move |item| {
924 let mut element = div().id(("leaf", item as u64)).size(px(2.));
925 for level in (0..depth).rev() {
926 element = div()
927 .id(("some-container-element", level as u64))
928 .child(element);
929 }
930 element.id(("item", item as u64)).size(px(4.))
931 }))
932 }
933 }
934
935 #[crate::test]
940 #[ignore = "prints timings; run by hand"]
941 fn frame_cost(cx: &mut crate::TestAppContext) {
942 use crate::AppContext as _;
943 for (items, depth) in [(500, 4), (500, 12), (2000, 12)] {
944 let window = cx.add_window(move |_, _| DeepStatefulTree { items, depth });
945 let window = crate::AnyWindowHandle::from(window);
946 let frame = |cx: &mut crate::TestAppContext| {
947 cx.update_window(window, |_, window, cx| {
948 window.refresh();
949 let started = std::time::Instant::now();
950 window.draw(cx).clear(cx);
951 started.elapsed()
952 })
953 .unwrap()
954 };
955 for _ in 0..5 {
956 frame(cx);
957 }
958 let mut samples: Vec<_> = (0..40).map(|_| frame(cx)).collect();
959 samples.sort();
960 let median = samples[samples.len() / 2];
961 let stateful = items * (depth + 2);
962 eprintln!(
963 "{items} items x {depth} deep ({stateful} stateful elements): median frame {:.2} ms, {:.0} ns per stateful element",
964 median.as_secs_f64() * 1e3,
965 median.as_nanos() as f64 / stateful as f64,
966 );
967 }
968 }
969
970 #[test]
972 #[ignore = "prints timings; run by hand"]
973 fn hash_cost() {
974 let ids = path(11, 7);
975 let id = GlobalElementId::new(&ids);
976 let n = 1_000_000u64;
977 let mut acc = 0u64;
978 let started = std::time::Instant::now();
979 for _ in 0..n {
980 acc ^= fx_hash(&std::hint::black_box(ids.as_slice()));
981 }
982 let walk = started.elapsed();
983 let started = std::time::Instant::now();
984 for _ in 0..n {
985 acc ^= fx_hash(std::hint::black_box(&id));
986 }
987 let cached = started.elapsed();
988 let started = std::time::Instant::now();
989 for _ in 0..n {
990 acc ^= GlobalElementId::new(std::hint::black_box(&ids)).hash;
991 }
992 let build = started.elapsed();
993 eprintln!(
994 "12-deep path: hash by walking ids {:.1} ns, cached {:.1} ns, build (clone + hash once) {:.1} ns [{acc}]",
995 walk.as_nanos() as f64 / n as f64,
996 cached.as_nanos() as f64 / n as f64,
997 build.as_nanos() as f64 / n as f64,
998 );
999 }
1000}