Skip to main content

concept_graph/
ordinal.rs

1//! Dense ordinals: the graph's own keys.
2//!
3//! A loader assigns every concept of a code system version a dense ordinal
4//! and every relationship type an edge kind; the graph never sees a native
5//! code. Both are `u32`, which bounds a version at about four billion
6//! concepts and keeps roaring bitmaps at their native width.
7
8use std::fmt;
9
10/// The position of a concept in a code system version.
11#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord)]
12pub struct Ordinal(u32);
13
14impl Ordinal {
15    /// Wraps a position.
16    #[must_use]
17    pub const fn new(index: u32) -> Self {
18        Self(index)
19    }
20
21    /// The position.
22    #[must_use]
23    pub const fn index(self) -> u32 {
24        self.0
25    }
26
27    /// The position as a `usize`, for indexing.
28    #[must_use]
29    pub fn as_usize(self) -> usize {
30        usize::try_from(self.0).unwrap_or(usize::MAX)
31    }
32}
33
34impl fmt::Display for Ordinal {
35    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
36        write!(f, "#{}", self.0)
37    }
38}
39
40/// The kind of an edge: the ordinal of its relationship type concept.
41#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord)]
42pub struct EdgeKind(u32);
43
44impl EdgeKind {
45    /// Wraps a kind.
46    #[must_use]
47    pub const fn new(index: u32) -> Self {
48        Self(index)
49    }
50
51    /// The kind.
52    #[must_use]
53    pub const fn index(self) -> u32 {
54        self.0
55    }
56}
57
58impl fmt::Display for EdgeKind {
59    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
60        write!(f, "kind#{}", self.0)
61    }
62}
63
64/// `u32` to `usize` without a lossy cast.
65#[must_use]
66pub fn to_usize(value: u32) -> usize {
67    usize::try_from(value).unwrap_or(usize::MAX)
68}