From bf6abf8cb3d1e169c1baab8d266bd43c58dfbcc6 Mon Sep 17 00:00:00 2001 From: Brendan Zabarauskas Date: Sat, 15 Feb 2014 01:20:43 +1100 Subject: [PATCH] Implement Show for 1-12 element tuples --- src/libstd/tuple.rs | 26 ++++++++++++++++++++++++++ 1 file changed, 26 insertions(+) diff --git a/src/libstd/tuple.rs b/src/libstd/tuple.rs index 33d23df242c..9a1fda07ecd 100644 --- a/src/libstd/tuple.rs +++ b/src/libstd/tuple.rs @@ -15,6 +15,8 @@ use clone::Clone; #[cfg(not(test))] use cmp::*; #[cfg(not(test))] use default::Default; +use fmt; +use result::{Ok, Err}; /// Method extensions to pairs where both types satisfy the `Clone` bound pub trait CloneableTuple { @@ -176,6 +178,12 @@ fn default() -> ($($T,)+) { ($({ let x: $T = Default::default(); x},)+) } } + + impl<$($T: fmt::Show),+> fmt::Show for ($($T,)+) { + fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { + write_tuple!(f.buf, $(self.$get_ref_fn()),+) + } + } )+ } } @@ -202,6 +210,17 @@ macro_rules! lexical_cmp { ($a:expr, $b:expr) => { ($a).cmp($b) }; } +macro_rules! write_tuple { + ($buf:expr, $x:expr) => ( + write!($buf, "({},)", *$x) + ); + ($buf:expr, $hd:expr, $($tl:expr),+) => ({ + if_ok!(write!($buf, "(")); + if_ok!(write!($buf, "{}", *$hd)); + $(if_ok!(write!($buf, ", {}", *$tl));)+ + write!($buf, ")") + }); +} tuple_impls! { (Tuple1, ImmutableTuple1) { @@ -422,4 +441,11 @@ fn test_tuple_cmp() { assert_eq!(small.cmp(&big), Less); assert_eq!(big.cmp(&small), Greater); } + + #[test] + fn test_show() { + assert_eq!(format!("{}", (1,)), ~"(1,)"); + assert_eq!(format!("{}", (1, true)), ~"(1, true)"); + assert_eq!(format!("{}", (1, ~"hi", true)), ~"(1, hi, true)"); + } }