af_core/test/
path.rs

1// Copyright © 2021 Alexandra Frydl
2//
3// This Source Code Form is subject to the terms of the Mozilla Public
4// License, v. 2.0. If a copy of the MPL was not distributed with this
5// file, You can obtain one at http://mozilla.org/MPL/2.0/.
6
7use crate::prelude::*;
8use crate::string::SharedString;
9
10/// A qualified test path, including scope names.
11#[derive(Clone, Default)]
12pub struct Path {
13  pub(super) components: im::Vector<SharedString>,
14}
15
16/// An iterator over the components of a path.
17pub type Components<'a> = im::vector::Iter<'a, SharedString>;
18
19/// An iterator over the component string slices of a path.
20pub type ComponentStrs<'a> = iter::Map<Components<'a>, fn(&'a SharedString) -> &'a str>;
21
22impl Path {
23  /// Returns a reference to the components in the path.
24  pub fn components(&self) -> Components {
25    self.components.iter()
26  }
27
28  /// Returns an iterator over the component string slices.
29  pub fn component_strs(&self) -> ComponentStrs {
30    self.components.iter().map(SharedString::as_str)
31  }
32}
33
34impl Debug for Path {
35  fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
36    write!(f, "{:?}", self.components)
37  }
38}
39
40impl Display for Path {
41  fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
42    if self.components.is_empty() {
43      return write!(f, "(root)");
44    }
45
46    let mut components = self.components.iter();
47
48    if let Some(first) = components.next() {
49      write!(f, "{}", first)?;
50    }
51
52    for component in components {
53      let first_char = match component.chars().next() {
54        Some(c) => c,
55        None => continue,
56      };
57
58      if first_char.is_whitespace() || [':', '(', '<'].contains(&first_char) {
59        write!(f, "{}", component)?;
60      } else {
61        write!(f, " {}", component)?;
62      }
63    }
64
65    Ok(())
66  }
67}