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
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
//! Crate `slice-group-by` is a library for efficiently iterating on a slice by groups defined by
//! a function that specifies if two elements are in the same group.
//!
//! # Example: Linear Searched Immutable Groups
//!
//! You will only need to define a function that returns `true` if two elements are in the same group.
//!
//! The `LinearGroupBy` iterator will always gives contiguous elements to the predicate function.
//!
//! ```rust
//! use slice_group_by::GroupBy;
//!
//! let slice = &[1, 1, 1, 3, 3, 2, 2, 2];
//!
//! let mut iter = slice.linear_group_by(|a, b| a == b);
//!
//! assert_eq!(iter.next(), Some(&[1, 1, 1][..]));
//! assert_eq!(iter.next(), Some(&[3, 3][..]));
//! assert_eq!(iter.next(), Some(&[2, 2, 2][..]));
//! assert_eq!(iter.next(), None);
//! ```
//!
//! # Example: Linear Searched Immutable Str Slices
//!
//! You will only need to define a function that returns `true` if two `char` are in the same group.
//!
//! The `LinearStrGroupBy` iterator will always gives contiguous `char` to the predicate function.
//!
//! ```rust
//! use slice_group_by::StrGroupBy;
//!
//! let string = "aaaabbbbb饰饰cccc";
//!
//! let mut iter = string.linear_group_by(|a, b| a == b);
//!
//! assert_eq!(iter.next(), Some("aaaa"));
//! assert_eq!(iter.next(), Some("bbbbb"));
//! assert_eq!(iter.next(), Some("饰饰"));
//! assert_eq!(iter.next(), Some("cccc"));
//! assert_eq!(iter.next(), None);
//! ```
//!
//! # Example: Binary Searched Mutable Groups
//!
//! It is also possible to get mutable non overlapping groups of a slice.
//!
//! The `BinaryGroupBy/Mut` and `ExponentialGroupBy/Mut` iterators will not necessarily
//! gives contiguous elements to the predicate function. The predicate function should implement
//! an order consistent with the sort order of the slice.
//!
//! ```rust
//! use slice_group_by::GroupByMut;
//!
//! let slice = &mut [1, 1, 1, 2, 2, 2, 3, 3];
//!
//! let mut iter = slice.binary_group_by_mut(|a, b| a == b);
//!
//! assert_eq!(iter.next(), Some(&mut [1, 1, 1][..]));
//! assert_eq!(iter.next(), Some(&mut [2, 2, 2][..]));
//! assert_eq!(iter.next(), Some(&mut [3, 3][..]));
//! assert_eq!(iter.next(), None);
//! ```
//!
//! # Example: Exponential Searched Mutable Groups starting from the End
//!
//! It is also possible to get mutable non overlapping groups of a slice even starting from the end of it.
//!
//! ```rust
//! use slice_group_by::GroupByMut;
//!
//! let slice = &mut [1, 1, 1, 2, 2, 2, 3, 3];
//!
//! let mut iter = slice.exponential_group_by_mut(|a, b| a == b).rev();
//!
//! assert_eq!(iter.next(), Some(&mut [3, 3][..]));
//! assert_eq!(iter.next(), Some(&mut [2, 2, 2][..]));
//! assert_eq!(iter.next(), Some(&mut [1, 1, 1][..]));
//! assert_eq!(iter.next(), None);
//! ```
//!

#![cfg_attr(feature = "nightly", feature(ptr_offset_from))]
#![cfg_attr(feature = "nightly", feature(test))]

#![cfg_attr(all(not(test), not(feature = "std")), no_std)]
#[cfg(all(not(test), not(feature = "std")))]
extern crate core as std;

