Skip to content

Commit 7e4f432

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 7e4f432

File tree

3 files changed

+44
-0
lines changed

3 files changed

+44
-0
lines changed

src/autorelease.rs

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

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)