alloc/io/buffered/linewriter.rs
1use crate::fmt;
2use crate::io::buffered::LineWriterShim;
3use crate::io::{self, BufWriter, IntoInnerError, IoSlice, Write};
4
5/// Wraps a writer and buffers output to it, flushing whenever a newline
6/// (`0x0a`, `'\n'`) is detected.
7///
8/// The [`BufWriter`] struct wraps a writer and buffers its output.
9/// But it only does this batched write when it goes out of scope, or when the
10/// internal buffer is full. Sometimes, you'd prefer to write each line as it's
11/// completed, rather than the entire buffer at once. Enter `LineWriter`. It
12/// does exactly that.
13///
14/// Like [`BufWriter`], a `LineWriter`’s buffer will also be flushed when the
15/// `LineWriter` goes out of scope or when its internal buffer is full.
16///
17/// If there's still a partial line in the buffer when the `LineWriter` is
18/// dropped, it will flush those contents.
19///
20/// # Examples
21///
22/// We can use `LineWriter` to write one line at a time, significantly
23/// reducing the number of actual writes to the file.
24///
25/// ```no_run
26/// use std::fs::{self, File};
27/// use std::io::prelude::*;
28/// use std::io::LineWriter;
29///
30/// fn main() -> std::io::Result<()> {
31/// let road_not_taken = b"I shall be telling this with a sigh
32/// Somewhere ages and ages hence:
33/// Two roads diverged in a wood, and I -
34/// I took the one less traveled by,
35/// And that has made all the difference.";
36///
37/// let file = File::create("poem.txt")?;
38/// let mut file = LineWriter::new(file);
39///
40/// file.write_all(b"I shall be telling this with a sigh")?;
41///
42/// // No bytes are written until a newline is encountered (or
43/// // the internal buffer is filled).
44/// assert_eq!(fs::read_to_string("poem.txt")?, "");
45/// file.write_all(b"\n")?;
46/// assert_eq!(
47/// fs::read_to_string("poem.txt")?,
48/// "I shall be telling this with a sigh\n",
49/// );
50///
51/// // Write the rest of the poem.
52/// file.write_all(b"Somewhere ages and ages hence:
53/// Two roads diverged in a wood, and I -
54/// I took the one less traveled by,
55/// And that has made all the difference.")?;
56///
57/// // The last line of the poem doesn't end in a newline, so
58/// // we have to flush or drop the `LineWriter` to finish
59/// // writing.
60/// file.flush()?;
61///
62/// // Confirm the whole poem was written.
63/// assert_eq!(fs::read("poem.txt")?, &road_not_taken[..]);
64/// Ok(())
65/// }
66/// ```
67#[stable(feature = "rust1", since = "1.0.0")]
68pub struct LineWriter<W: ?Sized + Write> {
69 inner: BufWriter<W>,
70}
71
72impl<W: Write> LineWriter<W> {
73 /// Creates a new `LineWriter`.
74 ///
75 /// # Examples
76 ///
77 /// ```no_run
78 /// use std::fs::File;
79 /// use std::io::LineWriter;
80 ///
81 /// fn main() -> std::io::Result<()> {
82 /// let file = File::create("poem.txt")?;
83 /// let file = LineWriter::new(file);
84 /// Ok(())
85 /// }
86 /// ```
87 #[cfg(not(no_global_oom_handling))]
88 #[stable(feature = "rust1", since = "1.0.0")]
89 pub fn new(inner: W) -> LineWriter<W> {
90 // Lines typically aren't that long, don't use a giant buffer
91 LineWriter::with_capacity(1024, inner)
92 }
93
94 /// Creates a new `LineWriter` with at least the specified capacity for the
95 /// internal buffer.
96 ///
97 /// # Examples
98 ///
99 /// ```no_run
100 /// use std::fs::File;
101 /// use std::io::LineWriter;
102 ///
103 /// fn main() -> std::io::Result<()> {
104 /// let file = File::create("poem.txt")?;
105 /// let file = LineWriter::with_capacity(100, file);
106 /// Ok(())
107 /// }
108 /// ```
109 #[cfg(not(no_global_oom_handling))]
110 #[stable(feature = "rust1", since = "1.0.0")]
111 pub fn with_capacity(capacity: usize, inner: W) -> LineWriter<W> {
112 LineWriter { inner: BufWriter::with_capacity(capacity, inner) }
113 }
114
115 /// Gets a mutable reference to the underlying writer.
116 ///
117 /// Caution must be taken when calling methods on the mutable reference
118 /// returned as extra writes could corrupt the output stream.
119 ///
120 /// # Examples
121 ///
122 /// ```no_run
123 /// use std::fs::File;
124 /// use std::io::LineWriter;
125 ///
126 /// fn main() -> std::io::Result<()> {
127 /// let file = File::create("poem.txt")?;
128 /// let mut file = LineWriter::new(file);
129 ///
130 /// // we can use reference just like file
131 /// let reference = file.get_mut();
132 /// Ok(())
133 /// }
134 /// ```
135 #[stable(feature = "rust1", since = "1.0.0")]
136 pub fn get_mut(&mut self) -> &mut W {
137 self.inner.get_mut()
138 }
139
140 /// Unwraps this `LineWriter`, returning the underlying writer.
141 ///
142 /// The internal buffer is written out before returning the writer.
143 ///
144 /// # Errors
145 ///
146 /// An [`Err`] will be returned if an error occurs while flushing the buffer.
147 ///
148 /// # Examples
149 ///
150 /// ```no_run
151 /// use std::fs::File;
152 /// use std::io::LineWriter;
153 ///
154 /// fn main() -> std::io::Result<()> {
155 /// let file = File::create("poem.txt")?;
156 ///
157 /// let writer: LineWriter<File> = LineWriter::new(file);
158 ///
159 /// let file: File = writer.into_inner()?;
160 /// Ok(())
161 /// }
162 /// ```
163 #[stable(feature = "rust1", since = "1.0.0")]
164 pub fn into_inner(self) -> Result<W, IntoInnerError<LineWriter<W>>> {
165 self.inner.into_inner().map_err(|err| err.new_wrapped(|inner| LineWriter { inner }))
166 }
167}
168
169impl<W: ?Sized + Write> LineWriter<W> {
170 /// Gets a reference to the underlying writer.
171 ///
172 /// # Examples
173 ///
174 /// ```no_run
175 /// use std::fs::File;
176 /// use std::io::LineWriter;
177 ///
178 /// fn main() -> std::io::Result<()> {
179 /// let file = File::create("poem.txt")?;
180 /// let file = LineWriter::new(file);
181 ///
182 /// let reference = file.get_ref();
183 /// Ok(())
184 /// }
185 /// ```
186 #[stable(feature = "rust1", since = "1.0.0")]
187 pub fn get_ref(&self) -> &W {
188 self.inner.get_ref()
189 }
190}
191
192#[stable(feature = "rust1", since = "1.0.0")]
193impl<W: ?Sized + Write> Write for LineWriter<W> {
194 fn write(&mut self, buf: &[u8]) -> io::Result<usize> {
195 LineWriterShim::new(&mut self.inner).write(buf)
196 }
197
198 fn flush(&mut self) -> io::Result<()> {
199 self.inner.flush()
200 }
201
202 fn write_vectored(&mut self, bufs: &[IoSlice<'_>]) -> io::Result<usize> {
203 LineWriterShim::new(&mut self.inner).write_vectored(bufs)
204 }
205
206 fn is_write_vectored(&self) -> bool {
207 self.inner.is_write_vectored()
208 }
209
210 fn write_all(&mut self, buf: &[u8]) -> io::Result<()> {
211 LineWriterShim::new(&mut self.inner).write_all(buf)
212 }
213
214 fn write_all_vectored(&mut self, bufs: &mut [IoSlice<'_>]) -> io::Result<()> {
215 LineWriterShim::new(&mut self.inner).write_all_vectored(bufs)
216 }
217
218 fn write_fmt(&mut self, fmt: fmt::Arguments<'_>) -> io::Result<()> {
219 LineWriterShim::new(&mut self.inner).write_fmt(fmt)
220 }
221}
222
223#[stable(feature = "rust1", since = "1.0.0")]
224impl<W: ?Sized + Write> fmt::Debug for LineWriter<W>
225where
226 W: fmt::Debug,
227{
228 fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result {
229 fmt.debug_struct("LineWriter")
230 .field("writer", &self.get_ref())
231 .field(
232 "buffer",
233 &format_args!("{}/{}", self.inner.buffer().len(), self.inner.capacity()),
234 )
235 .finish_non_exhaustive()
236 }
237}