Add safe translation for unions#205
Merged
Merged
Conversation
nunoplopes
reviewed
Jun 25, 2026
| PushBrace impl_brace(*this); | ||
| StrCat("fn default() -> Self"); | ||
| PushBrace fn_brace(*this); | ||
| StrCat(std::format("{} {{ __bytes: Rc::new(RefCell::new(vec![0u8; " |
Contributor
There was a problem hiding this comment.
I think Box::from([0u8; {}]) is more efficient
Contributor
Author
There was a problem hiding this comment.
They should be the same: https://godbolt.org/z/z59EYY6Wb. Historically Box::from([0u8; {}]) made a stack allocation for the array then copied the array on heap. But that seems to be solved so I will use your suggestion
nunoplopes
reviewed
Jun 25, 2026
| auto record_name = GetRecordName(decl); | ||
|
|
||
| if (decl->isUnion()) { | ||
| StrCat(std::format("impl Clone for {}", record_name)); |
Contributor
There was a problem hiding this comment.
a lot of these formats are wasteful. It's better to do StrCat("impl Clone for", record_name)
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
C/C++ unions are translated as a byte buffer + accessors that return a reinterpreted pointer into the byte buffer.
This C/C++ union:
becomes:
Where __bytes is the byte buffer and i() and f() are the accessors that return reinterpreted views into the backing buffer.
Compared to Rust unsafe/C/C++ unions, this implementation is safe because it always serializes/deserializes the bytes into valid values or panics otherwise.