Macro project_ptr

Source
macro_rules! project_ptr {
    ($expr:expr => {$( $($props:tt)=>+ ),* $(,)?}) => { ... };
    ($expr:expr => $($props:tt)=>+) => { ... };
}
Expand description

Unsafe: Given a *const pointer to a struct, obtain *const pointers to one or more of its fields.

This does not statically check whether multiple pointers to the same data are returned. This must be used in an unsafe block or function.

ยงUsage


let bob = Person {
    name: Name { first: "Bob", last: "Jones" },
    age: 35,
    id: (111, 222),
};
let bob_ptr: *const Person = &bob;

unsafe {
    // Pointer to a single field:
    let age: *const u32 = project_ptr!(bob_ptr => age);
    assert_eq!(*age, 35);

    // Pointers to multiple fields:
    let (first, name, id0): (*const &str, *const Name, *const usize) = project_ptr!(
        bob_ptr => { name => first, name, id => 0 }
    );
    assert_eq!(*first, "Bob");
    assert_eq!(*name, Name { first: "Bob", last: "Jones" });
    assert_eq!(*id0, 111);
}