macro_rules! group_by_partial_eq {
    (struct $name:ident, $elem:ty) => {
        impl<'a, T: 'a> $name<'a, T> {
            #[inline]
            pub fn is_empty(&self) -> bool {
                self.0.is_empty()
            }

            #[inline]
            pub fn remainder_len(&self) -> usize {
                self.0.remainder_len()
            }
        }

        impl<'a, T: 'a> Iterator for $name<'a, T>
        where T: PartialEq,
        {
            type Item = $elem;

            fn next(&mut self) -> Option<Self::Item> {
                self.0.next()
            }

            fn size_hint(&self) -> (usize, Option<usize>) {
                self.0.size_hint()
            }

            fn last(self) -> Option<Self::Item> {
                self.0.last()
            }
        }

        impl<'a, T: 'a> DoubleEndedIterator for $name<'a, T>
        where T: PartialEq,
        {
            fn next_back(&mut self) -> Option<Self::Item> {
                self.0.next_back()
            }
        }

        impl<'a, T: 'a> FusedIterator for $name<'a, T>
        where T: PartialEq,
        { }
    }
}

mod linear_group_by;
mod binary_group_by;
mod exponential_group_by;
mod linear_str_group_by;

use std::cmp::{self, Ordering};

pub use self::linear_group_by::{
    LinearGroupBy,
    LinearGroup,
    LinearGroupByMut,
    LinearGroupMut,
};
pub use self::binary_group_by::{
    BinaryGroupBy,
    BinaryGroup,
    BinaryGroupByMut,
    BinaryGroupMut,
};
pub use self::exponential_group_by::{
    ExponentialGroupBy,
    ExponentialGroup,
    ExponentialGroupByMut,
    ExponentialGroupMut,
};
pub use self::linear_str_group_by::{
    LinearStrGroupBy,
    LinearStrGroup,
    LinearStrGroupByMut,
    LinearStrGroupMut,
};

#[cfg(feature = "nightly")]
#[inline]
unsafe fn offset_from<T>(to: *const T, from: *const T) -> usize {
    to.offset_from(from) as usize
}

#[cfg(not(feature = "nightly"))]
#[inline]
unsafe fn offset_from<T>(to: *const T, from: *const T) -> usize {
    use std::mem;
    (to as usize - from as usize) / mem::size_of::<T>()
}

/// Exponential searches this sorted slice for a given element.
///
/// If the value is found then `Ok` is returned, containing the index of the matching element;
/// if the value is not found then `Err` is returned, containing the index where a matching element
/// could be inserted while maintaining sorted order.
///
/// # Examples
///
/// Looks up a series of four elements. The first is found, with a
/// uniquely determined position; the second and third are not
/// found; the fourth could match any position in `[1, 4]`.
///
/// ```
/// use slice_group_by::exponential_search;
///
/// let s = &[0, 1, 1, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55];
///
/// assert_eq!(exponential_search(s, &13),  Ok(9));
/// assert_eq!(exponential_search(s, &4),   Err(7));
/// assert_eq!(exponential_search(s, &100), Err(13));
/// let r = exponential_search(s, &1);
/// assert!(match r { Ok(1..=4) => true, _ => false, });
/// ```
#[inline]
pub fn exponential_search<T>(slice: &[T], elem: &T) -> Result<usize, usize>
where T: Ord
{
    exponential_search_by(slice, |x| x.cmp(elem))
}

