Skip to content

Commit 00a647e

Browse files
committed
Update global_allocator to use the attribute template
This also adds a little more detail. This is still a little light, and to some degree that is intentional because there is significant overlap with the standard library, and the standard library docs do contain a little more detail.
1 parent 9571d4d commit 00a647e

File tree

1 file changed

+37
-2
lines changed

1 file changed

+37
-2
lines changed

src/runtime.md

Lines changed: 37 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -6,8 +6,43 @@ This section documents features that define some aspects of the Rust runtime.
66
r[runtime.global_allocator]
77
## The `global_allocator` attribute
88

9-
The *`global_allocator` attribute* is used on a [static item] implementing the
10-
[`GlobalAlloc`] trait to set the global allocator.
9+
r[runtime.global_allocator.intro]
10+
The *`global_allocator` [attribute][attributes]* is used to define a [memory allocator][std::alloc].
11+
12+
> [!EXAMPLE]
13+
> ```rust
14+
> use std::alloc::{GlobalAlloc, System, Layout};
15+
>
16+
> struct MyAllocator;
17+
>
18+
> unsafe impl GlobalAlloc for MyAllocator {
19+
> unsafe fn alloc(&self, layout: Layout) -> *mut u8 {
20+
> unsafe { System.alloc(layout) }
21+
> }
22+
>
23+
> unsafe fn dealloc(&self, ptr: *mut u8, layout: Layout) {
24+
> unsafe { System.dealloc(ptr, layout) }
25+
> }
26+
> }
27+
>
28+
> #[global_allocator]
29+
> static GLOBAL: MyAllocator = MyAllocator;
30+
> ```
31+
32+
r[runtime.global_allocator.syntax]
33+
The `global_allocator` attribute uses the [MetaWord] syntax and thus does not take any inputs.
34+
35+
r[runtime.global_allocator.allowed-positions]
36+
The `global_allocator` attribute may only be applied to a [static item] that implements the [`GlobalAlloc`] trait.
37+
38+
r[runtime.global_allocator.duplicates]
39+
The `global_allocator` attribute may only be specified once on an item.
40+
41+
r[runtime.global_allocator.single]
42+
At most one `global_allocator` may be specified in the crate graph.
43+
44+
r[runtime.global_allocator.stdlib]
45+
The `global_allocator` attribute is exported in the [standard library prelude][core::prelude::v1].
1146
1247
r[runtime.windows_subsystem]
1348
## The `windows_subsystem` attribute

0 commit comments

Comments
 (0)