Skip to main content

rustorb_core/
name.rs

1//! CosNaming names and their string form, which `corbaname:` URLs use.
2//!
3//! The naming service client in `rustorb-naming` re-exports these; they
4//! live here because [`Orb::string_to_object`](crate::Orb::string_to_object)
5//! resolves `corbaname:` URLs itself.
6
7use std::fmt;
8
9use crate::{InStream, OutStream, SystemException};
10
11/// `CosNaming::NameComponent`: one step of a [`Name`].
12#[derive(Debug, Clone, Default, PartialEq, Eq, Hash, PartialOrd, Ord)]
13pub struct NameComponent {
14    /// The identifier.
15    pub id: String,
16    /// The kind, often empty.
17    pub kind: String,
18}
19
20impl NameComponent {
21    /// A component with `id` and `kind`.
22    pub fn new(id: impl Into<String>, kind: impl Into<String>) -> NameComponent {
23        NameComponent {
24            id: id.into(),
25            kind: kind.into(),
26        }
27    }
28
29    /// Writes the component as the `NameComponent` struct.
30    pub fn write(&self, out: &mut OutStream<'_>) -> Result<(), SystemException> {
31        out.write_string(&self.id)?;
32        out.write_string(&self.kind)
33    }
34
35    /// Reads a `NameComponent` struct.
36    pub fn read(input: &mut InStream<'_>) -> Result<NameComponent, SystemException> {
37        Ok(NameComponent {
38            id: input.read_string()?,
39            kind: input.read_string()?,
40        })
41    }
42}
43
44/// `CosNaming::Name`: a sequence of components, from the outermost context.
45pub type Name = Vec<NameComponent>;
46
47/// Writes a `CosNaming::Name`.
48pub fn write_name(out: &mut OutStream<'_>, name: &[NameComponent]) -> Result<(), SystemException> {
49    out.write_len(name.len())?;
50    for component in name {
51        component.write(out)?;
52    }
53    Ok(())
54}
55
56/// Reads a `CosNaming::Name`.
57pub fn read_name(input: &mut InStream<'_>) -> Result<Name, SystemException> {
58    // Each component takes at least two empty strings (8 bytes).
59    let len = input.read_len(8).map_err(crate::stream::marshal)?;
60    (0..len).map(|_| NameComponent::read(input)).collect()
61}
62
63/// A stringified name is malformed, or a name has no components
64/// (`CosNaming::NamingContext::InvalidName` when the conversion is local).
65#[derive(Debug, Clone, Copy, PartialEq, Eq)]
66pub struct InvalidName;
67
68impl fmt::Display for InvalidName {
69    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
70        f.write_str("invalid name")
71    }
72}
73
74impl std::error::Error for InvalidName {}
75
76/// Parses a stringified name, as `NamingContextExt::to_name` does:
77/// components are separated by `/`, the id and kind of a component by
78/// `.`, and `\` escapes the next character. `a.b/c\/d/.e` is the name
79/// `[("a", "b"), ("c/d", ""), ("", "e")]`; `.` alone is a component with
80/// an empty id and kind.
81///
82/// An empty string, an empty component (`a//b`), a component ending in
83/// `.` (`a.`), a second unescaped `.` in a component, or a trailing `\`
84/// are invalid.
85pub fn to_name(s: &str) -> Result<Name, InvalidName> {
86    if s.is_empty() {
87        return Err(InvalidName);
88    }
89    let mut name = Vec::new();
90    let mut id = String::new();
91    let mut kind = String::new();
92    // Whether the current component has seen its `.`, and any character.
93    let mut in_kind = false;
94    let mut seen = false;
95    let mut chars = s.chars();
96    while let Some(c) = chars.next() {
97        match c {
98            '\\' => {
99                let escaped = chars.next().ok_or(InvalidName)?;
100                if in_kind { &mut kind } else { &mut id }.push(escaped);
101                seen = true;
102            }
103            '/' => {
104                if !seen || trailing_dot(in_kind, &id, &kind) {
105                    return Err(InvalidName);
106                }
107                name.push(NameComponent::new(
108                    std::mem::take(&mut id),
109                    std::mem::take(&mut kind),
110                ));
111                in_kind = false;
112                seen = false;
113            }
114            '.' => {
115                if in_kind {
116                    return Err(InvalidName);
117                }
118                in_kind = true;
119                seen = true;
120            }
121            c => {
122                if in_kind { &mut kind } else { &mut id }.push(c);
123                seen = true;
124            }
125        }
126    }
127    if !seen || trailing_dot(in_kind, &id, &kind) {
128        return Err(InvalidName);
129    }
130    name.push(NameComponent::new(id, kind));
131    Ok(name)
132}
133
134/// Whether a component ends with the `.` before an empty kind, as in `a.`,
135/// which is not allowed (only `.` alone has an empty kind after its `.`).
136fn trailing_dot(in_kind: bool, id: &str, kind: &str) -> bool {
137    in_kind && kind.is_empty() && !id.is_empty()
138}
139
140/// Writes a name in the string form [`to_name`] reads, as
141/// `NamingContextExt::to_string` does. An empty name is invalid.
142pub fn to_string(name: &[NameComponent]) -> Result<String, InvalidName> {
143    if name.is_empty() {
144        return Err(InvalidName);
145    }
146    let mut s = String::new();
147    for (i, component) in name.iter().enumerate() {
148        if i > 0 {
149            s.push('/');
150        }
151        if component.id.is_empty() && component.kind.is_empty() {
152            s.push('.');
153            continue;
154        }
155        escape_into(&mut s, &component.id);
156        if !component.kind.is_empty() {
157            s.push('.');
158            escape_into(&mut s, &component.kind);
159        }
160    }
161    Ok(s)
162}
163
164fn escape_into(s: &mut String, part: &str) {
165    for c in part.chars() {
166        if matches!(c, '/' | '.' | '\\') {
167            s.push('\\');
168        }
169        s.push(c);
170    }
171}
172
173#[cfg(test)]
174mod tests {
175    use super::*;
176
177    fn nc(id: &str, kind: &str) -> NameComponent {
178        NameComponent::new(id, kind)
179    }
180
181    #[test]
182    fn parses_components_and_escapes() {
183        assert_eq!(
184            to_name("a.b/c\\/d/.e").unwrap(),
185            vec![nc("a", "b"), nc("c/d", ""), nc("", "e")]
186        );
187        assert_eq!(to_name("x").unwrap(), vec![nc("x", "")]);
188        assert_eq!(to_name(".").unwrap(), vec![nc("", "")]);
189        assert_eq!(to_name("a\\.b.c").unwrap(), vec![nc("a.b", "c")]);
190        assert_eq!(to_name("a\\\\b").unwrap(), vec![nc("a\\b", "")]);
191    }
192
193    #[test]
194    fn rejects_malformed_names() {
195        for s in ["", "a//b", "/a", "a/", "a.b.c", "a.", "a./b", "a\\"] {
196            assert_eq!(to_name(s), Err(InvalidName), "{s:?}");
197        }
198    }
199
200    #[test]
201    fn writes_and_reads_back() {
202        let name = vec![
203            nc("a", "b"),
204            nc("c/d", ""),
205            nc("", "e"),
206            nc("", ""),
207            nc("x.y", "z\\"),
208        ];
209        let s = to_string(&name).unwrap();
210        assert_eq!(s, "a.b/c\\/d/.e/./x\\.y.z\\\\");
211        assert_eq!(to_name(&s).unwrap(), name);
212        assert_eq!(to_string(&[]), Err(InvalidName));
213    }
214}