aboutsummaryrefslogtreecommitdiffstats
path: root/src/name.rs
blob: a1ed0e4591054bb2d3fe1687d82fe66e8f929763 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
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());
    }
}