-
Notifications
You must be signed in to change notification settings - Fork 1.6k
UnsafeUnion type #371
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Comments
re the last point - we have been moving in the direction of leaving layouts undefined and requiring an annotation to get a specific (C-compatible) layout, which I think is a good thing. I would recommend the same here. |
I agree with that in general, but in this particular case, where would you put the annotation? This is a type, not a language construct -- seems like that would require separate (The minimum size/alignment are dictated by size and alignment constraints of the contained types - and I guess you could make it even larger or more loosely aligned, but why?) |
As in the other RFC, this should be possible in Rust without special cases in the compiler. Instead of making one RFC per type, one should try to find out what features are necessary to implement this in a library. |
Triage: fixed by #1444 |
Splicing in my comment from a related RFC:
UnsafeUnion<A, B>
.union
s in C: a type compatible with the size and alignment of bothA
andB
. So sizeof(UnsafeUnion<A, B>
) = max(sizeof(A
), sizeof(B
)), and alignof(UnsafeUnion<A, B>
) = lcm(alignof(A
), alignof(B
)).transmute()
. Sotransmute::<A, UnsafeUnion<A, B>>
,transmute::<B, UnsafeUnion<A, B>>
,transmute::<UnsafeUnion<A, B>, A>
, andtransmute::<UnsafeUnion<A, B>, B>
all have well-defined behavior, in basically the same circumstances as in C. (This means that the input and output oftransmute
would not have the same size/alignment in these cases. I don't know whether this is an issue, provided that they are both known.)transmute
s of pointers/references, on the other hand, should only be valid in one direction: e.g. you can legallytransmute
&UnsafeUnion<A, B>
to&A
, but not vice versa.UnsafeUnion
s is idempotent: repr(UnsafeUnion<A, A>
) = repr(A
), commutative: repr(UnsafeUnion<A, B>
) = repr(UnsafeUnion<B, A>
), and associative: repr(UnsafeUnion<A, UnsafeUnion<B, C>>
) = repr(UnsafeUnion<UnsafeUnion<A, B>, C>
), larger unions can simply be composed from the binary one. The use oftransmute
for {,de}construction is also completely impervious to this nesting. We could then also potentially provide synonyms liketype UnsafeUnion3<A, B, C> = UnsafeUnion<A, UnsafeUnion<B, C>>
for convenience.This would primarily be for (a) unsafe code and (b) interfacing with C.
The text was updated successfully, but these errors were encountered: