Skip to main content

concept_graph/
ordinal.rs

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