Skip to content

Commit

Permalink
feat: Implement AsLockedWrite generically too
Browse files Browse the repository at this point in the history
  • Loading branch information
DaniPopes committed Oct 24, 2024
1 parent f4a1f98 commit 8639e08
Showing 1 changed file with 72 additions and 0 deletions.
72 changes: 72 additions & 0 deletions crates/anstream/src/stream.rs
Original file line number Diff line number Diff line change
Expand Up @@ -142,6 +142,30 @@ pub trait AsLockedWrite: private::Sealed {
fn as_locked_write(&mut self) -> Self::Write<'_>;
}

impl<T: AsLockedWrite + ?Sized> AsLockedWrite for &mut T {
type Write<'w>
= T::Write<'w>
where
Self: 'w;

#[inline]
fn as_locked_write(&mut self) -> Self::Write<'_> {
(**self).as_locked_write()
}
}

impl<T: AsLockedWrite + ?Sized> AsLockedWrite for Box<T> {
type Write<'w>
= T::Write<'w>
where
Self: 'w;

#[inline]
fn as_locked_write(&mut self) -> Self::Write<'_> {
(**self).as_locked_write()
}
}

impl AsLockedWrite for std::io::Stdout {
type Write<'w> = std::io::StdoutLock<'w>;

Expand Down Expand Up @@ -187,6 +211,24 @@ impl AsLockedWrite for dyn std::io::Write {
}
}

impl AsLockedWrite for dyn std::io::Write + Send {
type Write<'w> = &'w mut Self;

#[inline]
fn as_locked_write(&mut self) -> Self::Write<'_> {
self
}
}

impl AsLockedWrite for dyn std::io::Write + Send + Sync {
type Write<'w> = &'w mut Self;

#[inline]
fn as_locked_write(&mut self) -> Self::Write<'_> {
self
}
}

impl AsLockedWrite for Vec<u8> {
type Write<'w> = &'w mut Self;

Expand Down Expand Up @@ -241,3 +283,33 @@ mod private {
#[allow(deprecated)]
impl Sealed for crate::Buffer {}
}

#[cfg(test)]
mod tests {
use super::*;

fn assert_raw_stream<T: RawStream>()
where
crate::AutoStream<T>: std::io::Write,
{
}

#[test]
fn test() {
assert_raw_stream::<Box<dyn std::io::Write>>();
assert_raw_stream::<Box<dyn std::io::Write + 'static>>();
assert_raw_stream::<Box<dyn std::io::Write + Send>>();
assert_raw_stream::<Box<dyn std::io::Write + Send + Sync>>();

assert_raw_stream::<&mut (dyn std::io::Write)>();
assert_raw_stream::<&mut (dyn std::io::Write + 'static)>();
assert_raw_stream::<&mut (dyn std::io::Write + Send)>();
assert_raw_stream::<&mut (dyn std::io::Write + Send + Sync)>();

assert_raw_stream::<Vec<u8>>();
assert_raw_stream::<&mut Vec<u8>>();

assert_raw_stream::<std::fs::File>();
assert_raw_stream::<&mut std::fs::File>();
}
}

0 comments on commit 8639e08

Please sign in to comment.