#repr packed

28 messages · Page 1 of 1 (latest)

urban pendant
#
|       16 bytes      |
into
|  8 bytes |  8 bytes |

But now it can start at an address that is % 8 right ?

olive quiver
#

For many architectures, alignment is required and misaligned access will have to be performed differently. E.g. if your struct is packed as (u8, u16, u8) in that order, the u16 will often require something like loading a word, shifting the register, and then masking off the upper bits.

#

Or it will use two u8-wide loads and a shift and an or

#

Objects have an alignment of their own so that elements within an object don't need special considerations to load from. In the above case, you would need special cases for each of the 4 possible alignments of that packed object (u8, u16, u8).

#

So language designers have made the sensible decision to just... not do that and instead live with the extra wasted memory because speed is king.

#

Which leads us to the answer to your question:
Alignment only exists to make the processor happy and fast. You can do it the slow way instead with packed, unaligned data.
Yes, it will hurt performance.

#

It may also be interesting to note that unless you add #[repr(C)] to your struct, the Rust compiler can re-order the fields of your struct to get the best performance and size and whatnot

urban pendant
#

Alright thanks a lot

#

Very good explanation ! 👍

#

I don't understand how I can get a struct with alignment of 16 while not using i128 or u128 tho ?

#

Do you think it's possible ?

#

I think alignment is the max of all the alignments, right ? 🤔

#

Maybe with combination of struct ? 🤔

olive quiver
#

The reference you shared only says this

The alignment of the type is at least the maximum alignment of its fields.

urban pendant
#

Alright, thanks a lot !

#

🙏

#

And I found where this crate brought 16 bit alignment, it had that on one of the deep child :
#[repr(C, align(16))]

#

So yeah

olive quiver
urban pendant
#

It was to store a color palette of 4xf32

#

But I think that it's not great

#

I'll remove it

olive quiver
#

Aha, it may have to do with SIMD

#

SIMD instructions often only work with aligned data

olive quiver
urban pendant