Skip to content

Commit

Permalink
impl<T> Write for UniquePtr<T> where ... Pin<&a mut T> : Write.
Browse files Browse the repository at this point in the history
This commit implements forwarding of `Write` trait implementation from
`UniquePtr<T>` to the pointee type.  This is quite similar to how
`Box<T>` also forwards - see
https://doc.rust-lang.org/std/boxed/struct.Box.html#impl-Write-for-Box%3CW%3E

This commit has quite similar, orphan-rule-related motivation as the
earlier #1368 which covered the
`Read` trait.  For a more specific motivating example, please see
http://review.skia.org/c/skia/+/923337/3/experimental/rust_png/ffi/FFI.rs#254
  • Loading branch information
anforowicz committed Nov 22, 2024
1 parent 547a0ed commit 83299d1
Showing 1 changed file with 39 additions and 1 deletion.
40 changes: 39 additions & 1 deletion src/unique_ptr.rs
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,7 @@ use core::mem::{self, MaybeUninit};
use core::ops::{Deref, DerefMut};
use core::pin::Pin;
#[cfg(feature = "std")]
use std::io::{self, Read};
use std::io::{self, Read, Write};

/// Binding to C++ `std::unique_ptr<T, std::default_delete<T>>`.
#[repr(C)]
Expand Down Expand Up @@ -220,6 +220,44 @@ where
// `read_buf` and/or `is_read_vectored`).
}

/// Forwarding `Write` trait implementation in a manner similar to `Box<T>`.
///
/// Note that the implementation will panic for null `UniquePtr<T>`.
#[cfg(feature = "std")]
impl<T> Write for UniquePtr<T>
where
for<'a> Pin<&'a mut T>: Write,
T: UniquePtrTarget,
{
#[inline]
fn write(&mut self, buf: &[u8]) -> io::Result<usize> {
self.pin_mut().write(buf)
}

#[inline]
fn write_vectored(&mut self, bufs: &[io::IoSlice<'_>]) -> io::Result<usize> {
self.pin_mut().write_vectored(bufs)
}

#[inline]
fn flush(&mut self) -> io::Result<()> {
self.pin_mut().flush()
}

#[inline]
fn write_all(&mut self, buf: &[u8]) -> io::Result<()> {
self.pin_mut().write_all(buf)
}

#[inline]
fn write_fmt(&mut self, fmt: fmt::Arguments<'_>) -> io::Result<()> {
self.pin_mut().write_fmt(fmt)
}

// TODO: Foward other `Write` trait methods when they get stabilized (e.g.
// `write_all_vectored` and/or `is_write_vectored`).
}

/// Trait bound for types which may be used as the `T` inside of a
/// `UniquePtr<T>` in generic code.
///
Expand Down

0 comments on commit 83299d1

Please sign in to comment.