Skip to content

Use new io in print and println macroses #23206

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 1 commit into from
Mar 15, 2015
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion src/librustc_driver/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -37,7 +37,7 @@
#![feature(staged_api)]
#![feature(exit_status)]
#![feature(io)]
#![feature(set_panic)]
#![feature(set_stdio)]

extern crate arena;
extern crate flate;
Expand Down
2 changes: 1 addition & 1 deletion src/librustdoc/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -26,7 +26,7 @@
#![feature(core)]
#![feature(exit_status)]
#![feature(int_uint)]
#![feature(set_panic)]
#![feature(set_stdio)]
#![feature(libc)]
#![feature(old_path)]
#![feature(rustc_private)]
Expand Down
4 changes: 2 additions & 2 deletions src/libstd/io/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -37,10 +37,10 @@ pub use self::buffered::IntoInnerError;
pub use self::cursor::Cursor;
pub use self::error::{Result, Error, ErrorKind};
pub use self::util::{copy, sink, Sink, empty, Empty, repeat, Repeat};
pub use self::stdio::{stdin, stdout, stderr, Stdin, Stdout, Stderr};
pub use self::stdio::{stdin, stdout, stderr, _print, Stdin, Stdout, Stderr};
pub use self::stdio::{StdoutLock, StderrLock, StdinLock};
#[doc(no_inline, hidden)]
pub use self::stdio::set_panic;
pub use self::stdio::{set_panic, set_print};

#[macro_use] mod lazy;

Expand Down
52 changes: 47 additions & 5 deletions src/libstd/io/stdio.rs
Original file line number Diff line number Diff line change
Expand Up @@ -11,13 +11,21 @@
use prelude::v1::*;
use io::prelude::*;

use cell::RefCell;
use cmp;
use fmt;
use io::lazy::Lazy;
use io::{self, BufReader, LineWriter};
use sync::{Arc, Mutex, MutexGuard};
use sys::stdio;

/// Stdout used by print! and println! macroses
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

macros?

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Since this code is internal and docstring won’t appear in any public-facing documentation, I believe it is not worth updating this unless this bounces.

thread_local! {
static LOCAL_STDOUT: RefCell<Option<Box<Write + Send>>> = {
RefCell::new(None)
}
}

/// A handle to a raw instance of the standard input stream of this process.
///
/// This handle is not synchronized or buffered in any fashion. Constructed via
Expand Down Expand Up @@ -347,15 +355,15 @@ impl<'a> Write for StderrLock<'a> {
fn flush(&mut self) -> io::Result<()> { self.inner.flush() }
}

/// Resets the task-local stdout handle to the specified writer
/// Resets the task-local stderr handle to the specified writer
///
/// This will replace the current task's stdout handle, returning the old
/// handle. All future calls to `print` and friends will emit their output to
/// This will replace the current task's stderr handle, returning the old
/// handle. All future calls to `panic!` and friends will emit their output to
/// this specified handle.
///
/// Note that this does not need to be called for all new tasks; the default
/// output handle is to the process's stdout stream.
#[unstable(feature = "set_panic",
/// output handle is to the process's stderr stream.
#[unstable(feature = "set_stdio",
reason = "this function may disappear completely or be replaced \
with a more general mechanism")]
#[doc(hidden)]
Expand All @@ -369,3 +377,37 @@ pub fn set_panic(sink: Box<Write + Send>) -> Option<Box<Write + Send>> {
Some(s)
})
}

/// Resets the task-local stdout handle to the specified writer
///
/// This will replace the current task's stdout handle, returning the old
/// handle. All future calls to `print!` and friends will emit their output to
/// this specified handle.
///
/// Note that this does not need to be called for all new tasks; the default
/// output handle is to the process's stdout stream.
#[unstable(feature = "set_stdio",
reason = "this function may disappear completely or be replaced \
with a more general mechanism")]
#[doc(hidden)]
pub fn set_print(sink: Box<Write + Send>) -> Option<Box<Write + Send>> {
use mem;
LOCAL_STDOUT.with(move |slot| {
mem::replace(&mut *slot.borrow_mut(), Some(sink))
}).and_then(|mut s| {
let _ = s.flush();
Some(s)
})
}

#[unstable(feature = "print",
reason = "implementation detail which may disappear or be replaced at any time")]
#[doc(hidden)]
pub fn _print(args: fmt::Arguments) {
if let Err(e) = LOCAL_STDOUT.with(|s| match s.borrow_mut().as_mut() {
Some(w) => w.write_fmt(args),
None => stdout().write_fmt(args)
}) {
panic!("failed printing to stdout: {}", e);
}
}
15 changes: 9 additions & 6 deletions src/libstd/macros.rs
Original file line number Diff line number Diff line change
Expand Up @@ -60,19 +60,21 @@ macro_rules! panic {
});
}

