1 | use crate::fmt; |
2 | use crate::io::buffered::LineWriterShim; |
3 | use 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" )] |
68 | pub struct LineWriter<W: ?Sized + Write> { |
69 | inner: BufWriter<W>, |
70 | } |
71 | |
72 | impl<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 | #[stable (feature = "rust1" , since = "1.0.0" )] |
88 | pub fn new(inner: W) -> LineWriter<W> { |
89 | // Lines typically aren't that long, don't use a giant buffer |
90 | LineWriter::with_capacity(1024, inner) |
91 | } |
92 | |
93 | /// Creates a new `LineWriter` with at least the specified capacity for the |
94 | /// internal buffer. |
95 | /// |
96 | /// # Examples |
97 | /// |
98 | /// ```no_run |
99 | /// use std::fs::File; |
100 | /// use std::io::LineWriter; |
101 | /// |
102 | /// fn main() -> std::io::Result<()> { |
103 | /// let file = File::create("poem.txt" )?; |
104 | /// let file = LineWriter::with_capacity(100, file); |
105 | /// Ok(()) |
106 | /// } |
107 | /// ``` |
108 | #[stable (feature = "rust1" , since = "1.0.0" )] |
109 | pub fn with_capacity(capacity: usize, inner: W) -> LineWriter<W> { |
110 | LineWriter { inner: BufWriter::with_capacity(capacity, inner) } |
111 | } |
112 | |
113 | /// Gets a mutable reference to the underlying writer. |
114 | /// |
115 | /// Caution must be taken when calling methods on the mutable reference |
116 | /// returned as extra writes could corrupt the output stream. |
117 | /// |
118 | /// # Examples |
119 | /// |
120 | /// ```no_run |
121 | /// use std::fs::File; |
122 | /// use std::io::LineWriter; |
123 | /// |
124 | /// fn main() -> std::io::Result<()> { |
125 | /// let file = File::create("poem.txt" )?; |
126 | /// let mut file = LineWriter::new(file); |
127 | /// |
128 | /// // we can use reference just like file |
129 | /// let reference = file.get_mut(); |
130 | /// Ok(()) |
131 | /// } |
132 | /// ``` |
133 | #[stable (feature = "rust1" , since = "1.0.0" )] |
134 | pub fn get_mut(&mut self) -> &mut W { |
135 | self.inner.get_mut() |
136 | } |
137 | |
138 | /// Unwraps this `LineWriter`, returning the underlying writer. |
139 | /// |
140 | /// The internal buffer is written out before returning the writer. |
141 | /// |
142 | /// # Errors |
143 | /// |
144 | /// An [`Err`] will be returned if an error occurs while flushing the buffer. |
145 | /// |
146 | /// # Examples |
147 | /// |
148 | /// ```no_run |
149 | /// use std::fs::File; |
150 | /// use std::io::LineWriter; |
151 | /// |
152 | /// fn main() -> std::io::Result<()> { |
153 | /// let file = File::create("poem.txt" )?; |
154 | /// |
155 | /// let writer: LineWriter<File> = LineWriter::new(file); |
156 | /// |
157 | /// let file: File = writer.into_inner()?; |
158 | /// Ok(()) |
159 | /// } |
160 | /// ``` |
161 | #[stable (feature = "rust1" , since = "1.0.0" )] |
162 | pub fn into_inner(self) -> Result<W, IntoInnerError<LineWriter<W>>> { |
163 | self.inner.into_inner().map_err(|err| err.new_wrapped(|inner| LineWriter { inner })) |
164 | } |
165 | } |
166 | |
167 | impl<W: ?Sized + Write> LineWriter<W> { |
168 | /// Gets a reference to the underlying writer. |
169 | /// |
170 | /// # Examples |
171 | /// |
172 | /// ```no_run |
173 | /// use std::fs::File; |
174 | /// use std::io::LineWriter; |
175 | /// |
176 | /// fn main() -> std::io::Result<()> { |
177 | /// let file = File::create("poem.txt" )?; |
178 | /// let file = LineWriter::new(file); |
179 | /// |
180 | /// let reference = file.get_ref(); |
181 | /// Ok(()) |
182 | /// } |
183 | /// ``` |
184 | #[stable (feature = "rust1" , since = "1.0.0" )] |
185 | pub fn get_ref(&self) -> &W { |
186 | self.inner.get_ref() |
187 | } |
188 | } |
189 | |
190 | #[stable (feature = "rust1" , since = "1.0.0" )] |
191 | impl<W: ?Sized + Write> Write for LineWriter<W> { |
192 | fn write(&mut self, buf: &[u8]) -> io::Result<usize> { |
193 | LineWriterShim::new(&mut self.inner).write(buf) |
194 | } |
195 | |
196 | fn flush(&mut self) -> io::Result<()> { |
197 | self.inner.flush() |
198 | } |
199 | |
200 | fn write_vectored(&mut self, bufs: &[IoSlice<'_>]) -> io::Result<usize> { |
201 | LineWriterShim::new(&mut self.inner).write_vectored(bufs) |
202 | } |
203 | |
204 | fn is_write_vectored(&self) -> bool { |
205 | self.inner.is_write_vectored() |
206 | } |
207 | |
208 | fn write_all(&mut self, buf: &[u8]) -> io::Result<()> { |
209 | LineWriterShim::new(&mut self.inner).write_all(buf) |
210 | } |
211 | |
212 | fn write_all_vectored(&mut self, bufs: &mut [IoSlice<'_>]) -> io::Result<()> { |
213 | LineWriterShim::new(&mut self.inner).write_all_vectored(bufs) |
214 | } |
215 | |
216 | fn write_fmt(&mut self, fmt: fmt::Arguments<'_>) -> io::Result<()> { |
217 | LineWriterShim::new(&mut self.inner).write_fmt(fmt) |
218 | } |
219 | } |
220 | |
221 | #[stable (feature = "rust1" , since = "1.0.0" )] |
222 | impl<W: ?Sized + Write> fmt::Debug for LineWriter<W> |
223 | where |
224 | W: fmt::Debug, |
225 | { |
226 | fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result { |
227 | fmt&mut DebugStruct<'_, '_>.debug_struct("LineWriter" ) |
228 | .field("writer" , &self.get_ref()) |
229 | .field( |
230 | name:"buffer" , |
231 | &format_args!(" {}/ {}" , self.inner.buffer().len(), self.inner.capacity()), |
232 | ) |
233 | .finish_non_exhaustive() |
234 | } |
235 | } |
236 | |