interplane.Get Omega
Read in your language

aienux

Aienux, the AienOS kernel: boot, scheduling, IPC and capability boundaries. Pre-alpha; host, emulator and physical evidence are labelled separately.

Brought by drakestapleton

branch main Branches Tags History

aienux / vendor / ptr_meta / example.md

52 lines · 1344 bytes Raw Blame History Rendered
1```rust
2// Get the associated metadata for pointers
3let str = "hello world";
4assert_eq!(ptr_meta::metadata(str), str.len());
5
6let slice = &[1, 2, 3, 4, 5] as &[i32];
7assert_eq!(ptr_meta::metadata(slice), slice.len());
8
9// Make your own wide pointers from data pointers and metadata
10let bytes = [b'h', b'e', b'l', b'l', b'o'];
11let ptr = ptr_meta::from_raw_parts::<str>(bytes.as_ptr().cast(), 5);
12println!("{} world!", unsafe { &*ptr }); // prints "hello world!"
13
14// Derive Pointee on your own types
15#[derive(ptr_meta::Pointee)]
16#[repr(transparent)]
17struct CoolStr {
18 inner: str,
19}
20
21impl CoolStr {
22 fn print_cool(&self) {
23 println!("😎 {} 😎", &self.inner);
24 }
25}
26
27let ptr = ptr_meta::from_raw_parts::<CoolStr>(bytes.as_ptr().cast(), 5);
28let cool = unsafe { &*ptr };
29cool.print_cool(); // prints "😎 hello 😎"
30
31// Implement Pointee for trait objects
32#[ptr_meta::pointee]
33trait Printable {
34 fn print(&self);
35}
36
37impl Printable for i32 {
38 fn print(&self) {
39 println!("i32: {self}");
40 }
41}
42
43let i32_vtable = ptr_meta::metadata(&0i32 as &dyn Printable);
44let one_hundred = 100i32;
45let printable = ptr_meta::from_raw_parts::<dyn Printable>(
46 (&one_hundred as *const i32).cast(),
47 i32_vtable,
48);
49unsafe {
50 (*printable).print(); // prints "i32: 100"
51}
52```