Remove &mut T access from UniquePtr

This commit is contained in:
David Tolnay 2020-11-16 22:34:50 -08:00
parent 099adee57b
commit 6fdeeebee0
No known key found for this signature in database
GPG Key ID: F9BA143B95FF6D82
4 changed files with 16 additions and 22 deletions

View File

@ -6,7 +6,7 @@ use core::ffi::c_void;
use core::fmt::{self, Debug, Display};
use core::marker::PhantomData;
use core::mem;
use core::ops::{Deref, DerefMut};
use core::ops::Deref;
use core::pin::Pin;
use core::ptr;
@ -59,10 +59,13 @@ where
unsafe { T::__get(self.repr).as_ref() }
}
/// Returns a mutable reference to the object owned by this UniquePtr if
/// any, otherwise None.
pub fn as_mut(&mut self) -> Option<&mut T> {
unsafe { (T::__get(self.repr) as *mut T).as_mut() }
/// Returns a mutable pinned reference to the object owned by this UniquePtr
/// if any, otherwise None.
pub fn as_mut(&mut self) -> Option<Pin<&mut T>> {
unsafe {
let mut_reference = (T::__get(self.repr) as *mut T).as_mut()?;
Some(Pin::new_unchecked(mut_reference))
}
}
/// Consumes the UniquePtr, releasing its ownership of the heap-allocated T.
@ -126,18 +129,6 @@ where
}
}
impl<T> DerefMut for UniquePtr<T>
where
T: UniquePtrTarget,
{
fn deref_mut(&mut self) -> &mut Self::Target {
match self.as_mut() {
Some(target) => target,
None => panic!("called deref_mut on a null UniquePtr<{}>", T::__NAME),
}
}
}
impl<T> Debug for UniquePtr<T>
where
T: Debug + UniquePtrTarget,

View File

@ -124,7 +124,7 @@ pub mod ffi {
fn c_return_primitive() -> usize;
fn c_return_shared() -> Shared;
fn c_return_box() -> Box<R>;
fn c_return_unique_ptr() -> Pin<UniquePtr<C>>;
fn c_return_unique_ptr() -> UniquePtr<C>;
fn c_return_ref(shared: &Shared) -> &usize;
fn c_return_mut(shared: &mut Shared) -> &mut usize;
fn c_return_str(shared: &Shared) -> &str;

View File

@ -8,6 +8,6 @@ pub mod ffi {
type C = crate::ffi::C;
fn c_take_unique_ptr(c: Pin<UniquePtr<C>>);
fn c_take_unique_ptr(c: UniquePtr<C>);
}
}

View File

@ -188,11 +188,14 @@ fn test_c_method_calls() {
let old_value = unique_ptr.get();
assert_eq!(2020, old_value);
assert_eq!(2021, unique_ptr.as_mut().set(2021));
assert_eq!(2021, unique_ptr.as_mut().unwrap().set(2021));
assert_eq!(2021, unique_ptr.get());
assert_eq!(2021, unique_ptr.get2());
assert_eq!(2022, unique_ptr.as_mut().set_succeed(2022).unwrap());
assert!(unique_ptr.as_mut().get_fail().is_err());
assert_eq!(
2022,
unique_ptr.as_mut().unwrap().set_succeed(2022).unwrap(),
);
assert!(unique_ptr.as_mut().unwrap().get_fail().is_err());
assert_eq!(2021, ffi::Shared { z: 0 }.c_method_on_shared());
}