pub fn assert_no_alloc<T, F: FnOnce() -> T>(func: F) -> TExpand 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-26)
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 {
19 1
20 } else {
21 fib(n - 1) + fib(n - 2)
22 }
23 }
24
25 fib(5)
26 });
27 println!("\tSuccess, the 5th fibonacci number is {}", fib5);
28 println!();
29
30 assert_no_alloc(|| {
31 println!("Alloc is forbidden. Let's allocate some memory...");
32 let mut vec_cannot_push = Vec::new();
33 vec_cannot_push.push(42); // panics
34 });
35
36 println!("This will not be executed if the above allocation has aborted.");
37}