Skip to content

Commit

Permalink
Showing 4 changed files with 31 additions and 8 deletions.
1 change: 1 addition & 0 deletions crates/objc2/CHANGELOG.md
Original file line number Diff line number Diff line change
@@ -17,6 +17,7 @@ The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/).
- `AnyClass::instance_variables`.
- `AnyProtocol::protocols`.
- `AnyProtocol::adopted_protocols`.
* Added `Id::into_raw` as the oppositve of `Id::from_raw`.

### Changed
* Moved `ClassBuilder` and `ProtocolBuilder` from the `declare` module to the
2 changes: 1 addition & 1 deletion crates/objc2/src/__macro_helpers/declare_class.rs
Original file line number Diff line number Diff line change
@@ -108,7 +108,7 @@ pub trait MaybeOptionId: MaybeUnwrap {
impl<T: Message> MaybeOptionId for Id<T> {
#[inline]
fn consumed_return(self) -> IdReturnValue {
let ptr: *mut T = Id::consume_as_ptr(self);
let ptr: *mut T = Id::into_raw(self);
IdReturnValue(ptr.cast())
}

2 changes: 1 addition & 1 deletion crates/objc2/src/__macro_helpers/msg_send.rs
Original file line number Diff line number Diff line change
@@ -181,7 +181,7 @@ impl<T: ?Sized + Message> MsgSend for ManuallyDrop<Id<T>> {

#[inline]
fn into_raw_receiver(self) -> *mut AnyObject {
Id::consume_as_ptr(ManuallyDrop::into_inner(self)).cast()
Id::into_raw(ManuallyDrop::into_inner(self)).cast()
}
}

34 changes: 28 additions & 6 deletions crates/objc2/src/rc/id.rs
Original file line number Diff line number Diff line change
@@ -227,6 +227,33 @@ impl<T: ?Sized + Message> Id<T> {
unsafe { Self::from_raw(ptr) }
}

/// Consumes the `Id`, returning a raw pointer with +1 retain count.
///
/// After calling this function, the caller is responsible for the memory
/// previously managed by the `Id`.
///
/// This is effectively the opposite of [`Id::from_raw`], see that for
/// more details on when this function is useful.
///
///
/// # Examples
///
/// Converting an `Id` to a pointer and back.
///
/// ```
/// use objc2::rc::Id;
/// use objc2::runtime::NSObject;
///
/// let obj = NSObject::new();
/// let ptr = Id::into_raw(obj);
/// // SAFETY: The pointer is valid, and has +1 retain count from above.
/// let obj = unsafe { Id::from_raw(ptr) }.unwrap();
/// ```
#[inline]
pub fn into_raw(this: Self) -> *mut T {
ManuallyDrop::new(this).ptr.as_ptr()
}

/// Returns a raw pointer to the object.
///
/// The pointer is valid for at least as long as the `Id` is held.
@@ -257,17 +284,12 @@ impl<T: ?Sized + Message> Id<T> {
this.ptr.as_ptr()
}

#[inline]
pub(crate) fn consume_as_ptr(this: Self) -> *mut T {
ManuallyDrop::new(this).ptr.as_ptr()
}

#[inline]
pub(crate) fn consume_as_ptr_option(this: Option<Self>) -> *mut T
where
T: Sized,
{
this.map(|this| Id::consume_as_ptr(this))
this.map(|this| Id::into_raw(this))
.unwrap_or_else(ptr::null_mut)
}
}

0 comments on commit 1b8a9ee

Please sign in to comment.