Skip to main content

jemallocator_global/
lib.rs

1//! Sets `jemalloc` as the `#[global_allocator]` on targets that support it.
2//!
3//! Just add `jemallocator-global` as a dependency:
4//!
5//! ```toml
6//! # Cargo.toml
7//! [dependencies]
8//! jemallocator-global = "0.3.0"
9//! ```
10//!
11//! and `jemalloc` will be used as the `#[global_allocator]` on targets that
12//! support it.
13//!
14//! To unconditionally set `jemalloc` as the `#[global_allocator]` enable the
15//! `force_global_jemalloc` cargo feature.
16
17#[macro_use]
18extern crate cfg_if;
19
20cfg_if! {
21    if #[cfg(any(
22        feature = "force_global_jemalloc",
23        target_os = "linux",
24        target_os = "android",
25        target_os = "macos",
26        target_os = "ios",
27        target_os = "freebsd",
28        target_os = "openbsd",
29        target_os = "netbsd"
30    ))] {
31        extern crate jemallocator;
32
33        /// Sets `jemalloc` as the `#[global_allocator]`.
34        #[global_allocator]
35        pub static JEMALLOC: jemallocator::Jemalloc = jemallocator::Jemalloc;
36    }
37}
38
39#[cfg(test)]
40mod tests {
41    // Test that jemallocator-global is enabled automatically in those targets in
42    // which it should be enabled:
43
44    macro_rules! check {
45        () => {
46            #[test]
47            fn foo() {
48                let _ = super::JEMALLOC;
49            }
50        };
51        ($os_name:tt) => {
52            #[cfg(target_os = $os_name)]
53            check!();
54        };
55        ($($os_name:tt),*) => {
56            $(check!($os_name);)*
57        }
58    }
59
60    // If the `force_global_jemalloc` feature is enabled, then it
61    // should always be set as the global allocator:
62    #[cfg(feature = "force_global_jemalloc")]
63    check!();
64
65    // If the `force_global_jemalloc` feature is not enabled, then in the
66    // following targets it should be automatically enabled anyways:
67    #[cfg(not(feature = "force_global_jemalloc"))]
68    check!("linux", "android", "macos", "ios", "freebsd", "netbsd", "openbsd");
69}