-
Notifications
You must be signed in to change notification settings - Fork 35
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
Add a Style::with_writer() method, or an RAII guard equivalent #41
Comments
This would be very useful to me too. An alternative way to achieve the same thing (although I am not sure about the exception safety of such a solution) would be to have a writer wrapper in the spirit of (not tested, but it compiles) struct StyledWrite<'a, T: Write> {
style: Style,
inner: &'a mut T,
}
impl<'a, T: Write> StyledWrite<'a, T> {
fn new(inner: &'a mut T, style: Style) -> Self {
// write the style prefix sequence into inner here
Self { inner, style }
}
}
impl<T: Write> Drop for StyledWrite<'_, T> {
fn drop(&mut self) {
// write the style suffix sequence into inner here
}
}
impl<T: Write> Write for StyledWrite<'_, T> {
fn write(&mut self, buf: &[u8]) -> std::io::Result<usize> {
self.inner.write(buf)
}
fn flush(&mut self) -> std::io::Result<()> {
self.inner.flush()
}
}
trait WriteExt<T: Write> {
fn styled(&mut self, style: Style) -> StyledWrite<'_, T>;
fn red(&mut self) -> StyledWrite<'_, T>;
}
impl<T> WriteExt<T> for T
where
T: Write,
{
fn styled(&mut self, style: Style) -> StyledWrite<'_, T> {
StyledWrite::new(self, style)
}
fn red(&mut self) -> StyledWrite<'_, T> {
self.styled(Style::new().red())
}
} which would enable an even nicer API for styling the whole writer for a limited time: write!(myWrite.red(), "everything is red!");
write!(myWrite.styled(Style::new().bold()), "everything is bold!"); I have not filled out the parts which write the boundary sequences because I am not sure how to properly use the UPDATE: playing with this a little more, it works pretty well, but the writing of a suffix sequence in drop is not infallible, and I am not sure what the proper way of handling errors in drop is. |
Ah sadly with the RAII pattern, ignoring the error is the only reasonable option in
I'd personally say that dropping causing a color reset is a bit too magical, which suggests to me that the callback pattern would be better. |
I have an interesting use case:
This doesn't seem possible with owo-colors, but it seems like it would be possible with a little bit of infrastructure:
This would make it possible to write:
The callback pattern can also makes it more robust to panics, assuming an RAII guard is used. (Or actually, it might be a better design to just make an RAII guard part of the public API!)
What do you think?
The text was updated successfully, but these errors were encountered: