12 releases

0.3.0 Sep 11, 2024
0.3.0-pre1 Nov 4, 2023
0.3.0-alpha.3 Aug 11, 2024
0.3.0-alpha.2 Mar 30, 2024
0.1.2 Mar 17, 2021

#9 in No standard library

Download history 315252/week @ 2024-07-30 322463/week @ 2024-08-06 322505/week @ 2024-08-13 357072/week @ 2024-08-20 332341/week @ 2024-08-27 329278/week @ 2024-09-03 321923/week @ 2024-09-10 293953/week @ 2024-09-17 323684/week @ 2024-09-24 333841/week @ 2024-10-01 340684/week @ 2024-10-08 387461/week @ 2024-10-15 365709/week @ 2024-10-22 370957/week @ 2024-10-29 357349/week @ 2024-11-05 325062/week @ 2024-11-12

1,486,484 downloads per month
Used in 855 crates (16 directly)

MIT license

23KB
335 lines

ptr_meta

crates.io badge docs badge license badge

A radioactive stabilization of the ptr_meta RFC.

Documentation

Example

// Get the associated metadata for pointers
let str = "hello world";
assert_eq!(ptr_meta::metadata(str), str.len());

let slice = &[1, 2, 3, 4, 5] as &[i32];
assert_eq!(ptr_meta::metadata(slice), slice.len());

// Make your own wide pointers from data pointers and metadata
let bytes = [b'h', b'e', b'l', b'l', b'o'];
let ptr = ptr_meta::from_raw_parts::<str>(bytes.as_ptr().cast(), 5);
println!("{} world!", unsafe { &*ptr }); // prints "hello world!"

// Derive Pointee on your own types
#[derive(ptr_meta::Pointee)]
#[repr(transparent)]
struct CoolStr {
    inner: str,
}

impl CoolStr {
    fn print_cool(&self) {
        println!("😎 {} 😎", &self.inner);
    }
}

let ptr = ptr_meta::from_raw_parts::<CoolStr>(bytes.as_ptr().cast(), 5);
let cool = unsafe { &*ptr };
cool.print_cool(); // prints "😎 hello 😎"

// Implement Pointee for trait objects
#[ptr_meta::pointee]
trait Printable {
    fn print(&self);
}

impl Printable for i32 {
    fn print(&self) {
        println!("i32: {self}");
    }
}

let i32_vtable = ptr_meta::metadata(&0i32 as &dyn Printable);
let one_hundred = 100i32;
let printable = ptr_meta::from_raw_parts::<dyn Printable>(
    (&one_hundred as *const i32).cast(),
    i32_vtable,
);
unsafe {
    (*printable).print(); // prints "i32: 100"
}

Dependencies

~105KB