Crate memoffset

Source
Expand description

A crate used for calculating offsets of struct members and their spans.

This functionality currently can not be used in compile time code such as const or const fn definitions.

§Examples

use memoffset::{offset_of, span_of};

#[repr(C, packed)]
struct HelpMeIAmTrappedInAStructFactory {
    help_me_before_they_: [u8; 15],
    a: u32
}

assert_eq!(offset_of!(HelpMeIAmTrappedInAStructFactory, a), 15);
assert_eq!(span_of!(HelpMeIAmTrappedInAStructFactory, a), 15..19);
assert_eq!(span_of!(HelpMeIAmTrappedInAStructFactory, help_me_before_they_ .. a), 0..15);

This functionality can be useful, for example, for checksum calculations:

#[repr(C, packed)]
struct Message {
    header: MessageHeader,
    fragment_index: u32,
    fragment_count: u32,
    payload: [u8; 1024],
    checksum: u16
}

let checksum_range = &raw[span_of!(Message, header..checksum)];
let checksum = crc16(checksum_range);

Macros§

offset_of
Calculates the offset of the specified field from the start of the named struct.
offset_of_tuple
Calculates the offset of the specified field from the start of the tuple.
offset_of_union
Calculates the offset of the specified union member from the start of the union.
raw_field
Computes a const raw pointer to the given field of the given base pointer to the given parent type.
raw_field_tuple
Computes a const raw pointer to the given field of the given base pointer to the given parent tuple type.
raw_field_union
Computes a const raw pointer to the given field of the given base pointer to the given parent tuple type.
span_of
Produces a range instance representing the sub-slice containing the specified member.