Skip to content

Commit c23c7ad

Browse files
committed
impl<T> Read for UniquePtr<T> where ... Pin<&a mut T> : Read.
This commit implements forwarding of `Read` 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-Read-for-Box%3CR%3E Just as with `Box<T>`, the `impl` cannot be provided in the crate introducing `T`, because this violates the orphan rule. This means that before this commit a wrapper newtype would be required to work around the orphan rule - e.g.: ``` struct UniquePtrOfReadTrait(cxx::UniquePtr<ffi::ReadTrait>); impl Read for UniquePtrOfReadTrait { … } ``` After this commit, one can provide an `impl` that works more directly with the C++ type `T` (the FFI will typically require passing `self: Pin<&mut ffi::ReadTrait>`): ``` impl<'a> Read for Pin<&'a mut ffi::ReadTrait> { … } ``` For a more specific motivating example, please see: https://docs.google.com/document/d/1EPn1Ss-hfOC6Ki_B5CC6GA_UFnY3TmoDLCP2HjP7bms
1 parent 6809dc4 commit c23c7ad

File tree

1 file changed

+35
-0
lines changed

1 file changed

+35
-0
lines changed

src/unique_ptr.rs

Lines changed: 35 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -10,6 +10,9 @@ use core::mem::{self, MaybeUninit};
1010
use core::ops::{Deref, DerefMut};
1111
use core::pin::Pin;
1212

13+
#[cfg(feature = "std")]
14+
use std::io::Read;
15+
1316
/// Binding to C++ `std::unique_ptr<T, std::default_delete<T>>`.
1417
#[repr(C)]
1518
pub struct UniquePtr<T>
@@ -181,6 +184,38 @@ where
181184
}
182185
}
183186

187+
/// Forwarding `Read` trait implementation in a manner similar to `Box<T>`. Note that the
188+
/// implementation will panic for null `UniquePtr<T>`.
189+
#[cfg(feature = "std")]
190+
impl<T> Read for UniquePtr<T>
191+
where
192+
for<'a> Pin<&'a mut T>: Read,
193+
T: UniquePtrTarget,
194+
{
195+
#[inline]
196+
fn read(&mut self, buf: &mut [u8]) -> std::io::Result<usize> {
197+
self.pin_mut().read(buf)
198+
}
199+
200+
#[inline]
201+
fn read_to_end(&mut self, buf: &mut std::vec::Vec<u8>) -> std::io::Result<usize> {
202+
self.pin_mut().read_to_end(buf)
203+
}
204+
205+
#[inline]
206+
fn read_to_string(&mut self, buf: &mut std::string::String) -> std::io::Result<usize> {
207+
self.pin_mut().read_to_string(buf)
208+
}
209+
210+
#[inline]
211+
fn read_exact(&mut self, buf: &mut [u8]) -> std::io::Result<()> {
212+
self.pin_mut().read_exact(buf)
213+
}
214+
215+
// TODO: Foward other `Read` trait methods when they get stabilized (e.g.
216+
// `read_buf` and/or `is_read_vectored`).
217+
}
218+
184219
/// Trait bound for types which may be used as the `T` inside of a
185220
/// `UniquePtr<T>` in generic code.
186221
///

0 commit comments

Comments
 (0)