Skip to main content

darling_core/util/
path_to_string.rs

1use std::borrow::Cow;
2
3/// Transform Rust paths to a readable and comparable string.
4///
5/// # Limitations
6/// * Leading colons are ignored.
7/// * Angle brackets and `as` elements are ignored.
8///
9/// # Example
10/// ```rust
11/// # use darling_core::util::path_to_string;
12/// # use syn::parse_quote;
13/// assert_eq!(path_to_string(&parse_quote!(a::b)), "a::b");
14/// ```
15pub fn path_to_string(path: &syn::Path) -> String {
16    path.segments
17        .iter()
18        // like `.intersperse("::")`, but that's not stable yet
19        .enumerate()
20        .flat_map(|(i, s)| {
21            if i == 0 {
22                [Cow::Borrowed(""), s.ident.to_string().into()]
23            } else {
24                [Cow::Borrowed("::"), s.ident.to_string().into()]
25            }
26        })
27        .collect()
28}
29
30#[cfg(test)]
31mod tests {
32    use syn::parse_quote;
33
34    use super::path_to_string;
35
36    #[test]
37    fn simple_ident() {
38        assert_eq!(path_to_string(&parse_quote!(a)), "a");
39    }
40
41    #[test]
42    fn simple_path() {
43        assert_eq!(path_to_string(&parse_quote!(a::b)), "a::b");
44    }
45}