diff --git a/Foundation/Data.swift b/Foundation/Data.swift index 9cb570fa8f..284250bafa 100644 --- a/Foundation/Data.swift +++ b/Foundation/Data.swift @@ -16,11 +16,11 @@ import Darwin import Glibc #endif -internal func __NSDataInvokeDeallocatorUnmap(_ mem: UnsafeMutablePointer, _ length: Int) -> Void { +internal func __NSDataInvokeDeallocatorUnmap(_ mem: UnsafeMutableRawPointer, _ length: Int) -> Void { munmap(mem, length) } -internal func __NSDataInvokeDeallocatorFree(_ mem: UnsafeMutablePointer, _ length: Int) -> Void { +internal func __NSDataInvokeDeallocatorFree(_ mem: UnsafeMutableRawPointer, _ length: Int) -> Void { free(mem) } @@ -34,14 +34,14 @@ internal final class _SwiftNSData : NSData, _SwiftNativeFoundationType { // Take ownership. __wrapped = .Immutable(Unmanaged.passRetained(_unsafeReferenceCast(immutableObject, to: ImmutableType.self))) - let dummyPointer = unsafeBitCast(NSData.self, to: UnsafeMutablePointer.self) + let dummyPointer = unsafeBitCast(NSData.self, to: UnsafeMutableRawPointer.self) super.init(bytes: dummyPointer, length: 0, copy: false, deallocator: nil) } init(mutableObject: AnyObject) { // Take ownership. __wrapped = .Mutable(Unmanaged.passRetained(_unsafeReferenceCast(mutableObject, to: MutableType.self))) - let dummyPointer = unsafeBitCast(NSData.self, to: UnsafeMutablePointer.self) + let dummyPointer = unsafeBitCast(NSData.self, to: UnsafeMutableRawPointer.self) super.init(bytes: dummyPointer, length: 0, copy: false, deallocator: nil) } @@ -49,7 +49,7 @@ internal final class _SwiftNSData : NSData, _SwiftNativeFoundationType { // Take ownership. __wrapped = .Immutable(unmanagedImmutableObject) - let dummyPointer = unsafeBitCast(NSData.self, to: UnsafeMutablePointer.self) + let dummyPointer = unsafeBitCast(NSData.self, to: UnsafeMutableRawPointer.self) super.init(bytes: dummyPointer, length: 0, copy: false, deallocator: nil) } @@ -57,7 +57,7 @@ internal final class _SwiftNSData : NSData, _SwiftNativeFoundationType { // Take ownership. __wrapped = .Mutable(unmanagedMutableObject) - let dummyPointer = unsafeBitCast(NSData.self, to: UnsafeMutablePointer.self) + let dummyPointer = unsafeBitCast(NSData.self, to: UnsafeMutableRawPointer.self) super.init(bytes: dummyPointer, length: 0, copy: false, deallocator: nil) } @@ -82,7 +82,7 @@ internal final class _SwiftNSData : NSData, _SwiftNativeFoundationType { } } - override var bytes : UnsafePointer { + override var bytes : UnsafeRawPointer { return _mapUnmanaged { $0.bytes } } @@ -90,11 +90,11 @@ internal final class _SwiftNSData : NSData, _SwiftNativeFoundationType { // return _mapUnmanaged { $0.subdata(with: range) } // } // -// override func getBytes(_ buffer: UnsafeMutablePointer, length: Int) { +// override func getBytes(_ buffer: UnsafeMutableRawPointer, length: Int) { // return _mapUnmanaged { $0.getBytes(buffer, length: length) } // } // -// override func getBytes(_ buffer: UnsafeMutablePointer, range: NSRange) { +// override func getBytes(_ buffer: UnsafeMutableRawPointer, range: NSRange) { // return _mapUnmanaged { $0.getBytes(buffer, range: range) } // } // @@ -112,7 +112,7 @@ internal final class _SwiftNSData : NSData, _SwiftNativeFoundationType { // } // } // -// override func enumerateByteRanges(using block: @noescape (UnsafePointer, NSRange, UnsafeMutablePointer) -> Void) { +// override func enumerateByteRanges(using block: @noescape (UnsafeRawPointer, NSRange, UnsafeMutablePointer) -> Void) { // return _mapUnmanaged { $0.enumerateBytes(block) } // } // @@ -163,7 +163,7 @@ public struct Data : ReferenceConvertible, CustomStringConvertible, Equatable, H /// A custom deallocator. case custom((UnsafeMutablePointer, Int) -> Void) - fileprivate var _deallocator : ((UnsafeMutablePointer, Int) -> Void)? { + fileprivate var _deallocator : ((UnsafeMutableRawPointer, Int) -> Void)? { switch self { case .unmap: return { __NSDataInvokeDeallocatorUnmap($0, $1) } @@ -173,7 +173,8 @@ public struct Data : ReferenceConvertible, CustomStringConvertible, Equatable, H return nil case .custom(let b): return { (ptr, len) in - b(UnsafeMutablePointer(ptr), len) + let bytePtr = ptr.bindMemory(to: UInt8.self, capacity: len) + b(bytePtr, len) } } } @@ -186,7 +187,7 @@ public struct Data : ReferenceConvertible, CustomStringConvertible, Equatable, H /// /// - parameter bytes: A pointer to the memory. It will be copied. /// - parameter count: The number of bytes to copy. - public init(bytes: UnsafePointer, count: Int) { + public init(bytes: UnsafeRawPointer, count: Int) { _wrapped = _SwiftNSData(immutableObject: NSData(bytes: bytes, length: count)) } @@ -279,8 +280,8 @@ public struct Data : ReferenceConvertible, CustomStringConvertible, Equatable, H } public init?(count: Int) { - if let memory = malloc(count) { - self.init(bytesNoCopy: UnsafeMutablePointer(memory), count: count, deallocator: .free) + if let memory = malloc(count)?.bindMemory(to: UInt8.self, capacity: count) { + self.init(bytesNoCopy: memory, count: count, deallocator: .free) } else { return nil } @@ -304,7 +305,7 @@ public struct Data : ReferenceConvertible, CustomStringConvertible, Equatable, H } } - private func _getUnsafeBytesPointer() -> UnsafePointer { + private func _getUnsafeBytesPointer() -> UnsafeRawPointer { return _mapUnmanaged { return $0.bytes } } @@ -314,10 +315,11 @@ public struct Data : ReferenceConvertible, CustomStringConvertible, Equatable, H public func withUnsafeBytes(_ body: @noescape (UnsafePointer) throws -> ResultType) rethrows -> ResultType { let bytes = _getUnsafeBytesPointer() defer { _fixLifetime(self)} - return try body(UnsafePointer(bytes)) + let contentPtr = bytes.bindMemory(to: ContentType.self, capacity: count / strideof(ContentType.self)) + return try body(contentPtr) } - private mutating func _getUnsafeMutableBytesPointer() -> UnsafeMutablePointer { + private mutating func _getUnsafeMutableBytesPointer() -> UnsafeMutableRawPointer { return _applyUnmanagedMutation { return $0.mutableBytes } @@ -330,7 +332,8 @@ public struct Data : ReferenceConvertible, CustomStringConvertible, Equatable, H public mutating func withUnsafeMutableBytes(_ body: @noescape (UnsafeMutablePointer) throws -> ResultType) rethrows -> ResultType { let mutableBytes = _getUnsafeMutableBytesPointer() defer { _fixLifetime(self)} - return try body(UnsafeMutablePointer(mutableBytes)) + let contentPtr = mutableBytes.bindMemory(to: ContentType.self, capacity: count / strideof(ContentType.self)) + return try body(contentPtr) } // MARK: - @@ -437,7 +440,8 @@ public struct Data : ReferenceConvertible, CustomStringConvertible, Equatable, H _mapUnmanaged { $0.enumerateBytes { (ptr, range, stop) in var stopv = false - block(buffer: UnsafeBufferPointer(start: UnsafePointer(ptr), count: range.length), byteIndex: range.length, stop: &stopv) + let bytePtr = ptr.bindMemory(to: UInt8.self, capacity: range.length) + block(buffer: UnsafeBufferPointer(start: bytePtr, count: range.length), byteIndex: range.length, stop: &stopv) if stopv { stop.pointee = true } diff --git a/Foundation/IndexPath.swift b/Foundation/IndexPath.swift index b88fb14335..b9e357fb79 100644 --- a/Foundation/IndexPath.swift +++ b/Foundation/IndexPath.swift @@ -158,7 +158,7 @@ public struct IndexPath : ReferenceConvertible, Equatable, Hashable, MutableColl if count == 0 { _indexes = [] } else { - var ptr = UnsafeMutablePointer(malloc(count * sizeof(Element.self))) + var ptr = malloc(count * sizeof(Element.self))?.bindMemory(to: Element.self, capacity: count * sizeof(Element.self)) defer { free(ptr) } nsIndexPath.getIndexes(ptr!, range: NSMakeRange(0, count)) diff --git a/Foundation/NSArray.swift b/Foundation/NSArray.swift index 12636b3d41..483a428583 100644 --- a/Foundation/NSArray.swift +++ b/Foundation/NSArray.swift @@ -70,7 +70,7 @@ public class NSArray : NSObject, NSCopying, NSMutableCopying, NSSecureCoding, NS // because that's the way the code was originally written, unless // we go to a new version of the class, which has its own problems. withUnsafeMutablePointer(&cnt) { (ptr: UnsafeMutablePointer) -> Void in - aDecoder.decodeValue(ofObjCType: "i", at: UnsafeMutablePointer(ptr)) + aDecoder.decodeValue(ofObjCType: "i", at: UnsafeMutableRawPointer(ptr)) } let objects = UnsafeMutablePointer.allocate(capacity: Int(cnt)) for idx in 0..?) -> Int, context: UnsafeMutablePointer?) -> [AnyObject] { + public func sortedArray(_ comparator: @noescape @convention(c) (AnyObject, AnyObject, UnsafeMutableRawPointer?) -> Int, context: UnsafeMutableRawPointer?) -> [AnyObject] { return sortedArray([]) { lhs, rhs in return ComparisonResult(rawValue: comparator(lhs, rhs, context))! } } - public func sortedArray(_ comparator: @noescape @convention(c) (AnyObject, AnyObject, UnsafeMutablePointer?) -> Int, context: UnsafeMutablePointer?, hint: Data?) -> [AnyObject] { + public func sortedArray(_ comparator: @noescape @convention(c) (AnyObject, AnyObject, UnsafeMutableRawPointer?) -> Int, context: UnsafeMutableRawPointer?, hint: Data?) -> [AnyObject] { return sortedArray([]) { lhs, rhs in return ComparisonResult(rawValue: comparator(lhs, rhs, context))! } @@ -834,7 +834,7 @@ public class NSMutableArray : NSArray { } } - public func sortUsingFunction(_ compare: @convention(c) (AnyObject, AnyObject, UnsafeMutablePointer?) -> Int, context: UnsafeMutablePointer?) { + public func sortUsingFunction(_ compare: @convention(c) (AnyObject, AnyObject, UnsafeMutableRawPointer?) -> Int, context: UnsafeMutableRawPointer?) { self.setArray(self.sortedArray(compare, context: context)) } diff --git a/Foundation/NSCFArray.swift b/Foundation/NSCFArray.swift index 6e166a41f9..9734a458df 100644 --- a/Foundation/NSCFArray.swift +++ b/Foundation/NSCFArray.swift @@ -34,7 +34,7 @@ internal final class _NSCFArray : NSMutableArray { } override func insert(_ anObject: AnyObject, at index: Int) { - CFArrayInsertValueAtIndex(_cfMutableObject, index, unsafeBitCast(anObject, to: UnsafePointer.self)) + CFArrayInsertValueAtIndex(_cfMutableObject, index, unsafeBitCast(anObject, to: UnsafeRawPointer.self)) } override func removeObject(at index: Int) { diff --git a/Foundation/NSCFDictionary.swift b/Foundation/NSCFDictionary.swift index ed3ac3f1ca..af24b86661 100644 --- a/Foundation/NSCFDictionary.swift +++ b/Foundation/NSCFDictionary.swift @@ -37,7 +37,7 @@ internal final class _NSCFDictionary : NSMutableDictionary { } override func objectForKey(_ aKey: AnyObject) -> AnyObject? { - let value = CFDictionaryGetValue(_cfObject, unsafeBitCast(aKey, to: UnsafePointer.self)) + let value = CFDictionaryGetValue(_cfObject, unsafeBitCast(aKey, to: UnsafeRawPointer.self)) if value != nil { return unsafeBitCast(value, to: AnyObject.self) } else { @@ -64,7 +64,7 @@ internal final class _NSCFDictionary : NSMutableDictionary { let cf = dict._cfObject count = CFDictionaryGetCount(cf) - let keys = UnsafeMutablePointer?>.allocate(capacity: count) + let keys = UnsafeMutablePointer.allocate(capacity: count) CFDictionaryGetKeysAndValues(cf, keys, nil) for idx in 0...self)) + CFDictionaryRemoveValue(_cfMutableObject, unsafeBitCast(aKey, to: UnsafeRawPointer.self)) } override func setObject(_ anObject: AnyObject, forKey aKey: NSObject) { - CFDictionarySetValue(_cfMutableObject, unsafeBitCast(aKey, to: UnsafePointer.self), unsafeBitCast(anObject, to: UnsafePointer.self)) + CFDictionarySetValue(_cfMutableObject, unsafeBitCast(aKey, to: UnsafeRawPointer.self), unsafeBitCast(anObject, to: UnsafeRawPointer.self)) } override var classForCoder: AnyClass { @@ -152,7 +152,7 @@ internal func _CFSwiftDictionaryGetValuesAndKeys(_ dictionary: AnyObject, valueb } } -internal func _CFSwiftDictionaryApplyFunction(_ dictionary: AnyObject, applier: @convention(c) (AnyObject, AnyObject, UnsafeMutablePointer) -> Void, context: UnsafeMutablePointer) { +internal func _CFSwiftDictionaryApplyFunction(_ dictionary: AnyObject, applier: @convention(c) (AnyObject, AnyObject, UnsafeMutableRawPointer) -> Void, context: UnsafeMutableRawPointer) { (dictionary as! NSDictionary).enumerateKeysAndObjects([]) { key, value, _ in applier(key, value, context) } diff --git a/Foundation/NSCFString.swift b/Foundation/NSCFString.swift index 4eba1d49ef..59068221cf 100644 --- a/Foundation/NSCFString.swift +++ b/Foundation/NSCFString.swift @@ -59,13 +59,14 @@ internal class _NSCFString : NSMutableString { internal final class _NSCFConstantString : _NSCFString { internal var _ptr : UnsafePointer { - let ptr = unsafeAddress(of: self) + sizeof(OpaquePointer.self) + sizeof(Int32.self) + sizeof(Int32.self) + sizeof(_CFInfo.self) - return UnsafePointer>(ptr).pointee + let offset = sizeof(OpaquePointer.self) + sizeof(Int32.self) + sizeof(Int32.self) + sizeof(_CFInfo.self) + let ptr = Unmanaged.passUnretained(self).toOpaque() + return ptr.load(fromByteOffset: offset, as: UnsafePointer.self) } internal var _length : UInt32 { let offset = sizeof(OpaquePointer.self) + sizeof(Int32.self) + sizeof(Int32.self) + sizeof(_CFInfo.self) + sizeof(UnsafePointer.self) - let ptr = unsafeAddress(of: self) + offset - return UnsafePointer(ptr).pointee + let ptr = Unmanaged.passUnretained(self).toOpaque() + return ptr.load(fromByteOffset: offset, as: UInt32.self) } required init(characters: UnsafePointer, length: Int) { diff --git a/Foundation/NSCache.swift b/Foundation/NSCache.swift index 057cfdb3ca..f1e83f2cfd 100644 --- a/Foundation/NSCache.swift +++ b/Foundation/NSCache.swift @@ -22,7 +22,7 @@ public class Cache: NSObject { } } - private var _entries = Dictionary, NSCacheEntry>() + private var _entries = Dictionary() private let _lock = Lock() private var _totalCost = 0 private var _byCost: NSCacheEntry? @@ -41,7 +41,7 @@ public class Cache: NSObject { public func object(forKey key: AnyObject) -> AnyObject? { var object: AnyObject? - let keyRef = unsafeBitCast(key, to: UnsafePointer.self) + let keyRef = unsafeBitCast(key, to: UnsafeRawPointer.self) _lock.lock() if let entry = _entries[keyRef] { @@ -84,7 +84,7 @@ public class Cache: NSObject { } public func setObject(_ obj: AnyObject, forKey key: AnyObject, cost g: Int) { - let keyRef = unsafeBitCast(key, to: UnsafePointer.self) + let keyRef = unsafeBitCast(key, to: UnsafeRawPointer.self) _lock.lock() _totalCost += g @@ -152,13 +152,13 @@ public class Cache: NSObject { _lock.lock() for entry in toRemove { - _entries.removeValue(forKey: unsafeBitCast(entry.key, to: UnsafePointer.self)) // the cost list is already fixed up in the purge routines + _entries.removeValue(forKey: unsafeBitCast(entry.key, to: UnsafeRawPointer.self)) // the cost list is already fixed up in the purge routines } _lock.unlock() } public func removeObject(forKey key: AnyObject) { - let keyRef = unsafeBitCast(key, to: UnsafePointer.self) + let keyRef = unsafeBitCast(key, to: UnsafeRawPointer.self) _lock.lock() if let entry = _entries.removeValue(forKey: keyRef) { diff --git a/Foundation/NSCalendar.swift b/Foundation/NSCalendar.swift index 9747e99ddc..84c355cdc9 100644 --- a/Foundation/NSCalendar.swift +++ b/Foundation/NSCalendar.swift @@ -100,11 +100,11 @@ extension Calendar { public class Calendar: NSObject, NSCopying, NSSecureCoding { typealias CFType = CFCalendar private var _base = _CFInfo(typeID: CFCalendarGetTypeID()) - private var _identifier: UnsafeMutablePointer? = nil - private var _locale: UnsafeMutablePointer? = nil - private var _localeID: UnsafeMutablePointer? = nil - private var _tz: UnsafeMutablePointer? = nil - private var _cal: UnsafeMutablePointer? = nil + private var _identifier: UnsafeMutableRawPointer? = nil + private var _locale: UnsafeMutableRawPointer? = nil + private var _localeID: UnsafeMutableRawPointer? = nil + private var _tz: UnsafeMutableRawPointer? = nil + private var _cal: UnsafeMutableRawPointer? = nil internal var _cfObject: CFType { return unsafeBitCast(self, to: CFCalendar.self) diff --git a/Foundation/NSCharacterSet.swift b/Foundation/NSCharacterSet.swift index 75770deff2..a4e4289f4a 100644 --- a/Foundation/NSCharacterSet.swift +++ b/Foundation/NSCharacterSet.swift @@ -33,9 +33,9 @@ public class NSCharacterSet : NSObject, NSCopying, NSMutableCopying, NSCoding { typealias CFType = CFCharacterSet private var _base = _CFInfo(typeID: CFCharacterSetGetTypeID()) private var _hashValue = CFHashCode(0) - private var _buffer: UnsafeMutablePointer? = nil + private var _buffer: UnsafeMutableRawPointer? = nil private var _length = CFIndex(0) - private var _annex: UnsafeMutablePointer? = nil + private var _annex: UnsafeMutableRawPointer? = nil internal var _cfObject: CFType { return unsafeBitCast(self, to: CFType.self) diff --git a/Foundation/NSCoder.swift b/Foundation/NSCoder.swift index 901a69ab74..602f3679f3 100644 --- a/Foundation/NSCoder.swift +++ b/Foundation/NSCoder.swift @@ -17,16 +17,16 @@ public protocol NSSecureCoding : NSCoding { } public class NSCoder : NSObject { - internal var _pendingBuffers = Array<(UnsafeMutablePointer, Int)>() + internal var _pendingBuffers = Array<(UnsafeMutableRawPointer, Int)>() deinit { for buffer in _pendingBuffers { - buffer.0.deinitialize() - buffer.0.deallocate(capacity: buffer.1) + // Cannot deinitialize a pointer to unknown type. + buffer.0.deallocate(bytes: buffer.1, alignedTo: alignof(Int.self)) } } - public func encodeValue(ofObjCType type: UnsafePointer, at addr: UnsafePointer) { + public func encodeValue(ofObjCType type: UnsafePointer, at addr: UnsafeRawPointer) { NSRequiresConcreteImplementation() } @@ -34,7 +34,7 @@ public class NSCoder : NSObject { NSRequiresConcreteImplementation() } - public func decodeValue(ofObjCType type: UnsafePointer, at data: UnsafeMutablePointer) { + public func decodeValue(ofObjCType type: UnsafePointer, at data: UnsafeMutableRawPointer) { NSRequiresConcreteImplementation() } @@ -100,7 +100,7 @@ public class NSCoder : NSObject { public func encode(_ object: AnyObject?) { var object = object withUnsafePointer(&object) { (ptr: UnsafePointer) -> Void in - encodeValue(ofObjCType: "@", at: unsafeBitCast(ptr, to: UnsafePointer.self)) + encodeValue(ofObjCType: "@", at: unsafeBitCast(ptr, to: UnsafeRawPointer.self)) } } @@ -120,18 +120,18 @@ public class NSCoder : NSObject { encode(object) } - public func encodeArray(ofObjCType type: UnsafePointer, count: Int, at array: UnsafePointer) { + public func encodeArray(ofObjCType type: UnsafePointer, count: Int, at array: UnsafeRawPointer) { encodeValue(ofObjCType: "[\(count)\(String(cString: type))]", at: array) } - public func encodeBytes(_ byteaddr: UnsafePointer?, length: Int) { + public func encodeBytes(_ byteaddr: UnsafeRawPointer?, length: Int) { var newLength = UInt32(length) withUnsafePointer(&newLength) { (ptr: UnsafePointer) -> Void in encodeValue(ofObjCType: "I", at: ptr) } var empty: [Int8] = [] withUnsafePointer(&empty) { - encodeArray(ofObjCType: "c", count: length, at: byteaddr ?? UnsafePointer($0)) + encodeArray(ofObjCType: "c", count: length, at: byteaddr ?? UnsafeRawPointer($0)) } } @@ -142,24 +142,24 @@ public class NSCoder : NSObject { var obj: AnyObject? = nil withUnsafeMutablePointer(&obj) { (ptr: UnsafeMutablePointer) -> Void in - decodeValue(ofObjCType: "@", at: unsafeBitCast(ptr, to: UnsafeMutablePointer.self)) + decodeValue(ofObjCType: "@", at: unsafeBitCast(ptr, to: UnsafeMutableRawPointer.self)) } return obj } - public func decodeArray(ofObjCType itemType: UnsafePointer, count: Int, at array: UnsafeMutablePointer) { + public func decodeArray(ofObjCType itemType: UnsafePointer, count: Int, at array: UnsafeMutableRawPointer) { decodeValue(ofObjCType: "[\(count)\(String(cString: itemType))]", at: array) } /* // TODO: This is disabled, as functions which return unsafe interior pointers are inherently unsafe when we have no autorelease pool. - public func decodeBytes(withReturnedLength lengthp: UnsafeMutablePointer) -> UnsafeMutablePointer? { + public func decodeBytes(withReturnedLength lengthp: UnsafeMutablePointer) -> UnsafeMutableRawPointer? { var length: UInt32 = 0 withUnsafeMutablePointer(&length) { (ptr: UnsafeMutablePointer) -> Void in - decodeValue(ofObjCType: "I", at: unsafeBitCast(ptr, to: UnsafeMutablePointer.self)) + decodeValue(ofObjCType: "I", at: unsafeBitCast(ptr, to: UnsafeMutableRawPointer.self)) } // we cannot autorelease here so instead the pending buffers will manage the lifespan of the returned data... this is wasteful but good enough... - let result = UnsafeMutablePointer.allocate(capacity: Int(length)) + let result = UnsafeMutableRawPointer.allocate(bytes: Int(length), alignedTo: alignof(Int.self)) decodeValue(ofObjCType: "c", at: result) lengthp.pointee = Int(length) _pendingBuffers.append((result, Int(length))) diff --git a/Foundation/NSConcreteValue.swift b/Foundation/NSConcreteValue.swift index 55bde6e72c..f801b7201a 100644 --- a/Foundation/NSConcreteValue.swift +++ b/Foundation/NSConcreteValue.swift @@ -71,9 +71,9 @@ internal class NSConcreteValue : NSValue { private static var _cachedTypeInfoLock = Lock() private var _typeInfo : TypeInfo - private var _storage : UnsafeMutablePointer + private var _storage : UnsafeMutableRawPointer - required init(bytes value: UnsafePointer, objCType type: UnsafePointer) { + required init(bytes value: UnsafeRawPointer, objCType type: UnsafePointer) { let spec = String(cString: type) var typeInfo : TypeInfo? = nil @@ -91,17 +91,17 @@ internal class NSConcreteValue : NSValue { self._typeInfo = typeInfo! - self._storage = UnsafeMutablePointer.allocate(capacity: self._typeInfo.size) - self._storage.initialize(from: unsafeBitCast(value, to: UnsafeMutablePointer.self), count: self._typeInfo.size) + self._storage = UnsafeMutableRawPointer.allocate(bytes: self._typeInfo.size, alignedTo: 1) + self._storage.copyBytes(from: value, count: self._typeInfo.size) } deinit { - self._storage.deinitialize(count: self._size) - self._storage.deallocate(capacity: self._size) + // Cannot deinitialize raw memory. + self._storage.deallocate(bytes: self._size, alignedTo: 1) } - override func getValue(_ value: UnsafeMutablePointer) { - UnsafeMutablePointer(value).moveInitialize(from: unsafeBitCast(self._storage, to: UnsafeMutablePointer.self), count: self._size) + override func getValue(_ value: UnsafeMutableRawPointer) { + value.copyBytes(from: self._storage, count: self._size) } override var objCType : UnsafePointer { @@ -145,8 +145,8 @@ internal class NSConcreteValue : NSValue { return self._typeInfo.size } - private var value : UnsafeMutablePointer { - return unsafeBitCast(self._storage, to: UnsafeMutablePointer.self) + private var value : UnsafeMutableRawPointer { + return self._storage } private func _isEqualToValue(_ other: NSConcreteValue) -> Bool { diff --git a/Foundation/NSData.swift b/Foundation/NSData.swift index ac6a210184..2ec31fc3a2 100644 --- a/Foundation/NSData.swift +++ b/Foundation/NSData.swift @@ -61,7 +61,7 @@ extension NSData { } private final class _NSDataDeallocator { - var handler: (UnsafeMutablePointer, Int) -> Void = {_,_ in } + var handler: (UnsafeMutableRawPointer, Int) -> Void = {_,_ in } } private let __kCFMutable: CFOptionFlags = 0x01 @@ -77,7 +77,7 @@ public class NSData : NSObject, NSCopying, NSMutableCopying, NSSecureCoding { private var _base = _CFInfo(typeID: CFDataGetTypeID()) private var _length: CFIndex = 0 private var _capacity: CFIndex = 0 - private var _deallocator: UnsafeMutablePointer? = nil // for CF only + private var _deallocator: UnsafeMutableRawPointer? = nil // for CF only private var _deallocHandler: _NSDataDeallocator? = _NSDataDeallocator() // for Swift private var _bytes: UnsafeMutablePointer? = nil @@ -85,12 +85,13 @@ public class NSData : NSObject, NSCopying, NSMutableCopying, NSSecureCoding { if self.dynamicType === NSData.self || self.dynamicType === NSMutableData.self { return unsafeBitCast(self, to: CFType.self) } else { - return CFDataCreate(kCFAllocatorSystemDefault, UnsafePointer(self.bytes), self.length) + let bytePtr = self.bytes.bindMemory(to: UInt8.self, capacity: self.length) + return CFDataCreate(kCFAllocatorSystemDefault, bytePtr, self.length) } } public override required convenience init() { - let dummyPointer = unsafeBitCast(NSData.self, to: UnsafeMutablePointer.self) + let dummyPointer = unsafeBitCast(NSData.self, to: UnsafeMutableRawPointer.self) self.init(bytes: dummyPointer, length: 0, copy: false, deallocator: nil) } @@ -115,11 +116,12 @@ public class NSData : NSObject, NSCopying, NSMutableCopying, NSSecureCoding { } } - internal init(bytes: UnsafeMutablePointer?, length: Int, copy: Bool, deallocator: ((UnsafeMutablePointer, Int) -> Void)?) { + internal init(bytes: UnsafeMutableRawPointer?, length: Int, copy: Bool, deallocator: ((UnsafeMutableRawPointer, Int) -> Void)?) { super.init() let options : CFOptionFlags = (self.dynamicType == NSMutableData.self) ? __kCFMutable | __kCFGrowable : 0x0 + let bytePtr = bytes?.bindMemory(to: UInt8.self, capacity: length) if copy { - _CFDataInit(unsafeBitCast(self, to: CFMutableData.self), options, length, UnsafeMutablePointer(bytes), length, false) + _CFDataInit(unsafeBitCast(self, to: CFMutableData.self), options, length, bytePtr, length, false) if let handler = deallocator { handler(bytes!, length) } @@ -128,7 +130,7 @@ public class NSData : NSObject, NSCopying, NSMutableCopying, NSSecureCoding { _deallocHandler!.handler = handler } // The data initialization should flag that CF should not deallocate which leaves the handler a chance to deallocate instead - _CFDataInit(unsafeBitCast(self, to: CFMutableData.self), options | __kCFDontDeallocate, length, UnsafeMutablePointer(bytes), length, true) + _CFDataInit(unsafeBitCast(self, to: CFMutableData.self), options | __kCFDontDeallocate, length, bytePtr, length, true) } } @@ -136,8 +138,8 @@ public class NSData : NSObject, NSCopying, NSMutableCopying, NSSecureCoding { return CFDataGetLength(_cfObject) } - public var bytes: UnsafePointer { - return UnsafePointer(CFDataGetBytePtr(_cfObject)) + public var bytes: UnsafeRawPointer { + return UnsafeRawPointer(CFDataGetBytePtr(_cfObject)) } public override func copy() -> AnyObject { @@ -153,14 +155,15 @@ public class NSData : NSObject, NSCopying, NSMutableCopying, NSSecureCoding { } public func mutableCopy(with zone: NSZone? = nil) -> AnyObject { - return NSMutableData(bytes: UnsafeMutablePointer(bytes), length: length, copy: true, deallocator: nil) + return NSMutableData(bytes: UnsafeMutableRawPointer(mutating: bytes), length: length, copy: true, deallocator: nil) } public func encode(with aCoder: NSCoder) { if let aKeyedCoder = aCoder as? NSKeyedArchiver { aKeyedCoder._encodePropertyList(self, forKey: "NS.data") } else { - aCoder.encodeBytes(UnsafePointer(self.bytes), length: self.length) + let bytePtr = self.bytes.bindMemory(to: UInt8.self, capacity: self.length) + aCoder.encodeBytes(bytePtr, length: self.length) } } @@ -193,7 +196,6 @@ public class NSData : NSObject, NSCopying, NSMutableCopying, NSSecureCoding { private func byteDescription(limit: Int? = nil) -> String { var s = "" - let buffer = UnsafePointer(bytes) var i = 0 while i < self.length { if i > 0 && i % 4 == 0 { @@ -201,7 +203,7 @@ public class NSData : NSObject, NSCopying, NSMutableCopying, NSSecureCoding { if let limit = limit where self.length > limit && i == self.length - (limit / 2) { /* do nothing */ } else { s += " " } } - let byte = buffer[i] + let byte = bytes.load(fromByteOffset: i, as: UInt8.self) var byteStr = String(byte, radix: 16, uppercase: false) if byte <= 0xf { byteStr = "0\(byteStr)" } s += byteStr @@ -231,15 +233,15 @@ public class NSData : NSObject, NSCopying, NSMutableCopying, NSSecureCoding { extension NSData { - public convenience init(bytes: UnsafePointer?, length: Int) { - self.init(bytes: UnsafeMutablePointer(bytes), length: length, copy: true, deallocator: nil) + public convenience init(bytes: UnsafeRawPointer?, length: Int) { + self.init(bytes: UnsafeMutableRawPointer(mutating: bytes), length: length, copy: true, deallocator: nil) } - public convenience init(bytesNoCopy bytes: UnsafeMutablePointer, length: Int) { + public convenience init(bytesNoCopy bytes: UnsafeMutableRawPointer, length: Int) { self.init(bytes: bytes, length: length, copy: false, deallocator: nil) } - public convenience init(bytesNoCopy bytes: UnsafeMutablePointer, length: Int, freeWhenDone b: Bool) { + public convenience init(bytesNoCopy bytes: UnsafeMutableRawPointer, length: Int, freeWhenDone b: Bool) { self.init(bytes: bytes, length: length, copy: false) { buffer, length in if b { free(buffer) @@ -247,15 +249,15 @@ extension NSData { } } - public convenience init(bytesNoCopy bytes: UnsafeMutablePointer, length: Int, deallocator: ((UnsafeMutablePointer, Int) -> Void)?) { + public convenience init(bytesNoCopy bytes: UnsafeMutableRawPointer, length: Int, deallocator: ((UnsafeMutableRawPointer, Int) -> Void)?) { self.init(bytes: bytes, length: length, copy: false, deallocator: deallocator) } internal struct NSDataReadResult { - var bytes: UnsafeMutablePointer + var bytes: UnsafeMutableRawPointer var length: Int - var deallocator: ((buffer: UnsafeMutablePointer, length: Int) -> Void)? + var deallocator: ((buffer: UnsafeMutableRawPointer, length: Int) -> Void)? } internal static func readBytesFromFileWithExtendedAttributes(_ path: String, options: ReadingOptions) throws -> NSDataReadResult { @@ -285,7 +287,7 @@ extension NSData { let data = mmap(nil, length, PROT_READ, MAP_PRIVATE, fd, 0) // Swift does not currently expose MAP_FAILURE - if data != UnsafeMutablePointer(bitPattern: -1) { + if data != UnsafeMutableRawPointer(bitPattern: -1) { return NSDataReadResult(bytes: data!, length: length) { buffer, length in munmap(buffer, length) } @@ -364,12 +366,14 @@ extension NSData { } extension NSData { - public func getBytes(_ buffer: UnsafeMutablePointer, length: Int) { - CFDataGetBytes(_cfObject, CFRangeMake(0, length), UnsafeMutablePointer(buffer)) + public func getBytes(_ buffer: UnsafeMutableRawPointer, length: Int) { + let bytePtr = buffer.bindMemory(to: UInt8.self, capacity: length) + CFDataGetBytes(_cfObject, CFRangeMake(0, length), bytePtr) } - public func getBytes(_ buffer: UnsafeMutablePointer, range: NSRange) { - CFDataGetBytes(_cfObject, CFRangeMake(range.location, range.length), UnsafeMutablePointer(buffer)) + public func getBytes(_ buffer: UnsafeMutableRawPointer, range: NSRange) { + let bytePtr = buffer.bindMemory(to: UInt8.self, capacity: range.length) + CFDataGetBytes(_cfObject, CFRangeMake(range.location, range.length), bytePtr) } public func isEqual(to other: Data) -> Bool { @@ -408,7 +412,7 @@ extension NSData { return (fd, pathResult) } - internal class func writeToFileDescriptor(_ fd: Int32, path: String? = nil, buf: UnsafePointer, length: Int) throws { + internal class func writeToFileDescriptor(_ fd: Int32, path: String? = nil, buf: UnsafeRawPointer, length: Int) throws { var bytesRemaining = length while bytesRemaining > 0 { var bytesWritten : Int @@ -529,9 +533,11 @@ extension NSData { guard let searchRange = searchRange.toRange() else {fatalError("invalid range")} precondition(searchRange.endIndex <= self.length, "range outside the bounds of data") - - let baseData = UnsafeBufferPointer(start: UnsafePointer(self.bytes), count: self.length)[searchRange] - let search = UnsafeBufferPointer(start: UnsafePointer(dataToFind.bytes), count: dataToFind.length) + + let basePtr = self.bytes.bindMemory(to: UInt8.self, capacity: self.length) + let baseData = UnsafeBufferPointer(start: basePtr, count: self.length)[searchRange] + let searchPtr = dataToFind.bytes.bindMemory(to: UInt8.self, capacity: dataToFind.length) + let search = UnsafeBufferPointer(start: searchPtr, count: dataToFind.length) let location : Int? let anchored = mask.contains(.anchored) @@ -552,7 +558,7 @@ extension NSData { return nil } - internal func enumerateByteRangesUsingBlockRethrows(_ block: @noescape (UnsafePointer, NSRange, UnsafeMutablePointer) throws -> Void) throws { + internal func enumerateByteRangesUsingBlockRethrows(_ block: @noescape (UnsafeRawPointer, NSRange, UnsafeMutablePointer) throws -> Void) throws { var err : Swift.Error? = nil self.enumerateBytes() { (buf, range, stop) -> Void in do { @@ -566,7 +572,7 @@ extension NSData { } } - public func enumerateBytes(_ block: @noescape (UnsafePointer, NSRange, UnsafeMutablePointer) -> Void) { + public func enumerateBytes(_ block: @noescape (UnsafeRawPointer, NSRange, UnsafeMutablePointer) -> Void) { var stop = false withUnsafeMutablePointer(&stop) { stopPointer in block(bytes, NSMakeRange(0, length), stopPointer) @@ -611,12 +617,12 @@ public class NSMutableData : NSData { self.init(bytes: nil, length: 0) } - internal override init(bytes: UnsafeMutablePointer?, length: Int, copy: Bool, deallocator: ((UnsafeMutablePointer, Int) -> Void)?) { + internal override init(bytes: UnsafeMutableRawPointer?, length: Int, copy: Bool, deallocator: ((UnsafeMutableRawPointer, Int) -> Void)?) { super.init(bytes: bytes, length: length, copy: copy, deallocator: deallocator) } - public var mutableBytes: UnsafeMutablePointer { - return UnsafeMutablePointer(CFDataGetMutableBytePtr(_cfMutableObject)) + public var mutableBytes: UnsafeMutableRawPointer { + return UnsafeMutableRawPointer(CFDataGetMutableBytePtr(_cfMutableObject)) } public override var length: Int { @@ -892,8 +898,9 @@ extension NSData { extension NSMutableData { - public func append(_ bytes: UnsafePointer, length: Int) { - CFDataAppendBytes(_cfMutableObject, UnsafePointer(bytes), length) + public func append(_ bytes: UnsafeRawPointer, length: Int) { + let bytePtr = bytes.bindMemory(to: UInt8.self, capacity: length) + CFDataAppendBytes(_cfMutableObject, bytePtr, length) } public func append(_ other: Data) { @@ -908,8 +915,9 @@ extension NSMutableData { CFDataSetLength(_cfMutableObject, CFDataGetLength(_cfObject) + extraLength) } - public func replaceBytes(in range: NSRange, withBytes bytes: UnsafePointer) { - CFDataReplaceBytes(_cfMutableObject, CFRangeMake(range.location, range.length), UnsafePointer(bytes), length) + public func replaceBytes(in range: NSRange, withBytes bytes: UnsafeRawPointer) { + let bytePtr = bytes.bindMemory(to: UInt8.self, capacity: length) + CFDataReplaceBytes(_cfMutableObject, CFRangeMake(range.location, range.length), bytePtr, length) } public func resetBytes(in range: NSRange) { @@ -924,8 +932,9 @@ extension NSMutableData { } - public func replaceBytes(in range: NSRange, withBytes replacementBytes: UnsafePointer, length replacementLength: Int) { - CFDataReplaceBytes(_cfMutableObject, CFRangeMake(range.location, range.length), UnsafePointer(bytes), replacementLength) + public func replaceBytes(in range: NSRange, withBytes replacementBytes: UnsafeRawPointer, length replacementLength: Int) { + let bytePtr = bytes.bindMemory(to: UInt8.self, capacity: replacementLength) + CFDataReplaceBytes(_cfMutableObject, CFRangeMake(range.location, range.length), bytePtr, replacementLength) } } diff --git a/Foundation/NSDate.swift b/Foundation/NSDate.swift index 2b1b88958f..e143601501 100644 --- a/Foundation/NSDate.swift +++ b/Foundation/NSDate.swift @@ -72,7 +72,7 @@ public class NSDate : NSObject, NSCopying, NSSecureCoding, NSCoding { } else { var ti: TimeInterval = 0.0 withUnsafeMutablePointer(&ti) { (ptr: UnsafeMutablePointer) -> Void in - aDecoder.decodeValue(ofObjCType: "d", at: UnsafeMutablePointer(ptr)) + aDecoder.decodeValue(ofObjCType: "d", at: UnsafeMutableRawPointer(ptr)) } self.init(timeIntervalSinceReferenceDate: ti) } diff --git a/Foundation/NSDecimalNumber.swift b/Foundation/NSDecimalNumber.swift index 831b64ae49..383df90566 100644 --- a/Foundation/NSDecimalNumber.swift +++ b/Foundation/NSDecimalNumber.swift @@ -51,7 +51,7 @@ public class NSDecimalNumber : NSNumber { NSUnimplemented() } - public required convenience init(bytes buffer: UnsafePointer, objCType type: UnsafePointer) { + public required convenience init(bytes buffer: UnsafeRawPointer, objCType type: UnsafePointer) { NSRequiresConcreteImplementation() } diff --git a/Foundation/NSDictionary.swift b/Foundation/NSDictionary.swift index af537990aa..17655590dd 100644 --- a/Foundation/NSDictionary.swift +++ b/Foundation/NSDictionary.swift @@ -52,8 +52,8 @@ extension Dictionary : _ObjectTypeBridgeable { let cf = x._cfObject let cnt = CFDictionaryGetCount(cf) - let keys = UnsafeMutablePointer?>.allocate(capacity: cnt) - let values = UnsafeMutablePointer?>.allocate(capacity: cnt) + let keys = UnsafeMutablePointer.allocate(capacity: cnt) + let values = UnsafeMutablePointer.allocate(capacity: cnt) CFDictionaryGetKeysAndValues(cf, keys, values) @@ -126,7 +126,7 @@ public class NSDictionary : NSObject, NSCopying, NSMutableCopying, NSSecureCodin // because that's the way the code was originally written, unless // we go to a new version of the class, which has its own problems. withUnsafeMutablePointer(&cnt) { (ptr: UnsafeMutablePointer) -> Void in - aDecoder.decodeValue(ofObjCType: "i", at: UnsafeMutablePointer(ptr)) + aDecoder.decodeValue(ofObjCType: "i", at: UnsafeMutableRawPointer(ptr)) } let keys = UnsafeMutablePointer.allocate(capacity: Int(cnt)) let objects = UnsafeMutablePointer.allocate(capacity: Int(cnt)) diff --git a/Foundation/NSFileHandle.swift b/Foundation/NSFileHandle.swift index cd58bda561..4b7b0deb3b 100644 --- a/Foundation/NSFileHandle.swift +++ b/Foundation/NSFileHandle.swift @@ -34,7 +34,7 @@ public class FileHandle: NSObject, NSSecureCoding { internal func _readDataOfLength(_ length: Int, untilEOF: Bool) -> Data { var statbuf = stat() - var dynamicBuffer: UnsafeMutablePointer? = nil + var dynamicBuffer: UnsafeMutableRawPointer? = nil var total = 0 if _closed || fstat(_fd, &statbuf) < 0 { fatalError("Unable to read file") @@ -42,14 +42,14 @@ public class FileHandle: NSObject, NSSecureCoding { if statbuf.st_mode & S_IFMT != S_IFREG { /* We get here on sockets, character special files, FIFOs ... */ var currentAllocationSize: size_t = 1024 * 8 - dynamicBuffer = UnsafeMutablePointer(malloc(currentAllocationSize)) + dynamicBuffer = malloc(currentAllocationSize) var remaining = length while remaining > 0 { let amountToRead = min(1024 * 8, remaining) // Make sure there is always at least amountToRead bytes available in the buffer. if (currentAllocationSize - total) < amountToRead { currentAllocationSize *= 2 - dynamicBuffer = UnsafeMutablePointer(_CFReallocf(UnsafeMutablePointer(dynamicBuffer!), currentAllocationSize)) + dynamicBuffer = _CFReallocf(dynamicBuffer!, currentAllocationSize) if dynamicBuffer == nil { fatalError("unable to allocate backing buffer") } @@ -79,7 +79,7 @@ public class FileHandle: NSObject, NSSecureCoding { var remaining = size_t(statbuf.st_size - offset) remaining = min(remaining, size_t(length)) - dynamicBuffer = UnsafeMutablePointer(malloc(remaining)) + dynamicBuffer = malloc(remaining) if dynamicBuffer == nil { fatalError("Malloc failure") } @@ -100,7 +100,7 @@ public class FileHandle: NSObject, NSSecureCoding { } if length == Int.max && total > 0 { - dynamicBuffer = UnsafeMutablePointer(_CFReallocf(UnsafeMutablePointer(dynamicBuffer!), total)) + dynamicBuffer = _CFReallocf(dynamicBuffer!, total) } if (0 == total) { @@ -108,7 +108,8 @@ public class FileHandle: NSObject, NSSecureCoding { } if total > 0 { - return Data(bytesNoCopy: dynamicBuffer!, count: total, deallocator: .none) + let bytePtr = dynamicBuffer!.bindMemory(to: UInt8.self, capacity: total) + return Data(bytesNoCopy: bytePtr, count: total, deallocator: .none) } return Data() @@ -117,7 +118,7 @@ public class FileHandle: NSObject, NSSecureCoding { public func write(_ data: Data) { data.enumerateBytes() { (bytes, range, stop) in do { - try NSData.writeToFileDescriptor(self._fd, path: nil, buf: UnsafePointer(bytes.baseAddress!), length: bytes.count) + try NSData.writeToFileDescriptor(self._fd, path: nil, buf: UnsafeRawPointer(bytes.baseAddress!), length: bytes.count) } catch { fatalError("Write failure") } diff --git a/Foundation/NSGeometry.swift b/Foundation/NSGeometry.swift index eb1a2bd8fe..9c2987670f 100644 --- a/Foundation/NSGeometry.swift +++ b/Foundation/NSGeometry.swift @@ -100,11 +100,9 @@ public func ==(lhs: CGPoint, rhs: CGPoint) -> Bool { } extension CGPoint: NSSpecialValueCoding { - init(bytes: UnsafePointer) { - let buffer = UnsafePointer(bytes) - - self.x = buffer.pointee - self.y = buffer.advanced(by: 1).pointee + init(bytes: UnsafeRawPointer) { + self.x = bytes.load(as: CGFloat.self) + self.y = bytes.load(fromByteOffset: strideof(CGFloat.self), as: CGFloat.self) } init?(coder aDecoder: NSCoder) { @@ -127,8 +125,8 @@ extension CGPoint: NSSpecialValueCoding { return "{CGPoint=dd}" } - func getValue(_ value: UnsafeMutablePointer) { - UnsafeMutablePointer(value).pointee = self + func getValue(_ value: UnsafeMutableRawPointer) { + value.initializeMemory(as: CGPoint.self, to: self) } func isEqual(_ aValue: Any) -> Bool { @@ -167,11 +165,9 @@ public func ==(lhs: CGSize, rhs: CGSize) -> Bool { } extension CGSize: NSSpecialValueCoding { - init(bytes: UnsafePointer) { - let buffer = UnsafePointer(bytes) - - self.width = buffer.pointee - self.height = buffer.advanced(by: 1).pointee + init(bytes: UnsafeRawPointer) { + self.width = bytes.load(as: CGFloat.self) + self.height = bytes.load(fromByteOffset: strideof(CGFloat.self), as: CGFloat.self) } init?(coder aDecoder: NSCoder) { @@ -194,8 +190,8 @@ extension CGSize: NSSpecialValueCoding { return "{CGSize=dd}" } - func getValue(_ value: UnsafeMutablePointer) { - UnsafeMutablePointer(value).pointee = self + func getValue(_ value: UnsafeMutableRawPointer) { + value.initializeMemory(as: CGSize.self, to: self) } func isEqual(_ aValue: Any) -> Bool { @@ -249,11 +245,13 @@ public typealias NSRectPointer = UnsafeMutablePointer public typealias NSRectArray = UnsafeMutablePointer extension CGRect: NSSpecialValueCoding { - init(bytes: UnsafePointer) { - let buffer = UnsafePointer(bytes) - - self.origin = CGPoint(x: buffer.pointee, y: buffer.advanced(by: 1).pointee) - self.size = CGSize(width: buffer.advanced(by: 2).pointee, height: buffer.advanced(by: 3).pointee) + init(bytes: UnsafeRawPointer) { + self.origin = CGPoint( + x: bytes.load(as: CGFloat.self), + y: bytes.load(fromByteOffset: 1 * strideof(CGFloat.self), as: CGFloat.self)) + self.size = CGSize( + width: bytes.load(fromByteOffset: 2 * strideof(CGFloat.self), as: CGFloat.self), + height: bytes.load(fromByteOffset: 3 * strideof(CGFloat.self), as: CGFloat.self)) } init?(coder aDecoder: NSCoder) { @@ -276,8 +274,8 @@ extension CGRect: NSSpecialValueCoding { return "{CGRect={CGPoint=dd}{CGSize=dd}}" } - func getValue(_ value: UnsafeMutablePointer) { - UnsafeMutablePointer(value).pointee = self + func getValue(_ value: UnsafeMutableRawPointer) { + value.initializeMemory(as: CGRect.self, to: self) } func isEqual(_ aValue: Any) -> Bool { @@ -344,13 +342,11 @@ public struct NSEdgeInsets { } extension NSEdgeInsets: NSSpecialValueCoding { - init(bytes: UnsafePointer) { - let buffer = UnsafePointer(bytes) - - self.top = buffer.pointee - self.left = buffer.advanced(by: 1).pointee - self.bottom = buffer.advanced(by: 2).pointee - self.right = buffer.advanced(by: 3).pointee + init(bytes: UnsafeRawPointer) { + self.top = bytes.load(as: CGFloat.self) + self.left = bytes.load(fromByteOffset: strideof(CGFloat.self), as: CGFloat.self) + self.bottom = bytes.load(fromByteOffset: 2 * strideof(CGFloat.self), as: CGFloat.self) + self.right = bytes.load(fromByteOffset: 3 * strideof(CGFloat.self), as: CGFloat.self) } init?(coder aDecoder: NSCoder) { @@ -379,8 +375,8 @@ extension NSEdgeInsets: NSSpecialValueCoding { return "{NSEdgeInsets=dddd}" } - func getValue(_ value: UnsafeMutablePointer) { - UnsafeMutablePointer(value).pointee = self + func getValue(_ value: UnsafeMutableRawPointer) { + value.initializeMemory(as: NSEdgeInsets.self, to: self) } func isEqual(_ aValue: Any) -> Bool { diff --git a/Foundation/NSKeyedArchiver.swift b/Foundation/NSKeyedArchiver.swift index fdcedae19b..f19fea0935 100644 --- a/Foundation/NSKeyedArchiver.swift +++ b/Foundation/NSKeyedArchiver.swift @@ -285,7 +285,7 @@ public class NSKeyedArchiver : NSCoder { private static func _createObjectRef(_ uid : UInt32) -> CFKeyedArchiverUID { return Unmanaged.fromOpaque( - UnsafePointer(_CFKeyedArchiverUIDCreate(kCFAllocatorSystemDefault, uid))).takeUnretainedValue() + UnsafeRawPointer(_CFKeyedArchiverUIDCreate(kCFAllocatorSystemDefault, uid))).takeUnretainedValue() } private func _createObjectRefCached(_ uid : UInt32) -> CFKeyedArchiverUID { @@ -654,7 +654,7 @@ public class NSKeyedArchiver : NSCoder { _encodePropertyList(objv, forKey: key) } - private func _encodeValueOfObjCType(_ type: _NSSimpleObjCType, at addr: UnsafePointer) { + private func _encodeValueOfObjCType(_ type: _NSSimpleObjCType, at addr: UnsafeRawPointer) { switch type { case .ID: let objectp = unsafeBitCast(addr, to: UnsafePointer.self) @@ -710,7 +710,7 @@ public class NSKeyedArchiver : NSCoder { } } - public override func encodeValue(ofObjCType typep: UnsafePointer, at addr: UnsafePointer) { + public override func encodeValue(ofObjCType typep: UnsafePointer, at addr: UnsafeRawPointer) { guard let type = _NSSimpleObjCType(UInt8(typep.pointee)) else { let spec = String(typep.pointee) fatalError("NSKeyedArchiver.encodeValueOfObjCType: unsupported type encoding spec '\(spec)'") diff --git a/Foundation/NSKeyedCoderOldStyleArray.swift b/Foundation/NSKeyedCoderOldStyleArray.swift index 75e9897a3a..125bf10110 100644 --- a/Foundation/NSKeyedCoderOldStyleArray.swift +++ b/Foundation/NSKeyedCoderOldStyleArray.swift @@ -11,7 +11,7 @@ import CoreFoundation internal final class _NSKeyedCoderOldStyleArray : NSObject, NSCopying, NSSecureCoding, NSCoding { - private var _addr : UnsafeMutablePointer // free if decoding + private var _addr : UnsafeMutableRawPointer // free if decoding private var _count : Int private var _size : Int private var _type : _NSSimpleObjCType @@ -24,14 +24,15 @@ internal final class _NSKeyedCoderOldStyleArray : NSObject, NSCopying, NSSecureC return _NSGetSizeAndAlignment(type, &size, &align) ? size : nil } - init?(objCType type: _NSSimpleObjCType, count: Int, at addr: UnsafePointer) { - self._addr = UnsafeMutablePointer(addr) - self._count = count - + // TODO: Why isn't `addr` passed as a mutable pointer? + init?(objCType type: _NSSimpleObjCType, count: Int, at addr: UnsafeRawPointer) { + self._addr = UnsafeMutableRawPointer(mutating: addr) + self._count = count + guard let size = _NSKeyedCoderOldStyleArray.sizeForObjCType(type) else { return nil } - + self._size = size self._type = type self._decoded = false @@ -39,8 +40,8 @@ internal final class _NSKeyedCoderOldStyleArray : NSObject, NSCopying, NSSecureC deinit { if self._decoded { - self._addr.deinitialize(count: self._count * self._size) - self._addr.deallocate(capacity: self._count * self._size) + // Cannot deinitialize memory without knowing the element type. + self._addr.deallocate(bytes: self._count * self._size, alignedTo: 1) } } @@ -60,7 +61,7 @@ internal final class _NSKeyedCoderOldStyleArray : NSObject, NSCopying, NSSecureC return nil } - self._addr = UnsafeMutablePointer.allocate(capacity: self._count * self._size) + self._addr = UnsafeMutableRawPointer.allocate(bytes: self._count * self._size, alignedTo: 1) super.init() @@ -83,7 +84,7 @@ internal final class _NSKeyedCoderOldStyleArray : NSObject, NSCopying, NSSecureC var type = Int8(self._type) withUnsafePointer(&type) { typep in - aCoder.encodeValue(ofObjCType: typep, at: &self._addr[idx * self._size]) + aCoder.encodeValue(ofObjCType: typep, at: self._addr + (idx * self._size)) } } } @@ -92,9 +93,9 @@ internal final class _NSKeyedCoderOldStyleArray : NSObject, NSCopying, NSSecureC return true } - func fillObjCType(_ type: _NSSimpleObjCType, count: Int, at addr: UnsafeMutablePointer) { + func fillObjCType(_ type: _NSSimpleObjCType, count: Int, at addr: UnsafeMutableRawPointer) { if type == self._type && count <= self._count { - UnsafeMutablePointer(addr).moveInitialize(from: self._addr, count: count * self._size) + addr.copyBytes(from: self._addr, count: count * self._size) } } diff --git a/Foundation/NSKeyedUnarchiver.swift b/Foundation/NSKeyedUnarchiver.swift index 409e224692..cf3418868e 100644 --- a/Foundation/NSKeyedUnarchiver.swift +++ b/Foundation/NSKeyedUnarchiver.swift @@ -763,7 +763,7 @@ public class NSKeyedUnarchiver : NSCoder { return decodeObject() as? Data } - private func _decodeValueOfObjCType(_ type: _NSSimpleObjCType, at addr: UnsafeMutablePointer) { + private func _decodeValueOfObjCType(_ type: _NSSimpleObjCType, at addr: UnsafeMutableRawPointer) { switch type { case .ID: if let ns = decodeObject() { @@ -834,7 +834,7 @@ public class NSKeyedUnarchiver : NSCoder { } } - public override func decodeValue(ofObjCType typep: UnsafePointer, at addr: UnsafeMutablePointer) { + public override func decodeValue(ofObjCType typep: UnsafePointer, at addr: UnsafeMutableRawPointer) { guard let type = _NSSimpleObjCType(UInt8(typep.pointee)) else { let spec = String(typep.pointee) fatalError("NSKeyedUnarchiver.decodeValueOfObjCType: unsupported type encoding spec '\(spec)'") diff --git a/Foundation/NSLocale.swift b/Foundation/NSLocale.swift index b745c850b4..a2c0186a6a 100644 --- a/Foundation/NSLocale.swift +++ b/Foundation/NSLocale.swift @@ -13,9 +13,9 @@ import CoreFoundation public class Locale: NSObject, NSCopying, NSSecureCoding { typealias CFType = CFLocale private var _base = _CFInfo(typeID: CFLocaleGetTypeID()) - private var _identifier: UnsafeMutablePointer? = nil - private var _cache: UnsafeMutablePointer? = nil - private var _prefs: UnsafeMutablePointer? = nil + private var _identifier: UnsafeMutableRawPointer? = nil + private var _cache: UnsafeMutableRawPointer? = nil + private var _prefs: UnsafeMutableRawPointer? = nil #if os(OSX) || os(iOS) private var _lock = pthread_mutex_t() #elseif os(Linux) diff --git a/Foundation/NSNumber.swift b/Foundation/NSNumber.swift index 1212526795..4985e7967b 100644 --- a/Foundation/NSNumber.swift +++ b/Foundation/NSNumber.swift @@ -225,43 +225,43 @@ public class NSNumber : NSValue { _CFNumberInitBool(_cfObject, value) } - public required convenience init(bytes buffer: UnsafePointer, objCType: UnsafePointer) { + public required convenience init(bytes buffer: UnsafeRawPointer, objCType: UnsafePointer) { guard let type = _NSSimpleObjCType(UInt8(objCType.pointee)) else { fatalError("NSNumber.init: unsupported type encoding spec '\(String(cString: objCType))'") } switch type { case .Bool: - self.init(value:UnsafePointer(buffer).pointee) + self.init(value:buffer.load(as: Bool.self)) break case .Char: - self.init(value:UnsafePointer(buffer).pointee) + self.init(value:buffer.load(as: Int8.self)) break case .UChar: - self.init(value:UnsafePointer(buffer).pointee) + self.init(value:buffer.load(as: UInt8.self)) break case .Short: - self.init(value:UnsafePointer(buffer).pointee) + self.init(value:buffer.load(as: Int16.self)) break case .UShort: - self.init(value:UnsafePointer(buffer).pointee) + self.init(value:buffer.load(as: UInt16.self)) break case .Int, .Long: - self.init(value:UnsafePointer(buffer).pointee) + self.init(value:buffer.load(as: Int32.self)) break case .UInt, .ULong: - self.init(value:UnsafePointer(buffer).pointee) + self.init(value:buffer.load(as: UInt32.self)) break case .LongLong: - self.init(value:UnsafePointer(buffer).pointee) + self.init(value:buffer.load(as: Int64.self)) break case .ULongLong: - self.init(value:UnsafePointer(buffer).pointee) + self.init(value:buffer.load(as: UInt64.self)) break case .Float: - self.init(value:UnsafePointer(buffer).pointee) + self.init(value:buffer.load(as: Float.self)) break case .Double: - self.init(value:UnsafePointer(buffer).pointee) + self.init(value:buffer.load(as: Double.self)) break default: fatalError("NSNumber.init: unsupported type encoding spec '\(String(cString: objCType))'") @@ -273,7 +273,7 @@ public class NSNumber : NSValue { if !aDecoder.allowsKeyedCoding { var objCType: UnsafeMutablePointer? = nil withUnsafeMutablePointer(&objCType, { (ptr: UnsafeMutablePointer?>) -> Void in - aDecoder.decodeValue(ofObjCType: String(_NSSimpleObjCType.CharPtr), at: UnsafeMutablePointer(ptr)) + aDecoder.decodeValue(ofObjCType: String(_NSSimpleObjCType.CharPtr), at: UnsafeMutableRawPointer(ptr)) }) if objCType == nil { return nil diff --git a/Foundation/NSProcessInfo.swift b/Foundation/NSProcessInfo.swift index 9544ba5337..1c40d5ca18 100644 --- a/Foundation/NSProcessInfo.swift +++ b/Foundation/NSProcessInfo.swift @@ -95,7 +95,7 @@ public class ProcessInfo: NSObject { return NSOperatingSystemVersion(majorVersion: fallbackMajor, minorVersion: fallbackMinor, patchVersion: fallbackPatch) } - let productVersionKey = unsafeBitCast(_kCFSystemVersionProductVersionKey, to: UnsafePointer.self) + let productVersionKey = unsafeBitCast(_kCFSystemVersionProductVersionKey, to: UnsafeRawPointer.self) guard let productVersion = unsafeBitCast(CFDictionaryGetValue(systemVersionDictionary, productVersionKey), to: NSString!.self) else { return NSOperatingSystemVersion(majorVersion: fallbackMajor, minorVersion: fallbackMinor, patchVersion: fallbackPatch) } diff --git a/Foundation/NSRange.swift b/Foundation/NSRange.swift index 25928ac571..6ff73872f6 100644 --- a/Foundation/NSRange.swift +++ b/Foundation/NSRange.swift @@ -52,11 +52,9 @@ extension NSRange { } extension NSRange: NSSpecialValueCoding { - init(bytes: UnsafePointer) { - let buffer = UnsafePointer(bytes) - - self.location = buffer.pointee - self.length = buffer.advanced(by: 1).pointee + init(bytes: UnsafeRawPointer) { + self.location = bytes.load(as: Int.self) + self.length = bytes.load(fromByteOffset: strideof(Int.self), as: Int.self) } init?(coder aDecoder: NSCoder) { @@ -95,8 +93,8 @@ extension NSRange: NSSpecialValueCoding { #endif } - func getValue(_ value: UnsafeMutablePointer) { - UnsafeMutablePointer(value).pointee = self + func getValue(_ value: UnsafeMutableRawPointer) { + value.initializeMemory(as: NSRange.self, to: self) } func isEqual(_ aValue: Any) -> Bool { diff --git a/Foundation/NSRegularExpression.swift b/Foundation/NSRegularExpression.swift index 37a4f3d8c9..1ee2ce55bc 100644 --- a/Foundation/NSRegularExpression.swift +++ b/Foundation/NSRegularExpression.swift @@ -120,7 +120,7 @@ internal class _NSRegularExpressionMatcher { } } -internal func _NSRegularExpressionMatch(_ context: UnsafeMutablePointer?, ranges: UnsafeMutablePointer?, count: CFIndex, options: _CFRegularExpressionMatchingOptions, stop: UnsafeMutablePointer<_DarwinCompatibleBoolean>) -> Void { +internal func _NSRegularExpressionMatch(_ context: UnsafeMutableRawPointer?, ranges: UnsafeMutablePointer?, count: CFIndex, options: _CFRegularExpressionMatchingOptions, stop: UnsafeMutablePointer<_DarwinCompatibleBoolean>) -> Void { let matcher = unsafeBitCast(context, to: _NSRegularExpressionMatcher.self) if ranges == nil { #if os(OSX) || os(iOS) @@ -153,7 +153,7 @@ extension RegularExpression { #else let opts = _CFRegularExpressionMatchingOptions(options.rawValue) #endif - _CFRegularExpressionEnumerateMatchesInString(_internal, string._cfObject, opts, CFRange(range), unsafeBitCast(matcher, to: UnsafeMutablePointer.self), _NSRegularExpressionMatch) + _CFRegularExpressionEnumerateMatchesInString(_internal, string._cfObject, opts, CFRange(range), unsafeBitCast(matcher, to: UnsafeMutableRawPointer.self), _NSRegularExpressionMatch) } } diff --git a/Foundation/NSSet.swift b/Foundation/NSSet.swift index 582d6e2676..1f43570e6a 100644 --- a/Foundation/NSSet.swift +++ b/Foundation/NSSet.swift @@ -43,7 +43,7 @@ extension Set : _ObjectTypeBridgeable { let cf = x._cfObject let cnt = CFSetGetCount(cf) - let objs = UnsafeMutablePointer?>.allocate(capacity: cnt) + let objs = UnsafeMutablePointer.allocate(capacity: cnt) CFSetGetValues(cf, objs) @@ -120,7 +120,7 @@ public class NSSet : NSObject, NSCopying, NSMutableCopying, NSSecureCoding, NSCo // because that's the way the code was originally written, unless // we go to a new version of the class, which has its own problems. withUnsafeMutablePointer(&cnt) { (ptr: UnsafeMutablePointer) -> Void in - aDecoder.decodeValue(ofObjCType: "i", at: UnsafeMutablePointer(ptr)) + aDecoder.decodeValue(ofObjCType: "i", at: UnsafeMutableRawPointer(ptr)) } let objects = UnsafeMutablePointer.allocate(capacity: Int(cnt)) for idx in 0.. String - init(bytes value: UnsafePointer) + init(bytes value: UnsafeRawPointer) func encodeWithCoder(_ aCoder: NSCoder) init?(coder aDecoder: NSCoder) - func getValue(_ value: UnsafeMutablePointer) + func getValue(_ value: UnsafeMutableRawPointer) // Ideally we would make NSSpecialValue a generic class and specialise it for // NSPoint, etc, but then we couldn't implement NSValue.init?(coder:) because @@ -81,7 +81,7 @@ internal class NSSpecialValue : NSValue { self._value = value } - required init(bytes value: UnsafePointer, objCType type: UnsafePointer) { + required init(bytes value: UnsafeRawPointer, objCType type: UnsafePointer) { guard let specialType = NSSpecialValue._typeFromObjCType(type) else { NSUnimplemented() } @@ -89,7 +89,7 @@ internal class NSSpecialValue : NSValue { self._value = specialType.init(bytes: value) } - override func getValue(_ value: UnsafeMutablePointer) { + override func getValue(_ value: UnsafeMutableRawPointer) { self._value.getValue(value) } diff --git a/Foundation/NSString.swift b/Foundation/NSString.swift index f1b1a5c4d5..837e610f90 100644 --- a/Foundation/NSString.swift +++ b/Foundation/NSString.swift @@ -187,14 +187,14 @@ internal func _bytesInEncoding(_ str: NSString, _ encoding: String.Encoding, _ f return nil } - let buffer = malloc(cLength + 1)! + 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") } - UnsafeMutablePointer(buffer).advanced(by: cLength).initialize(to: 0) + buffer.advanced(by: cLength).initialize(to: 0) - return UnsafePointer(buffer) // leaked and should be autoreleased via a NSData backing but we cannot here + return UnsafePointer(buffer) // leaked and should be autoreleased via a NSData backing but we cannot here } internal func isALineSeparatorTypeCharacter(_ ch: unichar) -> Bool { @@ -888,14 +888,14 @@ extension NSString { return true } } - if getBytes(UnsafeMutablePointer(buffer), maxLength: maxBufferCount, usedLength: &used, encoding: encoding, options: [], range: NSMakeRange(0, self.length), remaining: nil) { + if getBytes(UnsafeMutableRawPointer(buffer), maxLength: maxBufferCount, usedLength: &used, encoding: encoding, options: [], range: NSMakeRange(0, self.length), remaining: nil) { buffer.advanced(by: used).initialize(to: 0) return true } return false } - public func getBytes(_ buffer: UnsafeMutablePointer?, maxLength maxBufferCount: Int, usedLength usedBufferCount: UnsafeMutablePointer?, encoding: UInt, options: EncodingConversionOptions = [], range: NSRange, remaining leftover: NSRangePointer?) -> Bool { + public func getBytes(_ buffer: UnsafeMutableRawPointer?, maxLength maxBufferCount: Int, usedLength usedBufferCount: UnsafeMutablePointer?, encoding: UInt, options: EncodingConversionOptions = [], range: NSRange, remaining leftover: NSRangePointer?) -> Bool { var totalBytesWritten = 0 var numCharsProcessed = 0 let cfStringEncoding = CFStringConvertNSStringEncodingToEncoding(encoding) @@ -905,7 +905,8 @@ extension NSString { let lossyOk = options.contains(.allowLossy) let externalRep = options.contains(.externalRepresentation) let failOnPartial = options.contains(.failOnPartialEncodingConversion) - numCharsProcessed = __CFStringEncodeByteStream(_cfObject, range.location, range.length, externalRep, cfStringEncoding, lossyOk ? (encoding == String.Encoding.ascii.rawValue ? 0xFF : 0x3F) : 0, UnsafeMutablePointer(buffer), buffer != nil ? maxBufferCount : 0, &totalBytesWritten) + let bytePtr = buffer?.bindMemory(to: UInt8.self, capacity: maxBufferCount) + numCharsProcessed = __CFStringEncodeByteStream(_cfObject, range.location, range.length, externalRep, cfStringEncoding, lossyOk ? (encoding == String.Encoding.ascii.rawValue ? 0xFF : 0x3F) : 0, bytePtr, bytePtr != nil ? maxBufferCount : 0, &totalBytesWritten) if (failOnPartial && numCharsProcessed < range.length) || numCharsProcessed == 0 { result = false } @@ -1147,7 +1148,8 @@ extension NSString { var mData = Data(count: numBytes)! // The getBytes:... call should hopefully not fail, given it succeeded above, but check anyway (mutable string changing behind our back?) var used = 0 - try mData.withUnsafeMutableBytes { (mutableBytes: UnsafeMutablePointer) -> Void in + // This binds mData memory to UInt8 because Data.withUnsafeMutableBytes does not handle raw pointers. + try mData.withUnsafeMutableBytes { (mutableBytes: UnsafeMutablePointer) -> Void in if !getBytes(mutableBytes, maxLength: numBytes, usedLength: &used, encoding: enc, options: [], range: theRange, remaining: nil) { throw NSError(domain: NSCocoaErrorDomain, code: NSCocoaError.FileWriteUnknownError.rawValue, userInfo: [ NSURLErrorKey: dest, @@ -1175,7 +1177,7 @@ extension NSString { // ignore the no-copy-ness self.init(characters: characters, length: length) if freeBuffer { // cant take a hint here... - free(UnsafeMutablePointer(characters)) + free(UnsafeMutableRawPointer(characters)) } } @@ -1215,8 +1217,8 @@ extension NSString { } public convenience init?(data: Data, encoding: UInt) { - guard let cf = data.withUnsafeBytes({ (bytes: UnsafePointer) -> CFString? in - return CFStringCreateWithBytes(kCFAllocatorDefault, UnsafePointer(bytes), data.count, CFStringConvertNSStringEncodingToEncoding(encoding), true) + guard let cf = data.withUnsafeBytes({ (bytes: UnsafePointer) -> CFString? in + return CFStringCreateWithBytes(kCFAllocatorDefault, bytes, data.count, CFStringConvertNSStringEncodingToEncoding(encoding), true) }) else { return nil } var str: String? @@ -1227,8 +1229,9 @@ extension NSString { } } - public convenience init?(bytes: UnsafePointer, length len: Int, encoding: UInt) { - guard let cf = CFStringCreateWithBytes(kCFAllocatorDefault, UnsafePointer(bytes), len, CFStringConvertNSStringEncodingToEncoding(encoding), true) else { + public convenience init?(bytes: UnsafeRawPointer, length len: Int, encoding: UInt) { + let bytePtr = bytes.bindMemory(to: UInt8.self, capacity: len) + guard let cf = CFStringCreateWithBytes(kCFAllocatorDefault, bytePtr, len, CFStringConvertNSStringEncodingToEncoding(encoding), true) else { return nil } var str: String? @@ -1239,7 +1242,7 @@ extension NSString { } } - public convenience init?(bytesNoCopy bytes: UnsafeMutablePointer, length len: Int, encoding: UInt, freeWhenDone freeBuffer: Bool) /* "NoCopy" is a hint */ { + public convenience init?(bytesNoCopy bytes: UnsafeMutableRawPointer, length len: Int, encoding: UInt, freeWhenDone freeBuffer: Bool) /* "NoCopy" is a hint */ { // just copy for now since the internal storage will be a copy anyhow self.init(bytes: bytes, length: len, encoding: encoding) if freeBuffer { // dont take the hint @@ -1262,7 +1265,8 @@ extension NSString { public convenience init(contentsOf url: URL, encoding enc: UInt) throws { let readResult = try NSData(contentsOf: url, options: []) - guard let cf = CFStringCreateWithBytes(kCFAllocatorDefault, UnsafePointer(readResult.bytes), readResult.length, CFStringConvertNSStringEncodingToEncoding(enc), true) else { + let bytePtr = readResult.bytes.bindMemory(to: UInt8.self, capacity: readResult.length) + guard let cf = CFStringCreateWithBytes(kCFAllocatorDefault, bytePtr, readResult.length, CFStringConvertNSStringEncodingToEncoding(enc), true) else { throw NSError(domain: NSCocoaErrorDomain, code: NSCocoaError.FileReadInapplicableStringEncodingError.rawValue, userInfo: [ "NSDebugDescription" : "Unable to create a string using the specified encoding." ]) @@ -1397,8 +1401,8 @@ extension NSMutableString { if let findResults = CFStringCreateArrayWithFindResults(kCFAllocatorSystemDefault, _cfObject, target._cfObject, CFRange(searchRange), options._cfValue(true)) { let numOccurrences = CFArrayGetCount(findResults) for cnt in 0..(CFArrayGetValueAtIndex(findResults, backwards ? cnt : numOccurrences - cnt - 1)!) - replaceCharacters(in: NSRange(range.pointee), with: replacement) + let rangePtr = CFArrayGetValueAtIndex(findResults, backwards ? cnt : numOccurrences - cnt - 1) + replaceCharacters(in: NSRange(rangePtr!.load(as: CFRange.self)), with: replacement) } return numOccurrences } else { diff --git a/Foundation/NSSwiftRuntime.swift b/Foundation/NSSwiftRuntime.swift index 0f4616bd19..f74791d2e4 100644 --- a/Foundation/NSSwiftRuntime.swift +++ b/Foundation/NSSwiftRuntime.swift @@ -67,7 +67,7 @@ internal func _CFSwiftIsEqual(_ cf1: AnyObject, cf2: AnyObject) -> Bool { // Ivars in _NSCF* types must be zeroed via an unsafe accessor to avoid deinit of potentially unsafe memory to accces as an object/struct etc since it is stored via a foreign object graph internal func _CFZeroUnsafeIvars(_ arg: inout T) { withUnsafeMutablePointer(&arg) { (ptr: UnsafeMutablePointer) -> Void in - bzero(unsafeBitCast(ptr, to: UnsafeMutablePointer.self), sizeof(T.self)) + bzero(unsafeBitCast(ptr, to: UnsafeMutableRawPointer.self), sizeof(T.self)) } } @@ -77,24 +77,24 @@ internal func __CFSwiftGetBaseClass() -> AnyObject.Type { internal func __CFInitializeSwift() { - _CFRuntimeBridgeTypeToClass(CFStringGetTypeID(), unsafeBitCast(_NSCFString.self, to: UnsafePointer.self)) - _CFRuntimeBridgeTypeToClass(CFArrayGetTypeID(), unsafeBitCast(_NSCFArray.self, to: UnsafePointer.self)) - _CFRuntimeBridgeTypeToClass(CFDictionaryGetTypeID(), unsafeBitCast(_NSCFDictionary.self, to: UnsafePointer.self)) - _CFRuntimeBridgeTypeToClass(CFSetGetTypeID(), unsafeBitCast(_NSCFSet.self, to: UnsafePointer.self)) - _CFRuntimeBridgeTypeToClass(CFNumberGetTypeID(), unsafeBitCast(NSNumber.self, to: UnsafePointer.self)) - _CFRuntimeBridgeTypeToClass(CFDataGetTypeID(), unsafeBitCast(NSData.self, to: UnsafePointer.self)) - _CFRuntimeBridgeTypeToClass(CFDateGetTypeID(), unsafeBitCast(NSDate.self, to: UnsafePointer.self)) - _CFRuntimeBridgeTypeToClass(CFURLGetTypeID(), unsafeBitCast(NSURL.self, to: UnsafePointer.self)) - _CFRuntimeBridgeTypeToClass(CFCalendarGetTypeID(), unsafeBitCast(Calendar.self, to: UnsafePointer.self)) - _CFRuntimeBridgeTypeToClass(CFLocaleGetTypeID(), unsafeBitCast(Locale.self, to: UnsafePointer.self)) - _CFRuntimeBridgeTypeToClass(CFTimeZoneGetTypeID(), unsafeBitCast(TimeZone.self, to: UnsafePointer.self)) - _CFRuntimeBridgeTypeToClass(CFCharacterSetGetTypeID(), unsafeBitCast(_NSCFCharacterSet.self, to: UnsafePointer.self)) + _CFRuntimeBridgeTypeToClass(CFStringGetTypeID(), unsafeBitCast(_NSCFString.self, to: UnsafeRawPointer.self)) + _CFRuntimeBridgeTypeToClass(CFArrayGetTypeID(), unsafeBitCast(_NSCFArray.self, to: UnsafeRawPointer.self)) + _CFRuntimeBridgeTypeToClass(CFDictionaryGetTypeID(), unsafeBitCast(_NSCFDictionary.self, to: UnsafeRawPointer.self)) + _CFRuntimeBridgeTypeToClass(CFSetGetTypeID(), unsafeBitCast(_NSCFSet.self, to: UnsafeRawPointer.self)) + _CFRuntimeBridgeTypeToClass(CFNumberGetTypeID(), unsafeBitCast(NSNumber.self, to: UnsafeRawPointer.self)) + _CFRuntimeBridgeTypeToClass(CFDataGetTypeID(), unsafeBitCast(NSData.self, to: UnsafeRawPointer.self)) + _CFRuntimeBridgeTypeToClass(CFDateGetTypeID(), unsafeBitCast(NSDate.self, to: UnsafeRawPointer.self)) + _CFRuntimeBridgeTypeToClass(CFURLGetTypeID(), unsafeBitCast(NSURL.self, to: UnsafeRawPointer.self)) + _CFRuntimeBridgeTypeToClass(CFCalendarGetTypeID(), unsafeBitCast(Calendar.self, to: UnsafeRawPointer.self)) + _CFRuntimeBridgeTypeToClass(CFLocaleGetTypeID(), unsafeBitCast(Locale.self, to: UnsafeRawPointer.self)) + _CFRuntimeBridgeTypeToClass(CFTimeZoneGetTypeID(), unsafeBitCast(TimeZone.self, to: UnsafeRawPointer.self)) + _CFRuntimeBridgeTypeToClass(CFCharacterSetGetTypeID(), unsafeBitCast(_NSCFCharacterSet.self, to: UnsafeRawPointer.self)) -// _CFRuntimeBridgeTypeToClass(CFErrorGetTypeID(), unsafeBitCast(NSError.self, UnsafePointer.self)) -// _CFRuntimeBridgeTypeToClass(CFAttributedStringGetTypeID(), unsafeBitCast(NSMutableAttributedString.self, UnsafePointer.self)) -// _CFRuntimeBridgeTypeToClass(CFReadStreamGetTypeID(), unsafeBitCast(NSInputStream.self, UnsafePointer.self)) -// _CFRuntimeBridgeTypeToClass(CFWriteStreamGetTypeID(), unsafeBitCast(NSOutputStream.self, UnsafePointer.self)) - _CFRuntimeBridgeTypeToClass(CFRunLoopTimerGetTypeID(), unsafeBitCast(Timer.self, to: UnsafePointer.self)) +// _CFRuntimeBridgeTypeToClass(CFErrorGetTypeID(), unsafeBitCast(NSError.self, UnsafeRawPointer.self)) +// _CFRuntimeBridgeTypeToClass(CFAttributedStringGetTypeID(), unsafeBitCast(NSMutableAttributedString.self, UnsafeRawPointer.self)) +// _CFRuntimeBridgeTypeToClass(CFReadStreamGetTypeID(), unsafeBitCast(NSInputStream.self, UnsafeRawPointer.self)) +// _CFRuntimeBridgeTypeToClass(CFWriteStreamGetTypeID(), unsafeBitCast(NSOutputStream.self, UnsafeRawPointer.self)) + _CFRuntimeBridgeTypeToClass(CFRunLoopTimerGetTypeID(), unsafeBitCast(Timer.self, to: UnsafeRawPointer.self)) __CFSwiftBridge.NSObject.isEqual = _CFSwiftIsEqual __CFSwiftBridge.NSObject.hash = _CFSwiftGetHash @@ -307,43 +307,47 @@ extension Bool : _NSObjectRepresentable { } public func === (lhs: AnyClass, rhs: AnyClass) -> Bool { - return unsafeBitCast(lhs, to: UnsafePointer.self) == unsafeBitCast(rhs, to: UnsafePointer.self) + return unsafeBitCast(lhs, to: UnsafeRawPointer.self) == unsafeBitCast(rhs, to: UnsafeRawPointer.self) } /// Swift extensions for common operations in Foundation that use unsafe things... extension NSObject { - static func unretainedReference(_ value: UnsafePointer) -> R { + static func unretainedReference(_ value: UnsafeRawPointer) -> R { return unsafeBitCast(value, to: R.self) } - static func unretainedReference(_ value: UnsafeMutablePointer) -> R { - return unretainedReference(UnsafePointer(value)) + static func unretainedReference(_ value: UnsafeMutableRawPointer) -> R { + return unretainedReference(value) } - static func releaseReference(_ value: UnsafePointer) { - _CFSwiftRelease(UnsafeMutablePointer(value)) + static func releaseReference(_ value: UnsafeRawPointer) { + _CFSwiftRelease(UnsafeMutableRawPointer(mutating: value)) } - static func releaseReference(_ value: UnsafeMutablePointer) { + static func releaseReference(_ value: UnsafeMutableRawPointer) { _CFSwiftRelease(value) } func withRetainedReference(_ work: @noescape (UnsafePointer) -> R) -> R { - return work(UnsafePointer(_CFSwiftRetain(unsafeBitCast(self, to: UnsafeMutablePointer.self))!)) + let selfPtr = Unmanaged.passRetained(self).toOpaque().assumingMemoryBound(to: T.self) + return work(selfPtr) } func withRetainedReference(_ work: @noescape (UnsafeMutablePointer) -> R) -> R { - return work(UnsafeMutablePointer(_CFSwiftRetain(unsafeBitCast(self, to: UnsafeMutablePointer.self))!)) + let selfPtr = Unmanaged.passRetained(self).toOpaque().assumingMemoryBound(to: T.self) + return work(selfPtr) } func withUnretainedReference(_ work: @noescape (UnsafePointer) -> R) -> R { - return work(unsafeBitCast(self, to: UnsafePointer.self)) + let selfPtr = Unmanaged.passRetained(self).toOpaque().assumingMemoryBound(to: T.self) + return work(selfPtr) } func withUnretainedReference(_ work: @noescape (UnsafeMutablePointer) -> R) -> R { - return work(unsafeBitCast(self, to: UnsafeMutablePointer.self)) + let selfPtr = Unmanaged.passRetained(self).toOpaque().assumingMemoryBound(to: T.self) + return work(selfPtr) } } diff --git a/Foundation/NSTask.swift b/Foundation/NSTask.swift index 08df7faaff..74ca7a7393 100644 --- a/Foundation/NSTask.swift +++ b/Foundation/NSTask.swift @@ -34,24 +34,24 @@ private var managerThreadRunLoopIsRunningCondition = Condition() internal let kCFSocketDataCallBack = CFSocketCallBackType.dataCallBack.rawValue #endif -private func emptyRunLoopCallback(_ context : UnsafeMutablePointer?) -> Void {} +private func emptyRunLoopCallback(_ context : UnsafeMutableRawPointer?) -> Void {} // Retain method for run loop source -private func runLoopSourceRetain(_ pointer : UnsafePointer?) -> UnsafePointer? { +private func runLoopSourceRetain(_ pointer : UnsafeRawPointer?) -> UnsafeRawPointer? { let ref = Unmanaged.fromOpaque(pointer!).takeUnretainedValue() let retained = Unmanaged.passRetained(ref) - return unsafeBitCast(retained, to: UnsafePointer.self) + return unsafeBitCast(retained, to: UnsafeRawPointer.self) } // Release method for run loop source -private func runLoopSourceRelease(_ pointer : UnsafePointer?) -> Void { +private func runLoopSourceRelease(_ pointer : UnsafeRawPointer?) -> Void { Unmanaged.fromOpaque(pointer!).release() } // Equal method for run loop source -private func runloopIsEqual(_ a : UnsafePointer?, _ b : UnsafePointer?) -> _DarwinCompatibleBoolean { +private func runloopIsEqual(_ a : UnsafeRawPointer?, _ b : UnsafeRawPointer?) -> _DarwinCompatibleBoolean { let unmanagedrunLoopA = Unmanaged.fromOpaque(a!) guard let runLoopA = unmanagedrunLoopA.takeUnretainedValue() as? RunLoop else { @@ -72,7 +72,7 @@ private func runloopIsEqual(_ a : UnsafePointer?, _ b : UnsafePointer?, _ b : UnsafePointer?) -> _DarwinCompatibleBoolean { +private func nstaskIsEqual(_ a : UnsafeRawPointer?, _ b : UnsafeRawPointer?) -> _DarwinCompatibleBoolean { let unmanagedTaskA = Unmanaged.fromOpaque(a!) guard let taskA = unmanagedTaskA.takeUnretainedValue() as? Task else { @@ -108,7 +108,8 @@ public class Task: NSObject { emptySourceContext.equal = runloopIsEqual emptySourceContext.perform = emptyRunLoopCallback managerThreadRunLoop!.withUnretainedReference { - emptySourceContext.info = $0 + (refPtr: UnsafeMutablePointer) in + emptySourceContext.info = UnsafeMutableRawPointer(refPtr) } CFRunLoopAddSource(managerThreadRunLoop?._cfRunLoop, CFRunLoopSourceCreate(kCFAllocatorDefault, 0, &emptySourceContext), kCFRunLoopDefaultMode) @@ -212,7 +213,7 @@ public class Task: NSObject { defer { for arg in argv ..< argv + args.count { - free(UnsafeMutablePointer(arg.pointee)) + free(UnsafeMutableRawPointer(arg.pointee)) } argv.deallocate(capacity: args.count + 1) @@ -232,7 +233,7 @@ public class Task: NSObject { defer { if let env = environment { for pair in envp ..< envp + env.count { - free(UnsafeMutablePointer(pair.pointee)) + free(UnsafeMutableRawPointer(pair.pointee)) } envp.deallocate(capacity: env.count + 1) } @@ -244,7 +245,7 @@ public class Task: NSObject { context.version = 0 context.retain = runLoopSourceRetain context.release = runLoopSourceRelease - context.info = UnsafeMutablePointer(Unmanaged.passUnretained(self).toOpaque()) + context.info = Unmanaged.passUnretained(self).toOpaque() let socket = CFSocketCreateWithNative( nil, taskSocketPair[0], CFOptionFlags(kCFSocketDataCallBack), { (socket, type, address, data, info ) in @@ -368,7 +369,7 @@ public class Task: NSObject { self.runLoop = RunLoop.current() self.runLoopSourceContext = CFRunLoopSourceContext(version: 0, - info: UnsafeMutablePointer(Unmanaged.passUnretained(self).toOpaque()), + info: Unmanaged.passUnretained(self).toOpaque(), retain: { return runLoopSourceRetain($0) }, release: { runLoopSourceRelease($0) }, copyDescription: nil, @@ -386,7 +387,8 @@ public class Task: NSObject { runLoopContext.equal = nstaskIsEqual runLoopContext.perform = emptyRunLoopCallback self.withUnretainedReference { - runLoopContext.info = $0 + (refPtr: UnsafeMutablePointer) in + runLoopContext.info = UnsafeMutableRawPointer(refPtr) } self.runLoopSourceContext = runLoopContext diff --git a/Foundation/NSThread.swift b/Foundation/NSThread.swift index ced09ddcb2..03fab7c748 100644 --- a/Foundation/NSThread.swift +++ b/Foundation/NSThread.swift @@ -46,7 +46,7 @@ internal enum _NSThreadStatus { case finished } -private func NSThreadStart(_ context: UnsafeMutablePointer?) -> UnsafeMutablePointer? { +private func NSThreadStart(_ context: UnsafeMutableRawPointer?) -> UnsafeMutableRawPointer? { let thread: Thread = NSObject.unretainedReference(context!) Thread._currentThread.set(thread) thread._status = .executing diff --git a/Foundation/NSTimeZone.swift b/Foundation/NSTimeZone.swift index ef49564ea9..0d382da77d 100644 --- a/Foundation/NSTimeZone.swift +++ b/Foundation/NSTimeZone.swift @@ -13,9 +13,9 @@ import CoreFoundation public class TimeZone : NSObject, NSCopying, NSSecureCoding, NSCoding { typealias CFType = CFTimeZone private var _base = _CFInfo(typeID: CFTimeZoneGetTypeID()) - private var _name: UnsafeMutablePointer? = nil - private var _data: UnsafeMutablePointer? = nil - private var _periods: UnsafeMutablePointer? = nil + private var _name: UnsafeMutableRawPointer? = nil + private var _data: UnsafeMutableRawPointer? = nil + private var _periods: UnsafeMutableRawPointer? = nil private var _periodCnt = Int32(0) internal var _cfObject: CFType { @@ -86,7 +86,7 @@ public class TimeZone : NSObject, NSCopying, NSSecureCoding, NSCoding { public convenience init?(abbreviation: String) { let abbr = abbreviation._cfObject - guard let name = unsafeBitCast(CFDictionaryGetValue(CFTimeZoneCopyAbbreviationDictionary(), unsafeBitCast(abbr, to: UnsafePointer.self)), to: NSString!.self) else { + guard let name = unsafeBitCast(CFDictionaryGetValue(CFTimeZoneCopyAbbreviationDictionary(), unsafeBitCast(abbr, to: UnsafeRawPointer.self)), to: NSString!.self) else { return nil } self.init(name: name._swiftObject , data: nil) diff --git a/Foundation/NSTimer.swift b/Foundation/NSTimer.swift index 8925d242de..e397ed32e8 100644 --- a/Foundation/NSTimer.swift +++ b/Foundation/NSTimer.swift @@ -10,7 +10,7 @@ import CoreFoundation -internal func __NSFireTimer(_ timer: CFRunLoopTimer?, info: UnsafeMutablePointer?) -> Void { +internal func __NSFireTimer(_ timer: CFRunLoopTimer?, info: UnsafeMutableRawPointer?) -> Void { let t: Timer = NSObject.unretainedReference(info!) t._fire(t) } @@ -39,7 +39,8 @@ public class Timer: NSObject { _fire = block var context = CFRunLoopTimerContext() withRetainedReference { - context.info = $0 + (refPtr: UnsafeMutablePointer) in + context.info = UnsafeMutableRawPointer(refPtr) } let timer = withUnsafeMutablePointer(&context) { (ctx: UnsafeMutablePointer) -> CFRunLoopTimer in var t = interval diff --git a/Foundation/NSURL.swift b/Foundation/NSURL.swift index 5fad200c3c..c3600a0cba 100644 --- a/Foundation/NSURL.swift +++ b/Foundation/NSURL.swift @@ -343,10 +343,10 @@ public class NSURL: NSObject, NSSecureCoding, NSCopying { let bytesNeeded = CFURLGetBytes(_cfObject, nil, 0) assert(bytesNeeded > 0) - let buffer = malloc(bytesNeeded)! - let bytesFilled = CFURLGetBytes(_cfObject, UnsafeMutablePointer(buffer), bytesNeeded) + let buffer = malloc(bytesNeeded)!.bindMemory(to: UInt8.self, capacity: bytesNeeded) + let bytesFilled = CFURLGetBytes(_cfObject, buffer, bytesNeeded) if bytesFilled == bytesNeeded { - return Data(bytesNoCopy: UnsafeMutablePointer(buffer), count: bytesNeeded, deallocator: .none) + return Data(bytesNoCopy: buffer, count: bytesNeeded, deallocator: .none) } else { fatalError() } diff --git a/Foundation/NSUUID.swift b/Foundation/NSUUID.swift index 9d17245d60..e35bf3a2d1 100644 --- a/Foundation/NSUUID.swift +++ b/Foundation/NSUUID.swift @@ -32,7 +32,7 @@ public class NSUUID : NSObject, NSCopying, NSSecureCoding, NSCoding { } public init(UUIDBytes bytes: UnsafePointer) { - memcpy(unsafeBitCast(buffer, to: UnsafeMutablePointer.self), UnsafePointer(bytes), 16) + memcpy(unsafeBitCast(buffer, to: UnsafeMutableRawPointer.self), UnsafeRawPointer(bytes), 16) } public func getUUIDBytes(_ uuid: UnsafeMutablePointer) { diff --git a/Foundation/NSValue.swift b/Foundation/NSValue.swift index b59834be37..5578cc300e 100644 --- a/Foundation/NSValue.swift +++ b/Foundation/NSValue.swift @@ -76,7 +76,7 @@ public class NSValue : NSObject, NSCopying, NSSecureCoding, NSCoding { } } - public func getValue(_ value: UnsafeMutablePointer) { + public func getValue(_ value: UnsafeMutableRawPointer) { if self.dynamicType == NSValue.self { return _concreteValue.getValue(value) } else { @@ -96,7 +96,7 @@ public class NSValue : NSObject, NSCopying, NSSecureCoding, NSCoding { return NSSpecialValue._typeFromObjCType(type) != nil } - public convenience required init(bytes value: UnsafePointer, objCType type: UnsafePointer) { + public convenience required init(bytes value: UnsafeRawPointer, objCType type: UnsafePointer) { if self.dynamicType == NSValue.self { self.init() if NSValue._isSpecialObjCType(type) { diff --git a/Foundation/NSXMLNode.swift b/Foundation/NSXMLNode.swift index c7765092da..c28bbc9224 100644 --- a/Foundation/NSXMLNode.swift +++ b/Foundation/NSXMLNode.swift @@ -719,7 +719,7 @@ public class XMLNode: NSObject, NSCopying { var result: [XMLNode] = [] for i in 0.., len: Int32) -> Void { let parser = ctx.parser if let delegate = parser.delegate { - delegate.parser(parser, foundCDATA: Data(bytes: UnsafePointer(value), count: Int(len))) + delegate.parser(parser, foundCDATA: Data(bytes: UnsafeRawPointer(value), count: Int(len))) } } @@ -565,13 +565,13 @@ public class XMLParser : NSObject { XMLParser.setCurrentParser(self) if let stream = _stream { stream.open() - let buffer = malloc(_chunkSize)! - var len = stream.read(UnsafeMutablePointer(buffer), maxLength: _chunkSize) + let buffer = malloc(_chunkSize)!.bindMemory(to: UInt8.self, capacity: _chunkSize) + var len = stream.read(buffer, maxLength: _chunkSize) if len != -1 { while len > 0 { - let data = Data(bytesNoCopy: UnsafeMutablePointer(buffer), count: len, deallocator: .none) + let data = Data(bytesNoCopy: buffer, count: len, deallocator: .none) result = parseData(data) - len = stream.read(UnsafeMutablePointer(buffer), maxLength: _chunkSize) + len = stream.read(buffer, maxLength: _chunkSize) } } else { result = false @@ -579,7 +579,7 @@ public class XMLParser : NSObject { free(buffer) stream.close() } else if let data = _data { - let buffer = malloc(_chunkSize)! + let buffer = malloc(_chunkSize)!.bindMemory(to: UInt8.self, capacity: _chunkSize) var range = NSMakeRange(0, min(_chunkSize, data.count)) while result { let chunk = data.withUnsafeBytes { (buffer: UnsafePointer) -> Data in diff --git a/Foundation/String.swift b/Foundation/String.swift index e535029052..bc06fe4aba 100644 --- a/Foundation/String.swift +++ b/Foundation/String.swift @@ -653,7 +653,7 @@ extension String { /// in a given encoding, and optionally frees the buffer. WARNING: /// this initializer is not memory-safe! public init?( - bytesNoCopy bytes: UnsafeMutablePointer, length: Int, + bytesNoCopy bytes: UnsafeMutableRawPointer, length: Int, encoding: Encoding, freeWhenDone flag: Bool ) { if let ns = NSString( diff --git a/TestFoundation/TestNSArray.swift b/TestFoundation/TestNSArray.swift index c2e15ed33e..b11685802d 100644 --- a/TestFoundation/TestNSArray.swift +++ b/TestFoundation/TestNSArray.swift @@ -363,12 +363,12 @@ class TestNSArray : XCTestCase { let mutableInput = inputNumbers.bridge().mutableCopy() as! NSMutableArray let expectedNumbers = inputNumbers.sorted() - func compare(_ left: AnyObject, right:AnyObject, context: UnsafeMutablePointer?) -> Int { + func compare(_ left: AnyObject, right:AnyObject, context: UnsafeMutableRawPointer?) -> Int { let l = (left as! NSNumber).intValue let r = (right as! NSNumber).intValue return l < r ? -1 : (l > r ? 0 : 1) } - mutableInput.sortUsingFunction(compare, context: UnsafeMutablePointer(bitPattern: 0)) + mutableInput.sortUsingFunction(compare, context: UnsafeMutableRawPointer(bitPattern: 0)) XCTAssertEqual(mutableInput.map { ($0 as! NSNumber).intValue}, expectedNumbers) } diff --git a/TestFoundation/TestNSJSONSerialization.swift b/TestFoundation/TestNSJSONSerialization.swift index bc33dbe978..8260214e13 100644 --- a/TestFoundation/TestNSJSONSerialization.swift +++ b/TestFoundation/TestNSJSONSerialization.swift @@ -45,7 +45,7 @@ extension TestNSJSONSerialization { } func test_JSONObjectWithData_emptyObject() { - let subject = Data(bytes: UnsafePointer([UInt8]([0x7B, 0x7D])), count: 2) + let subject = Data(bytes: UnsafeRawPointer([UInt8]([0x7B, 0x7D])), count: 2) let object = try! JSONSerialization.jsonObject(with: subject, options: []) as? [String:Any] XCTAssertEqual(object?.count, 0) @@ -75,7 +75,7 @@ extension TestNSJSONSerialization { ] for (description, encoded) in subjects { - let result = try? JSONSerialization.jsonObject(with: Data(bytes:UnsafePointer(encoded), count: encoded.count), options: []) + let result = try? JSONSerialization.jsonObject(with: Data(bytes:UnsafeRawPointer(encoded), count: encoded.count), options: []) XCTAssertNotNil(result, description) } } diff --git a/TestFoundation/TestNSKeyedArchiver.swift b/TestFoundation/TestNSKeyedArchiver.swift index 56f006778a..4925199f9b 100644 --- a/TestFoundation/TestNSKeyedArchiver.swift +++ b/TestFoundation/TestNSKeyedArchiver.swift @@ -151,7 +151,7 @@ class TestNSKeyedArchiver : XCTestCase { decode: {unarchiver -> Bool in var expected: Array = [0, 0, 0, 0] expected.withUnsafeMutableBufferPointer {(p: inout UnsafeMutableBufferPointer) in - unarchiver.decodeValue(ofObjCType: "[4i]", at: UnsafeMutablePointer(p.baseAddress!)) + unarchiver.decodeValue(ofObjCType: "[4i]", at: UnsafeMutableRawPointer(p.baseAddress!)) } XCTAssertEqual(expected, array) return true diff --git a/TestFoundation/TestNSXMLParser.swift b/TestFoundation/TestNSXMLParser.swift index 34744938bc..779a6a7a49 100644 --- a/TestFoundation/TestNSXMLParser.swift +++ b/TestFoundation/TestNSXMLParser.swift @@ -28,7 +28,7 @@ class TestNSXMLParser : XCTestCase { func test_data() { let xml = Array("bar".nulTerminatedUTF8) let data = xml.withUnsafeBufferPointer { (buffer: UnsafeBufferPointer) -> Data in - return Data(bytes:UnsafePointer(buffer.baseAddress!), count: buffer.count) + return Data(bytes:UnsafeRawPointer(buffer.baseAddress!), count: buffer.count) } let parser = XMLParser(data: data) let res = parser.parse()