From 9c3dbc2658d5d96939c48b878dc0f87fcb52e385 Mon Sep 17 00:00:00 2001 From: Brendan Zabarauskas Date: Mon, 29 Oct 2012 15:47:53 +1000 Subject: [PATCH] Improve Index trait implementation --- src/quat.rs | 17 +++++++++-------- src/vec.rs | 33 ++++++++++++++++----------------- 2 files changed, 25 insertions(+), 25 deletions(-) diff --git a/src/quat.rs b/src/quat.rs index ecbea8d..cba4756 100644 --- a/src/quat.rs +++ b/src/quat.rs @@ -1,6 +1,9 @@ -use std::cmp::FuzzyEq; +use cast::transmute; +use core::vec::raw::buf_as_slice; // for some reason we need to specify the core module here +use ptr::to_unsafe_ptr; use cmp::Eq; -use math::Sqrt; +use std::cmp::FuzzyEq; +use math::*; use mat::{Mat3, Mat4}; use vec::Vec3; @@ -161,12 +164,10 @@ pub impl Quat: Quaternion { pub impl Quat: Index { #[inline] pure fn index(i: uint) -> float { - match i { - 0 => self.w, - 1 => self.x, - 2 => self.y, - 3 => self.z, - _ => fail(~"Vector index out of bounds.") + unsafe { + do buf_as_slice( + transmute::<*Quat, *float>( + to_unsafe_ptr(&self)), 4) |slice| { slice[i] } } } } diff --git a/src/vec.rs b/src/vec.rs index d21d145..040d532 100644 --- a/src/vec.rs +++ b/src/vec.rs @@ -1,6 +1,9 @@ -use std::cmp::FuzzyEq; +use cast::transmute; +use core::vec::raw::buf_as_slice; // for some reason we need to specify the core module here +use ptr::to_unsafe_ptr; use cmp::Eq; -use math::{Abs, abs, min, max, Sqrt}; +use std::cmp::FuzzyEq; +use math::*; // // N-dimensional Vector @@ -152,10 +155,10 @@ pub impl Vec2: Vector { pub impl Vec2: Index { #[inline] pure fn index(i: uint) -> float { - match i { - 0 => self.x, - 1 => self.y, - _ => fail(~"Vector index out of bounds.") + unsafe { + do buf_as_slice( + transmute::<*Vec2, *float>( + to_unsafe_ptr(&self)), 2) |slice| { slice[i] } } } } @@ -338,11 +341,9 @@ pub impl Vec3: Vector { pub impl Vec3: Index { #[inline] pure fn index(i: uint) -> float { - match i { - 0 => self.x, - 1 => self.y, - 2 => self.z, - _ => fail(~"Vector index out of bounds.") + unsafe { do buf_as_slice( + transmute::<*Vec3, *float>( + to_unsafe_ptr(&self)), 3) |slice| { slice[i] } } } } @@ -530,12 +531,10 @@ pub impl Vec4: Vector { pub impl Vec4: Index { #[inline] pure fn index(i: uint) -> float { - match i { - 0 => self.x, - 1 => self.y, - 2 => self.z, - 3 => self.w, - _ => fail(~"Vector index out of bounds.") + unsafe { + do buf_as_slice( + transmute::<*Vec4, *float>( + to_unsafe_ptr(&self)), 4) |slice| { slice[i] } } } }