Skip to content

Commit c9d15ae

Browse files
[Interop][SwiftToCxx] Improving std::Expected constructors
1 parent 0b217b9 commit c9d15ae

File tree

1 file changed

+14
-13
lines changed

1 file changed

+14
-13
lines changed

lib/PrintAsClang/_SwiftCxxInteroperability.h

Lines changed: 14 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -202,23 +202,24 @@ class Expected {
202202

203203
/// Default
204204
constexpr Expected() { has_val = false; }
205-
constexpr Expected(T buf) : buffer(buf) { has_val = true; }
206-
constexpr Expected(swift::Error * _Nonnull error_val) : err(error_val) { has_val = false; }
205+
constexpr Expected(const swift::Error& error_val) : err(error_val) { has_val = false; }
206+
constexpr Expected(T buf) {
207+
new (&buffer) T(buf);
208+
has_val = true;
209+
}
207210

208211
/// Copy
209212
constexpr Expected(Expected const& other) noexcept {
210-
if (other.has_value()) {
211-
buffer = other.buffer;
212-
has_val = true;
213-
}
213+
if (other.has_value())
214+
new (&buffer) T(other.value());
215+
else
216+
new (&err) Error(other.error());
217+
218+
has_val = other.has_value();
214219
}
215220
/// Move
216-
constexpr Expected(Expected&& other) noexcept {
217-
if (other.has_value()) {
218-
buffer = other.buffer;
219-
has_val = true;
220-
}
221-
}
221+
// FIXME: Implement move semantics when move Swift values is possible
222+
constexpr Expected(Expected&&) noexcept { abort(); }
222223

223224
~Expected() noexcept { }
224225

@@ -273,7 +274,7 @@ class Expected {
273274
constexpr bool has_value() const noexcept { return has_val; }
274275

275276
private:
276-
T buffer;
277+
alignas(alignof(T)) char buffer[sizeof(T)];
277278
swift::Error err;
278279
bool has_val;
279280
};

0 commit comments

Comments
 (0)