hi,
is there a way to have field_slice to not take any space on disk ?
#[derive(Default)]
struct NestedB {
slice_length: usize,
}
#[derive(Default)]
struct SomeInfo {}
#[derive(Default)]
#[repr(C)]
struct A {
some_data: SomeInfo,
nested: NestedB,
field_slice: usize,
}
fn main() {
let mut a = A::default();
// ... do things with A, then:
let v = a.field_slice as *mut usize;
let _slice = unsafe { std::slice::from_raw_parts_mut(v, a.nested.slice_length) };
}
Basically, A is a header for a dynamically size array of bytes. And to simplify things, I like to have a field pointing to the beginning of the area to ease the coding experience.
So is there a trick in Rust to have field_slice to be storage free ? As if non existent on disk ?
You can just replace field_slice with any type without fields, also commonly called as ZST (Zero Sized Types). You should also mark such struct with #[align(...)] where the ... are replaced with the alignment of the type of your dynamically sized tail, otherwise it will be aligned to the end of nested rather than the start of the dynamically sized tail (if these don't coincide).
Be careful with this, you are converting the value of the field_slice field to a pointer instead of taking a pointer to it. Consider using addr_of!((*a).field_slice) instead, where a is a raw pointer to an instance of A. Also be very careful when creating references to A (avoid them if you can), as those will implicitly assert that they are only valid for A itself (thus excluding any dynamically sized tail you want to access).