Guide API
Skip to main content

tvision_rs/view/
id.rs

1//! `ViewId`, the global view identity (documented on the type).
2
3use std::num::NonZeroU64;
4use std::sync::atomic::{AtomicU64, Ordering};
5
6/// A lightweight, globally-unique view identity. `Copy`, carries no
7/// reference into the tree, so it can be stored freely (sibling links, focus
8/// stacks, capture handlers). Identity is `ViewId` equality.
9///
10/// Global view-identity minter.
11///
12/// ## Why this exists
13///
14/// A view tree needs links in every direction: each view to its parent, each
15/// view to its siblings, and each group to its focused/selected child. Rust
16/// forbids aliased mutable references, so those links cannot all be live
17/// pointers. tvision-rs splits them into two clean pieces:
18///
19/// * **Downward ownership is a tree** — a `Group` owns
20///   `children: Vec<Box<dyn View>>`.
21/// * **Up/sideways links become [`ViewId`] handles** — a lightweight identity
22///   that can be stored cheaply anywhere without borrowing the tree.
23///
24/// A [`ViewId`] is *not* an index into any store. It is a globally-unique
25/// identity, minted once at [`Group::insert`](crate::view::Group::insert) and
26/// stamped into the view's own [`ViewState`](crate::view::ViewState). Resolving a
27/// `ViewId` back to a `&mut dyn View` is a tree-walk
28/// ([`View::find_mut`](crate::view::View::find_mut)) performed by the downward
29/// context, not by the id itself.
30///
31/// ## Design
32///
33/// Ids are **process-global and monotonic**: a single `static AtomicU64`
34/// counter, never reset, never reused. A stale handle (its view removed) simply
35/// matches nothing in the tree-walk; there is no slot to alias, so no
36/// generational validation is needed (the earlier per-`Group` generational arena
37/// guarded an ABA hazard that the by-identity child scan cannot have). The
38/// `NonZeroU64` gives `Option<ViewId>` a niche, so it costs no extra size; use
39/// `Option<ViewId>` (not a sentinel value) to represent "no link / null". The
40/// `u64` space never realistically exhausts (mirrors `TimerId`).
41///
42/// Ids are **process-global and monotonic** — minted once at `Group::insert`,
43/// never reused. A stale handle (its view removed) therefore matches nothing and
44/// simply fails to resolve via [`View::find_mut`](crate::view::View::find_mut);
45/// there is no slot to alias, so no generational validation is needed. The
46/// `NonZeroU64` gives `Option<ViewId>` a niche (no discriminant word). The `u64`
47/// space never realistically exhausts (mirrors `TimerId`).
48///
49/// # Turbo Vision heritage
50///
51/// Replaces the raw `TView*` pointer web (`owner`, the `next`/`prev` sibling
52/// ring, `current`/`selected`) with owned tree edges plus by-value identity
53/// handles (deviation D3).
54///
55/// The by-value successor to a raw `TView*` used for `owner` / sibling /
56/// `current` links (deviation D3).
57#[derive(Clone, Copy, PartialEq, Eq, Hash, Debug)]
58pub struct ViewId(NonZeroU64);
59
60/// The global id counter. Starts at 1 so the first id is non-zero.
61static NEXT_VIEW_ID: AtomicU64 = AtomicU64::new(1);
62
63impl ViewId {
64    /// Mint a fresh, globally-unique id. Called by
65    /// [`Group::insert`](crate::view::Group::insert).
66    pub fn next() -> ViewId {
67        let n = NEXT_VIEW_ID.fetch_add(1, Ordering::Relaxed);
68        // fetch_add starts at 1 and only increases; n is never 0 in practice.
69        ViewId(NonZeroU64::new(n).expect("view id counter starts at 1 and increases"))
70    }
71}
72
73// ── Tests ─────────────────────────────────────────────────────────────────────
74
75#[cfg(test)]
76mod tests {
77    use super::*;
78    use std::mem::size_of;
79
80    #[test]
81    fn niche_optimization() {
82        // The NonZeroU64 gives Option<ViewId> a niche so it needs no extra
83        // discriminant word.
84        assert_eq!(size_of::<Option<ViewId>>(), size_of::<ViewId>());
85    }
86
87    #[test]
88    fn next_returns_distinct_strictly_increasing_ids() {
89        // The counter is process-global (shared across all tests), so only
90        // relative distinctness/ordering within this test is meaningful — never
91        // assert literal id values.
92        let a = ViewId::next();
93        let b = ViewId::next();
94        let c = ViewId::next();
95        assert_ne!(a, b);
96        assert_ne!(b, c);
97        assert_ne!(a, c);
98        assert!(a.0 < b.0, "ids are strictly increasing");
99        assert!(b.0 < c.0, "ids are strictly increasing");
100    }
101}