Skip to content

Commit 91b7a9a

Browse files
committed
libcore: add first_ref and second_ref to tuples
1 parent d301dd3 commit 91b7a9a

File tree

2 files changed

+28
-3
lines changed

2 files changed

+28
-3
lines changed

src/libcore/core.rs

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -11,7 +11,7 @@ pub use GenericPath = path::GenericPath;
1111
pub use WindowsPath = path::WindowsPath;
1212
pub use PosixPath = path::PosixPath;
1313

14-
pub use tuple::{TupleOps, ExtendedTupleOps};
14+
pub use tuple::{CopyableTuple, ImmutableTuple, ExtendedTupleOps};
1515
pub use str::{StrSlice, UniqueStr};
1616
pub use vec::{ConstVector, CopyableVector, ImmutableVector};
1717
pub use vec::{ImmutableEqVector, ImmutableCopyableVector};

src/libcore/tuple.rs

Lines changed: 27 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -6,13 +6,13 @@
66
77
use cmp::{Eq, Ord};
88

9-
pub trait TupleOps<T,U> {
9+
pub trait CopyableTuple<T, U> {
1010
pure fn first() -> T;
1111
pure fn second() -> U;
1212
pure fn swap() -> (U, T);
1313
}
1414

15-
impl<T: Copy, U: Copy> (T, U): TupleOps<T,U> {
15+
impl<T: Copy, U: Copy> (T, U): CopyableTuple<T, U> {
1616

1717
/// Return the first element of self
1818
pure fn first() -> T {
@@ -34,6 +34,24 @@ impl<T: Copy, U: Copy> (T, U): TupleOps<T,U> {
3434

3535
}
3636

37+
pub trait ImmutableTuple<T, U> {
38+
pure fn first_ref(&self) -> &self/T;
39+
pure fn second_ref(&self) -> &self/U;
40+
}
41+
42+
impl<T, U> (T, U): ImmutableTuple<T, U> {
43+
pure fn first_ref(&self) -> &self/T {
44+
match *self {
45+
(ref t, _) => t,
46+
}
47+
}
48+
pure fn second_ref(&self) -> &self/U {
49+
match *self {
50+
(_, ref u) => u,
51+
}
52+
}
53+
}
54+
3755
pub trait ExtendedTupleOps<A,B> {
3856
fn zip(&self) -> ~[(A, B)];
3957
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 {
145163
pure fn gt(other: &(A, B, C)) -> bool { (*other).lt(&self) }
146164
}
147165

166+
#[test]
167+
fn test_tuple_ref() {
168+
let (~"foo", ~"bar");
169+
assert x.first_ref() == &~"foo";
170+
assert x.second_ref() == &~"bar";
171+
}
172+
148173
#[test]
149174
#[allow(non_implicitly_copyable_typarams)]
150175
fn test_tuple() {

0 commit comments

Comments
 (0)