Skip to content

Commit eee5a27

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 <aliceryhl@google.com> Signed-off-by: Danilo Krummrich <dakr@kernel.org> Reviewed-by: Benno Lossin <benno.lossin@proton.me> Link: https://lore.kernel.org/r/20240911225449.152928-16-dakr@kernel.org
1 parent 5c648f9 commit eee5a27

1 file changed

Lines changed: 86 additions & 0 deletions

File tree

rust/kernel/alloc/kvec.rs

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

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

0 commit comments

Comments
 (0)