1use customizable_buddy::{AvlBuddy, BuddyAllocator, BuddyError, UsizeBuddy};
2use std::{
3 alloc::Layout,
4 ptr::{NonNull, addr_of, addr_of_mut, null_mut},
5 time::Instant,
6};
7
8type Allocator<const N: usize> = BuddyAllocator<N, UsizeBuddy, AvlBuddy>;
9
10#[repr(C, align(4096))]
11struct Page([u8; 4096]);
12
13impl Page {
14 const ZERO: Self = Self([0; 4096]);
15}
16
17static mut MEMORY: [Page; 65536] = [Page::ZERO; 65536];
19
20fn main() -> Result<(), BuddyError> {
21 let mut allocator = Allocator::<12>::new();
23 let ptr = NonNull::new(addr_of_mut!(MEMORY).cast::<u8>()).unwrap();
25 let len = size_of_val(unsafe { &*addr_of!(MEMORY) });
26 allocator.init(12, ptr);
28 println!(
29 "MEMORY: {:#x}..{:#x}",
30 ptr.as_ptr() as usize,
31 ptr.as_ptr() as usize + len
32 );
33 let t = Instant::now();
35 unsafe { allocator.transfer(ptr, len) };
37 println!("transfer {:?}", t.elapsed());
38
39 assert_eq!(len, allocator.capacity());
40 assert_eq!(len, allocator.free());
41
42 println!(
43 "
44BEFORE
45{allocator:#x?}"
46 );
47
48 let mut blocks = [null_mut::<Page>(); 65536];
50 let layout = Layout::new::<Page>();
51 let t = Instant::now();
52 for block in blocks.iter_mut() {
53 let (ptr, size) = allocator.allocate_type::<Page>()?;
55 debug_assert_eq!(layout.size(), size);
56 *block = ptr.as_ptr();
57 }
58 let ta = t.elapsed();
59
60 println!(
62 "
63EMPTY
64{allocator:#x?}"
65 );
66
67 assert_eq!(len, allocator.capacity());
69 assert_eq!(len - blocks.len() * layout.size(), allocator.free());
70
71 let t = Instant::now();
72 for block in blocks.iter_mut() {
73 allocator.deallocate(NonNull::new(*block).unwrap(), layout.size());
75 *block = null_mut();
76 }
78 let td = t.elapsed();
79
80 assert_eq!(len, allocator.capacity());
81 assert_eq!(len, allocator.free());
82
83 println!(
84 "
85AFTER
86{allocator:#x?}"
87 );
88
89 println!(
90 "allocate {:?} ({} times)",
91 ta / blocks.len() as u32,
92 blocks.len()
93 );
94 println!(
95 "deallocate {:?} ({} times)",
96 td / blocks.len() as u32,
97 blocks.len()
98 );
99
100 Ok(())
101}