libcore: add first_ref and second_ref to tuples

This commit is contained in:
Erick Tryzelaar 2012-10-07 16:01:01 -07:00
parent d301dd3686
commit 91b7a9a529
2 changed files with 28 additions and 3 deletions

View file

@ -11,7 +11,7 @@ pub use GenericPath = path::GenericPath;
pub use WindowsPath = path::WindowsPath;
pub use PosixPath = path::PosixPath;
pub use tuple::{TupleOps, ExtendedTupleOps};
pub use tuple::{CopyableTuple, ImmutableTuple, ExtendedTupleOps};
pub use str::{StrSlice, UniqueStr};
pub use vec::{ConstVector, CopyableVector, ImmutableVector};
pub use vec::{ImmutableEqVector, ImmutableCopyableVector};

View file

@ -6,13 +6,13 @@
use cmp::{Eq, Ord};
pub trait TupleOps<T,U> {
pub trait CopyableTuple<T, U> {
pure fn first() -> T;
pure fn second() -> U;
pure fn swap() -> (U, T);
}
impl<T: Copy, U: Copy> (T, U): TupleOps<T,U> {
impl<T: Copy, U: Copy> (T, U): CopyableTuple<T, U> {
/// Return the first element of self
pure fn first() -> T {
@ -34,6 +34,24 @@ impl<T: Copy, U: Copy> (T, U): TupleOps<T,U> {
}
pub trait ImmutableTuple<T, U> {
pure fn first_ref(&self) -> &self/T;
pure fn second_ref(&self) -> &self/U;
}
impl<T, U> (T, U): ImmutableTuple<T, U> {
pure fn first_ref(&self) -> &self/T {
match *self {
(ref t, _) => t,
}
}
pure fn second_ref(&self) -> &self/U {
match *self {
(_, ref u) => u,
}
}
}
pub trait ExtendedTupleOps<A,B> {
fn zip(&self) -> ~[(A, B)];
fn map<C>(&self, f: &fn(a: &A, b: &B) -> C) -> ~[C];
@ -145,6 +163,13 @@ impl<A: Ord, B: Ord, C: Ord> (A, B, C) : Ord {
pure fn gt(other: &(A, B, C)) -> bool { (*other).lt(&self) }
}
#[test]
fn test_tuple_ref() {
let (~"foo", ~"bar");
assert x.first_ref() == &~"foo";
assert x.second_ref() == &~"bar";
}
#[test]
#[allow(non_implicitly_copyable_typarams)]
fn test_tuple() {