Re: [PATCH v3 17/25] rust: alloc: implement `collect` for `IntoIter`

From: Alice Ryhl
Date: Thu Aug 01 2024 - 11:10:46 EST


On Thu, Aug 1, 2024 at 2:08 AM Danilo Krummrich <dakr@xxxxxxxxxx> wrote:
>
> 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.
>
> Signed-off-by: Danilo Krummrich <dakr@xxxxxxxxxx>

I'm not convinced a collect implementation specific to IntoIter is necessary?

> +
> + // SAFETY: `buf` points to the start of the backing buffer and `len` is guaranteed to be
> + // smaller than `cap`. Depending on `alloc` this operation may shrink the buffer or leaves
> + // it as it is.
> + ptr = match unsafe { A::realloc(Some(buf.cast()), layout, flags) } {

Why would you shrink it? You can just keep the capacity.

Alice