Skip to main content

try_reserve/
try_reserve.rs

1//! Demonstrates testing a fallible allocation path with `alloc-chaos`.
2//!
3//! Run it with:
4//!
5//! ```sh
6//! cargo run --example try_reserve
7//! ```
8
9#[global_allocator]
10static GLOBAL: alloc_chaos::ChaosAllocator = alloc_chaos::ChaosAllocator::system();
11
12#[derive(Debug, Clone, Copy, PartialEq, Eq)]
13struct OutOfMemory;
14
15fn build_payload(size: usize) -> Result<Vec<u8>, OutOfMemory> {
16    let mut bytes = Vec::new();
17    bytes.try_reserve_exact(size).map_err(|_| OutOfMemory)?;
18
19    // This should not allocate after a successful `try_reserve_exact` call.
20    bytes.resize(size, 0);
21
22    Ok(bytes)
23}
24
25fn main() {
26    let report = alloc_chaos::check(|| {
27        if let Ok(bytes) = build_payload(4096) {
28            assert_eq!(bytes.len(), 4096)
29        }
30    });
31
32    println!("{report}");
33    report.assert_success();
34}