|
1 | 1 | [](https://crates.io/crates/embedded-alloc) |
2 | 2 | [](https://crates.io/crates/embedded-alloc) |
| 3 | + - |
| 4 | + [Documentation](https://docs.rs/embedded-alloc) - [Change log](https://github.com/rust-embedded/embedded-alloc/blob/master/CHANGELOG.md) |
3 | 5 |
|
4 | 6 | # `embedded-alloc` |
5 | 7 |
|
6 | 8 | > A heap allocator for embedded systems. |
7 | 9 |
|
8 | | -Note that using this as your global allocator requires nightly Rust. |
| 10 | +Note that using this as your global allocator requires Rust 1.68 or later. |
| 11 | +(With earlier versions, you need the unstable feature `#![feature(default_alloc_error_handler)]`) |
9 | 12 |
|
10 | 13 | This project is developed and maintained by the [Cortex-M team][team]. |
11 | 14 |
|
12 | 15 | ## Example |
13 | 16 |
|
14 | | -For a usage example, see `examples/global_alloc.rs`. |
| 17 | +Starting with Rust 1.68, this crate can be used as a global allocator on stable Rust: |
15 | 18 |
|
16 | | -## [Documentation](https://docs.rs/embedded-alloc) |
| 19 | +```rust |
| 20 | +#![no_std] |
| 21 | +#![no_main] |
17 | 22 |
|
18 | | -## [Change log](CHANGELOG.md) |
| 23 | +extern crate alloc; |
| 24 | + |
| 25 | +use cortex_m_rt::entry; |
| 26 | +use embedded_alloc::Heap; |
| 27 | + |
| 28 | +#[global_allocator] |
| 29 | +static HEAP: Heap = Heap::empty(); |
| 30 | + |
| 31 | +#[entry] |
| 32 | +fn main() -> ! { |
| 33 | + // Initialize the allocator BEFORE you use it |
| 34 | + { |
| 35 | + use core::mem::MaybeUninit; |
| 36 | + const HEAP_SIZE: usize = 1024; |
| 37 | + static mut HEAP_MEM: [MaybeUninit<u8>; HEAP_SIZE] = [MaybeUninit::uninit(); HEAP_SIZE]; |
| 38 | + unsafe { HEAP.init(HEAP_MEM.as_ptr() as usize, HEAP_SIZE) } |
| 39 | + } |
| 40 | + |
| 41 | + // now the allocator is ready types like Box, Vec can be used. |
| 42 | + |
| 43 | + loop { /* .. */ } |
| 44 | +} |
| 45 | +``` |
| 46 | + |
| 47 | +For a full usage example, see [`examples/global_alloc.rs`](https://github.com/rust-embedded/embedded-alloc/blob/master/examples/global_alloc.rs). |
19 | 48 |
|
20 | 49 | ## License |
21 | 50 |
|
|
0 commit comments