/// Binary searches this sorted slice with a comparator function.
///
/// The comparator function should implement an order consistent with the sort order of
/// the underlying slice, returning an order code that indicates whether its argument
/// is `Less`, `Equal` or `Greater` the desired target.
///
/// If the value is found then `Ok` is returned, containing the index of the matching element;
/// if the value is not found then `Err` is returned, containing the index where a matching element
/// could be inserted while maintaining sorted order.
///
/// # Examples
///
/// Looks up a series of four elements. The first is found, with a
/// uniquely determined position; the second and third are not
/// found; the fourth could match any position in `[1, 4]`.
///
/// ```
/// use slice_group_by::exponential_search_by;
///
/// let s = &[0, 1, 1, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55];
///
/// let seek = 13;
/// assert_eq!(exponential_search_by(s, |probe| probe.cmp(&seek)), Ok(9));
/// let seek = 4;
/// assert_eq!(exponential_search_by(s, |probe| probe.cmp(&seek)), Err(7));
/// let seek = 100;
/// assert_eq!(exponential_search_by(s, |probe| probe.cmp(&seek)), Err(13));
/// let seek = 1;
/// let r = exponential_search_by(s, |probe| probe.cmp(&seek));
/// assert!(match r { Ok(1..=4) => true, _ => false, });
/// ```
#[inline]
pub fn exponential_search_by<T, F>(slice: &[T], mut f: F) -> Result<usize, usize>
where F: FnMut(&T) -> Ordering,
{
    let mut index = 1;
    while index < slice.len() && f(&slice[index]) == Ordering::Less {
        index *= 2;
    }

    let half_bound = index / 2;
    let bound = cmp::min(index + 1, slice.len());

    match slice[half_bound..bound].binary_search_by(f) {
        Ok(pos) => Ok(half_bound + pos),
        Err(pos) => Err(half_bound + pos),
    }
}

/// Binary searches this sorted slice with a key extraction function.
///
/// Assumes that the slice is sorted by the key.
///
/// If the value is found then `Ok` is returned, containing the index of the matching element;
/// if the value is not found then `Err` is returned, containing the index where a matching element
/// could be inserted while maintaining sorted order.
///
/// # Examples
///
/// Looks up a series of four elements. The first is found, with a
/// uniquely determined position; the second and third are not
/// found; the fourth could match any position in `[1, 4]`.
///
/// ```
/// use slice_group_by::exponential_search_by_key;
///
/// let s = &[(0, 0), (2, 1), (4, 1), (5, 1), (3, 1),
///           (1, 2), (2, 3), (4, 5), (5, 8), (3, 13),
///           (1, 21), (2, 34), (4, 55)];
///
/// assert_eq!(exponential_search_by_key(s, &13, |&(a,b)| b),  Ok(9));
/// assert_eq!(exponential_search_by_key(s, &4, |&(a,b)| b),   Err(7));
/// assert_eq!(exponential_search_by_key(s, &100, |&(a,b)| b), Err(13));
/// let r = exponential_search_by_key(s, &1, |&(a,b)| b);
/// assert!(match r { Ok(1..=4) => true, _ => false, });
/// ```
#[inline]
pub fn exponential_search_by_key<T, B, F>(slice: &[T], b: &B, mut f: F) -> Result<usize, usize>
where F: FnMut(&T) -> B,
      B: Ord
{
    exponential_search_by(slice, |k| f(k).cmp(b))
}

/// A convenient trait to construct an iterator returning non-overlapping groups
/// defined by a predicate.
pub trait GroupBy<T>
{
    /// Returns an iterator on slice groups using the *linear search* method.
    fn linear_group_by<P>(&self, predicate: P) -> LinearGroupBy<T, P>
    where P: FnMut(&T, &T) -> bool;

    /// Returns an iterator on slice groups based on the [`PartialEq::eq`] method of `T`,
    /// it uses *linear search* to iterate over groups.
    ///
    /// [`PartialEq::eq`]: https://doc.rust-lang.org/std/cmp/trait.PartialEq.html#tymethod.eq
    fn linear_group(&self) -> LinearGroup<T>
    where T: PartialEq;

    /// Returns an iterator on slice groups using the *binary search* method.
    ///
    /// The predicate function should implement an order consistent with
    /// the sort order of the slice.
    fn binary_group_by<P>(&self, predicate: P) -> BinaryGroupBy<T, P>
    where P: FnMut(&T, &T) -> bool;

    /// Returns an iterator on slice groups based on the [`PartialEq::eq`] method of `T`,
    /// it uses *binary search* to iterate over groups.
    ///
    /// The predicate function should implement an order consistent with
    /// the sort order of the slice.
    ///
    /// [`PartialEq::eq`]: https://doc.rust-lang.org/std/cmp/trait.PartialEq.html#tymethod.eq
    fn binary_group(&self) -> BinaryGroup<T>
    where T: PartialEq;

