Skip to content

Commit e970dc1

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 f41d5f4 commit e970dc1

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
@@ -693,6 +693,101 @@ pub struct IntoIter<T, A: Allocator> {
693693
_p: PhantomData<A>,
694694
}
695695

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

0 commit comments

Comments
 (0)