Skip to content

Commit

Permalink
Merge pull request #892 from adetaylor/add-as-unique-ptr
Browse files Browse the repository at this point in the history
Add UniquePtr::as_mut_ptr
  • Loading branch information
dtolnay authored Dec 25, 2024
2 parents cdf98a1 + e3ad7b3 commit e580f4c
Show file tree
Hide file tree
Showing 2 changed files with 22 additions and 0 deletions.
20 changes: 20 additions & 0 deletions src/unique_ptr.rs
Original file line number Diff line number Diff line change
Expand Up @@ -90,6 +90,26 @@ where
}
}

/// Returns a pointer to the object owned by this UniquePtr
/// if any, otherwise the null pointer.
pub fn as_ptr(&self) -> *const T {
match self.as_ref() {
Some(target) => target as *const T,
None => std::ptr::null(),
}
}

/// Returns a mutable pointer to the object owned by this UniquePtr
/// if any, otherwise the null pointer.
///
/// As with [std::unique_ptr\<T\>::get](https://en.cppreference.com/w/cpp/memory/unique_ptr/get),
/// this doesn't require that you hold a mutable reference to the `UniquePtr`.
/// This differs from Rust norms, so extra care should be taken in
/// the way the pointer is used.
pub fn as_mut_ptr(&self) -> *mut T {
self.as_ptr() as *mut T
}

/// Consumes the UniquePtr, releasing its ownership of the heap-allocated T.
///
/// Matches the behavior of [std::unique_ptr\<T\>::release](https://en.cppreference.com/w/cpp/memory/unique_ptr/release).
Expand Down
2 changes: 2 additions & 0 deletions tests/test.rs
Original file line number Diff line number Diff line change
Expand Up @@ -259,6 +259,8 @@ fn test_c_method_calls() {
assert_eq!(2021, unique_ptr.get());
assert_eq!(2021, unique_ptr.get2());
assert_eq!(2021, *unique_ptr.getRef());
assert_eq!(2021, unsafe { unique_ptr.as_mut_ptr().as_ref() }.unwrap().get());
assert_eq!(2021, unsafe { unique_ptr.as_ptr().as_ref() }.unwrap().get());
assert_eq!(2021, *unique_ptr.pin_mut().getMut());
assert_eq!(2022, unique_ptr.pin_mut().set_succeed(2022).unwrap());
assert!(unique_ptr.pin_mut().get_fail().is_err());
Expand Down

0 comments on commit e580f4c

Please sign in to comment.