File tree Expand file tree Collapse file tree 3 files changed +56
-1
lines changed Expand file tree Collapse file tree 3 files changed +56
-1
lines changed Original file line number Diff line number Diff line change
1
+ mod multi_writer;
2
+
3
+ pub use multi_writer:: MultiWriter ;
Original file line number Diff line number Diff line change
1
+ use std:: io:: { self , Write } ;
2
+
3
+ /// Takes 0, 1, or more `std::io::Write`s and writes to them at a time.
4
+ /// `MultiWriter` implements `std::io::Write` trait.
5
+ ///
6
+ /// Inspired by Go's MultiWriter.
7
+ ///
8
+ /// # Examples
9
+ ///
10
+ /// ```
11
+ /// use lib::io::MultiWriter;
12
+ /// use std::{fs::File, io::{self, Write}};
13
+ ///
14
+ /// fn main() -> io::Result<()> {
15
+ /// let stdout = io::stdout();
16
+ /// let f = File::create("a.txt")?;
17
+ ///
18
+ /// let mut mw = MultiWriter::new(vec![Box::new(stdout), Box::new(f)]);
19
+ ///
20
+ /// mw.write("xxx".as_bytes())?;
21
+ /// mw.flush()?;
22
+ ///
23
+ /// Ok(())
24
+ /// }
25
+ /// ```
26
+ pub struct MultiWriter ( Vec < Box < dyn Write > > ) ;
27
+
28
+ impl MultiWriter {
29
+ /// Constructor.
30
+ pub fn new ( writers : Vec < Box < dyn Write > > ) -> Self {
31
+ Self ( writers)
32
+ }
33
+ }
34
+
35
+ impl Write for MultiWriter {
36
+ fn write ( & mut self , buf : & [ u8 ] ) -> io:: Result < usize > {
37
+ for w in & mut self . 0 {
38
+ // Using `Write::write` is more straightforward but
39
+ // it sometimes (especially when buf is large) writes only part of buf.
40
+ // To align bytes written for all writers (self.0), here uses `Write::write_all`.
41
+ w. write_all ( buf) ?;
42
+ }
43
+ Ok ( buf. len ( ) )
44
+ }
45
+
46
+ fn flush ( & mut self ) -> io:: Result < ( ) > {
47
+ for w in & mut self . 0 {
48
+ w. flush ( ) ?;
49
+ }
50
+ Ok ( ( ) )
51
+ }
52
+ }
Original file line number Diff line number Diff line change 1
- // 共通ライブラリ
1
+ pub mod io ;
You can’t perform that action at this time.
0 commit comments