Skip to main content

micromegas_tracing/
source_path.rs

1//! Trimming of `file!()` paths before they leave the process.
2
3fn is_sep(b: u8) -> bool {
4    b == b'/' || b == b'\\'
5}
6
7fn is_absolute(path: &str) -> bool {
8    let b = path.as_bytes();
9    match b {
10        [first, ..] if is_sep(*first) => true,
11        [drive, b':', sep, ..] => drive.is_ascii_alphabetic() && is_sep(*sep),
12        _ => false,
13    }
14}
15
16/// Index just past the first `first<sep>second<sep>` sequence that starts at a component boundary.
17fn after_marker(path: &str, first: &str, second: &str) -> Option<usize> {
18    let b = path.as_bytes();
19    let (f, s) = (first.as_bytes(), second.as_bytes());
20    let len = f.len() + 1 + s.len() + 1;
21    (0..b.len()).find_map(|i| {
22        let boundary = i == 0 || is_sep(b[i - 1]);
23        let rest = &b[i..];
24        (boundary
25            && rest.len() >= len
26            && rest.starts_with(f)
27            && is_sep(rest[f.len()])
28            && rest[f.len() + 1..].starts_with(s)
29            && is_sep(rest[len - 1]))
30        .then_some(i + len)
31    })
32}
33
34fn file_name(path: &str) -> &str {
35    match path.bytes().rposition(is_sep) {
36        Some(i) => &path[i + 1..],
37        None => path,
38    }
39}
40
41/// Returns the part of a `file!()` path worth sending: a suffix of `path`, so no allocation.
42///
43/// Relative paths (workspace members) are unchanged. Absolute paths into the cargo registry lose
44/// everything through the index directory, git checkouts lose everything through
45/// `git/checkouts/`, and any other absolute path is reduced to its file name. Both `/` and `\`
46/// separate components, because the path comes from the build host, which may differ from the
47/// target.
48pub fn trim_source_path(path: &str) -> &str {
49    if !is_absolute(path) {
50        return path;
51    }
52    if let Some(start) = after_marker(path, "registry", "src") {
53        let rest = &path[start..];
54        if let Some(i) = rest.bytes().position(is_sep) {
55            let trimmed = &rest[i + 1..];
56            if !trimmed.is_empty() {
57                return trimmed;
58            }
59        }
60    }
61    if let Some(start) = after_marker(path, "git", "checkouts") {
62        let trimmed = &path[start..];
63        if !trimmed.is_empty() {
64            return trimmed;
65        }
66    }
67    file_name(path)
68}