pub const MAX_DEPTH: u8 = 4;
pub const MAX_ANCESTOR_PATH: usize = MAX_DEPTH as usize + 1;
#[derive(
Debug,
Clone,
Copy,
PartialEq,
Eq,
Hash,
Default,
PartialOrd,
Ord,
serde::Serialize,
serde::Deserialize,
)]
pub struct SubnetId(u32);
impl SubnetId {
pub const GLOBAL: Self = Self(0);
pub const MAX_DEPTH: u8 = MAX_DEPTH;
#[expect(
clippy::expect_used,
reason = "documented panicking variant; try_new is the fallible alternative for untrusted input"
)]
pub fn new(levels: &[u8]) -> Self {
Self::try_new(levels).expect("SubnetId::new: too many levels (use try_new for fallible)")
}
pub fn try_new(levels: &[u8]) -> Result<Self, super::SubnetError> {
if levels.len() > MAX_DEPTH as usize {
return Err(super::SubnetError::TooManyLevels {
got: levels.len(),
max: MAX_DEPTH,
});
}
let mut val = 0u32;
for (i, &level) in levels.iter().enumerate() {
val |= (level as u32) << (24 - i * 8);
}
Ok(Self(val))
}
#[inline]
pub const fn from_raw(raw: u32) -> Self {
Self(raw)
}
#[inline]
pub const fn raw(self) -> u32 {
self.0
}
#[inline]
pub const fn level(self, n: u8) -> u8 {
if n >= MAX_DEPTH {
return 0;
}
((self.0 >> (24 - n * 8)) & 0xFF) as u8
}
pub fn depth(self) -> u8 {
for d in (0..MAX_DEPTH).rev() {
if self.level(d) != 0 {
return d + 1;
}
}
0
}
#[inline]
pub const fn is_global(self) -> bool {
self.0 == 0
}
pub fn parent(self) -> Self {
let d = self.depth();
if d == 0 {
return Self::GLOBAL;
}
let mask = Self::mask_for_depth(d - 1);
Self(self.0 & mask)
}
#[inline]
pub fn is_ancestor_of(self, other: Self) -> bool {
self.is_ancestor_or_self_of(other)
}
#[inline]
pub fn is_ancestor_or_self_of(self, target: Self) -> bool {
if self.is_global() {
return true;
}
let d = self.depth();
let mask = Self::mask_for_depth(d);
(self.0 & mask) == (target.0 & mask)
}
#[inline]
pub fn ancestor_path(self) -> AncestorPath {
AncestorPath { next: Some(self) }
}
pub fn common_ancestor(self, other: Self) -> Self {
let limit = self.depth().min(other.depth());
let mut d = 0u8;
while d < limit && self.level(d) == other.level(d) {
d += 1;
}
Self(self.0 & Self::mask_for_depth(d))
}
#[inline]
pub const fn is_same_subnet(self, other: Self) -> bool {
self.0 == other.0
}
pub fn is_sibling(self, other: Self) -> bool {
let d1 = self.depth();
let d2 = other.depth();
if d1 != d2 || d1 == 0 {
return false;
}
let mask = Self::mask_for_depth(d1 - 1);
(self.0 & mask) == (other.0 & mask) && self.0 != other.0
}
#[inline]
pub const fn mask_for_depth(depth: u8) -> u32 {
match depth {
0 => 0x00000000,
1 => 0xFF000000,
2 => 0xFFFF0000,
3 => 0xFFFFFF00,
_ => 0xFFFFFFFF,
}
}
}
#[derive(Debug, Clone, Copy)]
pub struct AncestorPath {
next: Option<SubnetId>,
}
impl Iterator for AncestorPath {
type Item = SubnetId;
fn next(&mut self) -> Option<SubnetId> {
let current = self.next?;
self.next = (!current.is_global()).then(|| current.parent());
Some(current)
}
fn size_hint(&self) -> (usize, Option<usize>) {
let remaining = match self.next {
None => 0,
Some(id) => id.raw().to_be_bytes().iter().filter(|b| **b != 0).count() + 1,
};
(remaining, Some(remaining))
}
}
impl ExactSizeIterator for AncestorPath {}
impl std::fmt::Display for SubnetId {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
if self.is_global() {
write!(f, "global")
} else {
let d = self.depth();
for i in 0..d {
if i > 0 {
write!(f, ".")?;
}
write!(f, "{}", self.level(i))?;
}
Ok(())
}
}
}
impl std::str::FromStr for SubnetId {
type Err = super::SubnetError;
fn from_str(s: &str) -> Result<Self, Self::Err> {
let trimmed = s.trim();
if trimmed.eq_ignore_ascii_case("global") {
return Ok(Self::GLOBAL);
}
if trimmed.is_empty() {
return Err(super::SubnetError::ParseFailed {
input: s.to_string(),
reason: "empty".into(),
});
}
let parts: Vec<&str> = trimmed.split('.').collect();
if parts.len() > MAX_DEPTH as usize {
return Err(super::SubnetError::TooManyLevels {
got: parts.len(),
max: MAX_DEPTH,
});
}
let mut levels: Vec<u8> = Vec::with_capacity(parts.len());
for p in parts {
match p.parse::<u8>() {
Ok(level) => levels.push(level),
Err(e) => {
return Err(super::SubnetError::ParseFailed {
input: s.to_string(),
reason: format!("level `{p}` not a u8: {e}"),
})
}
}
}
Self::try_new(&levels)
}
}
pub type TopologySubnetId = SubnetId;
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_global() {
assert!(SubnetId::GLOBAL.is_global());
assert_eq!(SubnetId::GLOBAL.depth(), 0);
assert_eq!(SubnetId::GLOBAL.raw(), 0);
}
#[test]
fn test_new() {
let id = SubnetId::new(&[3, 7]);
assert_eq!(id.level(0), 3);
assert_eq!(id.level(1), 7);
assert_eq!(id.level(2), 0);
assert_eq!(id.level(3), 0);
assert_eq!(id.depth(), 2);
assert!(!id.is_global());
}
#[test]
fn test_full_depth() {
let id = SubnetId::new(&[1, 2, 3, 4]);
assert_eq!(id.depth(), 4);
assert_eq!(id.level(0), 1);
assert_eq!(id.level(1), 2);
assert_eq!(id.level(2), 3);
assert_eq!(id.level(3), 4);
assert_eq!(id.raw(), 0x01020304);
}
#[test]
fn test_parent() {
let id = SubnetId::new(&[3, 7, 2]);
let parent = id.parent();
assert_eq!(parent, SubnetId::new(&[3, 7]));
let grandparent = parent.parent();
assert_eq!(grandparent, SubnetId::new(&[3]));
let root = grandparent.parent();
assert_eq!(root, SubnetId::GLOBAL);
assert_eq!(SubnetId::GLOBAL.parent(), SubnetId::GLOBAL);
}
#[test]
fn test_is_ancestor_of() {
let region = SubnetId::new(&[3]);
let fleet = SubnetId::new(&[3, 7]);
let vehicle = SubnetId::new(&[3, 7, 2]);
let other_fleet = SubnetId::new(&[3, 8]);
let other_region = SubnetId::new(&[4]);
assert!(SubnetId::GLOBAL.is_ancestor_of(region));
assert!(SubnetId::GLOBAL.is_ancestor_of(vehicle));
assert!(region.is_ancestor_of(fleet));
assert!(region.is_ancestor_of(vehicle));
assert!(fleet.is_ancestor_of(vehicle));
assert!(!vehicle.is_ancestor_of(fleet));
assert!(!fleet.is_ancestor_of(region));
assert!(!region.is_ancestor_of(other_region));
assert!(!fleet.is_ancestor_of(other_fleet));
assert!(fleet.is_ancestor_of(fleet));
}
#[test]
fn ancestor_or_self_truth_table() {
let a = SubnetId::new(&[3]);
let a_b = SubnetId::new(&[3, 7]);
let a_c = SubnetId::new(&[3, 8]);
let a_b_c = SubnetId::new(&[3, 7, 2]);
let zero = SubnetId::GLOBAL;
assert!(a.is_ancestor_or_self_of(a));
assert!(a.is_ancestor_or_self_of(a_b));
assert!(!a_b.is_ancestor_or_self_of(a));
assert!(!a_b.is_ancestor_or_self_of(a_c));
assert!(a_b.is_ancestor_or_self_of(a_b_c));
assert!(zero.is_ancestor_or_self_of(zero));
assert!(zero.is_ancestor_or_self_of(a));
assert!(zero.is_ancestor_or_self_of(a_b_c));
assert!(!a.is_ancestor_or_self_of(zero));
assert!(!a_b_c.is_ancestor_or_self_of(zero));
assert_eq!(a.is_ancestor_of(a_b), a.is_ancestor_or_self_of(a_b));
assert_eq!(a_b.is_ancestor_of(zero), a_b.is_ancestor_or_self_of(zero));
}
#[test]
fn ancestor_path_is_deepest_first_and_bounded() {
let full: Vec<SubnetId> = SubnetId::new(&[1, 2, 3, 4]).ancestor_path().collect();
assert_eq!(
full,
vec![
SubnetId::new(&[1, 2, 3, 4]),
SubnetId::new(&[1, 2, 3]),
SubnetId::new(&[1, 2]),
SubnetId::new(&[1]),
SubnetId::GLOBAL,
],
);
assert_eq!(full.len(), MAX_ANCESTOR_PATH);
assert_eq!(
SubnetId::GLOBAL.ancestor_path().collect::<Vec<_>>(),
vec![SubnetId::GLOBAL],
);
for raw in [
0x00000000u32,
0x03000000,
0x03070000,
0x03070200,
0x01020304,
0x03000700,
0x00000009,
0x00070009,
] {
let id = SubnetId::from_raw(raw);
let path = id.ancestor_path();
let predicted = path.len();
let walked: Vec<SubnetId> = path.collect();
assert_eq!(predicted, walked.len(), "size_hint must be exact for {id}");
assert!(walked.len() <= MAX_ANCESTOR_PATH);
assert_eq!(walked[0], id, "the path starts at self");
assert_eq!(*walked.last().unwrap(), SubnetId::GLOBAL, "and ends global");
}
}
#[test]
fn common_ancestor_is_the_meet_of_the_containment_order() {
let cases = [
(&[3u8, 7, 2][..], &[3u8, 7, 9][..], &[3u8, 7][..]),
(&[3, 7, 2], &[3, 8, 2], &[3]),
(&[3, 7], &[4, 7], &[]),
(&[3, 7], &[3, 7], &[3, 7]),
(&[3, 7], &[3], &[3]),
(&[3], &[], &[]),
(&[], &[], &[]),
];
for (a, b, expected) in cases {
let (a, b) = (SubnetId::new(a), SubnetId::new(b));
let meet = SubnetId::new(expected);
assert_eq!(a.common_ancestor(b), meet, "{a} ∧ {b}");
assert_eq!(b.common_ancestor(a), meet, "commutative: {b} ∧ {a}");
}
let universe: Vec<SubnetId> = [
&[][..],
&[3][..],
&[4][..],
&[3, 7][..],
&[3, 8][..],
&[3, 7, 2][..],
&[3, 7, 9][..],
]
.iter()
.map(|l| SubnetId::new(l))
.collect();
for &a in &universe {
for &b in &universe {
let meet = a.common_ancestor(b);
for &scope in &universe {
let contains_both =
scope.is_ancestor_or_self_of(a) && scope.is_ancestor_or_self_of(b);
assert_eq!(
contains_both,
scope.is_ancestor_or_self_of(meet),
"scope {scope} vs {a}/{b} (meet {meet})",
);
}
assert!(a.ancestor_path().any(|s| s == meet));
assert!(b.ancestor_path().any(|s| s == meet));
}
}
}
#[test]
fn the_meet_property_holds_over_raw_paths_including_interior_zeros() {
let alphabet = [0u8, 3, 7];
let mut universe = Vec::with_capacity(81);
for &a in &alphabet {
for &b in &alphabet {
for &c in &alphabet {
for &d in &alphabet {
universe.push(SubnetId::from_raw(
(a as u32) << 24 | (b as u32) << 16 | (c as u32) << 8 | (d as u32),
));
}
}
}
}
assert_eq!(universe.len(), 81);
assert!(
universe.contains(&SubnetId::from_raw(0x03_00_07_00)),
"the domain must include the interior-zero path that broke the meet",
);
for &a in &universe {
for &b in &universe {
let meet = a.common_ancestor(b);
assert_eq!(meet, b.common_ancestor(a), "commutative: {a} ∧ {b}");
for &scope in &universe {
let contains_both =
scope.is_ancestor_or_self_of(a) && scope.is_ancestor_or_self_of(b);
assert_eq!(
contains_both,
scope.is_ancestor_or_self_of(meet),
"scope {scope} vs {a}/{b} (meet {meet})",
);
}
assert!(
a.ancestor_path().any(|s| s == meet),
"meet {meet} missing from the chain of {a}",
);
assert!(
b.ancestor_path().any(|s| s == meet),
"meet {meet} missing from the chain of {b}",
);
}
}
}
#[test]
fn a_path_is_its_own_common_ancestor() {
for raw in [
0x00_00_00_00u32,
0x03_00_00_00,
0x03_00_07_00,
0x03_00_00_09,
0x00_00_00_09,
0x03_07_02_05,
] {
let id = SubnetId::from_raw(raw);
assert_eq!(
id.common_ancestor(id),
id,
"{id} ({raw:#010x}) must be its own meet",
);
}
}
#[test]
fn test_is_sibling() {
let fleet_a = SubnetId::new(&[3, 7]);
let fleet_b = SubnetId::new(&[3, 8]);
let fleet_c = SubnetId::new(&[4, 7]);
let region = SubnetId::new(&[3]);
assert!(fleet_a.is_sibling(fleet_b));
assert!(!fleet_a.is_sibling(fleet_c)); assert!(!fleet_a.is_sibling(fleet_a)); assert!(!fleet_a.is_sibling(region)); }
#[test]
fn test_display() {
assert_eq!(format!("{}", SubnetId::GLOBAL), "global");
assert_eq!(format!("{}", SubnetId::new(&[3])), "3");
assert_eq!(format!("{}", SubnetId::new(&[3, 7])), "3.7");
assert_eq!(format!("{}", SubnetId::new(&[1, 2, 3, 4])), "1.2.3.4");
}
#[test]
fn test_from_raw() {
let id = SubnetId::from_raw(0x03070000);
assert_eq!(id, SubnetId::new(&[3, 7]));
}
#[test]
fn test_mask_for_depth() {
assert_eq!(SubnetId::mask_for_depth(0), 0x00000000);
assert_eq!(SubnetId::mask_for_depth(1), 0xFF000000);
assert_eq!(SubnetId::mask_for_depth(2), 0xFFFF0000);
assert_eq!(SubnetId::mask_for_depth(3), 0xFFFFFF00);
assert_eq!(SubnetId::mask_for_depth(4), 0xFFFFFFFF);
}
#[test]
fn try_new_rejects_too_many_levels() {
use super::super::error::SubnetError;
let err = SubnetId::try_new(&[1, 2, 3, 4, 5]).unwrap_err();
assert!(
matches!(err, SubnetError::TooManyLevels { got: 5, max: 4 }),
"expected TooManyLevels{{got: 5, max: 4}}, got {:?}",
err
);
}
#[test]
fn try_new_accepts_max_depth() {
let id = SubnetId::try_new(&[1, 2, 3, 4]).expect("4 levels must be accepted (boundary)");
assert_eq!(id, SubnetId::new(&[1, 2, 3, 4]));
}
#[test]
fn try_new_accepts_empty() {
let id = SubnetId::try_new(&[]).expect("0 levels (GLOBAL) must be accepted");
assert_eq!(id, SubnetId::GLOBAL);
}
#[test]
fn from_str_round_trips_global_and_dotted_levels() {
use std::str::FromStr;
assert_eq!(SubnetId::from_str("global").unwrap(), SubnetId::GLOBAL);
assert_eq!(SubnetId::from_str("GLOBAL").unwrap(), SubnetId::GLOBAL);
assert_eq!(SubnetId::from_str("3").unwrap(), SubnetId::new(&[3]));
assert_eq!(SubnetId::from_str("3.7").unwrap(), SubnetId::new(&[3, 7]));
assert_eq!(
SubnetId::from_str("1.2.3.4").unwrap(),
SubnetId::new(&[1, 2, 3, 4])
);
let id = SubnetId::new(&[3, 7, 2]);
assert_eq!(SubnetId::from_str(&id.to_string()).unwrap(), id);
}
#[test]
fn from_str_rejects_garbage() {
use super::super::error::SubnetError;
use std::str::FromStr;
assert!(matches!(
SubnetId::from_str("").unwrap_err(),
SubnetError::ParseFailed { .. }
));
assert!(matches!(
SubnetId::from_str("256").unwrap_err(),
SubnetError::ParseFailed { .. }
));
assert!(matches!(
SubnetId::from_str("1.2.3.4.5").unwrap_err(),
SubnetError::TooManyLevels { got: 5, max: 4 }
));
assert!(matches!(
SubnetId::from_str("not-a-number").unwrap_err(),
SubnetError::ParseFailed { .. }
));
}
}