Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- let mut chars = "abcdefg.".chars().peekable();
- let abc : String = chars.by_ref().cautious_take_while(|&x| x != 'd');
- let defg : String = chars.by_ref().cautious_take_while(|&x| x != '.');
- // yielding (abc = "abc", defg = "defg")
- pub trait IteratorExt: Iterator + Sized {
- fn by_ref(&mut self) -> &mut Self { self }
- }
- impl<'a, I> Iterator for &'a mut I where I: Iterator, I: ?Sized { ... }
- impl <'a, T: Iterator, P> Iterator for CautiousTakeWhile<&'a mut Peekable<T>, P>
- where P: FnMut(&T::Item) -> bool {
- //...
- }
- impl <'a, T: Iterator> CautiousTakeWhileable for &'a mut Peekable<T> {
- fn cautious_take_while<P>(self, f: P) -> CautiousTakeWhile<&'a mut Peekable<T>, P>
- where P: FnMut(&T::Item) -> bool {
- CautiousTakeWhile{inner: self, condition: f,}
- }
- }
- struct CautiousTakeWhile<'a, T: Iterator, P> {
- inner: &'a mut Peekable<T>,
- condition: P,
- }
- use std::iter::Peekable;
- fn main() {
- let mut chars = "abcdefg.".chars().peekable();
- let abc: String = CautiousTakeWhile{inner: chars.by_ref(), condition: |&x| x != 'd'}.collect();
- let defg: String = CautiousTakeWhile{inner: chars.by_ref(), condition: |&x| x != '.'}.collect();
- println!("{}, {}", abc, defg);
- }
- struct CautiousTakeWhile<'a, I, P> //'
- where I::Item: 'a, //'
- I: Iterator + 'a, //'
- P: FnMut(&I::Item) -> bool,
- {
- inner: &'a mut Peekable<I>, //'
- condition: P,
- }
- impl<'a, I, P> Iterator for CautiousTakeWhile<'a, I, P>
- where I::Item: 'a, //'
- I: Iterator + 'a, //'
- P: FnMut(&I::Item) -> bool
- {
- type Item = I::Item;
- fn next(&mut self) -> Option<I::Item> {
- let return_next =
- match self.inner.peek() {
- Some(ref v) => (self.condition)(v),
- _ => false,
- };
- if return_next { self.inner.next() } else { None }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement