yuk1ty / learning-systems-programming-in-rust

「Rustでもわかるシステムプログラミング」
430 stars 23 forks source link

add 2_4_5 #38

Closed shnmorimoto closed 3 years ago

shnmorimoto commented 3 years ago

5

一旦実装してみましたが、下記少し悩んでいます。

laysakura commented 3 years ago

io.MultiWriter 相当のものが見つからなかったので、自前でFileをwrapするものを実装したが、他に良い方法がないか、もしくはskipしたほうがよいか?

簡易的なものなら MultiWriter はシンプルに作れます。

use std::{
    fs::File,
    io::{self, Write},
};

struct MultiWriter(Vec<Box<dyn Write>>);

impl MultiWriter {
    fn new(writers: Vec<Box<dyn Write>>) -> Self {
        Self(writers)
    }
}

impl Write for MultiWriter {
    fn write(&mut self, buf: &[u8]) -> io::Result<usize> {
        for w in &mut self.0 {
            // Using `Write::write` is more straightforward but
            // it sometimes (especially when buf is large) writes only part of buf.
            // To align bytes written for all writers (self.0), here uses `Write::write_all`.
            w.write_all(buf)?;
        }
        Ok(buf.len())
    }

    fn flush(&mut self) -> io::Result<()> {
        for w in &mut self.0 {
            w.flush()?;
        }
        Ok(())
    }
}

fn main() -> io::Result<()> {
    let stdout = io::stdout();
    let f = File::create("a.txt")?;

    let mut mw = MultiWriter::new(vec![Box::new(stdout), Box::new(f)]);

    mw.write("xxx".as_bytes())?;
    mw.write("yyy".as_bytes())?;
    mw.flush()?;

    Ok(())
}

2.8 の Q3 を担当していてそこでも MultiWriter を使う必要があるから実装しました。

こんなふうに「標準ライブラリに入ってないしわざわざ外部クレート使うほどでもないが、このリポジトリでは共通して使いたい」ものはどうしましょうね? Issueを立てておきます。 → 立てました: https://github.com/yuk1ty/learning-systems-programming-in-rust/issues/39

laysakura commented 3 years ago

gzipのライブラリとして、flate2が適当か。

rust-lang organization 配下のcrateですし、 std::io::Write トレイト実装をしたエンコーダーがありこの本の題材にもマッチしやすいので、私は適当だと思います。

自分が担当している 2.8 Q3 でもgzip必要なので、flate2を使うことにします。 もしベターなものがありそれを使うということになったら追従します 🏃

shnmorimoto commented 3 years ago

@laysakura レビューありがとうございます。

簡易的なものなら MultiWriter はシンプルに作れます。

おぉ、こんなにシンプルに定義できるのですね。ありがとうございます。

こんなふうに「標準ライブラリに入ってないしわざわざ外部クレート使うほどでもないが、このリポジトリでは共通して使いたい」ものはどうしましょうね? Issueを立てておきます。 → 立てました: #39

lib を導入する予定とのことなので、そちらに定義され次第、利用するように修正致します。

rust-lang organization 配下のcrateですし、 std::io::Write トレイト実装をしたエンコーダーがありこの本の題材にもマッチしやすいので、私は適当だと思います。

自分が担当している 2.8 Q3 でもgzip必要なので、flate2を使うことにします。 もしベターなものがありそれを使うということになったら追従します runner

承知致しました。一旦flate2で進めようと思います。

laysakura commented 3 years ago

@shnmorimoto https://github.com/yuk1ty/learning-systems-programming-in-rust/pull/51 で lib::io::MultiWriter が入ったのでお知らせします 🔈

shnmorimoto commented 3 years ago

@laysakura ありがとうございます!修正完了致しました!

shnmorimoto commented 3 years ago

コンフリクト修正したら、少し変なコミットログになってしまったので、修正してpushしなおしました。🙏

yuk1ty commented 3 years ago

5/7 23:59 までオープンしておきます!