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
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
use super::StringExt;

use std_::mem;
use std_::str::CharIndices;

#[inline(always)]
fn next_split<'a, P, T: Eq + Clone>(
    pred: &mut P,
    s: &mut &'a str,
    last: &mut T,
) -> Option<KeyStr<'a, T>>
where
    P: FnMut(char) -> T,
{
    let mut next = last.clone();
    if s.is_empty() {
        return None;
    }
    let end = s
        .find(|c| {
            next = pred(c);
            *last != next
        })
        .map_or(s.len(), |v| v);
    let (ret, new_s) = s.split_at(end);
    *s = new_s;
    let key = mem::replace(last, next);
    Some(KeyStr { str: ret, key })
}

#[inline(always)]
fn next_rsplit<'a, P, T: Eq + Clone>(
    pred: &mut P,
    s: &mut &'a str,
    last: &mut T,
) -> Option<KeyStr<'a, T>>
where
    P: FnMut(char) -> T,
{
    let mut next = last.clone();
    if s.is_empty() {
        return None;
    }
    let left = s
        .rfind(|c| {
            next = pred(c);
            *last != next
        })
        .map_or(0, |v| s.next_char_boundary(v));
    let (new_s, ret) = s.split_at(left);
    *s = new_s;
    let key = mem::replace(last, next);
    Some(KeyStr { str: ret, key })
}

//-------------------------------------------------------------------------------------------

/// A pair of (string slice, key) returned by the 
/// [RSplitWhile](struct.RSplitWhile.html)/
/// [SplitWhile](struct.SplitWhile.html) iterators.
#[derive(Debug, Clone, Eq, PartialEq, Ord, PartialOrd)]
pub struct KeyStr<'a, T> {
    /// `str_slice` is a string slice for which all characters were mapped to `key` by a closure.
    pub str: &'a str,
    /// The value that all the chars in the string slice were mapped to.
    pub key: T,
}

impl<'a, T> KeyStr<'a, T> {
    /// Converts this into a key, string slice pair
    pub fn into_pair(self)->(T,&'a str){
        (self.key,self.str)
    }
}

//-------------------------------------------------------------------------------------------

/// Iterator over string slices,
/// in which all the chars in each string were mapped to the same key by a closure.
///
/// Look [here](trait.StringExt.html#method.split_while) for examples.
#[derive(Debug, Clone)]
pub struct SplitWhile<'a, P, T> {
    pub(super) mapper: P,
    pub(super) s: &'a str,
    pub(super) last_left: T,
    pub(super) last_right: T,
}

impl<'a, P, T: Eq + Clone> Iterator for SplitWhile<'a, P, T>
where
    P: FnMut(char) -> T,
{
    type Item = KeyStr<'a, T>;
    fn next(&mut self) -> Option<Self::Item> {
        next_split(&mut self.mapper, &mut self.s, &mut self.last_left)
    }
}

impl<'a, P, T: Eq + Clone> DoubleEndedIterator for SplitWhile<'a, P, T>
where
    P: FnMut(char) -> T,
{
    fn next_back(&mut self) -> Option<Self::Item> {
        next_rsplit(&mut self.mapper, &mut self.s, &mut self.last_right)
    }
}

//-------------------------------------------------------------------------------------------

/// Iterator over string slices,
/// in which all the chars in each string were mapped to the same key by a closure,
/// iterating from the end.
///
/// Look [here](trait.StringExt.html#method.rsplit_while) for examples.
#[derive(Debug, Clone)]
pub struct RSplitWhile<'a, P, T> {
    pub(super) mapper: P,
    pub(super) s: &'a str,
    pub(super) last_left: T,
    pub(super) last_right: T,
}

impl<'a, P, T: Eq + Clone> Iterator for RSplitWhile<'a, P, T>
where
    P: FnMut(char) -> T,
{
    type Item = KeyStr<'a, T>;
    fn next(&mut self) -> Option<Self::Item> {
        next_rsplit(&mut self.mapper, &mut self.s, &mut self.last_right)
    }
}

impl<'a, P, T: Eq + Clone> DoubleEndedIterator for RSplitWhile<'a, P, T>
where
    P: FnMut(char) -> T,
{
    fn next_back(&mut self) -> Option<Self::Item> {
        next_split(&mut self.mapper, &mut self.s, &mut self.last_left)
    }
}

//-------------------------------------------------------------------------------------------

/// Like [`CharIndices`], which starts from an offset.
///
/// Look [here](trait.StringExt.html#method.char_indices_from) for examples.
///
/// # Motivation
/// 
/// The reason to use this instead of `string[from..].char_indices()` is that 
/// this gives you the position of the characters in `string`, 
/// while [`CharIndices`] gives you the position of the characters in `string[from..]`.
/// 
/// [`CharIndices`]: https://doc.rust-lang.org/std/str/struct.CharIndices.html
#[derive(Clone, Debug)]
pub struct CharIndicesFrom<'a> {
    pub(super) offset: usize,
    pub(super) iter: CharIndices<'a>,
}

impl<'a> Iterator for CharIndicesFrom<'a> {
    type Item = (usize, char);

    #[inline]
    fn next(&mut self) -> Option<(usize, char)> {
        self.iter.next().map(|(i, c)| (i + self.offset, c))
    }

    #[inline]
    fn count(self) -> usize {
        self.iter.count()
    }

    #[inline]
    fn size_hint(&self) -> (usize, Option<usize>) {
        self.iter.size_hint()
    }

    #[inline]
    fn last(mut self) -> Option<(usize, char)> {
        self.next_back()
    }
}

impl<'a> DoubleEndedIterator for CharIndicesFrom<'a> {
    #[inline]
    fn next_back(&mut self) -> Option<(usize, char)> {
        self.iter.next_back().map(|(i, c)| (i + self.offset, c))
    }
}

impl<'a> CharIndicesFrom<'a> {
    /// Returns the rest of the slice to be iterated over.
    pub fn as_str(&self) -> &'a str {
        self.iter.as_str()
    }
}