Skip to content

Commit 8e039ff

Browse files
committed
Added CVarArg support to NSString and String
1 parent 2fc16a2 commit 8e039ff

File tree

2 files changed

+30
-0
lines changed

2 files changed

+30
-0
lines changed

Sources/Foundation/NSString.swift

Lines changed: 20 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1644,3 +1644,23 @@ extension NSString : _StructTypeBridgeable {
16441644
return _StructType._unconditionallyBridgeFromObjectiveC(self)
16451645
}
16461646
}
1647+
1648+
extension NSString : CVarArg {
1649+
@inlinable // c-abi
1650+
public var _cVarArgEncoding: [Int] {
1651+
return _encodeBitsAsWords(unsafeBitCast(self, to: CFString.self))
1652+
}
1653+
}
1654+
1655+
extension String : CVarArg {
1656+
@inlinable // c-abi
1657+
public var _cVarArgEncoding: [Int] {
1658+
// We don't have an autorelease pool to retain the NSString until the withVaList closure is complete.
1659+
// So add an operation to release on the next cycle of this thread.
1660+
let ns = Unmanaged.passRetained(NSString(string: self))
1661+
OperationQueue.current?.addOperation {
1662+
ns.release()
1663+
}
1664+
return ns.takeUnretainedValue()._cVarArgEncoding
1665+
}
1666+
}

Tests/Foundation/Tests/TestNSString.swift

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -813,6 +813,15 @@ class TestNSString: LoopbackServerTest {
813813
}
814814
}
815815

816+
func test_initializeWithFormat4() {
817+
let argument: [CVarArg] = ["One", "Two", "Three"]
818+
withVaList(argument) {
819+
pointer in
820+
let string = NSString(format: "Testing %@ %@ %@", arguments: pointer)
821+
XCTAssertEqual(string, "Testing One Two Three")
822+
}
823+
}
824+
816825
func test_appendingPathComponent() {
817826
do {
818827
let path: NSString = "/tmp"
@@ -1677,6 +1686,7 @@ class TestNSString: LoopbackServerTest {
16771686
("test_initializeWithFormat", test_initializeWithFormat),
16781687
("test_initializeWithFormat2", test_initializeWithFormat2),
16791688
("test_initializeWithFormat3", test_initializeWithFormat3),
1689+
("test_initializeWithFormat4", test_initializeWithFormat4),
16801690
("test_appendingPathComponent", test_appendingPathComponent),
16811691
("test_deletingLastPathComponent", test_deletingLastPathComponent),
16821692
("test_getCString_simple", test_getCString_simple),

0 commit comments

Comments
 (0)