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
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
use std_::mem;

#[allow(unused_imports)]
use super::ValSliceExt;


#[inline(always)]
fn next_split<'a,T, P, U: Eq + Clone>(
    pred: &mut P,
    s: &mut &'a [T],
    last: &mut U,
) -> Option<KeySlice<'a,T, U>>
where
    P: FnMut(&'a T) -> U,
{
    let mut next = last.clone();
    if s.is_empty() {
        return None;
    }
    let end = s.iter()
        .position(|x|{
            next=pred(x);
            *last!=next
        })
        .unwrap_or(s.len());
    let (ret, new_s) = s.split_at(end);
    *s = new_s;
    let key = mem::replace(last, next);
    Some(KeySlice { slice: ret, key })
}

#[inline(always)]
fn next_rsplit<'a, T, P, U: Eq + Clone>(
    pred: &mut P,
    s: &mut &'a [T],
    last: &mut U,
) -> Option<KeySlice<'a, T, U>>
where
    P: FnMut(&'a T) -> U,
{
    let mut next = last.clone();
    if s.is_empty() {
        return None;
    }
    let left = (*s).iter()
        .rposition(|x|{
            next=pred(x);
            *last!=next
        })
        .map_or(0,|x|x+1);
    let (new_s, ret) = s.split_at(left);
    *s = new_s;
    let key = mem::replace(last, next);
    Some(KeySlice { slice: ret, key })
}

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

/// KeySlice is a pair of (slice,key) returned from the (R)SplitSliceWhile iterators.
///
/// `slice` is the slice in which `mapper` returned the same key for every character.
///
/// `key` is the last value returned by `mapper`
///
/// `mapper` is a closure of the type `impl FnMut(&'a T) -> U`
#[derive(Debug, Clone, Eq, PartialEq, Ord, PartialOrd)]
pub struct KeySlice<'a, T:'a, U> {
    /// The slice where the sequence of values returned by `mapper` compared equal.
    pub slice: &'a [T],
    /// The last value that compared equal (in a sequence) returned by `mapper` .
    pub key: U,
}

impl<'a, T, U> KeySlice<'a, T, U> {
    /// Accessor for the underlying `&'a [T]`.
    pub fn slice(&self) -> &'a [T] {
        self.slice
    }
    /// Converts this KeySlice into a key/slice pair.
    pub fn into_pair(self)->(U,&'a [T]){
        (self.key,self.slice)
    }
}

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

/// Iterator that returns slices for the ranges in which `mapper` returns the same value.
///
/// Look [here](::slices::ValSliceExt::split_while) for details and examples.
#[derive(Debug, Clone)]
pub struct SplitSliceWhile<'a, T:'a, P, U> {
    pub(super) mapper: P,
    pub(super) s: &'a [T],
    pub(super) last_left: Option<U>,
    pub(super) last_right: Option<U>,
}

