-
Notifications
You must be signed in to change notification settings - Fork 531
/
Copy pathnamepath.rs
66 lines (55 loc) · 1.39 KB
/
namepath.rs
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
use super::*;
#[derive(Clone, Debug, PartialEq, Eq, Ord, PartialOrd)]
pub(crate) struct Namepath<'src>(Vec<Name<'src>>);
impl<'src> Namepath<'src> {
pub(crate) fn join(&self, name: Name<'src>) -> Self {
Self(self.0.iter().copied().chain(iter::once(name)).collect())
}
pub(crate) fn spaced(&self) -> ModulePath {
ModulePath {
path: self.0.iter().map(|name| name.lexeme().into()).collect(),
spaced: true,
}
}
pub(crate) fn push(&mut self, name: Name<'src>) {
self.0.push(name);
}
pub(crate) fn last(&self) -> &Name<'src> {
self.0.last().unwrap()
}
pub(crate) fn split_last(&self) -> (&Name<'src>, &[Name<'src>]) {
self.0.split_last().unwrap()
}
#[cfg(test)]
pub(crate) fn iter(&self) -> slice::Iter<'_, Name<'src>> {
self.0.iter()
}
#[cfg(test)]
pub(crate) fn len(&self) -> usize {
self.0.len()
}
}
impl Display for Namepath<'_> {
fn fmt(&self, f: &mut Formatter) -> fmt::Result {
for (i, name) in self.0.iter().enumerate() {
if i > 0 {
write!(f, "::")?;
}
write!(f, "{name}")?;
}
Ok(())
}
}
impl<'src> From<Name<'src>> for Namepath<'src> {
fn from(name: Name<'src>) -> Self {
Self(vec![name])
}
}
impl Serialize for Namepath<'_> {
fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
where
S: Serializer,
{
serializer.serialize_str(&format!("{self}"))
}
}