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
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
use std::cmp::Ordering;
use std::collections::BTreeMap;

/// A pattern for matching source paths.
///
/// A pattern either matches a string exactly (`Exact`)
/// or it matches any string starting with a certain prefix (`Prefix`).
///
/// Patterns are ordered as follows:
/// 1. Exact patterns come before prefixes
/// 2. Exact patterns are ordered lexicographically
/// 3. Prefix patterns are ordered inversely by length, i.e.,
///    longer before shorter, and lexicographically among equally long strings.
#[derive(Debug, Clone, PartialEq, Eq)]
enum Pattern {
    Exact(String),
    Prefix(String),
}

impl Pattern {
    fn parse(input: &str) -> Self {
        if let Some(prefix) = input.strip_suffix('*') {
            Pattern::Prefix(prefix.to_lowercase())
        } else {
            Pattern::Exact(input.to_lowercase())
        }
    }
}

impl Ord for Pattern {
    fn cmp(&self, other: &Self) -> Ordering {
        match (self, other) {
            (Pattern::Exact(s), Pattern::Exact(t)) => s.cmp(t),
            (Pattern::Exact(_), Pattern::Prefix(_)) => Ordering::Less,
            (Pattern::Prefix(_), Pattern::Exact(_)) => Ordering::Greater,
            (Pattern::Prefix(s), Pattern::Prefix(t)) => match s.len().cmp(&t.len()) {
                Ordering::Greater => Ordering::Less,
                Ordering::Equal => s.cmp(t),
                Ordering::Less => Ordering::Greater,
            },
        }
    }
}

impl PartialOrd for Pattern {
    fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
        Some(self.cmp(other))
    }
}

/// A structure mapping source file paths to remote locations.
///
/// # Example
/// ```
/// use symbolic_common::SourceLinkMappings;
/// let mappings = vec![
///     ("C:\\src\\*", "http://MyDefaultDomain.com/src/*"),
///     ("C:\\src\\fOO\\*", "http://MyFooDomain.com/src/*"),
///     ("C:\\src\\foo\\specific.txt", "http://MySpecificFoodDomain.com/src/specific.txt"),
///     ("C:\\src\\bar\\*", "http://MyBarDomain.com/src/*"),
/// ];
/// let mappings = SourceLinkMappings::new(mappings.into_iter());
/// let resolved = mappings.resolve("c:\\src\\bAr\\foo\\FiLe.txt").unwrap();
/// assert_eq!(resolved, "http://MyBarDomain.com/src/foo/FiLe.txt");
/// ````
#[derive(Debug, Default, Clone, PartialEq, Eq)]
pub struct SourceLinkMappings {
    mappings: BTreeMap<Pattern, String>,
}

impl<'a> Extend<(&'a str, &'a str)> for SourceLinkMappings {
    fn extend<T: IntoIterator<Item = (&'a str, &'a str)>>(&mut self, iter: T) {
        self.mappings.extend(
            iter.into_iter()
                .map(|(k, v)| (Pattern::parse(k), v.to_string())),
        )
    }
}

impl SourceLinkMappings {
    /// Creates a `SourceLinkMappings` struct from an iterator of pattern/target pairs.
    pub fn new<'a, I: IntoIterator<Item = (&'a str, &'a str)>>(iter: I) -> Self {
        let mut res = Self::default();
        res.extend(iter);
        res
    }
    /// Returns true if this structure contains no mappings.
    pub fn is_empty(&self) -> bool {
        self.mappings.is_empty()
    }

    /// Resolve the path to a URL.
    pub fn resolve(&self, path: &str) -> Option<String> {
        // Note: this is currently quite simple, just pick the first match. If we needed to improve
        // performance in the future because we encounter PDBs with too many items, we can do a
        // prefix binary search, for example.
        let path_lower = path.to_lowercase();
        for (pattern, target) in &self.mappings {
            match &pattern {
                Pattern::Exact(value) => {
                    if value == &path_lower {
                        return Some(target.clone());
                    }
                }
                Pattern::Prefix(value) => {
                    if path_lower.starts_with(value) {
                        let replacement = path
                            .get(value.len()..)
                            .unwrap_or_default()
                            .replace('\\', "/");
                        return Some(target.replace('*', &replacement));
                    }
                }
            }
        }
        None
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn test_mapping() {
        let mappings = vec![
            ("C:\\src\\*", "http://MyDefaultDomain.com/src/*"),
            ("C:\\src\\fOO\\*", "http://MyFooDomain.com/src/*"),
            (
                "C:\\src\\foo\\specific.txt",
                "http://MySpecificFoodDomain.com/src/specific.txt",
            ),
            ("C:\\src\\bar\\*", "http://MyBarDomain.com/src/*"),
            ("C:\\src\\file.txt", "https://example.com/file.txt"),
            ("/home/user/src/*", "https://linux.com/*"),
        ];

        let mappings = SourceLinkMappings::new(mappings);

        assert_eq!(mappings.mappings.len(), 6);

        // In this example:
        //   All files under directory bar will map to a relative URL beginning with http://MyBarDomain.com/src/.
        //   All files under directory foo will map to a relative URL beginning with http://MyFooDomain.com/src/ EXCEPT foo/specific.txt which will map to http://MySpecificFoodDomain.com/src/specific.txt.
        //   All other files anywhere under the src directory will map to a relative url beginning with http://MyDefaultDomain.com/src/.
        assert!(mappings.resolve("c:\\other\\path").is_none());
        assert!(mappings.resolve("/home/path").is_none());
        assert_eq!(
            mappings.resolve("c:\\src\\bAr\\foo\\FiLe.txt").unwrap(),
            "http://MyBarDomain.com/src/foo/FiLe.txt"
        );
        assert_eq!(
            mappings.resolve("c:\\src\\foo\\FiLe.txt").unwrap(),
            "http://MyFooDomain.com/src/FiLe.txt"
        );
        assert_eq!(
            mappings.resolve("c:\\src\\foo\\SpEcIfIc.txt").unwrap(),
            "http://MySpecificFoodDomain.com/src/specific.txt"
        );
        assert_eq!(
            mappings.resolve("c:\\src\\other\\path").unwrap(),
            "http://MyDefaultDomain.com/src/other/path"
        );
        assert_eq!(
            mappings.resolve("c:\\src\\other\\path").unwrap(),
            "http://MyDefaultDomain.com/src/other/path"
        );
        assert_eq!(
            mappings.resolve("/home/user/src/Path/TO/file.txt").unwrap(),
            "https://linux.com/Path/TO/file.txt"
        );
    }
}