Skip to main content

cranpose_core/
packed_node_id.rs

1//! A node id or none in one word.
2
3use crate::NodeId;
4
5/// A node id or none in one word, where `Option<NodeId>` takes two: no node
6/// takes the id `usize::MAX`, as ids index the applier's nodes, and the
7/// value keeps it for none.
8#[derive(Clone, Copy, PartialEq, Eq, Hash)]
9pub struct PackedNodeId(NodeId);
10
11// The id that stands for none.
12const NONE: NodeId = NodeId(usize::MAX);
13
14impl PackedNodeId {
15    /// No node.
16    pub const NONE: Self = Self(NONE);
17
18    /// `id` in one word.
19    pub const fn new(id: Option<NodeId>) -> Self {
20        match id {
21            Some(id) => Self(id),
22            None => Self(NONE),
23        }
24    }
25
26    /// The id, `None` for no node.
27    #[inline]
28    pub fn get(self) -> Option<NodeId> {
29        // With `then_some`, LLVM compiles the composer's group opening five
30        // instructions longer a group.
31        Some(self.0).filter(|&id| id != NONE)
32    }
33}
34
35impl From<Option<NodeId>> for PackedNodeId {
36    fn from(id: Option<NodeId>) -> Self {
37        debug_assert_ne!(id, Some(NONE), "no node takes the none id");
38        Self::new(id)
39    }
40}
41
42impl std::fmt::Debug for PackedNodeId {
43    fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
44        self.get().fmt(formatter)
45    }
46}