11 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

#136 in #rfc

Download history 336453/week @ 2024-09-26 327650/week @ 2024-10-03 356436/week @ 2024-10-10 384050/week @ 2024-10-17 367717/week @ 2024-10-24 360867/week @ 2024-10-31 361664/week @ 2024-11-07 400457/week @ 2024-11-14 380229/week @ 2024-11-21 371721/week @ 2024-11-28 403021/week @ 2024-12-05 528328/week @ 2024-12-12 314671/week @ 2024-12-19 242570/week @ 2024-12-26 556816/week @ 2025-01-02 626350/week @ 2025-01-09

1,835,916 downloads per month
Used in 808 crates (via ptr_meta)

MIT license

10KB
156 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

~225–670KB
~16K SLoC