use std::fmt;
use crate::{InStream, OutStream, SystemException};
#[derive(Debug, Clone, Default, PartialEq, Eq, Hash, PartialOrd, Ord)]
pub struct NameComponent {
pub id: String,
pub kind: String,
}
impl NameComponent {
pub fn new(id: impl Into<String>, kind: impl Into<String>) -> NameComponent {
NameComponent {
id: id.into(),
kind: kind.into(),
}
}
pub fn write(&self, out: &mut OutStream<'_>) -> Result<(), SystemException> {
out.write_string(&self.id)?;
out.write_string(&self.kind)
}
pub fn read(input: &mut InStream<'_>) -> Result<NameComponent, SystemException> {
Ok(NameComponent {
id: input.read_string()?,
kind: input.read_string()?,
})
}
}
pub type Name = Vec<NameComponent>;
pub fn write_name(out: &mut OutStream<'_>, name: &[NameComponent]) -> Result<(), SystemException> {
out.write_len(name.len())?;
for component in name {
component.write(out)?;
}
Ok(())
}
pub fn read_name(input: &mut InStream<'_>) -> Result<Name, SystemException> {
let len = input.read_len(8).map_err(crate::stream::marshal)?;
(0..len).map(|_| NameComponent::read(input)).collect()
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct InvalidName;
impl fmt::Display for InvalidName {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.write_str("invalid name")
}
}
impl std::error::Error for InvalidName {}
pub fn to_name(s: &str) -> Result<Name, InvalidName> {
if s.is_empty() {
return Err(InvalidName);
}
let mut name = Vec::new();
let mut id = String::new();
let mut kind = String::new();
let mut in_kind = false;
let mut seen = false;
let mut chars = s.chars();
while let Some(c) = chars.next() {
match c {
'\\' => {
let escaped = chars.next().ok_or(InvalidName)?;
if in_kind { &mut kind } else { &mut id }.push(escaped);
seen = true;
}
'/' => {
if !seen || trailing_dot(in_kind, &id, &kind) {
return Err(InvalidName);
}
name.push(NameComponent::new(
std::mem::take(&mut id),
std::mem::take(&mut kind),
));
in_kind = false;
seen = false;
}
'.' => {
if in_kind {
return Err(InvalidName);
}
in_kind = true;
seen = true;
}
c => {
if in_kind { &mut kind } else { &mut id }.push(c);
seen = true;
}
}
}
if !seen || trailing_dot(in_kind, &id, &kind) {
return Err(InvalidName);
}
name.push(NameComponent::new(id, kind));
Ok(name)
}
fn trailing_dot(in_kind: bool, id: &str, kind: &str) -> bool {
in_kind && kind.is_empty() && !id.is_empty()
}
pub fn to_string(name: &[NameComponent]) -> Result<String, InvalidName> {
if name.is_empty() {
return Err(InvalidName);
}
let mut s = String::new();
for (i, component) in name.iter().enumerate() {
if i > 0 {
s.push('/');
}
if component.id.is_empty() && component.kind.is_empty() {
s.push('.');
continue;
}
escape_into(&mut s, &component.id);
if !component.kind.is_empty() {
s.push('.');
escape_into(&mut s, &component.kind);
}
}
Ok(s)
}
fn escape_into(s: &mut String, part: &str) {
for c in part.chars() {
if matches!(c, '/' | '.' | '\\') {
s.push('\\');
}
s.push(c);
}
}
#[cfg(test)]
mod tests {
use super::*;
fn nc(id: &str, kind: &str) -> NameComponent {
NameComponent::new(id, kind)
}
#[test]
fn parses_components_and_escapes() {
assert_eq!(
to_name("a.b/c\\/d/.e").unwrap(),
vec![nc("a", "b"), nc("c/d", ""), nc("", "e")]
);
assert_eq!(to_name("x").unwrap(), vec![nc("x", "")]);
assert_eq!(to_name(".").unwrap(), vec![nc("", "")]);
assert_eq!(to_name("a\\.b.c").unwrap(), vec![nc("a.b", "c")]);
assert_eq!(to_name("a\\\\b").unwrap(), vec![nc("a\\b", "")]);
}
#[test]
fn rejects_malformed_names() {
for s in ["", "a//b", "/a", "a/", "a.b.c", "a.", "a./b", "a\\"] {
assert_eq!(to_name(s), Err(InvalidName), "{s:?}");
}
}
#[test]
fn writes_and_reads_back() {
let name = vec![
nc("a", "b"),
nc("c/d", ""),
nc("", "e"),
nc("", ""),
nc("x.y", "z\\"),
];
let s = to_string(&name).unwrap();
assert_eq!(s, "a.b/c\\/d/.e/./x\\.y.z\\\\");
assert_eq!(to_name(&s).unwrap(), name);
assert_eq!(to_string(&[]), Err(InvalidName));
}
}