|
| 1 | +//! Implementations of the [`Schema`] trait for the `nalgebra` crate v0.34 |
| 2 | +
|
| 3 | +use crate::{ |
| 4 | + schema::{DataModelType, NamedType}, |
| 5 | + Schema, |
| 6 | +}; |
| 7 | + |
| 8 | +#[cfg_attr(docsrs, doc(cfg(feature = "nalgebra-v0_34")))] |
| 9 | +impl<T, const R: usize, const C: usize> Schema |
| 10 | + for nalgebra_v0_34::Matrix< |
| 11 | + T, |
| 12 | + nalgebra_v0_34::Const<R>, |
| 13 | + nalgebra_v0_34::Const<C>, |
| 14 | + nalgebra_v0_34::ArrayStorage<T, R, C>, |
| 15 | + > |
| 16 | +where |
| 17 | + T: Schema + nalgebra_v0_34::Scalar, |
| 18 | +{ |
| 19 | + const SCHEMA: &'static NamedType = &NamedType { |
| 20 | + name: "nalgebra::Matrix<T, R, C, ArrayStorage<T, R, C>>", |
| 21 | + ty: &DataModelType::Tuple(flatten(&[[T::SCHEMA; R]; C])), |
| 22 | + }; |
| 23 | +} |
| 24 | + |
| 25 | +#[cfg_attr(docsrs, doc(cfg(feature = "nalgebra-v0_34")))] |
| 26 | +impl<T: Schema> Schema for nalgebra_v0_34::Unit<T> { |
| 27 | + const SCHEMA: &'static NamedType = T::SCHEMA; |
| 28 | +} |
| 29 | + |
| 30 | +#[cfg_attr(docsrs, doc(cfg(feature = "nalgebra-v0_34")))] |
| 31 | +impl<T: Schema + nalgebra_v0_34::Scalar> Schema for nalgebra_v0_34::Quaternion<T> { |
| 32 | + const SCHEMA: &'static NamedType = nalgebra_v0_34::Vector4::<T>::SCHEMA; |
| 33 | +} |
| 34 | + |
| 35 | +/// Const version of the const-unstable [`<[[T; N]]>::as_flattened()`] |
| 36 | +const fn flatten<T, const N: usize>(slice: &[[T; N]]) -> &[T] { |
| 37 | + const { |
| 38 | + assert!(size_of::<T>() != 0); |
| 39 | + } |
| 40 | + // SAFETY: `self.len() * N` cannot overflow because `self` is |
| 41 | + // already in the address space. |
| 42 | + let len = unsafe { slice.len().unchecked_mul(N) }; |
| 43 | + // SAFETY: `[T]` is layout-identical to `[T; N]` |
| 44 | + unsafe { core::slice::from_raw_parts(slice.as_ptr().cast(), len) } |
| 45 | +} |
| 46 | + |
| 47 | +#[test] |
| 48 | +fn flattened() { |
| 49 | + type T = nalgebra_v0_34::SMatrix<u8, 3, 3>; |
| 50 | + assert_eq!(T::SCHEMA.ty, <[u8; 9]>::SCHEMA.ty); |
| 51 | +} |
| 52 | + |
| 53 | +#[test] |
| 54 | +fn smoke() { |
| 55 | + let x = nalgebra_v0_34::SMatrix::<u8, 3, 3>::new(1, 2, 3, 4, 5, 6, 7, 8, 9); |
| 56 | + let y = postcard::to_stdvec(&x).unwrap(); |
| 57 | + assert_eq!(&[1, 4, 7, 2, 5, 8, 3, 6, 9], y.as_slice()); |
| 58 | +} |
0 commit comments