Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

subscriber: Add MakeWriter impl for Option #3196

Open
wants to merge 1 commit into
base: master
Choose a base branch
from

Conversation

joshka
Copy link
Contributor

@joshka joshka commented Jan 16, 2025

This adds a MakeWriter impl for Option<M> where M: MakeWriter.
This makes it possible to use Option<MakeWriter> in combination with
other MakeWriter implementations (e.g. Tee).

An example is found in #776,
where depending on the configuration, the user might want to use any or
all of File, Stdout, and Stderr writers.

let stdout = enable_stdout.then_some(std::io::stdout);
let stderr = enable_stderr.then_some(std::io::stderr);
let file = path.map(|f| File::create(f).ok());

let multi_make_writer = stdout.and(stderr).and(file);

Motivation

I was looking to contribute by trying to close out old PRs and tasks. The current oldest is #776. In that, @SriRamanujam expressed a need where they could combine multiple make writers easily. This is currently tricky as the types would have to be type erased in order for this to work. Making Option<impl MakeWriter> implement MakeWriter simplifies that significantly.

Solution

Implement MakeWriter for Option<M> where M: MakeWriter

This adds a `MakeWriter` impl for `Option<M>` where `M: MakeWriter`.
This makes it possible to use `Option<MakeWriter>` in combination with
other `MakeWriter` implementations (e.g. `Tee`).

An example is found in tokio-rs#776,
where depending on the configuration, the user might want to use any or
all of `File`, `Stdout`, and `Stderr` writers.

```rust
let stdout = if enable_stdout { Some(std::io::stdout) } else { None };
let stderr = if enable_stderr { Some(std::io::stderr) } else { None };
let file = if let Some(path) { Some(File::create(path)?) } else { None };

let multi_make_writer = stdout.and(stderr).and(file);
```
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

1 participant