Add general Dimensioned and SwapComponents impls

This commit is contained in:
Brendan Zabarauskas 2013-07-25 12:52:25 +10:00
parent 679db701c9
commit df3ce2935c
2 changed files with 97 additions and 0 deletions

View file

@ -40,6 +40,31 @@ macro_rules! impl_dimensioned(
unsafe { transmute(self) }
}
}
);
($Self:ident) => (
impl Dimensioned<$Self,[$Self,..1]> for $Self {
#[inline]
pub fn i<'a>(&'a self, i: uint) -> &'a $Self {
&'a self.as_slice()[i]
}
#[inline]
pub fn mut_i<'a>(&'a mut self, i: uint) -> &'a mut $Self {
&'a mut self.as_mut_slice()[i]
}
#[inline]
pub fn as_slice<'a>(&'a self) -> &'a [$Self,..1] {
use std::cast::transmute;
unsafe { transmute(self) }
}
#[inline]
pub fn as_mut_slice<'a>(&'a mut self) -> &'a mut [$Self,..1] {
use std::cast::transmute;
unsafe { transmute(self) }
}
}
)
)

View file

@ -50,3 +50,75 @@ pub trait Dimensioned<T,Slice> {
pub trait SwapComponents {
pub fn swap(&mut self, a: uint, b: uint);
}
// `Dimensioned` impls for primitive numeric types
impl_dimensioned!(u8)
impl_dimensioned!(u16)
impl_dimensioned!(u32)
impl_dimensioned!(u64)
impl_dimensioned!(uint)
impl_dimensioned!(i8)
impl_dimensioned!(i16)
impl_dimensioned!(i32)
impl_dimensioned!(i64)
impl_dimensioned!(int)
impl_dimensioned!(f32)
impl_dimensioned!(f64)
impl_dimensioned!(float)
// Helper type aliases for implementing `Dimendioned` and `SwapComponents`
// for tuples.
pub type Tuple1<T> = (T,);
pub type Tuple2<T> = (T,T);
pub type Tuple3<T> = (T,T,T);
pub type Tuple4<T> = (T,T,T,T);
pub type Tuple5<T> = (T,T,T,T,T);
pub type Tuple6<T> = (T,T,T,T,T,T);
// `Dimensioned` impls for tuples
impl_dimensioned!(Tuple1, T, 1)
impl_dimensioned!(Tuple2, T, 2)
impl_dimensioned!(Tuple3, T, 3)
impl_dimensioned!(Tuple4, T, 4)
impl_dimensioned!(Tuple5, T, 5)
impl_dimensioned!(Tuple6, T, 6)
// `SwapComponents` impls for tuples
impl_swap_components!(Tuple1)
impl_swap_components!(Tuple2)
impl_swap_components!(Tuple3)
impl_swap_components!(Tuple4)
impl_swap_components!(Tuple5)
impl_swap_components!(Tuple6)
// Helper type aliases for implementing `Dimendioned` and `SwapComponents`
// for fixed length vectors.
pub type Fixed1<T> = [T, ..1];
pub type Fixed2<T> = [T, ..2];
pub type Fixed3<T> = [T, ..3];
pub type Fixed4<T> = [T, ..4];
pub type Fixed5<T> = [T, ..5];
pub type Fixed6<T> = [T, ..6];
// `Dimensioned` impls for fixed length vectors
impl_dimensioned!(Fixed1, T, 1)
impl_dimensioned!(Fixed2, T, 2)
impl_dimensioned!(Fixed3, T, 3)
impl_dimensioned!(Fixed4, T, 4)
impl_dimensioned!(Fixed5, T, 5)
impl_dimensioned!(Fixed6, T, 6)
// `SwapComponents` impls for fixed length vectors
impl_swap_components!(Fixed1)
impl_swap_components!(Fixed2)
impl_swap_components!(Fixed3)
impl_swap_components!(Fixed4)
impl_swap_components!(Fixed5)
impl_swap_components!(Fixed6)