Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Deprecate cString on non-Darwin (#3885) #5190

Open
wants to merge 3 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions Sources/Foundation/NSConcreteValue.swift
Original file line number Diff line number Diff line change
Expand Up @@ -97,6 +97,7 @@ internal class NSConcreteValue : NSValue, @unchecked Sendable {
value.copyMemory(from: self._storage, byteCount: self._size)
}

@available(*, deprecated, message: "On platforms without Objective-C autorelease pools, use withCString instead")
override var objCType : UnsafePointer<Int8> {
return NSString(self._typeInfo.name).utf8String! // XXX leaky
}
Expand Down
1 change: 1 addition & 0 deletions Sources/Foundation/NSSpecialValue.swift
Original file line number Diff line number Diff line change
Expand Up @@ -97,6 +97,7 @@ internal class NSSpecialValue : NSValue, @unchecked Sendable {
_value.encodeWithCoder(aCoder)
}

@available(*, deprecated, message: "On platforms without Objective-C autorelease pools, use withCString instead")
override var objCType : UnsafePointer<Int8> {
let typeName = NSSpecialValue._objCTypeFromType(type(of: _value))
return typeName!._bridgeToObjectiveC().utf8String! // leaky
Expand Down
56 changes: 32 additions & 24 deletions Sources/Foundation/NSString.swift
Original file line number Diff line number Diff line change
Expand Up @@ -160,32 +160,19 @@ internal func _createRegexForPattern(_ pattern: String, _ options: NSRegularExpr
return regex
}

internal func _bytesInEncoding(_ str: NSString, _ encoding: String.Encoding, _ fatalOnError: Bool, _ externalRep: Bool, _ lossy: Bool) -> UnsafePointer<Int8>? {
let theRange = NSRange(location: 0, length: str.length)
// Caller must free, or leak, the pointer
fileprivate func _allocateBytesInEncoding(_ str: NSString, _ encoding: String.Encoding) -> UnsafeMutableBufferPointer<Int8>? {
let theRange: NSRange = NSRange(location: 0, length: str.length)
var cLength = 0
var used = 0
var options: NSString.EncodingConversionOptions = []
if externalRep {
options.formUnion(.externalRepresentation)
}
if lossy {
options.formUnion(.allowLossy)
}
if !str.getBytes(nil, maxLength: Int.max - 1, usedLength: &cLength, encoding: encoding.rawValue, options: options, range: theRange, remaining: nil) {
if fatalOnError {
fatalError("Conversion on encoding failed")
}
if !str.getBytes(nil, maxLength: Int.max - 1, usedLength: &cLength, encoding: encoding.rawValue, options: [], range: theRange, remaining: nil) {
return nil
}

let buffer = malloc(cLength + 1)!.bindMemory(to: Int8.self, capacity: cLength + 1)
if !str.getBytes(buffer, maxLength: cLength, usedLength: &used, encoding: encoding.rawValue, options: options, range: theRange, remaining: nil) {
fatalError("Internal inconsistency; previously claimed getBytes returned success but failed with similar invocation")
}
let buffer = UnsafeMutableBufferPointer<Int8>.allocate(capacity: cLength + 1)
buffer.initialize(repeating: 0)
_ = str.getBytes(buffer.baseAddress, maxLength: cLength, usedLength: nil, encoding: encoding.rawValue, options: [], range: theRange, remaining: nil)

buffer.advanced(by: cLength).initialize(to: 0)

return UnsafePointer(buffer) // leaked and should be autoreleased via a NSData backing but we cannot here
return buffer
}

internal func isALineSeparatorTypeCharacter(_ ch: unichar) -> Bool {
Expand Down Expand Up @@ -903,8 +890,13 @@ extension NSString {
}
}

@available(*, deprecated, message: "On platforms without Objective-C autorelease pools, use withCString instead")
public var utf8String: UnsafePointer<Int8>? {
return _bytesInEncoding(self, .utf8, false, false, false)
guard let buffer = _allocateBytesInEncoding(self, .utf8) else {
return nil
}
// leaked. On Darwin, freed via an autorelease
return UnsafePointer<Int8>(buffer.baseAddress)
}

public var fastestEncoding: UInt {
Expand Down Expand Up @@ -961,8 +953,24 @@ extension NSString {
0, nil, 0, nil) == length
}

public func cString(using encoding: UInt) -> UnsafePointer<Int8>? {
return _bytesInEncoding(self, String.Encoding(rawValue: encoding), false, false, false)
@available(*, deprecated, message: "On platforms without Objective-C autorelease pools, use withCString(encodedAs:_) instead")
public func cString(using encoding: UInt) -> UnsafePointer<Int8>? {
// leaked. On Darwin, freed via an autorelease
guard let buffer = _allocateBytesInEncoding(self, String.Encoding(rawValue: encoding)) else {
return nil
}
// leaked. On Darwin, freed via an autorelease
return UnsafePointer<Int8>(buffer.baseAddress)
}

internal func _withCString<T>(using encoding: UInt, closure: (UnsafePointer<Int8>?) -> T) -> T {
let buffer = _allocateBytesInEncoding(self, String.Encoding(rawValue: encoding))
let result = closure(buffer?.baseAddress)
if let buffer {
buffer.deinitialize()
buffer.deallocate()
}
return result
}

public func getCString(_ buffer: UnsafeMutablePointer<Int8>, maxLength maxBufferCount: Int, encoding: UInt) -> Bool {
Expand Down
5 changes: 2 additions & 3 deletions Sources/Foundation/NSStringAPI.swift
Original file line number Diff line number Diff line change
Expand Up @@ -633,9 +633,8 @@ extension StringProtocol {
/// Returns a representation of the string as a C string
/// using a given encoding.
public func cString(using encoding: String.Encoding) -> [CChar]? {
return withExtendedLifetime(_ns) {
(s: NSString) -> [CChar]? in
_persistCString(s.cString(using: encoding.rawValue))
return _ns._withCString(using: encoding.rawValue) {
_persistCString($0)
}
}

Expand Down
6 changes: 6 additions & 0 deletions Tests/Foundation/TestNSString.swift
Original file line number Diff line number Diff line change
Expand Up @@ -316,6 +316,12 @@ class TestNSString: LoopbackServerTest {
XCTAssertNil(string)
}

func test_cStringArray() {
let str = "abc"
let encoded = str.cString(using: .ascii)
XCTAssertEqual(encoded, [97, 98, 99, 0])
}

func test_FromContentsOfURL() throws {
throw XCTSkip("Test is flaky in CI: https://bugs.swift.org/browse/SR-10514")
#if false
Expand Down