allocator_api2_tests/
lib.rs

1#![cfg_attr(feature = "nightly", feature(allocator_api))]
2#![cfg(not(no_global_oom_handling))]
3
4use std::alloc::Layout;
5
6use allocator_api2::{alloc::Allocator, boxed::Box, vec::Vec};
7
8#[macro_export]
9macro_rules! make_test {
10    ($($test_name:ident($($arg:expr),* $(,)?)),* $(,)?) => {
11        $(
12            #[test]
13            fn $test_name() {
14                $crate::$test_name($($arg),*);
15            }
16        )*
17    };
18}
19
20pub fn test_allocate_layout<A: Allocator>(alloc: A, layout: Layout) {
21    if let Ok(ptr) = alloc.allocate(layout) {
22        unsafe { alloc.deallocate(ptr.cast(), layout) }
23    }
24}
25
26pub fn test_sizes<A: Allocator>(alloc: A) {
27    test_allocate_layout(&alloc, Layout::new::<u8>());
28    test_allocate_layout(&alloc, Layout::new::<u16>());
29    test_allocate_layout(&alloc, Layout::new::<u32>());
30    test_allocate_layout(&alloc, Layout::new::<u64>());
31    test_allocate_layout(&alloc, Layout::new::<[u8; 17]>());
32    test_allocate_layout(&alloc, Layout::new::<[u8; 67]>());
33    test_allocate_layout(&alloc, Layout::new::<[u8; 129]>());
34    test_allocate_layout(&alloc, Layout::new::<[u8; 654]>());
35    test_allocate_layout(&alloc, Layout::new::<[u8; 2345]>());
36    test_allocate_layout(&alloc, Layout::new::<[u8; 32578]>());
37    test_allocate_layout(&alloc, Layout::new::<[u8; 8603461]>());
38}
39
40pub fn test_vec<A: Allocator>(alloc: A) {
41    let mut vec = Vec::<u8, A>::new_in(alloc);
42
43    vec.push(1);
44    vec.push(2);
45    vec.shrink_to_fit();
46    vec.push(3);
47
48    vec.resize(10, 0xba);
49    vec.shrink_to_fit();
50
51    vec.resize(12467, 0xfe);
52    drop(vec);
53}
54
55pub fn test_many_boxes<A: Allocator + Copy>(alloc: A) {
56    let mut boxes = Vec::new_in(alloc);
57
58    for i in 0..15 {
59        boxes.push(Box::new_in(i, alloc));
60    }
61
62    for i in 0..15 {
63        assert_eq!(*boxes[i], i);
64    }
65
66    drop(boxes);
67}