Skip to content

Use String.decodeCString() instead of bitcasting. #1154

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

Merged
merged 1 commit into from
Aug 3, 2017
Merged
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
15 changes: 8 additions & 7 deletions Foundation/XMLParser.swift
Original file line number Diff line number Diff line change
Expand Up @@ -42,13 +42,14 @@ extension XMLParser {
}

private func UTF8STRING(_ bytes: UnsafePointer<UInt8>?) -> String? {
guard let bytes = bytes else { return nil }
// strlen operates on the wrong type, char*. We can't rebind the memory to a different type without knowing its length,
// but since we know strlen is in libc, it's safe to directly bitcast the pointer without worrying about multiple accesses
// of different types visible to the compiler.
let len = strlen(unsafeBitCast(bytes, to: UnsafePointer<Int8>.self))
let str = String._fromCodeUnitSequence(UTF8.self, input: UnsafeBufferPointer(start: bytes, count: Int(len)))
return str
guard let bytes = bytes else {
return nil
}
if let (str, _) = String.decodeCString(bytes, as: UTF8.self,
repairingInvalidCodeUnits: false) {
return str
}
return nil
}

internal func _NSXMLParserCurrentParser() -> _CFXMLInterface? {
Expand Down