Declare union fields as safe to access

In some (albeit small) cases it would be useful to declare an union's fields as "safe" to access.

One motivating example: Ergonomic bitfields

Note that the example is not sound as written, because #[repr(Rust)] union do not guarantee that all fields are placed at offset zero. If you want that, you (currently[1]) need to use #[repr(C)].

At a minimum, doing something like this is probably blocked on project safe transmute, as union field access is only possibly sound if arbitrary transmutes between the field types are sound.


  1. While the guarantee is not currently provided, there's very little benefit available from not providing it. It's possible that union layout will guarantee this in the future, but currently, they do not. ↩︎

6 Likes

When you say enum I assume you mean union?

1 Like

It could be an unsafe attribute now, and conditionally safe later.

2 Likes

Yep, typo! Fixed.

sidenote, i think rust itself violates the recommentations of that rfc, specifically this one:

Note that when writing a library crate, it is in general not possible to make claims like “there is no other global function of this name”. This is a fundamental limitation of the global linking namespace, and not something Rust currently is able to overcome. Libraries that make such assumptions should ideally document somewhere publicly that they consider some namespace, i.e. every function starting with _mycrate__, to be reserved for their exclusive use.

rust uses __rust_* for certain things, like the global allocator.

This topic was automatically closed 540 days after the last reply. New replies are no longer allowed.