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
59
60
61
62
63
64
65
66
67
68
69
//! Sets `jemalloc` as the `#[global_allocator]` on targets that support it.
//!
//! Just add `jemallocator-global` as a dependency:
//!
//! ```toml
//! # Cargo.toml
//! [dependencies]
//! jemallocator-global = "0.3.0"
//! ```
//!
//! and `jemalloc` will be used as the `#[global_allocator]` on targets that
//! support it.
//!
//! To unconditionally set `jemalloc` as the `#[global_allocator]` enable the
//! `force_global_jemalloc` cargo feature.

#[macro_use]
extern crate cfg_if;

cfg_if! {
    if #[cfg(any(
        feature = "force_global_jemalloc",
        target_os = "linux",
        target_os = "android",
        target_os = "macos",
        target_os = "ios",
        target_os = "freebsd",
        target_os = "openbsd",
        target_os = "netbsd"
    ))] {
        extern crate jemallocator;

        /// Sets `jemalloc` as the `#[global_allocator]`.
        #[global_allocator]
        pub static JEMALLOC: jemallocator::Jemalloc = jemallocator::Jemalloc;
    }
}

#[cfg(test)]
mod tests {
    // Test that jemallocator-global is enabled automatically in those targets in
    // which it should be enabled:

    macro_rules! check {
        () => {
            #[test]
            fn foo() {
                let _ = super::JEMALLOC;
            }
        };
        ($os_name:tt) => {
            #[cfg(target_os = $os_name)]
            check!();
        };
        ($($os_name:tt),*) => {
            $(check!($os_name);)*
        }
    }

    // If the `force_global_jemalloc` feature is enabled, then it
    // should always be set as the global allocator:
    #[cfg(feature = "force_global_jemalloc")]
    check!();

    // If the `force_global_jemalloc` feature is not enabled, then in the
    // following targets it should be automatically enabled anyways:
    #[cfg(not(feature = "force_global_jemalloc"))]
    check!("linux", "android", "macos", "ios", "freebsd", "netbsd", "openbsd");
}