impl<'a, T, P, U: Eq + Clone> Iterator for SplitSliceWhile<'a, T, P, U>
where
    P: FnMut(&'a T) -> U,
{
    type Item = KeySlice<'a, T, U>;
    fn next(&mut self) -> Option<Self::Item> {
        next_split(&mut self.mapper, &mut self.s,try_opt!(self.last_left.as_mut()))
    }
    fn size_hint(&self)->(usize,Option<usize>){
        let s=self.s;
        let min_len=if s.is_empty() { 0 }else{ 1 };
        ( min_len , Some(s.len()) )
    }
}

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

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

/// Iterator that returns slices for the ranges in which `mapper` returns the same value
/// ,from the end.
///
/// Look [here](::slices::ValSliceExt::rsplit_while) for details and examples.
#[derive(Debug, Clone)]
pub struct RSplitSliceWhile<'a, T:'a, P, U> {
    pub(super) mapper: P,
    pub(super) s: &'a [T],
    pub(super) last_left: Option<U>,
    pub(super) last_right: Option<U>,
}

impl<'a, T, P, U: Eq + Clone> Iterator for RSplitSliceWhile<'a, T, P, U>
where
    P: FnMut(&'a T) -> U,
{
    type Item = KeySlice<'a, T, U>;
    fn next(&mut self) -> Option<Self::Item> {
        next_rsplit(&mut self.mapper, &mut self.s, try_opt!(self.last_right.as_mut()))
    }
    fn size_hint(&self)->(usize,Option<usize>){
        let s=self.s;
        let min_len=if s.is_empty() { 0 }else{ 1 };
        ( min_len , Some(s.len()) )
    }
}

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

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


#[cfg(test)]
mod test{
    use super::*;

    use alloc_::vec::Vec;

    fn func<'a,T,U,F>(s:&'a [T],f:F)->Vec<(U,Vec<T>)>
    where
        T:Clone,
        F:FnMut(&'a T)->U,
        U:Eq+Clone,
    {
        s.split_while(f).map(|v| (v.key,v.slice.to_vec()) ).collect()
    }

    fn rfunc<'a,T,U,F>(s:&'a [T],f:F)->Vec<(U,Vec<T>)>
    where
        T:Clone,
        F:FnMut(&'a T)->U,
        U:Eq+Clone,
    {
        s.rsplit_while(f).map(|v| (v.key,v.slice.to_vec()) ).collect()
    }

    fn new_singletons()->Vec<Vec<u32>>{
        (0..30).map(|x| vec![x] ).collect()
    }

    fn new_list_0()->Vec<u32>{
        vec![0,9,1,4,5]
    }
    fn new_list_1()->Vec<u32>{
        vec![90,91,92,93,94,95]
    }
    fn new_list_2()->Vec<u32>{
        vec![10,5,4,17]
    }
    fn mapper_0(x:&u32)->u32{x%3}

    fn mapper_1(x:&u32)->u32{*x}

    fn mapper_2(x:&u32)->u32{x/3}

    fn spair<T>(v:&T)->(T,Vec<T>)
    where T:Clone
    {
        (v.clone(),vec![v.clone()])
    }



    #[test]
    fn with_every_mapper(){

        for mapper in vec![ mapper_0 as fn(&_)->_,mapper_1,mapper_2 ] {
            assert_eq!(func(&vec![] ,mapper_0),vec![]);
            assert_eq!(rfunc(&vec![] ,mapper_0),vec![]);
            
            let singletons=new_singletons();
            for list in singletons.iter() {
                assert_eq!(func(list,mapper),vec![(mapper(&list[0]),list.clone())]);
                assert_eq!(rfunc(list,mapper),vec![(mapper(&list[0]),list.clone())]);
            }
        }
    }



    #[test]
    fn with_mapper_0(){
        {
            let list_0=new_list_0();
            let mut expected=vec![(0,vec![0,9]),(1,vec![1,4]),(2,vec![5])];
            assert_eq!(func(&list_0,mapper_0),expected);
            expected.reverse();
            assert_eq!(rfunc(&list_0,mapper_0),expected);
        }
        for list in vec![new_list_1(),new_list_2()] {
            let mut expected=list.iter()
                .map(|x| (mapper_0(x),vec![*x]) )
                .collect::<Vec<_>>();
            assert_eq!(func(&list,mapper_0),expected);
            expected.reverse();
            assert_eq!(rfunc(&list,mapper_0),expected);
        }
    }

    #[test]
    fn with_mapper_1(){
        for list in vec![new_list_0(),new_list_1(),new_list_2()] {
            let mut expected=list.iter().map(spair).collect::<Vec<_>>();
            assert_eq!(func(&list,mapper_1),expected);
            expected.reverse();
            assert_eq!(rfunc(&list,mapper_1),expected);
        }    
    }

    #[test]
    fn with_mapper_2(){
        {
            let list_0=new_list_0();
            let mut expected=vec![(0,vec![0]),(3,vec![9]),(0,vec![1]),(1,vec![4,5])];
            assert_eq!(func(&list_0,mapper_2),expected);
            expected.reverse();
            assert_eq!(rfunc(&list_0,mapper_2),expected);
        }
        {
            let list_1=new_list_1();
            let mut expected=vec![(30,vec![90,91,92]),(31,vec![93,94,95])];
            assert_eq!(func(&list_1,mapper_2),expected);
            expected.reverse();
            assert_eq!(rfunc(&list_1,mapper_2),expected);
        }
        {
            let list_2=new_list_2();
            let mut expected=vec![(3,vec![10]),(1,vec![5,4]),(5,vec![17])];
            assert_eq!(func(&list_2,mapper_2),expected);
            expected.reverse();
            assert_eq!(rfunc(&list_2,mapper_2),expected);
        }
    }



}