rust_assembler/str/
find_str.rs

1/// Returns a `bool` saying whether the given string contains the specified pattern, expressed as an array of `&str`. Avoids all heap allocations.
2/// 
3/// # Examples
4/// 
5/// ```
6/// 
7/// let s = "Come va, amico?";
8/// assert_eq!(contains!(s; ["me", "v", "a, a"]), true);
9/// 
10#[macro_export]
11macro_rules! find_str {
12    ( $string:expr; $array:expr ) => ({
13        let bytes = $string.as_bytes();
14        let bytes_len = bytes.len();
15        // The start of the pattern that has to be checked, initialized as a `u8`.
16        let mut pat_start = 0u8;
17        // It is assigned the first character of the first non empty string.
18        for slice in $array {
19            if slice != "" {
20                pat_start = slice.as_bytes()[0];
21                break
22            }
23        }
24        let array_len = $array.len();
25
26        // Will get a `Some(usize)` value if there will be a match.
27        let mut opt_index = None;
28
29        // Counter needed when there are matches, so as to keep track of how many characters have already matched.
30        let mut counter = 0;
31
32        'outer: for i in 0..bytes_len {
33            // Counter is reset.
34            counter = 0;
35            // If first character matches..
36            if pat_start == bytes[i] {
37                'inner: for ii in 0..array_len {
38                    let slice = $array[ii].as_bytes();
39                    let len = slice.len();
40                    // If `slice` is empty, skip iteration.
41                    if len == 0 { continue 'inner }
42                    // Avoids out of bounds index.
43                    if i + len > bytes_len {
44                        break 'outer
45                    }
46
47                    // If `slice` matches to the specified portion of `$string`.
48                    if *slice == bytes[i + counter..i + counter + len] {
49                        // If it's the last element in the array, break the loop.
50                        if ii == array_len - 1 {
51                            opt_index = Some(i);
52                            break 'outer
53                        } else { // Else increase the number of characters that have already matched.
54                            counter += len
55                        }
56                    } else {
57                        continue 'outer
58                    }
59                }
60            }
61        }
62
63        opt_index
64    });
65}