Skip to main content

markdown_editor/
id.rs

1use std::num::NonZeroU64;
2use std::sync::atomic::{AtomicU64, Ordering};
3
4/// Opaque, process-unique block identity (design D1).
5///
6/// Allocated from a global counter like `dock::layout::tree::next_node_id`
7/// and never reused, so an id from a removed block, another document, or a
8/// state from before `set_source` can only fail lookup; it can never alias a
9/// live block.
10#[derive(Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord, Debug)]
11pub struct BlockId(NonZeroU64);
12
13static NEXT_BLOCK_ID: AtomicU64 = AtomicU64::new(1);
14
15impl BlockId {
16    pub(crate) fn next() -> Self {
17        let raw = NEXT_BLOCK_ID.fetch_add(1, Ordering::Relaxed);
18        // The counter starts at 1 and would need 2^64 allocations to wrap.
19        Self(NonZeroU64::new(raw).unwrap_or(NonZeroU64::MIN))
20    }
21
22    /// The raw value, for debugging and logging only.
23    pub fn as_u64(self) -> u64 {
24        self.0.get()
25    }
26}