Determine if struct is padded

Is there any way to determine if struct is padded?
I cannot seem to find anything even in intrinsics which makes me sad.

Are you trying to write a test that a struct gets a layout without padding? One option is to verify that its length is equal to the sum of length of its fields.

Yes, but I was trying to come up with generic solution that doesn't require me to instrument each and every struct declaration.
There seem to be no utility to actually know exact padding of generic T though.

There is even https://doc.rust-lang.org/core/alloc/struct.Layout.html#method.padding_needed_for that would help to determine required padding, but you cannot exactly get size of any T without it having padding

I guess you could build a proc-macro that looks at the fields and creates a constant with its unpadded size or similar. But otherwise I don't think its possible.

1
what are you trying to do?

2
struct layout in rust is quite different than it is in c.
you can use #[repr(C)], and then you should just be able to determine the padding by looking at the field sizes & alignments. (i say should, because struct layout isn't actually standardized in c, afaik. so i don't know what repr(C) really means.)
but it sounds like you want to run a program wide analysis. not sure that is possible. maybe if you use something like rust-analyzer. but again, rust struct layout is implementation defined.

what are you trying to do?

Assert that input type has no padding

struct layout in rust is quite different than it is in c.

Padding is the same regardless

Why exactly do you want to assert this?

No, it is not. A type like

struct Foo {
    a: u8,
    b: u16,
    c: u8,
}

would have 2 bytes of padding in total in C, while the current rustc version would reorder everything such that there is no padding at all. Other rustc versions or rust implementations may choose a different layout with padding.

1 Like

Are you looking for something like bytemuck::Pod?

1 Like

I do not care about padding size, its location and whatever
So for my purpose it is the same regardless

Why exactly do you want to assert this?

Because I need to know that type has no padding so that I could reinterpret it as raw bytes

It is not generic solution

What do you mean by "not generic"? If that means "I can't use it for my own types", well, you can derive it and have a compile error if the requirements are not met.

Generic means that I can apply it to any T without a need of instrumenting declaration of T to define this property

In that case there is no generic solution.

This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.