dimforge / nalgebra

Linear algebra library for Rust.
https://nalgebra.org
Apache License 2.0
4.02k stars 480 forks source link

`const fn` constructors #521

Open whatisaphone opened 5 years ago

whatisaphone commented 5 years ago

const fn has landed in Rust stable! It would be really helpful in one of my projects if nalgebra adopted it for constructors. The shortlist of types I need is Point2, Point3, Vector2, Vector3, UnitComplex, UnitQuaternion. But it probably makes sense for every type in the library.

Things like UnitComplex::new might not work due to compile-time restrictions on FP math, but I'm happy to work around that with UnitComplex::from_cos_sin_unchecked or whatever else makes sense.

Adding the keyword is a simple enough change (at least I hope!), but it will break on older compilers and I don't know your policy on Rust version compatibility.

jswrenn commented 5 years ago

I don't believe this is possible quite yet! The current level of const_fn support doesn't include functions with trait bounds. Not only do we need this feature to mark constructors as const in nalgebra (because of the pervasive N: Scalar, R: Dim, C: Dim, S: Storage bounds), but we need this feature to make the constructors in generic-array const, too.

whatisaphone commented 5 years ago

Aw, you're right :(

I guess this becomes the tracking issue then.

In the meantime I just learned about the union transmute hack, so that's the alternative for now.

related https://github.com/rust-lang/rust/issues/24111

sebcrozet commented 4 years ago

Revisiting this issue to see if the situation improved since last year. It appears that const fn on functions with trait bounds is still a problem:

error[E0723]: trait bounds other than `Sized` on const fn parameters are unstable
    --> src/base/construction.rs:842:14
     |
842  |           impl<N> MatrixMN<N, $R, $C>
     |                ^
...
clarfonthey commented 4 years ago

Side note, it would be nice if we could have a feature to enable these on nightly even though it'd be a mega pain to get working with macros.

lylythechosenone commented 5 months ago

I'm pretty sure trait bounds on const fns are now stable. It would be nice if we could revisit this.

Edit: confirmed stable since 1.61.0, just about two years ago.

Ralith commented 5 months ago

Calling trait methods in const isn't, so I'm not sure you'll be able to constify any useful constructors.

Andlon commented 5 months ago

The point!, vector! and matrix! construction macros are all usable in a const context, allowing you to construct const vectors, matrices and points.

The Unit-related constructors are probably currently not possible to support in const though, since AFAIK you'll need methods from SimdRealField or similar traits.

lylythechosenone commented 5 months ago

Ah, in that case this is not supported yet. Indeed, you still cannot call trait methods in const (coming soon, hopefully).