diff --git a/src/vector.rs b/src/vector.rs index 3d78eef..8351b99 100644 --- a/src/vector.rs +++ b/src/vector.rs @@ -98,6 +98,7 @@ use std::fmt; use std::mem; +use std::num::NumCast; use angle::{Rad, atan2, acos}; use approx::ApproxEq; @@ -208,6 +209,14 @@ macro_rules! vec( fn one() -> $Self<$S> { $Self { $($field: one()),+ } } } + impl<$S: NumCast + Copy> $Self<$S> { + /// Component-wise casting to another type + #[inline] + pub fn cast(&self) -> $Self { + $Self { $($field: NumCast::from(self.$field).unwrap()),+ } + } + } + impl<$S> FixedArray<[$S, ..$n]> for $Self<$S> { #[inline] fn into_fixed(self) -> [$S, ..$n] { diff --git a/tests/vector.rs b/tests/vector.rs index 0d74a7e..446b53f 100644 --- a/tests/vector.rs +++ b/tests/vector.rs @@ -14,7 +14,10 @@ // limitations under the License. #![feature(globs)] +#![feature(phase)] +#[phase(plugin)] +extern crate cgmath; extern crate cgmath; use cgmath::*; @@ -166,3 +169,10 @@ fn test_map() { assert_eq!(Vector3::new(7.12f64, 3.8f64, -6.98f64).map(|x| x.floor()), Vector3::new(7.0f64, 3.0f64, -7.0f64)); assert_eq!(Vector3::new(7.12f64, 3.8f64, -6.98f64).map(|x| x.max(0.0f64)), Vector3::new(7.12f64, 3.8f64, 0.0f64)); } + +#[test] +fn test_cast() { + assert_approx_eq!(Vector2::new(0.9f64, 1.5).cast(), Vector2::new(0.9f32, 1.5)); + assert_approx_eq!(Vector3::new(1.0f64, 2.4, -3.13).cast(), Vector3::new(1.0f32, 2.4, -3.13)); + assert_approx_eq!(Vector4::new(13.5f64, -4.6, -8.3, 2.41).cast(), Vector4::new(13.5f32, -4.6, -8.3, 2.41)); +}