Skip to content

Commit b074d3e

Browse files
committed
Generate unsafe Default impl for union only in unsafe model
1 parent fe80784 commit b074d3e

4 files changed

Lines changed: 18 additions & 4 deletions

File tree

cpp2rust/converter/converter.cpp

Lines changed: 11 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -3210,12 +3210,19 @@ void Converter::AddCloneTrait(const clang::CXXRecordDecl *decl) {}
32103210

32113211
void Converter::AddDropTrait(const clang::CXXRecordDecl *decl) {}
32123212

3213+
void Converter::AddDefaultTraitForUnion(const clang::RecordDecl *decl) {
3214+
StrCat(std::format("impl Default for {}", GetRecordName(decl)));
3215+
PushBrace impl_brace(*this);
3216+
StrCat("fn default() -> Self");
3217+
PushBrace fn_brace(*this);
3218+
StrCat("unsafe");
3219+
PushBrace unsafe_brace(*this);
3220+
StrCat("std::mem::zeroed()");
3221+
}
3222+
32133223
void Converter::AddDefaultTrait(const clang::RecordDecl *decl) {
32143224
if (decl->isUnion()) {
3215-
StrCat(
3216-
std::format("impl Default for {} {{ fn default() -> Self {{ unsafe {{ "
3217-
"std::mem::zeroed() }} }} }}",
3218-
GetRecordName(decl)));
3225+
AddDefaultTraitForUnion(decl);
32193226
return;
32203227
}
32213228
if (RecordDerivesDefault(decl)) {

cpp2rust/converter/converter.h

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -445,6 +445,8 @@ class Converter : public clang::RecursiveASTVisitor<Converter> {
445445

446446
virtual void AddDefaultTrait(const clang::RecordDecl *decl);
447447

448+
virtual void AddDefaultTraitForUnion(const clang::RecordDecl *decl);
449+
448450
virtual void AddByteReprTrait(const clang::RecordDecl *decl);
449451

450452
virtual void

cpp2rust/converter/models/converter_refcount.cpp

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -465,6 +465,9 @@ void ConverterRefCount::AddDefaultTrait(const clang::RecordDecl *decl) {
465465
Converter::AddDefaultTrait(decl);
466466
}
467467

468+
void ConverterRefCount::AddDefaultTraitForUnion(const clang::RecordDecl *decl) {
469+
}
470+
468471
void ConverterRefCount::AddDropTrait(const clang::CXXRecordDecl *decl) {
469472
if (!decl->hasUserDeclaredDestructor()) {
470473
return;

cpp2rust/converter/models/converter_refcount.h

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -41,6 +41,8 @@ class ConverterRefCount final : public Converter {
4141

4242
void AddDefaultTrait(const clang::RecordDecl *decl) override;
4343

44+
void AddDefaultTraitForUnion(const clang::RecordDecl *decl) override;
45+
4446
std::string GetSelfMaybeWithMut(const clang::CXXMethodDecl *decl) override;
4547

4648
bool VisitCXXConstructorDecl(clang::CXXConstructorDecl *decl) override;

0 commit comments

Comments
 (0)