rust / expert
Snippet
Implementierung eines globalen Allokators
Rust erlaubt es, den Standard-Speicherallokator für das gesamte Programm zu überschreiben. Durch die Implementierung des GlobalAlloc-Traits und die Verwendung des #[global_allocator]-Attributs kann man eigene Logik in jede Reservierung und Freigabe einfügen, was für Profiling oder spezialisierte Embedded-Anforderungen nützlich ist.
snippet.rs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
use std::alloc::{GlobalAlloc, Layout, System};struct TrackingAllocator;unsafe impl GlobalAlloc for TrackingAllocator {unsafe fn alloc(&self, layout: Layout) -> *mut u8 {println!("Allocating {} bytes", layout.size());System.alloc(layout)}unsafe fn dealloc(&self, ptr: *mut u8, layout: Layout) {println!("Deallocating {} bytes", layout.size());System.dealloc(ptr, layout)}}#[global_allocator]static GLOBAL: TrackingAllocator = TrackingAllocator;
Erklärung
1
unsafe impl GlobalAlloc
Die Implementierung dieses Traits ist 'unsafe', da sie Rohzeiger korrekt verwalten muss.
2
System.alloc(layout)
Delegiert die eigentliche Speicherarbeit an den zugrunde liegenden System-Allokator.
3
#[global_allocator]
Ein Compiler-Attribut, das die statische Variable als programmweiten Allokator registriert.