Skip to content

Commit 0e1be77

Browse files
authored
Merge pull request swiftlang#83701 from ludwwwig/interop-strcpy
[cxx-interop] Copy lazily bridged Cocoa strings correctly without hanging
2 parents 69cafe4 + 54f3153 commit 0e1be77

File tree

2 files changed

+14
-6
lines changed

2 files changed

+14
-6
lines changed

lib/PrintAsClang/_SwiftStdlibCxxOverlay.h

Lines changed: 7 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -74,13 +74,14 @@ static_assert(sizeof(_impl::_impl_String) >= 0,
7474
SWIFT_INLINE_THUNK String::operator std::string() const {
7575
auto u = getUtf8();
7676
std::string result;
77-
result.reserve(u.getCount() + 1);
78-
using IndexType = decltype(u.getStartIndex());
79-
for (auto s = u.getStartIndex().getEncodedOffset(),
80-
e = u.getEndIndex().getEncodedOffset();
81-
s != e; s = u.indexOffsetBy(IndexType::init(s), 1).getEncodedOffset()) {
82-
result.push_back(u[IndexType::init(s)]);
77+
result.reserve(u.getCount());
78+
79+
auto end_offset = u.getEndIndex().getEncodedOffset();
80+
for (auto idx = u.getStartIndex(); idx.getEncodedOffset() < end_offset;
81+
idx = u.indexAfter(idx)) {
82+
result.push_back(static_cast<char>(u[idx]));
8383
}
84+
8485
return result;
8586
}
8687

test/Interop/SwiftToCxx/stdlib/string/string-to-nsstring.mm

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -69,5 +69,12 @@ int main() {
6969
assert(std::string(nsStr.UTF8String) == "nsstr");
7070
assert([nsStr2 isEqualToString:nsStr]);
7171
}
72+
73+
NSString *nsStrContainingUnicode = @"👨‍💻👩‍💻åäö";
74+
{
75+
swift::String swiftStr = swift::String::init(nsStrContainingUnicode);
76+
assert(std::string(swiftStr) == "👨‍💻👩‍💻åäö");
77+
}
78+
7279
return 0;
7380
}

0 commit comments

Comments
 (0)