Type-cast a vector component-wise

This allows one to e.g. cast a vector of f64s to an equivalent vector of f32s.
More generally this is allowed for arbitrary NumCast types.
This commit is contained in:
Eduard Bopp 2014-11-20 15:24:38 +01:00
parent 9f8580eeca
commit 4d2fb64482
2 changed files with 19 additions and 0 deletions

View file

@ -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<T: NumCast>(&self) -> $Self<T> {
$Self { $($field: NumCast::from(self.$field).unwrap()),+ }
}
}
impl<$S> FixedArray<[$S, ..$n]> for $Self<$S> {
#[inline]
fn into_fixed(self) -> [$S, ..$n] {

View file

@ -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));
}