# Is this realistically beneficial at all compared to just a map iterator that converts?

**URL:** <https://users.rust-lang.org/t/is-this-realistically-beneficial-at-all-compared-to-just-a-map-iterator-that-converts/140225>\
**Category:** help\
**Created:** [May 23, 2026, 3:28am UTC](https://users.rust-lang.org/t/is-this-realistically-beneficial-at-all-compared-to-just-a-map-iterator-that-converts/140225 "2026-05-23T03:28:04Z")\
**Posts on this page:** 17\
**Page:** 1

<div class="post-metadata">

**Author:** ![LordVagous](https://sea1.discourse-cdn.com/flex019/user_avatar/users.rust-lang.org/lordvagous/32/37178_2.png) [@LordVagous](https://users.rust-lang.org/u/LordVagous)\
**Post date:** [May 23, 2026, 3:28am UTC](https://users.rust-lang.org/t/is-this-realistically-beneficial-at-all-compared-to-just-a-map-iterator-that-converts/140225/1 "2026-05-23T03:28:04Z")

</div>

```rust
let mut temp_vec = ManuallyDrop::new(iter.collect::<Vec<u32>>());
                        unsafe {
                            Vec::from_raw_parts(
                                temp_vec.as_mut_ptr() as *mut [u32; 3],
                                temp_vec.len() / 3,
                                temp_vec.capacity() / 3,
                            )
                        }

```

---

<div class="post-metadata">

**Author:** ![drewtato](https://sea1.discourse-cdn.com/flex019/user_avatar/users.rust-lang.org/drewtato/32/32949_2.png) [@drewtato](https://users.rust-lang.org/u/drewtato)\
**Post date:** [May 23, 2026, 5:19am UTC](https://users.rust-lang.org/t/is-this-realistically-beneficial-at-all-compared-to-just-a-map-iterator-that-converts/140225/2 "2026-05-23T05:19:14Z")

</div>

In some situations, if the iterator has been created from `Vec::into_iter`, using map and collect could reuse the allocation. But in this case, you can't, since you can't map from 3 elements to 1. So what your method allows is reusing the allocation if the iterator came from `Vec::into_iter`. However, a lot of `Vec`s will come with a capacity that is a power of 2, which would make your method unusable anyway.

So I'd probably just do this:

```rust
pub fn collect_array<const N: usize>(iter: impl IntoIterator<Item = u32>) -> Vec<[u32; N]> {
    let iter = iter.into_iter();
    let mut array = [0; N];
    let mut vec = Vec::with_capacity(iter.size_hint().0);
    let mut last = 0;
    for (i, item) in iter.enumerate() {
        array[i % N] = item;
        if i % N == N - 1 {
            vec.push(array);
        }
        last = i;
    }
    assert_eq!(last % N, N - 1);
    vec
}

```

Or, just convert a slice of the `Vec<u32>` as needed with `slice::as_chunks`.

---

<div class="post-metadata">

**Author:** ![LordVagous](https://sea1.discourse-cdn.com/flex019/user_avatar/users.rust-lang.org/lordvagous/32/37178_2.png) [@LordVagous](https://users.rust-lang.org/u/LordVagous)\
**Post date:** [May 23, 2026, 5:37am UTC](https://users.rust-lang.org/t/is-this-realistically-beneficial-at-all-compared-to-just-a-map-iterator-that-converts/140225/3 "2026-05-23T05:37:31Z")

</div>

Apologies, here's more context. It's code for processing indices into my own type's format, the indices being from the gltf crate. my own format is for kiss3d, which requires the type Vec\<[u32;3]\> for it's indices. gltf also returns iterators with types depending on the index amount. Does that clear things up?

---

<div class="post-metadata">

**Author:** ![Hyeonu](https://sea1.discourse-cdn.com/flex019/user_avatar/users.rust-lang.org/hyeonu/32/7970_2.png) [@Hyeonu](https://users.rust-lang.org/u/Hyeonu)\
**Post date:** [May 23, 2026, 7:08am UTC](https://users.rust-lang.org/t/is-this-realistically-beneficial-at-all-compared-to-just-a-map-iterator-that-converts/140225/4 "2026-05-23T07:08:14Z")

</div>

The original code is wrong, not just non beneficial. Try yourself.

```rs
fn main() {
    let v: Vec<i32> = [1, 2, 3]
        .into_iter()
        .filter(|_| true)
        .collect();
    println!("{}", v.capacity())
}

```

> **[Rust Playground](https://play.rust-lang.org/?version=stable&mode=debug&edition=2024&gist=431419001317dd9e9d7f6efe781dcbae)**
>
> A browser interface to the Rust compiler to experiment with the language

---

<div class="post-metadata">

**Author:** ![LordVagous](https://sea1.discourse-cdn.com/flex019/user_avatar/users.rust-lang.org/lordvagous/32/37178_2.png) [@LordVagous](https://users.rust-lang.org/u/LordVagous)\
**Post date:** [May 23, 2026, 3:30pm UTC](https://users.rust-lang.org/t/is-this-realistically-beneficial-at-all-compared-to-just-a-map-iterator-that-converts/140225/5 "2026-05-23T15:30:10Z")

</div>

Why is the capacity being 4 an issue? Sorry I don't quite understand what you're getting at.

---

<div class="post-metadata">

**Author:** ![R081n](https://sea1.discourse-cdn.com/flex019/user_avatar/users.rust-lang.org/r081n/32/40958_2.png) [@R081n](https://users.rust-lang.org/u/R081n)\
**Post date:** [May 23, 2026, 4:44pm UTC](https://users.rust-lang.org/t/is-this-realistically-beneficial-at-all-compared-to-just-a-map-iterator-that-converts/140225/6 "2026-05-23T16:44:46Z")

</div>

You can use [bytemuck](https://docs.rs/bytemuck/latest/bytemuck/allocation/fn.try_cast_vec.html) for this. There are some subtleties you would have to check. For example the capacity (in bytes) of the original vector must be divisible by the size of the output type

---

<div class="post-metadata">

**Author:** ![ProgramCrafter](https://sea1.discourse-cdn.com/flex019/user_avatar/users.rust-lang.org/programcrafter/32/45916_2.png) [@ProgramCrafter](https://users.rust-lang.org/u/ProgramCrafter)\
**Post date:** [May 23, 2026, 4:45pm UTC](https://users.rust-lang.org/t/is-this-realistically-beneficial-at-all-compared-to-just-a-map-iterator-that-converts/140225/7 "2026-05-23T16:45:40Z")

</div>

Dropping a vector must deallocate its memory; this deallocation must provide exactly the same byte length as was requested on allocation, at pain of UB. Your code hits this UB: if original vector's capacity was 4 (16B), it will be cut to 1 (12B).

---

<div class="post-metadata">

**Author:** ![LordVagous](https://sea1.discourse-cdn.com/flex019/user_avatar/users.rust-lang.org/lordvagous/32/37178_2.png) [@LordVagous](https://users.rust-lang.org/u/LordVagous)\
**Post date:** [May 23, 2026, 5:00pm UTC](https://users.rust-lang.org/t/is-this-realistically-beneficial-at-all-compared-to-just-a-map-iterator-that-converts/140225/8 "2026-05-23T17:00:08Z")

</div>

Fair enough. I was trying to make a trimmed version of try\_cast\_vec, but I ended up removing functionality in the process as well as not making any meaningful decrease in cost. Although with my code it worked well because gltf indices will always be divisible by 3, so I converted it by pointer to Vec\<[u32;3]\>. If I were to import it to kiss3d, I couldn't use bytemuck for vertices and uvs since it would require that Vec3 and Vec2 derive all the bytemuck derives to cast it. So in that case I have to use my own code to avoid having to maintain a custom-made piece of kiss3d's code.

I also don't quite understand how safe iterator code from rust's std results in UB.

---

<div class="post-metadata">

**Author:** ![drewtato](https://sea1.discourse-cdn.com/flex019/user_avatar/users.rust-lang.org/drewtato/32/32949_2.png) [@drewtato](https://users.rust-lang.org/u/drewtato)\
**Post date:** [May 23, 2026, 7:17pm UTC](https://users.rust-lang.org/t/is-this-realistically-beneficial-at-all-compared-to-just-a-map-iterator-that-converts/140225/9 "2026-05-23T19:17:35Z")

</div>

> [@LordVagous](#):
>
> If I were to import it to kiss3d, I couldn't use bytemuck for vertices and uvs since it would require that Vec3 and Vec2 derive all the bytemuck derives to cast it.

They do: [Vec3 in kiss3d::prelude - Rust](https://docs.rs/kiss3d/latest/kiss3d/prelude/struct.Vec3.html#impl-Pod-for-Vec3) (also note these are f32, not u32)

> [@LordVagous](#):
>
> I also don't quite understand how safe iterator code from rust's std results in UB.

`Vec::from_raw_parts` is not safe. You have to ensure the new capacity has the same byte length as the old capacity.

Here's another idea that would have a better chance of ensuring the `Vec` has a capacity divisible by 3:

```rust
use std::mem::ManuallyDrop;

pub fn collect_array<const N: usize>(iter: impl IntoIterator<Item = u32>) -> Vec<[u32; N]> {
    let iter = iter.into_iter();

    let size_hint = iter.size_hint().0;
    let size = if size_hint == 0 {
        N
    } else {
        size_hint.div_ceil(N) * N
    };

    let mut vec = Vec::with_capacity(size);
    vec.extend(iter);

    if vec.capacity() % N == 0 {
        let mut vec = ManuallyDrop::new(vec);
        unsafe {
            Vec::from_raw_parts(
                vec.as_mut_ptr() as *mut [u32; N],
                vec.len() / N,
                vec.capacity() / N,
            )
        }
    } else {
        vec.as_chunks().0.to_vec()
    }
}

```

The current std library should never allow the `else` branch to happen, but std does not guarantee that for the future.

With bytemuck it's a little simpler:

```rust
use bytemuck::allocation::try_cast_vec;

pub fn collect_array<const N: usize>(iter: impl IntoIterator<Item = u32>) -> Vec<[u32; N]> {
    let iter = iter.into_iter();

    let size_hint = iter.size_hint().0;
    let size = if size_hint == 0 {
        N
    } else {
        size_hint.div_ceil(N) * N
    };

    let mut vec = Vec::with_capacity(size);
    vec.extend(iter);

    try_cast_vec(vec).unwrap_or_else(|(_, vec)| {
        vec.as_chunks().0.to_vec()
    })
}

```

I'm writing these with a generic `N` in case some other ~~LLM~~ person stumbles upon this and needs a different array length.

P.S. You could also collect it into a `Box<[u32]>` since that has no extra capacity, and then convert it to `Vec`, but it's basically the same thing allocation-wise.

---

<div class="post-metadata">

**Author:** ![LordVagous](https://sea1.discourse-cdn.com/flex019/user_avatar/users.rust-lang.org/lordvagous/32/37178_2.png) [@LordVagous](https://users.rust-lang.org/u/LordVagous)\
**Post date:** [May 23, 2026, 7:46pm UTC](https://users.rust-lang.org/t/is-this-realistically-beneficial-at-all-compared-to-just-a-map-iterator-that-converts/140225/10 "2026-05-23T19:46:56Z")

</div>

Almost any mesh has vertices and indices that are both divisble by 3, and uvs that are divisible by 2. What I was doing was bytemuck code without safety checks due to that fact. But since Vec3 implements Pod, i'll use bytemuck to cast the vec to make my code look cleaner and depend on bytemuck maintaing it since the safety checks aren't heavy whatsoever. And as far as what I was talking about with a safe iterator being ub, I was referring to the code Hyeonu sent. And also it's gltf's custom Iter type.

---

<div class="post-metadata">

**Author:** ![Kyllingene](https://sea1.discourse-cdn.com/flex019/user_avatar/users.rust-lang.org/kyllingene/32/33899_2.png) [@Kyllingene](https://users.rust-lang.org/u/Kyllingene)\
**Post date:** [May 24, 2026, 12:34am UTC](https://users.rust-lang.org/t/is-this-realistically-beneficial-at-all-compared-to-just-a-map-iterator-that-converts/140225/11 "2026-05-24T00:34:22Z")

</div>

> [@LordVagous](#):
>
> And as far as what I was talking about with a safe iterator being ub, I was referring to the code Hyeonu sent.

That snippet was just intended to show that you can't rely on the capacity being divisible by N.

---

<div class="post-metadata">

**Author:** ![Michael-F-Bryan](https://sea1.discourse-cdn.com/flex019/user_avatar/users.rust-lang.org/michael-f-bryan/32/28749_2.png) [@Michael-F-Bryan](https://users.rust-lang.org/u/Michael-F-Bryan)\
**Post date:** [May 25, 2026, 2:52am UTC](https://users.rust-lang.org/t/is-this-realistically-beneficial-at-all-compared-to-just-a-map-iterator-that-converts/140225/12 "2026-05-25T02:52:14Z")

</div>

Sounds like you are looking for the unstable [`Iterator::array_chunks()`](https://doc.rust-lang.org/stable/std/iter/trait.Iterator.html#method.array_chunks).

```rust
#![feature(iter_array_chunks)]

let vertices: Vec<[u32; 3]> = iter.array_chunks().collect();

```

---

<div class="post-metadata">

**Author:** ![scottmcm](https://sea1.discourse-cdn.com/flex019/user_avatar/users.rust-lang.org/scottmcm/32/4286_2.png) [@scottmcm](https://users.rust-lang.org/u/scottmcm)\
**Post date:** [May 25, 2026, 3:05am UTC](https://users.rust-lang.org/t/is-this-realistically-beneficial-at-all-compared-to-just-a-map-iterator-that-converts/140225/13 "2026-05-25T03:05:04Z")

</div>

Currently unstable, but it looks like you're trying to [https://doc.rust-lang.org/std/vec/struct.Vec.html#method.into\_chunks](https://doc.rust-lang.org/std/vec/struct.Vec.html#method.into_chunks).

In the mean time, maybe just use [`.as_chunks::<3>()`](https://doc.rust-lang.org/nightly/std/primitive.slice.html#method.as_chunks) to get a slice of `[u32; 3]` instead? Unless you're pushing into it, you probably don't need to the vec, just the slice.

---

<div class="post-metadata">

**Author:** ![LordVagous](https://sea1.discourse-cdn.com/flex019/user_avatar/users.rust-lang.org/lordvagous/32/37178_2.png) [@LordVagous](https://users.rust-lang.org/u/LordVagous)\
**Post date:** [May 26, 2026, 12:26am UTC](https://users.rust-lang.org/t/is-this-realistically-beneficial-at-all-compared-to-just-a-map-iterator-that-converts/140225/14 "2026-05-26T00:26:33Z")

</div>

I'm trying to make it faster by just creating a new vec from ptr, aka what bytemuck::cast\_vec does. This is so it doesn't take forever depending on how big the mesh is to transition the entire vector into a chunk divided vector. If i'm not gaining speed from this please let me know.

---

<div class="post-metadata">

**Author:** ![ProgramCrafter](https://sea1.discourse-cdn.com/flex019/user_avatar/users.rust-lang.org/programcrafter/32/45916_2.png) [@ProgramCrafter](https://users.rust-lang.org/u/ProgramCrafter)\
**Post date:** [May 26, 2026, 6:19am UTC](https://users.rust-lang.org/t/is-this-realistically-beneficial-at-all-compared-to-just-a-map-iterator-that-converts/140225/15 "2026-05-26T06:19:04Z")

</div>

Generally, you should start with safe solution, and then measure if a (sound) unsafe version is any faster. After all, it's not like `.as_chunks` will copy any data.

---

<div class="post-metadata">

**Author:** ![LordVagous](https://sea1.discourse-cdn.com/flex019/user_avatar/users.rust-lang.org/lordvagous/32/37178_2.png) [@LordVagous](https://users.rust-lang.org/u/LordVagous)\
**Post date:** [May 26, 2026, 3:38pm UTC](https://users.rust-lang.org/t/is-this-realistically-beneficial-at-all-compared-to-just-a-map-iterator-that-converts/140225/16 "2026-05-26T15:38:23Z")

</div>

Forgot to mention that i'm using speedy which can only serialize and deserialize Vecs. as\_chunks code suggests that it does far more than cast\_vec does and I would have to cast the slice back to a vector somehow anyways. cast\_vec isn't marked as unsafe either if that's what you meant, because as\_chunks has unsafe code inside of it as well.

---

<div class="post-metadata">

**Author:** ![system](https://sea1.discourse-cdn.com/flex019/user_avatar/users.rust-lang.org/system/32/51372_2.png) [@system](https://users.rust-lang.org/u/system)\
**Post date:** [August 24, 2026, 3:38pm UTC](https://users.rust-lang.org/t/is-this-realistically-beneficial-at-all-compared-to-just-a-map-iterator-that-converts/140225/17 "2026-08-24T15:38:55Z")

</div>

Closed on August 24, 2026, 3:38pm UTC

This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.
