aienux
Aienux, the AienOS kernel: boot, scheduling, IPC and capability boundaries. Pre-alpha; host, emulator and physical evidence are labelled separately.
Brought by drakestapleton
aienux / vendor / ptr_meta_derive / README.md
| 1 | # `ptr_meta` |
| 2 | |
| 3 | [![crates.io badge]][crates.io] [![docs badge]][docs] [![license badge]][license] |
| 4 | |
| 5 | [crates.io badge]: https://img.shields.io/crates/v/ptr_meta.svg |
| 6 | [crates.io]: https://crates.io/crates/ptr_meta |
| 7 | [docs badge]: https://img.shields.io/docsrs/ptr_meta |
| 8 | [docs]: https://docs.rs/ptr_meta |
| 9 | [license badge]: https://img.shields.io/badge/license-MIT-blue.svg |
| 10 | [license]: https://github.com/rkyv/ptr_meta/blob/master/LICENSE |
| 11 | |
| 12 | A radioactive stabilization of the [`ptr_meta` RFC]. |
| 13 | |
| 14 | [`ptr_meta` RFC]: https://rust-lang.github.io/rfcs/2580-ptr-meta.html |
| 15 | |
| 16 | ## Documentation |
| 17 | |
| 18 | - [ptr_meta](https://docs.rs/ptr_meta), the core library |
| 19 | - [ptr_meta_derive](https://docs.rs/ptr_meta_derive), proc macros for |
| 20 | implementing `Pointee` for structs and trait objects |
| 21 | |
| 22 | ## Example |
| 23 | |
| 24 | ```rust |
| 25 | // Get the associated metadata for pointers |
| 26 | let str = "hello world"; |
| 27 | assert_eq!(ptr_meta::metadata(str), str.len()); |
| 28 | |
| 29 | let slice = &[1, 2, 3, 4, 5] as &[i32]; |
| 30 | assert_eq!(ptr_meta::metadata(slice), slice.len()); |
| 31 | |
| 32 | // Make your own wide pointers from data pointers and metadata |
| 33 | let bytes = [b'h', b'e', b'l', b'l', b'o']; |
| 34 | let ptr = ptr_meta::from_raw_parts::<str>(bytes.as_ptr().cast(), 5); |
| 35 | println!("{} world!", unsafe { &*ptr }); // prints "hello world!" |
| 36 | |
| 37 | // Derive Pointee on your own types |
| 38 | #[derive(ptr_meta::Pointee)] |
| 39 | #[repr(transparent)] |
| 40 | struct CoolStr { |
| 41 | inner: str, |
| 42 | } |
| 43 | |
| 44 | impl CoolStr { |
| 45 | fn print_cool(&self) { |
| 46 | println!("😎 {} 😎", &self.inner); |
| 47 | } |
| 48 | } |
| 49 | |
| 50 | let ptr = ptr_meta::from_raw_parts::<CoolStr>(bytes.as_ptr().cast(), 5); |
| 51 | let cool = unsafe { &*ptr }; |
| 52 | cool.print_cool(); // prints "😎 hello 😎" |
| 53 | |
| 54 | // Implement Pointee for trait objects |
| 55 | #[ptr_meta::pointee] |
| 56 | trait Printable { |
| 57 | fn print(&self); |
| 58 | } |
| 59 | |
| 60 | impl Printable for i32 { |
| 61 | fn print(&self) { |
| 62 | println!("i32: {self}"); |
| 63 | } |
| 64 | } |
| 65 | |
| 66 | let i32_vtable = ptr_meta::metadata(&0i32 as &dyn Printable); |
| 67 | let one_hundred = 100i32; |
| 68 | let printable = ptr_meta::from_raw_parts::<dyn Printable>( |
| 69 | (&one_hundred as *const i32).cast(), |
| 70 | i32_vtable, |
| 71 | ); |
| 72 | unsafe { |
| 73 | (*printable).print(); // prints "i32: 100" |
| 74 | } |
| 75 | ``` |