]> git.lizzy.rs Git - rust.git/blob - src/tools/miri/tests/pass/global_allocator.rs
Auto merge of #104915 - weihanglo:update-cargo, r=ehuss
[rust.git] / src / tools / miri / tests / pass / global_allocator.rs
1 #![feature(allocator_api, slice_ptr_get)]
2
3 use std::alloc::{Allocator as _, Global, GlobalAlloc, Layout, System};
4
5 #[global_allocator]
6 static ALLOCATOR: Allocator = Allocator;
7
8 struct Allocator;
9
10 unsafe impl GlobalAlloc for Allocator {
11     unsafe fn alloc(&self, layout: Layout) -> *mut u8 {
12         // use specific size to avoid getting triggered by rt
13         if layout.size() == 123 {
14             println!("Allocated!")
15         }
16
17         System.alloc(layout)
18     }
19
20     unsafe fn dealloc(&self, ptr: *mut u8, layout: Layout) {
21         if layout.size() == 123 {
22             println!("Dellocated!")
23         }
24
25         System.dealloc(ptr, layout)
26     }
27 }
28
29 fn main() {
30     // Only okay because we explicitly set a global allocator that uses the system allocator!
31     let l = Layout::from_size_align(123, 1).unwrap();
32     let ptr = Global.allocate(l).unwrap().as_non_null_ptr(); // allocating with Global...
33     unsafe {
34         System.deallocate(ptr, l);
35     } // ... and deallocating with System.
36
37     let ptr = System.allocate(l).unwrap().as_non_null_ptr(); // allocating with System...
38     unsafe {
39         Global.deallocate(ptr, l);
40     } // ... and deallocating with Global.
41 }