From fbf8f362114788412a011dfe5a2cd5442d43ed4b Mon Sep 17 00:00:00 2001 From: Andrew Trick Date: Wed, 27 Jul 2016 22:05:31 -0700 Subject: [PATCH] UnsafePointer conversion fixes. Update for SE-0107: UnsafeRawPointer. Some of this is pretty rough, but it's necessary to keep the build working and land the raw vs. typed pointer feature. As expected there are two major pain points: 1. CString vs. UTF8 types 2. NSData and company use pointer to UInt8 for untyped memory. --- Foundation/Data.swift | 13 +++-- Foundation/NSFileManager.swift | 57 +++++++++----------- Foundation/NSJSONSerialization.swift | 9 ++-- Foundation/NSRegularExpression.swift | 4 +- Foundation/NSString.swift | 10 ++-- Foundation/NSURL.swift | 4 +- Foundation/NSXMLElement.swift | 8 ++- Foundation/NSXMLParser.swift | 38 ++++++++----- Foundation/String.swift | 2 +- TestFoundation/TestNSData.swift | 2 +- TestFoundation/TestNSFileManager.swift | 7 ++- TestFoundation/TestNSJSONSerialization.swift | 8 +-- TestFoundation/TestNSKeyedArchiver.swift | 4 +- TestFoundation/TestNSStream.swift | 6 +-- TestFoundation/TestNSTask.swift | 2 +- TestFoundation/TestNSValue.swift | 2 +- 16 files changed, 96 insertions(+), 80 deletions(-) diff --git a/Foundation/Data.swift b/Foundation/Data.swift index 284250bafa..b9cb5f5983 100644 --- a/Foundation/Data.swift +++ b/Foundation/Data.swift @@ -130,7 +130,7 @@ internal final class _SwiftNSData : NSData, _SwiftNativeFoundationType { This type provides "copy-on-write" behavior, and is also bridged to the Objective-C `NSData` class. You can wrap an instance of a custom subclass of `NSData` in `struct Data` by converting it using `myData as Data`. - `Data` can be initialized with an `UnsafePointer` and count, an array of `UInt8` (the primitive byte type), or an `UnsafeBufferPointer`. The buffer-oriented functions provide an extra measure of safety by automatically performing the size calculation, as the type is known at compile time. + `Data` can be initialized with an `UnsafeRawPointer` and count, an array of `UInt8` (the primitive byte type), an `UnsafeBufferPointer`,the contents of a file, or base-64 encoded data or strings. The buffer-oriented functions provide an extra measure of safety by automatically performing the size calculation, as the type is known at compile time. */ public struct Data : ReferenceConvertible, CustomStringConvertible, Equatable, Hashable, RandomAccessCollection, MutableCollection, _MutablePairBoxing { /// The Objective-C bridged type of `Data`. @@ -161,7 +161,7 @@ public struct Data : ReferenceConvertible, CustomStringConvertible, Equatable, H case none /// A custom deallocator. - case custom((UnsafeMutablePointer, Int) -> Void) + case custom((UnsafeMutableRawPointer, Int) -> Void) fileprivate var _deallocator : ((UnsafeMutableRawPointer, Int) -> Void)? { switch self { @@ -173,8 +173,7 @@ public struct Data : ReferenceConvertible, CustomStringConvertible, Equatable, H return nil case .custom(let b): return { (ptr, len) in - let bytePtr = ptr.bindMemory(to: UInt8.self, capacity: len) - b(bytePtr, len) + b(ptr, len) } } } @@ -238,7 +237,7 @@ public struct Data : ReferenceConvertible, CustomStringConvertible, Equatable, H /// - parameter bytes: A pointer to the bytes. /// - parameter count: The size of the bytes. /// - parameter deallocator: Specifies the mechanism to free the indicated buffer, or `.none`. - public init(bytesNoCopy bytes: UnsafeMutablePointer, count: Int, deallocator: Deallocator) { + public init(bytesNoCopy bytes: UnsafeMutableRawPointer, count: Int, deallocator: Deallocator) { let whichDeallocator = deallocator._deallocator _wrapped = _SwiftNSData(immutableObject: NSData(bytesNoCopy: bytes, length: count, deallocator: whichDeallocator)) } @@ -348,7 +347,7 @@ public struct Data : ReferenceConvertible, CustomStringConvertible, Equatable, H _mapUnmanaged { $0.getBytes(pointer, length: count) } } - private func _copyBytesHelper(to pointer: UnsafeMutablePointer, from range: NSRange) { + private func _copyBytesHelper(to pointer: UnsafeMutableRawPointer, from range: NSRange) { _mapUnmanaged { $0.getBytes(pointer, range: range) } } @@ -389,7 +388,7 @@ public struct Data : ReferenceConvertible, CustomStringConvertible, Equatable, H guard !copyRange.isEmpty else { return 0 } let nsRange = NSMakeRange(copyRange.lowerBound, copyRange.upperBound - copyRange.lowerBound) - let pointer : UnsafeMutablePointer = UnsafeMutablePointer(buffer.baseAddress!) + let pointer = UnsafeMutableRawPointer(buffer.baseAddress!) _copyBytesHelper(to: pointer, from: nsRange) return copyRange.count } diff --git a/Foundation/NSFileManager.swift b/Foundation/NSFileManager.swift index d6bd93aea5..390cb9cda7 100644 --- a/Foundation/NSFileManager.swift +++ b/Foundation/NSFileManager.swift @@ -252,13 +252,12 @@ public class FileManager: NSObject { } while let entry = readdir(dir!) { - if let entryName = withUnsafePointer(to: &entry.pointee.d_name, { (ptr) -> String? in - return String(cString: UnsafePointer(ptr)) - }) { - // TODO: `entryName` should be limited in length to `entry.memory.d_namlen`. - if entryName != "." && entryName != ".." { - contents.append(entryName) - } + let entryName = withUnsafePointer(to: &entry.pointee.d_name) { + String(cString: UnsafeRawPointer($0).assumingMemoryBound(to: CChar.self)) + } + // TODO: `entryName` should be limited in length to `entry.memory.d_namlen`. + if entryName != "." && entryName != ".." { + contents.append(entryName) } } @@ -294,31 +293,27 @@ public class FileManager: NSObject { var entry = readdir(dir!) while entry != nil { - if let entryName = withUnsafePointer(to: &entry!.pointee.d_name, { (ptr) -> String? in - let int8Ptr = unsafeBitCast(ptr, to: UnsafePointer.self) - return String(cString: int8Ptr) - }) { - // TODO: `entryName` should be limited in length to `entry.memory.d_namlen`. - if entryName != "." && entryName != ".." { - contents.append(entryName) + let entryName = withUnsafePointer(to: &entry!.pointee.d_name) { + String(cString: UnsafeRawPointer($0).assumingMemoryBound(to: CChar.self)) + } + // TODO: `entryName` should be limited in length to `entry.memory.d_namlen`. + if entryName != "." && entryName != ".." { + contents.append(entryName) - if let entryType = withUnsafePointer(to: &entry!.pointee.d_type, { (ptr) -> Int32? in - let int32Ptr = unsafeBitCast(ptr, to: UnsafePointer.self) - return Int32(int32Ptr.pointee) - }) { - #if os(OSX) || os(iOS) - let tempEntryType = entryType - #elseif os(Linux) - let tempEntryType = Int(entryType) - #endif + let entryType = withUnsafePointer(to: &entry!.pointee.d_type) { (ptr) -> Int32 in + return Int32(ptr.pointee) + } + #if os(OSX) || os(iOS) + let tempEntryType = entryType + #elseif os(Linux) + let tempEntryType = Int(entryType) + #endif - if tempEntryType == DT_DIR { - let subPath: String = path + "/" + entryName + if tempEntryType == DT_DIR { + let subPath: String = path + "/" + entryName - let entries = try subpathsOfDirectory(atPath: subPath) - contents.append(contentsOf: entries.map({file in "\(entryName)/\(file)"})) - } - } + let entries = try subpathsOfDirectory(atPath: subPath) + contents.append(contentsOf: entries.map({file in "\(entryName)/\(file)"})) } } @@ -468,7 +463,7 @@ public class FileManager: NSObject { let fsRep = FileManager.default().fileSystemRepresentation(withPath: path) let ps = UnsafeMutablePointer?>.allocate(capacity: 2) - ps.initialize(to: UnsafeMutablePointer(fsRep)) + ps.initialize(to: UnsafeMutablePointer(mutating: fsRep)) ps.advanced(by: 1).initialize(to: nil) let stream = fts_open(ps, FTS_PHYSICAL | FTS_XDEV | FTS_NOCHDIR, nil) ps.deinitialize(count: 2) @@ -914,7 +909,7 @@ extension FileManager { if FileManager.default().fileExists(atPath: path) { let fsRep = FileManager.default().fileSystemRepresentation(withPath: path) let ps = UnsafeMutablePointer?>.allocate(capacity: 2) - ps.initialize(to: UnsafeMutablePointer(fsRep)) + ps.initialize(to: UnsafeMutablePointer(mutating: fsRep)) ps.advanced(by: 1).initialize(to: nil) _stream = fts_open(ps, FTS_PHYSICAL | FTS_XDEV | FTS_NOCHDIR, nil) ps.deinitialize(count: 2) diff --git a/Foundation/NSJSONSerialization.swift b/Foundation/NSJSONSerialization.swift index 927c2ba881..515f3f00fa 100644 --- a/Foundation/NSJSONSerialization.swift +++ b/Foundation/NSJSONSerialization.swift @@ -111,7 +111,8 @@ public class JSONSerialization : NSObject { pretty: opt.contains(.prettyPrinted), writer: { (str: String?) in if let str = str { - result.append(UnsafePointer(str.cString(using: .utf8)!), count: str.lengthOfBytes(using: .utf8)) + let count = str.lengthOfBytes(using: .utf8) + result.append(UnsafeRawPointer(str.cString(using: .utf8)!).bindMemory(to: UInt8.self, capacity: count), count: count) } } ) @@ -635,11 +636,11 @@ private struct JSONReader { func parseNumber(_ input: Index) throws -> (Any, Index)? { func parseTypedNumber(_ address: UnsafePointer, count: Int) -> (Any, IndexDistance)? { let temp_buffer_size = 64 - var temp_buffer = [UInt8](repeating: 0, count: temp_buffer_size) - return temp_buffer.withUnsafeMutableBufferPointer { (buffer: inout UnsafeMutableBufferPointer) -> (Any, IndexDistance)? in + var temp_buffer = [Int8](repeating: 0, count: temp_buffer_size) + return temp_buffer.withUnsafeMutableBufferPointer { (buffer: inout UnsafeMutableBufferPointer) -> (Any, IndexDistance)? in memcpy(buffer.baseAddress!, address, min(count, temp_buffer_size - 1)) // ensure null termination - let startPointer = UnsafePointer(buffer.baseAddress!) + let startPointer = buffer.baseAddress! let intEndPointer = UnsafeMutablePointer?>.allocate(capacity: 1) defer { intEndPointer.deallocate(capacity: 1) } let doubleEndPointer = UnsafeMutablePointer?>.allocate(capacity: 1) diff --git a/Foundation/NSRegularExpression.swift b/Foundation/NSRegularExpression.swift index e353539079..6de454c2d1 100644 --- a/Foundation/NSRegularExpression.swift +++ b/Foundation/NSRegularExpression.swift @@ -130,7 +130,9 @@ internal func _NSRegularExpressionMatch(_ context: UnsafeMutableRawPointer?, ran #endif matcher.block(nil, NSMatchingFlags(rawValue: opts), UnsafeMutablePointer(stop)) } else { - let result = TextCheckingResult.regularExpressionCheckingResultWithRanges(NSRangePointer(ranges!), count: count, regularExpression: matcher.regex) + let result = ranges!.withMemoryRebound(to: NSRange.self, capacity: count) { rangePtr in + TextCheckingResult.regularExpressionCheckingResultWithRanges(rangePtr, count: count, regularExpression: matcher.regex) + } #if os(OSX) || os(iOS) let flags = NSMatchingFlags(rawValue: options.rawValue) #else diff --git a/Foundation/NSString.swift b/Foundation/NSString.swift index dfe3aff5d2..c07eabd3aa 100644 --- a/Foundation/NSString.swift +++ b/Foundation/NSString.swift @@ -469,7 +469,7 @@ extension NSString { var numCharsBuffered = 0 var arrayBuffer = [unichar](repeating: 0, count: 100) let other = str._nsObject - return arrayBuffer.withUnsafeMutablePointerOrAllocation(selfLen, fastpath: UnsafeMutablePointer(_fastContents)) { (selfChars: UnsafeMutablePointer) -> String in + return arrayBuffer.withUnsafeMutablePointerOrAllocation(selfLen, fastpath: UnsafeMutablePointer(mutating: _fastContents)) { (selfChars: UnsafeMutablePointer) -> String in // Now do the binary search. Note that the probe value determines the length of the substring to check. while true { let range = NSMakeRange(0, isLiteral ? probe + 1 : NSMaxRange(rangeOfComposedCharacterSequence(at: probe))) // Extend the end of the composed char sequence @@ -1182,8 +1182,12 @@ extension NSString { } public convenience init?(UTF8String nullTerminatedCString: UnsafePointer) { - let buffer = UnsafeBufferPointer(start: UnsafePointer(nullTerminatedCString), count: Int(strlen(nullTerminatedCString))) - if let str = String._fromCodeUnitSequence(UTF8.self, input: buffer) { + let count = Int(strlen(nullTerminatedCString)) + if let str = nullTerminatedCString.withMemoryRebound(to: UInt8.self, capacity: count, { + let buffer = UnsafeBufferPointer(start: $0, count: count) + return String._fromCodeUnitSequence(UTF8.self, input: buffer) + }) as String? + { self.init(str) } else { return nil diff --git a/Foundation/NSURL.swift b/Foundation/NSURL.swift index c3600a0cba..4bb505d7b9 100644 --- a/Foundation/NSURL.swift +++ b/Foundation/NSURL.swift @@ -488,7 +488,9 @@ public class NSURL: NSObject, NSSecureCoding, NSCopying { /* Returns the URL's path in file system representation. File system representation is a null-terminated C string with canonical UTF-8 encoding. */ public func getFileSystemRepresentation(_ buffer: UnsafeMutablePointer, maxLength maxBufferLength: Int) -> Bool { - return CFURLGetFileSystemRepresentation(_cfObject, true, UnsafeMutablePointer(buffer), maxBufferLength) + return buffer.withMemoryRebound(to: UInt8.self, capacity: maxBufferLength) { + CFURLGetFileSystemRepresentation(_cfObject, true, $0, maxBufferLength) + } } /* Returns the URL's path in file system representation. File system representation is a null-terminated C string with canonical UTF-8 encoding. The returned C string will be automatically freed just as a returned object would be released; your code should copy the representation or use getFileSystemRepresentation:maxLength: if it needs to store the representation outside of the autorelease context in which the representation is created. diff --git a/Foundation/NSXMLElement.swift b/Foundation/NSXMLElement.swift index 649adc160c..13be306e15 100644 --- a/Foundation/NSXMLElement.swift +++ b/Foundation/NSXMLElement.swift @@ -74,8 +74,12 @@ public class XMLElement: XMLNode { @abstract Adds an attribute. Attributes with duplicate names are not added. */ public func addAttribute(_ attribute: XMLNode) { - guard _CFXMLNodeHasProp(_xmlNode, UnsafePointer(_CFXMLNodeGetName(attribute._xmlNode)!)) == nil else { return } - addChild(attribute) + let name = _CFXMLNodeGetName(attribute._xmlNode)! + let len = strlen(name) + name.withMemoryRebound(to: UInt8.self, capacity: Int(len)) { + guard _CFXMLNodeHasProp(_xmlNode, $0) == nil else { return } + addChild(attribute) + } } //primitive /*! diff --git a/Foundation/NSXMLParser.swift b/Foundation/NSXMLParser.swift index dbbf6eab2f..0f094d8caa 100644 --- a/Foundation/NSXMLParser.swift +++ b/Foundation/NSXMLParser.swift @@ -43,7 +43,10 @@ extension XMLParser { } private func UTF8STRING(_ bytes: UnsafePointer) -> String? { - let len = strlen(UnsafePointer(bytes)) + // strlen operates on the wrong type, char*. We can't rebind the memory to a different type without knowing it's length, + // but since we know strlen is in libc, its 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.self)) let str = String._fromCodeUnitSequence(UTF8.self, input: UnsafeBufferPointer(start: bytes, count: Int(len))) return str } @@ -244,9 +247,10 @@ internal func _NSXMLParserStartElementNs(_ ctx: _CFXMLInterface, localname: Unsa let parser = ctx.parser let reportQNameURI = parser.shouldProcessNamespaces let reportNamespaces = parser.shouldReportNamespacePrefixes - let prefixLen = prefix != nil ? UInt(strlen(UnsafePointer(prefix!))) : 0 + // Since strlen is in libc, it's safe to bitcast the UInt8 pointer argument to an Int8 (char *) pointer. + let prefixLen = prefix != nil ? UInt(strlen(unsafeBitCast(prefix!, to: UnsafePointer.self))) : 0 let localnameString = (prefixLen == 0 || reportQNameURI) ? UTF8STRING(localname) : nil - let qualifiedNameString = prefixLen != 0 ? _colonSeparatedStringFromPrefixAndSuffix(prefix!, UInt(prefixLen), localname, UInt(strlen(UnsafePointer(localname)))) : localnameString + let qualifiedNameString = prefixLen != 0 ? _colonSeparatedStringFromPrefixAndSuffix(prefix!, UInt(prefixLen), localname, UInt(strlen(unsafeBitCast(localname, to: UnsafePointer.self)))) : localnameString let namespaceURIString = reportQNameURI ? UTF8STRING(URI) : nil var nsDict = [String:String]() @@ -259,7 +263,7 @@ internal func _NSXMLParserStartElementNs(_ ctx: _CFXMLInterface, localname: Unsa if reportNamespaces { namespaceNameString = UTF8STRING(ns) } - asAttrNamespaceNameString = _colonSeparatedStringFromPrefixAndSuffix("xmlns", 5, ns, UInt(strlen(UnsafePointer(ns)))) + asAttrNamespaceNameString = _colonSeparatedStringFromPrefixAndSuffix("xmlns", 5, ns, UInt(strlen(unsafeBitCast(ns, to: UnsafePointer.self)))) } else { namespaceNameString = "" asAttrNamespaceNameString = "xmlns" @@ -290,9 +294,10 @@ internal func _NSXMLParserStartElementNs(_ ctx: _CFXMLInterface, localname: Unsa var attributeQName: String let attrLocalName = attributes[idx]! let attrPrefix = attributes[idx + 1] - let attrPrefixLen = attrPrefix != nil ? strlen(UnsafePointer(attrPrefix!)) : 0 + // Since strlen is in libc, it's safe to bitcast the UInt8 pointer argument to an Int8 (char *) pointer. + let attrPrefixLen = attrPrefix != nil ? strlen(unsafeBitCast(attrPrefix!, to: UnsafePointer.self)) : 0 if attrPrefixLen != 0 { - attributeQName = _colonSeparatedStringFromPrefixAndSuffix(attrPrefix!, UInt(attrPrefixLen), attrLocalName, UInt(strlen((UnsafePointer(attrLocalName))))) + attributeQName = _colonSeparatedStringFromPrefixAndSuffix(attrPrefix!, UInt(attrPrefixLen), attrLocalName, UInt(strlen((unsafeBitCast(attrLocalName, to: UnsafePointer.self))))) } else { attributeQName = UTF8STRING(attrLocalName)! } @@ -304,10 +309,14 @@ internal func _NSXMLParserStartElementNs(_ ctx: _CFXMLInterface, localname: Unsa let numBytesWithoutTerminator = attributes[idx + 4]! - attributes[idx + 3]! let numBytesWithTerminator = numBytesWithoutTerminator + 1 if numBytesWithoutTerminator != 0 { - var chars = [Int8](repeating: 0, count: numBytesWithTerminator) - attributeValue = chars.withUnsafeMutableBufferPointer({ (buffer: inout UnsafeMutableBufferPointer) -> String in - strncpy(buffer.baseAddress!, UnsafePointer(attributes[idx + 3]!), numBytesWithoutTerminator) //not strlcpy because attributes[i+3] is not Nul terminated - return UTF8STRING(UnsafePointer(buffer.baseAddress!))! + var chars = [UInt8](repeating: 0, count: numBytesWithTerminator) + attributeValue = chars.withUnsafeMutableBufferPointer({ (buffer: inout UnsafeMutableBufferPointer) -> String in + // In Swift code, buffer is alwaus accessed as UInt8. + // Since strncpy is in libc, it's safe to bitcast the UInt8 pointer arguments to an Int8 (char *) pointer. + strncpy(unsafeBitCast(buffer.baseAddress!, to: UnsafeMutablePointer.self), + unsafeBitCast(attributes[idx + 3]!, to: UnsafePointer.self), + numBytesWithoutTerminator) //not strlcpy because attributes[i+3] is not Nul terminated + return UTF8STRING(buffer.baseAddress!)! }) } attrDict[attributeQName] = attributeValue @@ -327,10 +336,10 @@ internal func _NSXMLParserStartElementNs(_ ctx: _CFXMLInterface, localname: Unsa internal func _NSXMLParserEndElementNs(_ ctx: _CFXMLInterface , localname: UnsafePointer, prefix: UnsafePointer?, URI: UnsafePointer) -> Void { let parser = ctx.parser let reportQNameURI = parser.shouldProcessNamespaces - let prefixLen = prefix != nil ? strlen(UnsafePointer(prefix!)) : 0 + let prefixLen = prefix != nil ? strlen(unsafeBitCast(prefix!, to: UnsafePointer.self)) : 0 let localnameString = (prefixLen == 0 || reportQNameURI) ? UTF8STRING(localname) : nil let nilStr: String? = nil - let qualifiedNameString = (prefixLen != 0) ? _colonSeparatedStringFromPrefixAndSuffix(prefix!, UInt(prefixLen), localname, UInt(strlen(UnsafePointer(localname)))) : nilStr + let qualifiedNameString = (prefixLen != 0) ? _colonSeparatedStringFromPrefixAndSuffix(prefix!, UInt(prefixLen), localname, UInt(strlen(unsafeBitCast(localname, to: UnsafePointer.self)))) : nilStr let namespaceURIString = reportQNameURI ? UTF8STRING(URI) : nilStr @@ -543,7 +552,8 @@ public class XMLParser : NSObject { if (totalLength > 4) { let remainingData = allExistingData.withUnsafeBytes { (bytes: UnsafePointer) -> Data in - return Data(bytesNoCopy: UnsafeMutablePointer(bytes.advanced(by: 4)), count: totalLength - 4, deallocator: .none) + let ptr = bytes.advanced(by: 4) + return Data(bytesNoCopy: UnsafeMutablePointer(mutating: ptr), count: totalLength - 4, deallocator: .none) } let _ = parseData(remainingData) @@ -584,7 +594,7 @@ public class XMLParser : NSObject { while result { let chunk = data.withUnsafeBytes { (buffer: UnsafePointer) -> Data in let ptr = buffer.advanced(by: range.location) - return Data(bytesNoCopy: UnsafeMutablePointer(ptr), count: range.length, deallocator: .none) + return Data(bytesNoCopy: UnsafeMutablePointer(mutating: ptr), count: range.length, deallocator: .none) } result = parseData(chunk) if range.location + range.length >= data.count { diff --git a/Foundation/String.swift b/Foundation/String.swift index bc06fe4aba..91e4b783c6 100644 --- a/Foundation/String.swift +++ b/Foundation/String.swift @@ -694,7 +694,7 @@ extension String { freeWhenDone flag: Bool ) { self = NSString( - charactersNoCopy: UnsafeMutablePointer(utf16CodeUnitsNoCopy), + charactersNoCopy: UnsafeMutablePointer(mutating: utf16CodeUnitsNoCopy), length: count, freeWhenDone: flag)._swiftObject } diff --git a/TestFoundation/TestNSData.swift b/TestFoundation/TestNSData.swift index b2b84f692d..b1ef9d68e7 100644 --- a/TestFoundation/TestNSData.swift +++ b/TestFoundation/TestNSData.swift @@ -118,7 +118,7 @@ class TestNSData: XCTestCase { func test_edgeNoCopyDescription() { let expected = "" let bytes = [UInt8](repeating: 0xff, count: 1025) - let data = NSData(bytesNoCopy: UnsafeMutablePointer(bytes), length: bytes.count, freeWhenDone: false) + let data = NSData(bytesNoCopy: UnsafeMutablePointer(mutating: bytes), length: bytes.count, freeWhenDone: false) XCTAssertEqual(data.debugDescription, expected) XCTAssertEqual(data.bytes, bytes) } diff --git a/TestFoundation/TestNSFileManager.swift b/TestFoundation/TestNSFileManager.swift index 7630306b17..9f7c34df36 100644 --- a/TestFoundation/TestNSFileManager.swift +++ b/TestFoundation/TestNSFileManager.swift @@ -107,10 +107,9 @@ class TestNSFileManager : XCTestCase { let str = "☃" let result = FileManager.default().fileSystemRepresentation(withPath: str) XCTAssertNotNil(result) - let uintResult = UnsafePointer(result) - XCTAssertEqual(uintResult[0], 0xE2) - XCTAssertEqual(uintResult[1], 0x98) - XCTAssertEqual(uintResult[2], 0x83) + XCTAssertEqual(UInt8(bitPattern: result[0]), 0xE2) + XCTAssertEqual(UInt8(bitPattern: result[1]), 0x98) + XCTAssertEqual(UInt8(bitPattern: result[2]), 0x83) } func test_fileAttributes() { diff --git a/TestFoundation/TestNSJSONSerialization.swift b/TestFoundation/TestNSJSONSerialization.swift index f364cddb88..75c9f87daa 100644 --- a/TestFoundation/TestNSJSONSerialization.swift +++ b/TestFoundation/TestNSJSONSerialization.swift @@ -759,7 +759,7 @@ extension TestNSJSONSerialization { let data = "12345679".data(using: .utf8)! do { let res = try data.withUnsafeBytes { (bytes: UnsafePointer) -> Any in - let slice = Data(bytesNoCopy: UnsafeMutablePointer(bytes), count: 1, deallocator: .none) + let slice = Data(bytesNoCopy: UnsafeMutablePointer(mutating: bytes), count: 1, deallocator: .none) return try JSONSerialization.jsonObject(with: slice, options: .allowFragments) } if let num = res as? Int { @@ -776,7 +776,7 @@ extension TestNSJSONSerialization { let dict = ["a":["b":1]] do { let buffer = Array(repeating: 0, count: 20) - let outputStream = NSOutputStream(toBuffer: UnsafeMutablePointer(buffer), capacity: 20) + let outputStream = NSOutputStream(toBuffer: UnsafeMutablePointer(mutating: buffer), capacity: 20) outputStream.open() let result = try JSONSerialization.writeJSONObject(dict.bridge(), toStream: outputStream, options: []) outputStream.close() @@ -821,7 +821,7 @@ extension TestNSJSONSerialization { func test_jsonObjectToOutputStreamInsufficeintBuffer() { let dict = ["a":["b":1]] let buffer = Array(repeating: 0, count: 10) - let outputStream = NSOutputStream(toBuffer: UnsafeMutablePointer(buffer), capacity: 20) + let outputStream = NSOutputStream(toBuffer: UnsafeMutablePointer(mutating: buffer), capacity: 20) outputStream.open() do { let result = try JSONSerialization.writeJSONObject(dict.bridge(), toStream: outputStream, options: []) @@ -837,7 +837,7 @@ extension TestNSJSONSerialization { func test_invalidJsonObjectToStreamBuffer() { let str = "Invalid JSON" let buffer = Array(repeating: 0, count: 10) - let outputStream = NSOutputStream(toBuffer: UnsafeMutablePointer(buffer), capacity: 20) + let outputStream = NSOutputStream(toBuffer: UnsafeMutablePointer(mutating: buffer), capacity: 20) outputStream.open() XCTAssertThrowsError(try JSONSerialization.writeJSONObject(str.bridge(), toStream: outputStream, options: [])) } diff --git a/TestFoundation/TestNSKeyedArchiver.swift b/TestFoundation/TestNSKeyedArchiver.swift index 4925199f9b..4eed6bec05 100644 --- a/TestFoundation/TestNSKeyedArchiver.swift +++ b/TestFoundation/TestNSKeyedArchiver.swift @@ -216,8 +216,8 @@ class TestNSKeyedArchiver : XCTestCase { } func test_archive_charptr() { - let charArray = [UInt8]("Hello world, we are testing!\0".utf8) - var charPtr = UnsafeMutablePointer(charArray) + let charArray = [CChar]("Hello world, we are testing!\0".utf8CString) + var charPtr = UnsafeMutablePointer(mutating: charArray) test_archive({ archiver -> Bool in let value = NSValue(bytes: &charPtr, objCType: "*") diff --git a/TestFoundation/TestNSStream.swift b/TestFoundation/TestNSStream.swift index 790c65b37a..f08adf70ba 100644 --- a/TestFoundation/TestNSStream.swift +++ b/TestFoundation/TestNSStream.swift @@ -147,7 +147,7 @@ class TestNSStream : XCTestCase { var buffer = Array(repeating: 0, count: 12) var myString = "Hello world!" let encodedData = [UInt8](myString.utf8) - let outputStream = NSOutputStream(toBuffer: UnsafeMutablePointer(buffer), capacity: 12) + let outputStream = NSOutputStream(toBuffer: UnsafeMutablePointer(mutating: buffer), capacity: 12) XCTAssertEqual(Stream.Status.notOpen, outputStream.streamStatus) outputStream.open() XCTAssertEqual(Stream.Status.open, outputStream.streamStatus) @@ -190,7 +190,7 @@ class TestNSStream : XCTestCase { //verify the data written let dataWritten = outputStream.propertyForKey(NSStreamDataWrittenToMemoryStreamKey) if let nsdataWritten = dataWritten as? NSData { - nsdataWritten.getBytes(UnsafeMutablePointer(buffer), length: result!) + nsdataWritten.getBytes(UnsafeMutablePointer(mutating: buffer), length: result!) XCTAssertEqual(NSString(bytes: &buffer, length: buffer.count, encoding: String.Encoding.utf8.rawValue), myString._bridgeToObject()) outputStream.close() } else { @@ -202,7 +202,7 @@ class TestNSStream : XCTestCase { let buffer = Array(repeating: 0, count: 12) var myString = "Welcome To Hello world !" let encodedData = [UInt8](myString.utf8) - let outputStream = NSOutputStream(toBuffer: UnsafeMutablePointer(buffer), capacity: 12) + let outputStream = NSOutputStream(toBuffer: UnsafeMutablePointer(mutating: buffer), capacity: 12) outputStream.open() XCTAssertTrue(outputStream.hasSpaceAvailable) _ = outputStream.write(encodedData, maxLength: encodedData.count) diff --git a/TestFoundation/TestNSTask.swift b/TestFoundation/TestNSTask.swift index c109cb2089..5321dcca04 100644 --- a/TestFoundation/TestNSTask.swift +++ b/TestFoundation/TestNSTask.swift @@ -251,7 +251,7 @@ private func mkstemp(template: String, body: @noescape (FileHandle) throws -> Vo let url = try! URL(fileURLWithPath: NSTemporaryDirectory()).appendingPathComponent("TestNSTask.XXXXXX") var buffer = [Int8](repeating: 0, count: Int(PATH_MAX)) try url.withUnsafeFileSystemRepresentation { - switch mkstemp(UnsafeMutablePointer($0)) { + switch mkstemp(UnsafeMutablePointer(mutating: $0)) { case -1: XCTFail("Could not create temporary file") case let fd: defer { unlink(&buffer) } diff --git a/TestFoundation/TestNSValue.swift b/TestFoundation/TestNSValue.swift index 9db7d14cbd..6d55d6cda8 100644 --- a/TestFoundation/TestNSValue.swift +++ b/TestFoundation/TestNSValue.swift @@ -120,7 +120,7 @@ class TestNSValue : XCTestCase { func test_valueWithCharPtr() { let charArray = [UInt8]("testing123".utf8) - var charPtr = UnsafeMutablePointer(charArray) + var charPtr = UnsafeMutablePointer(mutating: charArray) var expectedPtr: UnsafeMutablePointer? = nil NSValue(bytes: &charPtr, objCType: "*").getValue(&expectedPtr)