about summary refs log tree commit diff
path: root/src/test/ui/allocator/custom.rs
blob: c275db14b427cfa65c68f8a64ab1cebe1beafffa (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
// run-pass

// aux-build:helper.rs
// no-prefer-dynamic

#![feature(allocator_api)]

extern crate helper;

use std::alloc::{self, Global, AllocRef, System, Layout};
use std::sync::atomic::{AtomicUsize, Ordering};

static HITS: AtomicUsize = AtomicUsize::new(0);

struct A;

unsafe impl alloc::GlobalAlloc for A {
    unsafe fn alloc(&self, layout: Layout) -> *mut u8 {
        HITS.fetch_add(1, Ordering::SeqCst);
        System.alloc(layout)
    }

    unsafe fn dealloc(&self, ptr: *mut u8, layout: Layout) {
        HITS.fetch_add(1, Ordering::SeqCst);
        System.dealloc(ptr, layout)
    }
}

#[global_allocator]
static GLOBAL: A = A;

fn main() {
    println!("hello!");

    let n = HITS.load(Ordering::SeqCst);
    assert!(n > 0);
    unsafe {
        let layout = Layout::from_size_align(4, 2).unwrap();

        let (ptr, _) = Global.alloc(layout.clone()).unwrap();
        helper::work_with(&ptr);
        assert_eq!(HITS.load(Ordering::SeqCst), n + 1);
        Global.dealloc(ptr, layout.clone());
        assert_eq!(HITS.load(Ordering::SeqCst), n + 2);

        let s = String::with_capacity(10);
        helper::work_with(&s);
        assert_eq!(HITS.load(Ordering::SeqCst), n + 3);
        drop(s);
        assert_eq!(HITS.load(Ordering::SeqCst), n + 4);

        let (ptr, _) = System.alloc(layout.clone()).unwrap();
        assert_eq!(HITS.load(Ordering::SeqCst), n + 4);
        helper::work_with(&ptr);
        System.dealloc(ptr, layout);
        assert_eq!(HITS.load(Ordering::SeqCst), n + 4);
    }
}