/// Macro for printing to the standard output.
///
/// Equivalent to the `println!` macro except that a newline is not printed at
/// the end of the message.
#[macro_export]
#[stable(feature = "rust1", since = "1.0.0")]
#[allow_internal_unstable]
macro_rules! print {
($($arg:tt)*) => ($crate::old_io::stdio::print_args(format_args!($($arg)*)))
($($arg:tt)*) => ($crate::io::_print(format_args!($($arg)*)));
}

/// Macro for printing to a task's stdout handle.
/// Macro for printing to the standard output.
///
/// Each task can override its stdout handle via `std::old_io::stdio::set_stdout`.
/// The syntax of this macro is the same as that used for `format!`. For more
/// information, see `std::fmt` and `std::old_io::stdio`.
/// Use the `format!` syntax to write data to the standard output.
/// See `std::fmt` for more information.
///
/// # Examples
///
Expand All @@ -83,7 +85,8 @@ macro_rules! print {
#[macro_export]
#[stable(feature = "rust1", since = "1.0.0")]
macro_rules! println {
($($arg:tt)*) => ($crate::old_io::stdio::println_args(format_args!($($arg)*)))
($fmt:expr) => (print!(concat!($fmt, "\n")));
($fmt:expr, $($arg:tt)*) => (print!(concat!($fmt, "\n"), $($arg)*));
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Nice!

}

/// Helper macro for unwrapping `Result` values while returning early with an
Expand Down
14 changes: 0 additions & 14 deletions src/libstd/old_io/stdio.rs
Original file line number Diff line number Diff line change
Expand Up @@ -535,18 +535,4 @@ mod tests {
stdout();
stderr();
}

#[test]
fn capture_stdout() {
use old_io::{ChanReader, ChanWriter};

let (tx, rx) = channel();
let (mut r, w) = (ChanReader::new(rx), ChanWriter::new(tx));
// FIXME (#22405): Replace `Box::new` with `box` here when/if possible.
let _t = thread::spawn(move|| {
set_stdout(Box::new(w));
println!("hello!");
});
assert_eq!(r.read_to_string().unwrap(), "hello!\n");
}
}
11 changes: 2 additions & 9 deletions src/libtest/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -39,13 +39,12 @@
#![feature(collections)]
#![feature(core)]
#![feature(int_uint)]
#![feature(old_io)]
#![feature(rustc_private)]
#![feature(staged_api)]
#![feature(std_misc)]
#![feature(io)]
#![feature(libc)]
#![feature(set_panic)]
#![feature(set_stdio)]

extern crate getopts;
extern crate serialize;
Expand Down Expand Up @@ -909,7 +908,6 @@ pub fn run_test(opts: &TestOpts,
return;
}

#[allow(deprecated)] // set_stdout
fn run_test_inner(desc: TestDesc,
monitor_ch: Sender<MonitorMsg>,
nocapture: bool,
Expand All @@ -921,11 +919,6 @@ pub fn run_test(opts: &TestOpts,
}
fn flush(&mut self) -> io::Result<()> { Ok(()) }
}
impl Writer for Sink {
fn write_all(&mut self, data: &[u8]) -> std::old_io::IoResult<()> {
Writer::write_all(&mut *self.0.lock().unwrap(), data)
}
}

thread::spawn(move || {
let data = Arc::new(Mutex::new(Vec::new()));
Expand All @@ -937,7 +930,7 @@ pub fn run_test(opts: &TestOpts,

let result_guard = cfg.spawn(move || {
if !nocapture {
std::old_io::stdio::set_stdout(box Sink(data2.clone()));
io::set_print(box Sink(data2.clone()));
io::set_panic(box Sink(data2));
}
testfn.invoke(())
Expand Down
19 changes: 0 additions & 19 deletions src/libtest/stats.rs
Original file line number Diff line number Diff line change
Expand Up @@ -11,9 +11,6 @@
#![allow(missing_docs)]

use std::cmp::Ordering::{self, Less, Greater, Equal};
use std::collections::hash_map::Entry::{Occupied, Vacant};
use std::collections::hash_map;
use std::hash::Hash;
use std::mem;
use std::num::{Float, FromPrimitive};

Expand Down Expand Up @@ -330,22 +327,6 @@ pub fn winsorize<T: Float + FromPrimitive>(samples: &mut [T], pct: T) {
}
}

/// Returns a HashMap with the number of occurrences of every element in the
/// sequence that the iterator exposes.
#[cfg(not(stage0))]
pub fn freq_count<T, U>(iter: T) -> hash_map::HashMap<U, uint>
where T: Iterator<Item=U>, U: Eq + Clone + Hash
{
let mut map: hash_map::HashMap<U,uint> = hash_map::HashMap::new();
for elem in iter {
match map.entry(elem) {
Occupied(mut entry) => { *entry.get_mut() += 1; },
Vacant(entry) => { entry.insert(1); },
}
}
map
}

// Test vectors generated from R, using the script src/etc/stat-test-vectors.r.

#[cfg(test)]
Expand Down