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
// License: see LICENSE file at root directory of `master` branch

//! # Root

/// # Sub strings
///
/// You can make an instance of this struct by [`::sub_strs()`][::sub_strs()].
///
/// [::sub_strs()]: fn.sub_strs.html
#[derive(Debug)]
pub struct SubStrs<'a, S> where S: AsRef<str> {

    /// # Source
    source: &'a str,

    /// # Start
    start: S,

    /// # End
    end: S,

}

impl<'a, S> SubStrs<'a, S> where S: AsRef<str> {

    /// # Makes new instance
    fn new(source: &'a str, start: S, end: S) -> Self {
        Self {
            source,
            start,
            end,
        }
    }

}

impl<'a, S: AsRef<str>> Iterator for SubStrs<'a, S> where S: AsRef<str> {

    type Item = &'a str;

    fn next(&mut self) -> Option<Self::Item> {
        let start = self.start.as_ref();
        if let Some(start_idx) = self.source.find(start) {
            let end = self.end.as_ref();
            if let Some(end_idx) = self.source[start_idx + start.len()..].find(end) {
                let new_idx = start_idx + start.len() + end_idx + end.len();
                let result = &self.source[start_idx .. new_idx];
                self.source = &self.source[new_idx..];
                return Some(result);
            }
        }

        self.source = "";
        None
    }

}

/// # Finds sub strings
///
/// ## Examples
///
/// ```
/// let sample = "test(0)     test(1)---test(2) some test(3)";
/// let start = "test(";
/// let end = ")";
/// for (i, s) in sub_strs::sub_strs(sample, start, end).enumerate() {
///     assert_eq!(s, format!("{}{}{}", start, i, end));
/// }
/// ```
pub fn sub_strs<'a, S: AsRef<str>>(source: &'a str, start: S, end: S) -> SubStrs<'a, S> {
    SubStrs::new(source, start, end)
}