Skip to content

Commit 80dd4ac

Browse files
committed
Add autoreleasepool functionality.
This replicates the behaviour of @autoreleasepool blocks in Objective-C and allows higher performance creation of autorelease pools.
1 parent baa5586 commit 80dd4ac

File tree

3 files changed

+43
-0
lines changed

3 files changed

+43
-0
lines changed

src/autorelease.rs

+38
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,38 @@
1+
use std::os::raw::c_void;
2+
use runtime::{objc_autoreleasePoolPush, objc_autoreleasePoolPop};
3+
4+
struct AutoReleaseHelper {
5+
context: *mut c_void
6+
}
7+
8+
impl AutoReleaseHelper {
9+
fn new() -> AutoReleaseHelper {
10+
unsafe { AutoReleaseHelper{ context: objc_autoreleasePoolPush()} }
11+
}
12+
}
13+
14+
impl Drop for AutoReleaseHelper {
15+
fn drop(&mut self) {
16+
unsafe { objc_autoreleasePoolPop(self.context) }
17+
}
18+
}
19+
20+
/**
21+
Execute `f` in the context of a new autorelease pool. The pool is drained
22+
after the execution of `f` completes. This corresponds to @autoreleasepool blocks
23+
in Objective-c and Swift.
24+
*/
25+
pub fn autoreleasepool<F: FnOnce()>(f: F) {
26+
let _context = AutoReleaseHelper::new();
27+
f();
28+
}
29+
30+
#[cfg(test)]
31+
mod tests {
32+
use super::autoreleasepool;
33+
34+
#[test]
35+
fn test_pool() {
36+
autoreleasepool(|| {});
37+
}
38+
}

src/lib.rs

+2
Original file line numberDiff line numberDiff line change
@@ -75,6 +75,8 @@ mod macros;
7575

7676
pub mod runtime;
7777
pub mod declare;
78+
mod autorelease;
79+
pub use autorelease::autoreleasepool;
7880
mod encode;
7981
#[cfg(feature = "exception")]
8082
mod exception;

src/runtime.rs

+3
Original file line numberDiff line numberDiff line change
@@ -109,6 +109,9 @@ extern {
109109
pub fn objc_allocateProtocol(name: *const c_char) -> *mut Protocol;
110110
pub fn objc_registerProtocol(proto: *mut Protocol);
111111

112+
pub fn objc_autoreleasePoolPush() -> *mut c_void;
113+
pub fn objc_autoreleasePoolPop(context: *mut c_void);
114+
112115
pub fn protocol_addMethodDescription(proto: *mut Protocol, name: Sel, types: *const c_char, isRequiredMethod: BOOL,
113116
isInstanceMethod: BOOL);
114117
pub fn protocol_addProtocol(proto: *mut Protocol, addition: *const Protocol);

0 commit comments

Comments
 (0)