assert_no_alloc

Function assert_no_alloc 

Source
pub fn assert_no_alloc<T, F: FnOnce() -> T>(func: F) -> T
Expand description

Calls the func closure, but forbids any (de)allocations.

If a call to the allocator is made, the program will abort with an error, print a warning (depending on the warn_debug feature flag. Or ignore the situation, when compiled in --release mode with the disable_release feature flag set (which is the default)).

Examples found in repository?
examples/main.rs (lines 14-23)
7fn main() {
8	println!("Alloc is allowed. Let's allocate some memory...");
9	let mut vec_can_push = Vec::new();
10	vec_can_push.push(42);
11
12	println!();
13
14	let fib5 = assert_no_alloc(|| {
15		println!("Alloc is forbidden. Let's calculate something without memory allocations...");
16
17		fn fib(n: u32) -> u32 {
18			if n<=1 { 1 }
19			else { fib(n-1) + fib(n-2) }
20		}
21
22		fib(5)
23	});
24	println!("\tSuccess, the 5th fibonacci number is {}", fib5);
25	println!();
26
27	assert_no_alloc(|| {
28		println!("Alloc is forbidden. Let's allocate some memory...");
29		let mut vec_cannot_push = Vec::new();
30		vec_cannot_push.push(42); // panics
31	});
32
33	println!("This will not be executed if the above allocation has aborted.");
34}