Add map_as_vec{2,3,4} methods and document AsVec method impls

These are useful for when for reusing methods available on the Vec{2,3,4} types.
This commit is contained in:
Brendan Zabarauskas 2013-07-21 13:20:28 +10:00
parent a5c00bfe97
commit 31be8b79df
2 changed files with 17 additions and 4 deletions

View file

@ -61,25 +61,35 @@ macro_rules! impl_to_vec_helper(
)
macro_rules! impl_as_vec(
($Self:ident, 2) => (impl_as_vec_helper!(AsVec2, $Self, Vec2, as_vec2, as_mut_vec2));
($Self:ident, 3) => (impl_as_vec_helper!(AsVec3, $Self, Vec3, as_vec3, as_mut_vec3));
($Self:ident, 4) => (impl_as_vec_helper!(AsVec4, $Self, Vec4, as_vec4, as_mut_vec4));
($Self:ident, 2) => (impl_as_vec_helper!(AsVec2, $Self, Vec2, as_vec2, as_mut_vec2, map_as_vec2));
($Self:ident, 3) => (impl_as_vec_helper!(AsVec3, $Self, Vec3, as_vec3, as_mut_vec3, map_as_vec3));
($Self:ident, 4) => (impl_as_vec_helper!(AsVec4, $Self, Vec4, as_vec4, as_mut_vec4, map_as_vec4));
)
macro_rules! impl_as_vec_helper(
($AsVec:ident, $Self:ident, $Vec:ident, $as_vec:ident, $as_mut_vec:ident) => (
($AsVec:ident, $Self:ident, $Vec:ident, $as_vec:ident, $as_mut_vec:ident, $map_as_vec:ident) => (
impl<T> $AsVec<T> for $Self<T> {
/// Safely transmute to a vec.
#[inline]
pub fn $as_vec<'a>(&'a self) -> &'a $Vec<T> {
use std::cast::transmute;
unsafe { transmute(self) }
}
/// Safely transmute to a mutable vec.
#[inline]
pub fn $as_mut_vec<'a>(&'a mut self) -> &'a mut $Vec<T> {
use std::cast::transmute;
unsafe { transmute(self) }
}
/// Operate on `self` transmuted to a vec, then return the result as
/// transmuted back to the `Self` type.
#[inline]
pub fn $map_as_vec<'a>(&'a self, f: &fn(&'a $Vec<T>) -> $Vec<T>) -> $Self<T> {
use std::cast::transmute;
unsafe { transmute(f(self.$as_vec())) }
}
}
)
)

View file

@ -136,6 +136,7 @@ pub trait ToVec2<T> {
pub trait AsVec2<T> {
pub fn as_vec2<'a>(&'a self) -> &'a Vec2<T>;
pub fn as_mut_vec2<'a>(&'a mut self) -> &'a mut Vec2<T>;
pub fn map_as_vec2<'a>(&'a self, f: &fn(&'a Vec2<T>) -> Vec2<T>) -> Self;
}
impl_dimensioned!(Vec2, T, 2)
@ -755,6 +756,7 @@ pub trait ToVec3<T> {
pub trait AsVec3<T> {
pub fn as_vec3<'a>(&'a self) -> &'a Vec3<T>;
pub fn as_mut_vec3<'a>(&'a mut self) -> &'a mut Vec3<T>;
pub fn map_as_vec3<'a>(&'a self, f: &fn(&'a Vec3<T>) -> Vec3<T>) -> Self;
}
impl_dimensioned!(Vec3, T, 3)
@ -1446,6 +1448,7 @@ pub trait ToVec4<T> {
pub trait AsVec4<T> {
pub fn as_vec4<'a>(&'a self) -> &'a Vec4<T>;
pub fn as_mut_vec4<'a>(&'a mut self) -> &'a mut Vec4<T>;
pub fn map_as_vec4<'a>(&'a self, f: &fn(&'a Vec4<T>) -> Vec4<T>) -> Self;
}
impl_dimensioned!(Vec4, T, 4)