//! 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, } 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 { 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(&self, serializer: S) -> Result { serializer.collect_str(self) } } impl<'de> serde::Deserialize<'de> for Address { fn deserialize>(deserializer: D) -> Result { 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::
().is_err()); assert!("fleet/hosts/".parse::
().is_err()); assert!("fleet/../x".parse::
().is_err()); } }