Skip to content

Commit 999d55d

Browse files
committed
auto merge of #12630 : alexcrichton/rust/flush-buffered, r=brson
Now that we can call `flush()` in destructors, I think that it's appropriate for stdout/stderr to return buffered writers by default. This doesn't enable certain functionality like a buffered stdin does, but it's what you want 90% of the time for performance reasons.
2 parents 11ca7ec + 2cb83fd commit 999d55d

File tree

10 files changed

+66
-35
lines changed

10 files changed

+66
-35
lines changed

src/librustc/lib.rs

+1-2
Original file line numberDiff line numberDiff line change
@@ -297,8 +297,7 @@ pub fn run_compiler(args: &[~str]) {
297297
match input {
298298
d::FileInput(ref ifile) => {
299299
let mut stdout = io::stdout();
300-
d::list_metadata(sess, &(*ifile),
301-
&mut stdout as &mut io::Writer).unwrap();
300+
d::list_metadata(sess, &(*ifile), &mut stdout).unwrap();
302301
}
303302
d::StrInput(_) => {
304303
d::early_error("can not list metadata for stdin");

src/libstd/fmt/mod.rs

+2-2
Original file line numberDiff line numberDiff line change
@@ -654,8 +654,8 @@ uniform_fn_call_workaround! {
654654
/// use std::fmt;
655655
/// use std::io;
656656
///
657-
/// let w = &mut io::stdout() as &mut io::Writer;
658-
/// format_args!(|args| { fmt::write(w, args); }, "Hello, {}!", "world");
657+
/// let mut w = io::stdout();
658+
/// format_args!(|args| { fmt::write(&mut w, args); }, "Hello, {}!", "world");
659659
/// ```
660660
pub fn write(output: &mut io::Writer, args: &Arguments) -> Result {
661661
unsafe { write_unsafe(output, args.fmt, args.args) }

src/libstd/io/buffered.rs

+25-14
Original file line numberDiff line numberDiff line change
@@ -14,7 +14,8 @@ use cmp;
1414
use container::Container;
1515
use io::{Reader, Writer, Stream, Buffer, DEFAULT_BUF_SIZE, IoResult};
1616
use iter::ExactSize;
17-
use option::{Some, None};
17+
use ops::Drop;
18+
use option::{Some, None, Option};
1819
use result::{Ok, Err};
1920
use vec::{OwnedVector, ImmutableVector, MutableVector};
2021
use vec;
@@ -115,7 +116,7 @@ impl<R: Reader> Reader for BufferedReader<R> {
115116

116117
/// Wraps a Writer and buffers output to it
117118
///
118-
/// Note that `BufferedWriter` will NOT flush its buffer when dropped.
119+
/// This writer will be flushed when it is dropped.
119120
///
120121
/// # Example
121122
///
@@ -130,7 +131,7 @@ impl<R: Reader> Reader for BufferedReader<R> {
130131
/// writer.flush();
131132
/// ```
132133
pub struct BufferedWriter<W> {
133-
priv inner: W,
134+
priv inner: Option<W>,
134135
priv buf: ~[u8],
135136
priv pos: uint
136137
}
@@ -142,7 +143,7 @@ impl<W: Writer> BufferedWriter<W> {
142143
let mut buf = vec::with_capacity(cap);
143144
unsafe { buf.set_len(cap); }
144145
BufferedWriter {
145-
inner: inner,
146+
inner: Some(inner),
146147
buf: buf,
147148
pos: 0
148149
}
@@ -155,7 +156,7 @@ impl<W: Writer> BufferedWriter<W> {
155156

156157
fn flush_buf(&mut self) -> IoResult<()> {
157158
if self.pos != 0 {
158-
let ret = self.inner.write(self.buf.slice_to(self.pos));
159+
let ret = self.inner.get_mut_ref().write(self.buf.slice_to(self.pos));
159160
self.pos = 0;
160161
ret
161162
} else {
@@ -167,15 +168,15 @@ impl<W: Writer> BufferedWriter<W> {
167168
///
168169
/// This type does not expose the ability to get a mutable reference to the
169170
/// underlying reader because that could possibly corrupt the buffer.
170-
pub fn get_ref<'a>(&'a self) -> &'a W { &self.inner }
171+
pub fn get_ref<'a>(&'a self) -> &'a W { self.inner.get_ref() }
171172

172173
/// Unwraps this buffer, returning the underlying writer.
173174
///
174175
/// The buffer is flushed before returning the writer.
175176
pub fn unwrap(mut self) -> W {
176-
// FIXME: is failing the right thing to do if flushing fails?
177+
// FIXME(#12628): is failing the right thing to do if flushing fails?
177178
self.flush_buf().unwrap();
178-
self.inner
179+
self.inner.take_unwrap()
179180
}
180181
}
181182

@@ -186,7 +187,7 @@ impl<W: Writer> Writer for BufferedWriter<W> {
186187
}
187188

188189
if buf.len() > self.buf.len() {
189-
self.inner.write(buf)
190+
self.inner.get_mut_ref().write(buf)
190191
} else {
191192
let dst = self.buf.mut_slice_from(self.pos);
192193
vec::bytes::copy_memory(dst, buf);
@@ -196,14 +197,24 @@ impl<W: Writer> Writer for BufferedWriter<W> {
196197
}
197198

198199
fn flush(&mut self) -> IoResult<()> {
199-
self.flush_buf().and_then(|()| self.inner.flush())
200+
self.flush_buf().and_then(|()| self.inner.get_mut_ref().flush())
201+
}
202+
}
203+
204+
#[unsafe_destructor]
205+
impl<W: Writer> Drop for BufferedWriter<W> {
206+
fn drop(&mut self) {
207+
if self.inner.is_some() {
208+
// FIXME(#12628): should this error be ignored?
209+
let _ = self.flush_buf();
210+
}
200211
}
201212
}
202213

203214
/// Wraps a Writer and buffers output to it, flushing whenever a newline (`0x0a`,
204215
/// `'\n'`) is detected.
205216
///
206-
/// Note that this structure does NOT flush the output when dropped.
217+
/// This writer will be flushed when it is dropped.
207218
pub struct LineBufferedWriter<W> {
208219
priv inner: BufferedWriter<W>,
209220
}
@@ -256,13 +267,13 @@ impl<W> InternalBufferedWriter<W> {
256267

257268
impl<W: Reader> Reader for InternalBufferedWriter<W> {
258269
fn read(&mut self, buf: &mut [u8]) -> IoResult<uint> {
259-
self.get_mut_ref().inner.read(buf)
270+
self.get_mut_ref().inner.get_mut_ref().read(buf)
260271
}
261272
}
262273

263-
/// Wraps a Stream and buffers input and output to and from it
274+
/// Wraps a Stream and buffers input and output to and from it.
264275
///
265-
/// Note that `BufferedStream` will NOT flush its output buffer when dropped.
276+
/// The output half will be flushed when this stream is dropped.
266277
///
267278
/// # Example
268279
///

src/libstd/io/stdio.rs

+29-5
Original file line numberDiff line numberDiff line change
@@ -90,6 +90,12 @@ fn src<T>(fd: libc::c_int, readable: bool, f: |StdSource| -> T) -> T {
9090
/// buffered access is not desired, the `stdin_raw` function is provided to
9191
/// provided unbuffered access to stdin.
9292
///
93+
/// Care should be taken when creating multiple handles to the stdin of a
94+
/// process. Beause this is a buffered reader by default, it's possible for
95+
/// pending input to be unconsumed in one reader and unavailable to other
96+
/// readers. It is recommended that only one handle at a time is created for the
97+
/// stdin of a process.
98+
///
9399
/// See `stdout()` for more notes about this function.
94100
pub fn stdin() -> BufferedReader<StdReader> {
95101
BufferedReader::new(stdin_raw())
@@ -104,20 +110,38 @@ pub fn stdin_raw() -> StdReader {
104110
src(libc::STDIN_FILENO, true, |src| StdReader { inner: src })
105111
}
106112

107-
/// Creates a new non-blocking handle to the stdout of the current process.
113+
/// Creates a line-buffered handle to the stdout of the current process.
108114
///
109115
/// Note that this is a fairly expensive operation in that at least one memory
110116
/// allocation is performed. Additionally, this must be called from a runtime
111117
/// task context because the stream returned will be a non-blocking object using
112118
/// the local scheduler to perform the I/O.
113-
pub fn stdout() -> StdWriter {
119+
///
120+
/// Care should be taken when creating multiple handles to an output stream for
121+
/// a single process. While usage is still safe, the output may be surprising if
122+
/// no synchronization is performed to ensure a sane output.
123+
pub fn stdout() -> LineBufferedWriter<StdWriter> {
124+
LineBufferedWriter::new(stdout_raw())
125+
}
126+
127+
/// Creates an unbuffered handle to the stdout of the current process
128+
///
129+
/// See notes in `stdout()` for more information.
130+
pub fn stdout_raw() -> StdWriter {
114131
src(libc::STDOUT_FILENO, false, |src| StdWriter { inner: src })
115132
}
116133

117-
/// Creates a new non-blocking handle to the stderr of the current process.
134+
/// Creates a line-buffered handle to the stderr of the current process.
118135
///
119136
/// See `stdout()` for notes about this function.
120-
pub fn stderr() -> StdWriter {
137+
pub fn stderr() -> LineBufferedWriter<StdWriter> {
138+
LineBufferedWriter::new(stderr_raw())
139+
}
140+
141+
/// Creates an unbuffered handle to the stderr of the current process
142+
///
143+
/// See notes in `stdout()` for more information.
144+
pub fn stderr_raw() -> StdWriter {
121145
src(libc::STDERR_FILENO, false, |src| StdWriter { inner: src })
122146
}
123147

@@ -182,7 +206,7 @@ fn with_task_stdout(f: |&mut Writer| -> IoResult<()> ) {
182206
Local::put(task);
183207

184208
if my_stdout.is_none() {
185-
my_stdout = Some(~LineBufferedWriter::new(stdout()) as ~Writer);
209+
my_stdout = Some(~stdout() as ~Writer);
186210
}
187211
let ret = f(*my_stdout.get_mut_ref());
188212

src/libstd/logging.rs

+1-3
Original file line numberDiff line numberDiff line change
@@ -166,9 +166,7 @@ pub fn log(level: u32, args: &fmt::Arguments) {
166166
};
167167

168168
if logger.is_none() {
169-
logger = Some(~DefaultLogger {
170-
handle: LineBufferedWriter::new(io::stderr()),
171-
} as ~Logger);
169+
logger = Some(~DefaultLogger { handle: io::stderr(), } as ~Logger);
172170
}
173171
logger.get_mut_ref().log(level, args);
174172

src/libsyntax/diagnostic.rs

+2-2
Original file line numberDiff line numberDiff line change
@@ -227,8 +227,8 @@ enum Destination {
227227
impl EmitterWriter {
228228
pub fn stderr() -> EmitterWriter {
229229
let stderr = io::stderr();
230-
if stderr.isatty() {
231-
let dst = match term::Terminal::new(stderr) {
230+
if stderr.get_ref().isatty() {
231+
let dst = match term::Terminal::new(stderr.unwrap()) {
232232
Ok(t) => Terminal(t),
233233
Err(..) => Raw(~io::stderr()),
234234
};

src/libtest/lib.rs

+2-2
Original file line numberDiff line numberDiff line change
@@ -415,8 +415,8 @@ impl<T: Writer> ConsoleTestState<T> {
415415
Some(ref path) => Some(try!(File::create(path))),
416416
None => None
417417
};
418-
let out = match term::Terminal::new(io::stdout()) {
419-
Err(_) => Raw(io::stdout()),
418+
let out = match term::Terminal::new(io::stdio::stdout_raw()) {
419+
Err(_) => Raw(io::stdio::stdout_raw()),
420420
Ok(t) => Pretty(t)
421421
};
422422
Ok(ConsoleTestState {

src/test/bench/shootout-fasta-redux.rs

+2-2
Original file line numberDiff line numberDiff line change
@@ -9,7 +9,7 @@
99
// except according to those terms.
1010

1111
use std::cmp::min;
12-
use std::io::{stdout, BufferedWriter, IoResult};
12+
use std::io::{stdout, IoResult};
1313
use std::os;
1414
use std::vec::bytes::copy_memory;
1515
use std::vec;
@@ -183,7 +183,7 @@ fn main() {
183183
5
184184
};
185185

186-
let mut out = BufferedWriter::new(stdout());
186+
let mut out = stdout();
187187

188188
out.write_line(">ONE Homo sapiens alu").unwrap();
189189
{

src/test/bench/shootout-fasta.rs

+1-1
Original file line numberDiff line numberDiff line change
@@ -117,6 +117,6 @@ fn main() {
117117
let mut file = BufferedWriter::new(File::create(&Path::new("./shootout-fasta.data")));
118118
run(&mut file);
119119
} else {
120-
run(&mut BufferedWriter::new(io::stdout()));
120+
run(&mut io::stdout());
121121
}
122122
}

src/test/bench/shootout-mandelbrot.rs

+1-2
Original file line numberDiff line numberDiff line change
@@ -9,7 +9,6 @@
99
// except according to those terms.
1010

1111
use std::io;
12-
use std::io::BufferedWriter;
1312

1413
struct DummyWriter;
1514
impl Writer for DummyWriter {
@@ -27,7 +26,7 @@ fn main() {
2726
(1000, ~DummyWriter as ~Writer)
2827
} else {
2928
(from_str(args[1]).unwrap(),
30-
~BufferedWriter::new(std::io::stdout()) as ~Writer)
29+
~std::io::stdout() as ~Writer)
3130
};
3231
let h = w;
3332
let mut byte_acc = 0u8;

0 commit comments

Comments
 (0)