// Note: There are different ways to implement ZipSlices. // This version performed the best in benchmarks. // // I also implemented a version with three pointers (tptr, tend, uptr), // that mimiced slice::Iter and only checked bounds by using tptr == tend, // but that was inferior to this solution.
/// An iterator which iterates two slices simultaneously. /// /// `ZipSlices` acts like a double-ended `.zip()` iterator. /// /// It was intended to be more efficient than `.zip()`, and it was, then /// rustc changed how it optimizes so it can not promise improved performance /// at this time. /// /// Note that elements past the end of the shortest of the two slices are ignored. /// /// Iterator element type for `ZipSlices<T, U>` is `(T::Item, U::Item)`. For example, /// for a `ZipSlices<&'a [A], &'b mut [B]>`, the element type is `(&'a A, &'b mut B)`. #[derive(Clone)] pubstruct ZipSlices<T, U> {
t: T,
u: U,
len: usize,
index: usize,
}
impl<'a, 'b, A, B> ZipSlices<&'a [A], &'b [B]> { /// Create a new `ZipSlices` from slices `a` and `b`. /// /// Act like a double-ended `.zip()` iterator, but more efficiently. /// /// Note that elements past the end of the shortest of the two slices are ignored. #[inline(always)] pubfn new(a: &'a [A], b: &'b [B]) -> Self { let minl = cmp::min(a.len(), b.len());
ZipSlices {
t: a,
u: b,
len: minl,
index: 0,
}
}
}
impl<T, U> ZipSlices<T, U> where T: Slice,
U: Slice
{ /// Create a new `ZipSlices` from slices `a` and `b`. /// /// Act like a double-ended `.zip()` iterator, but more efficiently. /// /// Note that elements past the end of the shortest of the two slices are ignored. #[inline(always)] pubfn from_slices(a: T, b: U) -> Self { let minl = cmp::min(a.len(), b.len());
ZipSlices {
t: a,
u: b,
len: minl,
index: 0,
}
}
}
impl<T, U> Iterator for ZipSlices<T, U> where T: Slice,
U: Slice
{ type Item = (T::Item, U::Item);
/// A helper trait to let `ZipSlices` accept both `&[T]` and `&mut [T]`. /// /// Unsafe trait because: /// /// - Implementors must guarantee that `get_unchecked` is valid for all indices `0..len()`. pubunsafetrait Slice { /// The type of a reference to the slice's elements type Item; #[doc(hidden)] fn len(&self) -> usize; #[doc(hidden)] unsafefn get_unchecked(&mutself, i: usize) -> Self::Item;
}
Die Informationen auf dieser Webseite wurden
nach bestem Wissen sorgfältig zusammengestellt. Es wird jedoch weder Vollständigkeit, noch Richtigkeit,
noch Qualität der bereit gestellten Informationen zugesichert.
Bemerkung:
Die farbliche Syntaxdarstellung und die Messung sind noch experimentell.