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 prefix_match: String,
6    pub suffix_match: String,
7    pub ignore_case: bool,
8}
9
10impl Pattern {
11    pub fn has_prefix(&self) -> bool {
12        !self.prefix.is_empty()
13    }
14
15    pub fn has_suffix(&self) -> bool {
16        !self.suffix.is_empty()
17    }
18
19    pub fn description(&self) -> String {
20        match (self.has_prefix(), self.has_suffix()) {
21            (true, true) => format!(
22                "starting with '{}' and ending with '{}'",
23                self.prefix, self.suffix
24            ),
25            (true, false) => format!("starting with '{}'", self.prefix),
26            (false, true) => format!("ending with '{}'", self.suffix),
27            (false, false) => String::new(),
28        }
29    }
30
31    pub fn case_mode(&self) -> &'static str {
32        if self.ignore_case {
33            "any case"
34        } else {
35            "exact case"
36        }
37    }
38}
39
40pub fn matches_at(address: &str, pattern: &str, ignore_case: bool, at_start: bool) -> bool {
41    if pattern.is_empty() {
42        return true;
43    }
44
45    let addr_bytes = address.as_bytes();
46    let pat_bytes = pattern.as_bytes();
47
48    if pat_bytes.len() > addr_bytes.len() {
49        return false;
50    }
51
52    let slice = if at_start {
53        &addr_bytes[..pat_bytes.len()]
54    } else {
55        &addr_bytes[addr_bytes.len() - pat_bytes.len()..]
56    };
57
58    if ignore_case {
59        slice.eq_ignore_ascii_case(pat_bytes)
60    } else {
61        slice == pat_bytes
62    }
63}
64
65pub fn matches_both(address: &str, prefix: &str, suffix: &str, ignore_case: bool) -> bool {
66    matches_at(address, prefix, ignore_case, true)
67        && matches_at(address, suffix, ignore_case, false)
68}