::lending-iterator

Repository Latest version Documentation MSRV unsafe forbidden License CI

Fully generic LendingIterators in stable Rust.

Examples

Click to see/hide

windows_mut()!

```rust use ::lending_iterator::prelude::*;

let mut array = [0; 15]; array[1] = 1; // Cumulative sums are trivial with a mut sliding window, // so let's showcase that by generating a Fibonacci sequence. let mut iter = array.windowsmut::<3>(); while let Some(&mut [a, b, ref mut next]) = iter.next() { *next = a + b; } asserteq!( array, [0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144, 233, 377], ); ```

Rolling your own version of it using the handy from_fn constructor

```rust use ::lending_iterator::prelude::*;

let mut array = [0; 15]; array[1] = 1; // Let's hand-roll our iterator lending &mut sliding windows: let mut iter = { let mut start = 0; lendingiterator::FromFn:: { state: &mut array, next: move |array| { let toyield = array .getmut(start..)? .getmut(..3)? .tryinto() // &mut [u8] -> &mut [u8; 3] .unwrap() ; start += 1; Some(toyield) }, phantom: <_>::default(), } }; while let Some(&mut [a, b, ref mut next]) = iter.next() { *next = a + b; } asserteq!( array, [0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144, 233, 377], ); ```

LendingIterator adapters

See [lending_iterator::adapters].


Bonus: Higher-Kinded Types (HKT)

See higher_kinded_types for a presentation about them.

Real-life usage: .sort_by_key() that is fully generic over the key lending mode

As noted in this 6-year-old issue:

Such an API can easily be provided using the HKT API of this crate:

Click to see/hide

```rust use ::lendingiterator::higherkinded_types::{*, Apply as A};

fn slicesortbykey ( slice: &' mut [Item], mut getkey: KeyGetter, ) where Key : HKT, // "Key : <'>" KeyGetter : for<'item> FnMut(&'item Item) -> A!(Key<'item>), for<'item> A!(Key<'item>) : Ord , { slice.sortby(|a, b| Ord::cmp( &getkey(a), &get_key(b), )) }

// ---- Demo ----

struct Client { key: String, version: u8 }

fn main () { let clients: &mut [Client] = &mut [];

// Error: cannot infer an appropriate lifetime for autoref due to conflicting requirements
// clients.sort_by_key(|c| &c.key);

// OK
slice_sort_by_key::<HKT!(&str), _, _>(clients, |c| &c.key);

// Important: owned case works too!
slice_sort_by_key::<HKT!(u8), _, _>(clients, |c| c.version);

} ```