Skip to content

Commit

Permalink
Add RcBlock::as_ptr and RcBlock::into_raw
Browse files Browse the repository at this point in the history
Fixes #655
  • Loading branch information
madsmtm committed Sep 23, 2024
1 parent e9e09a6 commit 45844f8
Show file tree
Hide file tree
Showing 2 changed files with 42 additions and 0 deletions.
2 changes: 2 additions & 0 deletions crates/block2/CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,8 @@ The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/).
blocks with an encoding specified by `ManualBlockEncoding`.

This is useful for certain APIs that require blocks to have an encoding.
* Added `RcBlock::as_ptr`.
* Added `RcBlock::into_raw`.

### Fixed
* **BREAKING**: Converted function signatures into using `extern "C-unwind"`.
Expand Down
40 changes: 40 additions & 0 deletions crates/block2/src/rc_block.rs
Original file line number Diff line number Diff line change
Expand Up @@ -37,6 +37,46 @@ pub struct RcBlock<F: ?Sized> {
}

impl<F: ?Sized> RcBlock<F> {
/// A raw pointer to the underlying block.
///
/// The pointer is valid for at least as long as the `RcBlock` is alive.
///
/// This is an associated method, and must be called as
/// `RcBlock::as_ptr(&block)`.
#[inline]
pub fn as_ptr(this: &Self) -> *mut Block<F> {
this.ptr.as_ptr()
}

/// Consumes the `RcBlock`, passing ownership of the retain count to the
/// caller.
///
/// After calling this function, the caller is responsible for releasing
/// the memory with [`ffi::_Block_release`] or similar.
///
/// This is an associated method, and must be called as
/// `RcBlock::into_raw(block)`.
///
///
/// # Examples
///
/// Converting a `RcBlock` to a pointer and back.
///
/// ```
/// use block2::RcBlock;
///
/// let add2 = RcBlock::new(|x: i32| -> i32 {
/// x + 2
/// });
/// let ptr = RcBlock::into_raw(add2);
/// // SAFETY: The pointer is valid, and ownership from above.
/// let add2 = unsafe { RcBlock::from_raw(ptr) }.unwrap();
/// ```
pub fn into_raw(this: Self) -> *mut Block<F> {
let this = ManuallyDrop::new(this);
this.ptr.as_ptr()
}

/// Construct an `RcBlock` from the given block pointer by taking
/// ownership.
///
Expand Down

0 comments on commit 45844f8

Please sign in to comment.