    /// Returns an iterator on slice groups using the *exponential search* method.
    ///
    /// The predicate function should implement an order consistent with
    /// the sort order of the slice.
    fn exponential_group_by<P>(&self, predicate: P) -> ExponentialGroupBy<T, P>
    where P: FnMut(&T, &T) -> bool;

    /// Returns an iterator on slice groups based on the [`PartialEq::eq`] method of `T`,
    /// it uses *exponential search* to iterate over groups.
    ///
    /// The predicate function should implement an order consistent with
    /// the sort order of the slice.
    ///
    /// [`PartialEq::eq`]: https://doc.rust-lang.org/std/cmp/trait.PartialEq.html#tymethod.eq
    fn exponential_group(&self) -> ExponentialGroup<T>
    where T: PartialEq;
}

/// A convenient trait to construct an iterator returning non-overlapping *mutable*
/// groups defined by a predicate.
pub trait GroupByMut<T>
{
    /// Returns an iterator on *mutable* slice groups using the *linear search* method.
    fn linear_group_by_mut<P>(&mut self, predicate: P) -> LinearGroupByMut<T, P>
    where P: FnMut(&T, &T) -> bool;

    /// Returns an iterator on *mutable* slice groups based on the [`PartialEq::eq`] method of `T`,
    /// it uses *linear search* to iterate over groups.
    ///
    /// [`PartialEq::eq`]: https://doc.rust-lang.org/std/cmp/trait.PartialEq.html#tymethod.eq
    fn linear_group_mut(&mut self) -> LinearGroupMut<T>
    where T: PartialEq;

    /// Returns an iterator on *mutable* slice groups using the *binary search* method.
    ///
    /// The predicate function should implement an order consistent with
    /// the sort order of the slice.
    fn binary_group_by_mut<P>(&mut self, predicate: P) -> BinaryGroupByMut<T, P>
    where P: FnMut(&T, &T) -> bool;

    /// Returns an iterator on *mutable* slice groups based on the [`PartialEq::eq`] method of `T`,
    /// it uses *binary search* to iterate over groups.
    ///
    /// The predicate function should implement an order consistent with
    /// the sort order of the slice.
    ///
    /// [`PartialEq::eq`]: https://doc.rust-lang.org/std/cmp/trait.PartialEq.html#tymethod.eq
    fn binary_group_mut(&mut self) -> BinaryGroupMut<T>
    where T: PartialEq;

    /// Returns an iterator on *mutable* slice groups using the *exponential search* method.
    ///
    /// The predicate function should implement an order consistent with
    /// the sort order of the slice.
    fn exponential_group_by_mut<P>(&mut self, predicate: P) -> ExponentialGroupByMut<T, P>
    where P: FnMut(&T, &T) -> bool;

    /// Returns an iterator on *mutable* slice groups based on the [`PartialEq::eq`] method of `T`,
    /// it uses *exponential search* to iterate over groups.
    ///
    /// The predicate function should implement an order consistent with
    /// the sort order of the slice.
    ///
    /// [`PartialEq::eq`]: https://doc.rust-lang.org/std/cmp/trait.PartialEq.html#tymethod.eq
    fn exponential_group_mut(&mut self) -> ExponentialGroupMut<T>
    where T: PartialEq;
}

impl<T> GroupBy<T> for [T]
{
    fn linear_group_by<P>(&self, predicate: P) -> LinearGroupBy<T, P>
    where P: FnMut(&T, &T) -> bool,
    {
        LinearGroupBy::new(self, predicate)
    }

    fn linear_group(&self) -> LinearGroup<T>
    where T: PartialEq,
    {
        LinearGroup::new(self)
    }

    fn binary_group_by<P>(&self, predicate: P) -> BinaryGroupBy<T, P>
    where P: FnMut(&T, &T) -> bool,
    {
        BinaryGroupBy::new(self, predicate)
    }

