Macro repr_offset::pub_off

source ·
macro_rules! pub_off {
    ($value:expr; $($fields:tt).+ ) => { ... };
    ( $($fields:tt).+ ) => { ... };
}
Expand description

Gets the FieldOffset for a (possibly nested) public field, and an optionally passed in value.

This is the same as the off macro, except that this can’t access private fields, and it allows accessing fields from type parameters in generic functions.

The value argument is only necessary when the type that the fields are from can’t be inferred.

§Examples

§Named Type

use repr_offset::{
    for_examples::ReprC,
    pub_off,
    FieldOffset, ROExtAcc,
};

let this = ReprC {a: 3u8, b: 5u8, c: 8u8, d: 13u8};

// The value must be passed to the macro when you want to call
// any method on the returned `FieldOffset`.
assert_eq!(pub_off!(this; a).get(&this), &this.a);

assert_eq!(this.f_get(pub_off!(this; b)), &this.b);

assert_eq!(this.f_get(pub_off!(c)), &this.c);
assert_eq!(this.f_get(pub_off!(d)), &this.d);

§Accessing fields from type parameters

use repr_offset::{
    for_examples::ReprC,
    tstr::TS,
    pub_off,
    FieldOffset, GetPubFieldOffset, ROExtOps,
};

let this = ReprC {a: 3u8, b: 5u8, c: 8u8, d: 13u8};

assertions(this);

fn assertions<T, A>(this: T)
where
    T: GetPubFieldOffset<TS!(a), Type = u8, Alignment = A>,
    T: GetPubFieldOffset<TS!(b), Type = u8, Alignment = A>,
    T: GetPubFieldOffset<TS!(c), Type = u8, Alignment = A>,
    T: GetPubFieldOffset<TS!(d), Type = u8, Alignment = A>,
    T: ROExtOps<A>,
{
    assert_eq!(this.f_get_copy(pub_off!(this; a)), 3);
    assert_eq!(this.f_get_copy(pub_off!(this; b)), 5);
    assert_eq!(this.f_get_copy(pub_off!(c)), 8);
    assert_eq!(this.f_get_copy(pub_off!(d)), 13);
}