aboutsummaryrefslogtreecommitdiffstats
path: root/src/name.rs
diff options
context:
space:
mode:
authortv <tv@krebsco.de>2026-11-29 14:21:34 +0000
committertv <tv@krebsco.de>2026-11-30 14:59:15 +0000
commiteaac60ba88728bb582778c726e5798156dddfc45 (patch)
tree557f4709762f95a7a440d1fa919dcce3bbf83cb4 /src/name.rs
parent70367d17613ebe501fb2d3e9fa72b16c2eb9c2bd (diff)
enstate: the receptor and the provider, a first version
One program on a library: --plan and --apply of submissions (complete and partial, items required and optional, groups, removal, the chain as order), validators of types and across slots, views put in place by replacing a link, their reactions by systemctl; --status, --materialize; and --pack, a submission from a source list in JSON or TOML, by the config crate's sources. Programs by the protocol of design.md 5.2; tests with shell scripts as validators and renderers.
Diffstat (limited to 'src/name.rs')
-rw-r--r--src/name.rs140
1 files changed, 140 insertions, 0 deletions
diff --git a/src/name.rs b/src/name.rs
new file mode 100644
index 0000000..a1ed0e4
--- /dev/null
+++ b/src/name.rs
@@ -0,0 +1,140 @@
+//! Names of channels and slots, and addresses (docs/design.md, 5.1).
+
+use std::fmt;
+use std::str::FromStr;
+
+use anyhow::{Result, anyhow, bail};
+
+/// Whether `name` is a portable filename (POSIX.1-2017, 3.281) not starting with a
+/// hyphen, and neither `.` nor `..`: `[0-9A-Za-z._][0-9A-Za-z._-]*`.
+pub fn is_name(name: &str) -> bool {
+ let mut chars = name.chars();
+ let portable = |c: char| c.is_ascii_alphanumeric() || c == '.' || c == '_';
+ match chars.next() {
+ Some(first) if portable(first) => {}
+ _ => return false,
+ }
+ chars.all(|c| portable(c) || c == '-') && name != "." && name != ".."
+}
+
+/// `name`, if it is one, else an error saying what it was meant to name.
+pub fn check(what: &str, name: &str) -> Result<()> {
+ if is_name(name) {
+ Ok(())
+ } else {
+ bail!(
+ "{what} {name:?} is not a portable filename ([0-9A-Za-z._][0-9A-Za-z._-]*, not . or ..)"
+ )
+ }
+}
+
+/// `CHANNEL/SLOT` for an entry, `CHANNEL/SLOT/KEY` for a record. A record's key is
+/// everything after the second `/`, so it may hold `/` itself.
+#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
+pub struct Address {
+ pub channel: String,
+ pub slot: String,
+ pub key: Option<String>,
+}
+
+impl Address {
+ pub fn entry(channel: &str, slot: &str) -> Self {
+ Self {
+ channel: channel.to_owned(),
+ slot: slot.to_owned(),
+ key: None,
+ }
+ }
+
+ /// The address of the entry this is, or holds this record.
+ pub fn of_entry(&self) -> Self {
+ Self::entry(&self.channel, &self.slot)
+ }
+
+ /// Whether one of the two is within the other: the same entry, or an entry and one
+ /// of its records, or the same record.
+ pub fn overlaps(&self, other: &Address) -> bool {
+ self.channel == other.channel
+ && self.slot == other.slot
+ && match (&self.key, &other.key) {
+ (Some(one), Some(other)) => one == other,
+ _ => true,
+ }
+ }
+}
+
+impl FromStr for Address {
+ type Err = anyhow::Error;
+
+ fn from_str(text: &str) -> Result<Self> {
+ let mut parts = text.splitn(3, '/');
+ let channel = parts.next().unwrap_or_default();
+ let slot = parts
+ .next()
+ .ok_or_else(|| anyhow!("address {text:?} is not CHANNEL/SLOT or CHANNEL/SLOT/KEY"))?;
+ check("channel", channel)?;
+ check("slot", slot)?;
+ let key = match parts.next() {
+ None => None,
+ Some("") => bail!("address {text:?} has an empty key"),
+ Some(key) => Some(key.to_owned()),
+ };
+ Ok(Self {
+ channel: channel.to_owned(),
+ slot: slot.to_owned(),
+ key,
+ })
+ }
+}
+
+impl fmt::Display for Address {
+ fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
+ write!(f, "{}/{}", self.channel, self.slot)?;
+ if let Some(key) = &self.key {
+ write!(f, "/{key}")?;
+ }
+ Ok(())
+ }
+}
+
+impl serde::Serialize for Address {
+ fn serialize<S: serde::Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
+ serializer.collect_str(self)
+ }
+}
+
+impl<'de> serde::Deserialize<'de> for Address {
+ fn deserialize<D: serde::Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
+ let text = String::deserialize(deserializer)?;
+ text.parse().map_err(serde::de::Error::custom)
+ }
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ #[test]
+ fn names() {
+ for good in ["a", "retiolum.key", "_x", ".hidden", "a-b", "0"] {
+ assert!(is_name(good), "{good}");
+ }
+ for bad in ["", ".", "..", "-a", "a/b", "a b", "รค"] {
+ assert!(!is_name(bad), "{bad}");
+ }
+ }
+
+ #[test]
+ fn addresses() {
+ let record: Address = "fleet/hosts/a/b".parse().unwrap();
+ assert_eq!(record.key.as_deref(), Some("a/b"));
+ assert_eq!(record.to_string(), "fleet/hosts/a/b");
+ let entry: Address = "fleet/hosts".parse().unwrap();
+ assert!(entry.overlaps(&record) && record.overlaps(&entry));
+ let other: Address = "fleet/hosts/c".parse().unwrap();
+ assert!(!other.overlaps(&record));
+ assert!("fleet".parse::<Address>().is_err());
+ assert!("fleet/hosts/".parse::<Address>().is_err());
+ assert!("fleet/../x".parse::<Address>().is_err());
+ }
+}