Skip to main content

zaun_community_protocol/signed/bot_package/
rules.rs

1//! Field rules of `BotPackage` (§4.9): `app_id`, `version` and `world`, and version
2//! precedence for updates (§8.13).
3
4use std::cmp::Ordering;
5
6use super::{APP_ID_MAX, VERSION_MAX, WORLD_MAX};
7
8/// Lowercase reverse-DNS: `[a-z0-9-]+(\.[a-z0-9-]+)+`, 3–64 bytes.
9#[must_use]
10pub fn valid_app_id(app_id: &str) -> bool {
11    let label = |l: &str| {
12        !l.is_empty()
13            && l.bytes()
14                .all(|b| b.is_ascii_lowercase() || b.is_ascii_digit() || b == b'-')
15    };
16    (3..=APP_ID_MAX).contains(&app_id.len()) && app_id.contains('.') && app_id.split('.').all(label)
17}
18
19/// A numeric identifier: digits without a leading zero.
20fn numeric(id: &str) -> bool {
21    !id.is_empty() && id.bytes().all(|b| b.is_ascii_digit()) && (id == "0" || !id.starts_with('0'))
22}
23
24/// A pre-release identifier: alphanumerics and hyphens; numeric ones without leading zeros.
25fn pre_id(id: &str) -> bool {
26    let alnum = !id.is_empty() && id.bytes().all(|b| b.is_ascii_alphanumeric() || b == b'-');
27    alnum && (!id.bytes().all(|b| b.is_ascii_digit()) || numeric(id))
28}
29
30/// Splits `MAJOR.MINOR.PATCH[-PRE]`; `None` when it is not Semantic Versioning without build
31/// metadata.
32fn split(version: &str) -> Option<([u64; 3], Option<&str>)> {
33    let (core, pre) = match version.split_once('-') {
34        Some((core, pre)) => (core, Some(pre)),
35        None => (version, None),
36    };
37    let mut parts = core.split('.');
38    let mut out = [0u64; 3];
39    for slot in &mut out {
40        let part = parts.next().filter(|p| numeric(p))?;
41        *slot = part.parse().ok()?;
42    }
43    if parts.next().is_some() || pre.is_some_and(|p| !p.split('.').all(pre_id)) {
44        return None;
45    }
46    Some((out, pre))
47}
48
49/// Semantic Versioning 2.0.0 without build metadata, ≤ 64 bytes.
50#[must_use]
51pub fn valid_version(version: &str) -> bool {
52    version.len() <= VERSION_MAX && split(version).is_some()
53}
54
55/// The `zaun:bot` worlds a host built from this crate runs; a package for any other is
56/// refused at install and update (it could never load). Kept equal to the bot runtime's list.
57pub const SUPPORTED_WORLDS: &[&str] = &["zaun:bot/bot@0.1.0", "zaun:bot/bot@0.2.0"];
58
59/// `zaun:bot/bot@<semver>`, ≤ 64 bytes.
60#[must_use]
61pub fn valid_world(world: &str) -> bool {
62    world.len() <= WORLD_MAX
63        && world
64            .strip_prefix("zaun:bot/bot@")
65            .is_some_and(|v| split(v).is_some())
66}
67
68/// Semantic Versioning precedence of two versions; `None` when either is invalid. An update
69/// must be [`Ordering::Greater`] than the installed version (§8.13).
70#[must_use]
71pub fn compare_versions(a: &str, b: &str) -> Option<Ordering> {
72    let ((ca, pa), (cb, pb)) = (split(a)?, split(b)?);
73    Some(ca.cmp(&cb).then_with(|| match (pa, pb) {
74        (None, None) => Ordering::Equal,
75        (None, Some(_)) => Ordering::Greater,
76        (Some(_), None) => Ordering::Less,
77        (Some(x), Some(y)) => pre_cmp(x, y),
78    }))
79}
80
81/// Pre-release precedence: identifier by identifier, numeric below alphanumeric, a shorter
82/// list below a longer one with the same prefix.
83fn pre_cmp(a: &str, b: &str) -> Ordering {
84    let (mut xs, mut ys) = (a.split('.'), b.split('.'));
85    loop {
86        let (x, y) = match (xs.next(), ys.next()) {
87            (None, None) => return Ordering::Equal,
88            (None, Some(_)) => return Ordering::Less,
89            (Some(_), None) => return Ordering::Greater,
90            (Some(x), Some(y)) => (x, y),
91        };
92        let order = match (x.parse::<u64>(), y.parse::<u64>()) {
93            (Ok(m), Ok(n)) => m.cmp(&n),
94            (Ok(_), Err(_)) => Ordering::Less,
95            (Err(_), Ok(_)) => Ordering::Greater,
96            (Err(_), Err(_)) => x.cmp(y),
97        };
98        if order != Ordering::Equal {
99            return order;
100        }
101    }
102}