Debian Codegraph @

third_party/rust/block/src/lib.rs

raw
1 /*!
2 A Rust interface for Objective-C blocks.
3
4 For more information on the specifics of the block implementation, see
5 Clang's documentation: http://clang.llvm.org/docs/Block-ABI-Apple.html
6
7 # Invoking blocks
8
9 The `Block` struct is used for invoking blocks from Objective-C. For example,
10 consider this Objective-C function:
11
12 ``` objc
13 int32_t sum(int32_t (^block)(int32_t, int32_t)) {
14 return block(5, 8);
15 }
16 ```
17
18 We could write it in Rust as the following:
19
20 ```
21 # use block::Block;
22 unsafe fn sum(block: &Block<(i32, i32), i32>) -> i32 {
23 block.call((5, 8))
24 }
25 ```
26
27 Note the extra parentheses in the `call` method, since the arguments must be
28 passed as a tuple.
29
30 # Creating blocks
31
32 Creating a block to pass to Objective-C can be done with the `ConcreteBlock`
33 struct. For example, to create a block that adds two `i32`s, we could write:
34
35 ```
36 # use block::ConcreteBlock;
37 let block = ConcreteBlock::new(|a: i32, b: i32| a + b);
38 let block = block.copy();
39 assert!(unsafe { block.call((5, 8)) } == 13);
40 ```
41
42 It is important to copy your block to the heap (with the `copy` method) before
43 passing it to Objective-C; this is because our `ConcreteBlock` is only meant
44 to be copied once, and we can enforce this in Rust, but if Objective-C code
45 were to copy it twice we could have a double free.
46 */
47
48 #[cfg(test)]
49 mod test_utils;
50
51 use std::marker::PhantomData;
52 use std::mem;
53 use std::ops::{Deref, DerefMut};
54 use std::os::raw::{c_int, c_ulong, c_void};
55 use std::ptr;
56
57 enum Class { }
58
59 #[cfg_attr(any(target_os = "macos", target_os = "ios"),
60 link(name = "System", kind = "dylib"))]
61 #[cfg_attr(not(any(target_os = "macos", target_os = "ios")),
62 link(name = "BlocksRuntime", kind = "dylib"))]
63 extern {
64 static _NSConcreteStackBlock: Class;
65
66 fn _Block_copy(block: *const c_void) -> *mut c_void;
67 fn _Block_release(block: *const c_void);
68 }
69
70 /// Types that may be used as the arguments to an Objective-C block.
71 pub trait BlockArguments: Sized {
72 /// Calls the given `Block` with self as the arguments.
73 ///
74 /// Unsafe because `block` must point to a valid `Block` and this invokes
75 /// foreign code whose safety the compiler cannot verify.
76 unsafe fn call_block<R>(self, block: *mut Block<Self, R>) -> R;
77 }
78
79 macro_rules! block_args_impl {
80 ($($a:ident : $t:ident),*) => (
81 impl<$($t),*> BlockArguments for ($($t,)*) {
82 unsafe fn call_block<R>(self, block: *mut Block<Self, R>) -> R {
83 let invoke: unsafe extern fn(*mut Block<Self, R> $(, $t)*) -> R = {
84 let base = block as *mut BlockBase<Self, R>;
85 mem::transmute((*base).invoke)
86 };
87 let ($($a,)*) = self;
88 invoke(block $(, $a)*)
89 }
90 }
91 );
92 }
93
94 block_args_impl!();
95 block_args_impl!(a: A);
96 block_args_impl!(a: A, b: B);
97 block_args_impl!(a: A, b: B, c: C);
98 block_args_impl!(a: A, b: B, c: C, d: D);
99 block_args_impl!(a: A, b: B, c: C, d: D, e: E);
100 block_args_impl!(a: A, b: B, c: C, d: D, e: E, f: F);
101 block_args_impl!(a: A, b: B, c: C, d: D, e: E, f: F, g: G);
102 block_args_impl!(a: A, b: B, c: C, d: D, e: E, f: F, g: G, h: H);
103 block_args_impl!(a: A, b: B, c: C, d: D, e: E, f: F, g: G, h: H, i: I);
104 block_args_impl!(a: A, b: B, c: C, d: D, e: E, f: F, g: G, h: H, i: I, j: J);
105 block_args_impl!(a: A, b: B, c: C, d: D, e: E, f: F, g: G, h: H, i: I, j: J, k: K);
106 block_args_impl!(a: A, b: B, c: C, d: D, e: E, f: F, g: G, h: H, i: I, j: J, k: K, l: L);
107
108 #[repr(C)]
109 struct BlockBase<A, R> {
110 isa: *const Class,
111 flags: c_int,
112 _reserved: c_int,
113 invoke: unsafe extern fn(*mut Block<A, R>, ...) -> R,
114 }
115
116 /// An Objective-C block that takes arguments of `A` when called and
117 /// returns a value of `R`.
118 #[repr(C)]
119 pub struct Block<A, R> {
120 _base: PhantomData<BlockBase<A, R>>,
121 }
122
123 impl<A: BlockArguments, R> Block<A, R> where A: BlockArguments {
124 /// Call self with the given arguments.
125 ///
126 /// Unsafe because this invokes foreign code that the caller must verify
127 /// doesn't violate any of Rust's safety rules. For example, if this block
128 /// is shared with multiple references, the caller must ensure that calling
129 /// it will not cause a data race.
130 pub unsafe fn call(&self, args: A) -> R {
131 args.call_block(self as *const _ as *mut _)
132 }
133 }
134
135 /// A reference-counted Objective-C block.
136 pub struct RcBlock<A, R> {
137 ptr: *mut Block<A, R>,
138 }
139
140 impl<A, R> RcBlock<A, R> {
141 /// Construct an `RcBlock` for the given block without copying it.
142 /// The caller must ensure the block has a +1 reference count.
143 ///
144 /// Unsafe because `ptr` must point to a valid `Block` and must have a +1
145 /// reference count or it will be overreleased when the `RcBlock` is
146 /// dropped.
147 pub unsafe fn new(ptr: *mut Block<A, R>) -> Self {
148 RcBlock { ptr: ptr }
149 }
150
151 /// Constructs an `RcBlock` by copying the given block.
152 ///
153 /// Unsafe because `ptr` must point to a valid `Block`.
154 pub unsafe fn copy(ptr: *mut Block<A, R>) -> Self {
155 let ptr = _Block_copy(ptr as *const c_void) as *mut Block<A, R>;
156 RcBlock { ptr: ptr }
157 }
158 }
159
160 impl<A, R> Clone for RcBlock<A, R> {
161 fn clone(&self) -> RcBlock<A, R> {
162 unsafe {
163 RcBlock::copy(self.ptr)
164 }
165 }
166 }
167
168 impl<A, R> Deref for RcBlock<A, R> {
169 type Target = Block<A, R>;
170
171 fn deref(&self) -> &Block<A, R> {
172 unsafe { &*self.ptr }
173 }
174 }
175
176 impl<A, R> Drop for RcBlock<A, R> {
177 fn drop(&mut self) {
178 unsafe {
179 _Block_release(self.ptr as *const c_void);
180 }
181 }
182 }
183
184 /// Types that may be converted into a `ConcreteBlock`.
185 pub trait IntoConcreteBlock<A>: Sized where A: BlockArguments {
186 /// The return type of the resulting `ConcreteBlock`.
187 type Ret;
188
189 /// Consumes self to create a `ConcreteBlock`.
190 fn into_concrete_block(self) -> ConcreteBlock<A, Self::Ret, Self>;
191 }
192
193 macro_rules! concrete_block_impl {
194 ($f:ident) => (
195 concrete_block_impl!($f,);
196 );
197 ($f:ident, $($a:ident : $t:ident),*) => (
198 impl<$($t,)* R, X> IntoConcreteBlock<($($t,)*)> for X
199 where X: Fn($($t,)*) -> R {
200 type Ret = R;
201
202 fn into_concrete_block(self) -> ConcreteBlock<($($t,)*), R, X> {
203 unsafe extern fn $f<$($t,)* R, X>(
204 block_ptr: *mut ConcreteBlock<($($t,)*), R, X>
205 $(, $a: $t)*) -> R
206 where X: Fn($($t,)*) -> R {
207 let block = &*block_ptr;
208 (block.closure)($($a),*)
209 }
210
211 let f: unsafe extern fn(*mut ConcreteBlock<($($t,)*), R, X> $(, $a: $t)*) -> R = $f;
212 unsafe {
213 ConcreteBlock::with_invoke(mem::transmute(f), self)
214 }
215 }
216 }
217 );
218 }
219
220 concrete_block_impl!(concrete_block_invoke_args0);
221 concrete_block_impl!(concrete_block_invoke_args1, a: A);
222 concrete_block_impl!(concrete_block_invoke_args2, a: A, b: B);
223 concrete_block_impl!(concrete_block_invoke_args3, a: A, b: B, c: C);
224 concrete_block_impl!(concrete_block_invoke_args4, a: A, b: B, c: C, d: D);
225 concrete_block_impl!(concrete_block_invoke_args5, a: A, b: B, c: C, d: D, e: E);
226 concrete_block_impl!(concrete_block_invoke_args6, a: A, b: B, c: C, d: D, e: E, f: F);
227 concrete_block_impl!(concrete_block_invoke_args7, a: A, b: B, c: C, d: D, e: E, f: F, g: G);
228 concrete_block_impl!(concrete_block_invoke_args8, a: A, b: B, c: C, d: D, e: E, f: F, g: G, h: H);
229 concrete_block_impl!(concrete_block_invoke_args9, a: A, b: B, c: C, d: D, e: E, f: F, g: G, h: H, i: I);
230 concrete_block_impl!(concrete_block_invoke_args10, a: A, b: B, c: C, d: D, e: E, f: F, g: G, h: H, i: I, j: J);
231 concrete_block_impl!(concrete_block_invoke_args11, a: A, b: B, c: C, d: D, e: E, f: F, g: G, h: H, i: I, j: J, k: K);
232 concrete_block_impl!(concrete_block_invoke_args12, a: A, b: B, c: C, d: D, e: E, f: F, g: G, h: H, i: I, j: J, k: K, l: L);
233
234 /// An Objective-C block whose size is known at compile time and may be
235 /// constructed on the stack.
236 #[repr(C)]
237 pub struct ConcreteBlock<A, R, F> {
238 base: BlockBase<A, R>,
239 descriptor: Box<BlockDescriptor<ConcreteBlock<A, R, F>>>,
240 closure: F,
241 }
242
243 impl<A, R, F> ConcreteBlock<A, R, F>
244 where A: BlockArguments, F: IntoConcreteBlock<A, Ret=R> {
245 /// Constructs a `ConcreteBlock` with the given closure.
246 /// When the block is called, it will return the value that results from
247 /// calling the closure.
248 pub fn new(closure: F) -> Self {
249 closure.into_concrete_block()
250 }
251 }
252
253 impl<A, R, F> ConcreteBlock<A, R, F> {
254 /// Constructs a `ConcreteBlock` with the given invoke function and closure.
255 /// Unsafe because the caller must ensure the invoke function takes the
256 /// correct arguments.
257 unsafe fn with_invoke(invoke: unsafe extern fn(*mut Self, ...) -> R,
258 closure: F) -> Self {
259 ConcreteBlock {
260 base: BlockBase {
261 isa: &_NSConcreteStackBlock,
262 // 1 << 25 = BLOCK_HAS_COPY_DISPOSE
263 flags: 1 << 25,
264 _reserved: 0,
265 invoke: mem::transmute(invoke),
266 },
267 descriptor: Box::new(BlockDescriptor::new()),
268 closure: closure,
269 }
270 }
271 }
272
273 impl<A, R, F> ConcreteBlock<A, R, F> where F: 'static {
274 /// Copy self onto the heap as an `RcBlock`.
275 pub fn copy(self) -> RcBlock<A, R> {
276 unsafe {
277 let mut block = self;
278 let copied = RcBlock::copy(&mut *block);
279 // At this point, our copy helper has been run so the block will
280 // be moved to the heap and we can forget the original block
281 // because the heap block will drop in our dispose helper.
282 mem::forget(block);
283 copied
284 }
285 }
286 }
287
288 impl<A, R, F> Clone for ConcreteBlock<A, R, F> where F: Clone {
289 fn clone(&self) -> Self {
290 unsafe {
291 ConcreteBlock::with_invoke(mem::transmute(self.base.invoke),
292 self.closure.clone())
293 }
294 }
295 }
296
297 impl<A, R, F> Deref for ConcreteBlock<A, R, F> {
298 type Target = Block<A, R>;
299
300 fn deref(&self) -> &Block<A, R> {
301 unsafe { &*(&self.base as *const _ as *const Block<A, R>) }
302 }
303 }
304
305 impl<A, R, F> DerefMut for ConcreteBlock<A, R, F> {
306 fn deref_mut(&mut self) -> &mut Block<A, R> {
307 unsafe { &mut *(&mut self.base as *mut _ as *mut Block<A, R>) }
308 }
309 }
310
311 unsafe extern fn block_context_dispose<B>(block: &mut B) {
312 // Read the block onto the stack and let it drop
313 ptr::read(block);
314 }
315
316 unsafe extern fn block_context_copy<B>(_dst: &mut B, _src: &B) {
317 // The runtime memmoves the src block into the dst block, nothing to do
318 }
319
320 #[repr(C)]
321 struct BlockDescriptor<B> {
322 _reserved: c_ulong,
323 block_size: c_ulong,
324 copy_helper: unsafe extern fn(&mut B, &B),
325 dispose_helper: unsafe extern fn(&mut B),
326 }
327
328 impl<B> BlockDescriptor<B> {
329 fn new() -> BlockDescriptor<B> {
330 BlockDescriptor {
331 _reserved: 0,
332 block_size: mem::size_of::<B>() as c_ulong,
333 copy_helper: block_context_copy::<B>,
334 dispose_helper: block_context_dispose::<B>,
335 }
336 }
337 }
338
339 #[cfg(test)]
340 mod tests {
341 use test_utils::*;
342 use super::{ConcreteBlock, RcBlock};
343
344 #[test]
345 fn test_call_block() {
346 let block = get_int_block_with(13);
347 unsafe {
348 assert!(block.call(()) == 13);
349 }
350 }
351
352 #[test]
353 fn test_call_block_args() {
354 let block = get_add_block_with(13);
355 unsafe {
356 assert!(block.call((2,)) == 15);
357 }
358 }
359
360 #[test]
361 fn test_create_block() {
362 let block = ConcreteBlock::new(|| 13);
363 let result = invoke_int_block(&block);
364 assert!(result == 13);
365 }
366
367 #[test]
368 fn test_create_block_args() {
369 let block = ConcreteBlock::new(|a: i32| a + 5);
370 let result = invoke_add_block(&block, 6);
371 assert!(result == 11);
372 }
373
374 #[test]
375 fn test_concrete_block_copy() {
376 let s = "Hello!".to_string();
377 let expected_len = s.len() as i32;
378 let block = ConcreteBlock::new(move || s.len() as i32);
379 assert!(invoke_int_block(&block) == expected_len);
380
381 let copied = block.copy();
382 assert!(invoke_int_block(&copied) == expected_len);
383 }
384
385 #[test]
386 fn test_concrete_block_stack_copy() {
387 fn make_block() -> RcBlock<(), i32> {
388 let x = 7;
389 let block = ConcreteBlock::new(move || x);
390 block.copy()
391 }
392
393 let block = make_block();
394 assert!(invoke_int_block(&block) == 7);
395 }
396 }