dimforge / dimforge/nalgebra

Safe way to construct a vector or a matrix from an iterator?

Open
#1,122 1 comment 0 reactions 0 assignees View on GitHub
Dominant language
Rust
Stars
4.8k
Forks
565
PR merge metrics
No merged PRs in 30d

Description

Is there a way to create a Matrix or a Vector with the `from_iterator` function without panicking?

I am making a little wrapper around `nalgebra` for my own library, and I'd like to create vectors/matrices safely, that is, return a `Result` rather than panicking on failure. The `from_iterator` method panics if the iterator isn't long enough, and I couldn't find a variation that doesn't panic.

Right now, I pretty much copied the code in `from_iterator` and replaced the panicking part with returning `Err`:
```rust
use nalgebra as na;

pub fn from_iterator(value: I) -> Result
where
I: IntoIterator,
{
let mut arr: na::ArrayStorage, S, 1> =
na::DefaultAllocator::allocate_uninit(na::Const::, na::Const::<1>);

let mut counter = 0;
for (arr_ptr, e) in arr.as_mut_slice().iter_mut().zip(value) {
*arr_ptr = MaybeUninit::new(e);
counter += 1;
}

if counter == S {
unsafe {
Ok(Self {
data: na::SVector::from_data(,
na::Const<1>,
>>::assume_init(arr)),
})
}
} else {
Err(DimensionError {
message: "Not enough data for ".into(),
})
}
}
```

It doesn't look like the best solution. Is there a version of `from_iterator` that doesn't panic? If not, I'd consider adding it to the library. Something like `try_from_iterator`. If I really have to implement it myself, I'd like to know if my implementation is as efficient as it could be?

Contributor guide

No contributing guide indexed for this repository

Assessment

This issue has not been assessed yet.

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.