Skip to content

Instantly share code, notes, and snippets.

@bltavares
Created October 29, 2015 20:50
Show Gist options
  • Save bltavares/b161798cc07a1e551ad6 to your computer and use it in GitHub Desktop.
Save bltavares/b161798cc07a1e551ad6 to your computer and use it in GitHub Desktop.
diff --git a/src/libstd/io/stdio.rs b/src/libstd/io/stdio.rs
index 31b881b..0879918 100644
--- a/src/libstd/io/stdio.rs
+++ b/src/libstd/io/stdio.rs
@@ -576,7 +576,14 @@ pub fn set_print(sink: Box<Write + Send>) -> Option<Box<Write + Send>> {
issue = "0")]
#[doc(hidden)]
pub fn _print(args: fmt::Arguments) {
- let result = LOCAL_STDOUT.with(|s| {
+ result = _try_print(args);
+ if let Err(e) = result {
+ panic!("failed printing to stdout: {}", e);
+ }
+}
+
+pub fn _try_print(args: fmt::Arguments) {
+ LOCAL_STDOUT.with(|s| {
if s.borrow_state() == BorrowState::Unused {
if let Some(w) = s.borrow_mut().as_mut() {
return w.write_fmt(args);
@@ -584,9 +591,6 @@ pub fn _print(args: fmt::Arguments) {
}
stdout().write_fmt(args)
});
- if let Err(e) = result {
- panic!("failed printing to stdout: {}", e);
- }
}
#[cfg(test)]
diff --git a/src/libstd/macros.rs b/src/libstd/macros.rs
index a88ddb9..d9e1ba9 100644
--- a/src/libstd/macros.rs
+++ b/src/libstd/macros.rs
@@ -98,6 +98,12 @@ macro_rules! print {
($($arg:tt)*) => ($crate::io::_print(format_args!($($arg)*)));
}
+#[macro_export]
+#[allow_internal_unstable]
+macro_rules! try_print {
+ ($($arg:tt)*) => ($crate::io::_try_print(format_args!($($arg)*)));
+}
+
/// Macro for printing to the standard output, with a newline.
///
/// Use the `format!` syntax to write data to the standard output.
@@ -120,6 +126,12 @@ macro_rules! println {
($fmt:expr, $($arg:tt)*) => (print!(concat!($fmt, "\n"), $($arg)*));
}
+#[macro_export]
+macro_rules! try_println {
+ ($fmt:expr) => (try_print!(concat!($fmt, "\n")));
+ ($fmt:expr, $($arg:tt)*) => (try_print!(concat!($fmt, "\n"), $($arg)*));
+}
+
/// Helper macro for unwrapping `Result` values while returning early with an
/// error if the value of the expression is `Err`. Can only be used in
/// functions that return `Result` because of the early return of `Err` that
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment