From 8c9a8e4b6da14c380b9bf03237cc370b053092c2 Mon Sep 17 00:00:00 2001 From: Andrew Trick Date: Tue, 26 Jul 2016 22:39:58 -0700 Subject: [PATCH] Remove "illegal" UnsafePointer casts from the stdlib. Update for SE-0107: UnsafeRawPointer This adds a "mutating" initialize to UnsafePointer to make Immutable -> Mutable conversions explicit. These are quick fixes to stdlib, overlays, and test cases that are necessary in order to remove arbitrary UnsafePointer conversions. Many cases can be expressed better up by reworking the surrounding code, but we first need a working starting point. --- .../SwiftPrivateLibcExtras.swift | 18 ++- .../SwiftPrivatePthreadExtras.swift | 2 +- stdlib/public/SDK/Dispatch/Data.swift | 9 +- stdlib/public/SDK/Foundation/Data.swift | 5 +- .../public/SDK/Foundation/NSStringAPI.swift | 16 +-- stdlib/public/SDK/SceneKit/SceneKit.swift | 4 +- stdlib/public/core/ArrayBuffer.swift | 10 +- stdlib/public/core/BridgeObjectiveC.swift | 30 ++++- stdlib/public/core/Builtin.swift | 8 +- stdlib/public/core/CocoaArray.swift | 3 +- .../public/core/ContiguousArrayBuffer.swift | 3 +- .../core/FloatingPointParsing.swift.gyb | 5 +- .../public/core/HashedCollections.swift.gyb | 21 +-- stdlib/public/core/HeapBuffer.swift | 11 +- stdlib/public/core/InputStream.swift | 4 +- stdlib/public/core/LifetimeManager.swift | 4 +- stdlib/public/core/ManagedBuffer.swift | 10 +- stdlib/public/core/Runtime.swift.gyb | 46 ++++--- stdlib/public/core/String.swift | 15 ++- stdlib/public/core/StringBridge.swift | 2 +- stdlib/public/core/StringBuffer.swift | 3 +- stdlib/public/core/SwiftNativeNSArray.swift | 3 +- stdlib/public/core/Unicode.swift | 4 +- stdlib/public/core/UnsafePointer.swift.gyb | 21 +++ stdlib/public/core/UnsafeRawPointer.swift.gyb | 12 +- test/1_stdlib/BridgeNonVerbatim.swift | 6 +- test/1_stdlib/NSStringAPI.swift | 4 +- test/1_stdlib/StringAPI.swift | 66 +++++----- test/1_stdlib/TestUUID.swift | 2 +- test/Constraints/lvalues.swift | 2 +- .../SDK/archiving_generic_swift_class.swift | 14 +- test/Interpreter/SDK/objc_inner_pointer.swift | 4 +- test/Parse/pointer_conversion.swift.gyb | 10 +- test/decl/subscript/addressors.swift | 4 +- validation-test/stdlib/AtomicInt.swift | 3 +- validation-test/stdlib/CoreAudio.swift | 49 ++++--- validation-test/stdlib/NewArray.swift.gyb | 5 +- .../Prototypes/PersistentVector.swift.gyb | 124 +++++++++--------- 38 files changed, 334 insertions(+), 228 deletions(-) diff --git a/stdlib/private/SwiftPrivateLibcExtras/SwiftPrivateLibcExtras.swift b/stdlib/private/SwiftPrivateLibcExtras/SwiftPrivateLibcExtras.swift index 99742825d1d17..ab10cc58e7546 100644 --- a/stdlib/private/SwiftPrivateLibcExtras/SwiftPrivateLibcExtras.swift +++ b/stdlib/private/SwiftPrivateLibcExtras/SwiftPrivateLibcExtras.swift @@ -25,9 +25,13 @@ public func _stdlib_mkstemps(_ template: inout String, _ suffixlen: CInt) -> CIn var utf8 = template.nulTerminatedUTF8 let (fd, fileName) = utf8.withUnsafeMutableBufferPointer { (utf8) -> (CInt, String) in - let fd = mkstemps(UnsafeMutablePointer(utf8.baseAddress!), suffixlen) - let fileName = String(cString: utf8.baseAddress!) - return (fd, fileName) + return utf8.baseAddress!.withMemoryRebound( + to: CChar.self, capacity: Int(suffixlen)) { + + let fd = mkstemps($0, suffixlen) + let fileName = String(cString: $0) + return (fd, fileName) + } } template = fileName return fd @@ -97,11 +101,13 @@ public func _stdlib_select( let readAddr = readfds.baseAddress let writeAddr = writefds.baseAddress let errorAddr = errorfds.baseAddress + let bindAsFdSet = { (p: UnsafeMutablePointer?) in + UnsafeMutableRawPointer(p)?.assumingMemoryBound(to: fd_set.self) } return select( _stdlib_FD_SETSIZE, - UnsafeMutablePointer(readAddr), - UnsafeMutablePointer(writeAddr), - UnsafeMutablePointer(errorAddr), + bindAsFdSet(readAddr), + bindAsFdSet(writeAddr), + bindAsFdSet(errorAddr), timeout) } } diff --git a/stdlib/private/SwiftPrivatePthreadExtras/SwiftPrivatePthreadExtras.swift b/stdlib/private/SwiftPrivatePthreadExtras/SwiftPrivatePthreadExtras.swift index f3a9bbaa8452e..ed8380e88c7d0 100644 --- a/stdlib/private/SwiftPrivatePthreadExtras/SwiftPrivatePthreadExtras.swift +++ b/stdlib/private/SwiftPrivatePthreadExtras/SwiftPrivatePthreadExtras.swift @@ -113,7 +113,7 @@ public class _stdlib_Barrier { var _pthreadBarrier: _stdlib_pthread_barrier_t var _pthreadBarrierPtr: UnsafeMutablePointer<_stdlib_pthread_barrier_t> { - return UnsafeMutablePointer(_getUnsafePointerToStoredProperties(self)) + return _getUnsafePointerToStoredProperties(self).assumingMemoryBound(to: _stdlib_pthread_barrier_t.self) } public init(threadCount: Int) { diff --git a/stdlib/public/SDK/Dispatch/Data.swift b/stdlib/public/SDK/Dispatch/Data.swift index a33381932208f..274b3ede8ec75 100644 --- a/stdlib/public/SDK/Dispatch/Data.swift +++ b/stdlib/public/SDK/Dispatch/Data.swift @@ -114,10 +114,12 @@ public struct DispatchData : RandomAccessCollection, _ObjectiveCBridgeable { /// /// - parameter buffer: The buffer of bytes to append. The size is calculated from `SourceType` and `buffer.count`. public mutating func append(_ buffer : UnsafeBufferPointer) { - self.append(UnsafePointer(buffer.baseAddress!), count: buffer.count * sizeof(SourceType.self)) + buffer.baseAddress!.withMemoryRebound(to: UInt8.self, capacity: buffer.count * sizeof(SourceType.self)) { + self.append($0, count: buffer.count * sizeof(SourceType.self)) + } } - private func _copyBytesHelper(to pointer: UnsafeMutablePointer, from range: CountableRange) { + private func _copyBytesHelper(to pointer: UnsafeMutableRawPointer, from range: CountableRange) { var copiedCount = 0 __dispatch_data_apply(__wrapped) { (data: __DispatchData, offset: Int, ptr: UnsafeRawPointer, size: Int) in let limit = Swift.min((range.endIndex - range.startIndex) - copiedCount, size) @@ -172,8 +174,7 @@ public struct DispatchData : RandomAccessCollection, _ObjectiveCBridgeable { guard !copyRange.isEmpty else { return 0 } - let pointer : UnsafeMutablePointer = UnsafeMutablePointer(buffer.baseAddress!) - _copyBytesHelper(to: pointer, from: copyRange) + _copyBytesHelper(to: buffer.baseAddress!, from: copyRange) return copyRange.count } diff --git a/stdlib/public/SDK/Foundation/Data.swift b/stdlib/public/SDK/Foundation/Data.swift index c2039ab76baa0..e3c85fea02d97 100644 --- a/stdlib/public/SDK/Foundation/Data.swift +++ b/stdlib/public/SDK/Foundation/Data.swift @@ -316,7 +316,7 @@ public struct Data : ReferenceConvertible, Equatable, Hashable, RandomAccessColl _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) } } @@ -357,8 +357,7 @@ public struct Data : ReferenceConvertible, Equatable, Hashable, RandomAccessColl guard !copyRange.isEmpty else { return 0 } let nsRange = NSMakeRange(copyRange.lowerBound, copyRange.upperBound - copyRange.lowerBound) - let pointer : UnsafeMutablePointer = UnsafeMutablePointer(buffer.baseAddress!) - _copyBytesHelper(to: pointer, from: nsRange) + _copyBytesHelper(to: buffer.baseAddress!, from: nsRange) return copyRange.count } diff --git a/stdlib/public/SDK/Foundation/NSStringAPI.swift b/stdlib/public/SDK/Foundation/NSStringAPI.swift index 9b5a728617f39..138a1393185e8 100644 --- a/stdlib/public/SDK/Foundation/NSStringAPI.swift +++ b/stdlib/public/SDK/Foundation/NSStringAPI.swift @@ -387,12 +387,10 @@ extension String { outputArray in // FIXME: completePath(...) is incorrectly annotated as requiring // non-optional output parameters. rdar://problem/25494184 - let outputNonOptionalName = AutoreleasingUnsafeMutablePointer( - UnsafeMutablePointer(outputName) - ) - let outputNonOptionalArray = AutoreleasingUnsafeMutablePointer( - UnsafeMutablePointer(outputArray) - ) + let outputNonOptionalName = unsafeBitCast(outputName, + to: AutoreleasingUnsafeMutablePointer.self) + let outputNonOptionalArray = unsafeBitCast(outputArray, + to: AutoreleasingUnsafeMutablePointer.self) return self._ns.completePath( into: outputNonOptionalName, caseSensitive: caseSensitive, @@ -505,7 +503,7 @@ extension String { var stop_ = false body(line: line, stop: &stop_) if stop_ { - UnsafeMutablePointer(stop).pointee = true + stop.pointee = true } } } @@ -541,7 +539,7 @@ extension String { var stop_ = false body($0, self._range($1), self._range($2), &stop_) if stop_ { - UnsafeMutablePointer($3).pointee = true + ($3).pointee = true } } } @@ -823,7 +821,7 @@ extension String { freeWhenDone flag: Bool ) { self = NSString( - charactersNoCopy: UnsafeMutablePointer(utf16CodeUnitsNoCopy), + charactersNoCopy: UnsafeMutablePointer(mutating: utf16CodeUnitsNoCopy), length: count, freeWhenDone: flag) as String } diff --git a/stdlib/public/SDK/SceneKit/SceneKit.swift b/stdlib/public/SDK/SceneKit/SceneKit.swift index 90c012e7cb9e9..164ffd1ab3f7a 100644 --- a/stdlib/public/SDK/SceneKit/SceneKit.swift +++ b/stdlib/public/SDK/SceneKit/SceneKit.swift @@ -169,8 +169,10 @@ extension SCNGeometryElement { case .polygon: fatalError("Expected constant number of indices per primitive") } + // FIXME: Data should have an initializer for raw pointers. + let bytePtr = unsafeBitCast(UnsafeRawPointer(indices), to: UnsafePointer.self) self.init( - data: Data(bytes: UnsafePointer(indices), count: indexCount * sizeof(IndexType.self)), + data: Data(bytes: bytePtr, count: indexCount * sizeof(IndexType.self)), primitiveType: primitiveType, primitiveCount: primitiveCount, bytesPerIndex: sizeof(IndexType.self)) diff --git a/stdlib/public/core/ArrayBuffer.swift b/stdlib/public/core/ArrayBuffer.swift index 2d26672a2ac63..84dd3c952e8fc 100644 --- a/stdlib/public/core/ArrayBuffer.swift +++ b/stdlib/public/core/ArrayBuffer.swift @@ -204,7 +204,8 @@ extension _ArrayBuffer { location: bounds.lowerBound, length: bounds.upperBound - bounds.lowerBound) - let buffer = UnsafeMutablePointer(target) + let buffer = UnsafeMutableRawPointer(target).assumingMemoryBound( + to: AnyObject.self) // Copies the references out of the NSArray without retaining them nonNative.getObjects(buffer, range: nsSubRange) @@ -242,9 +243,11 @@ extension _ArrayBuffer { cocoa.contiguousStorage(Range(self.indices)) if let cocoaStorageBaseAddress = cocoaStorageBaseAddress { + let basePtr = UnsafeMutableRawPointer(cocoaStorageBaseAddress) + .assumingMemoryBound(to: Element.self) return _SliceBuffer( owner: nonNative, - subscriptBaseAddress: UnsafeMutablePointer(cocoaStorageBaseAddress), + subscriptBaseAddress: basePtr, indices: bounds, hasNativeBuffer: false) } @@ -255,7 +258,8 @@ extension _ArrayBuffer { // Tell Cocoa to copy the objects into our storage cocoa.buffer.getObjects( - UnsafeMutablePointer(result.firstElementAddress), + UnsafeMutableRawPointer(result.firstElementAddress) + .assumingMemoryBound(to: AnyObject.self), range: _SwiftNSRange(location: bounds.lowerBound, length: boundsCount)) return _SliceBuffer(result, shiftedToStartIndex: bounds.lowerBound) diff --git a/stdlib/public/core/BridgeObjectiveC.swift b/stdlib/public/core/BridgeObjectiveC.swift index cbb9cb79ed6b5..e05a6560e25cf 100644 --- a/stdlib/public/core/BridgeObjectiveC.swift +++ b/stdlib/public/core/BridgeObjectiveC.swift @@ -362,7 +362,7 @@ public struct AutoreleasingUnsafeMutablePointer /// Retrieve the value the pointer points to. @_transparent get { // We can do a strong load normally. - return UnsafeMutablePointer(self).pointee + return unsafeBitCast(self, to: UnsafeMutablePointer.self).pointee } /// Set the value the pointer points to, copying over the previous value. /// @@ -409,6 +409,9 @@ public struct AutoreleasingUnsafeMutablePointer /// This is inherently unsafe; UnsafeMutablePointer assumes the /// referenced memory has +1 strong ownership semantics, whereas /// AutoreleasingUnsafeMutablePointer implies +0 semantics. + /// + /// - Warning: Accessing `pointee` as a type that is unrelated to + /// the underlying memory's bound type is undefined. @_transparent public init(_ from: UnsafeMutablePointer) { self._rawValue = from._rawValue @@ -421,6 +424,9 @@ public struct AutoreleasingUnsafeMutablePointer /// This is inherently unsafe; UnsafeMutablePointer assumes the /// referenced memory has +1 strong ownership semantics, whereas /// AutoreleasingUnsafeMutablePointer implies +0 semantics. + /// + /// - Warning: Accessing `pointee` as a type that is unrelated to + /// the underlying memory's bound type is undefined. @_transparent public init?(_ from: UnsafeMutablePointer?) { guard let unwrapped = from else { return nil } @@ -431,6 +437,9 @@ public struct AutoreleasingUnsafeMutablePointer /// /// This is inherently unsafe because UnsafePointers do not imply /// mutability. + /// + /// - Warning: Accessing `pointee` as a type that is unrelated to + /// the underlying memory's bound type is undefined. @_transparent init(_ from: UnsafePointer) { self._rawValue = from._rawValue @@ -442,6 +451,9 @@ public struct AutoreleasingUnsafeMutablePointer /// /// This is inherently unsafe because UnsafePointers do not imply /// mutability. + /// + /// - Warning: Accessing `pointee` as a type that is unrelated to + /// the underlying memory's bound type is undefined. @_transparent init?(_ from: UnsafePointer?) { guard let unwrapped = from else { return nil } @@ -449,6 +461,22 @@ public struct AutoreleasingUnsafeMutablePointer } } +extension UnsafeMutableRawPointer { + /// Convert from `AutoreleasingUnsafeMutablePointer`. + @_transparent + public init(_ from: AutoreleasingUnsafeMutablePointer) { + _rawValue = from._rawValue + } +} + +extension UnsafeRawPointer { + /// Convert from `AutoreleasingUnsafeMutablePointer`. + @_transparent + public init(_ from: AutoreleasingUnsafeMutablePointer) { + _rawValue = from._rawValue + } +} + extension AutoreleasingUnsafeMutablePointer : CustomDebugStringConvertible { /// A textual representation of `self`, suitable for debugging. public var debugDescription: String { diff --git a/stdlib/public/core/Builtin.swift b/stdlib/public/core/Builtin.swift index fe185810b0038..eec79cc093b73 100644 --- a/stdlib/public/core/Builtin.swift +++ b/stdlib/public/core/Builtin.swift @@ -89,8 +89,8 @@ internal func _roundUp(_ offset: Int, toAlignment alignment: Int) -> Int { } @_versioned -internal func _roundUp( - _ pointer: UnsafeMutablePointer, +internal func _roundUp( + _ pointer: UnsafeMutableRawPointer, toAlignmentOf destinationType: DestinationType.Type ) -> UnsafeMutablePointer { // Note: unsafe unwrap is safe because this operation can only increase the @@ -245,11 +245,11 @@ public func unsafeDowncast(_ x: AnyObject, to: T.Type) -> T { @inline(__always) public func _getUnsafePointerToStoredProperties(_ x: AnyObject) - -> UnsafeMutablePointer { + -> UnsafeMutableRawPointer { let storedPropertyOffset = _roundUp( sizeof(_HeapObject.self), toAlignment: alignof(Optional.self)) - return UnsafeMutablePointer(Builtin.bridgeToRawPointer(x)) + + return UnsafeMutableRawPointer(Builtin.bridgeToRawPointer(x)) + storedPropertyOffset } diff --git a/stdlib/public/core/CocoaArray.swift b/stdlib/public/core/CocoaArray.swift index b67a65bfa4b5b..fc8f882922077 100644 --- a/stdlib/public/core/CocoaArray.swift +++ b/stdlib/public/core/CocoaArray.swift @@ -66,7 +66,8 @@ internal struct _CocoaArrayWrapper : RandomAccessCollection { } return contiguousCount >= subRange.upperBound - ? UnsafeMutablePointer(enumerationState.itemsPtr!) + ? UnsafeMutableRawPointer(enumerationState.itemsPtr!) + .assumingMemoryBound(to: AnyObject.self) + subRange.lowerBound : nil } diff --git a/stdlib/public/core/ContiguousArrayBuffer.swift b/stdlib/public/core/ContiguousArrayBuffer.swift index 3f372d27c08fb..251967a9532d5 100644 --- a/stdlib/public/core/ContiguousArrayBuffer.swift +++ b/stdlib/public/core/ContiguousArrayBuffer.swift @@ -115,7 +115,8 @@ final class _ContiguousArrayStorage : _ContiguousArrayStorage1 { ) rethrows { if _isBridgedVerbatimToObjectiveC(Element.self) { let count = __manager.header.count - let elements = UnsafePointer(__manager._elementPointer) + let elements = UnsafeMutableRawPointer(__manager._elementPointer) + .assumingMemoryBound(to: AnyObject.self) defer { _fixLifetime(__manager) } try body(UnsafeBufferPointer(start: elements, count: count)) } diff --git a/stdlib/public/core/FloatingPointParsing.swift.gyb b/stdlib/public/core/FloatingPointParsing.swift.gyb index 83c13344eb119..b60d7b43f77ea 100644 --- a/stdlib/public/core/FloatingPointParsing.swift.gyb +++ b/stdlib/public/core/FloatingPointParsing.swift.gyb @@ -57,10 +57,9 @@ extension ${Self} { func parseNTBS(_ chars: UnsafePointer) -> (${Self}, Int) { var result: ${Self} = 0 let endPtr = withUnsafeMutablePointer(to: &result) { - _swift_stdlib_strto${cFuncSuffix2[bits]}_clocale( - chars, UnsafeMutablePointer($0)) + _swift_stdlib_strto${cFuncSuffix2[bits]}_clocale(chars, $0) } - return (result, endPtr == nil ? 0 : UnsafePointer(endPtr!) - chars) + return (result, endPtr == nil ? 0 : endPtr! - chars) } let (result, n) = text.withCString(parseNTBS) diff --git a/stdlib/public/core/HashedCollections.swift.gyb b/stdlib/public/core/HashedCollections.swift.gyb index d7ae828f2b05c..fd87b097bd050 100644 --- a/stdlib/public/core/HashedCollections.swift.gyb +++ b/stdlib/public/core/HashedCollections.swift.gyb @@ -2585,7 +2585,7 @@ final internal class _Native${Self}StorageImpl<${TypeParameters}> : _UnsafeBitMap.sizeInWords(forSizeInBits: _body.capacity), strideof(UInt.self)) let start = - UnsafeMutablePointer(_initializedHashtableEntriesBitMapStorage) + UnsafeMutableRawPointer(_initializedHashtableEntriesBitMapStorage) + bitMapSizeInBytes return _roundUp(start, toAlignmentOf: Key.self) } @@ -2594,7 +2594,7 @@ final internal class _Native${Self}StorageImpl<${TypeParameters}> : // This API is unsafe and needs a `_fixLifetime` in the caller. internal var _values: UnsafeMutablePointer { let keysSizeInBytes = _unsafeMultiply(_body.capacity, strideof(Key.self)) - let start = UnsafeMutablePointer(_keys) + keysSizeInBytes + let start = UnsafeMutableRawPointer(_keys) + keysSizeInBytes return _roundUp(start, toAlignmentOf: Value.self) } %end @@ -3360,7 +3360,8 @@ final internal class _Native${Self}StorageOwner<${TypeParametersDecl}> /// Returns the pointer to the stored property, which contains bridged /// ${Self} elements. internal var _heapBufferBridgedPtr: UnsafeMutablePointer { - return UnsafeMutablePointer(_getUnsafePointerToStoredProperties(self)) + return _getUnsafePointerToStoredProperties(self).assumingMemoryBound( + to: Optional.self) } /// The storage for bridged ${Self} elements, if present. @@ -4755,12 +4756,14 @@ final internal class _Cocoa${Self}Iterator : IteratorProtocol { internal var _fastEnumerationStatePtr: UnsafeMutablePointer<_SwiftNSFastEnumerationState> { - return UnsafeMutablePointer(_getUnsafePointerToStoredProperties(self)) + return _getUnsafePointerToStoredProperties(self).assumingMemoryBound( + to: _SwiftNSFastEnumerationState.self) } internal var _fastEnumerationStackBufPtr: UnsafeMutablePointer<_CocoaFastEnumerationStackBuf> { - return UnsafeMutablePointer(_fastEnumerationStatePtr + 1) + return UnsafeMutableRawPointer(_fastEnumerationStatePtr + 1) + .assumingMemoryBound(to: _CocoaFastEnumerationStackBuf.self) } // These members have to be word-sized integers, they cannot be limited to @@ -4789,7 +4792,8 @@ final internal class _Cocoa${Self}Iterator : IteratorProtocol { // state struct. itemCount = cocoa${Self}.countByEnumerating( with: _fastEnumerationStatePtr, - objects: UnsafeMutablePointer(_fastEnumerationStackBufPtr), + objects: UnsafeMutableRawPointer(_fastEnumerationStackBufPtr) + .assumingMemoryBound(to: AnyObject.self), count: stackBufCount) if itemCount == 0 { itemIndex = -1 @@ -4797,8 +4801,9 @@ final internal class _Cocoa${Self}Iterator : IteratorProtocol { } itemIndex = 0 } - let itemsPtrUP: UnsafeMutablePointer = - UnsafeMutablePointer(_fastEnumerationState.itemsPtr!) + let itemsPtrUP = + UnsafeMutableRawPointer(_fastEnumerationState.itemsPtr!) + .assumingMemoryBound(to: AnyObject.self) let itemsPtr = _UnmanagedAnyObjectArray(itemsPtrUP) let key: AnyObject = itemsPtr[itemIndex] itemIndex += 1 diff --git a/stdlib/public/core/HeapBuffer.swift b/stdlib/public/core/HeapBuffer.swift index 6a5e4d4e326ce..5244a4b4275ea 100644 --- a/stdlib/public/core/HeapBuffer.swift +++ b/stdlib/public/core/HeapBuffer.swift @@ -92,19 +92,20 @@ struct _HeapBuffer : Equatable { : (heapAlign < elementAlign ? elementAlign : heapAlign)) } - internal var _address: UnsafeMutablePointer { - return UnsafeMutablePointer( + internal var _address: UnsafeMutableRawPointer { + return UnsafeMutableRawPointer( Builtin.bridgeToRawPointer(self._nativeObject)) } internal var _value: UnsafeMutablePointer { - return UnsafeMutablePointer( - _HeapBuffer._valueOffset() + _address) + return (_HeapBuffer._valueOffset() + _address).assumingMemoryBound( + to: Value.self) } public // @testable var baseAddress: UnsafeMutablePointer { - return UnsafeMutablePointer(_HeapBuffer._elementOffset() + _address) + return (_HeapBuffer._elementOffset() + _address).assumingMemoryBound( + to: Element.self) } internal func _allocatedSize() -> Int { diff --git a/stdlib/public/core/InputStream.swift b/stdlib/public/core/InputStream.swift index 2386680b956e9..186b6f775a479 100644 --- a/stdlib/public/core/InputStream.swift +++ b/stdlib/public/core/InputStream.swift @@ -59,9 +59,11 @@ public func readLine(strippingNewline: Bool = true) -> String? { } } } + let lineBytes = UnsafeMutableRawPointer(linePtr).bindMemory( + to: UTF8.CodeUnit.self, capacity: readBytes) let result = String._fromCodeUnitSequenceWithRepair(UTF8.self, input: UnsafeMutableBufferPointer( - start: UnsafeMutablePointer(linePtr), + start: lineBytes, count: readBytes)).0 _swift_stdlib_free(linePtr) return result diff --git a/stdlib/public/core/LifetimeManager.swift b/stdlib/public/core/LifetimeManager.swift index 103df7b9e106f..2d428caab7217 100644 --- a/stdlib/public/core/LifetimeManager.swift +++ b/stdlib/public/core/LifetimeManager.swift @@ -43,8 +43,8 @@ extension String { public func withCString( _ body: @noescape (UnsafePointer) throws -> Result ) rethrows -> Result { - return try self.nulTerminatedUTF8.withUnsafeBufferPointer { - try body(UnsafePointer($0.baseAddress!)) + return try self.nulTerminatedUTF8CString.withUnsafeBufferPointer { + try body($0.baseAddress!) } } } diff --git a/stdlib/public/core/ManagedBuffer.swift b/stdlib/public/core/ManagedBuffer.swift index 7526bb1a2cd53..358d340221330 100644 --- a/stdlib/public/core/ManagedBuffer.swift +++ b/stdlib/public/core/ManagedBuffer.swift @@ -395,8 +395,8 @@ public struct ManagedBufferPointer : Equatable { } /// The address of this instance in a convenient pointer-to-bytes form - internal var _address: UnsafePointer { - return UnsafePointer(Builtin.bridgeToRawPointer(_nativeBuffer)) + internal var _address: UnsafeMutableRawPointer { + return UnsafeMutableRawPointer(Builtin.bridgeToRawPointer(_nativeBuffer)) } /// Offset from the allocated storage for `self` to the stored `Header` @@ -412,7 +412,8 @@ public struct ManagedBufferPointer : Equatable { /// guarantee it doesn't dangle internal var _headerPointer: UnsafeMutablePointer
{ _onFastPath() - return UnsafeMutablePointer(_address + _My._headerOffset) + return (_address + _My._headerOffset).assumingMemoryBound( + to: Header.self) } /// An **unmanaged** pointer to the storage for `Element`s. Not @@ -420,7 +421,8 @@ public struct ManagedBufferPointer : Equatable { /// dangle. internal var _elementPointer: UnsafeMutablePointer { _onFastPath() - return UnsafeMutablePointer(_address + _My._elementOffset) + return (_address + _My._elementOffset).assumingMemoryBound( + to: Element.self) } /// Offset from the allocated storage for `self` to the `Element` storage diff --git a/stdlib/public/core/Runtime.swift.gyb b/stdlib/public/core/Runtime.swift.gyb index f3c43ab355943..68e0c14140872 100644 --- a/stdlib/public/core/Runtime.swift.gyb +++ b/stdlib/public/core/Runtime.swift.gyb @@ -121,8 +121,9 @@ func _stdlib_atomicCompareExchangeStrongInt${bits}( expected: UnsafeMutablePointer, desired: Int${bits}) -> Bool { return _stdlib_atomicCompareExchangeStrongUInt${bits}( - object: UnsafeMutablePointer(target), - expected: UnsafeMutablePointer(expected), + object: unsafeBitCast(target, to: UnsafeMutablePointer.self), + expected: unsafeBitCast(expected, + to: UnsafeMutablePointer.self), desired: UInt${bits}(bitPattern: desired)) } @@ -139,7 +140,7 @@ func _swift_stdlib_atomicStoreInt${bits}( object target: UnsafeMutablePointer, desired: Int${bits}) { return _swift_stdlib_atomicStoreUInt${bits}( - object: UnsafeMutablePointer(target), + object: unsafeBitCast(target, to: UnsafeMutablePointer.self), desired: UInt${bits}(bitPattern: desired)) } @@ -155,7 +156,8 @@ func _swift_stdlib_atomicLoadInt${bits}( object target: UnsafeMutablePointer) -> Int${bits} { return Int${bits}(bitPattern: _swift_stdlib_atomicLoadUInt${bits}( - object: UnsafeMutablePointer(target))) + object: unsafeBitCast(target, + to: UnsafeMutablePointer.self))) } % for operation in ['Add', 'And', 'Or', 'Xor']: @@ -178,7 +180,7 @@ func _swift_stdlib_atomicFetch${operation}Int${bits}( operand: Int${bits}) -> Int${bits} { return Int${bits}(bitPattern: _swift_stdlib_atomicFetch${operation}UInt${bits}( - object: UnsafeMutablePointer(target), + object: unsafeBitCast(target, to: UnsafeMutablePointer.self), operand: UInt${bits}(bitPattern: operand))) } % end @@ -196,8 +198,8 @@ func _stdlib_atomicCompareExchangeStrongInt( desired: UInt32(bitPattern: Int32(desired))) #elseif arch(x86_64) || arch(arm64) || arch(powerpc64) || arch(powerpc64le) || arch(s390x) return _stdlib_atomicCompareExchangeStrongUInt64( - object: UnsafeMutablePointer(target), - expected: UnsafeMutablePointer(expected), + object: unsafeBitCast(target, to: UnsafeMutablePointer.self), + expected: unsafeBitCast(expected, to: UnsafeMutablePointer.self), desired: UInt64(bitPattern: Int64(desired))) #endif } @@ -211,7 +213,7 @@ func _swift_stdlib_atomicStoreInt( desired: UInt32(bitPattern: Int32(desired))) #elseif arch(x86_64) || arch(arm64) || arch(powerpc64) || arch(powerpc64le) || arch(s390x) return _swift_stdlib_atomicStoreUInt64( - object: UnsafeMutablePointer(target), + object: unsafeBitCast(target, to: UnsafeMutablePointer.self), desired: UInt64(bitPattern: Int64(desired))) #endif } @@ -226,7 +228,7 @@ public func _swift_stdlib_atomicLoadInt( #elseif arch(x86_64) || arch(arm64) || arch(powerpc64) || arch(powerpc64le) || arch(s390x) return Int(Int64(bitPattern: _swift_stdlib_atomicLoadUInt64( - object: UnsafeMutablePointer(target)))) + object: unsafeBitCast(target, to: UnsafeMutablePointer.self)))) #endif } @@ -245,7 +247,7 @@ func _stdlib_atomicLoadARCRef( object target: UnsafeMutablePointer ) -> AnyObject? { let result = _swift_stdlib_atomicLoadPtrImpl( - object: UnsafeMutablePointer(target)) + object: unsafeBitCast(target, to: UnsafeMutablePointer.self)) if let unwrapped = result { return Unmanaged.fromOpaque( UnsafePointer(unwrapped)).takeUnretainedValue() @@ -261,12 +263,12 @@ public func _swift_stdlib_atomicFetch${operation}Int( #if arch(i386) || arch(arm) return Int(Int32(bitPattern: _swift_stdlib_atomicFetch${operation}UInt32( - object: UnsafeMutablePointer(target), - operand: UInt32(bitPattern: Int32(operand))))) + object: unsafeBitCast(target, to: UnsafeMutablePointer.self), + operand: UInt32(bitPattern: Int32(operand))))) #elseif arch(x86_64) || arch(arm64) || arch(powerpc64) || arch(powerpc64le) || arch(s390x) return Int(Int64(bitPattern: _swift_stdlib_atomicFetch${operation}UInt64( - object: UnsafeMutablePointer(target), + object: unsafeBitCast(target, to: UnsafeMutablePointer.self), operand: UInt64(bitPattern: Int64(operand))))) #endif } @@ -276,7 +278,8 @@ public final class _stdlib_AtomicInt { var _value: Int var _valuePtr: UnsafeMutablePointer { - return UnsafeMutablePointer(_getUnsafePointerToStoredProperties(self)) + return _getUnsafePointerToStoredProperties(self).assumingMemoryBound( + to: Int.self) } public init(_ value: Int = 0) { @@ -383,7 +386,8 @@ func _float${bits}ToString(_ value: Float${bits}, debug: Bool) -> String { var buffer = _Buffer32() return withUnsafeMutablePointer(to: &buffer) { (bufferPtr) in - let bufferUTF8Ptr = UnsafeMutablePointer(bufferPtr) + let bufferUTF8Ptr = UnsafeMutableRawPointer(bufferPtr) + .bindMemory(to: UTF8.CodeUnit.self, capacity: 32) let actualLength = _float${bits}ToStringImpl(bufferUTF8Ptr, 32, value, debug) return String._fromWellFormedCodeUnitSequence( UTF8.self, @@ -412,7 +416,8 @@ func _int64ToString( var buffer = _Buffer32() return withUnsafeMutablePointer(to: &buffer) { (bufferPtr) in - let bufferUTF8Ptr = UnsafeMutablePointer(bufferPtr) + let bufferUTF8Ptr = UnsafeMutableRawPointer(bufferPtr) + .bindMemory(to: UTF8.CodeUnit.self, capacity: 32) let actualLength = _int64ToStringImpl(bufferUTF8Ptr, 32, value, radix, uppercase) return String._fromWellFormedCodeUnitSequence( @@ -424,7 +429,8 @@ func _int64ToString( var buffer = _Buffer72() return withUnsafeMutablePointer(to: &buffer) { (bufferPtr) in - let bufferUTF8Ptr = UnsafeMutablePointer(bufferPtr) + let bufferUTF8Ptr = UnsafeMutableRawPointer(bufferPtr).bindMemory( + to: UTF8.CodeUnit.self, capacity: 72) let actualLength = _int64ToStringImpl(bufferUTF8Ptr, 72, value, radix, uppercase) return String._fromWellFormedCodeUnitSequence( @@ -449,7 +455,8 @@ func _uint64ToString( var buffer = _Buffer32() return withUnsafeMutablePointer(to: &buffer) { (bufferPtr) in - let bufferUTF8Ptr = UnsafeMutablePointer(bufferPtr) + let bufferUTF8Ptr = UnsafeMutableRawPointer(bufferPtr) + .bindMemory(to: UTF8.CodeUnit.self, capacity: 32) let actualLength = _uint64ToStringImpl(bufferUTF8Ptr, 32, value, radix, uppercase) return String._fromWellFormedCodeUnitSequence( @@ -461,7 +468,8 @@ func _uint64ToString( var buffer = _Buffer72() return withUnsafeMutablePointer(to: &buffer) { (bufferPtr) in - let bufferUTF8Ptr = UnsafeMutablePointer(bufferPtr) + let bufferUTF8Ptr = UnsafeMutableRawPointer(bufferPtr) + .bindMemory(to: UTF8.CodeUnit.self, capacity: 72) let actualLength = _uint64ToStringImpl(bufferUTF8Ptr, 72, value, radix, uppercase) return String._fromWellFormedCodeUnitSequence( diff --git a/stdlib/public/core/String.swift b/stdlib/public/core/String.swift index 45f67a6dbc36b..d96dc2fd9a2da 100644 --- a/stdlib/public/core/String.swift +++ b/stdlib/public/core/String.swift @@ -584,8 +584,9 @@ extension String { #else switch (_core.isASCII, rhs._core.isASCII) { case (true, false): - let lhsPtr = UnsafePointer(_core.startASCII) - let rhsPtr = UnsafePointer(rhs._core.startUTF16) + let lhsPtr = unsafeBitCast(_core.startASCII, + to: UnsafePointer.self) + let rhsPtr = UnsafePointer(rhs._core.startUTF16) return Int(_swift_stdlib_unicode_compare_utf8_utf16( lhsPtr, Int32(_core.count), rhsPtr, Int32(rhs._core.count))) @@ -593,15 +594,17 @@ extension String { // Just invert it and recurse for this case. return -rhs._compareDeterministicUnicodeCollation(self) case (false, false): - let lhsPtr = UnsafePointer(_core.startUTF16) - let rhsPtr = UnsafePointer(rhs._core.startUTF16) + let lhsPtr = UnsafePointer(_core.startUTF16) + let rhsPtr = UnsafePointer(rhs._core.startUTF16) return Int(_swift_stdlib_unicode_compare_utf16_utf16( lhsPtr, Int32(_core.count), rhsPtr, Int32(rhs._core.count))) case (true, true): - let lhsPtr = UnsafePointer(_core.startASCII) - let rhsPtr = UnsafePointer(rhs._core.startASCII) + let lhsPtr = unsafeBitCast(_core.startASCII, + to: UnsafePointer.self) + let rhsPtr = unsafeBitCast(rhs._core.startASCII, + to: UnsafePointer.self) return Int(_swift_stdlib_unicode_compare_utf8_utf8( lhsPtr, Int32(_core.count), diff --git a/stdlib/public/core/StringBridge.swift b/stdlib/public/core/StringBridge.swift index f55fe4ea93518..6f3f816016e07 100644 --- a/stdlib/public/core/StringBridge.swift +++ b/stdlib/public/core/StringBridge.swift @@ -40,7 +40,7 @@ public // @testable func _stdlib_binary_CFStringGetCharactersPtr( _ source: _CocoaString ) -> UnsafeMutablePointer? { - return UnsafeMutablePointer(_swift_stdlib_CFStringGetCharactersPtr(source)) + return UnsafeMutablePointer(mutating: _swift_stdlib_CFStringGetCharactersPtr(source)) } /// Bridges `source` to `Swift.String`, assuming that `source` has non-ASCII diff --git a/stdlib/public/core/StringBuffer.swift b/stdlib/public/core/StringBuffer.swift index a890b248a2a67..c3a294a1b07f3 100644 --- a/stdlib/public/core/StringBuffer.swift +++ b/stdlib/public/core/StringBuffer.swift @@ -241,7 +241,8 @@ public struct _StringBuffer { // } // &StringBufferIVars.usedEnd - let usedEndPhysicalPtr = _PointerToPointer(_storage._value) + let usedEndPhysicalPtr = UnsafeMutableRawPointer(_storage._value) + .assumingMemoryBound(to: Optional.self) // Create a temp var to hold the exchanged `expected` value. var expected : UnsafeRawPointer? = bounds.upperBound if _stdlib_atomicCompareExchangeStrongPtr( diff --git a/stdlib/public/core/SwiftNativeNSArray.swift b/stdlib/public/core/SwiftNativeNSArray.swift index 333e9a18344eb..9ca385a1d90b2 100644 --- a/stdlib/public/core/SwiftNativeNSArray.swift +++ b/stdlib/public/core/SwiftNativeNSArray.swift @@ -138,7 +138,8 @@ extension _SwiftNativeNSArrayWithContiguousStorage : _NSArrayCore { internal let _nativeStorage: _ContiguousArrayStorageBase internal var _heapBufferBridgedPtr: UnsafeMutablePointer { - return UnsafeMutablePointer(_getUnsafePointerToStoredProperties(self)) + return _getUnsafePointerToStoredProperties(self).assumingMemoryBound( + to: Optional.self) } internal typealias HeapBufferStorage = _HeapBufferStorage diff --git a/stdlib/public/core/Unicode.swift b/stdlib/public/core/Unicode.swift index 73cb626062f0f..5fc1829030acc 100644 --- a/stdlib/public/core/Unicode.swift +++ b/stdlib/public/core/Unicode.swift @@ -427,7 +427,9 @@ public struct UTF8 : UnicodeCodec { } public static func _nullCodeUnitOffset(in input: UnsafePointer) -> Int { - return Int(_swift_stdlib_strlen(UnsafePointer(input))) + // Relying on a permissive memory model in C. + let cstr = unsafeBitCast(input, to: UnsafePointer.self) + return Int(_swift_stdlib_strlen(cstr)) } // Support parsing C strings as-if they are UTF8 strings. public static func _nullCodeUnitOffset(in input: UnsafePointer) -> Int { diff --git a/stdlib/public/core/UnsafePointer.swift.gyb b/stdlib/public/core/UnsafePointer.swift.gyb index b263f3f928a22..a507bc58f7c8b 100644 --- a/stdlib/public/core/UnsafePointer.swift.gyb +++ b/stdlib/public/core/UnsafePointer.swift.gyb @@ -69,6 +69,8 @@ public struct ${Self} } /// Construct ${a_Self} with a given pattern of bits. + /// + /// Returns nil if `bitPattern` is zero. @_transparent public init?(bitPattern: UInt) { if bitPattern == 0 { return nil } @@ -121,6 +123,25 @@ public struct ${Self} self.init(unwrapped) } +% if mutable: + /// Convert from `UnsafePointer` to `UnsafeMutablePointer` of the same + /// `Pointee`. + @_transparent + public init(mutating other: UnsafePointer) { + self._rawValue = other._rawValue + } + + /// Convert from `UnsafePointer` to `UnsafeMutablePointer` of the same + /// `Pointee`. + /// + /// Returns nil if `bitPattern` is zero. + @_transparent + public init?(mutating other: UnsafePointer?) { + guard let unwrapped = other else { return nil } + self.init(mutating: unwrapped) + } +% end + % if mutable: /// Allocate and point at uninitialized aligned memory for `count` /// instances of `Pointee`. diff --git a/stdlib/public/core/UnsafeRawPointer.swift.gyb b/stdlib/public/core/UnsafeRawPointer.swift.gyb index 28570535e8d44..6da5250352d08 100644 --- a/stdlib/public/core/UnsafeRawPointer.swift.gyb +++ b/stdlib/public/core/UnsafeRawPointer.swift.gyb @@ -27,13 +27,21 @@ public struct Unsafe${Mutable}RawPointer : Strideable, Hashable, _Pointer { /// Implements conformance to the public protocol `_Pointer`. public let _rawValue: Builtin.RawPointer - // Construct ${a_Self} from another ${a_Self}. - // FIXME: Why is this necessary? + /// Construct ${a_Self} from another ${a_Self}. @_transparent public init(_ other: Unsafe${Mutable}RawPointer) { self = other } + /// Construct ${a_Self} from another ${a_Self}. + /// + /// Returns nil if `other` is nil. + @_transparent + public init?(_ other: Unsafe${Mutable}RawPointer?) { + guard let unwrapped = other else { return nil } + self = unwrapped + } + /// Convert a builtin raw pointer to ${a_Self}. @_transparent public init(_ _rawValue: Builtin.RawPointer) { diff --git a/test/1_stdlib/BridgeNonVerbatim.swift b/test/1_stdlib/BridgeNonVerbatim.swift index 73d849fe668da..591ea88ae216e 100644 --- a/test/1_stdlib/BridgeNonVerbatim.swift +++ b/test/1_stdlib/BridgeNonVerbatim.swift @@ -92,9 +92,9 @@ func testScope() { objects.withUnsafeMutableBufferPointer { // FIXME: Can't elide signature and use $0 here (buf: inout UnsafeMutableBufferPointer) -> () in - nsx.getObjects( - UnsafeMutablePointer(buf.baseAddress!), - range: _SwiftNSRange(location: 1, length: 2)) + let objPtr = UnsafeMutableRawPointer(buf.baseAddress!).bindMemory( + to: AnyObject.self, capacity: 2) + nsx.getObjects(objPtr, range: _SwiftNSRange(location: 1, length: 2)) } // CHECK-NEXT: getObjects yields them at +0: true diff --git a/test/1_stdlib/NSStringAPI.swift b/test/1_stdlib/NSStringAPI.swift index 148573c318b57..55e5fb65886bb 100644 --- a/test/1_stdlib/NSStringAPI.swift +++ b/test/1_stdlib/NSStringAPI.swift @@ -204,7 +204,9 @@ NSStringAPIs.test("init(utf8String:)") { i += 1 } up[i] = 0 - expectOptionalEqual(s, String(utf8String: UnsafePointer(up))) + let cstr = UnsafeMutableRawPointer(up) + .bindMemory(to: CChar.self, capacity: 100) + expectOptionalEqual(s, String(utf8String: cstr)) up.deallocate(capacity: 100) } diff --git a/test/1_stdlib/StringAPI.swift b/test/1_stdlib/StringAPI.swift index 0d67034b87535..2735b08e1a6cf 100644 --- a/test/1_stdlib/StringAPI.swift +++ b/test/1_stdlib/StringAPI.swift @@ -320,19 +320,19 @@ StringTests.test("CompareStringsWithUnpairedSurrogates") var CStringTests = TestSuite("CStringTests") -func getNullCString() -> UnsafeMutablePointer? { +func getNullUTF8() -> UnsafeMutablePointer? { return nil } -func getASCIICString() -> (UnsafeMutablePointer, dealloc: () -> ()) { - let up = UnsafeMutablePointer.allocate(capacity: 100) +func getASCIIUTF8() -> (UnsafeMutablePointer, dealloc: () -> ()) { + let up = UnsafeMutablePointer.allocate(capacity: 100) up[0] = 0x61 up[1] = 0x62 up[2] = 0 return (up, { up.deallocate(capacity: 100) }) } -func getNonASCIICString() -> (UnsafeMutablePointer, dealloc: () -> ()) { +func getNonASCIIUTF8() -> (UnsafeMutablePointer, dealloc: () -> ()) { let up = UnsafeMutablePointer.allocate(capacity: 100) up[0] = 0xd0 up[1] = 0xb0 @@ -343,7 +343,7 @@ func getNonASCIICString() -> (UnsafeMutablePointer, dealloc: () -> ()) { } func getIllFormedUTF8String1( -) -> (UnsafeMutablePointer, dealloc: () -> ()) { +) -> (UnsafeMutablePointer, dealloc: () -> ()) { let up = UnsafeMutablePointer.allocate(capacity: 100) up[0] = 0x41 up[1] = 0xed @@ -355,7 +355,7 @@ func getIllFormedUTF8String1( } func getIllFormedUTF8String2( -) -> (UnsafeMutablePointer, dealloc: () -> ()) { +) -> (UnsafeMutablePointer, dealloc: () -> ()) { let up = UnsafeMutablePointer.allocate(capacity: 100) up[0] = 0x41 up[0] = 0x41 @@ -371,7 +371,7 @@ func asCCharArray(_ a: [UInt8]) -> [CChar] { return a.map { CChar(bitPattern: $0) } } -func getCStringLength(_ cString: UnsafePointer) -> Int { +func getUTF8Length(_ cString: UnsafePointer) -> Int { var length = 0 while cString[length] != 0 { length += 1 @@ -379,13 +379,13 @@ func getCStringLength(_ cString: UnsafePointer) -> Int { return length } -func bindAsUTF8(_ cString: UnsafePointer) -> UnsafePointer { - return UnsafeRawPointer(cString).bindMemory(to: UInt8.self, - capacity: getCStringLength(cString)) +func bindAsCChar(_ utf8: UnsafePointer) -> UnsafePointer { + return UnsafeRawPointer(utf8).bindMemory(to: CChar.self, + capacity: getUTF8Length(utf8)) } -func expectEqualCString(_ lhs: UnsafePointer, - _ rhs: UnsafePointer) { +func expectEqualCString(_ lhs: UnsafePointer, + _ rhs: UnsafePointer) { var index = 0 while lhs[index] != 0 { @@ -395,18 +395,18 @@ func expectEqualCString(_ lhs: UnsafePointer, expectEqual(0, rhs[index]) } -func expectEqualCString(_ lhs: UnsafePointer, - _ rhs: ContiguousArray) { +func expectEqualCString(_ lhs: UnsafePointer, + _ rhs: ContiguousArray) { rhs.withUnsafeBufferPointer { expectEqualCString(lhs, $0.baseAddress!) } } -func expectEqualCString(_ lhs: UnsafePointer, - _ rhs: ContiguousArray) { +func expectEqualCString(_ lhs: UnsafePointer, + _ rhs: ContiguousArray) { rhs.withUnsafeBufferPointer { $0.baseAddress!.withMemoryRebound( - to: CChar.self, capacity: rhs.count) { + to: UInt8.self, capacity: rhs.count) { expectEqualCString(lhs, $0) } } @@ -414,36 +414,36 @@ func expectEqualCString(_ lhs: UnsafePointer, CStringTests.test("String.init(validatingUTF8:)") { do { - let (s, dealloc) = getASCIICString() - expectOptionalEqual("ab", String(validatingUTF8: s)) + let (s, dealloc) = getASCIIUTF8() + expectOptionalEqual("ab", String(validatingUTF8: bindAsCChar(s))) dealloc() } do { - let (s, dealloc) = getNonASCIICString() - expectOptionalEqual("аб", String(validatingUTF8: s)) + let (s, dealloc) = getNonASCIIUTF8() + expectOptionalEqual("аб", String(validatingUTF8: bindAsCChar(s))) dealloc() } do { let (s, dealloc) = getIllFormedUTF8String1() - expectEmpty(String(validatingUTF8: s)) + expectEmpty(String(validatingUTF8: bindAsCChar(s))) dealloc() } } CStringTests.test("String(cString:)") { do { - let (s, dealloc) = getASCIICString() + let (s, dealloc) = getASCIIUTF8() let result = String(cString: s) expectEqual("ab", result) - let su = bindAsUTF8(s) + let su = bindAsCChar(s) expectEqual("ab", String(cString: su)) dealloc() } do { - let (s, dealloc) = getNonASCIICString() + let (s, dealloc) = getNonASCIIUTF8() let result = String(cString: s) expectEqual("аб", result) - let su = bindAsUTF8(s) + let su = bindAsCChar(s) expectEqual("аб", String(cString: su)) dealloc() } @@ -451,7 +451,7 @@ CStringTests.test("String(cString:)") { let (s, dealloc) = getIllFormedUTF8String1() let result = String(cString: s) expectEqual("\u{41}\u{fffd}\u{fffd}\u{fffd}\u{41}", result) - let su = bindAsUTF8(s) + let su = bindAsCChar(s) expectEqual("\u{41}\u{fffd}\u{fffd}\u{fffd}\u{41}", String(cString: su)) dealloc() } @@ -459,14 +459,14 @@ CStringTests.test("String(cString:)") { CStringTests.test("String.decodeCString") { do { - let s = getNullCString() - let result = String.decodeCString(UnsafePointer(s), as: UTF8.self) + let s = getNullUTF8() + let result = String.decodeCString(s, as: UTF8.self) expectEmpty(result) } do { // repairing let (s, dealloc) = getIllFormedUTF8String1() if let (result, repairsMade) = String.decodeCString( - UnsafePointer(s), as: UTF8.self, repairingInvalidCodeUnits: true) { + s, as: UTF8.self, repairingInvalidCodeUnits: true) { expectOptionalEqual("\u{41}\u{fffd}\u{fffd}\u{fffd}\u{41}", result) expectTrue(repairsMade) } else { @@ -477,7 +477,7 @@ CStringTests.test("String.decodeCString") { do { // non repairing let (s, dealloc) = getIllFormedUTF8String1() let result = String.decodeCString( - UnsafePointer(s), as: UTF8.self, repairingInvalidCodeUnits: false) + s, as: UTF8.self, repairingInvalidCodeUnits: false) expectEmpty(result) dealloc() } @@ -485,14 +485,14 @@ CStringTests.test("String.decodeCString") { CStringTests.test("String.nulTerminatedUTF8") { do { - let (cstr, dealloc) = getASCIICString() + let (cstr, dealloc) = getASCIIUTF8() let str = String(cString: cstr) expectEqualCString(cstr, str.nulTerminatedUTF8) expectEqualCString(cstr, str.nulTerminatedUTF8CString) dealloc() } do { - let (cstr, dealloc) = getNonASCIICString() + let (cstr, dealloc) = getNonASCIIUTF8() let str = String(cString: cstr) expectEqualCString(cstr, str.nulTerminatedUTF8) expectEqualCString(cstr, str.nulTerminatedUTF8CString) diff --git a/test/1_stdlib/TestUUID.swift b/test/1_stdlib/TestUUID.swift index e041e76eda864..25668f6f38a38 100644 --- a/test/1_stdlib/TestUUID.swift +++ b/test/1_stdlib/TestUUID.swift @@ -75,7 +75,7 @@ class TestUUID : TestUUIDSuper { var bytes: [UInt8] = [0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0] let valFromBytes = bytes.withUnsafeMutableBufferPointer { buffer -> UUID in ref.getBytes(buffer.baseAddress) - return UUID(uuid: UnsafePointer(buffer.baseAddress!).pointee) + return UUID(uuid: UnsafeRawPointer(buffer.baseAddress!).load(as: uuid_t.self)) } let valFromStr = UUID(uuidString: ref.uuidString) expectEqual(ref.uuidString, valFromRef.uuidString) diff --git a/test/Constraints/lvalues.swift b/test/Constraints/lvalues.swift index 4352b412de3b8..cf193d7b85b97 100644 --- a/test/Constraints/lvalues.swift +++ b/test/Constraints/lvalues.swift @@ -179,7 +179,7 @@ func rdar19835413() { f1(&a[i]) f1(&a[0]) f1(pi) - f1(UnsafeMutablePointer(pi)) + f1(pi) } } diff --git a/test/Interpreter/SDK/archiving_generic_swift_class.swift b/test/Interpreter/SDK/archiving_generic_swift_class.swift index 05166168d01b4..1017671ff856c 100644 --- a/test/Interpreter/SDK/archiving_generic_swift_class.swift +++ b/test/Interpreter/SDK/archiving_generic_swift_class.swift @@ -70,10 +70,11 @@ func driver() { } // Spawn the archiver process. + let str = "-archive" as StaticString + let optStr = UnsafeMutableRawPointer(mutating: str.utf8Start).bindMemory( + to: CChar.self, capacity: str.utf8CodeUnitCount) let archiverArgv: [UnsafeMutablePointer?] = [ - CommandLine.unsafeArgv[0], - UnsafeMutablePointer(("-archive" as StaticString).utf8Start), - nil + CommandLine.unsafeArgv[0], optStr, nil ] guard posix_spawn(&archiver, CommandLine.unsafeArgv[0], &archiverActions, nil, @@ -99,11 +100,12 @@ func driver() { } // Spawn the unarchiver process. + let str = "-unarchive" as StaticString + let optStr = UnsafeMutableRawPointer(mutating: str.utf8Start).bindMemory( + to: CChar.self, capacity: str.utf8CodeUnitCount) var unarchiver: pid_t = 0 let unarchiverArgv: [UnsafeMutablePointer?] = [ - CommandLine.unsafeArgv[0], - UnsafeMutablePointer(("-unarchive" as StaticString).utf8Start), - nil + CommandLine.unsafeArgv[0], optStr, nil ] guard posix_spawn(&unarchiver, CommandLine.unsafeArgv[0], &unarchiverActions, nil, diff --git a/test/Interpreter/SDK/objc_inner_pointer.swift b/test/Interpreter/SDK/objc_inner_pointer.swift index dca84734ae73e..288a74ebb27dd 100644 --- a/test/Interpreter/SDK/objc_inner_pointer.swift +++ b/test/Interpreter/SDK/objc_inner_pointer.swift @@ -28,7 +28,7 @@ autoreleasepool { repeat { let data = NSData(bytes: [2, 3, 5, 7] as [UInt8], length: 4) hangCanary(data) - bytes = UnsafeMutablePointer(data.bytes.assumingMemoryBound(to: UInt8.self)) + bytes = UnsafeMutablePointer(mutating: data.bytes.assumingMemoryBound(to: UInt8.self)) } while false // CHECK-NOT: died print(bytes[0]) // CHECK: 2 print(bytes[1]) // CHECK-NEXT: 3 @@ -44,7 +44,7 @@ autoreleasepool { let data = NSData(bytes: [11, 13, 17, 19] as [UInt8], length: 4) hangCanary(data) let dataAsAny: AnyObject = data - bytes = UnsafeMutablePointer(dataAsAny.bytes!.assumingMemoryBound(to: UInt8.self)) + bytes = UnsafeMutablePointer(mutating: dataAsAny.bytes!.assumingMemoryBound(to: UInt8.self)) } while false // CHECK-NOT: died print(bytes[0]) // CHECK: 11 print(bytes[1]) // CHECK-NEXT: 13 diff --git a/test/Parse/pointer_conversion.swift.gyb b/test/Parse/pointer_conversion.swift.gyb index f8715e151f621..c9df34b6d735f 100644 --- a/test/Parse/pointer_conversion.swift.gyb +++ b/test/Parse/pointer_conversion.swift.gyb @@ -259,10 +259,6 @@ func stringArguments(_ s: String) { } -func pointerConstructor(_ x: UnsafeMutablePointer) -> UnsafeMutablePointer { - return UnsafeMutablePointer(x) -} - func optionality(_ op: UnsafeMutablePointer?) { takesMutableVoidPointer(op) % if not suffix: @@ -286,10 +282,10 @@ func genericPointerArithmetic(_ x: UnsafeMutablePointer, i: Int, t: T) -> p.initialize(to: t) } -func passPointerToClosure(_ f: (UnsafeMutablePointer) -> Int) -> Int { } +func passPointerToClosure(_ f: (UnsafeMutablePointer) -> Int) -> Int { } -func pointerInClosure(_ f: (UnsafeMutablePointer) -> Int) -> Int { - return passPointerToClosure { f(UnsafeMutablePointer($0)) } +func pointerInClosure(_ f: (UnsafePointer) -> Int) -> Int { + return passPointerToClosure { f($0) } } struct NotEquatable {} diff --git a/test/decl/subscript/addressors.swift b/test/decl/subscript/addressors.swift index 41145928f352b..9689f08d56651 100644 --- a/test/decl/subscript/addressors.swift +++ b/test/decl/subscript/addressors.swift @@ -72,7 +72,7 @@ struct AddressorAndGet { subscript(index: Int) -> Int { unsafeAddress { // expected-error {{subscript cannot provide both 'address' and a getter}} - return UnsafePointer(base) + return base } get { return base.get() @@ -85,7 +85,7 @@ struct AddressorAndSet { subscript(index: Int) -> Int { unsafeAddress { - return UnsafePointer(base) + return base } set { // expected-error {{subscript cannot provide both 'address' and a setter; use an ordinary getter instead}} } diff --git a/validation-test/stdlib/AtomicInt.swift b/validation-test/stdlib/AtomicInt.swift index 9861c60f886bd..edb4afff3cbbc 100644 --- a/validation-test/stdlib/AtomicInt.swift +++ b/validation-test/stdlib/AtomicInt.swift @@ -704,7 +704,8 @@ struct AtomicInitializeARCRefRaceTest : RaceTestWithPerTrialData { var _atomicReference: AnyObject? = nil var atomicReferencePtr: UnsafeMutablePointer { - return UnsafeMutablePointer(_getUnsafePointerToStoredProperties(self)) + return _getUnsafePointerToStoredProperties(self).assumingMemoryBound( + to: Optional.self) } init() {} diff --git a/validation-test/stdlib/CoreAudio.swift b/validation-test/stdlib/CoreAudio.swift index 477683e7ed207..fde72ec4d3a59 100644 --- a/validation-test/stdlib/CoreAudio.swift +++ b/validation-test/stdlib/CoreAudio.swift @@ -106,25 +106,25 @@ CoreAudioTestSuite.test( } CoreAudioTestSuite.test("AudioBufferList.sizeInBytes(maximumBuffers: Int)") { - expectEqual(ablHeaderSize + strideof(AudioBuffer), + expectEqual(ablHeaderSize + strideof(AudioBuffer.self), AudioBufferList.sizeInBytes(maximumBuffers: 1)) - expectEqual(ablHeaderSize + 16 * strideof(AudioBuffer), + expectEqual(ablHeaderSize + 16 * strideof(AudioBuffer.self), AudioBufferList.sizeInBytes(maximumBuffers: 16)) } CoreAudioTestSuite.test("AudioBufferList.sizeInBytes(maximumBuffers: Int)/trap/count<0") { expectCrashLater() - AudioBufferList.sizeInBytes(maximumBuffers: -1) + _ = AudioBufferList.sizeInBytes(maximumBuffers: -1) } CoreAudioTestSuite.test("AudioBufferList.sizeInBytes(maximumBuffers: Int)/trap/count==0") { expectCrashLater() - AudioBufferList.sizeInBytes(maximumBuffers: -1) + _ = AudioBufferList.sizeInBytes(maximumBuffers: -1) } CoreAudioTestSuite.test("AudioBufferList.sizeInBytes(maximumBuffers: Int)/trap/overflow") { expectCrashLater() - AudioBufferList.sizeInBytes(maximumBuffers: Int.max) + _ = AudioBufferList.sizeInBytes(maximumBuffers: Int.max) } CoreAudioTestSuite.test("AudioBufferList.allocate(maximumBuffers: Int)") { @@ -142,17 +142,17 @@ CoreAudioTestSuite.test("AudioBufferList.allocate(maximumBuffers: Int)") { CoreAudioTestSuite.test("AudioBufferList.allocate(maximumBuffers: Int)/trap/count==0") { expectCrashLater() - AudioBufferList.allocate(maximumBuffers: 0) + _ = AudioBufferList.allocate(maximumBuffers: 0) } CoreAudioTestSuite.test("AudioBufferList.allocate(maximumBuffers: Int)/trap/count<0") { expectCrashLater() - AudioBufferList.allocate(maximumBuffers: -1) + _ = AudioBufferList.allocate(maximumBuffers: -1) } CoreAudioTestSuite.test("AudioBufferList.allocate(maximumBuffers: Int)/trap/overflow") { expectCrashLater() - AudioBufferList.allocate(maximumBuffers: Int.max) + _ = AudioBufferList.allocate(maximumBuffers: Int.max) } CoreAudioTestSuite.test("UnsafeMutableAudioBufferListPointer/AssociatedTypes") { @@ -201,28 +201,37 @@ CoreAudioTestSuite.test( CoreAudioTestSuite.test("UnsafeMutableAudioBufferListPointer.count") { let sizeInBytes = AudioBufferList.sizeInBytes(maximumBuffers: 16) - let ablPtr = UnsafeMutablePointer( - UnsafeMutablePointer.allocate(capacity: sizeInBytes)) + let rawPtr = UnsafeMutableRawPointer.allocate( + bytes: sizeInBytes, alignedTo: alignof(AudioBufferList.self)) + let ablPtr = rawPtr.bindMemory(to: AudioBufferList.self, + capacity: sizeInBytes / sizeof(AudioBufferList.self)) // It is important that 'ablPtrWrapper' is a 'let'. We are verifying that // the 'count' property has a nonmutating setter. let ablPtrWrapper = UnsafeMutableAudioBufferListPointer(ablPtr) // Test getter. - UnsafeMutablePointer(ablPtr).pointee = 0x1234_5678 + UnsafeMutableRawPointer(ablPtr) + .assumingMemoryBound(to: UInt32.self).pointee = 0x1234_5678 expectEqual(0x1234_5678, ablPtrWrapper.count) // Test setter. ablPtrWrapper.count = 0x7765_4321 - expectEqual(0x7765_4321, UnsafeMutablePointer(ablPtr).pointee) + expectEqual(0x7765_4321, rawPtr.assumingMemoryBound(to: UInt32.self).pointee) - ablPtr.deallocate(capacity: sizeInBytes) + rawPtr.deallocate( + bytes: sizeInBytes, alignedTo: alignof(AudioBufferList.self)) } CoreAudioTestSuite.test("UnsafeMutableAudioBufferListPointer.subscript(_: Int)") { let sizeInBytes = AudioBufferList.sizeInBytes(maximumBuffers: 16) - let ablPtr = UnsafeMutablePointer( - UnsafeMutablePointer.allocate(capacity: sizeInBytes)) + + let rawPtr = UnsafeMutableRawPointer.allocate( + bytes: sizeInBytes, alignedTo: 1) + + let ablPtr = rawPtr.bindMemory( + to: AudioBufferList.self, + capacity: sizeInBytes / sizeof(AudioBufferList.self)) // It is important that 'ablPtrWrapper' is a 'let'. We are verifying that // the subscript has a nonmutating setter. @@ -234,9 +243,9 @@ CoreAudioTestSuite.test("UnsafeMutableAudioBufferListPointer.subscript(_: Int)") mNumberChannels: 2, mDataByteSize: 1024, mData: UnsafeMutableRawPointer(bitPattern: 0x1234_5678)) - UnsafeMutablePointer( - UnsafeMutablePointer(ablPtr) + ablHeaderSize - ).pointee = audioBuffer + let bufPtr = (rawPtr + ablHeaderSize).assumingMemoryBound( + to: AudioBuffer.self) + bufPtr.pointee = audioBuffer ablPtrWrapper.count = 1 expectEqual(2, ablPtrWrapper[0].mNumberChannels) @@ -253,8 +262,8 @@ CoreAudioTestSuite.test("UnsafeMutableAudioBufferListPointer.subscript(_: Int)") ablPtrWrapper.count = 2 ablPtrWrapper[1] = audioBuffer - let audioBufferPtr = UnsafeMutablePointer( - UnsafeMutablePointer(ablPtr) + ablHeaderSize) + 1 + let audioBufferPtr = (rawPtr + ablHeaderSize).assumingMemoryBound( + to: AudioBuffer.self) + 1 expectEqual(5, audioBufferPtr.pointee.mNumberChannels) expectEqual(256, audioBufferPtr.pointee.mDataByteSize) expectEqual(audioBuffer.mData, audioBufferPtr.pointee.mData) diff --git a/validation-test/stdlib/NewArray.swift.gyb b/validation-test/stdlib/NewArray.swift.gyb index c4e8d875e7723..ce993c650fd49 100644 --- a/validation-test/stdlib/NewArray.swift.gyb +++ b/validation-test/stdlib/NewArray.swift.gyb @@ -190,7 +190,10 @@ func nsArrayOfStrings() -> Array { let src: ContiguousArray = ["foo", "bar", "baz"] return src.withUnsafeBufferPointer { - let ns = NSArray(objects: UnsafePointer($0.baseAddress!), count: $0.count) + let ns = NSArray( + objects: unsafeBitCast($0.baseAddress!, + to: UnsafeMutablePointer.self), + count: $0.count) return ns as! [NSString] } } diff --git a/validation-test/stdlib/Prototypes/PersistentVector.swift.gyb b/validation-test/stdlib/Prototypes/PersistentVector.swift.gyb index a9558356e2f34..aba6cd3a9e09f 100644 --- a/validation-test/stdlib/Prototypes/PersistentVector.swift.gyb +++ b/validation-test/stdlib/Prototypes/PersistentVector.swift.gyb @@ -104,13 +104,13 @@ import SwiftShims // func allocBytes(count: Int, alignment: Int) - -> UnsafeMutablePointer { - return UnsafeMutablePointer( + -> UnsafeMutableRawPointer { + return UnsafeMutableRawPointer( Builtin.allocRaw(count._builtinWordValue, alignment._builtinWordValue)) } func deallocBytes( - _ pointer: UnsafeMutablePointer, + _ pointer: UnsafeMutableRawPointer, byteCount: Int, alignment: Int ) { @@ -125,7 +125,7 @@ func _swift_stdlib_atomicStoreInt( desired: Int) { #if arch(x86_64) return _swift_stdlib_atomicStoreUInt64( - object: UnsafeMutablePointer(target), + object: unsafeBitCast(target, to: UnsafeMutablePointer.self), desired: UInt64(UInt(bitPattern: desired))) #endif } @@ -357,10 +357,10 @@ struct _PVSparseVectorNodePointer return _valueVectorOffset(layout: layout) + _valueVectorSize(layout: layout) } - var _nodePointer: UnsafeMutablePointer + var _nodePointer: UnsafeMutableRawPointer var _referenceCountPointer: UnsafeMutablePointer { - return UnsafeMutablePointer(_nodePointer) + return unsafeBitCast(_nodePointer, to: UnsafeMutablePointer.self) } var layoutParameters: _PVSparseVectorNodeLayoutParameters { @@ -403,23 +403,23 @@ struct _PVSparseVectorNodePointer var childNodePopulationBitmap: _Int32Bitmap { unsafeAddress { - return UnsafePointer( - _nodePointer + _Self._childNodePopulationBitmapOffset) + return UnsafePointer((_nodePointer + _Self._childNodePopulationBitmapOffset) + .assumingMemoryBound(to: _Int32Bitmap.self)) } nonmutating unsafeMutableAddress { - return UnsafeMutablePointer( - _nodePointer + _Self._childNodePopulationBitmapOffset) + return (_nodePointer + _Self._childNodePopulationBitmapOffset) + .assumingMemoryBound(to: _Int32Bitmap.self) } } var keyPopulationBitmap: _Int32Bitmap { unsafeAddress { - return UnsafePointer( - _nodePointer + _Self._keyPopulationBitmapOffset) + return UnsafePointer((_nodePointer + _Self._keyPopulationBitmapOffset) + .assumingMemoryBound(to: _Int32Bitmap.self)) } nonmutating unsafeMutableAddress { - return UnsafeMutablePointer( - _nodePointer + _Self._keyPopulationBitmapOffset) + return (_nodePointer + _Self._keyPopulationBitmapOffset) + .assumingMemoryBound(to: _Int32Bitmap.self) } } @@ -432,8 +432,8 @@ struct _PVSparseVectorNodePointer } var _childNodeVector: UnsafeMutablePointer<_PVAnyNodePointer?> { - return UnsafeMutablePointer( - _nodePointer + _Self._childNodeVectorOffset) + return (_nodePointer + _Self._childNodeVectorOffset) + .assumingMemoryBound(to: Optional<_PVAnyNodePointer>.self) } var childNodes: UnsafeMutableBufferPointer<_PVAnyNodePointer?> { @@ -444,17 +444,17 @@ struct _PVSparseVectorNodePointer func _keyVector(layout: _PVSparseVectorNodeLayoutParameters) -> UnsafeMutablePointer { - return UnsafeMutablePointer( - _nodePointer + _Self._keyVectorOffset(layout: layout)) + return (_nodePointer + _Self._keyVectorOffset(layout: layout)) + .assumingMemoryBound(to: Key.self) } func _valueVector(layout: _PVSparseVectorNodeLayoutParameters) -> UnsafeMutablePointer { - return UnsafeMutablePointer( - _nodePointer + _Self._valueVectorOffset(layout: layout)) + return (_nodePointer + _Self._valueVectorOffset(layout: layout)) + .assumingMemoryBound(to: Value.self) } - init(_nodePointer: UnsafeMutablePointer) { + init(_nodePointer: UnsafeMutableRawPointer) { self._nodePointer = _nodePointer } @@ -1025,10 +1025,10 @@ struct _PVArrayNodePointer return _valueArrayOffset + _valueArraySize } - var _nodePointer: UnsafeMutablePointer + var _nodePointer: UnsafeMutableRawPointer var _referenceCountPointer: UnsafeMutablePointer { - return UnsafeMutablePointer(_nodePointer) + return _nodePointer.assumingMemoryBound(to: Int.self) } func retain() { @@ -1049,15 +1049,15 @@ struct _PVArrayNodePointer func dealloc() { for i in childNodePopulationBitmap.setBitIndices { - UnsafeMutablePointer<_PVAnyNodePointer>( - _childNodeOrKeyArray + _Self._childNodeOrKeyStride * i) - .pointee.release() + (_childNodeOrKeyArray + _Self._childNodeOrKeyStride * i) + .assumingMemoryBound(to: _PVAnyNodePointer.self) + .pointee.release() } if !_isPOD(Key.self) { for i in keyPopulationBitmap.setBitIndices { - UnsafeMutablePointer( - _childNodeOrKeyArray + _Self._childNodeOrKeyStride * i) - .deinitialize() + (_childNodeOrKeyArray + _Self._childNodeOrKeyStride * i) + .assumingMemoryBound(to: Key.self) + .deinitialize() } } if !_isPOD(Value.self) { @@ -1076,23 +1076,23 @@ struct _PVArrayNodePointer var childNodePopulationBitmap: _Int32Bitmap { unsafeAddress { - return UnsafePointer( - _nodePointer + _Self._childNodePopulationBitmapOffset) + return UnsafePointer((_nodePointer + _Self._childNodePopulationBitmapOffset) + .assumingMemoryBound(to: _Int32Bitmap.self)) } nonmutating unsafeMutableAddress { - return UnsafeMutablePointer( - _nodePointer + _Self._childNodePopulationBitmapOffset) + return (_nodePointer + _Self._childNodePopulationBitmapOffset) + .assumingMemoryBound(to: _Int32Bitmap.self) } } var keyPopulationBitmap: _Int32Bitmap { unsafeAddress { - return UnsafePointer( - _nodePointer + _Self._keyPopulationBitmapOffset) + return UnsafePointer((_nodePointer + _Self._keyPopulationBitmapOffset) + .assumingMemoryBound(to: _Int32Bitmap.self)) } nonmutating unsafeMutableAddress { - return UnsafeMutablePointer( - _nodePointer + _Self._keyPopulationBitmapOffset) + return (_nodePointer + _Self._keyPopulationBitmapOffset) + .assumingMemoryBound(to: _Int32Bitmap.self) } } @@ -1104,17 +1104,16 @@ struct _PVArrayNodePointer return keyPopulationBitmap.setBitCount } - var _childNodeOrKeyArray: UnsafeMutablePointer { - return UnsafeMutablePointer( - _nodePointer + _Self._childNodeOrKeyArrayOffset) + var _childNodeOrKeyArray: UnsafeMutableRawPointer { + return _nodePointer + _Self._childNodeOrKeyArrayOffset } var _valueArray: UnsafeMutablePointer { - return UnsafeMutablePointer( - _nodePointer + _Self._valueArrayOffset) + return (_nodePointer + _Self._valueArrayOffset) + .assumingMemoryBound(to: Value.self) } - init(_nodePointer: UnsafeMutablePointer) { + init(_nodePointer: UnsafeMutableRawPointer) { self._nodePointer = _nodePointer } @@ -1138,9 +1137,8 @@ struct _PVArrayNodePointer precondition(!childNodePopulationBitmap[i]) // sanity check precondition(!keyPopulationBitmap[i]) // sanity check - UnsafeMutablePointer( - _childNodeOrKeyArray + _Self._childNodeOrKeyStride * i) - .initialize(to: key) + (_childNodeOrKeyArray + _Self._childNodeOrKeyStride * i) + .initializeMemory(as: Key.self, to: key) (_valueArray + i).initialize(to: value) keyPopulationBitmap[i] = true @@ -1242,10 +1240,10 @@ struct _PVCollisionNodePointer return _valueArrayOffset(layout: layout) + _valueArraySize(layout: layout) } - var _nodePointer: UnsafeMutablePointer + var _nodePointer: UnsafeMutableRawPointer var _referenceCountPointer: UnsafeMutablePointer { - return UnsafeMutablePointer(_nodePointer) + return _nodePointer.assumingMemoryBound(to: Int.self) } var layoutParameters: _PVCollisionNodePointerLayoutParameters { @@ -1284,25 +1282,27 @@ struct _PVCollisionNodePointer var keyCount: Int { unsafeAddress { - return UnsafePointer(_nodePointer + _Self._countOffset) + return UnsafePointer((_nodePointer + _Self._countOffset) + .assumingMemoryBound(to: Int.self)) } nonmutating unsafeMutableAddress { - return UnsafeMutablePointer(_nodePointer + _Self._countOffset) + return (_nodePointer + _Self._countOffset) + .assumingMemoryBound(to: Int.self) } } var _keyArray: UnsafeMutablePointer { - return UnsafeMutablePointer( - _nodePointer + _Self._keyArrayOffset) + return (_nodePointer + _Self._keyArrayOffset) + .assumingMemoryBound(to: Key.self) } func _valueArray(layout: _PVCollisionNodePointerLayoutParameters) -> UnsafeMutablePointer { - return UnsafeMutablePointer( - _nodePointer + _Self._valueArrayOffset(layout: layout)) + return (_nodePointer + _Self._valueArrayOffset(layout: layout)) + .assumingMemoryBound(to: Value.self) } - init(_nodePointer: UnsafeMutablePointer) { + init(_nodePointer: UnsafeMutableRawPointer) { self._nodePointer = _nodePointer } @@ -1486,9 +1486,9 @@ struct _PVCollisionNodePointer struct _PVAnyNodePointer : CustomReflectable, Equatable { - let taggedPointer: UnsafeMutablePointer + let taggedPointer: UnsafeMutableRawPointer - init(taggedPointer: UnsafeMutablePointer) { + init(taggedPointer: UnsafeMutableRawPointer) { self.taggedPointer = taggedPointer } @@ -1501,14 +1501,14 @@ struct _PVAnyNodePointer init(_ arrayNode: _PVArrayNodePointer) { precondition( Int(bitPattern: arrayNode._nodePointer) & 0x3 == 0) // sanity check - self.taggedPointer = UnsafeMutablePointer(bitPattern: + self.taggedPointer = UnsafeMutableRawPointer(bitPattern: Int(bitPattern: arrayNode._nodePointer) | 1)! } init(_ collisionNode: _PVCollisionNodePointer) { precondition( Int(bitPattern: collisionNode._nodePointer) & 0x3 == 0) // sanity check - self.taggedPointer = UnsafeMutablePointer(bitPattern: + self.taggedPointer = UnsafeMutableRawPointer(bitPattern: Int(bitPattern: collisionNode._nodePointer) | 2)! } @@ -1516,13 +1516,13 @@ struct _PVAnyNodePointer return Int(bitPattern: taggedPointer) & 0x3 } - var _untaggedPointer: UnsafeMutablePointer { - return UnsafeMutablePointer(bitPattern: + var _untaggedPointer: UnsafeMutableRawPointer { + return UnsafeMutableRawPointer(bitPattern: Int(bitPattern: taggedPointer) & ~0x3)! } var _referenceCountPointer: UnsafeMutablePointer { - return UnsafeMutablePointer(_untaggedPointer) + return _untaggedPointer.assumingMemoryBound(to: Int.self) } var asSparseVectorNode: _PVSparseVectorNodePointer {