Skip to content

Commit

Permalink
Add autoreleasepool functionality.
Browse files Browse the repository at this point in the history
This replicates the behaviour of @autoreleasepool blocks in
Objective-C and allows higher performance creation of autorelease pools.
  • Loading branch information
jrmuizel committed Jul 12, 2018
1 parent baa5586 commit 7e4f432
Show file tree
Hide file tree
Showing 3 changed files with 44 additions and 0 deletions.
39 changes: 39 additions & 0 deletions src/autorelease.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,39 @@
use std::os::raw::c_void;
use runtime::{objc_autoreleasePoolPush, objc_autoreleasePoolPop};

// we use a struct to ensure that objc_autoreleasePoolPop during unwinding.
struct AutoReleaseHelper {
context: *mut c_void,
}

impl AutoReleaseHelper {
unsafe fn new() -> Self {
AutoReleaseHelper { context: objc_autoreleasePoolPush() }
}
}

impl Drop for AutoReleaseHelper {
fn drop(&mut self) {
unsafe { objc_autoreleasePoolPop(self.context) }
}
}

/**
Execute `f` in the context of a new autorelease pool. The pool is drained
after the execution of `f` completes. This corresponds to @autoreleasepool blocks
in Objective-c and Swift.
*/
pub fn autoreleasepool<F: FnOnce()>(f: F) {
let _context = unsafe { AutoReleaseHelper::new() };
f();
}

#[cfg(test)]
mod tests {
use super::autoreleasepool;

#[test]
fn test_pool() {
autoreleasepool(|| {});
}
}
2 changes: 2 additions & 0 deletions src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -75,6 +75,8 @@ mod macros;

pub mod runtime;
pub mod declare;
mod autorelease;
pub use autorelease::autoreleasepool;
mod encode;
#[cfg(feature = "exception")]
mod exception;
Expand Down
3 changes: 3 additions & 0 deletions src/runtime.rs
Original file line number Diff line number Diff line change
Expand Up @@ -109,6 +109,9 @@ extern {
pub fn objc_allocateProtocol(name: *const c_char) -> *mut Protocol;
pub fn objc_registerProtocol(proto: *mut Protocol);

pub fn objc_autoreleasePoolPush() -> *mut c_void;
pub fn objc_autoreleasePoolPop(context: *mut c_void);

pub fn protocol_addMethodDescription(proto: *mut Protocol, name: Sel, types: *const c_char, isRequiredMethod: BOOL,
isInstanceMethod: BOOL);
pub fn protocol_addProtocol(proto: *mut Protocol, addition: *const Protocol);
Expand Down

0 comments on commit 7e4f432

Please sign in to comment.