diff --git a/.github/workflows/nalgebra-ci-build.yml b/.github/workflows/nalgebra-ci-build.yml index 6f97b38b4..60c56457e 100644 --- a/.github/workflows/nalgebra-ci-build.yml +++ b/.github/workflows/nalgebra-ci-build.yml @@ -60,7 +60,7 @@ jobs: - name: Select rustc version uses: actions-rs/toolchain@v1 with: - toolchain: 1.79.0 + toolchain: 1.85.0 override: true - uses: actions/checkout@v4 - name: check @@ -77,7 +77,7 @@ jobs: - name: Select rustc version uses: actions-rs/toolchain@v1 with: - toolchain: 1.81.0 + toolchain: 1.85.0 override: true - uses: actions/checkout@v4 - name: test diff --git a/CHANGELOG.md b/CHANGELOG.md index 9c0a88355..6ac55d8c1 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -11,6 +11,10 @@ This project adheres to [Semantic Versioning](https://semver.org/). - Add the `convert-glam030` feature to enable conversion from/to types from `glam` v0.30. +### Changed + +- Moved to Rust 2024 edition. + ## [0.33.2] (29 October 2024) ### Added diff --git a/Cargo.toml b/Cargo.toml index e21a686df..65d44e82e 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -11,7 +11,8 @@ readme = "README.md" categories = ["science", "mathematics", "wasm", "no-std"] keywords = ["linear", "algebra", "matrix", "vector", "math"] license = "Apache-2.0" -edition = "2018" +edition = "2024" +rust-version = "1.85.0" exclude = ["/ci/*", "/.travis.yml", "/Makefile"] [badges] @@ -103,6 +104,7 @@ matrixmultiply = { version = "0.3", optional = true } serde = { version = "1.0", default-features = false, features = [ "derive", ], optional = true } +# TODO: once rkyv is updated to 0.8, we could consider removing the `allow(unsafe_op_in_unsafe_fn)`. rkyv = { version = "0.7.41", default-features = false, optional = true } mint = { version = "0.5", optional = true } quickcheck = { version = "1", optional = true } @@ -134,7 +136,7 @@ rayon = { version = "1.6", optional = true } [dev-dependencies] serde_json = "1.0" rand_xorshift = "0.4" -rand_isaac = "0.3" +rand_isaac = "0.4" criterion = { version = "0.4", features = ["html_reports"] } nalgebra = { path = ".", features = ["debug", "compare", "rand", "macros"] } diff --git a/benches/common/macros.rs b/benches/common/macros.rs index 3f775958f..2f64f83a1 100644 --- a/benches/common/macros.rs +++ b/benches/common/macros.rs @@ -5,8 +5,8 @@ macro_rules! bench_binop( fn $name(bh: &mut criterion::Criterion) { use rand::SeedableRng; let mut rng = IsaacRng::seed_from_u64(0); - let a = rng.gen::<$t1>(); - let b = rng.gen::<$t2>(); + let a = rng.random::<$t1>(); + let b = rng.random::<$t2>(); bh.bench_function(stringify!($name), move |bh| bh.iter(|| { a.$binop(b) @@ -20,8 +20,8 @@ macro_rules! bench_binop_ref( fn $name(bh: &mut criterion::Criterion) { use rand::SeedableRng; let mut rng = IsaacRng::seed_from_u64(0); - let a = rng.gen::<$t1>(); - let b = rng.gen::<$t2>(); + let a = rng.random::<$t1>(); + let b = rng.random::<$t2>(); bh.bench_function(stringify!($name), move |bh| bh.iter(|| { a.$binop(&b) @@ -35,8 +35,8 @@ macro_rules! bench_binop_fn( fn $name(bh: &mut criterion::Criterion) { use rand::SeedableRng; let mut rng = IsaacRng::seed_from_u64(0); - let a = rng.gen::<$t1>(); - let b = rng.gen::<$t2>(); + let a = rng.random::<$t1>(); + let b = rng.random::<$t2>(); bh.bench_function(stringify!($name), move |bh| bh.iter(|| { $binop(&a, &b) @@ -53,7 +53,7 @@ macro_rules! bench_unop_na( use rand::SeedableRng; let mut rng = IsaacRng::seed_from_u64(0); - let elems: Vec<$t> = (0usize .. LEN).map(|_| rng.gen::<$t>()).collect(); + let elems: Vec<$t> = (0usize .. LEN).map(|_| rng.random::<$t>()).collect(); let mut i = 0; bh.bench_function(stringify!($name), move |bh| bh.iter(|| { @@ -75,7 +75,7 @@ macro_rules! bench_unop( use rand::SeedableRng; let mut rng = IsaacRng::seed_from_u64(0); - let mut elems: Vec<$t> = (0usize .. LEN).map(|_| rng.gen::<$t>()).collect(); + let mut elems: Vec<$t> = (0usize .. LEN).map(|_| rng.random::<$t>()).collect(); let mut i = 0; bh.bench_function(stringify!($name), move |bh| bh.iter(|| { @@ -97,7 +97,7 @@ macro_rules! bench_construction( use rand::SeedableRng; let mut rng = IsaacRng::seed_from_u64(0); - $(let $args: Vec<$types> = (0usize .. LEN).map(|_| rng.gen::<$types>()).collect();)* + $(let $args: Vec<$types> = (0usize .. LEN).map(|_| rng.random::<$types>()).collect();)* let mut i = 0; bh.bench_function(stringify!($name), move |bh| bh.iter(|| { diff --git a/benches/core/matrix.rs b/benches/core/matrix.rs index ec1102b71..2f156ca72 100644 --- a/benches/core/matrix.rs +++ b/benches/core/matrix.rs @@ -1,4 +1,4 @@ -use na::{DMatrix, DVector, Matrix2, Matrix3, Matrix4, OMatrix, Vector2, Vector3, Vector4, U10}; +use na::{DMatrix, DVector, Matrix2, Matrix3, Matrix4, OMatrix, U10, Vector2, Vector3, Vector4}; use rand::Rng; use rand_isaac::IsaacRng; use std::ops::{Add, Div, Mul, Sub}; diff --git a/benches/core/vector.rs b/benches/core/vector.rs index 6d5dbdc41..f05789e74 100644 --- a/benches/core/vector.rs +++ b/benches/core/vector.rs @@ -52,7 +52,7 @@ fn vec10000_axpy_f64(bh: &mut criterion::Criterion) { let mut rng = IsaacRng::seed_from_u64(0); let mut a = DVector::new_random(10000); let b = DVector::new_random(10000); - let n = rng.gen::(); + let n = rng.random::(); bh.bench_function("vec10000_axpy_f64", move |bh| { bh.iter(|| a.axpy(n, &b, 1.0)) @@ -64,8 +64,8 @@ fn vec10000_axpy_beta_f64(bh: &mut criterion::Criterion) { let mut rng = IsaacRng::seed_from_u64(0); let mut a = DVector::new_random(10000); let b = DVector::new_random(10000); - let n = rng.gen::(); - let beta = rng.gen::(); + let n = rng.random::(); + let beta = rng.random::(); bh.bench_function("vec10000_axpy_beta_f64", move |bh| { bh.iter(|| a.axpy(n, &b, beta)) @@ -77,7 +77,7 @@ fn vec10000_axpy_f64_slice(bh: &mut criterion::Criterion) { let mut rng = IsaacRng::seed_from_u64(0); let mut a = DVector::new_random(10000); let b = DVector::new_random(10000); - let n = rng.gen::(); + let n = rng.random::(); bh.bench_function("vec10000_axpy_f64_slice", move |bh| { bh.iter(|| { @@ -94,7 +94,7 @@ fn vec10000_axpy_f64_static(bh: &mut criterion::Criterion) { let mut rng = IsaacRng::seed_from_u64(0); let mut a = SVector::::new_random(); let b = SVector::::new_random(); - let n = rng.gen::(); + let n = rng.random::(); // NOTE: for some reasons, it is much faster if the argument are boxed (Box::new(OVector...)). bh.bench_function("vec10000_axpy_f64_static", move |bh| { @@ -107,7 +107,7 @@ fn vec10000_axpy_f32(bh: &mut criterion::Criterion) { let mut rng = IsaacRng::seed_from_u64(0); let mut a = DVector::new_random(10000); let b = DVector::new_random(10000); - let n = rng.gen::(); + let n = rng.random::(); bh.bench_function("vec10000_axpy_f32", move |bh| { bh.iter(|| a.axpy(n, &b, 1.0)) @@ -119,8 +119,8 @@ fn vec10000_axpy_beta_f32(bh: &mut criterion::Criterion) { let mut rng = IsaacRng::seed_from_u64(0); let mut a = DVector::new_random(10000); let b = DVector::new_random(10000); - let n = rng.gen::(); - let beta = rng.gen::(); + let n = rng.random::(); + let beta = rng.random::(); bh.bench_function("vec10000_axpy_beta_f32", move |bh| { bh.iter(|| a.axpy(n, &b, beta)) diff --git a/benches/lib.rs b/benches/lib.rs index 48633317d..df866cca3 100644 --- a/benches/lib.rs +++ b/benches/lib.rs @@ -17,7 +17,7 @@ pub mod linalg; fn reproducible_dmatrix(nrows: usize, ncols: usize) -> DMatrix { use rand::SeedableRng; let mut rng = IsaacRng::seed_from_u64(0); - DMatrix::::from_fn(nrows, ncols, |_, _| rng.gen()) + DMatrix::::from_fn(nrows, ncols, |_, _| rng.random()) } criterion_main!( diff --git a/nalgebra-glm/Cargo.toml b/nalgebra-glm/Cargo.toml index ba3d77cc1..1610cc8f1 100644 --- a/nalgebra-glm/Cargo.toml +++ b/nalgebra-glm/Cargo.toml @@ -11,7 +11,7 @@ readme = "../README.md" categories = ["science", "mathematics", "wasm", "no standard library"] keywords = ["linear", "algebra", "matrix", "vector", "math"] license = "Apache-2.0" -edition = "2018" +edition = "2024" [badges] maintenance = { status = "actively-developed" } diff --git a/nalgebra-glm/src/common.rs b/nalgebra-glm/src/common.rs index f41fafbba..4a9e57518 100644 --- a/nalgebra-glm/src/common.rs +++ b/nalgebra-glm/src/common.rs @@ -1,8 +1,8 @@ use core::mem; +use crate::RealNumber; use crate::aliases::{TMat, TVec}; use crate::traits::Number; -use crate::RealNumber; /// For each matrix or vector component `x` if `x >= 0`; otherwise, it returns `-x`. /// @@ -515,11 +515,7 @@ pub fn smoothstep(edge0: T, edge1: T, x: T) -> T { /// Returns 0.0 if `x < edge`, otherwise it returns 1.0. pub fn step_scalar(edge: T, x: T) -> T { - if edge > x { - T::zero() - } else { - T::one() - } + if edge > x { T::zero() } else { T::one() } } /// Returns 0.0 if `x[i] < edge`, otherwise it returns 1.0. diff --git a/nalgebra-glm/src/constructors.rs b/nalgebra-glm/src/constructors.rs index 5a43f2b59..ff7205752 100644 --- a/nalgebra-glm/src/constructors.rs +++ b/nalgebra-glm/src/constructors.rs @@ -1,8 +1,8 @@ +use crate::RealNumber; use crate::aliases::{ Qua, TMat, TMat2, TMat2x3, TMat2x4, TMat3, TMat3x2, TMat3x4, TMat4, TMat4x2, TMat4x3, TVec1, TVec2, TVec3, TVec4, }; -use crate::RealNumber; use na::Scalar; /// Creates a new 1D vector. diff --git a/nalgebra-glm/src/exponential.rs b/nalgebra-glm/src/exponential.rs index 340389a2e..5a8153d4d 100644 --- a/nalgebra-glm/src/exponential.rs +++ b/nalgebra-glm/src/exponential.rs @@ -1,5 +1,5 @@ -use crate::aliases::TVec; use crate::RealNumber; +use crate::aliases::TVec; /// Component-wise exponential. /// diff --git a/nalgebra-glm/src/ext/matrix_clip_space.rs b/nalgebra-glm/src/ext/matrix_clip_space.rs index 5ea39d234..acf3de0be 100644 --- a/nalgebra-glm/src/ext/matrix_clip_space.rs +++ b/nalgebra-glm/src/ext/matrix_clip_space.rs @@ -1,5 +1,5 @@ -use crate::aliases::TMat4; use crate::RealNumber; +use crate::aliases::TMat4; //pub fn frustum(left: T, right: T, bottom: T, top: T, near: T, far: T) -> TMat4 { // unimplemented!() diff --git a/nalgebra-glm/src/ext/matrix_projection.rs b/nalgebra-glm/src/ext/matrix_projection.rs index 86a2cca96..f8ab2d253 100644 --- a/nalgebra-glm/src/ext/matrix_projection.rs +++ b/nalgebra-glm/src/ext/matrix_projection.rs @@ -1,5 +1,5 @@ -use crate::aliases::{TMat4, TVec2, TVec3, TVec4}; use crate::RealNumber; +use crate::aliases::{TMat4, TVec2, TVec3, TVec4}; /// Define a picking region. /// diff --git a/nalgebra-glm/src/ext/quaternion_common.rs b/nalgebra-glm/src/ext/quaternion_common.rs index b1e10f747..559e20847 100644 --- a/nalgebra-glm/src/ext/quaternion_common.rs +++ b/nalgebra-glm/src/ext/quaternion_common.rs @@ -1,7 +1,7 @@ use na::Unit; -use crate::aliases::Qua; use crate::RealNumber; +use crate::aliases::Qua; /// The conjugate of `q`. pub fn quat_conjugate(q: &Qua) -> Qua { diff --git a/nalgebra-glm/src/ext/quaternion_relational.rs b/nalgebra-glm/src/ext/quaternion_relational.rs index b9f6eaf58..95f6ad4e9 100644 --- a/nalgebra-glm/src/ext/quaternion_relational.rs +++ b/nalgebra-glm/src/ext/quaternion_relational.rs @@ -1,5 +1,5 @@ -use crate::aliases::{Qua, TVec}; use crate::RealNumber; +use crate::aliases::{Qua, TVec}; /// Component-wise equality comparison between two quaternions. pub fn quat_equal(x: &Qua, y: &Qua) -> TVec { diff --git a/nalgebra-glm/src/ext/quaternion_transform.rs b/nalgebra-glm/src/ext/quaternion_transform.rs index 17566c171..178e06e47 100644 --- a/nalgebra-glm/src/ext/quaternion_transform.rs +++ b/nalgebra-glm/src/ext/quaternion_transform.rs @@ -1,7 +1,7 @@ use na::{Unit, UnitQuaternion}; -use crate::aliases::{Qua, TVec3}; use crate::RealNumber; +use crate::aliases::{Qua, TVec3}; /// Computes the quaternion exponential. pub fn quat_exp(q: &Qua) -> Qua { diff --git a/nalgebra-glm/src/ext/quaternion_trigonometric.rs b/nalgebra-glm/src/ext/quaternion_trigonometric.rs index 59d37e03b..78dced3df 100644 --- a/nalgebra-glm/src/ext/quaternion_trigonometric.rs +++ b/nalgebra-glm/src/ext/quaternion_trigonometric.rs @@ -1,7 +1,7 @@ use na::{Unit, UnitQuaternion}; -use crate::aliases::{Qua, TVec3}; use crate::RealNumber; +use crate::aliases::{Qua, TVec3}; /// The rotation angle of this quaternion assumed to be normalized. pub fn quat_angle(x: &Qua) -> T { diff --git a/nalgebra-glm/src/ext/scalar_common.rs b/nalgebra-glm/src/ext/scalar_common.rs index c7d50da0c..9685eaac9 100644 --- a/nalgebra-glm/src/ext/scalar_common.rs +++ b/nalgebra-glm/src/ext/scalar_common.rs @@ -16,11 +16,7 @@ use crate::traits::Number; /// * [`min3_scalar()`] /// * [`min4_scalar()`] pub fn max2_scalar(a: T, b: T) -> T { - if a >= b { - a - } else { - b - } + if a >= b { a } else { b } } /// Returns the maximum among two values. @@ -39,11 +35,7 @@ pub fn max2_scalar(a: T, b: T) -> T { /// * [`min3_scalar()`] /// * [`min4_scalar()`] pub fn min2_scalar(a: T, b: T) -> T { - if a <= b { - a - } else { - b - } + if a <= b { a } else { b } } /// Returns the maximum among three values. diff --git a/nalgebra-glm/src/gtc/quaternion.rs b/nalgebra-glm/src/gtc/quaternion.rs index c145e121e..9d3467133 100644 --- a/nalgebra-glm/src/gtc/quaternion.rs +++ b/nalgebra-glm/src/gtc/quaternion.rs @@ -1,7 +1,7 @@ use na::UnitQuaternion; -use crate::aliases::{Qua, TMat4, TVec, TVec3}; use crate::RealNumber; +use crate::aliases::{Qua, TMat4, TVec, TVec3}; /// Euler angles of the quaternion `q` as (pitch, yaw, roll). pub fn quat_euler_angles(x: &Qua) -> TVec3 { diff --git a/nalgebra-glm/src/gtx/matrix_cross_product.rs b/nalgebra-glm/src/gtx/matrix_cross_product.rs index fd3ed32ea..a49b3bfbf 100644 --- a/nalgebra-glm/src/gtx/matrix_cross_product.rs +++ b/nalgebra-glm/src/gtx/matrix_cross_product.rs @@ -1,5 +1,5 @@ -use crate::aliases::{TMat3, TMat4, TVec3}; use crate::RealNumber; +use crate::aliases::{TMat3, TMat4, TVec3}; /// Builds a 3x3 matrix `m` such that for any `v`: `m * v == cross(x, v)`. /// diff --git a/nalgebra-glm/src/gtx/mod.rs b/nalgebra-glm/src/gtx/mod.rs index b06f3998d..391f578c1 100644 --- a/nalgebra-glm/src/gtx/mod.rs +++ b/nalgebra-glm/src/gtx/mod.rs @@ -24,8 +24,8 @@ pub use self::rotate_vector::{ }; pub use self::transform::{rotation, rotation2d, scaling, scaling2d, translation, translation2d}; pub use self::transform2::{ - proj, proj2d, reflect, reflect2d, scale_bias, scale_bias_matrix, shear2d_x, shear2d_y, shear_x, - shear_y, shear_z, + proj, proj2d, reflect, reflect2d, scale_bias, scale_bias_matrix, shear_x, shear_y, shear_z, + shear2d_x, shear2d_y, }; pub use self::transform2d::{rotate2d, scale2d, translate2d}; pub use self::vector_angle::angle; diff --git a/nalgebra-glm/src/gtx/norm.rs b/nalgebra-glm/src/gtx/norm.rs index e21e61fb8..3402719bc 100644 --- a/nalgebra-glm/src/gtx/norm.rs +++ b/nalgebra-glm/src/gtx/norm.rs @@ -1,5 +1,5 @@ -use crate::aliases::TVec; use crate::RealNumber; +use crate::aliases::TVec; /// The squared distance between two points. /// diff --git a/nalgebra-glm/src/gtx/quaternion.rs b/nalgebra-glm/src/gtx/quaternion.rs index 736d3bbbb..b5c3887fc 100644 --- a/nalgebra-glm/src/gtx/quaternion.rs +++ b/nalgebra-glm/src/gtx/quaternion.rs @@ -1,7 +1,7 @@ use na::{Rotation3, Unit, UnitQuaternion}; -use crate::aliases::{Qua, TMat3, TMat4, TVec3, TVec4}; use crate::RealNumber; +use crate::aliases::{Qua, TMat3, TMat4, TVec3, TVec4}; /// Rotate the vector `v` by the quaternion `q` assumed to be normalized. pub fn quat_cross_vec(q: &Qua, v: &TVec3) -> TVec3 { diff --git a/nalgebra-glm/src/gtx/rotate_normalized_axis.rs b/nalgebra-glm/src/gtx/rotate_normalized_axis.rs index a5788e94f..4c5acf452 100644 --- a/nalgebra-glm/src/gtx/rotate_normalized_axis.rs +++ b/nalgebra-glm/src/gtx/rotate_normalized_axis.rs @@ -1,7 +1,7 @@ use na::{Rotation3, Unit, UnitQuaternion}; -use crate::aliases::{Qua, TMat4, TVec3}; use crate::RealNumber; +use crate::aliases::{Qua, TMat4, TVec3}; /// Builds a rotation 4 * 4 matrix created from a normalized axis and an angle. /// diff --git a/nalgebra-glm/src/gtx/rotate_vector.rs b/nalgebra-glm/src/gtx/rotate_vector.rs index 213adb559..6dc3b3515 100644 --- a/nalgebra-glm/src/gtx/rotate_vector.rs +++ b/nalgebra-glm/src/gtx/rotate_vector.rs @@ -1,7 +1,7 @@ use na::{Rotation3, Unit, UnitComplex}; -use crate::aliases::{TMat4, TVec2, TVec3, TVec4}; use crate::RealNumber; +use crate::aliases::{TMat4, TVec2, TVec3, TVec4}; /// Build the rotation matrix needed to align `normal` and `up`. pub fn orientation(normal: &TVec3, up: &TVec3) -> TMat4 { diff --git a/nalgebra-glm/src/gtx/transform2.rs b/nalgebra-glm/src/gtx/transform2.rs index 56f736d72..be8878bf5 100644 --- a/nalgebra-glm/src/gtx/transform2.rs +++ b/nalgebra-glm/src/gtx/transform2.rs @@ -1,6 +1,6 @@ +use crate::RealNumber; use crate::aliases::{TMat3, TMat4, TVec2, TVec3}; use crate::traits::Number; -use crate::RealNumber; /// Build planar projection matrix along normal axis and right-multiply it to `m`. pub fn proj2d(m: &TMat3, normal: &TVec2) -> TMat3 { diff --git a/nalgebra-glm/src/lib.rs b/nalgebra-glm/src/lib.rs index 026488a68..48b407ec1 100644 --- a/nalgebra-glm/src/lib.rs +++ b/nalgebra-glm/src/lib.rs @@ -115,7 +115,7 @@ unused, missing_docs, rust_2018_idioms, - rust_2018_compatibility, + rust_2024_compatibility, future_incompatible, missing_copy_implementations, missing_debug_implementations @@ -191,17 +191,17 @@ pub use gtx::{ proj2d, quat_cross_vec, quat_extract_real_component, quat_fast_mix, quat_identity, quat_inv_cross_vec, quat_length2, quat_magnitude2, quat_rotate_normalized_axis, quat_rotate_vec, quat_rotate_vec3, quat_rotation, quat_short_mix, quat_to_mat3, quat_to_mat4, - reflect, reflect2d, right_handed, rotate2d, rotate_normalized_axis, rotate_vec2, rotate_vec3, + reflect, reflect2d, right_handed, rotate_normalized_axis, rotate_vec2, rotate_vec3, rotate_vec4, rotate_x_vec3, rotate_x_vec4, rotate_y_vec3, rotate_y_vec4, rotate_z_vec3, - rotate_z_vec4, rotation, rotation2d, scale2d, scale_bias, scale_bias_matrix, scaling, - scaling2d, shear2d_x, shear2d_y, shear_x, shear_y, shear_z, slerp, to_quat, translate2d, + rotate_z_vec4, rotate2d, rotation, rotation2d, scale_bias, scale_bias_matrix, scale2d, scaling, + scaling2d, shear_x, shear_y, shear_z, shear2d_x, shear2d_y, slerp, to_quat, translate2d, translation, translation2d, triangle_normal, }; +pub use na::{DefaultAllocator, Scalar, U1, U2, U3, U4}; pub use na::{ convert, convert_ref, convert_ref_unchecked, convert_unchecked, try_convert, try_convert_ref, }; -pub use na::{DefaultAllocator, Scalar, U1, U2, U3, U4}; mod aliases; mod common; diff --git a/nalgebra-glm/src/traits.rs b/nalgebra-glm/src/traits.rs index 5e342c09f..62aaefbaa 100644 --- a/nalgebra-glm/src/traits.rs +++ b/nalgebra-glm/src/traits.rs @@ -19,16 +19,16 @@ pub trait Number: } impl< - T: Scalar - + Copy - + PartialOrd - + ClosedAddAssign - + ClosedSubAssign - + ClosedMulAssign - + AbsDiffEq - + Signed - + Bounded, - > Number for T + T: Scalar + + Copy + + PartialOrd + + ClosedAddAssign + + ClosedSubAssign + + ClosedMulAssign + + AbsDiffEq + + Signed + + Bounded, +> Number for T { } diff --git a/nalgebra-glm/src/trigonometric.rs b/nalgebra-glm/src/trigonometric.rs index 597b037e4..d2af5100a 100644 --- a/nalgebra-glm/src/trigonometric.rs +++ b/nalgebra-glm/src/trigonometric.rs @@ -1,5 +1,5 @@ -use crate::aliases::TVec; use crate::RealNumber; +use crate::aliases::TVec; /// Component-wise arc-cosinus. pub fn acos(x: &TVec) -> TVec { diff --git a/nalgebra-lapack/Cargo.toml b/nalgebra-lapack/Cargo.toml index 48bcd96a1..170150265 100644 --- a/nalgebra-lapack/Cargo.toml +++ b/nalgebra-lapack/Cargo.toml @@ -11,7 +11,7 @@ readme = "../README.md" categories = ["science", "mathematics"] keywords = ["linear", "algebra", "matrix", "vector", "lapack"] license = "MIT" -edition = "2018" +edition = "2024" [badges] maintenance = { status = "actively-developed" } diff --git a/nalgebra-lapack/src/eigen.rs b/nalgebra-lapack/src/eigen.rs index 6ccf8804e..b116efbd0 100644 --- a/nalgebra-lapack/src/eigen.rs +++ b/nalgebra-lapack/src/eigen.rs @@ -8,7 +8,7 @@ use simba::scalar::RealField; use crate::ComplexHelper; use na::dimension::{Const, Dim}; -use na::{allocator::Allocator, DefaultAllocator, Matrix, OMatrix, OVector, Scalar}; +use na::{DefaultAllocator, Matrix, OMatrix, OVector, Scalar, allocator::Allocator}; use lapack; @@ -237,10 +237,10 @@ where false => { let (number_of_elements, _) = self.eigenvalues_re.shape_generic(); let number_of_elements_value = number_of_elements.value(); - let number_of_complex_entries = - self.eigenvalues_im - .iter() - .fold(0, |acc, e| if !e.is_zero() { acc + 1 } else { acc }); + let number_of_complex_entries = self + .eigenvalues_im + .iter() + .fold(0, |acc, e| if !e.is_zero() { acc + 1 } else { acc }); let mut eigenvalues = Vec::>::with_capacity(number_of_complex_entries); let mut eigenvectors = match self.eigenvectors.is_some() { true => Some(Vec::, D>>::with_capacity( diff --git a/nalgebra-lapack/src/generalized_eigenvalues.rs b/nalgebra-lapack/src/generalized_eigenvalues.rs index 33312868f..ac0c8543c 100644 --- a/nalgebra-lapack/src/generalized_eigenvalues.rs +++ b/nalgebra-lapack/src/generalized_eigenvalues.rs @@ -83,7 +83,7 @@ where ); assert!( - a.shape_generic() == b.shape_generic(), + a.shape_generic() == b.shape_generic(), "Unable to compute the generalized eigenvalues of two square matrices of different dimensions." ); diff --git a/nalgebra-lapack/src/lib.rs b/nalgebra-lapack/src/lib.rs index 502d24b03..d5a077314 100644 --- a/nalgebra-lapack/src/lib.rs +++ b/nalgebra-lapack/src/lib.rs @@ -98,7 +98,7 @@ pub use self::cholesky::{Cholesky, CholeskyScalar}; pub use self::eigen::Eigen; pub use self::generalized_eigenvalues::GeneralizedEigen; pub use self::hessenberg::Hessenberg; -pub use self::lu::{LUScalar, LU}; +pub use self::lu::{LU, LUScalar}; pub use self::qr::QR; pub use self::qz::QZ; pub use self::schur::Schur; diff --git a/nalgebra-lapack/src/qz.rs b/nalgebra-lapack/src/qz.rs index ec113e970..cb06f59de 100644 --- a/nalgebra-lapack/src/qz.rs +++ b/nalgebra-lapack/src/qz.rs @@ -81,7 +81,7 @@ where ); assert!( - a.shape_generic() == b.shape_generic(), + a.shape_generic() == b.shape_generic(), "Unable to compute the qz decomposition of two square matrices of different dimensions." ); diff --git a/nalgebra-lapack/src/symmetric_eigen.rs b/nalgebra-lapack/src/symmetric_eigen.rs index 6fda636ca..bb631ecc4 100644 --- a/nalgebra-lapack/src/symmetric_eigen.rs +++ b/nalgebra-lapack/src/symmetric_eigen.rs @@ -183,7 +183,7 @@ pub trait SymmetricEigenScalar: Scalar { ); #[allow(missing_docs)] fn xsyev_work_size(jobz: u8, uplo: u8, n: i32, a: &mut [Self], lda: i32, info: &mut i32) - -> i32; + -> i32; } macro_rules! real_eigensystem_scalar_impl ( diff --git a/nalgebra-macros/Cargo.toml b/nalgebra-macros/Cargo.toml index 4b74ba5b6..72f5cb536 100644 --- a/nalgebra-macros/Cargo.toml +++ b/nalgebra-macros/Cargo.toml @@ -2,7 +2,7 @@ name = "nalgebra-macros" version = "0.2.2" authors = ["Andreas Longva", "Sébastien Crozet "] -edition = "2018" +edition = "2024" description = "Procedural macros for nalgebra" documentation = "https://www.nalgebra.rs/docs" homepage = "https://nalgebra.rs" diff --git a/nalgebra-macros/src/lib.rs b/nalgebra-macros/src/lib.rs index e209ef687..6d96332eb 100644 --- a/nalgebra-macros/src/lib.rs +++ b/nalgebra-macros/src/lib.rs @@ -8,7 +8,7 @@ unused, missing_docs, rust_2018_idioms, - rust_2018_compatibility, + rust_2024_compatibility, future_incompatible, missing_copy_implementations, missing_debug_implementations, diff --git a/nalgebra-macros/src/matrix_vector_impl.rs b/nalgebra-macros/src/matrix_vector_impl.rs index d4357e88f..b68df28dd 100644 --- a/nalgebra-macros/src/matrix_vector_impl.rs +++ b/nalgebra-macros/src/matrix_vector_impl.rs @@ -1,11 +1,11 @@ use proc_macro::TokenStream; -use quote::{quote, ToTokens, TokenStreamExt}; +use quote::{ToTokens, TokenStreamExt, quote}; use std::ops::Index; +use syn::Expr; use syn::parse::{Error, Parse, ParseStream}; use syn::punctuated::Punctuated; use syn::spanned::Spanned; -use syn::Expr; -use syn::{parse_macro_input, Token}; +use syn::{Token, parse_macro_input}; use proc_macro2::{Delimiter, Spacing, TokenStream as TokenStream2, TokenTree}; use proc_macro2::{Group, Punct}; diff --git a/nalgebra-macros/src/stack_impl.rs b/nalgebra-macros/src/stack_impl.rs index c2c9a397d..480524b2d 100644 --- a/nalgebra-macros/src/stack_impl.rs +++ b/nalgebra-macros/src/stack_impl.rs @@ -180,8 +180,8 @@ fn is_literal_zero(expr: &Expr) -> bool { #[cfg(test)] mod tests { - use crate::stack_impl::stack_impl; use crate::Matrix; + use crate::stack_impl::stack_impl; use quote::quote; #[test] diff --git a/nalgebra-sparse/Cargo.toml b/nalgebra-sparse/Cargo.toml index fa305e88b..aa369ec33 100644 --- a/nalgebra-sparse/Cargo.toml +++ b/nalgebra-sparse/Cargo.toml @@ -2,7 +2,7 @@ name = "nalgebra-sparse" version = "0.10.0" authors = ["Andreas Longva", "Sébastien Crozet "] -edition = "2018" +edition = "2024" description = "Sparse matrix computation based on nalgebra." documentation = "https://www.nalgebra.rs/docs" homepage = "https://nalgebra.rs" diff --git a/nalgebra-sparse/src/coo/coo_serde.rs b/nalgebra-sparse/src/coo/coo_serde.rs index 7ffcdf4aa..461ba0d2c 100644 --- a/nalgebra-sparse/src/coo/coo_serde.rs +++ b/nalgebra-sparse/src/coo/coo_serde.rs @@ -1,5 +1,5 @@ use crate::coo::CooMatrix; -use serde::{de, Deserialize, Deserializer, Serialize, Serializer}; +use serde::{Deserialize, Deserializer, Serialize, Serializer, de}; /// This is an intermediate type for (de)serializing `CooMatrix`. /// diff --git a/nalgebra-sparse/src/cs.rs b/nalgebra-sparse/src/cs.rs index 30bdc9b89..ed7723bf0 100644 --- a/nalgebra-sparse/src/cs.rs +++ b/nalgebra-sparse/src/cs.rs @@ -471,7 +471,7 @@ impl UninitVec { /// /// Must be called exactly once per index, otherwise results in undefined behavior. pub unsafe fn set(&mut self, index: usize, value: T) { - self.vec.as_mut_ptr().add(index).write(value) + unsafe { self.vec.as_mut_ptr().add(index).write(value) } } /// Marks the vector data as initialized by returning a full vector. @@ -479,7 +479,9 @@ impl UninitVec { /// It is undefined behavior to call this function unless *all* elements have been written to /// exactly once. pub unsafe fn assume_init(mut self) -> Vec { - self.vec.set_len(self.len); + unsafe { + self.vec.set_len(self.len); + } self.vec } } diff --git a/nalgebra-sparse/src/csc/csc_serde.rs b/nalgebra-sparse/src/csc/csc_serde.rs index aab12d478..fe8348cf1 100644 --- a/nalgebra-sparse/src/csc/csc_serde.rs +++ b/nalgebra-sparse/src/csc/csc_serde.rs @@ -1,5 +1,5 @@ use crate::CscMatrix; -use serde::{de, Deserialize, Deserializer, Serialize, Serializer}; +use serde::{Deserialize, Deserializer, Serialize, Serializer, de}; /// This is an intermediate type for (de)serializing `CscMatrix`. /// diff --git a/nalgebra-sparse/src/csr/csr_serde.rs b/nalgebra-sparse/src/csr/csr_serde.rs index 1b33fda02..e88569462 100644 --- a/nalgebra-sparse/src/csr/csr_serde.rs +++ b/nalgebra-sparse/src/csr/csr_serde.rs @@ -1,5 +1,5 @@ use crate::CsrMatrix; -use serde::{de, Deserialize, Deserializer, Serialize, Serializer}; +use serde::{Deserialize, Deserializer, Serialize, Serializer, de}; /// This is an intermediate type for (de)serializing `CsrMatrix`. /// diff --git a/nalgebra-sparse/src/factorization/cholesky.rs b/nalgebra-sparse/src/factorization/cholesky.rs index 1c2cb1b11..18303a6cf 100644 --- a/nalgebra-sparse/src/factorization/cholesky.rs +++ b/nalgebra-sparse/src/factorization/cholesky.rs @@ -1,6 +1,6 @@ use crate::csc::CscMatrix; -use crate::ops::serial::spsolve_csc_lower_triangular; use crate::ops::Op; +use crate::ops::serial::spsolve_csc_lower_triangular; use crate::pattern::SparsityPattern; use core::{iter, mem}; use nalgebra::{DMatrix, DMatrixView, DMatrixViewMut, RealField}; diff --git a/nalgebra-sparse/src/io/matrix_market.rs b/nalgebra-sparse/src/io/matrix_market.rs index 975c586ed..17c8527dd 100644 --- a/nalgebra-sparse/src/io/matrix_market.rs +++ b/nalgebra-sparse/src/io/matrix_market.rs @@ -5,8 +5,8 @@ use crate::SparseFormatError; use crate::SparseFormatErrorKind; use crate::{CooMatrix, CscMatrix, CsrMatrix}; use nalgebra::Complex; -use pest::iterators::Pairs; use pest::Parser; +use pest::iterators::Pairs; use std::cmp::PartialEq; use std::convert::Infallible; use std::convert::TryFrom; @@ -1145,7 +1145,13 @@ fn parse_sparse_shape( // check for square matrix, when it's not a general matrix if *storagescheme != StorageScheme::General && r != c { - return Err(MatrixMarketError::from_kind_and_message(MatrixMarketErrorKind::NonSquare, format!("(Skew-)Symmetric or hermitian matrix should be square matrix, but it has dimension {} and {}", r, c))); + return Err(MatrixMarketError::from_kind_and_message( + MatrixMarketErrorKind::NonSquare, + format!( + "(Skew-)Symmetric or hermitian matrix should be square matrix, but it has dimension {} and {}", + r, c + ), + )); } Ok((r, c, nnz)) @@ -1170,7 +1176,13 @@ fn parse_dense_shape( // check for square matrix, when it's not a general matrix if *storagescheme != StorageScheme::General && r != c { - return Err(MatrixMarketError::from_kind_and_message(MatrixMarketErrorKind::NonSquare, format!("(Skew-)Symmetric or hermitian matrix should be square matrix, but it has dimension {} and {}", r, c))); + return Err(MatrixMarketError::from_kind_and_message( + MatrixMarketErrorKind::NonSquare, + format!( + "(Skew-)Symmetric or hermitian matrix should be square matrix, but it has dimension {} and {}", + r, c + ), + )); } let n: usize; diff --git a/nalgebra-sparse/src/io/mod.rs b/nalgebra-sparse/src/io/mod.rs index 1f4cb0816..e0aa9d41b 100644 --- a/nalgebra-sparse/src/io/mod.rs +++ b/nalgebra-sparse/src/io/mod.rs @@ -34,8 +34,8 @@ //! > "*The Matrix Market Exchange Formats: Initial Design.*" (1996). pub use self::matrix_market::{ + MatrixMarketError, MatrixMarketErrorKind, MatrixMarketExport, MatrixMarketScalar, load_coo_from_matrix_market_file, load_coo_from_matrix_market_str, save_to_matrix_market, - save_to_matrix_market_file, save_to_matrix_market_str, MatrixMarketError, - MatrixMarketErrorKind, MatrixMarketExport, MatrixMarketScalar, + save_to_matrix_market_file, save_to_matrix_market_str, }; mod matrix_market; diff --git a/nalgebra-sparse/src/lib.rs b/nalgebra-sparse/src/lib.rs index 4fd9fe491..5bf757efb 100644 --- a/nalgebra-sparse/src/lib.rs +++ b/nalgebra-sparse/src/lib.rs @@ -137,7 +137,7 @@ unused, missing_docs, rust_2018_idioms, - rust_2018_compatibility, + rust_2024_compatibility, future_incompatible, missing_copy_implementations )] diff --git a/nalgebra-sparse/src/ops/impl_std_ops.rs b/nalgebra-sparse/src/ops/impl_std_ops.rs index 9f01e15d3..c93572c29 100644 --- a/nalgebra-sparse/src/ops/impl_std_ops.rs +++ b/nalgebra-sparse/src/ops/impl_std_ops.rs @@ -1,11 +1,11 @@ use crate::csc::CscMatrix; use crate::csr::CsrMatrix; +use crate::ops::Op; use crate::ops::serial::{ spadd_csc_prealloc, spadd_csr_prealloc, spadd_pattern, spmm_csc_dense, spmm_csc_pattern, spmm_csc_prealloc_unchecked, spmm_csr_dense, spmm_csr_pattern, spmm_csr_prealloc_unchecked, }; -use crate::ops::Op; use nalgebra::allocator::Allocator; use nalgebra::base::storage::RawStorage; use nalgebra::constraint::{DimEq, ShapeConstraint}; diff --git a/nalgebra-sparse/src/ops/serial/cs.rs b/nalgebra-sparse/src/ops/serial/cs.rs index ec2690358..76e5e4e42 100644 --- a/nalgebra-sparse/src/ops/serial/cs.rs +++ b/nalgebra-sparse/src/ops/serial/cs.rs @@ -1,7 +1,7 @@ +use crate::SparseEntryMut; use crate::cs::CsMatrix; -use crate::ops::serial::{OperationError, OperationErrorKind}; use crate::ops::Op; -use crate::SparseEntryMut; +use crate::ops::serial::{OperationError, OperationErrorKind}; use nalgebra::{ClosedAddAssign, ClosedMulAssign, DMatrixView, DMatrixViewMut, Scalar}; use num_traits::{One, Zero}; diff --git a/nalgebra-sparse/src/ops/serial/csc.rs b/nalgebra-sparse/src/ops/serial/csc.rs index a7a9104c5..950bae60b 100644 --- a/nalgebra-sparse/src/ops/serial/csc.rs +++ b/nalgebra-sparse/src/ops/serial/csc.rs @@ -1,9 +1,9 @@ use crate::csc::CscMatrix; +use crate::ops::Op; use crate::ops::serial::cs::{ spadd_cs_prealloc, spmm_cs_dense, spmm_cs_prealloc, spmm_cs_prealloc_unchecked, }; use crate::ops::serial::{OperationError, OperationErrorKind}; -use crate::ops::Op; use nalgebra::{ClosedAddAssign, ClosedMulAssign, DMatrixView, DMatrixViewMut, RealField, Scalar}; use num_traits::{One, Zero}; diff --git a/nalgebra-sparse/src/ops/serial/csr.rs b/nalgebra-sparse/src/ops/serial/csr.rs index 48b006571..b10bf923e 100644 --- a/nalgebra-sparse/src/ops/serial/csr.rs +++ b/nalgebra-sparse/src/ops/serial/csr.rs @@ -1,9 +1,9 @@ use crate::csr::CsrMatrix; +use crate::ops::Op; +use crate::ops::serial::OperationError; use crate::ops::serial::cs::{ spadd_cs_prealloc, spmm_cs_dense, spmm_cs_prealloc, spmm_cs_prealloc_unchecked, }; -use crate::ops::serial::OperationError; -use crate::ops::Op; use nalgebra::{ClosedAddAssign, ClosedMulAssign, DMatrixView, DMatrixViewMut, Scalar}; use num_traits::{One, Zero}; use std::borrow::Cow; diff --git a/nalgebra-sparse/src/ops/serial/mod.rs b/nalgebra-sparse/src/ops/serial/mod.rs index d8f1a343d..42f1b42ae 100644 --- a/nalgebra-sparse/src/ops/serial/mod.rs +++ b/nalgebra-sparse/src/ops/serial/mod.rs @@ -12,22 +12,22 @@ macro_rules! assert_compatible_spmm_dims { ($c:expr, $a:expr, $b:expr) => {{ use crate::ops::Op::{NoOp, Transpose}; match (&$a, &$b) { - (NoOp(ref a), NoOp(ref b)) => { + (&NoOp(ref a), &NoOp(ref b)) => { assert_eq!($c.nrows(), a.nrows(), "C.nrows() != A.nrows()"); assert_eq!($c.ncols(), b.ncols(), "C.ncols() != B.ncols()"); assert_eq!(a.ncols(), b.nrows(), "A.ncols() != B.nrows()"); } - (Transpose(ref a), NoOp(ref b)) => { + (&Transpose(ref a), &NoOp(ref b)) => { assert_eq!($c.nrows(), a.ncols(), "C.nrows() != A.ncols()"); assert_eq!($c.ncols(), b.ncols(), "C.ncols() != B.ncols()"); assert_eq!(a.nrows(), b.nrows(), "A.nrows() != B.nrows()"); } - (NoOp(ref a), Transpose(ref b)) => { + (&NoOp(ref a), &Transpose(ref b)) => { assert_eq!($c.nrows(), a.nrows(), "C.nrows() != A.nrows()"); assert_eq!($c.ncols(), b.nrows(), "C.ncols() != B.nrows()"); assert_eq!(a.ncols(), b.ncols(), "A.ncols() != B.ncols()"); } - (Transpose(ref a), Transpose(ref b)) => { + (&Transpose(ref a), &Transpose(ref b)) => { assert_eq!($c.nrows(), a.ncols(), "C.nrows() != A.ncols()"); assert_eq!($c.ncols(), b.nrows(), "C.ncols() != B.nrows()"); assert_eq!(a.nrows(), b.ncols(), "A.nrows() != B.ncols()"); diff --git a/nalgebra-sparse/src/pattern.rs b/nalgebra-sparse/src/pattern.rs index 803e7f2dd..50950b621 100644 --- a/nalgebra-sparse/src/pattern.rs +++ b/nalgebra-sparse/src/pattern.rs @@ -3,8 +3,8 @@ #[cfg(feature = "serde-serialize")] mod pattern_serde; -use crate::cs::transpose_cs; use crate::SparseFormatError; +use crate::cs::transpose_cs; use std::error::Error; use std::fmt; diff --git a/nalgebra-sparse/src/pattern/pattern_serde.rs b/nalgebra-sparse/src/pattern/pattern_serde.rs index e11a550a2..6f7fe61da 100644 --- a/nalgebra-sparse/src/pattern/pattern_serde.rs +++ b/nalgebra-sparse/src/pattern/pattern_serde.rs @@ -1,5 +1,5 @@ use crate::pattern::SparsityPattern; -use serde::{de, Deserialize, Deserializer, Serialize, Serializer}; +use serde::{Deserialize, Deserializer, Serialize, Serializer, de}; /// This is an intermediate type for (de)serializing `SparsityPattern`. /// diff --git a/nalgebra-sparse/tests/unit_tests/convert_serial.rs b/nalgebra-sparse/tests/unit_tests/convert_serial.rs index b895c9455..38a3216a5 100644 --- a/nalgebra-sparse/tests/unit_tests/convert_serial.rs +++ b/nalgebra-sparse/tests/unit_tests/convert_serial.rs @@ -1,6 +1,6 @@ use crate::common::csc_strategy; -use nalgebra::proptest::matrix; use nalgebra::DMatrix; +use nalgebra::proptest::matrix; use nalgebra_sparse::convert::serial::{ convert_coo_csc, convert_coo_csr, convert_coo_dense, convert_csc_coo, convert_csc_csr, convert_csc_dense, convert_csr_coo, convert_csr_csc, convert_csr_dense, convert_dense_coo, diff --git a/nalgebra-sparse/tests/unit_tests/coo.rs b/nalgebra-sparse/tests/unit_tests/coo.rs index 1dacc7c2a..89b2d26ed 100644 --- a/nalgebra-sparse/tests/unit_tests/coo.rs +++ b/nalgebra-sparse/tests/unit_tests/coo.rs @@ -1,7 +1,7 @@ use crate::assert_panics; use nalgebra::DMatrix; -use nalgebra_sparse::coo::CooMatrix; use nalgebra_sparse::SparseFormatErrorKind; +use nalgebra_sparse::coo::CooMatrix; #[test] fn coo_construction_for_valid_data() { @@ -201,12 +201,14 @@ fn coo_try_from_triplets_iter() { 5, vec![(0, 6, 3.0)].into_iter(), )); - assert!(CooMatrix::::try_from_triplets_iter( - 3, - 5, - vec![(0, 3, 3.0), (1, 2, 2.0), (0, 3, 1.0),].into_iter(), - ) - .is_ok()); + assert!( + CooMatrix::::try_from_triplets_iter( + 3, + 5, + vec![(0, 3, 3.0), (1, 2, 2.0), (0, 3, 1.0),].into_iter(), + ) + .is_ok() + ); } #[test] diff --git a/nalgebra-sparse/tests/unit_tests/matrix_market.rs b/nalgebra-sparse/tests/unit_tests/matrix_market.rs index 44e276447..f4c1486c8 100644 --- a/nalgebra-sparse/tests/unit_tests/matrix_market.rs +++ b/nalgebra-sparse/tests/unit_tests/matrix_market.rs @@ -1,12 +1,12 @@ use matrixcompare::assert_matrix_eq; -use nalgebra::matrix; use nalgebra::Complex; +use nalgebra::matrix; +use nalgebra_sparse::CooMatrix; use nalgebra_sparse::io::{ load_coo_from_matrix_market_file, load_coo_from_matrix_market_str, save_to_matrix_market_file, save_to_matrix_market_str, }; use nalgebra_sparse::proptest::coo_no_duplicates; -use nalgebra_sparse::CooMatrix; use proptest::prelude::*; use tempfile::tempdir; diff --git a/nalgebra-sparse/tests/unit_tests/ops.rs b/nalgebra-sparse/tests/unit_tests/ops.rs index c8d80f326..8f0a8c10e 100644 --- a/nalgebra-sparse/tests/unit_tests/ops.rs +++ b/nalgebra-sparse/tests/unit_tests/ops.rs @@ -1,15 +1,15 @@ use crate::common::{ - csc_strategy, csr_strategy, non_zero_i32_value_strategy, value_strategy, - PROPTEST_I32_VALUE_STRATEGY, PROPTEST_MATRIX_DIM, PROPTEST_MAX_NNZ, + PROPTEST_I32_VALUE_STRATEGY, PROPTEST_MATRIX_DIM, PROPTEST_MAX_NNZ, csc_strategy, csr_strategy, + non_zero_i32_value_strategy, value_strategy, }; use nalgebra_sparse::csc::CscMatrix; use nalgebra_sparse::csr::CsrMatrix; +use nalgebra_sparse::ops::Op; use nalgebra_sparse::ops::serial::{ spadd_csc_prealloc, spadd_csr_prealloc, spadd_pattern, spmm_csc_dense, spmm_csc_prealloc, spmm_csc_prealloc_unchecked, spmm_csr_dense, spmm_csr_pattern, spmm_csr_prealloc, spmm_csr_prealloc_unchecked, spsolve_csc_lower_triangular, }; -use nalgebra_sparse::ops::Op; use nalgebra_sparse::pattern::SparsityPattern; use nalgebra_sparse::proptest::{csc, csr, sparsity_pattern}; @@ -378,22 +378,22 @@ proptest! { ) { // We refer to `A * B` as the "product" let product_rows = match &a { - Op::NoOp(ref a) => a.nrows(), - Op::Transpose(ref a) => a.ncols(), + Op::NoOp(a) => a.nrows(), + Op::Transpose(a) => a.ncols(), }; let product_cols = match &b { - Op::NoOp(ref b) => b.ncols(), - Op::Transpose(ref b) => b.nrows(), + Op::NoOp(b) => b.ncols(), + Op::Transpose(b) => b.nrows(), }; // Determine the common dimension in the product // from the perspective of a and b, respectively let product_a_common = match &a { - Op::NoOp(ref a) => a.ncols(), - Op::Transpose(ref a) => a.nrows(), + Op::NoOp(a) => a.ncols(), + Op::Transpose(a) => a.nrows(), }; let product_b_common = match &b { - Op::NoOp(ref b) => b.nrows(), - Op::Transpose(ref b) => b.ncols() + Op::NoOp(b) => b.nrows(), + Op::Transpose(b) => b.ncols() }; let dims_are_compatible = product_rows == c.nrows() @@ -601,22 +601,22 @@ proptest! { ) { // We refer to `A * B` as the "product" let product_rows = match &a { - Op::NoOp(ref a) => a.nrows(), - Op::Transpose(ref a) => a.ncols(), + Op::NoOp(a) => a.nrows(), + Op::Transpose(a) => a.ncols(), }; let product_cols = match &b { - Op::NoOp(ref b) => b.ncols(), - Op::Transpose(ref b) => b.nrows(), + Op::NoOp(b) => b.ncols(), + Op::Transpose(b) => b.nrows(), }; // Determine the common dimension in the product // from the perspective of a and b, respectively let product_a_common = match &a { - Op::NoOp(ref a) => a.ncols(), - Op::Transpose(ref a) => a.nrows(), + Op::NoOp(a) => a.ncols(), + Op::Transpose(a) => a.nrows(), }; let product_b_common = match &b { - Op::NoOp(ref b) => b.nrows(), - Op::Transpose(ref b) => b.ncols(), + Op::NoOp(b) => b.nrows(), + Op::Transpose(b) => b.ncols(), }; let dims_are_compatible = product_rows == c.nrows() @@ -763,22 +763,22 @@ proptest! { ) { // We refer to `A * B` as the "product" let product_rows = match &a { - Op::NoOp(ref a) => a.nrows(), - Op::Transpose(ref a) => a.ncols(), + Op::NoOp(a) => a.nrows(), + Op::Transpose(a) => a.ncols(), }; let product_cols = match &b { - Op::NoOp(ref b) => b.ncols(), - Op::Transpose(ref b) => b.nrows(), + Op::NoOp(b) => b.ncols(), + Op::Transpose(b) => b.nrows(), }; // Determine the common dimension in the product // from the perspective of a and b, respectively let product_a_common = match &a { - Op::NoOp(ref a) => a.ncols(), - Op::Transpose(ref a) => a.nrows(), + Op::NoOp(a) => a.ncols(), + Op::Transpose(a) => a.nrows(), }; let product_b_common = match &b { - Op::NoOp(ref b) => b.nrows(), - Op::Transpose(ref b) => b.ncols(), + Op::NoOp(b) => b.nrows(), + Op::Transpose(b) => b.ncols(), }; let dims_are_compatible = product_rows == c.nrows() @@ -867,22 +867,22 @@ proptest! { ) { // We refer to `A * B` as the "product" let product_rows = match &a { - Op::NoOp(ref a) => a.nrows(), - Op::Transpose(ref a) => a.ncols(), + Op::NoOp(a) => a.nrows(), + Op::Transpose(a) => a.ncols(), }; let product_cols = match &b { - Op::NoOp(ref b) => b.ncols(), - Op::Transpose(ref b) => b.nrows(), + Op::NoOp(b) => b.ncols(), + Op::Transpose(b) => b.nrows(), }; // Determine the common dimension in the product // from the perspective of a and b, respectively let product_a_common = match &a { - Op::NoOp(ref a) => a.ncols(), - Op::Transpose(ref a) => a.nrows(), + Op::NoOp(a) => a.ncols(), + Op::Transpose(a) => a.nrows(), }; let product_b_common = match &b { - Op::NoOp(ref b) => b.nrows(), - Op::Transpose(ref b) => b.ncols() + Op::NoOp(b) => b.nrows(), + Op::Transpose(b) => b.ncols() }; let dims_are_compatible = product_rows == c.nrows() diff --git a/rustfmt.toml b/rustfmt.toml index 91b5446c2..f46a9b745 100644 --- a/rustfmt.toml +++ b/rustfmt.toml @@ -1,3 +1,3 @@ -edition = "2018" +edition = "2024" use_try_shorthand = true use_field_init_shorthand = true diff --git a/src/base/allocator.rs b/src/base/allocator.rs index 07304b2d3..6f58b21dc 100644 --- a/src/base/allocator.rs +++ b/src/base/allocator.rs @@ -2,11 +2,11 @@ use std::any::Any; +use crate::StorageMut; use crate::base::constraint::{SameNumberOfColumns, SameNumberOfRows, ShapeConstraint}; use crate::base::dimension::{Dim, U1}; use crate::base::{DefaultAllocator, Scalar}; use crate::storage::{IsContiguous, RawStorageMut}; -use crate::StorageMut; use std::fmt::Debug; use std::mem::MaybeUninit; diff --git a/src/base/array_storage.rs b/src/base/array_storage.rs index 15405a6a2..fcc3487ec 100644 --- a/src/base/array_storage.rs +++ b/src/base/array_storage.rs @@ -1,3 +1,6 @@ +// Needed otherwise the rkyv macros generate code incompatible with rust-2024 +#![cfg_attr(feature = "rkyv-serialize", allow(unsafe_op_in_unsafe_fn))] + use std::fmt::{self, Debug, Formatter}; // use std::hash::{Hash, Hasher}; use std::ops::Mul; @@ -14,12 +17,12 @@ use std::marker::PhantomData; #[cfg(feature = "rkyv-serialize")] use rkyv::bytecheck; +use crate::Storage; +use crate::base::Scalar; use crate::base::allocator::Allocator; use crate::base::default_allocator::DefaultAllocator; use crate::base::dimension::{Const, ToTypenum}; use crate::base::storage::{IsContiguous, Owned, RawStorage, RawStorageMut, ReshapableStorage}; -use crate::base::Scalar; -use crate::Storage; use std::mem; /* @@ -106,7 +109,7 @@ unsafe impl RawStorage, Const> #[inline] unsafe fn as_slice_unchecked(&self) -> &[T] { - std::slice::from_raw_parts(self.ptr(), R * C) + unsafe { std::slice::from_raw_parts(self.ptr(), R * C) } } } @@ -148,7 +151,7 @@ unsafe impl RawStorageMut, Const< #[inline] unsafe fn as_mut_slice_unchecked(&mut self) -> &mut [T] { - std::slice::from_raw_parts_mut(self.ptr_mut(), R * C) + unsafe { std::slice::from_raw_parts_mut(self.ptr_mut(), R * C) } } } @@ -164,12 +167,12 @@ where Const: ToTypenum, as ToTypenum>::Typenum: Mul< as ToTypenum>::Typenum>, as ToTypenum>::Typenum: Mul< - as ToTypenum>::Typenum, - Output = typenum::Prod< - as ToTypenum>::Typenum, - as ToTypenum>::Typenum, + as ToTypenum>::Typenum, + Output = typenum::Prod< + as ToTypenum>::Typenum, + as ToTypenum>::Typenum, + >, >, - >, { type Output = ArrayStorage; diff --git a/src/base/blas_uninit.rs b/src/base/blas_uninit.rs index 173dff87b..8f05dd193 100644 --- a/src/base/blas_uninit.rs +++ b/src/base/blas_uninit.rs @@ -43,10 +43,12 @@ unsafe fn array_axcpy( Status: InitStatus, T: Scalar + Zero + ClosedAddAssign + ClosedMulAssign, { - for i in 0..len { - let y = Status::assume_init_mut(y.get_unchecked_mut(i * stride1)); - *y = - a.clone() * x.get_unchecked(i * stride2).clone() * c.clone() + beta.clone() * y.clone(); + unsafe { + for i in 0..len { + let y = Status::assume_init_mut(y.get_unchecked_mut(i * stride1)); + *y = a.clone() * x.get_unchecked(i * stride2).clone() * c.clone() + + beta.clone() * y.clone(); + } } } @@ -95,20 +97,22 @@ pub unsafe fn axcpy_uninit( ShapeConstraint: DimEq, Status: InitStatus, { - assert_eq!(y.nrows(), x.nrows(), "Axcpy: mismatched vector shapes."); + unsafe { + assert_eq!(y.nrows(), x.nrows(), "Axcpy: mismatched vector shapes."); - let rstride1 = y.strides().0; - let rstride2 = x.strides().0; + let rstride1 = y.strides().0; + let rstride2 = x.strides().0; - // SAFETY: the conversion to slices is OK because we access the - // elements taking the strides into account. - let y = y.data.as_mut_slice_unchecked(); - let x = x.data.as_slice_unchecked(); + // SAFETY: the conversion to slices is OK because we access the + // elements taking the strides into account. + let y = y.data.as_mut_slice_unchecked(); + let x = x.data.as_slice_unchecked(); - if !b.is_zero() { - array_axcpy(status, y, a, x, c, b, rstride1, rstride2, x.len()); - } else { - array_axc(status, y, a, x, c, rstride1, rstride2, x.len()); + if !b.is_zero() { + array_axcpy(status, y, a, x, c, b, rstride1, rstride2, x.len()); + } else { + array_axc(status, y, a, x, c, rstride1, rstride2, x.len()); + } } } @@ -135,38 +139,40 @@ pub unsafe fn gemv_uninit, ShapeConstraint: DimEq + AreMultipliable, { - let dim1 = y.nrows(); - let (nrows2, ncols2) = a.shape(); - let dim3 = x.nrows(); + unsafe { + let dim1 = y.nrows(); + let (nrows2, ncols2) = a.shape(); + let dim3 = x.nrows(); - assert!( - ncols2 == dim3 && dim1 == nrows2, - "Gemv: dimensions mismatch." - ); + assert!( + ncols2 == dim3 && dim1 == nrows2, + "Gemv: dimensions mismatch." + ); - if ncols2 == 0 { - if beta.is_zero() { - y.apply(|e| Status::init(e, T::zero())); - } else { - // SAFETY: this is UB if y is uninitialized. - y.apply(|e| *Status::assume_init_mut(e) *= beta.clone()); + if ncols2 == 0 { + if beta.is_zero() { + y.apply(|e| Status::init(e, T::zero())); + } else { + // SAFETY: this is UB if y is uninitialized. + y.apply(|e| *Status::assume_init_mut(e) *= beta.clone()); + } + return; } - return; - } - // TODO: avoid bound checks. - let col2 = a.column(0); - let val = x.vget_unchecked(0).clone(); + // TODO: avoid bound checks. + let col2 = a.column(0); + let val = x.vget_unchecked(0).clone(); - // SAFETY: this is the call that makes this method unsafe: it is UB if Status = Uninit and beta != 0. - axcpy_uninit(status, y, alpha.clone(), &col2, val, beta); + // SAFETY: this is the call that makes this method unsafe: it is UB if Status = Uninit and beta != 0. + axcpy_uninit(status, y, alpha.clone(), &col2, val, beta); - for j in 1..ncols2 { - let col2 = a.column(j); - let val = x.vget_unchecked(j).clone(); + for j in 1..ncols2 { + let col2 = a.column(j); + let val = x.vget_unchecked(j).clone(); - // SAFETY: safe because y was initialized above. - axcpy_uninit(status, y, alpha.clone(), &col2, val, T::one()); + // SAFETY: safe because y was initialized above. + axcpy_uninit(status, y, alpha.clone(), &col2, val, T::one()); + } } } @@ -206,117 +212,122 @@ pub unsafe fn gemm_uninit< ShapeConstraint: SameNumberOfRows + SameNumberOfColumns + AreMultipliable, { - let ncols1 = y.ncols(); + unsafe { + let ncols1 = y.ncols(); - #[cfg(feature = "std")] - { - // We assume large matrices will be Dyn but small matrices static. - // We could use matrixmultiply for large statically-sized matrices but the performance - // threshold to activate it would be different from SMALL_DIM because our code optimizes - // better for statically-sized matrices. - if R1::is::() - || C1::is::() - || R2::is::() - || C2::is::() - || R3::is::() - || C3::is::() + #[cfg(feature = "std")] { - // matrixmultiply can be used only if the std feature is available. - let nrows1 = y.nrows(); - let (nrows2, ncols2) = a.shape(); - let (nrows3, ncols3) = b.shape(); + // We assume large matrices will be Dyn but small matrices static. + // We could use matrixmultiply for large statically-sized matrices but the performance + // threshold to activate it would be different from SMALL_DIM because our code optimizes + // better for statically-sized matrices. + if R1::is::() + || C1::is::() + || R2::is::() + || C2::is::() + || R3::is::() + || C3::is::() + { + // matrixmultiply can be used only if the std feature is available. + let nrows1 = y.nrows(); + let (nrows2, ncols2) = a.shape(); + let (nrows3, ncols3) = b.shape(); - // Threshold determined empirically. - const SMALL_DIM: usize = 5; + // Threshold determined empirically. + const SMALL_DIM: usize = 5; - if nrows1 > SMALL_DIM && ncols1 > SMALL_DIM && nrows2 > SMALL_DIM && ncols2 > SMALL_DIM - { - assert_eq!( - ncols2, nrows3, - "gemm: dimensions mismatch for multiplication." - ); - assert_eq!( - (nrows1, ncols1), - (nrows2, ncols3), - "gemm: dimensions mismatch for addition." - ); + if nrows1 > SMALL_DIM + && ncols1 > SMALL_DIM + && nrows2 > SMALL_DIM + && ncols2 > SMALL_DIM + { + assert_eq!( + ncols2, nrows3, + "gemm: dimensions mismatch for multiplication." + ); + assert_eq!( + (nrows1, ncols1), + (nrows2, ncols3), + "gemm: dimensions mismatch for addition." + ); - // NOTE: this case should never happen because we enter this - // codepath only when ncols2 > SMALL_DIM. Though we keep this - // here just in case if in the future we change the conditions to - // enter this codepath. - if ncols2 == 0 { - // NOTE: we can't just always multiply by beta - // because we documented the guaranty that `self` is - // never read if `beta` is zero. - if beta.is_zero() { - y.apply(|e| Status::init(e, T::zero())); - } else { - // SAFETY: this is UB if Status = Uninit - y.apply(|e| *Status::assume_init_mut(e) *= beta.clone()); + // NOTE: this case should never happen because we enter this + // codepath only when ncols2 > SMALL_DIM. Though we keep this + // here just in case if in the future we change the conditions to + // enter this codepath. + if ncols2 == 0 { + // NOTE: we can't just always multiply by beta + // because we documented the guaranty that `self` is + // never read if `beta` is zero. + if beta.is_zero() { + y.apply(|e| Status::init(e, T::zero())); + } else { + // SAFETY: this is UB if Status = Uninit + y.apply(|e| *Status::assume_init_mut(e) *= beta.clone()); + } + return; } - return; - } - if TypeId::of::() == TypeId::of::() { - let (rsa, csa) = a.strides(); - let (rsb, csb) = b.strides(); - let (rsc, csc) = y.strides(); + if TypeId::of::() == TypeId::of::() { + let (rsa, csa) = a.strides(); + let (rsb, csb) = b.strides(); + let (rsc, csc) = y.strides(); - matrixmultiply::sgemm( - nrows2, - ncols2, - ncols3, - mem::transmute_copy(&alpha), - a.data.ptr() as *const f32, - rsa as isize, - csa as isize, - b.data.ptr() as *const f32, - rsb as isize, - csb as isize, - mem::transmute_copy(&beta), - y.data.ptr_mut() as *mut f32, - rsc as isize, - csc as isize, - ); - return; - } else if TypeId::of::() == TypeId::of::() { - let (rsa, csa) = a.strides(); - let (rsb, csb) = b.strides(); - let (rsc, csc) = y.strides(); + matrixmultiply::sgemm( + nrows2, + ncols2, + ncols3, + mem::transmute_copy(&alpha), + a.data.ptr() as *const f32, + rsa as isize, + csa as isize, + b.data.ptr() as *const f32, + rsb as isize, + csb as isize, + mem::transmute_copy(&beta), + y.data.ptr_mut() as *mut f32, + rsc as isize, + csc as isize, + ); + return; + } else if TypeId::of::() == TypeId::of::() { + let (rsa, csa) = a.strides(); + let (rsb, csb) = b.strides(); + let (rsc, csc) = y.strides(); - matrixmultiply::dgemm( - nrows2, - ncols2, - ncols3, - mem::transmute_copy(&alpha), - a.data.ptr() as *const f64, - rsa as isize, - csa as isize, - b.data.ptr() as *const f64, - rsb as isize, - csb as isize, - mem::transmute_copy(&beta), - y.data.ptr_mut() as *mut f64, - rsc as isize, - csc as isize, - ); - return; + matrixmultiply::dgemm( + nrows2, + ncols2, + ncols3, + mem::transmute_copy(&alpha), + a.data.ptr() as *const f64, + rsa as isize, + csa as isize, + b.data.ptr() as *const f64, + rsb as isize, + csb as isize, + mem::transmute_copy(&beta), + y.data.ptr_mut() as *mut f64, + rsc as isize, + csc as isize, + ); + return; + } } } } - } - for j1 in 0..ncols1 { - // TODO: avoid bound checks. - // SAFETY: this is UB if Status = Uninit && beta != 0 - gemv_uninit( - status, - &mut y.column_mut(j1), - alpha.clone(), - a, - &b.column(j1), - beta.clone(), - ); + for j1 in 0..ncols1 { + // TODO: avoid bound checks. + // SAFETY: this is UB if Status = Uninit && beta != 0 + gemv_uninit( + status, + &mut y.column_mut(j1), + alpha.clone(), + a, + &b.column(j1), + beta.clone(), + ); + } } } diff --git a/src/base/cg.rs b/src/base/cg.rs index 650e4c1b3..790db61db 100644 --- a/src/base/cg.rs +++ b/src/base/cg.rs @@ -207,11 +207,8 @@ impl Matrix4 { } /// # Append/prepend translation and scaling -impl< - T: Scalar + Zero + One + ClosedMulAssign + ClosedAddAssign, - D: DimName, - S: Storage, - > SquareMatrix +impl> + SquareMatrix { /// Computes the transformation equal to `self` followed by an uniform scaling factor. #[inline] diff --git a/src/base/componentwise.rs b/src/base/componentwise.rs index 051bdb0a1..a99d517f0 100644 --- a/src/base/componentwise.rs +++ b/src/base/componentwise.rs @@ -6,12 +6,12 @@ use std::ops::{Add, Mul}; use simba::scalar::{ClosedDivAssign, ClosedMulAssign}; use simba::simd::SimdPartialOrd; +use crate::ClosedAddAssign; use crate::base::allocator::{Allocator, SameShapeAllocator}; use crate::base::constraint::{SameNumberOfColumns, SameNumberOfRows, ShapeConstraint}; use crate::base::dimension::Dim; use crate::base::storage::{Storage, StorageMut}; use crate::base::{DefaultAllocator, Matrix, MatrixSum, OMatrix, Scalar}; -use crate::ClosedAddAssign; /// The type of the result of a matrix component-wise operation. pub type MatrixComponentOp = MatrixSum; @@ -47,7 +47,7 @@ impl> Matrix { } macro_rules! component_binop_impl( - ($($binop: ident, $binop_mut: ident, $binop_assign: ident, $cmpy: ident, $Trait: ident . $op: ident . $op_assign: ident, $desc:expr, $desc_cmpy:expr, $desc_mut:expr);* $(;)*) => {$( + ($($binop: ident, $binop_mut: ident, $binop_assign: ident, $cmpy: ident, $Trait: ident . $op: ident . $op_assign: ident, $desc:expr_2021, $desc_cmpy:expr_2021, $desc_mut:expr_2021);* $(;)*) => {$( #[doc = $desc] #[inline] #[must_use] diff --git a/src/base/constraint.rs b/src/base/constraint.rs index 55a476849..fce48a17a 100644 --- a/src/base/constraint.rs +++ b/src/base/constraint.rs @@ -44,7 +44,7 @@ impl DimEq for ShapeConstraint { } macro_rules! equality_trait_decl( - ($($doc: expr, $Trait: ident),* $(,)*) => {$( + ($($doc: expr_2021, $Trait: ident),* $(,)*) => {$( // XXX: we can't do something like `DimEq for D2` because we would require a blanket impl… #[doc = $doc] pub trait $Trait: DimEq + DimEq { diff --git a/src/base/construction.rs b/src/base/construction.rs index 3e4496f0a..635060beb 100644 --- a/src/base/construction.rs +++ b/src/base/construction.rs @@ -9,22 +9,21 @@ use quickcheck::{Arbitrary, Gen}; use num::{Bounded, One, Zero}; #[cfg(feature = "rand-no-std")] use rand::{ - distr::{Distribution, StandardUniform}, Rng, + distr::{Distribution, StandardUniform}, }; -use std::iter; use typenum::{self, Cmp, Greater}; use simba::scalar::{ClosedAddAssign, ClosedMulAssign}; +use crate::UninitMatrix; use crate::base::allocator::Allocator; use crate::base::dimension::{Dim, DimName, Dyn, ToTypenum}; use crate::base::storage::RawStorage; use crate::base::{ ArrayStorage, Const, DefaultAllocator, Matrix, OMatrix, OVector, Scalar, Unit, Vector, }; -use crate::UninitMatrix; use std::mem::MaybeUninit; impl UninitMatrix @@ -56,7 +55,7 @@ where #[inline] pub fn from_element_generic(nrows: R, ncols: C, elem: T) -> Self { let len = nrows.value() * ncols.value(); - Self::from_iterator_generic(nrows, ncols, iter::repeat(elem).take(len)) + Self::from_iterator_generic(nrows, ncols, std::iter::repeat_n(elem, len)) } /// Creates a matrix with all its elements set to `elem`. @@ -65,7 +64,7 @@ where #[inline] pub fn repeat_generic(nrows: R, ncols: C, elem: T) -> Self { let len = nrows.value() * ncols.value(); - Self::from_iterator_generic(nrows, ncols, iter::repeat(elem).take(len)) + Self::from_iterator_generic(nrows, ncols, std::iter::repeat_n(elem, len)) } /// Creates a matrix with all its elements set to 0. @@ -382,7 +381,7 @@ where * */ macro_rules! impl_constructors( - ($($Dims: ty),*; $(=> $DimIdent: ident: $DimBound: ident),*; $($gargs: expr),*; $($args: ident),*) => { + ($($Dims: ty),*; $(=> $DimIdent: ident: $DimBound: ident),*; $($gargs: expr_2021),*; $($args: ident),*) => { /// Creates a matrix or vector with all its elements set to `elem`. /// /// # Example @@ -696,7 +695,7 @@ where * */ macro_rules! impl_constructors_from_data( - ($data: ident; $($Dims: ty),*; $(=> $DimIdent: ident: $DimBound: ident),*; $($gargs: expr),*; $($args: ident),*) => { + ($data: ident; $($Dims: ty),*; $(=> $DimIdent: ident: $DimBound: ident),*; $($gargs: expr_2021),*; $($args: ident),*) => { impl OMatrix where DefaultAllocator: Allocator<$($Dims),*> { /// Creates a matrix with its elements filled with the components provided by a slice @@ -939,7 +938,7 @@ macro_rules! transpose_array( ); macro_rules! componentwise_constructors_impl( - ($($R: expr, $C: expr, [$($($args: ident),*);*] $(;)*)*) => {$( + ($($R: expr_2021, $C: expr_2021, [$($($args: ident),*);*] $(;)*)*) => {$( impl Matrix, Const<$C>, ArrayStorage> { /// Initializes this matrix from its components. #[inline] diff --git a/src/base/construction_view.rs b/src/base/construction_view.rs index 21819e047..d96ebc6d1 100644 --- a/src/base/construction_view.rs +++ b/src/base/construction_view.rs @@ -22,12 +22,14 @@ impl<'a, T: Scalar, R: Dim, C: Dim, RStride: Dim, CStride: Dim> rstride: RStride, cstride: CStride, ) -> Self { - let data = ViewStorage::from_raw_parts( - data.as_ptr().add(start), - (nrows, ncols), - (rstride, cstride), - ); - Self::from_data(data) + unsafe { + let data = ViewStorage::from_raw_parts( + data.as_ptr().add(start), + (nrows, ncols), + (rstride, cstride), + ); + Self::from_data(data) + } } /// Creates a matrix view from an array and with dimensions and strides specified by generic types instances. @@ -70,9 +72,11 @@ impl<'a, T: Scalar, R: Dim, C: Dim> MatrixView<'a, T, R, C> { nrows: R, ncols: C, ) -> Self { - Self::from_slice_with_strides_generic_unchecked( - data, start, nrows, ncols, Const::<1>, nrows, - ) + unsafe { + Self::from_slice_with_strides_generic_unchecked( + data, start, nrows, ncols, Const::<1>, nrows, + ) + } } /// Creates a matrix view from an array and with dimensions and strides specified by generic types instances. @@ -86,7 +90,7 @@ impl<'a, T: Scalar, R: Dim, C: Dim> MatrixView<'a, T, R, C> { } macro_rules! impl_constructors( - ($($Dims: ty),*; $(=> $DimIdent: ident: $DimBound: ident),*; $($gargs: expr),*; $($args: ident),*) => { + ($($Dims: ty),*; $(=> $DimIdent: ident: $DimBound: ident),*; $($gargs: expr_2021),*; $($args: ident),*) => { impl<'a, T: Scalar, $($DimIdent: $DimBound),*> MatrixView<'a, T, $($Dims),*> { /// Creates a new matrix view from the given data array. /// @@ -100,9 +104,9 @@ macro_rules! impl_constructors( /// # Safety /// `data[start..start+rstride * cstride]` must be within bounds. #[inline] - pub unsafe fn from_slice_unchecked(data: &'a [T], start: usize, $($args: usize),*) -> Self { + pub unsafe fn from_slice_unchecked(data: &'a [T], start: usize, $($args: usize),*) -> Self { unsafe { Self::from_slice_generic_unchecked(data, start, $($gargs),*) - } + }} } impl<'a, T: Scalar, $($DimIdent: $DimBound, )*> MatrixView<'a, T, $($Dims,)* Dyn, Dyn> { @@ -121,9 +125,9 @@ macro_rules! impl_constructors( /// `start`, `rstride`, and `cstride`, with the given matrix size will not index /// outside of `data`. #[inline] - pub unsafe fn from_slice_with_strides_unchecked(data: &'a [T], start: usize, $($args: usize,)* rstride: usize, cstride: usize) -> Self { + pub unsafe fn from_slice_with_strides_unchecked(data: &'a [T], start: usize, $($args: usize,)* rstride: usize, cstride: usize) -> Self { unsafe { Self::from_slice_with_strides_generic_unchecked(data, start, $($gargs,)* Dyn(rstride), Dyn(cstride)) - } + }} } } ); @@ -167,12 +171,14 @@ impl<'a, T: Scalar, R: Dim, C: Dim, RStride: Dim, CStride: Dim> rstride: RStride, cstride: CStride, ) -> Self { - let data = ViewStorageMut::from_raw_parts( - data.as_mut_ptr().add(start), - (nrows, ncols), - (rstride, cstride), - ); - Self::from_data(data) + unsafe { + let data = ViewStorageMut::from_raw_parts( + data.as_mut_ptr().add(start), + (nrows, ncols), + (rstride, cstride), + ); + Self::from_data(data) + } } /// Creates a mutable matrix view from an array and with dimensions and strides specified by generic types instances. @@ -237,9 +243,11 @@ impl<'a, T: Scalar, R: Dim, C: Dim> MatrixViewMut<'a, T, R, C> { nrows: R, ncols: C, ) -> Self { - Self::from_slice_with_strides_generic_unchecked( - data, start, nrows, ncols, Const::<1>, nrows, - ) + unsafe { + Self::from_slice_with_strides_generic_unchecked( + data, start, nrows, ncols, Const::<1>, nrows, + ) + } } /// Creates a mutable matrix view from an array and with dimensions and strides specified by generic types instances. @@ -253,7 +261,7 @@ impl<'a, T: Scalar, R: Dim, C: Dim> MatrixViewMut<'a, T, R, C> { } macro_rules! impl_constructors_mut( - ($($Dims: ty),*; $(=> $DimIdent: ident: $DimBound: ident),*; $($gargs: expr),*; $($args: ident),*) => { + ($($Dims: ty),*; $(=> $DimIdent: ident: $DimBound: ident),*; $($gargs: expr_2021),*; $($args: ident),*) => { impl<'a, T: Scalar, $($DimIdent: $DimBound),*> MatrixViewMut<'a, T, $($Dims),*> { /// Creates a new mutable matrix view from the given data array. /// @@ -269,9 +277,9 @@ macro_rules! impl_constructors_mut( /// /// `data[start..start+(R * C)]` must be within bounds. #[inline] - pub unsafe fn from_slice_unchecked(data: &'a mut [T], start: usize, $($args: usize),*) -> Self { + pub unsafe fn from_slice_unchecked(data: &'a mut [T], start: usize, $($args: usize),*) -> Self { unsafe { Self::from_slice_generic_unchecked(data, start, $($gargs),*) - } + }} } impl<'a, T: Scalar, $($DimIdent: $DimBound, )*> MatrixViewMut<'a, T, $($Dims,)* Dyn, Dyn> { @@ -288,10 +296,10 @@ macro_rules! impl_constructors_mut( /// # Safety /// `data[start..start+rstride * cstride]` must be within bounds. #[inline] - pub unsafe fn from_slice_with_strides_unchecked(data: &'a mut [T], start: usize, $($args: usize,)* rstride: usize, cstride: usize) -> Self { + pub unsafe fn from_slice_with_strides_unchecked(data: &'a mut [T], start: usize, $($args: usize,)* rstride: usize, cstride: usize) -> Self { unsafe { Self::from_slice_with_strides_generic_unchecked( data, start, $($gargs,)* Dyn(rstride), Dyn(cstride)) - } + }} } } ); diff --git a/src/base/conversion.rs b/src/base/conversion.rs index b7bf533a8..98a439a2e 100644 --- a/src/base/conversion.rs +++ b/src/base/conversion.rs @@ -9,7 +9,7 @@ use simba::simd::{PrimitiveSimdValue, SimdValue}; use crate::base::allocator::{Allocator, SameShapeAllocator}; use crate::base::constraint::{SameNumberOfColumns, SameNumberOfRows, ShapeConstraint}; use crate::base::dimension::{ - Const, Dim, U1, U10, U11, U12, U13, U14, U15, U16, U2, U3, U4, U5, U6, U7, U8, U9, + Const, Dim, U1, U2, U3, U4, U5, U6, U7, U8, U9, U10, U11, U12, U13, U14, U15, U16, }; #[cfg(any(feature = "std", feature = "alloc"))] use crate::base::dimension::{DimName, Dyn}; @@ -187,7 +187,7 @@ where } macro_rules! impl_from_into_asref_1D( - ($(($NRows: ident, $NCols: ident) => $SZ: expr);* $(;)*) => {$( + ($(($NRows: ident, $NCols: ident) => $SZ: expr_2021);* $(;)*) => {$( impl AsRef<[T; $SZ]> for Matrix where T: Scalar, S: RawStorage + IsContiguous { @@ -265,7 +265,7 @@ macro_rules! impl_from_into_asref_borrow_2D( //does the impls on one case for either AsRef/AsMut and Borrow/BorrowMut ( - ($NRows: ty, $NCols: ty) => ($SZRows: expr, $SZCols: expr); + ($NRows: ty, $NCols: ty) => ($SZRows: expr_2021, $SZCols: expr_2021); $Ref:ident.$ref:ident(), $Mut:ident.$mut:ident() ) => { impl $Ref<[[T; $SZRows]; $SZCols]> for Matrix @@ -292,7 +292,7 @@ macro_rules! impl_from_into_asref_borrow_2D( }; //collects the mappings from typenum pairs to consts - ($(($NRows: ty, $NCols: ty) => ($SZRows: expr, $SZCols: expr));* $(;)*) => {$( + ($(($NRows: ty, $NCols: ty) => ($SZRows: expr_2021, $SZCols: expr_2021));* $(;)*) => {$( impl_from_into_asref_borrow_2D!( ($NRows, $NCols) => ($SZRows, $SZCols); AsRef.as_ref(), AsMut.as_mut() ); diff --git a/src/base/default_allocator.rs b/src/base/default_allocator.rs index 3b5d12811..3685dbb3d 100644 --- a/src/base/default_allocator.rs +++ b/src/base/default_allocator.rs @@ -10,6 +10,7 @@ use std::ptr; use alloc::vec::Vec; use super::Const; +use crate::base::Scalar; use crate::base::allocator::{Allocator, Reallocator}; use crate::base::array_storage::ArrayStorage; use crate::base::dimension::Dim; @@ -18,7 +19,6 @@ use crate::base::dimension::{DimName, Dyn}; use crate::base::storage::{RawStorage, RawStorageMut, Storage}; #[cfg(any(feature = "std", feature = "alloc"))] use crate::base::vec_storage::VecStorage; -use crate::base::Scalar; #[cfg(any(feature = "std", feature = "alloc"))] use std::mem::ManuallyDrop; use std::mem::MaybeUninit; @@ -49,12 +49,14 @@ impl Allocator, Const> for DefaultAl unsafe fn assume_init( uninit: ArrayStorage, R, C>, ) -> ArrayStorage { - // Safety: - // * The caller guarantees that all elements of the array are initialized - // * `MaybeUninit` and T are guaranteed to have the same layout - // * `MaybeUninit` does not drop, so there are no double-frees - // And thus the conversion is safe - ArrayStorage((&uninit as *const _ as *const [_; C]).read()) + unsafe { + // Safety: + // * The caller guarantees that all elements of the array are initialized + // * `MaybeUninit` and T are guaranteed to have the same layout + // * `MaybeUninit` does not drop, so there are no double-frees + // And thus the conversion is safe + ArrayStorage((&uninit as *const _ as *const [_; C]).read()) + } } #[inline] @@ -104,17 +106,19 @@ impl Allocator for DefaultAllocator { unsafe fn assume_init( uninit: VecStorage, Dyn, C>, ) -> VecStorage { - // Avoids a double-drop. - let (nrows, ncols) = uninit.shape(); - let vec: Vec<_> = uninit.into(); - let mut md = ManuallyDrop::new(vec); - - // Safety: - // - MaybeUninit has the same alignment and layout as T. - // - The length and capacity come from a valid vector. - let new_data = Vec::from_raw_parts(md.as_mut_ptr() as *mut _, md.len(), md.capacity()); - - VecStorage::new(nrows, ncols, new_data) + unsafe { + // Avoids a double-drop. + let (nrows, ncols) = uninit.shape(); + let vec: Vec<_> = uninit.into(); + let mut md = ManuallyDrop::new(vec); + + // Safety: + // - MaybeUninit has the same alignment and layout as T. + // - The length and capacity come from a valid vector. + let new_data = Vec::from_raw_parts(md.as_mut_ptr() as *mut _, md.len(), md.capacity()); + + VecStorage::new(nrows, ncols, new_data) + } } #[inline] @@ -125,8 +129,10 @@ impl Allocator for DefaultAllocator { ) -> Self::Buffer { let it = iter.into_iter(); let res: Vec = it.collect(); - assert!(res.len() == nrows.value() * ncols.value(), - "Allocation from iterator error: the iterator did not yield the correct number of elements."); + assert!( + res.len() == nrows.value() * ncols.value(), + "Allocation from iterator error: the iterator did not yield the correct number of elements." + ); VecStorage::new(nrows, ncols, res) } @@ -152,17 +158,19 @@ impl Allocator for DefaultAllocator { unsafe fn assume_init( uninit: VecStorage, R, Dyn>, ) -> VecStorage { - // Avoids a double-drop. - let (nrows, ncols) = uninit.shape(); - let vec: Vec<_> = uninit.into(); - let mut md = ManuallyDrop::new(vec); - - // Safety: - // - MaybeUninit has the same alignment and layout as T. - // - The length and capacity come from a valid vector. - let new_data = Vec::from_raw_parts(md.as_mut_ptr() as *mut _, md.len(), md.capacity()); - - VecStorage::new(nrows, ncols, new_data) + unsafe { + // Avoids a double-drop. + let (nrows, ncols) = uninit.shape(); + let vec: Vec<_> = uninit.into(); + let mut md = ManuallyDrop::new(vec); + + // Safety: + // - MaybeUninit has the same alignment and layout as T. + // - The length and capacity come from a valid vector. + let new_data = Vec::from_raw_parts(md.as_mut_ptr() as *mut _, md.len(), md.capacity()); + + VecStorage::new(nrows, ncols, new_data) + } } #[inline] @@ -173,8 +181,10 @@ impl Allocator for DefaultAllocator { ) -> Self::Buffer { let it = iter.into_iter(); let res: Vec = it.collect(); - assert!(res.len() == nrows.value() * ncols.value(), - "Allocation from iterator error: the iterator did not yield the correct number of elements."); + assert!( + res.len() == nrows.value() * ncols.value(), + "Allocation from iterator error: the iterator did not yield the correct number of elements." + ); VecStorage::new(nrows, ncols, res) } @@ -199,21 +209,23 @@ where cto: Const, buf: >::Buffer, ) -> ArrayStorage, RTO, CTO> { - let mut res = , Const>>::allocate_uninit(rto, cto); + unsafe { + let mut res = , Const>>::allocate_uninit(rto, cto); - let (rfrom, cfrom) = buf.shape(); + let (rfrom, cfrom) = buf.shape(); - let len_from = rfrom.value() * cfrom.value(); - let len_to = rto.value() * cto.value(); - let len_copied = cmp::min(len_from, len_to); - ptr::copy_nonoverlapping(buf.ptr(), res.ptr_mut() as *mut T, len_copied); + let len_from = rfrom.value() * cfrom.value(); + let len_to = rto.value() * cto.value(); + let len_copied = cmp::min(len_from, len_to); + ptr::copy_nonoverlapping(buf.ptr(), res.ptr_mut() as *mut T, len_copied); - // Safety: - // - We don’t care about dropping elements because the caller is responsible for dropping things. - // - We forget `buf` so that we don’t drop the other elements, but ensure the buffer itself is cleaned up. - buf.forget_elements(); + // Safety: + // - We don’t care about dropping elements because the caller is responsible for dropping things. + // - We forget `buf` so that we don’t drop the other elements, but ensure the buffer itself is cleaned up. + buf.forget_elements(); - res + res + } } } @@ -230,21 +242,23 @@ where cto: CTo, buf: ArrayStorage, ) -> VecStorage, Dyn, CTo> { - let mut res = >::allocate_uninit(rto, cto); + unsafe { + let mut res = >::allocate_uninit(rto, cto); - let (rfrom, cfrom) = buf.shape(); + let (rfrom, cfrom) = buf.shape(); - let len_from = rfrom.value() * cfrom.value(); - let len_to = rto.value() * cto.value(); - let len_copied = cmp::min(len_from, len_to); - ptr::copy_nonoverlapping(buf.ptr(), res.ptr_mut() as *mut T, len_copied); + let len_from = rfrom.value() * cfrom.value(); + let len_to = rto.value() * cto.value(); + let len_copied = cmp::min(len_from, len_to); + ptr::copy_nonoverlapping(buf.ptr(), res.ptr_mut() as *mut T, len_copied); - // Safety: - // - We don’t care about dropping elements because the caller is responsible for dropping things. - // - We forget `buf` so that we don’t drop the other elements, but ensure the buffer itself is cleaned up. - buf.forget_elements(); + // Safety: + // - We don’t care about dropping elements because the caller is responsible for dropping things. + // - We forget `buf` so that we don’t drop the other elements, but ensure the buffer itself is cleaned up. + buf.forget_elements(); - res + res + } } } @@ -261,21 +275,23 @@ where cto: Dyn, buf: ArrayStorage, ) -> VecStorage, RTo, Dyn> { - let mut res = >::allocate_uninit(rto, cto); + unsafe { + let mut res = >::allocate_uninit(rto, cto); - let (rfrom, cfrom) = buf.shape(); + let (rfrom, cfrom) = buf.shape(); - let len_from = rfrom.value() * cfrom.value(); - let len_to = rto.value() * cto.value(); - let len_copied = cmp::min(len_from, len_to); - ptr::copy_nonoverlapping(buf.ptr(), res.ptr_mut() as *mut T, len_copied); + let len_from = rfrom.value() * cfrom.value(); + let len_to = rto.value() * cto.value(); + let len_copied = cmp::min(len_from, len_to); + ptr::copy_nonoverlapping(buf.ptr(), res.ptr_mut() as *mut T, len_copied); - // Safety: - // - We don’t care about dropping elements because the caller is responsible for dropping things. - // - We forget `buf` so that we don’t drop the other elements, but ensure the buffer itself is cleaned up. - buf.forget_elements(); + // Safety: + // - We don’t care about dropping elements because the caller is responsible for dropping things. + // - We forget `buf` so that we don’t drop the other elements, but ensure the buffer itself is cleaned up. + buf.forget_elements(); - res + res + } } } @@ -288,8 +304,10 @@ impl Reallocator for D cto: CTo, buf: VecStorage, ) -> VecStorage, Dyn, CTo> { - let new_buf = buf.resize(rto.value() * cto.value()); - VecStorage::new(rto, cto, new_buf) + unsafe { + let new_buf = buf.resize(rto.value() * cto.value()); + VecStorage::new(rto, cto, new_buf) + } } } @@ -303,8 +321,10 @@ impl Reallocator cto: Dyn, buf: VecStorage, ) -> VecStorage, RTo, Dyn> { - let new_buf = buf.resize(rto.value() * cto.value()); - VecStorage::new(rto, cto, new_buf) + unsafe { + let new_buf = buf.resize(rto.value() * cto.value()); + VecStorage::new(rto, cto, new_buf) + } } } @@ -318,8 +338,10 @@ impl Reallocator cto: CTo, buf: VecStorage, ) -> VecStorage, Dyn, CTo> { - let new_buf = buf.resize(rto.value() * cto.value()); - VecStorage::new(rto, cto, new_buf) + unsafe { + let new_buf = buf.resize(rto.value() * cto.value()); + VecStorage::new(rto, cto, new_buf) + } } } @@ -333,7 +355,9 @@ impl Reallocator, ) -> VecStorage, RTo, Dyn> { - let new_buf = buf.resize(rto.value() * cto.value()); - VecStorage::new(rto, cto, new_buf) + unsafe { + let new_buf = buf.resize(rto.value() * cto.value()); + VecStorage::new(rto, cto, new_buf) + } } } diff --git a/src/base/dimension.rs b/src/base/dimension.rs index 44f94ecd5..73e0bdf17 100644 --- a/src/base/dimension.rs +++ b/src/base/dimension.rs @@ -304,7 +304,7 @@ impl ToConst for typenum::U1 { } macro_rules! from_to_typenum ( - ($($D: ident, $VAL: expr);* $(;)*) => {$( + ($($D: ident, $VAL: expr_2021);* $(;)*) => {$( pub type $D = Const<$VAL>; impl ToTypenum for Const<$VAL> { diff --git a/src/base/edition.rs b/src/base/edition.rs index b9a2b72e6..b7a97c2a9 100644 --- a/src/base/edition.rs +++ b/src/base/edition.rs @@ -690,27 +690,29 @@ impl> Matrix { C: DimAdd, DefaultAllocator: Reallocator>, { - let m = self.into_owned(); - let (nrows, ncols) = m.shape_generic(); - let mut res = Matrix::from_data(DefaultAllocator::reallocate_copy( - nrows, - ncols.add(ninsert), - m.data, - )); - - assert!(i <= ncols.value(), "Column insertion index out of range."); - - if ninsert.value() != 0 && i != ncols.value() { - let ptr_in = res.data.ptr().add(i * nrows.value()); - let ptr_out = res - .data - .ptr_mut() - .add((i + ninsert.value()) * nrows.value()); - - ptr::copy(ptr_in, ptr_out, (ncols.value() - i) * nrows.value()) - } + unsafe { + let m = self.into_owned(); + let (nrows, ncols) = m.shape_generic(); + let mut res = Matrix::from_data(DefaultAllocator::reallocate_copy( + nrows, + ncols.add(ninsert), + m.data, + )); - res + assert!(i <= ncols.value(), "Column insertion index out of range."); + + if ninsert.value() != 0 && i != ncols.value() { + let ptr_in = res.data.ptr().add(i * nrows.value()); + let ptr_out = res + .data + .ptr_mut() + .add((i + ninsert.value()) * nrows.value()); + + ptr::copy(ptr_in, ptr_out, (ncols.value() - i) * nrows.value()) + } + + res + } } /* @@ -784,27 +786,29 @@ impl> Matrix { R: DimAdd, DefaultAllocator: Reallocator, C>, { - let m = self.into_owned(); - let (nrows, ncols) = m.shape_generic(); - let mut res = Matrix::from_data(DefaultAllocator::reallocate_copy( - nrows.add(ninsert), - ncols, - m.data, - )); - - assert!(i <= nrows.value(), "Row insertion index out of range."); - - if ninsert.value() != 0 { - extend_rows( - res.as_mut_slice(), - nrows.value(), - ncols.value(), - i, - ninsert.value(), - ); - } + unsafe { + let m = self.into_owned(); + let (nrows, ncols) = m.shape_generic(); + let mut res = Matrix::from_data(DefaultAllocator::reallocate_copy( + nrows.add(ninsert), + ncols, + m.data, + )); - res + assert!(i <= nrows.value(), "Row insertion index out of range."); + + if ninsert.value() != 0 { + extend_rows( + res.as_mut_slice(), + nrows.value(), + ncols.value(), + i, + ninsert.value(), + ); + } + + res + } } } @@ -1087,80 +1091,84 @@ unsafe fn compress_rows( i: usize, nremove: usize, ) { - let new_nrows = nrows - nremove; + unsafe { + let new_nrows = nrows - nremove; - if nremove == 0 { - return; // Nothing to remove or drop. - } + if nremove == 0 { + return; // Nothing to remove or drop. + } - if new_nrows == 0 || ncols == 0 { - // The output matrix is empty, drop everything. - ptr::drop_in_place(data); - return; - } + if new_nrows == 0 || ncols == 0 { + // The output matrix is empty, drop everything. + ptr::drop_in_place(data); + return; + } - // Safety: because `nremove != 0`, the pointers given to `ptr::copy` - // won’t alias. - let ptr_in = data.as_ptr(); - let ptr_out = data.as_mut_ptr(); + // Safety: because `nremove != 0`, the pointers given to `ptr::copy` + // won’t alias. + let ptr_in = data.as_ptr(); + let ptr_out = data.as_mut_ptr(); + + let mut curr_i = i; + + for k in 0..ncols - 1 { + // Safety: we drop the row elements in-place because we will overwrite these + // entries later with the `ptr::copy`. + let s = ptr::slice_from_raw_parts_mut(ptr_out.add(curr_i), nremove); + ptr::drop_in_place(s); + ptr::copy( + ptr_in.add(curr_i + (k + 1) * nremove), + ptr_out.add(curr_i), + new_nrows, + ); - let mut curr_i = i; + curr_i += new_nrows; + } - for k in 0..ncols - 1 { + /* + * Deal with the last column from which less values have to be copied. + */ // Safety: we drop the row elements in-place because we will overwrite these // entries later with the `ptr::copy`. let s = ptr::slice_from_raw_parts_mut(ptr_out.add(curr_i), nremove); ptr::drop_in_place(s); + let remaining_len = nrows - i - nremove; ptr::copy( - ptr_in.add(curr_i + (k + 1) * nremove), + ptr_in.add(nrows * ncols - remaining_len), ptr_out.add(curr_i), - new_nrows, + remaining_len, ); - - curr_i += new_nrows; } - - /* - * Deal with the last column from which less values have to be copied. - */ - // Safety: we drop the row elements in-place because we will overwrite these - // entries later with the `ptr::copy`. - let s = ptr::slice_from_raw_parts_mut(ptr_out.add(curr_i), nremove); - ptr::drop_in_place(s); - let remaining_len = nrows - i - nremove; - ptr::copy( - ptr_in.add(nrows * ncols - remaining_len), - ptr_out.add(curr_i), - remaining_len, - ); } // Moves entries of a matrix buffer to make place for `ninsert` empty rows starting at the `i-th` row index. // The `data` buffer is assumed to contained at least `(nrows + ninsert) * ncols` elements. unsafe fn extend_rows(data: &mut [T], nrows: usize, ncols: usize, i: usize, ninsert: usize) { - let new_nrows = nrows + ninsert; + unsafe { + let new_nrows = nrows + ninsert; - if new_nrows == 0 || ncols == 0 { - return; // Nothing to do as the output matrix is empty. - } + if new_nrows == 0 || ncols == 0 { + return; // Nothing to do as the output matrix is empty. + } - let ptr_in = data.as_ptr(); - let ptr_out = data.as_mut_ptr(); + let ptr_in = data.as_ptr(); + let ptr_out = data.as_mut_ptr(); - let remaining_len = nrows - i; - let mut curr_i = new_nrows * ncols - remaining_len; + let remaining_len = nrows - i; + let mut curr_i = new_nrows * ncols - remaining_len; - // Deal with the last column from which less values have to be copied. - ptr::copy( - ptr_in.add(nrows * ncols - remaining_len), - ptr_out.add(curr_i), - remaining_len, - ); + // Deal with the last column from which less values have to be copied. + ptr::copy( + ptr_in.add(nrows * ncols - remaining_len), + ptr_out.add(curr_i), + remaining_len, + ); - for k in (0..ncols - 1).rev() { - curr_i -= new_nrows; + for k in (0..ncols - 1).rev() { + curr_i -= new_nrows; - ptr::copy(ptr_in.add(k * nrows + i), ptr_out.add(curr_i), nrows); + ptr::copy(ptr_in.add(k * nrows + i), ptr_out.add(curr_i), nrows); + } } } diff --git a/src/base/helper.rs b/src/base/helper.rs index 85fdc6595..968bc94d0 100644 --- a/src/base/helper.rs +++ b/src/base/helper.rs @@ -3,8 +3,8 @@ use quickcheck::{Arbitrary, Gen}; #[cfg(feature = "rand-no-std")] use rand::{ - distr::{Distribution, StandardUniform}, Rng, + distr::{Distribution, StandardUniform}, }; /// Simple helper function for rejection sampling diff --git a/src/base/indexing.rs b/src/base/indexing.rs index 5a860fe0b..e91fea144 100644 --- a/src/base/indexing.rs +++ b/src/base/indexing.rs @@ -529,7 +529,7 @@ impl> Matrix { where I: MatrixIndex<'a, T, R, C, S>, { - index.get_unchecked(self) + unsafe { index.get_unchecked(self) } } /// Returns a mutable view of the data at the given index, without doing @@ -544,7 +544,7 @@ impl> Matrix { S: RawStorageMut, I: MatrixIndexMut<'a, T, R, C, S>, { - index.get_unchecked_mut(self) + unsafe { index.get_unchecked_mut(self) } } } @@ -568,10 +568,12 @@ where #[doc(hidden)] #[inline(always)] unsafe fn get_unchecked(self, matrix: &'a Matrix) -> Self::Output { - let nrows = matrix.shape().0; - let row = self % nrows; - let col = self / nrows; - matrix.data.get_unchecked(row, col) + unsafe { + let nrows = matrix.shape().0; + let row = self % nrows; + let col = self / nrows; + matrix.data.get_unchecked(row, col) + } } } @@ -590,10 +592,12 @@ where where S: RawStorageMut, { - let nrows = matrix.shape().0; - let row = self % nrows; - let col = self / nrows; - matrix.data.get_unchecked_mut(row, col) + unsafe { + let nrows = matrix.shape().0; + let row = self % nrows; + let col = self / nrows; + matrix.data.get_unchecked_mut(row, col) + } } } @@ -618,8 +622,10 @@ where #[doc(hidden)] #[inline(always)] unsafe fn get_unchecked(self, matrix: &'a Matrix) -> Self::Output { - let (row, col) = self; - matrix.data.get_unchecked(row, col) + unsafe { + let (row, col) = self; + matrix.data.get_unchecked(row, col) + } } } @@ -637,8 +643,10 @@ where where S: RawStorageMut, { - let (row, col) = self; - matrix.data.get_unchecked_mut(row, col) + unsafe { + let (row, col) = self; + matrix.data.get_unchecked_mut(row, col) + } } } @@ -682,7 +690,7 @@ macro_rules! impl_index_pair { #[doc(hidden)] #[inline(always)] - unsafe fn get_unchecked(self, matrix: &'a Matrix) -> Self::Output { + unsafe fn get_unchecked(self, matrix: &'a Matrix) -> Self::Output { unsafe { use crate::base::ViewStorage; let (rows, cols) = self; @@ -694,7 +702,7 @@ macro_rules! impl_index_pair { (rows.length(nrows), cols.length(ncols))); Matrix::from_data_statically_unchecked(data) - } + }} } impl<'a, T, $R, $C, S, $($RTyP : $RTyPB,)* $($CTyP : $CTyPB),*> MatrixIndexMut<'a, T, $R, $C, S> for ($RIdx, $CIdx) @@ -710,7 +718,7 @@ macro_rules! impl_index_pair { #[doc(hidden)] #[inline(always)] - unsafe fn get_unchecked_mut(self, matrix: &'a mut Matrix) -> Self::OutputMut { + unsafe fn get_unchecked_mut(self, matrix: &'a mut Matrix) -> Self::OutputMut { unsafe { use crate::base::ViewStorageMut; let (rows, cols) = self; @@ -722,7 +730,7 @@ macro_rules! impl_index_pair { (rows.length(nrows), cols.length(ncols))); Matrix::from_data_statically_unchecked(data) - } + }} } } } diff --git a/src/base/interpolation.rs b/src/base/interpolation.rs index e7ef55293..95710d091 100644 --- a/src/base/interpolation.rs +++ b/src/base/interpolation.rs @@ -6,10 +6,10 @@ use simba::scalar::{ClosedAddAssign, ClosedMulAssign, ClosedSubAssign}; /// # Interpolation impl< - T: Scalar + Zero + One + ClosedAddAssign + ClosedSubAssign + ClosedMulAssign, - D: Dim, - S: Storage, - > Vector + T: Scalar + Zero + One + ClosedAddAssign + ClosedSubAssign + ClosedMulAssign, + D: Dim, + S: Storage, +> Vector { /// Returns `self * (1.0 - t) + rhs * t`, i.e., the linear blend of the vectors x and y using the scalar value a. /// diff --git a/src/base/matrix.rs b/src/base/matrix.rs index 77f6c1c88..5b65f2c07 100644 --- a/src/base/matrix.rs +++ b/src/base/matrix.rs @@ -1,3 +1,6 @@ +// Needed otherwise the rkyv macros generate code incompatible with rust-2024 +#![cfg_attr(feature = "rkyv-serialize", allow(unsafe_op_in_unsafe_fn))] + use num::{One, Zero}; use approx::{AbsDiffEq, RelativeEq, UlpsEq}; @@ -16,7 +19,7 @@ use super::rkyv_wrappers::CustomPhantom; #[cfg(feature = "rkyv-serialize")] use rkyv::bytecheck; #[cfg(feature = "rkyv-serialize-no-std")] -use rkyv::{with::With, Archive, Archived}; +use rkyv::{Archive, Archived, with::With}; use simba::scalar::{ClosedAddAssign, ClosedMulAssign, ClosedSubAssign, Field, SupersetOf}; use simba::simd::SimdPartialOrd; @@ -394,9 +397,11 @@ where /// or Undefined Behavior will immediately occur. #[inline(always)] pub unsafe fn assume_init(self) -> OMatrix { - OMatrix::from_data(>::assume_init( - self.data, - )) + unsafe { + OMatrix::from_data(>::assume_init( + self.data, + )) + } } } @@ -1203,9 +1208,11 @@ impl> Matrix { /// Both `(r, c)` must have `r < nrows(), c < ncols()`. #[inline] pub unsafe fn swap_unchecked(&mut self, row_cols1: (usize, usize), row_cols2: (usize, usize)) { - debug_assert!(row_cols1.0 < self.nrows() && row_cols1.1 < self.ncols()); - debug_assert!(row_cols2.0 < self.nrows() && row_cols2.1 < self.ncols()); - self.data.swap_unchecked(row_cols1, row_cols2) + unsafe { + debug_assert!(row_cols1.0 < self.nrows() && row_cols1.1 < self.ncols()); + debug_assert!(row_cols2.0 < self.nrows() && row_cols2.1 < self.ncols()); + self.data.swap_unchecked(row_cols1, row_cols2) + } } /// Swaps two entries. @@ -1312,9 +1319,11 @@ impl> Vector { #[inline] #[must_use] pub unsafe fn vget_unchecked(&self, i: usize) -> &T { - debug_assert!(i < self.nrows(), "Vector index out of bounds."); - let i = i * self.strides().0; - self.data.get_unchecked_linear(i) + unsafe { + debug_assert!(i < self.nrows(), "Vector index out of bounds."); + let i = i * self.strides().0; + self.data.get_unchecked_linear(i) + } } } @@ -1325,9 +1334,11 @@ impl> Vector { #[inline] #[must_use] pub unsafe fn vget_unchecked_mut(&mut self, i: usize) -> &mut T { - debug_assert!(i < self.nrows(), "Vector index out of bounds."); - let i = i * self.strides().0; - self.data.get_unchecked_linear_mut(i) + unsafe { + debug_assert!(i < self.nrows(), "Vector index out of bounds."); + let i = i * self.strides().0; + self.data.get_unchecked_linear_mut(i) + } } } @@ -1902,7 +1913,7 @@ where } macro_rules! impl_fmt { - ($trait: path, $fmt_str_without_precision: expr, $fmt_str_with_precision: expr) => { + ($trait: path, $fmt_str_without_precision: expr_2021, $fmt_str_with_precision: expr_2021) => { impl $trait for Matrix where T: Scalar + $trait, @@ -2011,11 +2022,11 @@ mod tests { /// # Cross product impl< - T: Scalar + ClosedAddAssign + ClosedSubAssign + ClosedMulAssign, - R: Dim, - C: Dim, - S: RawStorage, - > Matrix + T: Scalar + ClosedAddAssign + ClosedSubAssign + ClosedMulAssign, + R: Dim, + C: Dim, + S: RawStorage, +> Matrix { /// The perpendicular product between two 2D column vectors, i.e. `a.x * b.y - a.y * b.x`. #[inline] @@ -2039,8 +2050,7 @@ impl< assert_eq!( shape, (2, 1), - "2D perpendicular product requires (2, 1) vectors {:?}", - shape + "2D perpendicular product requires (2, 1) vectors {shape:?}", ); // SAFETY: assertion above ensures correct shape @@ -2071,8 +2081,7 @@ impl< assert_eq!(shape, b.shape(), "Vector cross product dimension mismatch."); assert!( shape == (3, 1) || shape == (1, 3), - "Vector cross product dimension mismatch: must be (3, 1) or (1, 3) but found {:?}.", - shape + "Vector cross product dimension mismatch: must be (3, 1) or (1, 3) but found {shape:?}.", ); if shape.0 == 3 { diff --git a/src/base/matrix_simba.rs b/src/base/matrix_simba.rs index 83324f5b4..89829726e 100644 --- a/src/base/matrix_simba.rs +++ b/src/base/matrix_simba.rs @@ -33,7 +33,7 @@ where #[inline] unsafe fn extract_unchecked(&self, i: usize) -> Self::Element { - self.map(|e| e.extract_unchecked(i)) + unsafe { self.map(|e| e.extract_unchecked(i)) } } #[inline] @@ -45,9 +45,11 @@ where #[inline] unsafe fn replace_unchecked(&mut self, i: usize, val: Self::Element) { - self.zip_apply(&val, |a, b| { - a.replace_unchecked(i, b); - }) + unsafe { + self.zip_apply(&val, |a, b| { + a.replace_unchecked(i, b); + }) + } } fn select(self, cond: Self::SimdBool, other: Self) -> Self { diff --git a/src/base/matrix_view.rs b/src/base/matrix_view.rs index 95b99bcc8..550047ad6 100644 --- a/src/base/matrix_view.rs +++ b/src/base/matrix_view.rs @@ -2,6 +2,7 @@ use std::marker::PhantomData; use std::ops::{Range, RangeFrom, RangeFull, RangeInclusive, RangeTo}; use std::slice; +use crate::ReshapableStorage; use crate::base::allocator::Allocator; use crate::base::default_allocator::DefaultAllocator; use crate::base::dimension::{Const, Dim, DimName, Dyn, IsNotStaticOne, U1}; @@ -9,10 +10,9 @@ use crate::base::iter::MatrixIter; use crate::base::storage::{IsContiguous, Owned, RawStorage, RawStorageMut, Storage}; use crate::base::{Matrix, Scalar}; use crate::constraint::{DimEq, ShapeConstraint}; -use crate::ReshapableStorage; macro_rules! view_storage_impl ( - ($doc: expr; $Storage: ident as $SRef: ty; $legacy_name:ident => $T: ident.$get_addr: ident ($Ptr: ty as $Ref: ty)) => { + ($doc: expr_2021; $Storage: ident as $SRef: ty; $legacy_name:ident => $T: ident.$get_addr: ident ($Ptr: ty as $Ref: ty)) => { #[doc = $doc] #[derive(Debug)] pub struct $T<'a, T, R: Dim, C: Dim, RStride: Dim, CStride: Dim> { @@ -77,11 +77,11 @@ macro_rules! view_storage_impl ( -> $T<'a, T, R, C, S::RStride, S::CStride> where RStor: Dim, CStor: Dim, - S: $Storage { + S: $Storage { unsafe { let strides = storage.strides(); $T::new_with_strides_unchecked(storage, start, shape, strides) - } + }} /// Create a new matrix view without bounds checking. /// @@ -98,9 +98,9 @@ macro_rules! view_storage_impl ( CStor: Dim, S: $Storage, RStride: Dim, - CStride: Dim { + CStride: Dim { unsafe { $T::from_raw_parts(storage.$get_addr(start.0, start.1), shape, strides) - } + }} } impl <'a, T, R: Dim, C: Dim, RStride: Dim, CStride: Dim> @@ -202,7 +202,7 @@ macro_rules! storage_impl( } #[inline] - unsafe fn as_slice_unchecked(&self) -> &[T] { + unsafe fn as_slice_unchecked(&self) -> &[T] { unsafe { let (nrows, ncols) = self.shape(); if nrows.value() != 0 && ncols.value() != 0 { let sz = self.linear_index(nrows.value() - 1, ncols.value() - 1); @@ -211,7 +211,7 @@ macro_rules! storage_impl( else { slice::from_raw_parts(self.ptr, 0) } - } + }} } unsafe impl<'a, T: Scalar, R: Dim, C: Dim, RStride: Dim, CStride: Dim> Storage @@ -250,12 +250,14 @@ unsafe impl RawStorageMut &mut [T] { - let (nrows, ncols) = self.shape(); - if nrows.value() != 0 && ncols.value() != 0 { - let sz = self.linear_index(nrows.value() - 1, ncols.value() - 1); - slice::from_raw_parts_mut(self.ptr, sz + 1) - } else { - slice::from_raw_parts_mut(self.ptr, 0) + unsafe { + let (nrows, ncols) = self.shape(); + if nrows.value() != 0 && ncols.value() != 0 { + let sz = self.linear_index(nrows.value() - 1, ncols.value() - 1); + slice::from_raw_parts_mut(self.ptr, sz + 1) + } else { + slice::from_raw_parts_mut(self.ptr, 0) + } } } } @@ -297,7 +299,7 @@ impl> Matrix { } macro_rules! matrix_view_impl ( - ($me: ident: $Me: ty, $MatrixView: ident, $ViewStorage: ident, $Storage: ident.$get_addr: ident (), $data: expr; + ($me: ident: $Me: ty, $MatrixView: ident, $ViewStorage: ident, $Storage: ident.$get_addr: ident (), $data: expr_2021; $row: ident, $row_part: ident, $rows: ident, diff --git a/src/base/norm.rs b/src/base/norm.rs index 90362be62..832ae19a2 100644 --- a/src/base/norm.rs +++ b/src/base/norm.rs @@ -631,8 +631,10 @@ where } #[cfg(all(not(feature = "std"), not(feature = "alloc")))] { - panic!("Cannot compute the orthogonal subspace basis of a vector with a dimension greater than 3 \ - if #![no_std] is enabled and the 'alloc' feature is not enabled.") + panic!( + "Cannot compute the orthogonal subspace basis of a vector with a dimension greater than 3 \ + if #![no_std] is enabled and the 'alloc' feature is not enabled." + ) } } } diff --git a/src/base/ops.rs b/src/base/ops.rs index d08ecfa84..34ef59f22 100644 --- a/src/base/ops.rs +++ b/src/base/ops.rs @@ -398,10 +398,11 @@ where /// iter::empty::>().sum::>(); // panics! /// ``` fn sum>>(mut iter: I) -> OMatrix { - if let Some(first) = iter.next() { - iter.fold(first, |acc, x| acc + x) - } else { - panic!("Cannot compute `sum` of empty iterator.") + match iter.next() { + Some(first) => iter.fold(first, |acc, x| acc + x), + None => { + panic!("Cannot compute `sum` of empty iterator.") + } } } } diff --git a/src/base/par_iter.rs b/src/base/par_iter.rs index c4cac01b8..3d19dcbc6 100644 --- a/src/base/par_iter.rs +++ b/src/base/par_iter.rs @@ -1,8 +1,8 @@ //! Parallel iterators for matrices compatible with rayon. use crate::{ - iter::{ColumnIter, ColumnIterMut}, Dim, Matrix, MatrixView, MatrixViewMut, RawStorage, RawStorageMut, Scalar, U1, + iter::{ColumnIter, ColumnIterMut}, }; use rayon::iter::plumbing::Producer; use rayon::{iter::plumbing::bridge, prelude::*}; diff --git a/src/base/properties.rs b/src/base/properties.rs index 0fdfaf019..143b4bf33 100644 --- a/src/base/properties.rs +++ b/src/base/properties.rs @@ -4,11 +4,11 @@ use num::{One, Zero}; use simba::scalar::{ClosedAddAssign, ClosedMulAssign, ComplexField, RealField}; +use crate::RawStorage; use crate::base::allocator::Allocator; use crate::base::dimension::{Dim, DimMin}; use crate::base::storage::Storage; use crate::base::{DefaultAllocator, Matrix, SquareMatrix}; -use crate::RawStorage; impl> Matrix { /// The total number of elements of this matrix. diff --git a/src/base/rkyv_wrappers.rs b/src/base/rkyv_wrappers.rs index fa05c1452..b6ebf939a 100644 --- a/src/base/rkyv_wrappers.rs +++ b/src/base/rkyv_wrappers.rs @@ -3,8 +3,8 @@ //! Copied from (MIT-Apache2 licences) which isn’t published yet. use rkyv::{ - with::{ArchiveWith, DeserializeWith, SerializeWith}, Fallible, + with::{ArchiveWith, DeserializeWith, SerializeWith}, }; use std::marker::PhantomData; diff --git a/src/base/statistics.rs b/src/base/statistics.rs index 3837f385f..845b7529e 100644 --- a/src/base/statistics.rs +++ b/src/base/statistics.rs @@ -1,6 +1,6 @@ use crate::allocator::Allocator; use crate::storage::RawStorage; -use crate::{Const, DefaultAllocator, Dim, Matrix, OVector, RowOVector, Scalar, VectorView, U1}; +use crate::{Const, DefaultAllocator, Dim, Matrix, OVector, RowOVector, Scalar, U1, VectorView}; use num::{One, Zero}; use simba::scalar::{ClosedAddAssign, ClosedMulAssign, Field, SupersetOf}; use std::mem::MaybeUninit; diff --git a/src/base/storage.rs b/src/base/storage.rs index d26bf082c..9ca0eb9cf 100644 --- a/src/base/storage.rs +++ b/src/base/storage.rs @@ -2,10 +2,10 @@ use std::ptr; +use crate::base::Scalar; use crate::base::allocator::{Allocator, SameShapeC, SameShapeR}; use crate::base::default_allocator::DefaultAllocator; use crate::base::dimension::{Dim, U1}; -use crate::base::Scalar; /* * Aliases for allocation results. @@ -100,7 +100,7 @@ pub unsafe trait RawStorage: Sized { /// If the index is out of bounds, the method will cause undefined behavior. #[inline] unsafe fn get_unchecked_linear(&self, i: usize) -> &T { - &*self.get_address_unchecked_linear(i) + unsafe { &*self.get_address_unchecked_linear(i) } } /// Retrieves a reference to the i-th element without bound-checking. @@ -109,7 +109,7 @@ pub unsafe trait RawStorage: Sized { /// If the index is out of bounds, the method will cause undefined behavior. #[inline] unsafe fn get_unchecked(&self, irow: usize, icol: usize) -> &T { - self.get_unchecked_linear(self.linear_index(irow, icol)) + unsafe { self.get_unchecked_linear(self.linear_index(irow, icol)) } } /// Indicates whether this data buffer stores its elements contiguously. @@ -193,7 +193,7 @@ pub unsafe trait RawStorageMut: RawStorage { /// # Safety /// If the index is out of bounds, the method will cause undefined behavior. unsafe fn get_unchecked_linear_mut(&mut self, i: usize) -> &mut T { - &mut *self.get_address_unchecked_linear_mut(i) + unsafe { &mut *self.get_address_unchecked_linear_mut(i) } } /// Retrieves a mutable reference to the element at `(irow, icol)` without bound-checking. @@ -202,7 +202,7 @@ pub unsafe trait RawStorageMut: RawStorage { /// If the index is out of bounds, the method will cause undefined behavior. #[inline] unsafe fn get_unchecked_mut(&mut self, irow: usize, icol: usize) -> &mut T { - &mut *self.get_address_unchecked_mut(irow, icol) + unsafe { &mut *self.get_address_unchecked_mut(irow, icol) } } /// Swaps two elements using their linear index without bound-checking. @@ -218,21 +218,23 @@ pub unsafe trait RawStorageMut: RawStorage { /// trait implementation may be invalid or unsound and should be overridden. #[inline] unsafe fn swap_unchecked_linear(&mut self, i1: usize, i2: usize) { - // we can't just use the pointers returned from `get_address_unchecked_linear_mut` because calling a - // method taking self mutably invalidates any existing (mutable) pointers. since `get_address_unchecked_linear_mut` can - // also be overridden by a custom implementation, we can't just use `wrapping_add` assuming that's what the method does. - // instead, we use `offset_from` to compute the re-calculate the pointers from the base pointer. - // this is sound as long as this trait matches the Validity preconditions - // (and it's the caller's responsibility to ensure the indices are in-bounds). - let base = self.ptr_mut(); - let offset1 = self.get_address_unchecked_linear_mut(i1).offset_from(base); - let offset2 = self.get_address_unchecked_linear_mut(i2).offset_from(base); - - let base = self.ptr_mut(); - let a = base.offset(offset1); - let b = base.offset(offset2); - - ptr::swap(a, b); + unsafe { + // we can't just use the pointers returned from `get_address_unchecked_linear_mut` because calling a + // method taking self mutably invalidates any existing (mutable) pointers. since `get_address_unchecked_linear_mut` can + // also be overridden by a custom implementation, we can't just use `wrapping_add` assuming that's what the method does. + // instead, we use `offset_from` to compute the re-calculate the pointers from the base pointer. + // this is sound as long as this trait matches the Validity preconditions + // (and it's the caller's responsibility to ensure the indices are in-bounds). + let base = self.ptr_mut(); + let offset1 = self.get_address_unchecked_linear_mut(i1).offset_from(base); + let offset2 = self.get_address_unchecked_linear_mut(i2).offset_from(base); + + let base = self.ptr_mut(); + let a = base.offset(offset1); + let b = base.offset(offset2); + + ptr::swap(a, b); + } } /// Swaps two elements without bound-checking. @@ -241,10 +243,12 @@ pub unsafe trait RawStorageMut: RawStorage { /// If the indices are out of bounds, the method will cause undefined behavior. #[inline] unsafe fn swap_unchecked(&mut self, row_col1: (usize, usize), row_col2: (usize, usize)) { - let lid1 = self.linear_index(row_col1.0, row_col1.1); - let lid2 = self.linear_index(row_col2.0, row_col2.1); + unsafe { + let lid1 = self.linear_index(row_col1.0, row_col1.1); + let lid2 = self.linear_index(row_col2.0, row_col2.1); - self.swap_unchecked_linear(lid1, lid2) + self.swap_unchecked_linear(lid1, lid2) + } } /// Retrieves the mutable data buffer as a contiguous slice. diff --git a/src/base/swizzle.rs b/src/base/swizzle.rs index 303322611..517e633f8 100644 --- a/src/base/swizzle.rs +++ b/src/base/swizzle.rs @@ -3,7 +3,7 @@ use crate::storage::RawStorage; use typenum::{self, Cmp, Greater}; macro_rules! impl_swizzle { - ($( where $BaseDim: ident: $( $name: ident() -> $Result: ident[$($i: expr),+] ),+ ;)* ) => { + ($( where $BaseDim: ident: $( $name: ident() -> $Result: ident[$($i: expr_2021),+] ),+ ;)* ) => { $( $( /// Builds a new vector from components of `self`. diff --git a/src/base/uninit.rs b/src/base/uninit.rs index 401e3336b..736664d99 100644 --- a/src/base/uninit.rs +++ b/src/base/uninit.rs @@ -66,11 +66,15 @@ unsafe impl InitStatus for Uninit { #[inline(always)] unsafe fn assume_init_ref(t: &MaybeUninit) -> &T { - &*t.as_ptr() // TODO: use t.assume_init_ref() + unsafe { + &*t.as_ptr() // TODO: use t.assume_init_ref() + } } #[inline(always)] unsafe fn assume_init_mut(t: &mut MaybeUninit) -> &mut T { - &mut *t.as_mut_ptr() // TODO: use t.assume_init_mut() + unsafe { + &mut *t.as_mut_ptr() // TODO: use t.assume_init_mut() + } } } diff --git a/src/base/unit.rs b/src/base/unit.rs index 84cfc3154..aac3a44c5 100644 --- a/src/base/unit.rs +++ b/src/base/unit.rs @@ -1,3 +1,6 @@ +// Needed otherwise the rkyv macros generate code incompatible with rust-2024 +#![cfg_attr(feature = "rkyv-serialize", allow(unsafe_op_in_unsafe_fn))] + use std::fmt; use std::ops::Deref; diff --git a/src/base/vec_storage.rs b/src/base/vec_storage.rs index f0a0593fa..c1bdbc036 100644 --- a/src/base/vec_storage.rs +++ b/src/base/vec_storage.rs @@ -153,44 +153,46 @@ impl VecStorage { /// It is the responsibility of the caller of this method to drop these elements. #[inline] pub unsafe fn resize(mut self, sz: usize) -> Vec> { - let len = self.len(); - - let new_data = if sz < len { - // Use `set_len` instead of `truncate` because we don’t want to - // drop the removed elements (it’s the caller’s responsibility). - self.data.set_len(sz); - self.data.shrink_to_fit(); - - // Safety: - // - MaybeUninit has the same alignment and layout as T. - // - The length and capacity come from a valid vector. - Vec::from_raw_parts( - self.data.as_mut_ptr() as *mut MaybeUninit, - self.data.len(), - self.data.capacity(), - ) - } else { - self.data.reserve_exact(sz - len); - - // Safety: - // - MaybeUninit has the same alignment and layout as T. - // - The length and capacity come from a valid vector. - let mut new_data = Vec::from_raw_parts( - self.data.as_mut_ptr() as *mut MaybeUninit, - self.data.len(), - self.data.capacity(), - ); - - // Safety: we can set the length here because MaybeUninit is always assumed - // to be initialized. - new_data.set_len(sz); + unsafe { + let len = self.len(); + + let new_data = if sz < len { + // Use `set_len` instead of `truncate` because we don’t want to + // drop the removed elements (it’s the caller’s responsibility). + self.data.set_len(sz); + self.data.shrink_to_fit(); + + // Safety: + // - MaybeUninit has the same alignment and layout as T. + // - The length and capacity come from a valid vector. + Vec::from_raw_parts( + self.data.as_mut_ptr() as *mut MaybeUninit, + self.data.len(), + self.data.capacity(), + ) + } else { + self.data.reserve_exact(sz - len); + + // Safety: + // - MaybeUninit has the same alignment and layout as T. + // - The length and capacity come from a valid vector. + let mut new_data = Vec::from_raw_parts( + self.data.as_mut_ptr() as *mut MaybeUninit, + self.data.len(), + self.data.capacity(), + ); + + // Safety: we can set the length here because MaybeUninit is always assumed + // to be initialized. + new_data.set_len(sz); + new_data + }; + + // Avoid double-free by forgetting `self` because its data buffer has + // been transferred to `new_data`. + std::mem::forget(self); new_data - }; - - // Avoid double-free by forgetting `self` because its data buffer has - // been transferred to `new_data`. - std::mem::forget(self); - new_data + } } /// The number of elements on the underlying vector. @@ -470,8 +472,10 @@ impl Extend for VecStorage { fn extend>(&mut self, iter: I) { self.data.extend(iter); self.ncols = Dyn(self.data.len() / self.nrows.value()); - assert!(self.data.len() % self.nrows.value() == 0, - "The number of elements produced by the given iterator was not a multiple of the number of rows."); + assert!( + self.data.len() % self.nrows.value() == 0, + "The number of elements produced by the given iterator was not a multiple of the number of rows." + ); } } diff --git a/src/debug/random_orthogonal.rs b/src/debug/random_orthogonal.rs index 77d0302dc..117b4e861 100644 --- a/src/debug/random_orthogonal.rs +++ b/src/debug/random_orthogonal.rs @@ -3,9 +3,9 @@ use crate::base::storage::Owned; #[cfg(feature = "arbitrary")] use quickcheck::{Arbitrary, Gen}; +use crate::base::Scalar; use crate::base::allocator::Allocator; use crate::base::dimension::{Dim, Dyn}; -use crate::base::Scalar; use crate::base::{DefaultAllocator, OMatrix}; use crate::linalg::givens::GivensRotation; use simba::scalar::ComplexField; diff --git a/src/debug/random_sdp.rs b/src/debug/random_sdp.rs index 31e363768..37d5b6669 100644 --- a/src/debug/random_sdp.rs +++ b/src/debug/random_sdp.rs @@ -3,9 +3,9 @@ use crate::base::storage::Owned; #[cfg(feature = "arbitrary")] use quickcheck::{Arbitrary, Gen}; +use crate::base::Scalar; use crate::base::allocator::Allocator; use crate::base::dimension::{Dim, Dyn}; -use crate::base::Scalar; use crate::base::{DefaultAllocator, OMatrix}; use simba::scalar::ComplexField; diff --git a/src/geometry/dual_quaternion.rs b/src/geometry/dual_quaternion.rs index 6b3047fb3..7dbc6ddd0 100644 --- a/src/geometry/dual_quaternion.rs +++ b/src/geometry/dual_quaternion.rs @@ -1,3 +1,5 @@ +// Needed otherwise the rkyv macros generate code incompatible with rust-2024 +#![cfg_attr(feature = "rkyv-serialize", allow(unsafe_op_in_unsafe_fn))] // The macros break if the references are taken out, for some reason. #![allow(clippy::op_ref)] @@ -6,7 +8,7 @@ use rkyv::bytecheck; use crate::{ Isometry3, Matrix4, Normed, OVector, Point3, Quaternion, Scalar, SimdRealField, Translation3, - Unit, UnitQuaternion, Vector3, Zero, U8, + U8, Unit, UnitQuaternion, Vector3, Zero, }; use approx::{AbsDiffEq, RelativeEq, UlpsEq}; #[cfg(feature = "serde-serialize-no-std")] @@ -960,24 +962,27 @@ impl Default for UnitDualQuaternion { impl fmt::Display for UnitDualQuaternion { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { - if let Some(axis) = self.rotation().axis() { - let axis = axis.into_inner(); - write!( - f, - "UnitDualQuaternion translation: {} − angle: {} − axis: ({}, {}, {})", - self.translation().vector, - self.rotation().angle(), - axis[0], - axis[1], - axis[2] - ) - } else { - write!( - f, - "UnitDualQuaternion translation: {} − angle: {} − axis: (undefined)", - self.translation().vector, - self.rotation().angle() - ) + match self.rotation().axis() { + Some(axis) => { + let axis = axis.into_inner(); + write!( + f, + "UnitDualQuaternion translation: {} − angle: {} − axis: ({}, {}, {})", + self.translation().vector, + self.rotation().angle(), + axis[0], + axis[1], + axis[2] + ) + } + None => { + write!( + f, + "UnitDualQuaternion translation: {} − angle: {} − axis: (undefined)", + self.translation().vector, + self.rotation().angle() + ) + } } } } diff --git a/src/geometry/dual_quaternion_ops.rs b/src/geometry/dual_quaternion_ops.rs index 7bf6a0db6..40676beee 100644 --- a/src/geometry/dual_quaternion_ops.rs +++ b/src/geometry/dual_quaternion_ops.rs @@ -49,8 +49,8 @@ use crate::base::storage::Storage; use crate::{ - DualQuaternion, Isometry3, Point, Point3, Quaternion, SimdRealField, Translation3, Unit, - UnitDualQuaternion, UnitQuaternion, Vector, Vector3, U3, + DualQuaternion, Isometry3, Point, Point3, Quaternion, SimdRealField, Translation3, U3, Unit, + UnitDualQuaternion, UnitQuaternion, Vector, Vector3, }; use std::ops::{ Add, AddAssign, Div, DivAssign, Index, IndexMut, Mul, MulAssign, Neg, Sub, SubAssign, @@ -139,7 +139,7 @@ macro_rules! dual_quaternion_op_impl( ($LhsRDim: ident, $LhsCDim: ident), ($RhsRDim: ident, $RhsCDim: ident) $(for $Storage: ident: $StoragesBound: ident $(<$($BoundParam: ty),*>)*),*; $lhs: ident: $Lhs: ty, $rhs: ident: $Rhs: ty, Output = $Result: ty $(=> $VDimA: ty, $VDimB: ty)*; - $action: expr; $($lives: tt),*) => { + $action: expr_2021; $($lives: tt),*) => { impl<$($lives ,)* T: SimdRealField $(, $Storage: $StoragesBound $(<$($BoundParam),*>)*)*> $Op<$Rhs> for $Lhs where T::Element: SimdRealField, { type Output = $Result; @@ -960,7 +960,7 @@ macro_rules! dual_quaternion_op_impl( ($OpAssign: ident, $op_assign: ident; ($LhsRDim: ident, $LhsCDim: ident), ($RhsRDim: ident, $RhsCDim: ident); $lhs: ident: $Lhs: ty, $rhs: ident: $Rhs: ty $(=> $VDimA: ty, $VDimB: ty)*; - $action: expr; $($lives: tt),*) => { + $action: expr_2021; $($lives: tt),*) => { impl<$($lives ,)* T: SimdRealField> $OpAssign<$Rhs> for $Lhs where T::Element: SimdRealField { diff --git a/src/geometry/isometry.rs b/src/geometry/isometry.rs index 9e9f742e1..e59a78190 100644 --- a/src/geometry/isometry.rs +++ b/src/geometry/isometry.rs @@ -1,3 +1,6 @@ +// Needed otherwise the rkyv macros generate code incompatible with rust-2024 +#![cfg_attr(feature = "rkyv-serialize", allow(unsafe_op_in_unsafe_fn))] + use approx::{AbsDiffEq, RelativeEq, UlpsEq}; use std::fmt; use std::hash; diff --git a/src/geometry/isometry_construction.rs b/src/geometry/isometry_construction.rs index 923399484..4f1ca139f 100644 --- a/src/geometry/isometry_construction.rs +++ b/src/geometry/isometry_construction.rs @@ -6,8 +6,8 @@ use quickcheck::{Arbitrary, Gen}; use num::One; #[cfg(feature = "rand-no-std")] use rand::{ - distr::{Distribution, StandardUniform}, Rng, + distr::{Distribution, StandardUniform}, }; use simba::scalar::SupersetOf; diff --git a/src/geometry/isometry_ops.rs b/src/geometry/isometry_ops.rs index fad798d60..4c8b8c915 100644 --- a/src/geometry/isometry_ops.rs +++ b/src/geometry/isometry_ops.rs @@ -7,8 +7,8 @@ use std::ops::{Div, DivAssign, Mul, MulAssign}; use simba::scalar::{ClosedAddAssign, ClosedMulAssign}; use simba::simd::SimdRealField; -use crate::base::{SVector, Unit}; use crate::Scalar; +use crate::base::{SVector, Unit}; use crate::geometry::{ AbstractRotation, Isometry, Point, Rotation, Translation, UnitComplex, UnitQuaternion, @@ -68,7 +68,7 @@ use crate::geometry::{ macro_rules! isometry_binop_impl( ($Op: ident, $op: ident; $lhs: ident: $Lhs: ty, $rhs: ident: $Rhs: ty, Output = $Output: ty; - $action: expr; $($lives: tt),*) => { + $action: expr_2021; $($lives: tt),*) => { impl<$($lives ,)* T: SimdRealField, R, const D: usize> $Op<$Rhs> for $Lhs where T::Element: SimdRealField, R: AbstractRotation, { @@ -85,10 +85,10 @@ macro_rules! isometry_binop_impl( macro_rules! isometry_binop_impl_all( ($Op: ident, $op: ident; $lhs: ident: $Lhs: ty, $rhs: ident: $Rhs: ty, Output = $Output: ty; - [val val] => $action_val_val: expr; - [ref val] => $action_ref_val: expr; - [val ref] => $action_val_ref: expr; - [ref ref] => $action_ref_ref: expr;) => { + [val val] => $action_val_val: expr_2021; + [ref val] => $action_ref_val: expr_2021; + [val ref] => $action_val_ref: expr_2021; + [ref ref] => $action_ref_ref: expr_2021;) => { isometry_binop_impl!( $Op, $op; $lhs: $Lhs, $rhs: $Rhs, Output = $Output; @@ -114,8 +114,8 @@ macro_rules! isometry_binop_impl_all( macro_rules! isometry_binop_assign_impl_all( ($OpAssign: ident, $op_assign: ident; $lhs: ident: $Lhs: ty, $rhs: ident: $Rhs: ty; - [val] => $action_val: expr; - [ref] => $action_ref: expr;) => { + [val] => $action_val: expr_2021; + [ref] => $action_ref: expr_2021;) => { impl $OpAssign<$Rhs> for $Lhs where T::Element: SimdRealField, R: AbstractRotation { @@ -314,7 +314,7 @@ macro_rules! isometry_from_composition_impl( ($Op: ident, $op: ident; $($Dims: ident),*; $lhs: ident: $Lhs: ty, $rhs: ident: $Rhs: ty, Output = $Output: ty; - $action: expr; $($lives: tt),*) => { + $action: expr_2021; $($lives: tt),*) => { impl<$($lives ,)* T: SimdRealField $(, const $Dims: usize)*> $Op<$Rhs> for $Lhs where T::Element: SimdRealField { type Output = $Output; @@ -331,10 +331,10 @@ macro_rules! isometry_from_composition_impl_all( ($Op: ident, $op: ident; $($Dims: ident),*; $lhs: ident: $Lhs: ty, $rhs: ident: $Rhs: ty, Output = $Output: ty; - [val val] => $action_val_val: expr; - [ref val] => $action_ref_val: expr; - [val ref] => $action_val_ref: expr; - [ref ref] => $action_ref_ref: expr;) => { + [val val] => $action_val_val: expr_2021; + [ref val] => $action_ref_val: expr_2021; + [val ref] => $action_val_ref: expr_2021; + [ref ref] => $action_ref_ref: expr_2021;) => { isometry_from_composition_impl!( $Op, $op; diff --git a/src/geometry/isometry_simba.rs b/src/geometry/isometry_simba.rs index 9e4246856..8026e5068 100755 --- a/src/geometry/isometry_simba.rs +++ b/src/geometry/isometry_simba.rs @@ -26,10 +26,12 @@ where #[inline] unsafe fn extract_unchecked(&self, i: usize) -> Self::Element { - Isometry::from_parts( - self.translation.extract_unchecked(i), - self.rotation.extract_unchecked(i), - ) + unsafe { + Isometry::from_parts( + self.translation.extract_unchecked(i), + self.rotation.extract_unchecked(i), + ) + } } #[inline] @@ -40,8 +42,10 @@ where #[inline] unsafe fn replace_unchecked(&mut self, i: usize, val: Self::Element) { - self.translation.replace_unchecked(i, val.translation); - self.rotation.replace_unchecked(i, val.rotation); + unsafe { + self.translation.replace_unchecked(i, val.translation); + self.rotation.replace_unchecked(i, val.rotation); + } } #[inline] diff --git a/src/geometry/op_macros.rs b/src/geometry/op_macros.rs index 4bdcf9914..ff3668fb8 100644 --- a/src/geometry/op_macros.rs +++ b/src/geometry/op_macros.rs @@ -17,7 +17,7 @@ macro_rules! md_impl( // Argument identifiers and types + output. $lhs: ident: $Lhs: ty, $rhs: ident: $Rhs: ty, Output = $Result: ty; // Operator actual implementation. - $action: expr; + $action: expr_2021; // Lifetime. $($lives: tt),*) => { impl<$($lives ,)* T $(, $DimsDecl)* $(, const $D: usize)*> $Op<$Rhs> for $Lhs @@ -51,10 +51,10 @@ macro_rules! md_impl_all( // Argument identifiers and types + output. $lhs: ident: $Lhs: ty, $rhs: ident: $Rhs: ty, Output = $Result: ty; // Operators actual implementations. - [val val] => $action_val_val: expr; - [ref val] => $action_ref_val: expr; - [val ref] => $action_val_ref: expr; - [ref ref] => $action_ref_ref: expr;) => { + [val val] => $action_val_val: expr_2021; + [ref val] => $action_ref_val: expr_2021; + [val ref] => $action_val_ref: expr_2021; + [ref ref] => $action_ref_ref: expr_2021;) => { md_impl!( $Op, $op $(where T: $($ScalarBounds),*)*; @@ -110,7 +110,7 @@ macro_rules! md_assign_impl( // Argument identifiers and types. $lhs: ident: $Lhs: ty, $rhs: ident: $Rhs: ty; // Actual implementation and lifetimes. - $action: expr; $($lives: tt),*) => { + $action: expr_2021; $($lives: tt),*) => { impl<$($lives ,)* T $(, $DimsDecl)* $(, const $D: usize)*> $Op<$Rhs> for $Lhs where T: Scalar + Zero + One + ClosedAddAssign + ClosedMulAssign $($(+ $ScalarBounds)*)*, $($(T::Element: $ElementBounds,)*)* @@ -141,8 +141,8 @@ macro_rules! md_assign_impl_all( // Argument identifiers and types. $lhs: ident: $Lhs: ty, $rhs: ident: $Rhs: ty; // Actual implementation and lifetimes. - [val] => $action_val: expr; - [ref] => $action_ref: expr;) => { + [val] => $action_val: expr_2021; + [ref] => $action_ref: expr_2021;) => { md_assign_impl!( $Op, $op $(where T: $($ScalarBounds),*)* $(for T::Element: $($ElementBounds),*)*; ($R1, $C1),($R2, $C2) @@ -175,7 +175,7 @@ macro_rules! add_sub_impl( // Where clause. where $($ConstraintType: ty: $ConstraintBound: ident$(<$($ConstraintBoundParams: ty $( = $EqBound: ty )*),*>)*),*; $lhs: ident: $Lhs: ty, $rhs: ident: $Rhs: ty, Output = $Result: ty; - $action: expr; $($lives: tt),*) => { + $action: expr_2021; $($lives: tt),*) => { impl<$($lives ,)* T $(, $DimsDecl)* $(, const $D: usize)*> $Op<$Rhs> for $Lhs where T: Scalar + $bound, ShapeConstraint: SameNumberOfRows<$R1, $R2 $(, Representative = $RRes)*> + @@ -197,7 +197,7 @@ macro_rules! add_sub_assign_impl( ($Op: ident, $op: ident, $bound: ident; $(const $D: ident),*; $lhs: ident: $Lhs: ty, $rhs: ident: $Rhs: ty; - $action: expr; $($lives: tt),*) => { + $action: expr_2021; $($lives: tt),*) => { impl<$($lives ,)* T $(, const $D: usize),*> $Op<$Rhs> for $Lhs where T: Scalar + $bound { #[inline] diff --git a/src/geometry/orthographic.rs b/src/geometry/orthographic.rs index 8e6cc82ef..f6f684fdc 100644 --- a/src/geometry/orthographic.rs +++ b/src/geometry/orthographic.rs @@ -1,9 +1,12 @@ +// Needed otherwise the rkyv macros generate code incompatible with rust-2024 +#![cfg_attr(feature = "rkyv-serialize", allow(unsafe_op_in_unsafe_fn))] + #[cfg(feature = "arbitrary")] use quickcheck::{Arbitrary, Gen}; #[cfg(feature = "rand-no-std")] use rand::{ - distr::{Distribution, StandardUniform}, Rng, + distr::{Distribution, StandardUniform}, }; #[cfg(feature = "serde-serialize-no-std")] use serde::{Deserialize, Deserializer, Serialize, Serializer}; diff --git a/src/geometry/perspective.rs b/src/geometry/perspective.rs index 42ea4c8f9..848b9f9c1 100644 --- a/src/geometry/perspective.rs +++ b/src/geometry/perspective.rs @@ -1,9 +1,13 @@ +// Needed otherwise the rkyv macros generate code incompatible with rust-2024 +#![cfg_attr(feature = "rkyv-serialize", allow(unsafe_op_in_unsafe_fn))] + #[cfg(feature = "arbitrary")] use quickcheck::{Arbitrary, Gen}; + #[cfg(feature = "rand-no-std")] use rand::{ - distr::{Distribution, StandardUniform}, Rng, + distr::{Distribution, StandardUniform}, }; #[cfg(feature = "serde-serialize-no-std")] diff --git a/src/geometry/point.rs b/src/geometry/point.rs index 1b54285ea..3f390bb88 100644 --- a/src/geometry/point.rs +++ b/src/geometry/point.rs @@ -1,3 +1,6 @@ +// Needed otherwise the rkyv macros generate code incompatible with rust-2024 +#![cfg_attr(feature = "rkyv-serialize", allow(unsafe_op_in_unsafe_fn))] + use approx::{AbsDiffEq, RelativeEq, UlpsEq}; use num::{One, Zero}; use std::cmp::Ordering; @@ -316,7 +319,7 @@ where #[inline] #[must_use] pub unsafe fn get_unchecked(&self, i: usize) -> &T { - self.coords.vget_unchecked(i) + unsafe { self.coords.vget_unchecked(i) } } /// Mutably iterates through this point coordinates. @@ -347,7 +350,7 @@ where #[inline] #[must_use] pub unsafe fn get_unchecked_mut(&mut self, i: usize) -> &mut T { - self.coords.vget_unchecked_mut(i) + unsafe { self.coords.vget_unchecked_mut(i) } } /// Swaps two entries without bound-checking. @@ -357,7 +360,7 @@ where /// `i1` and `i2` must be less than `self.len()`. #[inline] pub unsafe fn swap_unchecked(&mut self, i1: usize, i2: usize) { - self.coords.swap_unchecked((i1, 0), (i2, 0)) + unsafe { self.coords.swap_unchecked((i1, 0), (i2, 0)) } } } diff --git a/src/geometry/point_alias.rs b/src/geometry/point_alias.rs index f5f855c9e..9a47257f1 100644 --- a/src/geometry/point_alias.rs +++ b/src/geometry/point_alias.rs @@ -1,5 +1,5 @@ -use crate::geometry::OPoint; use crate::Const; +use crate::geometry::OPoint; /// A point with `D` elements. pub type Point = OPoint>; diff --git a/src/geometry/point_construction.rs b/src/geometry/point_construction.rs index baba25f4c..e2268f79d 100644 --- a/src/geometry/point_construction.rs +++ b/src/geometry/point_construction.rs @@ -4,8 +4,8 @@ use quickcheck::{Arbitrary, Gen}; use num::{Bounded, One, Zero}; #[cfg(feature = "rand-no-std")] use rand::{ - distr::{Distribution, StandardUniform}, Rng, + distr::{Distribution, StandardUniform}, }; use crate::base::allocator::Allocator; @@ -209,7 +209,7 @@ impl Point1 { } } macro_rules! componentwise_constructors_impl( - ($($doc: expr; $Point: ident, $Vector: ident, $($args: ident:$irow: expr),*);* $(;)*) => {$( + ($($doc: expr_2021; $Point: ident, $Vector: ident, $($args: ident:$irow: expr_2021),*);* $(;)*) => {$( impl $Point { #[doc = "Initializes this point from its components."] #[doc = "# Example\n```"] diff --git a/src/geometry/point_ops.rs b/src/geometry/point_ops.rs index 44d7aee95..1dce324a4 100644 --- a/src/geometry/point_ops.rs +++ b/src/geometry/point_ops.rs @@ -14,9 +14,9 @@ use crate::base::dimension::{Dim, DimName, U1}; use crate::base::storage::Storage; use crate::base::{Const, Matrix, OVector, Scalar, Vector}; +use crate::DefaultAllocator; use crate::allocator::Allocator; use crate::geometry::{OPoint, Point}; -use crate::DefaultAllocator; /* * diff --git a/src/geometry/point_simba.rs b/src/geometry/point_simba.rs index 8a62919d6..fc1bf5758 100644 --- a/src/geometry/point_simba.rs +++ b/src/geometry/point_simba.rs @@ -24,7 +24,7 @@ where #[inline] unsafe fn extract_unchecked(&self, i: usize) -> Self::Element { - self.coords.extract_unchecked(i).into() + unsafe { self.coords.extract_unchecked(i).into() } } #[inline] @@ -34,7 +34,7 @@ where #[inline] unsafe fn replace_unchecked(&mut self, i: usize, val: Self::Element) { - self.coords.replace_unchecked(i, val.coords) + unsafe { self.coords.replace_unchecked(i, val.coords) } } #[inline] diff --git a/src/geometry/quaternion.rs b/src/geometry/quaternion.rs index 160cb5455..2f6312775 100644 --- a/src/geometry/quaternion.rs +++ b/src/geometry/quaternion.rs @@ -1,3 +1,6 @@ +// Needed otherwise the rkyv macros generate code incompatible with rust-2024 +#![cfg_attr(feature = "rkyv-serialize", allow(unsafe_op_in_unsafe_fn))] + use approx::{AbsDiffEq, RelativeEq, UlpsEq}; use num::Zero; use std::fmt; @@ -468,16 +471,16 @@ where where T: RealField, { - if let Some((q, n)) = Unit::try_new_and_get(self.clone(), T::zero()) { - if let Some(axis) = Unit::try_new(self.vector().clone_owned(), T::zero()) { - let angle = q.angle() / crate::convert(2.0f64); - - (n, angle, Some(axis)) - } else { - (n, T::zero(), None) - } - } else { - (T::zero(), T::zero(), None) + match Unit::try_new_and_get(self.clone(), T::zero()) { + Some((q, n)) => match Unit::try_new(self.vector().clone_owned(), T::zero()) { + Some(axis) => { + let angle = q.angle() / crate::convert(2.0f64); + + (n, angle, Some(axis)) + } + None => (n, T::zero(), None), + }, + None => (T::zero(), T::zero(), None), } } @@ -1227,7 +1230,7 @@ where /// * `other`: the second quaternion to interpolate toward. /// * `t`: the interpolation parameter. Should be between 0 and 1. /// * `epsilon`: the value below which the sinus of the angle separating both quaternion - /// must be to return `None`. + /// must be to return `None`. #[inline] #[must_use] pub fn try_slerp(&self, other: &Self, t: T, epsilon: T) -> Option @@ -1319,10 +1322,9 @@ where where T: RealField, { - if let Some(axis) = self.axis() { - axis.into_inner() * self.angle() - } else { - Vector3::zero() + match self.axis() { + Some(axis) => axis.into_inner() * self.angle(), + None => Vector3::zero(), } } @@ -1380,10 +1382,9 @@ where where T: RealField, { - if let Some(v) = self.axis() { - Quaternion::from_imag(v.into_inner() * self.angle()) - } else { - Quaternion::zero() + match self.axis() { + Some(v) => Quaternion::from_imag(v.into_inner() * self.angle()), + None => Quaternion::zero(), } } @@ -1409,10 +1410,9 @@ where where T: RealField, { - if let Some(v) = self.axis() { - Self::from_axis_angle(&v, self.angle() * n) - } else { - Self::identity() + match self.axis() { + Some(v) => Self::from_axis_angle(&v, self.angle() * n), + None => Self::identity(), } } @@ -1642,22 +1642,25 @@ impl Default for UnitQuaternion { impl fmt::Display for UnitQuaternion { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { - if let Some(axis) = self.axis() { - let axis = axis.into_inner(); - write!( - f, - "UnitQuaternion angle: {} − axis: ({}, {}, {})", - self.angle(), - axis[0], - axis[1], - axis[2] - ) - } else { - write!( - f, - "UnitQuaternion angle: {} − axis: (undefined)", - self.angle() - ) + match self.axis() { + Some(axis) => { + let axis = axis.into_inner(); + write!( + f, + "UnitQuaternion angle: {} − axis: ({}, {}, {})", + self.angle(), + axis[0], + axis[1], + axis[2] + ) + } + None => { + write!( + f, + "UnitQuaternion angle: {} − axis: (undefined)", + self.angle() + ) + } } } } diff --git a/src/geometry/quaternion_construction.rs b/src/geometry/quaternion_construction.rs index 50d1e8ac1..46451d544 100644 --- a/src/geometry/quaternion_construction.rs +++ b/src/geometry/quaternion_construction.rs @@ -7,8 +7,8 @@ use quickcheck::{Arbitrary, Gen}; #[cfg(feature = "rand-no-std")] use rand::{ - distr::{uniform::SampleUniform, Distribution, OpenClosed01, StandardUniform, Uniform}, Rng, + distr::{Distribution, OpenClosed01, StandardUniform, Uniform, uniform::SampleUniform}, }; use num::{One, Zero}; @@ -427,8 +427,8 @@ where /// * `eps`: the angular errors tolerated between the current rotation and the optimal one. /// * `max_iter`: the maximum number of iterations. Loops indefinitely until convergence if set to `0`. /// * `guess`: an estimate of the solution. Convergence will be significantly faster if an initial solution close - /// to the actual solution is provided. Can be set to `UnitQuaternion::identity()` if no other - /// guesses come to mind. + /// to the actual solution is provided. Can be set to `UnitQuaternion::identity()` if no other + /// guesses come to mind. pub fn from_matrix_eps(m: &Matrix3, eps: T, max_iter: usize, guess: Self) -> Self where T: RealField, @@ -487,13 +487,12 @@ where SC: Storage, { // TODO: code duplication with Rotation. - if let (Some(na), Some(nb)) = ( + match ( Unit::try_new(a.clone_owned(), T::zero()), Unit::try_new(b.clone_owned(), T::zero()), ) { - Self::scaled_rotation_between_axis(&na, &nb, s) - } else { - Some(Self::identity()) + (Some(na), Some(nb)) => Self::scaled_rotation_between_axis(&na, &nb, s), + _ => Some(Self::identity()), } } @@ -551,26 +550,31 @@ where // TODO: code duplication with Rotation. let c = na.cross(nb); - if let Some(axis) = Unit::try_new(c, T::default_epsilon()) { - let cos = na.dot(nb); - - // The cosinus may be out of [-1, 1] because of inaccuracies. - if cos <= -T::one() { - None - } else if cos >= T::one() { - Some(Self::identity()) - } else { - Some(Self::from_axis_angle(&axis, cos.acos() * s)) + match Unit::try_new(c, T::default_epsilon()) { + Some(axis) => { + let cos = na.dot(nb); + + // The cosinus may be out of [-1, 1] because of inaccuracies. + if cos <= -T::one() { + None + } else if cos >= T::one() { + Some(Self::identity()) + } else { + Some(Self::from_axis_angle(&axis, cos.acos() * s)) + } + } + None => { + if na.dot(nb) < T::zero() { + // PI + // + // The rotation axis is undefined but the angle not zero. This is not a + // simple rotation. + None + } else { + // Zero + Some(Self::identity()) + } } - } else if na.dot(nb) < T::zero() { - // PI - // - // The rotation axis is undefined but the angle not zero. This is not a - // simple rotation. - None - } else { - // Zero - Some(Self::identity()) } } diff --git a/src/geometry/quaternion_coordinates.rs b/src/geometry/quaternion_coordinates.rs index cb16e59ee..4cd2f0bd3 100644 --- a/src/geometry/quaternion_coordinates.rs +++ b/src/geometry/quaternion_coordinates.rs @@ -2,8 +2,8 @@ use std::ops::{Deref, DerefMut}; use simba::simd::SimdValue; -use crate::base::coordinates::IJKW; use crate::Scalar; +use crate::base::coordinates::IJKW; use crate::geometry::Quaternion; diff --git a/src/geometry/quaternion_ops.rs b/src/geometry/quaternion_ops.rs index 081873ba8..13e813bf7 100644 --- a/src/geometry/quaternion_ops.rs +++ b/src/geometry/quaternion_ops.rs @@ -57,10 +57,10 @@ use std::ops::{ Add, AddAssign, Div, DivAssign, Index, IndexMut, Mul, MulAssign, Neg, Sub, SubAssign, }; +use crate::SimdRealField; use crate::base::dimension::U3; use crate::base::storage::Storage; use crate::base::{Const, Scalar, Unit, Vector, Vector3}; -use crate::SimdRealField; use crate::geometry::{Point3, Quaternion, Rotation, UnitQuaternion}; @@ -84,7 +84,7 @@ macro_rules! quaternion_op_impl( ($Op: ident, $op: ident; $($Storage: ident: $StoragesBound: ident $(<$($BoundParam: ty),*>)*),*; $lhs: ident: $Lhs: ty, $rhs: ident: $Rhs: ty, Output = $Result: ty; - $action: expr; $($lives: tt),*) => { + $action: expr_2021; $($lives: tt),*) => { impl<$($lives ,)* T: SimdRealField $(, $Storage: $StoragesBound $(<$($BoundParam),*>)*)*> $Op<$Rhs> for $Lhs where T::Element: SimdRealField { type Output = $Result; @@ -564,7 +564,7 @@ where macro_rules! quaternion_op_impl( ($OpAssign: ident, $op_assign: ident; $lhs: ident: $Lhs: ty, $rhs: ident: $Rhs: ty $(=> $VDimA: ty, $VDimB: ty)*; - $action: expr; $($lives: tt),*) => { + $action: expr_2021; $($lives: tt),*) => { impl<$($lives ,)* T: SimdRealField> $OpAssign<$Rhs> for $Lhs where T::Element: SimdRealField { diff --git a/src/geometry/quaternion_simba.rs b/src/geometry/quaternion_simba.rs index 3bfab80b1..501a07a5e 100755 --- a/src/geometry/quaternion_simba.rs +++ b/src/geometry/quaternion_simba.rs @@ -1,8 +1,8 @@ use simba::simd::SimdValue; +use crate::Scalar; use crate::base::Vector4; use crate::geometry::{Quaternion, UnitQuaternion}; -use crate::Scalar; impl SimdValue for Quaternion where @@ -24,7 +24,7 @@ where #[inline] unsafe fn extract_unchecked(&self, i: usize) -> Self::Element { - self.coords.extract_unchecked(i).into() + unsafe { self.coords.extract_unchecked(i).into() } } #[inline] @@ -34,7 +34,7 @@ where #[inline] unsafe fn replace_unchecked(&mut self, i: usize, val: Self::Element) { - self.coords.replace_unchecked(i, val.coords) + unsafe { self.coords.replace_unchecked(i, val.coords) } } #[inline] @@ -63,7 +63,7 @@ where #[inline] unsafe fn extract_unchecked(&self, i: usize) -> Self::Element { - UnitQuaternion::new_unchecked(self.as_ref().extract_unchecked(i)) + unsafe { UnitQuaternion::new_unchecked(self.as_ref().extract_unchecked(i)) } } #[inline] @@ -73,8 +73,10 @@ where #[inline] unsafe fn replace_unchecked(&mut self, i: usize, val: Self::Element) { - self.as_mut_unchecked() - .replace_unchecked(i, val.into_inner()) + unsafe { + self.as_mut_unchecked() + .replace_unchecked(i, val.into_inner()) + } } #[inline] diff --git a/src/geometry/reflection_alias.rs b/src/geometry/reflection_alias.rs index 14f55a3a0..a771330e9 100644 --- a/src/geometry/reflection_alias.rs +++ b/src/geometry/reflection_alias.rs @@ -1,6 +1,6 @@ +use crate::Const; use crate::base::ArrayStorage; use crate::geometry::Reflection; -use crate::Const; /// A 1-dimensional reflection. pub type Reflection1 = Reflection, ArrayStorage>; diff --git a/src/geometry/rotation.rs b/src/geometry/rotation.rs index 4e90ff7a0..4407e23a7 100644 --- a/src/geometry/rotation.rs +++ b/src/geometry/rotation.rs @@ -1,3 +1,6 @@ +// Needed otherwise the rkyv macros generate code incompatible with rust-2024 +#![cfg_attr(feature = "rkyv-serialize", allow(unsafe_op_in_unsafe_fn))] + use approx::{AbsDiffEq, RelativeEq, UlpsEq}; use num::{One, Zero}; use std::fmt; diff --git a/src/geometry/rotation_simba.rs b/src/geometry/rotation_simba.rs index 7802f1d59..a3dc04d44 100755 --- a/src/geometry/rotation_simba.rs +++ b/src/geometry/rotation_simba.rs @@ -25,7 +25,7 @@ where #[inline] unsafe fn extract_unchecked(&self, i: usize) -> Self::Element { - Rotation::from_matrix_unchecked(self.matrix().extract_unchecked(i)) + unsafe { Rotation::from_matrix_unchecked(self.matrix().extract_unchecked(i)) } } #[inline] @@ -35,8 +35,10 @@ where #[inline] unsafe fn replace_unchecked(&mut self, i: usize, val: Self::Element) { - self.matrix_mut_unchecked() - .replace_unchecked(i, val.into_inner()) + unsafe { + self.matrix_mut_unchecked() + .replace_unchecked(i, val.into_inner()) + } } #[inline] diff --git a/src/geometry/rotation_specialization.rs b/src/geometry/rotation_specialization.rs index d814081fd..9eb93abb4 100644 --- a/src/geometry/rotation_specialization.rs +++ b/src/geometry/rotation_specialization.rs @@ -7,8 +7,8 @@ use num::Zero; #[cfg(feature = "rand-no-std")] use rand::{ - distr::{uniform::SampleUniform, Distribution, OpenClosed01, StandardUniform, Uniform}, Rng, + distr::{Distribution, OpenClosed01, StandardUniform, Uniform, uniform::SampleUniform}, }; use simba::scalar::RealField; @@ -93,8 +93,8 @@ impl Rotation2 { /// * `eps`: the angular errors tolerated between the current rotation and the optimal one. /// * `max_iter`: the maximum number of iterations. Loops indefinitely until convergence if set to `0`. /// * `guess`: an estimate of the solution. Convergence will be significantly faster if an initial solution close - /// to the actual solution is provided. Can be set to `Rotation2::identity()` if no other - /// guesses come to mind. + /// to the actual solution is provided. Can be set to `Rotation2::identity()` if no other + /// guesses come to mind. pub fn from_matrix_eps(m: &Matrix2, eps: T, mut max_iter: usize, guess: Self) -> Self where T: RealField, @@ -685,13 +685,16 @@ where where T: RealField, { - if let Some(axis) = self.axis() { - Self::from_axis_angle(&axis, self.angle() * n) - } else if self.matrix()[(0, 0)] < T::zero() { - let minus_id = SMatrix::::from_diagonal_element(-T::one()); - Self::from_matrix_unchecked(minus_id) - } else { - Self::identity() + match self.axis() { + Some(axis) => Self::from_axis_angle(&axis, self.angle() * n), + None => { + if self.matrix()[(0, 0)] < T::zero() { + let minus_id = SMatrix::::from_diagonal_element(-T::one()); + Self::from_matrix_unchecked(minus_id) + } else { + Self::identity() + } + } } } @@ -728,8 +731,8 @@ where /// * `eps`: the angular errors tolerated between the current rotation and the optimal one. /// * `max_iter`: the maximum number of iterations. Loops indefinitely until convergence if set to `0`. /// * `guess`: a guess of the solution. Convergence will be significantly faster if an initial solution close - /// to the actual solution is provided. Can be set to `Rotation3::identity()` if no other - /// guesses come to mind. + /// to the actual solution is provided. Can be set to `Rotation3::identity()` if no other + /// guesses come to mind. pub fn from_matrix_eps(m: &Matrix3, eps: T, mut max_iter: usize, guess: Self) -> Self where T: RealField, @@ -753,36 +756,39 @@ where let axisangle = axis / (denom.abs() + T::default_epsilon()); - if let Some((axis, angle)) = Unit::try_new_and_get(axisangle, eps.clone()) { - rot = Rotation3::from_axis_angle(&axis, angle) * rot; - } else { - // Check if stuck in a maximum w.r.t. the norm (m - rot).norm() - let mut perturbed = rot.clone(); - let norm_squared = (m - &rot).norm_squared(); - let mut new_norm_squared: T; - - // Perturb until the new norm is significantly different - loop { - perturbed *= - Rotation3::from_axis_angle(&perturbation_axes, eps_disturbance.clone()); - new_norm_squared = (m - &perturbed).norm_squared(); - if abs_diff_ne!( - norm_squared, - new_norm_squared, - epsilon = T::default_epsilon() - ) { + match Unit::try_new_and_get(axisangle, eps.clone()) { + Some((axis, angle)) => { + rot = Rotation3::from_axis_angle(&axis, angle) * rot; + } + None => { + // Check if stuck in a maximum w.r.t. the norm (m - rot).norm() + let mut perturbed = rot.clone(); + let norm_squared = (m - &rot).norm_squared(); + let mut new_norm_squared: T; + + // Perturb until the new norm is significantly different + loop { + perturbed *= + Rotation3::from_axis_angle(&perturbation_axes, eps_disturbance.clone()); + new_norm_squared = (m - &perturbed).norm_squared(); + if abs_diff_ne!( + norm_squared, + new_norm_squared, + epsilon = T::default_epsilon() + ) { + break; + } + } + + // If new norm is larger, it's a minimum + if norm_squared < new_norm_squared { break; } - } - // If new norm is larger, it's a minimum - if norm_squared < new_norm_squared { - break; + // If not, continue from perturbed rotation, but use a different axes for the next perturbation + perturbation_axes = UnitVector3::new_unchecked(perturbation_axes.yzx()); + rot = perturbed; } - - // If not, continue from perturbed rotation, but use a different axes for the next perturbation - perturbation_axes = UnitVector3::new_unchecked(perturbation_axes.yzx()); - rot = perturbed; } } @@ -873,10 +879,9 @@ impl Rotation3 { where T: RealField, { - if let Some(axis) = self.axis() { - axis.into_inner() * self.angle() - } else { - Vector::zero() + match self.axis() { + Some(axis) => axis.into_inner() * self.angle(), + None => Vector::zero(), } } diff --git a/src/geometry/scale.rs b/src/geometry/scale.rs index 10f1bb9bd..541cd3933 100644 --- a/src/geometry/scale.rs +++ b/src/geometry/scale.rs @@ -1,3 +1,6 @@ +// Needed otherwise the rkyv macros generate code incompatible with rust-2024 +#![cfg_attr(feature = "rkyv-serialize", allow(unsafe_op_in_unsafe_fn))] + use approx::{AbsDiffEq, RelativeEq, UlpsEq}; use num::{One, Zero}; use std::fmt; @@ -6,12 +9,12 @@ use std::hash; #[cfg(feature = "serde-serialize-no-std")] use serde::{Deserialize, Deserializer, Serialize, Serializer}; +use crate::ClosedDivAssign; +use crate::ClosedMulAssign; use crate::base::allocator::Allocator; use crate::base::dimension::{DimNameAdd, DimNameSum, U1}; use crate::base::storage::Owned; use crate::base::{Const, DefaultAllocator, OMatrix, OVector, SVector, Scalar}; -use crate::ClosedDivAssign; -use crate::ClosedMulAssign; use crate::geometry::Point; @@ -262,11 +265,12 @@ impl Scale { where T: ClosedDivAssign + One + Zero, { - if let Some(v) = self.try_inverse() { - self.vector = v.vector; - true - } else { - false + match self.try_inverse() { + Some(v) => { + self.vector = v.vector; + true + } + None => false, } } } diff --git a/src/geometry/scale_construction.rs b/src/geometry/scale_construction.rs index 597dc639e..d1f720a50 100644 --- a/src/geometry/scale_construction.rs +++ b/src/geometry/scale_construction.rs @@ -6,8 +6,8 @@ use quickcheck::{Arbitrary, Gen}; use num::One; #[cfg(feature = "rand-no-std")] use rand::{ - distr::{Distribution, StandardUniform}, Rng, + distr::{Distribution, StandardUniform}, }; use simba::scalar::{ClosedMulAssign, SupersetOf}; @@ -92,7 +92,7 @@ where * */ macro_rules! componentwise_constructors_impl( - ($($doc: expr; $D: expr, $($args: ident:$irow: expr),*);* $(;)*) => {$( + ($($doc: expr_2021; $D: expr_2021, $($args: ident:$irow: expr_2021),*);* $(;)*) => {$( impl Scale { #[doc = "Initializes this Scale from its components."] diff --git a/src/geometry/scale_conversion.rs b/src/geometry/scale_conversion.rs index bf1b06474..926456f5f 100644 --- a/src/geometry/scale_conversion.rs +++ b/src/geometry/scale_conversion.rs @@ -7,8 +7,8 @@ use crate::base::allocator::Allocator; use crate::base::dimension::{DimNameAdd, DimNameSum, U1}; use crate::base::{Const, DefaultAllocator, OMatrix, OVector, SVector, Scalar}; -use crate::geometry::{Scale, SuperTCategoryOf, TAffine, Transform}; use crate::Point; +use crate::geometry::{Scale, SuperTCategoryOf, TAffine, Transform}; /* * This file provides the following conversions: diff --git a/src/geometry/scale_coordinates.rs b/src/geometry/scale_coordinates.rs index 5158c62de..b11c49f6d 100644 --- a/src/geometry/scale_coordinates.rs +++ b/src/geometry/scale_coordinates.rs @@ -1,7 +1,7 @@ use std::ops::{Deref, DerefMut}; -use crate::base::coordinates::{X, XY, XYZ, XYZW, XYZWA, XYZWAB}; use crate::base::Scalar; +use crate::base::coordinates::{X, XY, XYZ, XYZW, XYZWA, XYZWAB}; use crate::geometry::Scale; @@ -12,7 +12,7 @@ use crate::geometry::Scale; */ macro_rules! deref_impl( - ($D: expr, $Target: ident $(, $comps: ident)*) => { + ($D: expr_2021, $Target: ident $(, $comps: ident)*) => { impl Deref for Scale { type Target = $Target; diff --git a/src/geometry/scale_simba.rs b/src/geometry/scale_simba.rs index 8f15d20cb..3cd1e6734 100755 --- a/src/geometry/scale_simba.rs +++ b/src/geometry/scale_simba.rs @@ -1,7 +1,7 @@ use simba::simd::SimdValue; -use crate::base::OVector; use crate::Scalar; +use crate::base::OVector; use crate::geometry::Scale; @@ -25,7 +25,7 @@ where #[inline] unsafe fn extract_unchecked(&self, i: usize) -> Self::Element { - self.vector.extract_unchecked(i).into() + unsafe { self.vector.extract_unchecked(i).into() } } #[inline] @@ -35,7 +35,7 @@ where #[inline] unsafe fn replace_unchecked(&mut self, i: usize, val: Self::Element) { - self.vector.replace_unchecked(i, val.vector) + unsafe { self.vector.replace_unchecked(i, val.vector) } } #[inline] diff --git a/src/geometry/similarity.rs b/src/geometry/similarity.rs index 66ab6ac76..339b5f199 100644 --- a/src/geometry/similarity.rs +++ b/src/geometry/similarity.rs @@ -1,3 +1,6 @@ +// Needed otherwise the rkyv macros generate code incompatible with rust-2024 +#![cfg_attr(feature = "rkyv-serialize", allow(unsafe_op_in_unsafe_fn))] + use approx::{AbsDiffEq, RelativeEq, UlpsEq}; use num::Zero; use std::fmt; diff --git a/src/geometry/similarity_construction.rs b/src/geometry/similarity_construction.rs index 005ceade1..f15efcb0c 100644 --- a/src/geometry/similarity_construction.rs +++ b/src/geometry/similarity_construction.rs @@ -6,8 +6,8 @@ use quickcheck::{Arbitrary, Gen}; use num::One; #[cfg(feature = "rand-no-std")] use rand::{ - distr::{Distribution, StandardUniform}, Rng, + distr::{Distribution, StandardUniform}, }; use simba::scalar::SupersetOf; diff --git a/src/geometry/similarity_ops.rs b/src/geometry/similarity_ops.rs index b87f17e26..2a0946977 100644 --- a/src/geometry/similarity_ops.rs +++ b/src/geometry/similarity_ops.rs @@ -70,7 +70,7 @@ use crate::geometry::{ macro_rules! similarity_binop_impl( ($Op: ident, $op: ident; $lhs: ident: $Lhs: ty, $rhs: ident: $Rhs: ty, Output = $Output: ty; - $action: expr; $($lives: tt),*) => { + $action: expr_2021; $($lives: tt),*) => { impl<$($lives ,)* T: SimdRealField, R, const D: usize> $Op<$Rhs> for $Lhs where T::Element: SimdRealField, R: AbstractRotation { @@ -87,10 +87,10 @@ macro_rules! similarity_binop_impl( macro_rules! similarity_binop_impl_all( ($Op: ident, $op: ident; $lhs: ident: $Lhs: ty, $rhs: ident: $Rhs: ty, Output = $Output: ty; - [val val] => $action_val_val: expr; - [ref val] => $action_ref_val: expr; - [val ref] => $action_val_ref: expr; - [ref ref] => $action_ref_ref: expr;) => { + [val val] => $action_val_val: expr_2021; + [ref val] => $action_ref_val: expr_2021; + [val ref] => $action_val_ref: expr_2021; + [ref ref] => $action_ref_ref: expr_2021;) => { similarity_binop_impl!( $Op, $op; $lhs: $Lhs, $rhs: $Rhs, Output = $Output; @@ -116,8 +116,8 @@ macro_rules! similarity_binop_impl_all( macro_rules! similarity_binop_assign_impl_all( ($OpAssign: ident, $op_assign: ident; $lhs: ident: $Lhs: ty, $rhs: ident: $Rhs: ty; - [val] => $action_val: expr; - [ref] => $action_ref: expr;) => { + [val] => $action_val: expr_2021; + [ref] => $action_ref: expr_2021;) => { impl $OpAssign<$Rhs> for $Lhs where T::Element: SimdRealField, R: AbstractRotation{ @@ -395,7 +395,7 @@ macro_rules! similarity_from_composition_impl( ($Op: ident, $op: ident; $($Dims: ident),*; $lhs: ident: $Lhs: ty, $rhs: ident: $Rhs: ty, Output = $Output: ty; - $action: expr; $($lives: tt),*) => { + $action: expr_2021; $($lives: tt),*) => { impl<$($lives ,)* T: SimdRealField $(, const $Dims: usize)*> $Op<$Rhs> for $Lhs where T::Element: SimdRealField { type Output = $Output; @@ -412,10 +412,10 @@ macro_rules! similarity_from_composition_impl_all( ($Op: ident, $op: ident; $($Dims: ident),*; $lhs: ident: $Lhs: ty, $rhs: ident: $Rhs: ty, Output = $Output: ty; - [val val] => $action_val_val: expr; - [ref val] => $action_ref_val: expr; - [val ref] => $action_val_ref: expr; - [ref ref] => $action_ref_ref: expr;) => { + [val val] => $action_val_val: expr_2021; + [ref val] => $action_ref_val: expr_2021; + [val ref] => $action_val_ref: expr_2021; + [ref ref] => $action_ref_ref: expr_2021;) => { similarity_from_composition_impl!( $Op, $op; diff --git a/src/geometry/similarity_simba.rs b/src/geometry/similarity_simba.rs index dec746cf3..6de5a6914 100755 --- a/src/geometry/similarity_simba.rs +++ b/src/geometry/similarity_simba.rs @@ -25,10 +25,12 @@ where #[inline] unsafe fn extract_unchecked(&self, i: usize) -> Self::Element { - Similarity::from_isometry( - self.isometry.extract_unchecked(i), - self.scaling().extract_unchecked(i), - ) + unsafe { + Similarity::from_isometry( + self.isometry.extract_unchecked(i), + self.scaling().extract_unchecked(i), + ) + } } #[inline] @@ -41,10 +43,12 @@ where #[inline] unsafe fn replace_unchecked(&mut self, i: usize, val: Self::Element) { - let mut s = self.scaling(); - s.replace_unchecked(i, val.scaling()); - self.set_scaling(s); - self.isometry.replace_unchecked(i, val.isometry); + unsafe { + let mut s = self.scaling(); + s.replace_unchecked(i, val.scaling()); + self.set_scaling(s); + self.isometry.replace_unchecked(i, val.isometry); + } } #[inline] diff --git a/src/geometry/swizzle.rs b/src/geometry/swizzle.rs index f8f9f6d52..ce2116ca8 100644 --- a/src/geometry/swizzle.rs +++ b/src/geometry/swizzle.rs @@ -3,7 +3,7 @@ use crate::geometry::{Point, Point2, Point3}; use typenum::{self, Cmp, Greater}; macro_rules! impl_swizzle { - ($( where $BaseDim: ident: $( $name: ident() -> $Result: ident[$($i: expr),+] ),+ ;)* ) => { + ($( where $BaseDim: ident: $( $name: ident() -> $Result: ident[$($i: expr_2021),+] ),+ ;)* ) => { $( $( /// Builds a new point from components of `self`. diff --git a/src/geometry/transform_simba.rs b/src/geometry/transform_simba.rs index 5d66d1d36..a9bb3bcf1 100755 --- a/src/geometry/transform_simba.rs +++ b/src/geometry/transform_simba.rs @@ -1,9 +1,9 @@ use simba::simd::SimdValue; +use crate::RealField; use crate::base::allocator::Allocator; use crate::base::dimension::{DimNameAdd, DimNameSum, U1}; use crate::base::{Const, DefaultAllocator, OMatrix, Scalar}; -use crate::RealField; use crate::geometry::{TCategory, Transform}; @@ -30,7 +30,7 @@ where #[inline] unsafe fn extract_unchecked(&self, i: usize) -> Self::Element { - Transform::from_matrix_unchecked(self.matrix().extract_unchecked(i)) + unsafe { Transform::from_matrix_unchecked(self.matrix().extract_unchecked(i)) } } #[inline] @@ -40,8 +40,10 @@ where #[inline] unsafe fn replace_unchecked(&mut self, i: usize, val: Self::Element) { - self.matrix_mut_unchecked() - .replace_unchecked(i, val.into_inner()) + unsafe { + self.matrix_mut_unchecked() + .replace_unchecked(i, val.into_inner()) + } } #[inline] diff --git a/src/geometry/translation.rs b/src/geometry/translation.rs index 074a551aa..5fc4321bc 100644 --- a/src/geometry/translation.rs +++ b/src/geometry/translation.rs @@ -1,3 +1,6 @@ +// Needed otherwise the rkyv macros generate code incompatible with rust-2024 +#![cfg_attr(feature = "rkyv-serialize", allow(unsafe_op_in_unsafe_fn))] + use approx::{AbsDiffEq, RelativeEq, UlpsEq}; use num::{One, Zero}; use std::fmt; diff --git a/src/geometry/translation_construction.rs b/src/geometry/translation_construction.rs index 8e356aa43..4d132fd85 100644 --- a/src/geometry/translation_construction.rs +++ b/src/geometry/translation_construction.rs @@ -6,8 +6,8 @@ use quickcheck::{Arbitrary, Gen}; use num::{One, Zero}; #[cfg(feature = "rand-no-std")] use rand::{ - distr::{Distribution, StandardUniform}, Rng, + distr::{Distribution, StandardUniform}, }; use simba::scalar::{ClosedAddAssign, SupersetOf}; @@ -98,7 +98,7 @@ where * */ macro_rules! componentwise_constructors_impl( - ($($doc: expr; $D: expr, $($args: ident:$irow: expr),*);* $(;)*) => {$( + ($($doc: expr_2021; $D: expr_2021, $($args: ident:$irow: expr_2021),*);* $(;)*) => {$( impl Translation { #[doc = "Initializes this translation from its components."] diff --git a/src/geometry/translation_coordinates.rs b/src/geometry/translation_coordinates.rs index 80267e060..8cdf44b2d 100644 --- a/src/geometry/translation_coordinates.rs +++ b/src/geometry/translation_coordinates.rs @@ -1,7 +1,7 @@ use std::ops::{Deref, DerefMut}; -use crate::base::coordinates::{X, XY, XYZ, XYZW, XYZWA, XYZWAB}; use crate::base::Scalar; +use crate::base::coordinates::{X, XY, XYZ, XYZW, XYZWA, XYZWAB}; use crate::geometry::Translation; @@ -12,7 +12,7 @@ use crate::geometry::Translation; */ macro_rules! deref_impl( - ($D: expr, $Target: ident $(, $comps: ident)*) => { + ($D: expr_2021, $Target: ident $(, $comps: ident)*) => { impl Deref for Translation { type Target = $Target; diff --git a/src/geometry/translation_simba.rs b/src/geometry/translation_simba.rs index a4df7799b..a96394c33 100755 --- a/src/geometry/translation_simba.rs +++ b/src/geometry/translation_simba.rs @@ -1,7 +1,7 @@ use simba::simd::SimdValue; -use crate::base::OVector; use crate::Scalar; +use crate::base::OVector; use crate::geometry::Translation; @@ -25,7 +25,7 @@ where #[inline] unsafe fn extract_unchecked(&self, i: usize) -> Self::Element { - self.vector.extract_unchecked(i).into() + unsafe { self.vector.extract_unchecked(i).into() } } #[inline] @@ -35,7 +35,7 @@ where #[inline] unsafe fn replace_unchecked(&mut self, i: usize, val: Self::Element) { - self.vector.replace_unchecked(i, val.vector) + unsafe { self.vector.replace_unchecked(i, val.vector) } } #[inline] diff --git a/src/geometry/unit_complex.rs b/src/geometry/unit_complex.rs index a04df89bb..11bb06b84 100755 --- a/src/geometry/unit_complex.rs +++ b/src/geometry/unit_complex.rs @@ -2,9 +2,9 @@ use approx::{AbsDiffEq, RelativeEq, UlpsEq}; use num_complex::Complex; use std::fmt; +use crate::Scalar; use crate::base::{Matrix2, Matrix3, Normed, Unit, Vector1, Vector2}; use crate::geometry::{Point2, Rotation2}; -use crate::Scalar; use simba::scalar::RealField; use simba::simd::SimdRealField; use std::cmp::{Eq, PartialEq}; diff --git a/src/geometry/unit_complex_construction.rs b/src/geometry/unit_complex_construction.rs index 961314e77..c83506d1e 100644 --- a/src/geometry/unit_complex_construction.rs +++ b/src/geometry/unit_complex_construction.rs @@ -3,8 +3,8 @@ use quickcheck::{Arbitrary, Gen}; #[cfg(feature = "rand-no-std")] use rand::{ - distr::{Distribution, StandardUniform}, Rng, + distr::{Distribution, StandardUniform}, }; use num::One; @@ -229,8 +229,8 @@ where /// * `eps`: the angular errors tolerated between the current rotation and the optimal one. /// * `max_iter`: the maximum number of iterations. Loops indefinitely until convergence if set to `0`. /// * `guess`: an estimate of the solution. Convergence will be significantly faster if an initial solution close - /// to the actual solution is provided. Can be set to `UnitQuaternion::identity()` if no other - /// guesses come to mind. + /// to the actual solution is provided. Can be set to `UnitQuaternion::identity()` if no other + /// guesses come to mind. pub fn from_matrix_eps(m: &Matrix2, eps: T, max_iter: usize, guess: Self) -> Self where T: RealField, @@ -334,13 +334,12 @@ where SC: Storage, { // TODO: code duplication with Rotation. - if let (Some(na), Some(nb)) = ( + match ( Unit::try_new(a.clone_owned(), T::zero()), Unit::try_new(b.clone_owned(), T::zero()), ) { - Self::scaled_rotation_between_axis(&na, &nb, s) - } else { - Self::identity() + (Some(na), Some(nb)) => Self::scaled_rotation_between_axis(&na, &nb, s), + _ => Self::identity(), } } diff --git a/src/geometry/unit_complex_ops.rs b/src/geometry/unit_complex_ops.rs index fe486393e..48215b038 100644 --- a/src/geometry/unit_complex_ops.rs +++ b/src/geometry/unit_complex_ops.rs @@ -145,7 +145,7 @@ macro_rules! complex_op_impl( ($Op: ident, $op: ident; $($Storage: ident: $StoragesBound: ident $(<$($BoundParam: ty),*>)*),*; $lhs: ident: $Lhs: ty, $rhs: ident: $Rhs: ty, Output = $Result: ty; - $action: expr; $($lives: tt),*) => { + $action: expr_2021; $($lives: tt),*) => { impl<$($lives ,)* T: SimdRealField $(, $Storage: $StoragesBound $(<$($BoundParam),*>)*)*> $Op<$Rhs> for $Lhs where T::Element: SimdRealField { type Output = $Result; @@ -162,10 +162,10 @@ macro_rules! complex_op_impl_all( ($Op: ident, $op: ident; $($Storage: ident: $StoragesBound: ident $(<$($BoundParam: ty),*>)*),*; $lhs: ident: $Lhs: ty, $rhs: ident: $Rhs: ty, Output = $Result: ty; - [val val] => $action_val_val: expr; - [ref val] => $action_ref_val: expr; - [val ref] => $action_val_ref: expr; - [ref ref] => $action_ref_ref: expr;) => { + [val val] => $action_val_val: expr_2021; + [ref val] => $action_ref_val: expr_2021; + [val ref] => $action_val_ref: expr_2021; + [ref ref] => $action_ref_ref: expr_2021;) => { complex_op_impl!($Op, $op; $($Storage: $StoragesBound $(<$($BoundParam),*>)*),*; diff --git a/src/geometry/unit_complex_simba.rs b/src/geometry/unit_complex_simba.rs index 14d89ec57..7c24ac121 100755 --- a/src/geometry/unit_complex_simba.rs +++ b/src/geometry/unit_complex_simba.rs @@ -2,9 +2,9 @@ use num_complex::Complex; use simba::simd::SimdValue; use std::ops::Deref; +use crate::SimdRealField; use crate::base::Unit; use crate::geometry::UnitComplex; -use crate::SimdRealField; impl SimdValue for UnitComplex where @@ -26,7 +26,7 @@ where #[inline] unsafe fn extract_unchecked(&self, i: usize) -> Self::Element { - Unit::new_unchecked(self.deref().extract_unchecked(i)) + unsafe { Unit::new_unchecked(self.deref().extract_unchecked(i)) } } #[inline] @@ -36,8 +36,10 @@ where #[inline] unsafe fn replace_unchecked(&mut self, i: usize, val: Self::Element) { - self.as_mut_unchecked() - .replace_unchecked(i, val.into_inner()) + unsafe { + self.as_mut_unchecked() + .replace_unchecked(i, val.into_inner()) + } } #[inline] diff --git a/src/io/matrix_market.rs b/src/io/matrix_market.rs index 2b0a0182e..a56574bcb 100644 --- a/src/io/matrix_market.rs +++ b/src/io/matrix_market.rs @@ -1,8 +1,8 @@ use std::fs; use std::path::Path; -use crate::sparse::CsMatrix; use crate::RealField; +use crate::sparse::CsMatrix; use pest::Parser; #[derive(Parser)] diff --git a/src/lib.rs b/src/lib.rs index e5f92d5eb..941c0070b 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -84,7 +84,7 @@ an optimized set of tools for computer graphics and physics. Those features incl unused_mut, unused_parens, rust_2018_idioms, - rust_2018_compatibility, + rust_2024_compatibility, future_incompatible, missing_copy_implementations )] @@ -242,11 +242,7 @@ where #[inline] pub fn clamp(val: T, min: T, max: T) -> T { if val > min { - if val < max { - val - } else { - max - } + if val < max { val } else { max } } else { min } diff --git a/src/linalg/bidiagonal.rs b/src/linalg/bidiagonal.rs index 13ffc7eae..6aa2df215 100644 --- a/src/linalg/bidiagonal.rs +++ b/src/linalg/bidiagonal.rs @@ -156,11 +156,7 @@ where #[inline] fn axis_shift(&self) -> (usize, usize) { - if self.upper_diagonal { - (0, 1) - } else { - (1, 0) - } + if self.upper_diagonal { (0, 1) } else { (1, 0) } } /// Unpacks this decomposition into its three matrix factors `(U, D, V^t)`. diff --git a/src/linalg/col_piv_qr.rs b/src/linalg/col_piv_qr.rs index 40d9f596a..5e3fbc409 100644 --- a/src/linalg/col_piv_qr.rs +++ b/src/linalg/col_piv_qr.rs @@ -2,15 +2,15 @@ use num::Zero; #[cfg(feature = "serde-serialize-no-std")] use serde::{Deserialize, Serialize}; +use crate::ComplexField; use crate::allocator::{Allocator, Reallocator}; use crate::base::{Const, DefaultAllocator, Matrix, OMatrix, OVector, Unit}; use crate::constraint::{SameNumberOfRows, ShapeConstraint}; use crate::dimension::{Dim, DimMin, DimMinimum}; use crate::storage::StorageMut; -use crate::ComplexField; use crate::geometry::Reflection; -use crate::linalg::{householder, PermutationSequence}; +use crate::linalg::{PermutationSequence, householder}; use std::mem::MaybeUninit; /// The QR decomposition (with column pivoting) of a general matrix. diff --git a/src/linalg/convolution.rs b/src/linalg/convolution.rs index 3434f3a83..0d241c025 100644 --- a/src/linalg/convolution.rs +++ b/src/linalg/convolution.rs @@ -4,7 +4,7 @@ use crate::base::allocator::Allocator; use crate::base::default_allocator::DefaultAllocator; use crate::base::dimension::{Const, Dim, DimAdd, DimDiff, DimSub, DimSum}; use crate::storage::Storage; -use crate::{zero, OVector, RealField, Vector, U1}; +use crate::{OVector, RealField, U1, Vector, zero}; impl> Vector { /// Returns the convolution of the target vector and a kernel. @@ -31,7 +31,9 @@ impl> Vector { let ker = kernel.len(); if ker == 0 || ker > vec { - panic!("convolve_full expects `self.len() >= kernel.len() > 0`, received {} and {} respectively.", vec, ker); + panic!( + "convolve_full expects `self.len() >= kernel.len() > 0`, received {vec} and {ker} respectively." + ); } let result_len = self @@ -84,7 +86,9 @@ impl> Vector { let ker = kernel.len(); if ker == 0 || ker > vec { - panic!("convolve_valid expects `self.len() >= kernel.len() > 0`, received {} and {} respectively.",vec,ker); + panic!( + "convolve_valid expects `self.len() >= kernel.len() > 0`, received {vec} and {ker} respectively." + ); } let result_len = self @@ -123,7 +127,9 @@ impl> Vector { let ker = kernel.len(); if ker == 0 || ker > vec { - panic!("convolve_same expects `self.len() >= kernel.len() > 0`, received {} and {} respectively.",vec,ker); + panic!( + "convolve_same expects `self.len() >= kernel.len() > 0`, received {vec} and {ker} respectively." + ); } let mut conv = OVector::zeros_generic(self.shape_generic().0, Const::<1>); diff --git a/src/linalg/decomposition.rs b/src/linalg/decomposition.rs index 957d38ab1..b424b799a 100644 --- a/src/linalg/decomposition.rs +++ b/src/linalg/decomposition.rs @@ -1,8 +1,8 @@ use crate::storage::Storage; use crate::{ Allocator, Bidiagonal, Cholesky, ColPivQR, ComplexField, DefaultAllocator, Dim, DimDiff, - DimMin, DimMinimum, DimSub, FullPivLU, Hessenberg, Matrix, OMatrix, RealField, Schur, - SymmetricEigen, SymmetricTridiagonal, LU, QR, SVD, U1, UDU, + DimMin, DimMinimum, DimSub, FullPivLU, Hessenberg, LU, Matrix, OMatrix, QR, RealField, SVD, + Schur, SymmetricEigen, SymmetricTridiagonal, U1, UDU, }; /// # Rectangular matrix decomposition diff --git a/src/linalg/exp.rs b/src/linalg/exp.rs index afd906f40..be090f643 100644 --- a/src/linalg/exp.rs +++ b/src/linalg/exp.rs @@ -1,12 +1,13 @@ //! This module provides the matrix exponent (exp) function to square matrices. //! use crate::{ + ComplexField, OMatrix, RealField, base::{ + DefaultAllocator, allocator::Allocator, dimension::{Const, Dim, DimMin, DimMinimum}, - DefaultAllocator, }, - convert, try_convert, ComplexField, OMatrix, RealField, + convert, try_convert, }; use crate::num::Zero; @@ -388,7 +389,7 @@ where fn factorial(n: usize) -> u128 { match FACTORIAL.get(n) { Some(f) => *f, - None => panic!("{}! is greater than u128::MAX", n), + None => panic!("{n}! is greater than u128::MAX"), } } @@ -435,11 +436,7 @@ where let u = 2_f64.powf(-53.0); let log2_alpha_div_u = (alpha / u).log2(); let value = (log2_alpha_div_u / (2.0 * m as f64)).ceil(); - if value > 0.0 { - value as u64 - } else { - 0 - } + if value > 0.0 { value as u64 } else { 0 } } fn solve_p_q(u: OMatrix, v: OMatrix) -> OMatrix @@ -525,11 +522,7 @@ where } else { let l2 = try_convert::<_, f64>((eta_5 / theta_13).log2().ceil()).unwrap(); - if l2 < 0.0 { - 0 - } else { - l2 as u64 - } + if l2 < 0.0 { 0 } else { l2 as u64 } }; s += ell( diff --git a/src/linalg/full_piv_lu.rs b/src/linalg/full_piv_lu.rs index 123de7c0b..fea793f5f 100644 --- a/src/linalg/full_piv_lu.rs +++ b/src/linalg/full_piv_lu.rs @@ -8,8 +8,8 @@ use crate::dimension::{Dim, DimMin, DimMinimum}; use crate::storage::{Storage, StorageMut}; use simba::scalar::ComplexField; -use crate::linalg::lu; use crate::linalg::PermutationSequence; +use crate::linalg::lu; /// LU decomposition with full row and column pivoting. #[cfg_attr(feature = "serde-serialize-no-std", derive(Serialize, Deserialize))] diff --git a/src/linalg/hessenberg.rs b/src/linalg/hessenberg.rs index d1e57bcc1..625852a07 100644 --- a/src/linalg/hessenberg.rs +++ b/src/linalg/hessenberg.rs @@ -6,8 +6,8 @@ use crate::base::{DefaultAllocator, OMatrix, OVector}; use crate::dimension::{Const, DimDiff, DimSub, U1}; use simba::scalar::ComplexField; -use crate::linalg::householder; use crate::Matrix; +use crate::linalg::householder; use std::mem::MaybeUninit; /// Hessenberg decomposition of a general matrix. diff --git a/src/linalg/inverse.rs b/src/linalg/inverse.rs index b11eae13a..52f9d28af 100644 --- a/src/linalg/inverse.rs +++ b/src/linalg/inverse.rs @@ -20,11 +20,7 @@ impl> SquareMatrix { DefaultAllocator: Allocator, { let mut me = self.into_owned(); - if me.try_inverse_mut() { - Some(me) - } else { - None - } + if me.try_inverse_mut() { Some(me) } else { None } } } diff --git a/src/linalg/pow.rs b/src/linalg/pow.rs index c6ff74aed..8e619c4df 100644 --- a/src/linalg/pow.rs +++ b/src/linalg/pow.rs @@ -1,9 +1,9 @@ //! This module provides the matrix exponential (pow) function to square matrices. use crate::{ + DefaultAllocator, DimMin, Matrix, OMatrix, Scalar, allocator::Allocator, storage::{Storage, StorageMut}, - DefaultAllocator, DimMin, Matrix, OMatrix, Scalar, }; use num::{One, Zero}; use simba::scalar::{ClosedAddAssign, ClosedMulAssign}; diff --git a/src/linalg/schur.rs b/src/linalg/schur.rs index 7366b4cbb..4362a86fb 100644 --- a/src/linalg/schur.rs +++ b/src/linalg/schur.rs @@ -13,9 +13,9 @@ use crate::base::storage::Storage; use crate::base::{DefaultAllocator, OMatrix, OVector, SquareMatrix, Unit, Vector2, Vector3}; use crate::geometry::Reflection; +use crate::linalg::Hessenberg; use crate::linalg::givens::GivensRotation; use crate::linalg::householder; -use crate::linalg::Hessenberg; use crate::{Matrix, UninitVector}; use std::mem::MaybeUninit; @@ -486,20 +486,17 @@ fn compute_2x2_basis>( return None; } - if let Some((eigval1, eigval2)) = compute_2x2_eigvals(m) { - let x1 = eigval1 - m[(1, 1)].clone(); - let x2 = eigval2 - m[(1, 1)].clone(); + let (eigval1, eigval2) = compute_2x2_eigvals(m)?; + let x1 = eigval1 - m[(1, 1)].clone(); + let x2 = eigval2 - m[(1, 1)].clone(); - // NOTE: Choose the one that yields a larger x component. - // This is necessary for numerical stability of the normalization of the complex - // number. - if x1.clone().norm1() > x2.clone().norm1() { - Some(GivensRotation::new(x1, h10).0) - } else { - Some(GivensRotation::new(x2, h10).0) - } + // NOTE: Choose the one that yields a larger x component. + // This is necessary for numerical stability of the normalization of the complex + // number. + if x1.clone().norm1() > x2.clone().norm1() { + Some(GivensRotation::new(x1, h10).0) } else { - None + Some(GivensRotation::new(x2, h10).0) } } diff --git a/src/linalg/svd.rs b/src/linalg/svd.rs index fc5ed6b4d..73c5e5ab0 100644 --- a/src/linalg/svd.rs +++ b/src/linalg/svd.rs @@ -13,9 +13,9 @@ use crate::storage::Storage; use crate::{Matrix2, Matrix3, RawStorage, U2, U3}; use simba::scalar::{ComplexField, RealField}; +use crate::linalg::Bidiagonal; use crate::linalg::givens::GivensRotation; use crate::linalg::symmetric_eigen; -use crate::linalg::Bidiagonal; /// Singular Value Decomposition of a general matrix. #[cfg_attr(feature = "serde-serialize-no-std", derive(Serialize, Deserialize))] @@ -213,54 +213,59 @@ where m12, ); - if let Some((rot1, norm1)) = GivensRotation::cancel_y(&vec) { - rot1.inverse() - .rotate_rows(&mut subm.fixed_columns_mut::<2>(0)); - let rot1 = GivensRotation::new_unchecked(rot1.c(), T::from_real(rot1.s())); + match GivensRotation::cancel_y(&vec) { + Some((rot1, norm1)) => { + rot1.inverse() + .rotate_rows(&mut subm.fixed_columns_mut::<2>(0)); + let rot1 = + GivensRotation::new_unchecked(rot1.c(), T::from_real(rot1.s())); - if k > start { - // This is not the first iteration. - off_diagonal[k - 1] = norm1; - } + if k > start { + // This is not the first iteration. + off_diagonal[k - 1] = norm1; + } - let v = Vector2::new(subm[(0, 0)].clone(), subm[(1, 0)].clone()); - // TODO: does the case `v.y == 0` ever happen? - let (rot2, norm2) = GivensRotation::cancel_y(&v) - .unwrap_or((GivensRotation::identity(), subm[(0, 0)].clone())); + let v = Vector2::new(subm[(0, 0)].clone(), subm[(1, 0)].clone()); + // TODO: does the case `v.y == 0` ever happen? + let (rot2, norm2) = GivensRotation::cancel_y(&v) + .unwrap_or((GivensRotation::identity(), subm[(0, 0)].clone())); - rot2.rotate(&mut subm.fixed_columns_mut::<2>(1)); - let rot2 = GivensRotation::new_unchecked(rot2.c(), T::from_real(rot2.s())); + rot2.rotate(&mut subm.fixed_columns_mut::<2>(1)); + let rot2 = + GivensRotation::new_unchecked(rot2.c(), T::from_real(rot2.s())); - subm[(0, 0)] = norm2; + subm[(0, 0)] = norm2; - if let Some(ref mut v_t) = v_t { - if bi_matrix.is_upper_diagonal() { - rot1.rotate(&mut v_t.fixed_rows_mut::<2>(k)); - } else { - rot2.rotate(&mut v_t.fixed_rows_mut::<2>(k)); + if let Some(ref mut v_t) = v_t { + if bi_matrix.is_upper_diagonal() { + rot1.rotate(&mut v_t.fixed_rows_mut::<2>(k)); + } else { + rot2.rotate(&mut v_t.fixed_rows_mut::<2>(k)); + } } - } - if let Some(ref mut u) = u { - if bi_matrix.is_upper_diagonal() { - rot2.inverse().rotate_rows(&mut u.fixed_columns_mut::<2>(k)); - } else { - rot1.inverse().rotate_rows(&mut u.fixed_columns_mut::<2>(k)); + if let Some(ref mut u) = u { + if bi_matrix.is_upper_diagonal() { + rot2.inverse().rotate_rows(&mut u.fixed_columns_mut::<2>(k)); + } else { + rot1.inverse().rotate_rows(&mut u.fixed_columns_mut::<2>(k)); + } } - } - diagonal[k] = subm[(0, 0)].clone(); - diagonal[k + 1] = subm[(1, 1)].clone(); - off_diagonal[k] = subm[(0, 1)].clone(); + diagonal[k] = subm[(0, 0)].clone(); + diagonal[k + 1] = subm[(1, 1)].clone(); + off_diagonal[k] = subm[(0, 1)].clone(); - if k != n - 1 { - off_diagonal[k + 1] = subm[(1, 2)].clone(); - } + if k != n - 1 { + off_diagonal[k + 1] = subm[(1, 2)].clone(); + } - vec.x = subm[(0, 1)].clone(); - vec.y = subm[(0, 2)].clone(); - } else { - break; + vec.x = subm[(0, 1)].clone(); + vec.y = subm[(0, 2)].clone(); + } + None => { + break; + } } } } else if subdim == 2 { @@ -476,26 +481,29 @@ where off_diagonal[i] = T::RealField::zero(); for k in i..end { - if let Some((rot, norm)) = GivensRotation::cancel_x(&v) { - let rot = GivensRotation::new_unchecked(rot.c(), T::from_real(rot.s())); - diagonal[k + 1] = norm; + match GivensRotation::cancel_x(&v) { + Some((rot, norm)) => { + let rot = GivensRotation::new_unchecked(rot.c(), T::from_real(rot.s())); + diagonal[k + 1] = norm; + + if is_upper_diagonal { + if let Some(ref mut u) = *u { + rot.inverse() + .rotate_rows(&mut u.fixed_columns_with_step_mut::<2>(i, k - i)); + } + } else if let Some(ref mut v_t) = *v_t { + rot.rotate(&mut v_t.fixed_rows_with_step_mut::<2>(i, k - i)); + } - if is_upper_diagonal { - if let Some(ref mut u) = *u { - rot.inverse() - .rotate_rows(&mut u.fixed_columns_with_step_mut::<2>(i, k - i)); + if k + 1 != end { + v.x = -rot.s().real() * off_diagonal[k + 1].clone(); + v.y = diagonal[k + 2].clone(); + off_diagonal[k + 1] *= rot.c(); } - } else if let Some(ref mut v_t) = *v_t { - rot.rotate(&mut v_t.fixed_rows_with_step_mut::<2>(i, k - i)); } - - if k + 1 != end { - v.x = -rot.s().real() * off_diagonal[k + 1].clone(); - v.y = diagonal[k + 2].clone(); - off_diagonal[k + 1] *= rot.c(); + None => { + break; } - } else { - break; } } } @@ -513,26 +521,29 @@ where off_diagonal[i] = T::RealField::zero(); for k in (0..i + 1).rev() { - if let Some((rot, norm)) = GivensRotation::cancel_y(&v) { - let rot = GivensRotation::new_unchecked(rot.c(), T::from_real(rot.s())); - diagonal[k] = norm; + match GivensRotation::cancel_y(&v) { + Some((rot, norm)) => { + let rot = GivensRotation::new_unchecked(rot.c(), T::from_real(rot.s())); + diagonal[k] = norm; + + if is_upper_diagonal { + if let Some(ref mut v_t) = *v_t { + rot.rotate(&mut v_t.fixed_rows_with_step_mut::<2>(k, i - k)); + } + } else if let Some(ref mut u) = *u { + rot.inverse() + .rotate_rows(&mut u.fixed_columns_with_step_mut::<2>(k, i - k)); + } - if is_upper_diagonal { - if let Some(ref mut v_t) = *v_t { - rot.rotate(&mut v_t.fixed_rows_with_step_mut::<2>(k, i - k)); + if k > 0 { + v.x = diagonal[k - 1].clone(); + v.y = rot.s().real() * off_diagonal[k - 1].clone(); + off_diagonal[k - 1] *= rot.c(); } - } else if let Some(ref mut u) = *u { - rot.inverse() - .rotate_rows(&mut u.fixed_columns_with_step_mut::<2>(k, i - k)); } - - if k > 0 { - v.x = diagonal[k - 1].clone(); - v.y = rot.s().real() * off_diagonal[k - 1].clone(); - off_diagonal[k - 1] *= rot.c(); + None => { + break; } - } else { - break; } } } diff --git a/src/linalg/svd2.rs b/src/linalg/svd2.rs index f23fed50e..3e21755ad 100644 --- a/src/linalg/svd2.rs +++ b/src/linalg/svd2.rs @@ -1,4 +1,4 @@ -use crate::{Matrix2, RealField, Vector2, SVD, U2}; +use crate::{Matrix2, RealField, SVD, U2, Vector2}; // Implementation of the 2D SVD from https://ieeexplore.ieee.org/document/486688 // See also https://scicomp.stackexchange.com/questions/8899/robust-algorithm-for-2-times-2-svd diff --git a/src/linalg/symmetric_eigen.rs b/src/linalg/symmetric_eigen.rs index 986d5383e..f90c875ea 100644 --- a/src/linalg/symmetric_eigen.rs +++ b/src/linalg/symmetric_eigen.rs @@ -10,8 +10,8 @@ use crate::dimension::{Dim, DimDiff, DimSub, U1}; use crate::storage::Storage; use simba::scalar::ComplexField; -use crate::linalg::givens::GivensRotation; use crate::linalg::SymmetricTridiagonal; +use crate::linalg::givens::GivensRotation; /// Eigendecomposition of a symmetric matrix. #[cfg_attr(feature = "serde-serialize-no-std", derive(Serialize, Deserialize))] @@ -151,38 +151,43 @@ where for i in start..n { let j = i + 1; - if let Some((rot, norm)) = GivensRotation::cancel_y(&vec) { - if i > start { - // Not the first iteration. - off_diag[i - 1] = norm; + match GivensRotation::cancel_y(&vec) { + Some((rot, norm)) => { + if i > start { + // Not the first iteration. + off_diag[i - 1] = norm; + } + + let mii = diag[i].clone(); + let mjj = diag[j].clone(); + let mij = off_diag[i].clone(); + + let cc = rot.c() * rot.c(); + let ss = rot.s() * rot.s(); + let cs = rot.c() * rot.s(); + + let b = cs.clone() * crate::convert(2.0) * mij.clone(); + + diag[i] = + (cc.clone() * mii.clone() + ss.clone() * mjj.clone()) - b.clone(); + diag[j] = (ss.clone() * mii.clone() + cc.clone() * mjj.clone()) + b; + off_diag[i] = cs * (mii - mjj) + mij * (cc - ss); + + if i != n - 1 { + vec.x = off_diag[i].clone(); + vec.y = -rot.s() * off_diag[i + 1].clone(); + off_diag[i + 1] *= rot.c(); + } + + if let Some(ref mut q) = q_mat { + let rot = + GivensRotation::new_unchecked(rot.c(), T::from_real(rot.s())); + rot.inverse().rotate_rows(&mut q.fixed_columns_mut::<2>(i)); + } } - - let mii = diag[i].clone(); - let mjj = diag[j].clone(); - let mij = off_diag[i].clone(); - - let cc = rot.c() * rot.c(); - let ss = rot.s() * rot.s(); - let cs = rot.c() * rot.s(); - - let b = cs.clone() * crate::convert(2.0) * mij.clone(); - - diag[i] = (cc.clone() * mii.clone() + ss.clone() * mjj.clone()) - b.clone(); - diag[j] = (ss.clone() * mii.clone() + cc.clone() * mjj.clone()) + b; - off_diag[i] = cs * (mii - mjj) + mij * (cc - ss); - - if i != n - 1 { - vec.x = off_diag[i].clone(); - vec.y = -rot.s() * off_diag[i + 1].clone(); - off_diag[i + 1] *= rot.c(); - } - - if let Some(ref mut q) = q_mat { - let rot = GivensRotation::new_unchecked(rot.c(), T::from_real(rot.s())); - rot.inverse().rotate_rows(&mut q.fixed_columns_mut::<2>(i)); + None => { + break; } - } else { - break; } } diff --git a/src/linalg/symmetric_tridiagonal.rs b/src/linalg/symmetric_tridiagonal.rs index 0d1a16c5d..12fd7c9d3 100644 --- a/src/linalg/symmetric_tridiagonal.rs +++ b/src/linalg/symmetric_tridiagonal.rs @@ -6,8 +6,8 @@ use crate::base::{DefaultAllocator, OMatrix, OVector}; use crate::dimension::{Const, DimDiff, DimSub, U1}; use simba::scalar::ComplexField; -use crate::linalg::householder; use crate::Matrix; +use crate::linalg::householder; use std::mem::MaybeUninit; /// Tridiagonalization of a symmetric matrix. diff --git a/src/sparse/cs_matrix.rs b/src/sparse/cs_matrix.rs index ae8aafaf3..39cafff7e 100644 --- a/src/sparse/cs_matrix.rs +++ b/src/sparse/cs_matrix.rs @@ -7,7 +7,7 @@ use std::slice; use crate::allocator::Allocator; use crate::sparse::cs_utils; -use crate::{Const, DefaultAllocator, Dim, Dyn, Matrix, OVector, Scalar, Vector, U1}; +use crate::{Const, DefaultAllocator, Dim, Dyn, Matrix, OVector, Scalar, U1, Vector}; pub struct ColumnEntries<'a, T> { curr: usize, @@ -180,12 +180,12 @@ where #[inline] unsafe fn row_index_unchecked(&self, i: usize) -> usize { - *self.i.get_unchecked(i) + unsafe { *self.i.get_unchecked(i) } } #[inline] unsafe fn get_value_unchecked(&self, i: usize) -> &T { - self.vals.get_unchecked(i) + unsafe { self.vals.get_unchecked(i) } } #[inline] diff --git a/src/sparse/cs_matrix_cholesky.rs b/src/sparse/cs_matrix_cholesky.rs index 722d04a85..f41f01dc8 100644 --- a/src/sparse/cs_matrix_cholesky.rs +++ b/src/sparse/cs_matrix_cholesky.rs @@ -67,20 +67,12 @@ where /// The lower-triangular matrix of the cholesky decomposition. #[must_use] pub fn l(&self) -> Option<&CsMatrix> { - if self.ok { - Some(&self.l) - } else { - None - } + if self.ok { Some(&self.l) } else { None } } /// Extracts the lower-triangular matrix of the cholesky decomposition. pub fn unwrap_l(self) -> Option> { - if self.ok { - Some(self.l) - } else { - None - } + if self.ok { Some(self.l) } else { None } } /// Perform a numerical left-looking cholesky decomposition of a matrix with the same structure as the diff --git a/src/third_party/alga/alga_dual_quaternion.rs b/src/third_party/alga/alga_dual_quaternion.rs index bc07cfa4b..f5fcc87b3 100644 --- a/src/third_party/alga/alga_dual_quaternion.rs +++ b/src/third_party/alga/alga_dual_quaternion.rs @@ -119,12 +119,12 @@ impl FiniteDimVectorSpace for DualQuate #[inline] unsafe fn component_unchecked(&self, i: usize) -> &T { - self.as_ref().get_unchecked(i) + unsafe { self.as_ref().get_unchecked(i) } } #[inline] unsafe fn component_unchecked_mut(&mut self, i: usize) -> &mut T { - self.as_mut().get_unchecked_mut(i) + unsafe { self.as_mut().get_unchecked_mut(i) } } } diff --git a/src/third_party/alga/alga_isometry.rs b/src/third_party/alga/alga_isometry.rs index 7633bf5c4..448056716 100755 --- a/src/third_party/alga/alga_isometry.rs +++ b/src/third_party/alga/alga_isometry.rs @@ -34,7 +34,6 @@ where R: Rotation> + AbstractRotation, { #[inline] - #[must_use = "Did you mean to use two_sided_inverse_mut()?"] fn two_sided_inverse(&self) -> Self { self.inverse() } diff --git a/src/third_party/alga/alga_matrix.rs b/src/third_party/alga/alga_matrix.rs index 83c08806a..7a0e673a9 100644 --- a/src/third_party/alga/alga_matrix.rs +++ b/src/third_party/alga/alga_matrix.rs @@ -52,7 +52,6 @@ where DefaultAllocator: Allocator, { #[inline] - #[must_use = "Did you mean to use two_sided_inverse_mut()?"] fn two_sided_inverse(&self) -> Self { -self } @@ -138,20 +137,20 @@ where #[inline] unsafe fn component_unchecked(&self, i: usize) -> &T { - self.data.get_unchecked_linear(i) + unsafe { self.data.get_unchecked_linear(i) } } #[inline] unsafe fn component_unchecked_mut(&mut self, i: usize) -> &mut T { - self.data.get_unchecked_linear_mut(i) + unsafe { self.data.get_unchecked_linear_mut(i) } } } impl< - T: ComplexField + simba::scalar::ComplexField::RealField>, - R: DimName, - C: DimName, - > NormedSpace for OMatrix + T: ComplexField + simba::scalar::ComplexField::RealField>, + R: DimName, + C: DimName, +> NormedSpace for OMatrix where ::RealField: simba::scalar::RealField, DefaultAllocator: Allocator, @@ -170,7 +169,6 @@ where } #[inline] - #[must_use = "Did you mean to use normalize_mut()?"] fn normalize(&self) -> Self { self.normalize() } @@ -181,7 +179,6 @@ where } #[inline] - #[must_use = "Did you mean to use try_normalize_mut()?"] fn try_normalize(&self, min_norm: ::RealField) -> Option { self.try_normalize(min_norm) } @@ -196,10 +193,10 @@ where } impl< - T: ComplexField + simba::scalar::ComplexField::RealField>, - R: DimName, - C: DimName, - > InnerSpace for OMatrix + T: ComplexField + simba::scalar::ComplexField::RealField>, + R: DimName, + C: DimName, +> InnerSpace for OMatrix where ::RealField: simba::scalar::RealField, DefaultAllocator: Allocator, @@ -220,10 +217,10 @@ where // − use `x()` instead of `::canonical_basis_element` // − use `::new(x, y, z)` instead of `::from_slice` impl< - T: ComplexField + simba::scalar::ComplexField::RealField>, - R: DimName, - C: DimName, - > FiniteDimInnerSpace for OMatrix + T: ComplexField + simba::scalar::ComplexField::RealField>, + R: DimName, + C: DimName, +> FiniteDimInnerSpace for OMatrix where ::RealField: simba::scalar::RealField, DefaultAllocator: Allocator, @@ -344,8 +341,10 @@ where } #[cfg(all(not(feature = "std"), not(feature = "alloc")))] { - panic!("Cannot compute the orthogonal subspace basis of a vector with a dimension greater than 3 \ - if #![no_std] is enabled and the 'alloc' feature is not enabled.") + panic!( + "Cannot compute the orthogonal subspace basis of a vector with a dimension greater than 3 \ + if #![no_std] is enabled and the 'alloc' feature is not enabled." + ) } } } diff --git a/src/third_party/alga/alga_quaternion.rs b/src/third_party/alga/alga_quaternion.rs index 7282e0f17..cc20d13dc 100755 --- a/src/third_party/alga/alga_quaternion.rs +++ b/src/third_party/alga/alga_quaternion.rs @@ -108,12 +108,12 @@ impl FiniteDimVectorSpace for Quaternio #[inline] unsafe fn component_unchecked(&self, i: usize) -> &T { - self.coords.component_unchecked(i) + unsafe { self.coords.component_unchecked(i) } } #[inline] unsafe fn component_unchecked_mut(&mut self, i: usize) -> &mut T { - self.coords.component_unchecked_mut(i) + unsafe { self.coords.component_unchecked_mut(i) } } } diff --git a/src/third_party/alga/alga_rotation.rs b/src/third_party/alga/alga_rotation.rs index cec4ae7d3..79ce1f71f 100755 --- a/src/third_party/alga/alga_rotation.rs +++ b/src/third_party/alga/alga_rotation.rs @@ -28,7 +28,6 @@ impl TwoSidedInverse { #[inline] - #[must_use = "Did you mean to use two_sided_inverse_mut()?"] fn two_sided_inverse(&self) -> Self { self.transpose() } diff --git a/src/third_party/alga/alga_similarity.rs b/src/third_party/alga/alga_similarity.rs index f0d298679..54138ef46 100755 --- a/src/third_party/alga/alga_similarity.rs +++ b/src/third_party/alga/alga_similarity.rs @@ -30,7 +30,6 @@ where R: Rotation> + AbstractRotation, { #[inline] - #[must_use = "Did you mean to use two_sided_inverse_mut()?"] fn two_sided_inverse(&self) -> Self { self.inverse() } diff --git a/src/third_party/alga/alga_transform.rs b/src/third_party/alga/alga_transform.rs index adab183cc..00c5a5394 100755 --- a/src/third_party/alga/alga_transform.rs +++ b/src/third_party/alga/alga_transform.rs @@ -36,7 +36,6 @@ where DefaultAllocator: Allocator, U1>, DimNameSum, U1>>, { #[inline] - #[must_use = "Did you mean to use two_sided_inverse_mut()?"] fn two_sided_inverse(&self) -> Self { self.clone().inverse() } diff --git a/src/third_party/alga/alga_translation.rs b/src/third_party/alga/alga_translation.rs index 246fe6406..daf11ab01 100755 --- a/src/third_party/alga/alga_translation.rs +++ b/src/third_party/alga/alga_translation.rs @@ -29,7 +29,6 @@ impl TwoSidedInverse { #[inline] - #[must_use = "Did you mean to use two_sided_inverse_mut()?"] fn two_sided_inverse(&self) -> Self { self.inverse() } diff --git a/src/third_party/alga/alga_unit_complex.rs b/src/third_party/alga/alga_unit_complex.rs index ca55691b2..f178b3483 100755 --- a/src/third_party/alga/alga_unit_complex.rs +++ b/src/third_party/alga/alga_unit_complex.rs @@ -31,7 +31,6 @@ impl AbstractMagma for impl TwoSidedInverse for UnitComplex { #[inline] - #[must_use = "Did you mean to use two_sided_inverse_mut()?"] fn two_sided_inverse(&self) -> Self { self.inverse() } diff --git a/src/third_party/glam/common/glam_matrix.rs b/src/third_party/glam/common/glam_matrix.rs index 26f58803c..86e93f231 100644 --- a/src/third_party/glam/common/glam_matrix.rs +++ b/src/third_party/glam/common/glam_matrix.rs @@ -4,8 +4,8 @@ use super::glam::{ }; use crate::storage::RawStorage; use crate::{ - Matrix, Matrix2, Matrix3, Matrix4, Unit, UnitVector2, UnitVector3, UnitVector4, Vector, - Vector2, Vector3, Vector4, U2, U3, U4, + Matrix, Matrix2, Matrix3, Matrix4, U2, U3, U4, Unit, UnitVector2, UnitVector3, UnitVector4, + Vector, Vector2, Vector3, Vector4, }; use std::convert::TryFrom; diff --git a/tests/core/blas.rs b/tests/core/blas.rs index ef5c1c2fc..2c3ca6df3 100644 --- a/tests/core/blas.rs +++ b/tests/core/blas.rs @@ -1,4 +1,4 @@ -use na::{geometry::Quaternion, Matrix2, Vector3}; +use na::{Matrix2, Vector3, geometry::Quaternion}; use num_traits::{One, Zero}; #[test] diff --git a/tests/core/helper.rs b/tests/core/helper.rs index 3eb6fc4e4..a178b088a 100644 --- a/tests/core/helper.rs +++ b/tests/core/helper.rs @@ -4,8 +4,8 @@ use na::RealField; use num_complex::Complex; use quickcheck::{Arbitrary, Gen}; -use rand::distr::{Distribution, StandardUniform}; use rand::Rng; +use rand::distr::{Distribution, StandardUniform}; #[derive(Copy, Clone, Debug, PartialEq, Eq)] pub struct RandComplex(pub Complex); diff --git a/tests/core/matrix.rs b/tests/core/matrix.rs index 50c0e426a..0c0179c01 100644 --- a/tests/core/matrix.rs +++ b/tests/core/matrix.rs @@ -2,7 +2,7 @@ use na::iter::MatrixIter; use num::{One, Zero}; use std::cmp::Ordering; -use na::dimension::{U15, U8}; +use na::dimension::{U8, U15}; use na::{ self, Const, DMatrix, DVector, Matrix2, Matrix2x3, Matrix2x4, Matrix3, Matrix3x2, Matrix3x4, Matrix4, Matrix4x3, Matrix4x5, Matrix5, Matrix6, MatrixView2x3, MatrixViewMut2x3, OMatrix, @@ -883,7 +883,7 @@ fn swizzle() { #[cfg(feature = "proptest-support")] mod transposition_tests { use super::*; - use crate::proptest::{dmatrix, matrix, vector4, PROPTEST_F64}; + use crate::proptest::{PROPTEST_F64, dmatrix, matrix, vector4}; use proptest::{prop_assert, prop_assert_eq, proptest}; proptest! { diff --git a/tests/core/reshape.rs b/tests/core/reshape.rs index 3873667f6..a271b4a1f 100644 --- a/tests/core/reshape.rs +++ b/tests/core/reshape.rs @@ -1,6 +1,6 @@ use na::{ Const, DMatrix, DMatrixView, DMatrixViewMut, Dyn, Matrix, MatrixView, MatrixViewMut, SMatrix, - SMatrixView, SMatrixViewMut, VecStorage, U3, U4, + SMatrixView, SMatrixViewMut, U3, U4, VecStorage, }; use nalgebra_macros::matrix; use simba::scalar::SupersetOf; diff --git a/tests/linalg/balancing.rs b/tests/linalg/balancing.rs index 5d250b2cc..760cf720b 100644 --- a/tests/linalg/balancing.rs +++ b/tests/linalg/balancing.rs @@ -1,7 +1,7 @@ #![cfg(feature = "proptest-support")] -use na::balancing; use na::DMatrix; +use na::balancing; use crate::proptest::*; use proptest::{prop_assert_eq, proptest}; diff --git a/tests/linalg/convolution.rs b/tests/linalg/convolution.rs index eba8b84d2..79eccf642 100644 --- a/tests/linalg/convolution.rs +++ b/tests/linalg/convolution.rs @@ -25,23 +25,29 @@ fn convolve_same_check() { // Panic Tests // These really only apply to dynamic sized vectors - assert!(panic::catch_unwind(|| { - let _ = DVector::from_vec(vec![1.0, 2.0]) - .convolve_same(DVector::from_vec(vec![1.0, 2.0, 3.0, 4.0])); - }) - .is_err()); - - assert!(panic::catch_unwind(|| { - let _ = DVector::::from_vec(vec![]) - .convolve_same(DVector::from_vec(vec![1.0, 2.0, 3.0, 4.0])); - }) - .is_err()); - - assert!(panic::catch_unwind(|| { - let _ = DVector::from_vec(vec![1.0, 2.0, 3.0, 4.0]) - .convolve_same(DVector::::from_vec(vec![])); - }) - .is_err()); + assert!( + panic::catch_unwind(|| { + let _ = DVector::from_vec(vec![1.0, 2.0]) + .convolve_same(DVector::from_vec(vec![1.0, 2.0, 3.0, 4.0])); + }) + .is_err() + ); + + assert!( + panic::catch_unwind(|| { + let _ = DVector::::from_vec(vec![]) + .convolve_same(DVector::from_vec(vec![1.0, 2.0, 3.0, 4.0])); + }) + .is_err() + ); + + assert!( + panic::catch_unwind(|| { + let _ = DVector::from_vec(vec![1.0, 2.0, 3.0, 4.0]) + .convolve_same(DVector::::from_vec(vec![])); + }) + .is_err() + ); } // >>> convolve([1,2,3,4],[1,2],"full") @@ -63,21 +69,29 @@ fn convolve_full_check() { // Panic Tests // These really only apply to dynamic sized vectors - assert!(panic::catch_unwind(|| { - DVector::from_vec(vec![1.0, 2.0]) - .convolve_full(DVector::from_vec(vec![1.0, 2.0, 3.0, 4.0])); - }) - .is_err()); - - assert!(panic::catch_unwind(|| { - DVector::::from_vec(vec![]).convolve_full(DVector::from_vec(vec![1.0, 2.0, 3.0, 4.0])); - }) - .is_err()); - - assert!(panic::catch_unwind(|| { - DVector::from_vec(vec![1.0, 2.0, 3.0, 4.0]).convolve_full(DVector::::from_vec(vec![])); - }) - .is_err()); + assert!( + panic::catch_unwind(|| { + DVector::from_vec(vec![1.0, 2.0]) + .convolve_full(DVector::from_vec(vec![1.0, 2.0, 3.0, 4.0])); + }) + .is_err() + ); + + assert!( + panic::catch_unwind(|| { + DVector::::from_vec(vec![]) + .convolve_full(DVector::from_vec(vec![1.0, 2.0, 3.0, 4.0])); + }) + .is_err() + ); + + assert!( + panic::catch_unwind(|| { + DVector::from_vec(vec![1.0, 2.0, 3.0, 4.0]) + .convolve_full(DVector::::from_vec(vec![])); + }) + .is_err() + ); } // >>> convolve([1, 2, 3, 4],[1, 2],"valid") @@ -99,21 +113,27 @@ fn convolve_valid_check() { // Panic Tests // These really only apply to dynamic sized vectors - assert!(panic::catch_unwind(|| { - DVector::from_vec(vec![1.0, 2.0]) - .convolve_valid(DVector::from_vec(vec![1.0, 2.0, 3.0, 4.0])); - }) - .is_err()); - - assert!(panic::catch_unwind(|| { - DVector::::from_vec(vec![]) - .convolve_valid(DVector::from_vec(vec![1.0, 2.0, 3.0, 4.0])); - }) - .is_err()); - - assert!(panic::catch_unwind(|| { - DVector::from_vec(vec![1.0, 2.0, 3.0, 4.0]) - .convolve_valid(DVector::::from_vec(vec![])); - }) - .is_err()); + assert!( + panic::catch_unwind(|| { + DVector::from_vec(vec![1.0, 2.0]) + .convolve_valid(DVector::from_vec(vec![1.0, 2.0, 3.0, 4.0])); + }) + .is_err() + ); + + assert!( + panic::catch_unwind(|| { + DVector::::from_vec(vec![]) + .convolve_valid(DVector::from_vec(vec![1.0, 2.0, 3.0, 4.0])); + }) + .is_err() + ); + + assert!( + panic::catch_unwind(|| { + DVector::from_vec(vec![1.0, 2.0, 3.0, 4.0]) + .convolve_valid(DVector::::from_vec(vec![])); + }) + .is_err() + ); } diff --git a/tests/macros/stack.rs b/tests/macros/stack.rs index 7ba3af828..20f8701a3 100644 --- a/tests/macros/stack.rs +++ b/tests/macros/stack.rs @@ -2,11 +2,11 @@ use crate::macros::assert_eq_and_type; use cool_asserts::assert_panics; use na::VecStorage; use nalgebra::dimension::U1; -use nalgebra::{dmatrix, matrix, stack}; use nalgebra::{ DMatrix, DMatrixView, Dyn, Matrix, Matrix2, Matrix4, OMatrix, SMatrix, SMatrixView, SMatrixViewMut, Scalar, U2, }; +use nalgebra::{dmatrix, matrix, stack}; use nalgebra_macros::vector; use num_traits::Zero; diff --git a/tests/macros/trybuild/stack_incompatible_block_dimensions.stderr b/tests/macros/trybuild/stack_incompatible_block_dimensions.stderr index c0428719d..4425106a4 100644 --- a/tests/macros/trybuild/stack_incompatible_block_dimensions.stderr +++ b/tests/macros/trybuild/stack_incompatible_block_dimensions.stderr @@ -18,15 +18,3 @@ error[E0282]: type annotations needed | |____________________^ cannot infer type | = note: this error originates in the macro `stack` (in Nightly builds, run with -Z macro-backtrace for more info) - -error[E0599]: no method named `generic_view_mut` found for struct `Matrix<_, Const<3>, _, _>` in the current scope - --> tests/macros/trybuild/stack_incompatible_block_dimensions.rs:11:5 - | -11 | stack![a11, a12; - | _____^ -12 | | a21, a22]; - | |____________________^ method not found in `Matrix<_, Const<3>, _, _>` - | - = note: the method was found for - - `Matrix` - = note: this error originates in the macro `stack` (in Nightly builds, run with -Z macro-backtrace for more info) diff --git a/tests/macros/trybuild/stack_incompatible_block_dimensions2.stderr b/tests/macros/trybuild/stack_incompatible_block_dimensions2.stderr index 6e40b854f..bb0c87fe0 100644 --- a/tests/macros/trybuild/stack_incompatible_block_dimensions2.stderr +++ b/tests/macros/trybuild/stack_incompatible_block_dimensions2.stderr @@ -18,15 +18,3 @@ error[E0282]: type annotations needed | |____________________^ cannot infer type | = note: this error originates in the macro `stack` (in Nightly builds, run with -Z macro-backtrace for more info) - -error[E0599]: no method named `generic_view_mut` found for struct `Matrix<_, _, Const<4>, _>` in the current scope - --> tests/macros/trybuild/stack_incompatible_block_dimensions2.rs:12:5 - | -12 | stack![a11, a12; - | _____^ -13 | | a21, a22]; - | |____________________^ method not found in `Matrix<_, _, Const<4>, _>` - | - = note: the method was found for - - `Matrix` - = note: this error originates in the macro `stack` (in Nightly builds, run with -Z macro-backtrace for more info) diff --git a/tests/proptest/mod.rs b/tests/proptest/mod.rs index f2e537252..592cda3f8 100644 --- a/tests/proptest/mod.rs +++ b/tests/proptest/mod.rs @@ -8,7 +8,7 @@ use nalgebra::proptest::{DimRange, MatrixStrategy}; use nalgebra::{ DMatrix, DVector, DefaultAllocator, Dim, DualQuaternion, Isometry2, Isometry3, Matrix3, OMatrix, Point2, Point3, Quaternion, Rotation2, Rotation3, Scalar, Similarity3, Translation2, - Translation3, UnitComplex, UnitDualQuaternion, UnitQuaternion, Vector3, U3, U4, + Translation3, U3, U4, UnitComplex, UnitDualQuaternion, UnitQuaternion, Vector3, }; use num_complex::Complex; use proptest::prelude::*;