From 1e71dc1d0a3cc97af8bb0c903b7cfd535cda8ba4 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?S=C3=A9bastien=20Crozet?= Date: Sun, 1 Dec 2013 20:17:18 +0100 Subject: [PATCH] Add unchecked access to vector components on the Indexable trait. --- src/structs/mat_macros.rs | 10 ++++++++++ src/structs/spec/vec0.rs | 9 ++++++++- src/structs/vec_macros.rs | 10 ++++++++++ src/traits/structure.rs | 9 +++++++++ 4 files changed, 37 insertions(+), 1 deletion(-) diff --git a/src/structs/mat_macros.rs b/src/structs/mat_macros.rs index 9b5da7db..e5744af5 100644 --- a/src/structs/mat_macros.rs +++ b/src/structs/mat_macros.rs @@ -192,6 +192,16 @@ macro_rules! indexable_impl( .swap(i1 + j1 * $dim, i2 + j2 * $dim) } } + + #[inline] + unsafe fn unsafe_at(&self, (i, j): (uint, uint)) -> N { + (*cast::transmute::<&$t, &[N, ..$dim * $dim]>(self).unsafe_ref(i + j * $dim)).clone() + } + + #[inline] + unsafe fn unsafe_set(&mut self, (i, j): (uint, uint), val: N) { + (*cast::transmute::<&mut $t, &mut [N, ..$dim * $dim]>(self).unsafe_mut_ref(i + j * $dim)) = val + } } ) ) diff --git a/src/structs/spec/vec0.rs b/src/structs/spec/vec0.rs index 1b1a9b90..01d2af76 100644 --- a/src/structs/spec/vec0.rs +++ b/src/structs/spec/vec0.rs @@ -23,12 +23,19 @@ impl Indexable for vec::Vec0 { #[inline] fn set(&mut self, _: uint, _: N) { - } #[inline] fn swap(&mut self, _: uint, _: uint) { + } + #[inline] + unsafe fn unsafe_at(&self, _: uint) -> N { + fail!("Cannot index a Vec0.") + } + + #[inline] + unsafe fn unsafe_set(&mut self, _: uint, _: N) { } } diff --git a/src/structs/vec_macros.rs b/src/structs/vec_macros.rs index f8067002..fb15ddea 100644 --- a/src/structs/vec_macros.rs +++ b/src/structs/vec_macros.rs @@ -144,6 +144,16 @@ macro_rules! indexable_impl( cast::transmute::<&mut $t, &mut [N, ..$dim]>(self).swap(i1, i2) } } + + #[inline] + unsafe fn unsafe_at(&self, i: uint) -> N { + (*cast::transmute::<&$t, &[N, ..$dim]>(self).unsafe_ref(i)).clone() + } + + #[inline] + unsafe fn unsafe_set(&mut self, i: uint, val: N) { + (*cast::transmute::<&mut $t, &mut [N, ..$dim]>(self).unsafe_mut_ref(i)) = val + } } ) ) diff --git a/src/traits/structure.rs b/src/traits/structure.rs index ac664003..1c35c4a6 100644 --- a/src/traits/structure.rs +++ b/src/traits/structure.rs @@ -113,6 +113,15 @@ pub trait Indexable { fn set(&mut self, i: Index, Res); /// Swaps the `i`-th element of `self` with its `j`-th element. fn swap(&mut self, i: Index, j: Index); + + /// Reads the `i`-th element of `self`. + /// + /// `i` is not checked. + unsafe fn unsafe_at(&self, i: Index) -> Res; + /// Writes to the `i`-th element of `self`. + /// + /// `i` is not checked. + unsafe fn unsafe_set(&mut self, i: Index, Res); } /// This is a workaround of current Rust limitations.