Skip to content

Commit 611d72c

Browse files
Danilo Krummrichfbq
authored andcommitted
rust: alloc: implement collect for IntoIter
Currently, we can't implement `FromIterator`. There are a couple of issues with this trait in the kernel, namely: - Rust's specialization feature is unstable. This prevents us to optimze for the special case where `I::IntoIter` equals `Vec`'s `IntoIter` type. - We also can't use `I::IntoIter`'s type ID either to work around this, since `FromIterator` doesn't require this type to be `'static`. - `FromIterator::from_iter` does return `Self` instead of `Result<Self, AllocError>`, hence we can't properly handle allocation failures. - Neither `Iterator::collect` nor `FromIterator::from_iter` can handle additional allocation flags. Instead, provide `IntoIter::collect`, such that we can at least convert `IntoIter` into a `Vec` again. Reviewed-by: Alice Ryhl <[email protected]> Signed-off-by: Danilo Krummrich <[email protected]> Link: https://lore.kernel.org/r/[email protected]
1 parent 76f8ff8 commit 611d72c

File tree

1 file changed

+78
-0
lines changed

1 file changed

+78
-0
lines changed

rust/kernel/alloc/kvec.rs

Lines changed: 78 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -681,6 +681,84 @@ where
681681
fn as_raw_mut_slice(&mut self) -> *mut [T] {
682682
ptr::slice_from_raw_parts_mut(self.ptr, self.len)
683683
}
684+
685+
fn into_raw_parts(self) -> (*mut T, NonNull<T>, usize, usize) {
686+
let me = ManuallyDrop::new(self);
687+
let ptr = me.ptr;
688+
let buf = me.buf;
689+
let len = me.len;
690+
let cap = me.cap;
691+
(ptr, buf, len, cap)
692+
}
693+
694+
/// Same as `Iterator::collect` but specialized for `Vec`'s `IntoIter`.
695+
///
696+
/// Currently, we can't implement `FromIterator`. There are a couple of issues with this trait
697+
/// in the kernel, namely:
698+
///
699+
/// - Rust's specialization feature is unstable. This prevents us to optimze for the special
700+
/// case where `I::IntoIter` equals `Vec`'s `IntoIter` type.
701+
/// - We also can't use `I::IntoIter`'s type ID either to work around this, since `FromIterator`
702+
/// doesn't require this type to be `'static`.
703+
/// - `FromIterator::from_iter` does return `Self` instead of `Result<Self, AllocError>`, hence
704+
/// we can't properly handle allocation failures.
705+
/// - Neither `Iterator::collect` nor `FromIterator::from_iter` can handle additional allocation
706+
/// flags.
707+
///
708+
/// Instead, provide `IntoIter::collect`, such that we can at least convert a `IntoIter` into a
709+
/// `Vec` again.
710+
///
711+
/// Note that `IntoIter::collect` doesn't require `Flags`, since it re-uses the existing backing
712+
/// buffer. However, this backing buffer may be shrunk to the actual count of elements.
713+
///
714+
/// # Examples
715+
///
716+
/// ```
717+
/// let v = kernel::kvec![1, 2, 3]?;
718+
/// let mut it = v.into_iter();
719+
///
720+
/// assert_eq!(it.next(), Some(1));
721+
///
722+
/// let v = it.collect(GFP_KERNEL);
723+
/// assert_eq!(v, [2, 3]);
724+
///
725+
/// # Ok::<(), Error>(())
726+
/// ```
727+
pub fn collect(self, flags: Flags) -> Vec<T, A> {
728+
let (mut ptr, buf, len, mut cap) = self.into_raw_parts();
729+
let has_advanced = ptr != buf.as_ptr();
730+
731+
if has_advanced {
732+
// SAFETY: Copy the contents we have advanced to at the beginning of the buffer.
733+
// `ptr` is guaranteed to be between `buf` and `buf.add(cap)` and `ptr.add(len)` is
734+
// guaranteed to be smaller than `buf.add(cap)`.
735+
unsafe { ptr::copy(ptr, buf.as_ptr(), len) };
736+
ptr = buf.as_ptr();
737+
}
738+
739+
// This can never fail, `len` is guaranteed to be smaller than `cap`.
740+
let layout = core::alloc::Layout::array::<T>(len).unwrap();
741+
742+
// SAFETY: `buf` points to the start of the backing buffer and `len` is guaranteed to be
743+
// smaller than `cap`. Depending on `alloc` this operation may shrink the buffer or leaves
744+
// it as it is.
745+
ptr = match unsafe { A::realloc(Some(buf.cast()), layout, flags) } {
746+
// If we fail to shrink, which likely can't even happen, continue with the existing
747+
// buffer.
748+
Err(_) => ptr,
749+
Ok(ptr) => {
750+
cap = len;
751+
ptr.as_ptr().cast()
752+
}
753+
};
754+
755+
// SAFETY: If the iterator has been advanced, the advanced elements have been copied to
756+
// the beginning of the buffer and `len` has been adjusted accordingly. `ptr` is guaranteed
757+
// to point to the start of the backing buffer. `cap` is either the original capacity or,
758+
// after shrinking the buffer, equal to `len`. `alloc` is guaranteed to be unchanged since
759+
// `into_iter` has been called on the original `Vec`.
760+
unsafe { Vec::from_raw_parts(ptr, len, cap) }
761+
}
684762
}
685763

686764
impl<T, A> Iterator for IntoIter<T, A>

0 commit comments

Comments
 (0)