DrainWhileable

Trait DrainWhileable 

Source
pub trait DrainWhileable<T> {
    // Required method
    fn drain_while<P>(&mut self, pred: P) -> DrainWhile<'_, T> 
       where P: Fn(&T) -> bool;
}

Required Methods§

Source

fn drain_while<P>(&mut self, pred: P) -> DrainWhile<'_, T>
where P: Fn(&T) -> bool,

Take the elements of a vector, left-to-right, stopping at the first non-matching element.

The returned DrainWhile iterates over the longest prefex in which all elements satisfy pred; when the iterator is dropped, the prefix is removed from vec.

let mut orig: Vec<usize> = vec![0,1,2,3,4,5];
let none: Vec<usize> = orig.drain_while(|_| false).collect();
let some: Vec<usize> = orig.drain_while(|x| *x < 3).collect();
let rest: Vec<usize> = orig.drain_while(|_| true).collect();

assert_eq!(none, vec![]);
assert_eq!(some, vec![0,1,2]);
assert_eq!(rest, vec![3,4,5]);
assert_eq!(orig, vec![]);

The behaviour of drain_while() differs from drain().take_while() in the final state of the original vector, as illustrated here:

let mut v1 = vec![1,2,3,4,5];
let mut v2 = vec![1,2,3,4,5];
v1.drain(..).take_while(|x| *x < 3);
v2.drain_while(|x| *x < 3);
assert_eq!(v1, vec![]);
assert_eq!(v2, vec![3,4,5]);

The same caveats which apply to drain also apply to drain_while:

  1. The element range is removed even if the iterator is only partially consumed or not consumed at all.
  2. It is unspecified how many elements are removed from the vector, if the DrainWhile value is leaked.

The current implementation is fairly naive, but I believe there’s scope for speeding it up substantially.

Dyn Compatibility§

This trait is not dyn compatible.

In older versions of Rust, dyn compatibility was called "object safety", so this trait is not object safe.

Implementations on Foreign Types§

Source§

impl<T> DrainWhileable<T> for Vec<T>

Source§

fn drain_while<P>(&mut self, pred: P) -> DrainWhile<'_, T>
where P: FnMut(&T) -> bool,

Implementors§