Skip to content

Commit 93e6023

Browse files
Danilo Krummrichojeda
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 optimize 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> Reviewed-by: Benno Lossin <benno.lossin@proton.me> Signed-off-by: Danilo Krummrich <dakr@kernel.org> Link: https://lore.kernel.org/r/20241004154149.93856-19-dakr@kernel.org [ Added newline in documentation, changed case of section to be consistent with an existing one, fixed typo. - Miguel ] Signed-off-by: Miguel Ojeda <ojeda@kernel.org>
1 parent 1d1d223 commit 93e6023

File tree

1 file changed

+95
-0
lines changed

1 file changed

+95
-0
lines changed

rust/kernel/alloc/kvec.rs

Lines changed: 95 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -692,6 +692,101 @@ pub struct IntoIter<T, A: Allocator> {
692692
_p: PhantomData<A>,
693693
}
694694

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

0 commit comments

Comments
 (0)