Skip to content

Commit b5e250f

Browse files
committed
SR-7455: Minor speedups
- If CFStringGetLength() returns 0 just create an empty string (""). - Try CFStringGetCharactersPtr() before CFStringGetCharacters() to avoid allocating a buffer.
1 parent 40b4ee6 commit b5e250f

File tree

1 file changed

+9
-8
lines changed

1 file changed

+9
-8
lines changed

Foundation/String.swift

Lines changed: 9 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -30,24 +30,25 @@ extension String : _ObjectiveCBridgeable {
3030
} else if type(of: source) == _NSCFString.self {
3131
let cf = unsafeBitCast(source, to: CFString.self)
3232
let length = CFStringGetLength(cf)
33-
if let str = CFStringGetCStringPtr(cf, CFStringEncoding(kCFStringEncodingUTF8)) {
34-
result = str.withMemoryRebound(to: UInt8.self, capacity: length) { ptr in
35-
let buffer = UnsafeBufferPointer(start: ptr, count: length)
36-
return String(decoding: buffer, as: UTF8.self)
33+
if length == 0 {
34+
result = ""
35+
} else if let ptr = CFStringGetCStringPtr(cf, CFStringEncoding(kCFStringEncodingUTF8)) {
36+
result = ptr.withMemoryRebound(to: UInt8.self, capacity: length) {
37+
return String(decoding: UnsafeBufferPointer(start: $0, count: length), as: UTF8.self)
3738
}
39+
} else if let ptr = CFStringGetCharactersPtr(cf) {
40+
result = String(decoding: UnsafeBufferPointer(start: ptr, count: length), as: UTF16.self)
3841
} else {
3942
let buffer = UnsafeMutablePointer<UniChar>.allocate(capacity: length)
4043
CFStringGetCharacters(cf, CFRangeMake(0, length), buffer)
4144

42-
let str = String(decoding: UnsafeBufferPointer(start: buffer, count: length), as: UTF16.self)
45+
result = String(decoding: UnsafeBufferPointer(start: buffer, count: length), as: UTF16.self)
4346
buffer.deinitialize(count: length)
4447
buffer.deallocate()
45-
result = str
4648
}
4749
} else if type(of: source) == _NSCFConstantString.self {
4850
let conststr = unsafeDowncast(source, to: _NSCFConstantString.self)
49-
let str = String(decoding: UnsafeBufferPointer(start: conststr._ptr, count: Int(conststr._length)), as: UTF8.self)
50-
result = str
51+
result = String(decoding: UnsafeBufferPointer(start: conststr._ptr, count: Int(conststr._length)), as: UTF8.self)
5152
} else {
5253
let len = source.length
5354
var characters = [unichar](repeating: 0, count: len)

0 commit comments

Comments
 (0)