|
9 | 9 | // except according to those terms.
|
10 | 10 |
|
11 | 11 | //! Memory allocation APIs
|
| 12 | +//! |
| 13 | +//! In a given program, the standard library has one “global” memory allocator |
| 14 | +//! that is used for example by `Box<T>` and `Vec<T>`. |
| 15 | +//! |
| 16 | +//! Currently the default global allocator is unspecified. |
| 17 | +//! The compiler may link to a version of [jemalloc] on some platforms, |
| 18 | +//! but this is not guaranteed. |
| 19 | +//! Libraries, however, like `cdylib`s and `staticlib`s are guaranteed |
| 20 | +//! to use the [`System`] by default. |
| 21 | +//! |
| 22 | +//! [jemalloc]: https://github.com/jemalloc/jemalloc |
| 23 | +//! [`System`]: struct.System.html |
| 24 | +//! |
| 25 | +//! # The `#[global_allocator]` attribute |
| 26 | +//! |
| 27 | +//! This attribute allows configuring the choice of global allocator. |
| 28 | +//! You can use this to implement a completely custom global allocator |
| 29 | +//! to route all default allocation requests to a custom object. |
| 30 | +//! |
| 31 | +//! ```rust |
| 32 | +//! use std::alloc::{GlobalAlloc, System, Layout}; |
| 33 | +//! |
| 34 | +//! struct MyAllocator; |
| 35 | +//! |
| 36 | +//! unsafe impl GlobalAlloc for MyAllocator { |
| 37 | +//! unsafe fn alloc(&self, layout: Layout) -> *mut u8 { |
| 38 | +//! System.alloc(layout) |
| 39 | +//! } |
| 40 | +//! |
| 41 | +//! unsafe fn dealloc(&self, ptr: *mut u8, layout: Layout) { |
| 42 | +//! System.dealloc(ptr, layout) |
| 43 | +//! } |
| 44 | +//! } |
| 45 | +//! |
| 46 | +//! #[global_allocator] |
| 47 | +//! static GLOBAL: MyAllocator = MyAllocator; |
| 48 | +//! |
| 49 | +//! fn main() { |
| 50 | +//! // This `Vec` will allocate memory through `GLOBAL` above |
| 51 | +//! let mut v = Vec::new(); |
| 52 | +//! v.push(1); |
| 53 | +//! } |
| 54 | +//! ``` |
| 55 | +//! |
| 56 | +//! The attribute is used on a `static` item whose type implements the |
| 57 | +//! [`GlobalAlloc`] trait. This type can be provided by an external library: |
| 58 | +//! |
| 59 | +//! [`GlobalAlloc`]: ../../core/alloc/trait.GlobalAlloc.html |
| 60 | +//! |
| 61 | +//! ```rust,ignore (demonstrates crates.io usage) |
| 62 | +//! extern crate jemallocator; |
| 63 | +//! |
| 64 | +//! use jemallacator::Jemalloc; |
| 65 | +//! |
| 66 | +//! #[global_allocator] |
| 67 | +//! static GLOBAL: Jemalloc = Jemalloc; |
| 68 | +//! |
| 69 | +//! fn main() {} |
| 70 | +//! ``` |
| 71 | +//! |
| 72 | +//! The `#[global_allocator]` can only be used once in a crate |
| 73 | +//! or its recursive dependencies. |
12 | 74 |
|
13 | 75 | #![stable(feature = "alloc_module", since = "1.28.0")]
|
14 | 76 |
|
|
0 commit comments