]> git.proxmox.com Git - rustc.git/blob - src/test/ui/allocator/custom.rs
New upstream version 1.50.0+dfsg1
[rustc.git] / src / test / ui / allocator / custom.rs
1 // run-pass
2
3 // aux-build:helper.rs
4 // no-prefer-dynamic
5
6 #![feature(allocator_api)]
7 #![feature(slice_ptr_get)]
8
9 extern crate helper;
10
11 use std::alloc::{self, Allocator, Global, Layout, System};
12 use std::sync::atomic::{AtomicUsize, Ordering};
13
14 static HITS: AtomicUsize = AtomicUsize::new(0);
15
16 struct A;
17
18 unsafe impl alloc::GlobalAlloc for A {
19 unsafe fn alloc(&self, layout: Layout) -> *mut u8 {
20 HITS.fetch_add(1, Ordering::SeqCst);
21 alloc::GlobalAlloc::alloc(&System, layout)
22 }
23
24 unsafe fn dealloc(&self, ptr: *mut u8, layout: Layout) {
25 HITS.fetch_add(1, Ordering::SeqCst);
26 alloc::GlobalAlloc::dealloc(&System, ptr, layout)
27 }
28 }
29
30 #[global_allocator]
31 static GLOBAL: A = A;
32
33 fn main() {
34 println!("hello!");
35
36 let n = HITS.load(Ordering::SeqCst);
37 assert!(n > 0);
38 unsafe {
39 let layout = Layout::from_size_align(4, 2).unwrap();
40
41 let memory = Global.allocate(layout.clone()).unwrap();
42 helper::work_with(&memory);
43 assert_eq!(HITS.load(Ordering::SeqCst), n + 1);
44 Global.deallocate(memory.as_non_null_ptr(), layout);
45 assert_eq!(HITS.load(Ordering::SeqCst), n + 2);
46
47 let s = String::with_capacity(10);
48 helper::work_with(&s);
49 assert_eq!(HITS.load(Ordering::SeqCst), n + 3);
50 drop(s);
51 assert_eq!(HITS.load(Ordering::SeqCst), n + 4);
52
53 let memory = System.allocate(layout.clone()).unwrap();
54 helper::work_with(&memory);
55 assert_eq!(HITS.load(Ordering::SeqCst), n + 4);
56 System.deallocate(memory.as_non_null_ptr(), layout);
57 assert_eq!(HITS.load(Ordering::SeqCst), n + 4);
58 }
59 }