4 // aux-build:custom-as-global.rs
8 #![feature(allocator_api)]
11 extern crate custom_as_global;
14 use std::alloc::{alloc, dealloc, GlobalAlloc, System, Layout};
15 use std::sync::atomic::{Ordering, ATOMIC_USIZE_INIT};
17 static GLOBAL: custom::A = custom::A(ATOMIC_USIZE_INIT);
21 let n = custom_as_global::get();
22 let layout = Layout::from_size_align(4, 2).unwrap();
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);
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);
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);