    fn binary_group(&self) -> BinaryGroup<T>
    where T: PartialEq,
    {
        BinaryGroup::new(self)
    }

    fn exponential_group_by<P>(&self, predicate: P) -> ExponentialGroupBy<T, P>
    where P: FnMut(&T, &T) -> bool,
    {
        ExponentialGroupBy::new(self, predicate)
    }

    fn exponential_group(&self) -> ExponentialGroup<T>
    where T: PartialEq,
    {
        ExponentialGroup::new(self)
    }
}

impl<T> GroupByMut<T> for [T]
{
    fn linear_group_by_mut<P>(&mut self, predicate: P) -> LinearGroupByMut<T, P>
    where P: FnMut(&T, &T) -> bool,
    {
        LinearGroupByMut::new(self, predicate)
    }

    fn linear_group_mut(&mut self) -> LinearGroupMut<T>
    where T: PartialEq,
    {
        LinearGroupMut::new(self)
    }

    fn binary_group_by_mut<P>(&mut self, predicate: P) -> BinaryGroupByMut<T, P>
    where P: FnMut(&T, &T) -> bool,
    {
        BinaryGroupByMut::new(self, predicate)
    }

    fn binary_group_mut(&mut self) -> BinaryGroupMut<T>
    where T: PartialEq,
    {
        BinaryGroupMut::new(self)
    }

    fn exponential_group_by_mut<P>(&mut self, predicate: P) -> ExponentialGroupByMut<T, P>
    where P: FnMut(&T, &T) -> bool,
    {
        ExponentialGroupByMut::new(self, predicate)
    }

    fn exponential_group_mut(&mut self) -> ExponentialGroupMut<T>
    where T: PartialEq,
    {
        ExponentialGroupMut::new(self)
    }
}

/// A convenient trait to construct an iterator returning non-overlapping `str` slices
/// defined by a predicate.
pub trait StrGroupBy
{
    /// Returns an iterator on `str` groups using the *linear search* method.
    fn linear_group_by<P>(&self, predicate: P) -> LinearStrGroupBy<P>
    where P: FnMut(char, char) -> bool;

    /// Returns an iterator on `str` groups based on the [`PartialEq::eq`] method of `char`,
    /// it uses *linear search* to iterate over groups.
    ///
    /// [`PartialEq::eq`]: https://doc.rust-lang.org/std/primitive.char.html#impl-PartialEq%3Cchar%3E
    fn linear_group(&self) -> LinearStrGroup;
}

/// A convenient trait to construct an iterator returning non-overlapping *mutable* `str` slices
/// defined by a predicate.
pub trait StrGroupByMut
{
    /// Returns an iterator on *mutable* `str` groups using the *linear search* method.
    fn linear_group_by_mut<P>(&mut self, predicate: P) -> LinearStrGroupByMut<P>
    where P: FnMut(char, char) -> bool;

    /// Returns an iterator on *mutable* `str` groups based on the [`PartialEq::eq`] method of `char`,
    /// it uses *linear search* to iterate over groups.
    ///
    /// [`PartialEq::eq`]: https://doc.rust-lang.org/std/primitive.char.html#impl-PartialEq%3Cchar%3E
    fn linear_group_mut(&mut self) -> LinearStrGroupMut;
}

impl StrGroupBy for str
{
    fn linear_group_by<P>(&self, predicate: P) -> LinearStrGroupBy<P>
    where P: FnMut(char, char) -> bool,
    {
        LinearStrGroupBy::new(self, predicate)
    }

    fn linear_group(&self) -> LinearStrGroup {
        LinearStrGroup::new(self)
    }
}

impl StrGroupByMut for str
{
    fn linear_group_by_mut<P>(&mut self, predicate: P) -> LinearStrGroupByMut<P>
    where P: FnMut(char, char) -> bool,
    {
        LinearStrGroupByMut::new(self, predicate)
    }

    fn linear_group_mut(&mut self) -> LinearStrGroupMut {
        LinearStrGroupMut::new(self)
    }
}