Skip to main content

vanity_core/
pattern.rs

1#[derive(Debug, Clone)]
2pub struct Pattern {
3    pub prefix: String,
4    pub suffix: String,
5    pub contains: String,
6    pub prefix_match: String,
7    pub suffix_match: String,
8    pub contains_match: String,
9    pub ignore_case: bool,
10    /// Leading chars of `prefix` every address has anyway (`0x`, `kaspa:`, `cosmos1`…);
11    /// they cost nothing to match, so difficulty counts skip them.
12    pub fixed_prefix_len: usize,
13}
14
15impl Pattern {
16    pub fn has_prefix(&self) -> bool {
17        !self.prefix.is_empty()
18    }
19
20    pub fn has_suffix(&self) -> bool {
21        !self.suffix.is_empty()
22    }
23
24    pub fn has_contains(&self) -> bool {
25        !self.contains.is_empty()
26    }
27
28    pub fn description(&self) -> String {
29        let mut parts = Vec::new();
30        if self.has_prefix() {
31            parts.push(format!("starting with '{}'", self.prefix));
32        }
33        if self.has_contains() {
34            parts.push(format!("containing '{}'", self.contains));
35        }
36        if self.has_suffix() {
37            parts.push(format!("ending with '{}'", self.suffix));
38        }
39        parts.join(" and ")
40    }
41
42    pub fn case_mode(&self) -> &'static str {
43        if self.ignore_case {
44            "any case"
45        } else {
46            "exact case"
47        }
48    }
49
50    /// Literal character count used for difficulty estimates (`*` wildcards ignored).
51    pub fn effective_literal_chars(&self) -> usize {
52        literal_len(&self.prefix).saturating_sub(self.fixed_prefix_len)
53            + literal_len(&self.suffix)
54            + literal_len(&self.contains)
55    }
56
57    /// The part of `prefix` the user actually asked for (chain-forced start removed).
58    pub fn user_prefix(&self) -> &str {
59        self.prefix
60            .char_indices()
61            .nth(self.fixed_prefix_len)
62            .map_or("", |(i, _)| &self.prefix[i..])
63    }
64
65    /// Record `fixed` as the chain-forced start of `prefix` (no-op if it isn't there).
66    pub fn set_fixed_prefix(&mut self, fixed: &str) {
67        self.fixed_prefix_len = match self.prefix.get(..fixed.len()) {
68            Some(head) if head.eq_ignore_ascii_case(fixed) => fixed.chars().count(),
69            _ => 0,
70        };
71    }
72}
73
74/// One OR-alternative for build_pattern (prefix, suffix, contains).
75pub type PatternAlternative = (Option<String>, Option<String>, Option<String>);
76
77/// Split comma-separated OR alternatives. Only one of prefix/suffix/contains may
78/// contain commas; others are shared across all alternatives.
79pub fn expand_pattern_alternatives(
80    prefix: Option<&str>,
81    suffix: Option<&str>,
82    contains: Option<&str>,
83) -> Result<Vec<PatternAlternative>, String> {
84    let split = |s: Option<&str>| -> Vec<String> {
85        match s {
86            None | Some("") => vec![],
87            Some(raw) => raw
88                .split(',')
89                .map(|p| p.trim().to_string())
90                .filter(|p| !p.is_empty())
91                .collect(),
92        }
93    };
94
95    let prefixes = split(prefix);
96    let suffixes = split(suffix);
97    let contains_list = split(contains);
98
99    let multi_count = [
100        prefixes.len() > 1,
101        suffixes.len() > 1,
102        contains_list.len() > 1,
103    ]
104    .iter()
105    .filter(|&&b| b)
106    .count();
107    if multi_count > 1 {
108        return Err("comma OR is only allowed in one of --prefix, --suffix, or --contains".into());
109    }
110
111    let n = prefixes
112        .len()
113        .max(suffixes.len())
114        .max(contains_list.len())
115        .max(1);
116
117    if prefixes.is_empty() && suffixes.is_empty() && contains_list.is_empty() {
118        return Ok(vec![(None, None, None)]);
119    }
120
121    let mut out = Vec::with_capacity(n);
122    for i in 0..n {
123        let p = if prefixes.len() > 1 {
124            prefixes.get(i).cloned()
125        } else if prefixes.len() == 1 {
126            Some(prefixes[0].clone())
127        } else {
128            None
129        };
130        let s = if suffixes.len() > 1 {
131            suffixes.get(i).cloned()
132        } else if suffixes.len() == 1 {
133            Some(suffixes[0].clone())
134        } else {
135            None
136        };
137        let c = if contains_list.len() > 1 {
138            contains_list.get(i).cloned()
139        } else if contains_list.len() == 1 {
140            Some(contains_list[0].clone())
141        } else {
142            None
143        };
144        out.push((p, s, c));
145    }
146    Ok(out)
147}
148
149/// Combined expected attempts when any of several patterns may match (OR).
150pub fn expected_attempts_any(per_pattern: &[f64]) -> f64 {
151    if per_pattern.is_empty() {
152        return f64::INFINITY;
153    }
154    let inv: f64 = per_pattern.iter().map(|&e| 1.0 / e.max(1.0)).sum();
155    if inv <= 0.0 {
156        f64::INFINITY
157    } else {
158        1.0 / inv
159    }
160}
161
162fn literal_len(s: &str) -> usize {
163    s.chars().filter(|c| *c != '*').count()
164}
165
166pub fn matches_at(address: &str, pattern: &str, ignore_case: bool, at_start: bool) -> bool {
167    if pattern.is_empty() {
168        return true;
169    }
170
171    if pattern.contains('*') {
172        return match_glob_affix(address, pattern, ignore_case, at_start);
173    }
174
175    let addr_bytes = address.as_bytes();
176    let pat_bytes = pattern.as_bytes();
177
178    if pat_bytes.len() > addr_bytes.len() {
179        return false;
180    }
181
182    let slice = if at_start {
183        &addr_bytes[..pat_bytes.len()]
184    } else {
185        &addr_bytes[addr_bytes.len() - pat_bytes.len()..]
186    };
187
188    if ignore_case {
189        slice.eq_ignore_ascii_case(pat_bytes)
190    } else {
191        slice == pat_bytes
192    }
193}
194
195/// Glob-style match for a single `*` (zero or more chars) within an affix constraint.
196fn match_glob_affix(address: &str, pattern: &str, ignore_case: bool, at_start: bool) -> bool {
197    let addr = if ignore_case {
198        address.to_ascii_lowercase()
199    } else {
200        address.to_string()
201    };
202    let pat = if ignore_case {
203        pattern.to_ascii_lowercase()
204    } else {
205        pattern.to_string()
206    };
207
208    let parts: Vec<&str> = pat.split('*').collect();
209    if parts.len() == 1 {
210        return if at_start {
211            addr.starts_with(&pat)
212        } else {
213            addr.ends_with(&pat)
214        };
215    }
216
217    // For prefix globs: must start with first literal; for suffix: must end with last.
218    if at_start {
219        if !parts[0].is_empty() && !addr.starts_with(parts[0]) {
220            return false;
221        }
222        return match_contains_glob(&addr, &pat);
223    }
224
225    if !parts[parts.len() - 1].is_empty() && !addr.ends_with(parts[parts.len() - 1]) {
226        return false;
227    }
228    match_contains_glob(&addr, &pat)
229}
230
231fn match_contains_glob(address: &str, pattern: &str) -> bool {
232    if !pattern.contains('*') {
233        return address.contains(pattern);
234    }
235    let parts: Vec<&str> = pattern.split('*').collect();
236    let mut rest = address;
237    for (i, part) in parts.iter().enumerate() {
238        if part.is_empty() {
239            continue;
240        }
241        if let Some(idx) = rest.find(part) {
242            if i == 0 && !pattern.starts_with('*') && idx != 0 {
243                // anchored start handled by caller for prefix; for contains, first part can be anywhere
244            }
245            rest = &rest[idx + part.len()..];
246        } else {
247            return false;
248        }
249    }
250    if !pattern.ends_with('*') {
251        // last literal already consumed from rest; ok
252    }
253    true
254}
255
256pub fn matches_contains(address: &str, pattern: &str, ignore_case: bool) -> bool {
257    if pattern.is_empty() {
258        return true;
259    }
260    let addr = if ignore_case {
261        address.to_ascii_lowercase()
262    } else {
263        address.to_string()
264    };
265    let pat = if ignore_case {
266        pattern.to_ascii_lowercase()
267    } else {
268        pattern.to_string()
269    };
270    match_contains_glob(&addr, &pat)
271}
272
273pub fn matches_both(address: &str, prefix: &str, suffix: &str, ignore_case: bool) -> bool {
274    matches_at(address, prefix, ignore_case, true)
275        && matches_at(address, suffix, ignore_case, false)
276}
277
278pub fn matches_full(
279    address: &str,
280    prefix: &str,
281    suffix: &str,
282    contains: &str,
283    ignore_case: bool,
284) -> bool {
285    matches_both(address, prefix, suffix, ignore_case)
286        && matches_contains(address, contains, ignore_case)
287}
288
289#[cfg(test)]
290mod tests {
291    use super::*;
292
293    #[test]
294    fn contains_and_wildcard() {
295        assert!(matches_contains("abcXYZdef", "XYZ", false));
296        assert!(matches_contains("abcXYZdef", "X*Z", false));
297        assert!(!matches_contains("abcXYZdef", "ZZZ", false));
298        assert!(matches_at("CoolEnd", "Cool*", false, true));
299        assert!(matches_at("xxpump", "*pump", false, false));
300    }
301}