repr_offset::ext

Trait ROExtRawAcc

Source
pub unsafe trait ROExtRawAcc: PointerTarget {
    // Required method
    unsafe fn f_raw_get<F, A>(
        self,
        offset: FieldOffset<Self::Target, F, A>,
    ) -> *const F;
}
Expand description

Extension trait for raw pointers to access fields generically, where the field is determined by a FieldOffset parameter.

§Safety

This trait must not to be implemented outside the repr_offset crate.

§Example

This example shows how you can get references to known aligned fields from a raw pointer to a partially initialized value..

use repr_offset::{
    for_examples::ReprC,
    off,
    ROExtRawAcc, ROExtRawMutOps,
};

use std::mem::MaybeUninit;

type This = ReprC<u8, Option<usize>, &'static [u16], &'static str>;

let mut uninit = MaybeUninit::<This>::uninit();

unsafe {
    let ptr = uninit.as_mut_ptr();
    ptr.f_write(off!(a), 3);
    ptr.f_write(off!(b), Some(5));

    let (a, b) = get_init_refs(&uninit);
    assert_eq!(*a, 3);
    assert_eq!(*b, Some(5));
}

/// # Safety
///
/// The fields up to and including `b` must be initialized.
unsafe fn get_init_refs(this: &MaybeUninit<This>) -> (&u8, &Option<usize>) {
    let this = this.as_ptr();

    (
        &*this.f_raw_get(off!(a)),
        &*this.f_raw_get(off!(b)),
    )
}

Required Methods§

Source

unsafe fn f_raw_get<F, A>( self, offset: FieldOffset<Self::Target, F, A>, ) -> *const F

Gets a raw pointer to a field (determined by offset) from this raw pointer.

§Safety

self must point to some allocated object, allocated at least up to the field (inclusive).

§Example
use repr_offset::{
    for_examples::{ReprC, ReprPacked},
    tstr::TS,
    GetPubFieldOffset, FieldType,
    ROExtRawAcc,
    pub_off,
};

use std::cmp::Ordering;

let value = ReprPacked {
    a: 3,
    b: Some(5),
    c: Ordering::Less,
    d: ReprC {
        a: 8,
        b: "bar",
        c: 13,
        d: 21,
    },
};

unsafe {
    assert_eq!(copy_fields(&value), (3, 13));
}


/// Copies the `a` and `d.c` fields in this.
///
/// # Safety
///
/// The `a` and `d.c` fields in this must be initialized
unsafe fn copy_fields<T, O, U>(
    this: *const T,
) -> (O, U)
where
    T: GetPubFieldOffset<TS!(a), Type = O>,
    T: GetPubFieldOffset<TS!(d,c), Type = U>,
    O: Copy,
    U: Copy,
{
    (
        this.f_raw_get(pub_off!(a)).read_unaligned(),
        this.f_raw_get(pub_off!(d.c)).read_unaligned(),
    )
}

Dyn Compatibility§

This trait is not dyn compatible.

In older versions of Rust, dyn compatibility was called "object safety", so this trait is not object safe.

Implementations on Foreign Types§

Source§

impl<S> ROExtRawAcc for *const S

Source§

unsafe fn f_raw_get<F, A>( self, offset: FieldOffset<Self::Target, F, A>, ) -> *const F

Source§

impl<S> ROExtRawAcc for *mut S

Source§

unsafe fn f_raw_get<F, A>( self, offset: FieldOffset<Self::Target, F, A>, ) -> *const F

Implementors§