Skip to content

Commit 168a531

Browse files
authored
Merge pull request #51 from yuk1ty/lib-MultiWriter
feat: lib::io::MultiWriter を追加
2 parents dcac3ef + 80f95f7 commit 168a531

File tree

3 files changed

+56
-1
lines changed

3 files changed

+56
-1
lines changed

lib/src/io.rs

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,3 @@
1+
mod multi_writer;
2+
3+
pub use multi_writer::MultiWriter;

lib/src/io/multi_writer.rs

Lines changed: 52 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,52 @@
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+
}

lib/src/lib.rs

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1 +1 @@
1-
// 共通ライブラリ
1+
pub mod io;

0 commit comments

Comments
 (0)