Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #![warn(rust_2018_idioms)]
- fn reduce_async_with_store<'a, I, A, F, C>(
- store: &mut Store,
- mut iterator: I,
- accumulator: A,
- mut f: F,
- continuation: C,
- ) where
- I: Iterator + 'a,
- F: FnMut(&mut Store, I::Item, A, Box<dyn FnOnce(&mut Store, A) + 'a>) + Clone + 'a,
- C: FnOnce(&mut Store, A) + 'a,
- {
- match iterator.next() {
- None => continuation(store, accumulator),
- Some(item) => {
- let next: Box<dyn FnOnce(&mut Store, A) + 'a> = {
- let f = f.clone();
- Box::new(move |store, accumulator| {
- reduce_async_with_store(store, iterator, accumulator, f, continuation)
- })
- };
- f(store, item, accumulator, next);
- }
- }
- }
- fn some_operation(state: &mut Store, continuation: Box<dyn FnOnce(&mut Store) + 'static>) {
- let mut new_state = Store { foo: state.foo };
- continuation(&mut new_state);
- }
- #[derive(Debug)]
- pub struct Store {
- foo: u8,
- }
- fn main() {
- let mut some_state = Store { foo: 0 };
- let arr = vec![1u8, 2u8, 3u8];
- reduce_async_with_store(
- &mut some_state,
- arr.into_iter(),
- Vec::new(),
- |store, item, mut acc, continuation| {
- println!("Item: {}", item);
- store.foo += item;
- acc.push(item);
- some_operation(
- store,
- Box::new(move |stor| {
- continuation(stor, acc);
- }),
- );
- },
- |store, acc| {
- println!("Done!! {:?} {:?}", store, acc);
- },
- )
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement