Path: blob/main/crates/polars-utils/src/itertools/mod.rs
6940 views
use std::cmp::Ordering;12use crate::IdxSize;34pub mod enumerate_idx;56/// Utility extension trait of iterator methods.7pub trait Itertools: Iterator {8/// Equivalent to `.collect::<Vec<_>>()`.9fn collect_vec(self) -> Vec<Self::Item>10where11Self: Sized,12{13self.collect()14}1516/// Equivalent to `.collect::<Result<_, _>>()`.17fn try_collect<T, U, E>(self) -> Result<U, E>18where19Self: Sized + Iterator<Item = Result<T, E>>,20Result<U, E>: FromIterator<Result<T, E>>,21{22self.collect()23}2425/// Equivalent to `.collect::<Result<Vec<_>, _>>()`.26fn try_collect_vec<T, U, E>(self) -> Result<Vec<U>, E>27where28Self: Sized + Iterator<Item = Result<T, E>>,29Result<Vec<U>, E>: FromIterator<Result<T, E>>,30{31self.collect()32}3334fn enumerate_idx(self) -> enumerate_idx::EnumerateIdx<Self, IdxSize>35where36Self: Sized,37{38enumerate_idx::EnumerateIdx::new(self)39}4041fn enumerate_u32(self) -> enumerate_idx::EnumerateIdx<Self, u32>42where43Self: Sized,44{45enumerate_idx::EnumerateIdx::new(self)46}4748fn all_equal(mut self) -> bool49where50Self: Sized,51Self::Item: PartialEq,52{53match self.next() {54None => true,55Some(a) => self.all(|x| a == x),56}57}5859// Stable copy of the unstable eq_by from the stdlib.60fn eq_by_<I, F>(mut self, other: I, mut eq: F) -> bool61where62Self: Sized,63I: IntoIterator,64F: FnMut(Self::Item, I::Item) -> bool,65{66let mut other = other.into_iter();67loop {68match (self.next(), other.next()) {69(None, None) => return true,70(None, Some(_)) => return false,71(Some(_), None) => return false,72(Some(l), Some(r)) => {73if eq(l, r) {74continue;75} else {76return false;77}78},79}80}81}8283// Stable copy of the unstable partial_cmp_by from the stdlib.84fn partial_cmp_by_<I, F>(mut self, other: I, mut partial_cmp: F) -> Option<Ordering>85where86Self: Sized,87I: IntoIterator,88F: FnMut(Self::Item, I::Item) -> Option<Ordering>,89{90let mut other = other.into_iter();91loop {92match (self.next(), other.next()) {93(None, None) => return Some(Ordering::Equal),94(None, Some(_)) => return Some(Ordering::Less),95(Some(_), None) => return Some(Ordering::Greater),96(Some(l), Some(r)) => match partial_cmp(l, r) {97Some(Ordering::Equal) => continue,98ord => return ord,99},100}101}102}103}104105impl<T: Iterator + ?Sized> Itertools for T {}106107108