]> git.lizzy.rs Git - rust.git/blob - src/test/run-pass/allocator/xcrate-use2.rs
be657f127bbc259e98c016ab54abf69854525200
[rust.git] / src / test / run-pass / allocator / xcrate-use2.rs
1 // run-pass
2
3 // aux-build:custom.rs
4 // aux-build:custom-as-global.rs
5 // aux-build:helper.rs
6 // no-prefer-dynamic
7
8 #![feature(allocator_api)]
9
10 extern crate custom;
11 extern crate custom_as_global;
12 extern crate helper;
13
14 use std::alloc::{alloc, dealloc, GlobalAlloc, System, Layout};
15 use std::sync::atomic::{Ordering, ATOMIC_USIZE_INIT};
16
17 static GLOBAL: custom::A = custom::A(ATOMIC_USIZE_INIT);
18
19 fn main() {
20     unsafe {
21         let n = custom_as_global::get();
22         let layout = Layout::from_size_align(4, 2).unwrap();
23
24         // Global allocator routes to the `custom_as_global` global
25         let ptr = alloc(layout.clone());
26         helper::work_with(&ptr);
27         assert_eq!(custom_as_global::get(), n + 1);
28         dealloc(ptr, layout.clone());
29         assert_eq!(custom_as_global::get(), n + 2);
30
31         // Usage of the system allocator avoids all globals
32         let ptr = System.alloc(layout.clone());
33         helper::work_with(&ptr);
34         assert_eq!(custom_as_global::get(), n + 2);
35         System.dealloc(ptr, layout.clone());
36         assert_eq!(custom_as_global::get(), n + 2);
37
38         // Usage of our personal allocator doesn't affect other instances
39         let ptr = GLOBAL.alloc(layout.clone());
40         helper::work_with(&ptr);
41         assert_eq!(custom_as_global::get(), n + 2);
42         assert_eq!(GLOBAL.0.load(Ordering::SeqCst), 1);
43         GLOBAL.dealloc(ptr, layout);
44         assert_eq!(custom_as_global::get(), n + 2);
45         assert_eq!(GLOBAL.0.load(Ordering::SeqCst), 2);
46     }
47 }
48