Skip to content

Commit 5acb7f1

Browse files
authoredOct 16, 2020
Rollup merge of #76084 - Lucretiel:split-buffered, r=dtolnay
Refactor io/buffered.rs into submodules This pull request splits `BufWriter`, `BufReader`, `LineWriter`, and `LineWriterShim` (along with their associated tests) into separate submodules. It contains no functional changes. This change is being made in anticipation of adding another type of buffered writer which can be switched between line- and block-buffering mode. Part of a series of pull requests resolving #60673.
2 parents 1643fd8 + c4280af commit 5acb7f1

File tree

7 files changed

+1466
-1441
lines changed

7 files changed

+1466
-1441
lines changed
 

‎library/std/src/io/buffered.rs

Lines changed: 0 additions & 1438 deletions
This file was deleted.
Lines changed: 423 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,423 @@
1+
use crate::cmp;
2+
use crate::fmt;
3+
use crate::io::{self, BufRead, Initializer, IoSliceMut, Read, Seek, SeekFrom, DEFAULT_BUF_SIZE};
4+
5+
/// The `BufReader<R>` struct adds buffering to any reader.
6+
///
7+
/// It can be excessively inefficient to work directly with a [`Read`] instance.
8+
/// For example, every call to [`read`][`TcpStream::read`] on [`TcpStream`]
9+
/// results in a system call. A `BufReader<R>` performs large, infrequent reads on
10+
/// the underlying [`Read`] and maintains an in-memory buffer of the results.
11+
///
12+
/// `BufReader<R>` can improve the speed of programs that make *small* and
13+
/// *repeated* read calls to the same file or network socket. It does not
14+
/// help when reading very large amounts at once, or reading just one or a few
15+
/// times. It also provides no advantage when reading from a source that is
16+
/// already in memory, like a [`Vec`]`<u8>`.
17+
///
18+
/// When the `BufReader<R>` is dropped, the contents of its buffer will be
19+
/// discarded. Creating multiple instances of a `BufReader<R>` on the same
20+
/// stream can cause data loss. Reading from the underlying reader after
21+
/// unwrapping the `BufReader<R>` with [`BufReader::into_inner`] can also cause
22+
/// data loss.
23+
///
24+
/// [`TcpStream::read`]: Read::read
25+
/// [`TcpStream`]: crate::net::TcpStream
26+
///
27+
/// # Examples
28+
///
29+
/// ```no_run
30+
/// use std::io::prelude::*;
31+
/// use std::io::BufReader;
32+
/// use std::fs::File;
33+
///
34+
/// fn main() -> std::io::Result<()> {
35+
/// let f = File::open("log.txt")?;
36+
/// let mut reader = BufReader::new(f);
37+
///
38+
/// let mut line = String::new();
39+
/// let len = reader.read_line(&mut line)?;
40+
/// println!("First line is {} bytes long", len);
41+
/// Ok(())
42+
/// }
43+
/// ```
44+
#[stable(feature = "rust1", since = "1.0.0")]
45+
pub struct BufReader<R> {
46+
inner: R,
47+
buf: Box<[u8]>,
48+
pos: usize,
49+
cap: usize,
50+
}
51+
52+
impl<R: Read> BufReader<R> {
53+
/// Creates a new `BufReader<R>` with a default buffer capacity. The default is currently 8 KB,
54+
/// but may change in the future.
55+
///
56+
/// # Examples
57+
///
58+
/// ```no_run
59+
/// use std::io::BufReader;
60+
/// use std::fs::File;
61+
///
62+
/// fn main() -> std::io::Result<()> {
63+
/// let f = File::open("log.txt")?;
64+
/// let reader = BufReader::new(f);
65+
/// Ok(())
66+
/// }
67+
/// ```
68+
#[stable(feature = "rust1", since = "1.0.0")]
69+
pub fn new(inner: R) -> BufReader<R> {
70+
BufReader::with_capacity(DEFAULT_BUF_SIZE, inner)
71+
}
72+
73+
/// Creates a new `BufReader<R>` with the specified buffer capacity.
74+
///
75+
/// # Examples
76+
///
77+
/// Creating a buffer with ten bytes of capacity:
78+
///
79+
/// ```no_run
80+
/// use std::io::BufReader;
81+
/// use std::fs::File;
82+
///
83+
/// fn main() -> std::io::Result<()> {
84+
/// let f = File::open("log.txt")?;
85+
/// let reader = BufReader::with_capacity(10, f);
86+
/// Ok(())
87+
/// }
88+
/// ```
89+
#[stable(feature = "rust1", since = "1.0.0")]
90+
pub fn with_capacity(capacity: usize, inner: R) -> BufReader<R> {
91+
unsafe {
92+
let mut buffer = Vec::with_capacity(capacity);
93+
buffer.set_len(capacity);
94+
inner.initializer().initialize(&mut buffer);
95+
BufReader { inner, buf: buffer.into_boxed_slice(), pos: 0, cap: 0 }
96+
}
97+
}
98+
}
99+
100+
impl<R> BufReader<R> {
101+
/// Gets a reference to the underlying reader.
102+
///
103+
/// It is inadvisable to directly read from the underlying reader.
104+
///
105+
/// # Examples
106+
///
107+
/// ```no_run
108+
/// use std::io::BufReader;
109+
/// use std::fs::File;
110+
///
111+
/// fn main() -> std::io::Result<()> {
112+
/// let f1 = File::open("log.txt")?;
113+
/// let reader = BufReader::new(f1);
114+
///
115+
/// let f2 = reader.get_ref();
116+
/// Ok(())
117+
/// }
118+
/// ```
119+
#[stable(feature = "rust1", since = "1.0.0")]
120+
pub fn get_ref(&self) -> &R {
121+
&self.inner
122+
}
123+
124+
/// Gets a mutable reference to the underlying reader.
125+
///
126+
/// It is inadvisable to directly read from the underlying reader.
127+
///
128+
/// # Examples
129+
///
130+
/// ```no_run
131+
/// use std::io::BufReader;
132+
/// use std::fs::File;
133+
///
134+
/// fn main() -> std::io::Result<()> {
135+
/// let f1 = File::open("log.txt")?;
136+
/// let mut reader = BufReader::new(f1);
137+
///
138+
/// let f2 = reader.get_mut();
139+
/// Ok(())
140+
/// }
141+
/// ```
142+
#[stable(feature = "rust1", since = "1.0.0")]
143+
pub fn get_mut(&mut self) -> &mut R {
144+
&mut self.inner
145+
}
146+
147+
/// Returns a reference to the internally buffered data.
148+
///
149+
/// Unlike [`fill_buf`], this will not attempt to fill the buffer if it is empty.
150+
///
151+
/// [`fill_buf`]: BufRead::fill_buf
152+
///
153+
/// # Examples
154+
///
155+
/// ```no_run
156+
/// use std::io::{BufReader, BufRead};
157+
/// use std::fs::File;
158+
///
159+
/// fn main() -> std::io::Result<()> {
160+
/// let f = File::open("log.txt")?;
161+
/// let mut reader = BufReader::new(f);
162+
/// assert!(reader.buffer().is_empty());
163+
///
164+
/// if reader.fill_buf()?.len() > 0 {
165+
/// assert!(!reader.buffer().is_empty());
166+
/// }
167+
/// Ok(())
168+
/// }
169+
/// ```
170+
#[stable(feature = "bufreader_buffer", since = "1.37.0")]
171+
pub fn buffer(&self) -> &[u8] {
172+
&self.buf[self.pos..self.cap]
173+
}
174+
175+
/// Returns the number of bytes the internal buffer can hold at once.
176+
///
177+
/// # Examples
178+
///
179+
/// ```no_run
180+
/// use std::io::{BufReader, BufRead};
181+
/// use std::fs::File;
182+
///
183+
/// fn main() -> std::io::Result<()> {
184+
/// let f = File::open("log.txt")?;
185+
/// let mut reader = BufReader::new(f);
186+
///
187+
/// let capacity = reader.capacity();
188+
/// let buffer = reader.fill_buf()?;
189+
/// assert!(buffer.len() <= capacity);
190+
/// Ok(())
191+
/// }
192+
/// ```
193+
#[stable(feature = "buffered_io_capacity", since = "1.46.0")]
194+
pub fn capacity(&self) -> usize {
195+
self.buf.len()
196+
}
197+
198+
/// Unwraps this `BufReader<R>`, returning the underlying reader.
199+
///
200+
/// Note that any leftover data in the internal buffer is lost. Therefore,
201+
/// a following read from the underlying reader may lead to data loss.
202+
///
203+
/// # Examples
204+
///
205+
/// ```no_run
206+
/// use std::io::BufReader;
207+
/// use std::fs::File;
208+
///
209+
/// fn main() -> std::io::Result<()> {
210+
/// let f1 = File::open("log.txt")?;
211+
/// let reader = BufReader::new(f1);
212+
///
213+
/// let f2 = reader.into_inner();
214+
/// Ok(())
215+
/// }
216+
/// ```
217+
#[stable(feature = "rust1", since = "1.0.0")]
218+
pub fn into_inner(self) -> R {
219+
self.inner
220+
}
221+
222+
/// Invalidates all data in the internal buffer.
223+
#[inline]
224+
fn discard_buffer(&mut self) {
225+
self.pos = 0;
226+
self.cap = 0;
227+
}
228+
}
229+
230+
impl<R: Seek> BufReader<R> {
231+
/// Seeks relative to the current position. If the new position lies within the buffer,
232+
/// the buffer will not be flushed, allowing for more efficient seeks.
233+
/// This method does not return the location of the underlying reader, so the caller
234+
/// must track this information themselves if it is required.
235+
#[unstable(feature = "bufreader_seek_relative", issue = "31100")]
236+
pub fn seek_relative(&mut self, offset: i64) -> io::Result<()> {
237+
let pos = self.pos as u64;
238+
if offset < 0 {
239+
if let Some(new_pos) = pos.checked_sub((-offset) as u64) {
240+
self.pos = new_pos as usize;
241+
return Ok(());
242+
}
243+
} else {
244+
if let Some(new_pos) = pos.checked_add(offset as u64) {
245+
if new_pos <= self.cap as u64 {
246+
self.pos = new_pos as usize;
247+
return Ok(());
248+
}
249+
}
250+
}
251+
self.seek(SeekFrom::Current(offset)).map(drop)
252+
}
253+
}
254+
255+
#[stable(feature = "rust1", since = "1.0.0")]
256+
impl<R: Read> Read for BufReader<R> {
257+
fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> {
258+
// If we don't have any buffered data and we're doing a massive read
259+
// (larger than our internal buffer), bypass our internal buffer
260+
// entirely.
261+
if self.pos == self.cap && buf.len() >= self.buf.len() {
262+
self.discard_buffer();
263+
return self.inner.read(buf);
264+
}
265+
let nread = {
266+
let mut rem = self.fill_buf()?;
267+
rem.read(buf)?
268+
};
269+
self.consume(nread);
270+
Ok(nread)
271+
}
272+
273+
fn read_vectored(&mut self, bufs: &mut [IoSliceMut<'_>]) -> io::Result<usize> {
274+
let total_len = bufs.iter().map(|b| b.len()).sum::<usize>();
275+
if self.pos == self.cap && total_len >= self.buf.len() {
276+
self.discard_buffer();
277+
return self.inner.read_vectored(bufs);
278+
}
279+
let nread = {
280+
let mut rem = self.fill_buf()?;
281+
rem.read_vectored(bufs)?
282+
};
283+
self.consume(nread);
284+
Ok(nread)
285+
}
286+
287+
fn is_read_vectored(&self) -> bool {
288+
self.inner.is_read_vectored()
289+
}
290+
291+
// we can't skip unconditionally because of the large buffer case in read.
292+
unsafe fn initializer(&self) -> Initializer {
293+
self.inner.initializer()
294+
}
295+
}
296+
297+
#[stable(feature = "rust1", since = "1.0.0")]
298+
impl<R: Read> BufRead for BufReader<R> {
299+
fn fill_buf(&mut self) -> io::Result<&[u8]> {
300+
// If we've reached the end of our internal buffer then we need to fetch
301+
// some more data from the underlying reader.
302+
// Branch using `>=` instead of the more correct `==`
303+
// to tell the compiler that the pos..cap slice is always valid.
304+
if self.pos >= self.cap {
305+
debug_assert!(self.pos == self.cap);
306+
self.cap = self.inner.read(&mut self.buf)?;
307+
self.pos = 0;
308+
}
309+
Ok(&self.buf[self.pos..self.cap])
310+
}
311+
312+
fn consume(&mut self, amt: usize) {
313+
self.pos = cmp::min(self.pos + amt, self.cap);
314+
}
315+
}
316+
317+
#[stable(feature = "rust1", since = "1.0.0")]
318+
impl<R> fmt::Debug for BufReader<R>
319+
where
320+
R: fmt::Debug,
321+
{
322+
fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result {
323+
fmt.debug_struct("BufReader")
324+
.field("reader", &self.inner)
325+
.field("buffer", &format_args!("{}/{}", self.cap - self.pos, self.buf.len()))
326+
.finish()
327+
}
328+
}
329+
330+
#[stable(feature = "rust1", since = "1.0.0")]
331+
impl<R: Seek> Seek for BufReader<R> {
332+
/// Seek to an offset, in bytes, in the underlying reader.
333+
///
334+
/// The position used for seeking with [`SeekFrom::Current`]`(_)` is the
335+
/// position the underlying reader would be at if the `BufReader<R>` had no
336+
/// internal buffer.
337+
///
338+
/// Seeking always discards the internal buffer, even if the seek position
339+
/// would otherwise fall within it. This guarantees that calling
340+
/// [`BufReader::into_inner()`] immediately after a seek yields the underlying reader
341+
/// at the same position.
342+
///
343+
/// To seek without discarding the internal buffer, use [`BufReader::seek_relative`].
344+
///
345+
/// See [`std::io::Seek`] for more details.
346+
///
347+
/// Note: In the edge case where you're seeking with [`SeekFrom::Current`]`(n)`
348+
/// where `n` minus the internal buffer length overflows an `i64`, two
349+
/// seeks will be performed instead of one. If the second seek returns
350+
/// [`Err`], the underlying reader will be left at the same position it would
351+
/// have if you called `seek` with [`SeekFrom::Current`]`(0)`.
352+
///
353+
/// [`std::io::Seek`]: Seek
354+
fn seek(&mut self, pos: SeekFrom) -> io::Result<u64> {
355+
let result: u64;
356+
if let SeekFrom::Current(n) = pos {
357+
let remainder = (self.cap - self.pos) as i64;
358+
// it should be safe to assume that remainder fits within an i64 as the alternative
359+
// means we managed to allocate 8 exbibytes and that's absurd.
360+
// But it's not out of the realm of possibility for some weird underlying reader to
361+
// support seeking by i64::MIN so we need to handle underflow when subtracting
362+
// remainder.
363+
if let Some(offset) = n.checked_sub(remainder) {
364+
result = self.inner.seek(SeekFrom::Current(offset))?;
365+
} else {
366+
// seek backwards by our remainder, and then by the offset
367+
self.inner.seek(SeekFrom::Current(-remainder))?;
368+
self.discard_buffer();
369+
result = self.inner.seek(SeekFrom::Current(n))?;
370+
}
371+
} else {
372+
// Seeking with Start/End doesn't care about our buffer length.
373+
result = self.inner.seek(pos)?;
374+
}
375+
self.discard_buffer();
376+
Ok(result)
377+
}
378+
379+
/// Returns the current seek position from the start of the stream.
380+
///
381+
/// The value returned is equivalent to `self.seek(SeekFrom::Current(0))`
382+
/// but does not flush the internal buffer. Due to this optimization the
383+
/// function does not guarantee that calling `.into_inner()` immediately
384+
/// afterwards will yield the underlying reader at the same position. Use
385+
/// [`BufReader::seek`] instead if you require that guarantee.
386+
///
387+
/// # Panics
388+
///
389+
/// This function will panic if the position of the inner reader is smaller
390+
/// than the amount of buffered data. That can happen if the inner reader
391+
/// has an incorrect implementation of [`Seek::stream_position`], or if the
392+
/// position has gone out of sync due to calling [`Seek::seek`] directly on
393+
/// the underlying reader.
394+
///
395+
/// # Example
396+
///
397+
/// ```no_run
398+
/// #![feature(seek_convenience)]
399+
/// use std::{
400+
/// io::{self, BufRead, BufReader, Seek},
401+
/// fs::File,
402+
/// };
403+
///
404+
/// fn main() -> io::Result<()> {
405+
/// let mut f = BufReader::new(File::open("foo.txt")?);
406+
///
407+
/// let before = f.stream_position()?;
408+
/// f.read_line(&mut String::new())?;
409+
/// let after = f.stream_position()?;
410+
///
411+
/// println!("The first line was {} bytes long", after - before);
412+
/// Ok(())
413+
/// }
414+
/// ```
415+
fn stream_position(&mut self) -> io::Result<u64> {
416+
let remainder = (self.cap - self.pos) as u64;
417+
self.inner.stream_position().map(|pos| {
418+
pos.checked_sub(remainder).expect(
419+
"overflow when subtracting remaining buffer size from inner stream position",
420+
)
421+
})
422+
}
423+
}
Lines changed: 387 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,387 @@
1+
use crate::fmt;
2+
use crate::io::{
3+
self, Error, ErrorKind, IntoInnerError, IoSlice, Seek, SeekFrom, Write, DEFAULT_BUF_SIZE,
4+
};
5+
6+
/// Wraps a writer and buffers its output.
7+
///
8+
/// It can be excessively inefficient to work directly with something that
9+
/// implements [`Write`]. For example, every call to
10+
/// [`write`][`TcpStream::write`] on [`TcpStream`] results in a system call. A
11+
/// `BufWriter<W>` keeps an in-memory buffer of data and writes it to an underlying
12+
/// writer in large, infrequent batches.
13+
///
14+
/// `BufWriter<W>` can improve the speed of programs that make *small* and
15+
/// *repeated* write calls to the same file or network socket. It does not
16+
/// help when writing very large amounts at once, or writing just one or a few
17+
/// times. It also provides no advantage when writing to a destination that is
18+
/// in memory, like a [`Vec`]<u8>`.
19+
///
20+
/// It is critical to call [`flush`] before `BufWriter<W>` is dropped. Though
21+
/// dropping will attempt to flush the contents of the buffer, any errors
22+
/// that happen in the process of dropping will be ignored. Calling [`flush`]
23+
/// ensures that the buffer is empty and thus dropping will not even attempt
24+
/// file operations.
25+
///
26+
/// # Examples
27+
///
28+
/// Let's write the numbers one through ten to a [`TcpStream`]:
29+
///
30+
/// ```no_run
31+
/// use std::io::prelude::*;
32+
/// use std::net::TcpStream;
33+
///
34+
/// let mut stream = TcpStream::connect("127.0.0.1:34254").unwrap();
35+
///
36+
/// for i in 0..10 {
37+
/// stream.write(&[i+1]).unwrap();
38+
/// }
39+
/// ```
40+
///
41+
/// Because we're not buffering, we write each one in turn, incurring the
42+
/// overhead of a system call per byte written. We can fix this with a
43+
/// `BufWriter<W>`:
44+
///
45+
/// ```no_run
46+
/// use std::io::prelude::*;
47+
/// use std::io::BufWriter;
48+
/// use std::net::TcpStream;
49+
///
50+
/// let mut stream = BufWriter::new(TcpStream::connect("127.0.0.1:34254").unwrap());
51+
///
52+
/// for i in 0..10 {
53+
/// stream.write(&[i+1]).unwrap();
54+
/// }
55+
/// stream.flush().unwrap();
56+
/// ```
57+
///
58+
/// By wrapping the stream with a `BufWriter<W>`, these ten writes are all grouped
59+
/// together by the buffer and will all be written out in one system call when
60+
/// the `stream` is flushed.
61+
///
62+
/// [`TcpStream::write`]: Write::write
63+
/// [`TcpStream`]: crate::net::TcpStream
64+
/// [`flush`]: Write::flush
65+
#[stable(feature = "rust1", since = "1.0.0")]
66+
pub struct BufWriter<W: Write> {
67+
inner: Option<W>,
68+
buf: Vec<u8>,
69+
// #30888: If the inner writer panics in a call to write, we don't want to
70+
// write the buffered data a second time in BufWriter's destructor. This
71+
// flag tells the Drop impl if it should skip the flush.
72+
panicked: bool,
73+
}
74+
75+
impl<W: Write> BufWriter<W> {
76+
/// Creates a new `BufWriter<W>` with a default buffer capacity. The default is currently 8 KB,
77+
/// but may change in the future.
78+
///
79+
/// # Examples
80+
///
81+
/// ```no_run
82+
/// use std::io::BufWriter;
83+
/// use std::net::TcpStream;
84+
///
85+
/// let mut buffer = BufWriter::new(TcpStream::connect("127.0.0.1:34254").unwrap());
86+
/// ```
87+
#[stable(feature = "rust1", since = "1.0.0")]
88+
pub fn new(inner: W) -> BufWriter<W> {
89+
BufWriter::with_capacity(DEFAULT_BUF_SIZE, inner)
90+
}
91+
92+
/// Creates a new `BufWriter<W>` with the specified buffer capacity.
93+
///
94+
/// # Examples
95+
///
96+
/// Creating a buffer with a buffer of a hundred bytes.
97+
///
98+
/// ```no_run
99+
/// use std::io::BufWriter;
100+
/// use std::net::TcpStream;
101+
///
102+
/// let stream = TcpStream::connect("127.0.0.1:34254").unwrap();
103+
/// let mut buffer = BufWriter::with_capacity(100, stream);
104+
/// ```
105+
#[stable(feature = "rust1", since = "1.0.0")]
106+
pub fn with_capacity(capacity: usize, inner: W) -> BufWriter<W> {
107+
BufWriter { inner: Some(inner), buf: Vec::with_capacity(capacity), panicked: false }
108+
}
109+
110+
/// Send data in our local buffer into the inner writer, looping as
111+
/// necessary until either it's all been sent or an error occurs.
112+
///
113+
/// Because all the data in the buffer has been reported to our owner as
114+
/// "successfully written" (by returning nonzero success values from
115+
/// `write`), any 0-length writes from `inner` must be reported as i/o
116+
/// errors from this method.
117+
pub(super) fn flush_buf(&mut self) -> io::Result<()> {
118+
/// Helper struct to ensure the buffer is updated after all the writes
119+
/// are complete. It tracks the number of written bytes and drains them
120+
/// all from the front of the buffer when dropped.
121+
struct BufGuard<'a> {
122+
buffer: &'a mut Vec<u8>,
123+
written: usize,
124+
}
125+
126+
impl<'a> BufGuard<'a> {
127+
fn new(buffer: &'a mut Vec<u8>) -> Self {
128+
Self { buffer, written: 0 }
129+
}
130+
131+
/// The unwritten part of the buffer
132+
fn remaining(&self) -> &[u8] {
133+
&self.buffer[self.written..]
134+
}
135+
136+
/// Flag some bytes as removed from the front of the buffer
137+
fn consume(&mut self, amt: usize) {
138+
self.written += amt;
139+
}
140+
141+
/// true if all of the bytes have been written
142+
fn done(&self) -> bool {
143+
self.written >= self.buffer.len()
144+
}
145+
}
146+
147+
impl Drop for BufGuard<'_> {
148+
fn drop(&mut self) {
149+
if self.written > 0 {
150+
self.buffer.drain(..self.written);
151+
}
152+
}
153+
}
154+
155+
let mut guard = BufGuard::new(&mut self.buf);
156+
let inner = self.inner.as_mut().unwrap();
157+
while !guard.done() {
158+
self.panicked = true;
159+
let r = inner.write(guard.remaining());
160+
self.panicked = false;
161+
162+
match r {
163+
Ok(0) => {
164+
return Err(Error::new(
165+
ErrorKind::WriteZero,
166+
"failed to write the buffered data",
167+
));
168+
}
169+
Ok(n) => guard.consume(n),
170+
Err(ref e) if e.kind() == io::ErrorKind::Interrupted => {}
171+
Err(e) => return Err(e),
172+
}
173+
}
174+
Ok(())
175+
}
176+
177+
/// Buffer some data without flushing it, regardless of the size of the
178+
/// data. Writes as much as possible without exceeding capacity. Returns
179+
/// the number of bytes written.
180+
pub(super) fn write_to_buf(&mut self, buf: &[u8]) -> usize {
181+
let available = self.buf.capacity() - self.buf.len();
182+
let amt_to_buffer = available.min(buf.len());
183+
self.buf.extend_from_slice(&buf[..amt_to_buffer]);
184+
amt_to_buffer
185+
}
186+
187+
/// Gets a reference to the underlying writer.
188+
///
189+
/// # Examples
190+
///
191+
/// ```no_run
192+
/// use std::io::BufWriter;
193+
/// use std::net::TcpStream;
194+
///
195+
/// let mut buffer = BufWriter::new(TcpStream::connect("127.0.0.1:34254").unwrap());
196+
///
197+
/// // we can use reference just like buffer
198+
/// let reference = buffer.get_ref();
199+
/// ```
200+
#[stable(feature = "rust1", since = "1.0.0")]
201+
pub fn get_ref(&self) -> &W {
202+
self.inner.as_ref().unwrap()
203+
}
204+
205+
/// Gets a mutable reference to the underlying writer.
206+
///
207+
/// It is inadvisable to directly write to the underlying writer.
208+
///
209+
/// # Examples
210+
///
211+
/// ```no_run
212+
/// use std::io::BufWriter;
213+
/// use std::net::TcpStream;
214+
///
215+
/// let mut buffer = BufWriter::new(TcpStream::connect("127.0.0.1:34254").unwrap());
216+
///
217+
/// // we can use reference just like buffer
218+
/// let reference = buffer.get_mut();
219+
/// ```
220+
#[stable(feature = "rust1", since = "1.0.0")]
221+
pub fn get_mut(&mut self) -> &mut W {
222+
self.inner.as_mut().unwrap()
223+
}
224+
225+
/// Returns a reference to the internally buffered data.
226+
///
227+
/// # Examples
228+
///
229+
/// ```no_run
230+
/// use std::io::BufWriter;
231+
/// use std::net::TcpStream;
232+
///
233+
/// let buf_writer = BufWriter::new(TcpStream::connect("127.0.0.1:34254").unwrap());
234+
///
235+
/// // See how many bytes are currently buffered
236+
/// let bytes_buffered = buf_writer.buffer().len();
237+
/// ```
238+
#[stable(feature = "bufreader_buffer", since = "1.37.0")]
239+
pub fn buffer(&self) -> &[u8] {
240+
&self.buf
241+
}
242+
243+
/// Returns the number of bytes the internal buffer can hold without flushing.
244+
///
245+
/// # Examples
246+
///
247+
/// ```no_run
248+
/// use std::io::BufWriter;
249+
/// use std::net::TcpStream;
250+
///
251+
/// let buf_writer = BufWriter::new(TcpStream::connect("127.0.0.1:34254").unwrap());
252+
///
253+
/// // Check the capacity of the inner buffer
254+
/// let capacity = buf_writer.capacity();
255+
/// // Calculate how many bytes can be written without flushing
256+
/// let without_flush = capacity - buf_writer.buffer().len();
257+
/// ```
258+
#[stable(feature = "buffered_io_capacity", since = "1.46.0")]
259+
pub fn capacity(&self) -> usize {
260+
self.buf.capacity()
261+
}
262+
263+
/// Unwraps this `BufWriter<W>`, returning the underlying writer.
264+
///
265+
/// The buffer is written out before returning the writer.
266+
///
267+
/// # Errors
268+
///
269+
/// An [`Err`] will be returned if an error occurs while flushing the buffer.
270+
///
271+
/// # Examples
272+
///
273+
/// ```no_run
274+
/// use std::io::BufWriter;
275+
/// use std::net::TcpStream;
276+
///
277+
/// let mut buffer = BufWriter::new(TcpStream::connect("127.0.0.1:34254").unwrap());
278+
///
279+
/// // unwrap the TcpStream and flush the buffer
280+
/// let stream = buffer.into_inner().unwrap();
281+
/// ```
282+
#[stable(feature = "rust1", since = "1.0.0")]
283+
pub fn into_inner(mut self) -> Result<W, IntoInnerError<BufWriter<W>>> {
284+
match self.flush_buf() {
285+
Err(e) => Err(IntoInnerError::new(self, e)),
286+
Ok(()) => Ok(self.inner.take().unwrap()),
287+
}
288+
}
289+
}
290+
291+
#[stable(feature = "rust1", since = "1.0.0")]
292+
impl<W: Write> Write for BufWriter<W> {
293+
fn write(&mut self, buf: &[u8]) -> io::Result<usize> {
294+
if self.buf.len() + buf.len() > self.buf.capacity() {
295+
self.flush_buf()?;
296+
}
297+
// FIXME: Why no len > capacity? Why not buffer len == capacity? #72919
298+
if buf.len() >= self.buf.capacity() {
299+
self.panicked = true;
300+
let r = self.get_mut().write(buf);
301+
self.panicked = false;
302+
r
303+
} else {
304+
self.buf.extend_from_slice(buf);
305+
Ok(buf.len())
306+
}
307+
}
308+
309+
fn write_all(&mut self, buf: &[u8]) -> io::Result<()> {
310+
// Normally, `write_all` just calls `write` in a loop. We can do better
311+
// by calling `self.get_mut().write_all()` directly, which avoids
312+
// round trips through the buffer in the event of a series of partial
313+
// writes in some circumstances.
314+
if self.buf.len() + buf.len() > self.buf.capacity() {
315+
self.flush_buf()?;
316+
}
317+
// FIXME: Why no len > capacity? Why not buffer len == capacity? #72919
318+
if buf.len() >= self.buf.capacity() {
319+
self.panicked = true;
320+
let r = self.get_mut().write_all(buf);
321+
self.panicked = false;
322+
r
323+
} else {
324+
self.buf.extend_from_slice(buf);
325+
Ok(())
326+
}
327+
}
328+
329+
fn write_vectored(&mut self, bufs: &[IoSlice<'_>]) -> io::Result<usize> {
330+
let total_len = bufs.iter().map(|b| b.len()).sum::<usize>();
331+
if self.buf.len() + total_len > self.buf.capacity() {
332+
self.flush_buf()?;
333+
}
334+
// FIXME: Why no len > capacity? Why not buffer len == capacity? #72919
335+
if total_len >= self.buf.capacity() {
336+
self.panicked = true;
337+
let r = self.get_mut().write_vectored(bufs);
338+
self.panicked = false;
339+
r
340+
} else {
341+
bufs.iter().for_each(|b| self.buf.extend_from_slice(b));
342+
Ok(total_len)
343+
}
344+
}
345+
346+
fn is_write_vectored(&self) -> bool {
347+
self.get_ref().is_write_vectored()
348+
}
349+
350+
fn flush(&mut self) -> io::Result<()> {
351+
self.flush_buf().and_then(|()| self.get_mut().flush())
352+
}
353+
}
354+
355+
#[stable(feature = "rust1", since = "1.0.0")]
356+
impl<W: Write> fmt::Debug for BufWriter<W>
357+
where
358+
W: fmt::Debug,
359+
{
360+
fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result {
361+
fmt.debug_struct("BufWriter")
362+
.field("writer", &self.inner.as_ref().unwrap())
363+
.field("buffer", &format_args!("{}/{}", self.buf.len(), self.buf.capacity()))
364+
.finish()
365+
}
366+
}
367+
368+
#[stable(feature = "rust1", since = "1.0.0")]
369+
impl<W: Write + Seek> Seek for BufWriter<W> {
370+
/// Seek to the offset, in bytes, in the underlying writer.
371+
///
372+
/// Seeking always writes out the internal buffer before seeking.
373+
fn seek(&mut self, pos: SeekFrom) -> io::Result<u64> {
374+
self.flush_buf()?;
375+
self.get_mut().seek(pos)
376+
}
377+
}
378+
379+
#[stable(feature = "rust1", since = "1.0.0")]
380+
impl<W: Write> Drop for BufWriter<W> {
381+
fn drop(&mut self) {
382+
if self.inner.is_some() && !self.panicked {
383+
// dtors should not panic, so we ignore a failed flush
384+
let _r = self.flush_buf();
385+
}
386+
}
387+
}
Lines changed: 232 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,232 @@
1+
use crate::fmt;
2+
use crate::io::{self, buffered::LineWriterShim, BufWriter, IntoInnerError, IoSlice, Write};
3+
4+
/// Wraps a writer and buffers output to it, flushing whenever a newline
5+
/// (`0x0a`, `'\n'`) is detected.
6+
///
7+
/// The [`BufWriter`] struct wraps a writer and buffers its output.
8+
/// But it only does this batched write when it goes out of scope, or when the
9+
/// internal buffer is full. Sometimes, you'd prefer to write each line as it's
10+
/// completed, rather than the entire buffer at once. Enter `LineWriter`. It
11+
/// does exactly that.
12+
///
13+
/// Like [`BufWriter`], a `LineWriter`’s buffer will also be flushed when the
14+
/// `LineWriter` goes out of scope or when its internal buffer is full.
15+
///
16+
/// If there's still a partial line in the buffer when the `LineWriter` is
17+
/// dropped, it will flush those contents.
18+
///
19+
/// # Examples
20+
///
21+
/// We can use `LineWriter` to write one line at a time, significantly
22+
/// reducing the number of actual writes to the file.
23+
///
24+
/// ```no_run
25+
/// use std::fs::{self, File};
26+
/// use std::io::prelude::*;
27+
/// use std::io::LineWriter;
28+
///
29+
/// fn main() -> std::io::Result<()> {
30+
/// let road_not_taken = b"I shall be telling this with a sigh
31+
/// Somewhere ages and ages hence:
32+
/// Two roads diverged in a wood, and I -
33+
/// I took the one less traveled by,
34+
/// And that has made all the difference.";
35+
///
36+
/// let file = File::create("poem.txt")?;
37+
/// let mut file = LineWriter::new(file);
38+
///
39+
/// file.write_all(b"I shall be telling this with a sigh")?;
40+
///
41+
/// // No bytes are written until a newline is encountered (or
42+
/// // the internal buffer is filled).
43+
/// assert_eq!(fs::read_to_string("poem.txt")?, "");
44+
/// file.write_all(b"\n")?;
45+
/// assert_eq!(
46+
/// fs::read_to_string("poem.txt")?,
47+
/// "I shall be telling this with a sigh\n",
48+
/// );
49+
///
50+
/// // Write the rest of the poem.
51+
/// file.write_all(b"Somewhere ages and ages hence:
52+
/// Two roads diverged in a wood, and I -
53+
/// I took the one less traveled by,
54+
/// And that has made all the difference.")?;
55+
///
56+
/// // The last line of the poem doesn't end in a newline, so
57+
/// // we have to flush or drop the `LineWriter` to finish
58+
/// // writing.
59+
/// file.flush()?;
60+
///
61+
/// // Confirm the whole poem was written.
62+
/// assert_eq!(fs::read("poem.txt")?, &road_not_taken[..]);
63+
/// Ok(())
64+
/// }
65+
/// ```
66+
#[stable(feature = "rust1", since = "1.0.0")]
67+
pub struct LineWriter<W: Write> {
68+
inner: BufWriter<W>,
69+
}
70+
71+
impl<W: Write> LineWriter<W> {
72+
/// Creates a new `LineWriter`.
73+
///
74+
/// # Examples
75+
///
76+
/// ```no_run
77+
/// use std::fs::File;
78+
/// use std::io::LineWriter;
79+
///
80+
/// fn main() -> std::io::Result<()> {
81+
/// let file = File::create("poem.txt")?;
82+
/// let file = LineWriter::new(file);
83+
/// Ok(())
84+
/// }
85+
/// ```
86+
#[stable(feature = "rust1", since = "1.0.0")]
87+
pub fn new(inner: W) -> LineWriter<W> {
88+
// Lines typically aren't that long, don't use a giant buffer
89+
LineWriter::with_capacity(1024, inner)
90+
}
91+
92+
/// Creates a new `LineWriter` with a specified capacity for the internal
93+
/// buffer.
94+
///
95+
/// # Examples
96+
///
97+
/// ```no_run
98+
/// use std::fs::File;
99+
/// use std::io::LineWriter;
100+
///
101+
/// fn main() -> std::io::Result<()> {
102+
/// let file = File::create("poem.txt")?;
103+
/// let file = LineWriter::with_capacity(100, file);
104+
/// Ok(())
105+
/// }
106+
/// ```
107+
#[stable(feature = "rust1", since = "1.0.0")]
108+
pub fn with_capacity(capacity: usize, inner: W) -> LineWriter<W> {
109+
LineWriter { inner: BufWriter::with_capacity(capacity, inner) }
110+
}
111+
112+
/// Gets a reference to the underlying writer.
113+
///
114+
/// # Examples
115+
///
116+
/// ```no_run
117+
/// use std::fs::File;
118+
/// use std::io::LineWriter;
119+
///
120+
/// fn main() -> std::io::Result<()> {
121+
/// let file = File::create("poem.txt")?;
122+
/// let file = LineWriter::new(file);
123+
///
124+
/// let reference = file.get_ref();
125+
/// Ok(())
126+
/// }
127+
/// ```
128+
#[stable(feature = "rust1", since = "1.0.0")]
129+
pub fn get_ref(&self) -> &W {
130+
self.inner.get_ref()
131+
}
132+
133+
/// Gets a mutable reference to the underlying writer.
134+
///
135+
/// Caution must be taken when calling methods on the mutable reference
136+
/// returned as extra writes could corrupt the output stream.
137+
///
138+
/// # Examples
139+
///
140+
/// ```no_run
141+
/// use std::fs::File;
142+
/// use std::io::LineWriter;
143+
///
144+
/// fn main() -> std::io::Result<()> {
145+
/// let file = File::create("poem.txt")?;
146+
/// let mut file = LineWriter::new(file);
147+
///
148+
/// // we can use reference just like file
149+
/// let reference = file.get_mut();
150+
/// Ok(())
151+
/// }
152+
/// ```
153+
#[stable(feature = "rust1", since = "1.0.0")]
154+
pub fn get_mut(&mut self) -> &mut W {
155+
self.inner.get_mut()
156+
}
157+
158+
/// Unwraps this `LineWriter`, returning the underlying writer.
159+
///
160+
/// The internal buffer is written out before returning the writer.
161+
///
162+
/// # Errors
163+
///
164+
/// An [`Err`] will be returned if an error occurs while flushing the buffer.
165+
///
166+
/// # Examples
167+
///
168+
/// ```no_run
169+
/// use std::fs::File;
170+
/// use std::io::LineWriter;
171+
///
172+
/// fn main() -> std::io::Result<()> {
173+
/// let file = File::create("poem.txt")?;
174+
///
175+
/// let writer: LineWriter<File> = LineWriter::new(file);
176+
///
177+
/// let file: File = writer.into_inner()?;
178+
/// Ok(())
179+
/// }
180+
/// ```
181+
#[stable(feature = "rust1", since = "1.0.0")]
182+
pub fn into_inner(self) -> Result<W, IntoInnerError<LineWriter<W>>> {
183+
self.inner.into_inner().map_err(|err| err.new_wrapped(|inner| LineWriter { inner }))
184+
}
185+
}
186+
187+
#[stable(feature = "rust1", since = "1.0.0")]
188+
impl<W: Write> Write for LineWriter<W> {
189+
fn write(&mut self, buf: &[u8]) -> io::Result<usize> {
190+
LineWriterShim::new(&mut self.inner).write(buf)
191+
}
192+
193+
fn flush(&mut self) -> io::Result<()> {
194+
self.inner.flush()
195+
}
196+
197+
fn write_vectored(&mut self, bufs: &[IoSlice<'_>]) -> io::Result<usize> {
198+
LineWriterShim::new(&mut self.inner).write_vectored(bufs)
199+
}
200+
201+
fn is_write_vectored(&self) -> bool {
202+
self.inner.is_write_vectored()
203+
}
204+
205+
fn write_all(&mut self, buf: &[u8]) -> io::Result<()> {
206+
LineWriterShim::new(&mut self.inner).write_all(buf)
207+
}
208+
209+
fn write_all_vectored(&mut self, bufs: &mut [IoSlice<'_>]) -> io::Result<()> {
210+
LineWriterShim::new(&mut self.inner).write_all_vectored(bufs)
211+
}
212+
213+
fn write_fmt(&mut self, fmt: fmt::Arguments<'_>) -> io::Result<()> {
214+
LineWriterShim::new(&mut self.inner).write_fmt(fmt)
215+
}
216+
}
217+
218+
#[stable(feature = "rust1", since = "1.0.0")]
219+
impl<W: Write> fmt::Debug for LineWriter<W>
220+
where
221+
W: fmt::Debug,
222+
{
223+
fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result {
224+
fmt.debug_struct("LineWriter")
225+
.field("writer", &self.get_ref())
226+
.field(
227+
"buffer",
228+
&format_args!("{}/{}", self.inner.buffer().len(), self.inner.capacity()),
229+
)
230+
.finish()
231+
}
232+
}
Lines changed: 270 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,270 @@
1+
use crate::io::{self, BufWriter, IoSlice, Write};
2+
use crate::memchr;
3+
4+
/// Private helper struct for implementing the line-buffered writing logic.
5+
/// This shim temporarily wraps a BufWriter, and uses its internals to
6+
/// implement a line-buffered writer (specifically by using the internal
7+
/// methods like write_to_buf and flush_buf). In this way, a more
8+
/// efficient abstraction can be created than one that only had access to
9+
/// `write` and `flush`, without needlessly duplicating a lot of the
10+
/// implementation details of BufWriter. This also allows existing
11+
/// `BufWriters` to be temporarily given line-buffering logic; this is what
12+
/// enables Stdout to be alternately in line-buffered or block-buffered mode.
13+
#[derive(Debug)]
14+
pub struct LineWriterShim<'a, W: Write> {
15+
buffer: &'a mut BufWriter<W>,
16+
}
17+
18+
impl<'a, W: Write> LineWriterShim<'a, W> {
19+
pub fn new(buffer: &'a mut BufWriter<W>) -> Self {
20+
Self { buffer }
21+
}
22+
23+
/// Get a mutable reference to the inner writer (that is, the writer
24+
/// wrapped by the BufWriter). Be careful with this writer, as writes to
25+
/// it will bypass the buffer.
26+
fn inner_mut(&mut self) -> &mut W {
27+
self.buffer.get_mut()
28+
}
29+
30+
/// Get the content currently buffered in self.buffer
31+
fn buffered(&self) -> &[u8] {
32+
self.buffer.buffer()
33+
}
34+
35+
/// Flush the buffer iff the last byte is a newline (indicating that an
36+
/// earlier write only succeeded partially, and we want to retry flushing
37+
/// the buffered line before continuing with a subsequent write)
38+
fn flush_if_completed_line(&mut self) -> io::Result<()> {
39+
match self.buffered().last().copied() {
40+
Some(b'\n') => self.buffer.flush_buf(),
41+
_ => Ok(()),
42+
}
43+
}
44+
}
45+
46+
impl<'a, W: Write> Write for LineWriterShim<'a, W> {
47+
/// Write some data into this BufReader with line buffering. This means
48+
/// that, if any newlines are present in the data, the data up to the last
49+
/// newline is sent directly to the underlying writer, and data after it
50+
/// is buffered. Returns the number of bytes written.
51+
///
52+
/// This function operates on a "best effort basis"; in keeping with the
53+
/// convention of `Write::write`, it makes at most one attempt to write
54+
/// new data to the underlying writer. If that write only reports a partial
55+
/// success, the remaining data will be buffered.
56+
///
57+
/// Because this function attempts to send completed lines to the underlying
58+
/// writer, it will also flush the existing buffer if it ends with a
59+
/// newline, even if the incoming data does not contain any newlines.
60+
fn write(&mut self, buf: &[u8]) -> io::Result<usize> {
61+
let newline_idx = match memchr::memrchr(b'\n', buf) {
62+
// If there are no new newlines (that is, if this write is less than
63+
// one line), just do a regular buffered write (which may flush if
64+
// we exceed the inner buffer's size)
65+
None => {
66+
self.flush_if_completed_line()?;
67+
return self.buffer.write(buf);
68+
}
69+
// Otherwise, arrange for the lines to be written directly to the
70+
// inner writer.
71+
Some(newline_idx) => newline_idx + 1,
72+
};
73+
74+
// Flush existing content to prepare for our write. We have to do this
75+
// before attempting to write `buf` in order to maintain consistency;
76+
// if we add `buf` to the buffer then try to flush it all at once,
77+
// we're obligated to return Ok(), which would mean suppressing any
78+
// errors that occur during flush.
79+
self.buffer.flush_buf()?;
80+
81+
// This is what we're going to try to write directly to the inner
82+
// writer. The rest will be buffered, if nothing goes wrong.
83+
let lines = &buf[..newline_idx];
84+
85+
// Write `lines` directly to the inner writer. In keeping with the
86+
// `write` convention, make at most one attempt to add new (unbuffered)
87+
// data. Because this write doesn't touch the BufWriter state directly,
88+
// and the buffer is known to be empty, we don't need to worry about
89+
// self.buffer.panicked here.
90+
let flushed = self.inner_mut().write(lines)?;
91+
92+
// If buffer returns Ok(0), propagate that to the caller without
93+
// doing additional buffering; otherwise we're just guaranteeing
94+
// an "ErrorKind::WriteZero" later.
95+
if flushed == 0 {
96+
return Ok(0);
97+
}
98+
99+
// Now that the write has succeeded, buffer the rest (or as much of
100+
// the rest as possible). If there were any unwritten newlines, we
101+
// only buffer out to the last unwritten newline that fits in the
102+
// buffer; this helps prevent flushing partial lines on subsequent
103+
// calls to LineWriterShim::write.
104+
105+
// Handle the cases in order of most-common to least-common, under
106+
// the presumption that most writes succeed in totality, and that most
107+
// writes are smaller than the buffer.
108+
// - Is this a partial line (ie, no newlines left in the unwritten tail)
109+
// - If not, does the data out to the last unwritten newline fit in
110+
// the buffer?
111+
// - If not, scan for the last newline that *does* fit in the buffer
112+
let tail = if flushed >= newline_idx {
113+
&buf[flushed..]
114+
} else if newline_idx - flushed <= self.buffer.capacity() {
115+
&buf[flushed..newline_idx]
116+
} else {
117+
let scan_area = &buf[flushed..];
118+
let scan_area = &scan_area[..self.buffer.capacity()];
119+
match memchr::memrchr(b'\n', scan_area) {
120+
Some(newline_idx) => &scan_area[..newline_idx + 1],
121+
None => scan_area,
122+
}
123+
};
124+
125+
let buffered = self.buffer.write_to_buf(tail);
126+
Ok(flushed + buffered)
127+
}
128+
129+
fn flush(&mut self) -> io::Result<()> {
130+
self.buffer.flush()
131+
}
132+
133+
/// Write some vectored data into this BufReader with line buffering. This
134+
/// means that, if any newlines are present in the data, the data up to
135+
/// and including the buffer containing the last newline is sent directly
136+
/// to the inner writer, and the data after it is buffered. Returns the
137+
/// number of bytes written.
138+
///
139+
/// This function operates on a "best effort basis"; in keeping with the
140+
/// convention of `Write::write`, it makes at most one attempt to write
141+
/// new data to the underlying writer.
142+
///
143+
/// Because this function attempts to send completed lines to the underlying
144+
/// writer, it will also flush the existing buffer if it contains any
145+
/// newlines.
146+
///
147+
/// Because sorting through an array of `IoSlice` can be a bit convoluted,
148+
/// This method differs from write in the following ways:
149+
///
150+
/// - It attempts to write the full content of all the buffers up to and
151+
/// including the one containing the last newline. This means that it
152+
/// may attempt to write a partial line, that buffer has data past the
153+
/// newline.
154+
/// - If the write only reports partial success, it does not attempt to
155+
/// find the precise location of the written bytes and buffer the rest.
156+
///
157+
/// If the underlying vector doesn't support vectored writing, we instead
158+
/// simply write the first non-empty buffer with `write`. This way, we
159+
/// get the benefits of more granular partial-line handling without losing
160+
/// anything in efficiency
161+
fn write_vectored(&mut self, bufs: &[IoSlice<'_>]) -> io::Result<usize> {
162+
// If there's no specialized behavior for write_vectored, just use
163+
// write. This has the benefit of more granular partial-line handling.
164+
if !self.is_write_vectored() {
165+
return match bufs.iter().find(|buf| !buf.is_empty()) {
166+
Some(buf) => self.write(buf),
167+
None => Ok(0),
168+
};
169+
}
170+
171+
// Find the buffer containing the last newline
172+
let last_newline_buf_idx = bufs
173+
.iter()
174+
.enumerate()
175+
.rev()
176+
.find_map(|(i, buf)| memchr::memchr(b'\n', buf).map(|_| i));
177+
178+
// If there are no new newlines (that is, if this write is less than
179+
// one line), just do a regular buffered write
180+
let last_newline_buf_idx = match last_newline_buf_idx {
181+
// No newlines; just do a normal buffered write
182+
None => {
183+
self.flush_if_completed_line()?;
184+
return self.buffer.write_vectored(bufs);
185+
}
186+
Some(i) => i,
187+
};
188+
189+
// Flush existing content to prepare for our write
190+
self.buffer.flush_buf()?;
191+
192+
// This is what we're going to try to write directly to the inner
193+
// writer. The rest will be buffered, if nothing goes wrong.
194+
let (lines, tail) = bufs.split_at(last_newline_buf_idx + 1);
195+
196+
// Write `lines` directly to the inner writer. In keeping with the
197+
// `write` convention, make at most one attempt to add new (unbuffered)
198+
// data. Because this write doesn't touch the BufWriter state directly,
199+
// and the buffer is known to be empty, we don't need to worry about
200+
// self.panicked here.
201+
let flushed = self.inner_mut().write_vectored(lines)?;
202+
203+
// If inner returns Ok(0), propagate that to the caller without
204+
// doing additional buffering; otherwise we're just guaranteeing
205+
// an "ErrorKind::WriteZero" later.
206+
if flushed == 0 {
207+
return Ok(0);
208+
}
209+
210+
// Don't try to reconstruct the exact amount written; just bail
211+
// in the event of a partial write
212+
let lines_len = lines.iter().map(|buf| buf.len()).sum();
213+
if flushed < lines_len {
214+
return Ok(flushed);
215+
}
216+
217+
// Now that the write has succeeded, buffer the rest (or as much of the
218+
// rest as possible)
219+
let buffered: usize = tail
220+
.iter()
221+
.filter(|buf| !buf.is_empty())
222+
.map(|buf| self.buffer.write_to_buf(buf))
223+
.take_while(|&n| n > 0)
224+
.sum();
225+
226+
Ok(flushed + buffered)
227+
}
228+
229+
fn is_write_vectored(&self) -> bool {
230+
self.buffer.is_write_vectored()
231+
}
232+
233+
/// Write some data into this BufReader with line buffering. This means
234+
/// that, if any newlines are present in the data, the data up to the last
235+
/// newline is sent directly to the underlying writer, and data after it
236+
/// is buffered.
237+
///
238+
/// Because this function attempts to send completed lines to the underlying
239+
/// writer, it will also flush the existing buffer if it contains any
240+
/// newlines, even if the incoming data does not contain any newlines.
241+
fn write_all(&mut self, buf: &[u8]) -> io::Result<()> {
242+
match memchr::memrchr(b'\n', buf) {
243+
// If there are no new newlines (that is, if this write is less than
244+
// one line), just do a regular buffered write (which may flush if
245+
// we exceed the inner buffer's size)
246+
None => {
247+
self.flush_if_completed_line()?;
248+
self.buffer.write_all(buf)
249+
}
250+
Some(newline_idx) => {
251+
let (lines, tail) = buf.split_at(newline_idx + 1);
252+
253+
if self.buffered().is_empty() {
254+
self.inner_mut().write_all(lines)?;
255+
} else {
256+
// If there is any buffered data, we add the incoming lines
257+
// to that buffer before flushing, which saves us at least
258+
// one write call. We can't really do this with `write`,
259+
// since we can't do this *and* not suppress errors *and*
260+
// report a consistent state to the caller in a return
261+
// value, but here in write_all it's fine.
262+
self.buffer.write_all(lines)?;
263+
self.buffer.flush_buf()?;
264+
}
265+
266+
self.buffer.write_all(tail)
267+
}
268+
}
269+
}
270+
}

‎library/std/src/io/buffered/mod.rs

Lines changed: 151 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,151 @@
1+
//! Buffering wrappers for I/O traits
2+
3+
mod bufreader;
4+
mod bufwriter;
5+
mod linewriter;
6+
mod linewritershim;
7+
8+
#[cfg(test)]
9+
mod tests;
10+
11+
use crate::error;
12+
use crate::fmt;
13+
use crate::io::Error;
14+
15+
pub use bufreader::BufReader;
16+
pub use bufwriter::BufWriter;
17+
pub use linewriter::LineWriter;
18+
use linewritershim::LineWriterShim;
19+
20+
/// An error returned by [`BufWriter::into_inner`] which combines an error that
21+
/// happened while writing out the buffer, and the buffered writer object
22+
/// which may be used to recover from the condition.
23+
///
24+
/// # Examples
25+
///
26+
/// ```no_run
27+
/// use std::io::BufWriter;
28+
/// use std::net::TcpStream;
29+
///
30+
/// let mut stream = BufWriter::new(TcpStream::connect("127.0.0.1:34254").unwrap());
31+
///
32+
/// // do stuff with the stream
33+
///
34+
/// // we want to get our `TcpStream` back, so let's try:
35+
///
36+
/// let stream = match stream.into_inner() {
37+
/// Ok(s) => s,
38+
/// Err(e) => {
39+
/// // Here, e is an IntoInnerError
40+
/// panic!("An error occurred");
41+
/// }
42+
/// };
43+
/// ```
44+
#[derive(Debug)]
45+
#[stable(feature = "rust1", since = "1.0.0")]
46+
pub struct IntoInnerError<W>(W, Error);
47+
48+
impl<W> IntoInnerError<W> {
49+
/// Construct a new IntoInnerError
50+
fn new(writer: W, error: Error) -> Self {
51+
Self(writer, error)
52+
}
53+
54+
/// Helper to construct a new IntoInnerError; intended to help with
55+
/// adapters that wrap other adapters
56+
fn new_wrapped<W2>(self, f: impl FnOnce(W) -> W2) -> IntoInnerError<W2> {
57+
let Self(writer, error) = self;
58+
IntoInnerError::new(f(writer), error)
59+
}
60+
61+
/// Returns the error which caused the call to [`BufWriter::into_inner()`]
62+
/// to fail.
63+
///
64+
/// This error was returned when attempting to write the internal buffer.
65+
///
66+
/// # Examples
67+
///
68+
/// ```no_run
69+
/// use std::io::BufWriter;
70+
/// use std::net::TcpStream;
71+
///
72+
/// let mut stream = BufWriter::new(TcpStream::connect("127.0.0.1:34254").unwrap());
73+
///
74+
/// // do stuff with the stream
75+
///
76+
/// // we want to get our `TcpStream` back, so let's try:
77+
///
78+
/// let stream = match stream.into_inner() {
79+
/// Ok(s) => s,
80+
/// Err(e) => {
81+
/// // Here, e is an IntoInnerError, let's log the inner error.
82+
/// //
83+
/// // We'll just 'log' to stdout for this example.
84+
/// println!("{}", e.error());
85+
///
86+
/// panic!("An unexpected error occurred.");
87+
/// }
88+
/// };
89+
/// ```
90+
#[stable(feature = "rust1", since = "1.0.0")]
91+
pub fn error(&self) -> &Error {
92+
&self.1
93+
}
94+
95+
/// Returns the buffered writer instance which generated the error.
96+
///
97+
/// The returned object can be used for error recovery, such as
98+
/// re-inspecting the buffer.
99+
///
100+
/// # Examples
101+
///
102+
/// ```no_run
103+
/// use std::io::BufWriter;
104+
/// use std::net::TcpStream;
105+
///
106+
/// let mut stream = BufWriter::new(TcpStream::connect("127.0.0.1:34254").unwrap());
107+
///
108+
/// // do stuff with the stream
109+
///
110+
/// // we want to get our `TcpStream` back, so let's try:
111+
///
112+
/// let stream = match stream.into_inner() {
113+
/// Ok(s) => s,
114+
/// Err(e) => {
115+
/// // Here, e is an IntoInnerError, let's re-examine the buffer:
116+
/// let buffer = e.into_inner();
117+
///
118+
/// // do stuff to try to recover
119+
///
120+
/// // afterwards, let's just return the stream
121+
/// buffer.into_inner().unwrap()
122+
/// }
123+
/// };
124+
/// ```
125+
#[stable(feature = "rust1", since = "1.0.0")]
126+
pub fn into_inner(self) -> W {
127+
self.0
128+
}
129+
}
130+
131+
#[stable(feature = "rust1", since = "1.0.0")]
132+
impl<W> From<IntoInnerError<W>> for Error {
133+
fn from(iie: IntoInnerError<W>) -> Error {
134+
iie.1
135+
}
136+
}
137+
138+
#[stable(feature = "rust1", since = "1.0.0")]
139+
impl<W: Send + fmt::Debug> error::Error for IntoInnerError<W> {
140+
#[allow(deprecated, deprecated_in_future)]
141+
fn description(&self) -> &str {
142+
error::Error::description(self.error())
143+
}
144+
}
145+
146+
#[stable(feature = "rust1", since = "1.0.0")]
147+
impl<W> fmt::Display for IntoInnerError<W> {
148+
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
149+
self.error().fmt(f)
150+
}
151+
}

‎src/test/ui/suggestions/mut-borrow-needed-by-trait.stderr

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -13,7 +13,7 @@ error[E0277]: the trait bound `&dyn std::io::Write: std::io::Write` is not satis
1313
LL | let fp = BufWriter::new(fp);
1414
| ^^^^^^^^^^^^^^ the trait `std::io::Write` is not implemented for `&dyn std::io::Write`
1515
|
16-
::: $SRC_DIR/std/src/io/buffered.rs:LL:COL
16+
::: $SRC_DIR/std/src/io/buffered/bufwriter.rs:LL:COL
1717
|
1818
LL | pub struct BufWriter<W: Write> {
1919
| ----- required by this bound in `BufWriter`
@@ -26,7 +26,7 @@ error[E0277]: the trait bound `&dyn std::io::Write: std::io::Write` is not satis
2626
LL | let fp = BufWriter::new(fp);
2727
| ^^^^^^^^^^^^^^^^^^ the trait `std::io::Write` is not implemented for `&dyn std::io::Write`
2828
|
29-
::: $SRC_DIR/std/src/io/buffered.rs:LL:COL
29+
::: $SRC_DIR/std/src/io/buffered/bufwriter.rs:LL:COL
3030
|
3131
LL | pub struct BufWriter<W: Write> {
3232
| ----- required by this bound in `BufWriter`
@@ -39,7 +39,7 @@ error[E0599]: no method named `write_fmt` found for struct `BufWriter<&dyn std::
3939
LL | writeln!(fp, "hello world").unwrap();
4040
| ^^^^^^^^^^^^^^^^^^^^^^^^^^^ method not found in `BufWriter<&dyn std::io::Write>`
4141
|
42-
::: $SRC_DIR/std/src/io/buffered.rs:LL:COL
42+
::: $SRC_DIR/std/src/io/buffered/bufwriter.rs:LL:COL
4343
|
4444
LL | pub struct BufWriter<W: Write> {
4545
| ------------------------------ doesn't satisfy `BufWriter<&dyn std::io::Write>: std::io::Write`

0 commit comments

Comments
 (0)
Please sign in to comment.