Skip to content

Commit 99dffd7

Browse files
authored
Merge pull request #3854 from rintaro/SE-0101-memorylayout
[SE-0101] Implement: Reconfiguring sizeof and related functions into a unified MemoryLayout struct - Part 1
2 parents 3034b01 + 06603c1 commit 99dffd7

Some content is hidden

Large Commits have some content hidden by default. Use the searchbox below for content that may be hidden.

54 files changed

+353
-293
lines changed

benchmark/single-source/BitCount.swift

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -17,7 +17,7 @@ import Foundation
1717
import TestsUtils
1818

1919
func countBitSet(_ num: Int) -> Int {
20-
let bits = sizeof(Int.self) * 8
20+
let bits = MemoryLayout<Int>.size * 8
2121
var cnt: Int = 0
2222
var mask: Int = 1
2323
for _ in 0...bits {

stdlib/private/SwiftPrivateLibcExtras/Subprocess.swift

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -116,7 +116,7 @@ public func spawnChild(_ args: [String])
116116

117117
// If execve() encountered an error, we write the errno encountered to the
118118
// parent write pipe.
119-
let errnoSize = sizeof(errno.dynamicType)
119+
let errnoSize = MemoryLayout._ofInstance(errno).size
120120
var execveErrno = errno
121121
let writtenBytes = withUnsafePointer(to: &execveErrno) {
122122
write(childToParentPipe.writeFD, UnsafePointer($0), errnoSize)

stdlib/private/SwiftPrivateLibcExtras/SwiftPrivateLibcExtras.swift

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -42,7 +42,7 @@ public var _stdlib_FD_SETSIZE: CInt {
4242
public struct _stdlib_fd_set {
4343
var _data: [UInt]
4444
static var _wordBits: Int {
45-
return sizeof(UInt.self) * 8
45+
return MemoryLayout<UInt>.size * 8
4646
}
4747

4848
public init() {

stdlib/private/SwiftReflectionTest/SwiftReflectionTest.swift

Lines changed: 15 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -157,21 +157,21 @@ internal func sendAddress(of instance: AnyObject) {
157157
debugLog("BEGIN \(#function)")
158158
defer { debugLog("END \(#function)") }
159159
var address = Unmanaged.passUnretained(instance).toOpaque()
160-
sendBytes(from: &address, count: sizeof(UInt.self))
160+
sendBytes(from: &address, count: MemoryLayout<UInt>.size)
161161
}
162162

163163
/// Send the `value`'s bits to the parent.
164164
internal func sendValue<T>(_ value: T) {
165165
debugLog("BEGIN \(#function)"); defer { debugLog("END \(#function)") }
166166
var value = value
167-
sendBytes(from: &value, count: sizeof(T.self))
167+
sendBytes(from: &value, count: MemoryLayout<T>.size)
168168
}
169169

170170
/// Read a word-sized unsigned integer from the parent.
171171
internal func readUInt() -> UInt {
172172
debugLog("BEGIN \(#function)"); defer { debugLog("END \(#function)") }
173173
var value: UInt = 0
174-
fread(&value, sizeof(UInt.self), 1, stdin)
174+
fread(&value, MemoryLayout<UInt>.size, 1, stdin)
175175
return value
176176
}
177177

@@ -184,7 +184,7 @@ internal func sendReflectionInfos() {
184184
var numInfos = infos.count
185185
debugLog("\(numInfos) reflection info bundles.")
186186
precondition(numInfos >= 1)
187-
sendBytes(from: &numInfos, count: sizeof(UInt.self))
187+
sendBytes(from: &numInfos, count: MemoryLayout<UInt>.size)
188188
for info in infos {
189189
debugLog("Sending info for \(info.imageName)")
190190
for section in info {
@@ -247,7 +247,7 @@ internal func sendStringLength() {
247247
/// Send the size of this architecture's pointer type.
248248
internal func sendPointerSize() {
249249
debugLog("BEGIN \(#function)"); defer { debugLog("END \(#function)") }
250-
let pointerSize = UInt8(sizeof(UnsafeRawPointer.self))
250+
let pointerSize = UInt8(MemoryLayout<UnsafeRawPointer>.size)
251251
sendValue(pointerSize)
252252
}
253253

@@ -357,11 +357,11 @@ public func reflect(object: AnyObject) {
357357
/// an Any existential.
358358
public func reflect<T>(any: T) {
359359
let any: Any = any
360-
let anyPointer = UnsafeMutablePointer<Any>.allocate(capacity: sizeof(Any.self))
360+
let anyPointer = UnsafeMutablePointer<Any>.allocate(capacity: MemoryLayout<Any>.size)
361361
anyPointer.initialize(to: any)
362362
let anyPointerValue = unsafeBitCast(anyPointer, to: UInt.self)
363363
reflect(instanceAddress: anyPointerValue, kind: .Existential)
364-
anyPointer.deallocate(capacity: sizeof(Any.self))
364+
anyPointer.deallocate(capacity: MemoryLayout<Any>.size)
365365
}
366366

367367
// Reflect an `Error`, a.k.a. an "error existential".
@@ -421,61 +421,61 @@ struct ThickFunctionParts {
421421
/// @convention(thick) function value.
422422
public func reflect(function: @escaping () -> ()) {
423423
let fn = UnsafeMutablePointer<ThickFunction0>.allocate(
424-
capacity: sizeof(ThickFunction0.self))
424+
capacity: MemoryLayout<ThickFunction0>.size)
425425
fn.initialize(to: ThickFunction0(function: function))
426426

427427
let parts = unsafeBitCast(fn, to: UnsafePointer<ThickFunctionParts>.self)
428428
let contextPointer = unsafeBitCast(parts.pointee.context, to: UInt.self)
429429

430430
reflect(instanceAddress: contextPointer, kind: .Object)
431431

432-
fn.deallocate(capacity: sizeof(ThickFunction0.self))
432+
fn.deallocate(capacity: MemoryLayout<ThickFunction0>.size)
433433
}
434434

435435
/// Reflect a closure context. The given function must be a Swift-native
436436
/// @convention(thick) function value.
437437
public func reflect(function: @escaping (Int) -> ()) {
438438
let fn =
439439
UnsafeMutablePointer<ThickFunction1>.allocate(
440-
capacity: sizeof(ThickFunction1.self))
440+
capacity: MemoryLayout<ThickFunction1>.size)
441441
fn.initialize(to: ThickFunction1(function: function))
442442

443443
let parts = unsafeBitCast(fn, to: UnsafePointer<ThickFunctionParts>.self)
444444
let contextPointer = unsafeBitCast(parts.pointee.context, to: UInt.self)
445445

446446
reflect(instanceAddress: contextPointer, kind: .Object)
447447

448-
fn.deallocate(capacity: sizeof(ThickFunction1.self))
448+
fn.deallocate(capacity: MemoryLayout<ThickFunction1>.size)
449449
}
450450

451451
/// Reflect a closure context. The given function must be a Swift-native
452452
/// @convention(thick) function value.
453453
public func reflect(function: @escaping (Int, String) -> ()) {
454454
let fn = UnsafeMutablePointer<ThickFunction2>.allocate(
455-
capacity: sizeof(ThickFunction2.self))
455+
capacity: MemoryLayout<ThickFunction2>.size)
456456
fn.initialize(to: ThickFunction2(function: function))
457457

458458
let parts = unsafeBitCast(fn, to: UnsafePointer<ThickFunctionParts>.self)
459459
let contextPointer = unsafeBitCast(parts.pointee.context, to: UInt.self)
460460

461461
reflect(instanceAddress: contextPointer, kind: .Object)
462462

463-
fn.deallocate(capacity: sizeof(ThickFunction2.self))
463+
fn.deallocate(capacity: MemoryLayout<ThickFunction2>.size)
464464
}
465465

466466
/// Reflect a closure context. The given function must be a Swift-native
467467
/// @convention(thick) function value.
468468
public func reflect(function: @escaping (Int, String, AnyObject?) -> ()) {
469469
let fn = UnsafeMutablePointer<ThickFunction3>.allocate(
470-
capacity: sizeof(ThickFunction3.self))
470+
capacity: MemoryLayout<ThickFunction3>.size)
471471
fn.initialize(to: ThickFunction3(function: function))
472472

473473
let parts = unsafeBitCast(fn, to: UnsafePointer<ThickFunctionParts>.self)
474474
let contextPointer = unsafeBitCast(parts.pointee.context, to: UInt.self)
475475

476476
reflect(instanceAddress: contextPointer, kind: .Object)
477477

478-
fn.deallocate(capacity: sizeof(ThickFunction3.self))
478+
fn.deallocate(capacity: MemoryLayout<ThickFunction3>.size)
479479
}
480480

481481
/// Call this function to indicate to the parent that there are

stdlib/public/SDK/CoreAudio/CoreAudio.swift

Lines changed: 6 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -16,7 +16,7 @@ extension UnsafeBufferPointer {
1616
/// Initialize an `UnsafeBufferPointer<Element>` from an `AudioBuffer`.
1717
/// Binds the the buffer's memory type to `Element`.
1818
public init(_ audioBuffer: AudioBuffer) {
19-
let count = Int(audioBuffer.mDataByteSize) / strideof(Element.self)
19+
let count = Int(audioBuffer.mDataByteSize) / MemoryLayout<Element>.stride
2020
let elementPtr = audioBuffer.mData?.bindMemory(
2121
to: Element.self, capacity: count)
2222
self.init(start: elementPtr, count: count)
@@ -27,7 +27,7 @@ extension UnsafeMutableBufferPointer {
2727
/// Initialize an `UnsafeMutableBufferPointer<Element>` from an
2828
/// `AudioBuffer`.
2929
public init(_ audioBuffer: AudioBuffer) {
30-
let count = Int(audioBuffer.mDataByteSize) / strideof(Element.self)
30+
let count = Int(audioBuffer.mDataByteSize) / MemoryLayout<Element>.stride
3131
let elementPtr = audioBuffer.mData?.bindMemory(
3232
to: Element.self, capacity: count)
3333
self.init(start: elementPtr, count: count)
@@ -43,7 +43,7 @@ extension AudioBuffer {
4343
) {
4444
self.mNumberChannels = UInt32(numberOfChannels)
4545
self.mData = UnsafeMutableRawPointer(typedBuffer.baseAddress)
46-
self.mDataByteSize = UInt32(typedBuffer.count * strideof(Element.self))
46+
self.mDataByteSize = UInt32(typedBuffer.count * MemoryLayout<Element>.stride)
4747
}
4848
}
4949

@@ -53,8 +53,8 @@ extension AudioBufferList {
5353
public static func sizeInBytes(maximumBuffers: Int) -> Int {
5454
_precondition(maximumBuffers >= 1,
5555
"AudioBufferList should contain at least one AudioBuffer")
56-
return sizeof(AudioBufferList.self) +
57-
(maximumBuffers - 1) * strideof(AudioBuffer.self)
56+
return MemoryLayout<AudioBufferList>.size +
57+
(maximumBuffers - 1) * MemoryLayout<AudioBuffer>.stride
5858
}
5959

6060
/// Allocate an `AudioBufferList` with a capacity for the specified number of
@@ -72,7 +72,7 @@ extension AudioBufferList {
7272
"failed to allocate memory for an AudioBufferList")
7373

7474
let listPtr = ablMemory!.bindMemory(to: AudioBufferList.self, capacity: 1)
75-
(ablMemory! + strideof(AudioBufferList.self)).bindMemory(
75+
(ablMemory! + MemoryLayout<AudioBufferList>.stride).bindMemory(
7676
to: AudioBuffer.self, capacity: maximumBuffers)
7777
let abl = UnsafeMutableAudioBufferListPointer(listPtr)
7878
abl.count = maximumBuffers

stdlib/public/SDK/Dispatch/Data.swift

Lines changed: 6 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -76,7 +76,7 @@ public struct DispatchData : RandomAccessCollection, _ObjectiveCBridgeable {
7676
var size = 0
7777
let data = __dispatch_data_create_map(__wrapped, &ptr, &size)
7878
let contentPtr = ptr!.bindMemory(
79-
to: ContentType.self, capacity: size / strideof(ContentType.self))
79+
to: ContentType.self, capacity: size / MemoryLayout<ContentType>.stride)
8080
defer { _fixLifetime(data) }
8181
return try body(contentPtr)
8282
}
@@ -114,8 +114,8 @@ public struct DispatchData : RandomAccessCollection, _ObjectiveCBridgeable {
114114
///
115115
/// - parameter buffer: The buffer of bytes to append. The size is calculated from `SourceType` and `buffer.count`.
116116
public mutating func append<SourceType>(_ buffer : UnsafeBufferPointer<SourceType>) {
117-
buffer.baseAddress!.withMemoryRebound(to: UInt8.self, capacity: buffer.count * strideof(SourceType.self)) {
118-
self.append($0, count: buffer.count * sizeof(SourceType.self))
117+
buffer.baseAddress!.withMemoryRebound(to: UInt8.self, capacity: buffer.count * MemoryLayout<SourceType>.stride) {
118+
self.append($0, count: buffer.count * MemoryLayout<SourceType>.stride)
119119
}
120120
}
121121

@@ -149,7 +149,7 @@ public struct DispatchData : RandomAccessCollection, _ObjectiveCBridgeable {
149149

150150
/// Copy the contents of the data into a buffer.
151151
///
152-
/// This function copies the bytes in `range` from the data into the buffer. If the count of the `range` is greater than `sizeof(DestinationType) * buffer.count` then the first N bytes will be copied into the buffer.
152+
/// This function copies the bytes in `range` from the data into the buffer. If the count of the `range` is greater than `MemoryLayout<DestinationType>.size * buffer.count` then the first N bytes will be copied into the buffer.
153153
/// - precondition: The range must be within the bounds of the data. Otherwise `fatalError` is called.
154154
/// - parameter buffer: A buffer to copy the data into.
155155
/// - parameter range: A range in the data to copy into the buffer. If the range is empty, this function will return 0 without copying anything. If the range is nil, as much data as will fit into `buffer` is copied.
@@ -167,9 +167,9 @@ public struct DispatchData : RandomAccessCollection, _ObjectiveCBridgeable {
167167
precondition(r.endIndex >= 0)
168168
precondition(r.endIndex <= cnt, "The range is outside the bounds of the data")
169169

170-
copyRange = r.startIndex..<(r.startIndex + Swift.min(buffer.count * sizeof(DestinationType.self), r.count))
170+
copyRange = r.startIndex..<(r.startIndex + Swift.min(buffer.count * MemoryLayout<DestinationType>.stride, r.count))
171171
} else {
172-
copyRange = 0..<Swift.min(buffer.count * sizeof(DestinationType.self), cnt)
172+
copyRange = 0..<Swift.min(buffer.count * MemoryLayout<DestinationType>.stride, cnt)
173173
}
174174

175175
guard !copyRange.isEmpty else { return 0 }

stdlib/public/SDK/Foundation/Data.swift

Lines changed: 9 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -137,14 +137,14 @@ public struct Data : ReferenceConvertible, Equatable, Hashable, RandomAccessColl
137137
///
138138
/// - parameter buffer: A buffer pointer to copy. The size is calculated from `SourceType` and `buffer.count`.
139139
public init<SourceType>(buffer: UnsafeBufferPointer<SourceType>) {
140-
_wrapped = _SwiftNSData(immutableObject: NSData(bytes: buffer.baseAddress, length: strideof(SourceType.self) * buffer.count))
140+
_wrapped = _SwiftNSData(immutableObject: NSData(bytes: buffer.baseAddress, length: MemoryLayout<SourceType>.stride * buffer.count))
141141
}
142142

143143
/// Initialize a `Data` with copied memory content.
144144
///
145145
/// - parameter buffer: A buffer pointer to copy. The size is calculated from `SourceType` and `buffer.count`.
146146
public init<SourceType>(buffer: UnsafeMutableBufferPointer<SourceType>) {
147-
_wrapped = _SwiftNSData(immutableObject: NSData(bytes: UnsafePointer(buffer.baseAddress), length: strideof(SourceType.self) * buffer.count))
147+
_wrapped = _SwiftNSData(immutableObject: NSData(bytes: UnsafePointer(buffer.baseAddress), length: MemoryLayout<SourceType>.stride * buffer.count))
148148
}
149149

150150
/// Initialize a `Data` with the contents of an Array.
@@ -281,7 +281,7 @@ public struct Data : ReferenceConvertible, Equatable, Hashable, RandomAccessColl
281281
public func withUnsafeBytes<ResultType, ContentType>(_ body: @noescape (UnsafePointer<ContentType>) throws -> ResultType) rethrows -> ResultType {
282282
let bytes = _getUnsafeBytesPointer()
283283
defer { _fixLifetime(self)}
284-
let contentPtr = bytes.bindMemory(to: ContentType.self, capacity: count / strideof(ContentType.self))
284+
let contentPtr = bytes.bindMemory(to: ContentType.self, capacity: count / MemoryLayout<ContentType>.stride)
285285
return try body(contentPtr)
286286
}
287287

@@ -298,7 +298,7 @@ public struct Data : ReferenceConvertible, Equatable, Hashable, RandomAccessColl
298298
public mutating func withUnsafeMutableBytes<ResultType, ContentType>(_ body: @noescape (UnsafeMutablePointer<ContentType>) throws -> ResultType) rethrows -> ResultType {
299299
let mutableBytes = _getUnsafeMutableBytesPointer()
300300
defer { _fixLifetime(self)}
301-
let contentPtr = mutableBytes.bindMemory(to: ContentType.self, capacity: count / strideof(ContentType.self))
301+
let contentPtr = mutableBytes.bindMemory(to: ContentType.self, capacity: count / MemoryLayout<ContentType>.stride)
302302
return try body(UnsafeMutablePointer(contentPtr))
303303
}
304304

@@ -329,7 +329,7 @@ public struct Data : ReferenceConvertible, Equatable, Hashable, RandomAccessColl
329329

330330
/// Copy the contents of the data into a buffer.
331331
///
332-
/// This function copies the bytes in `range` from the data into the buffer. If the count of the `range` is greater than `strideof(DestinationType) * buffer.count` then the first N bytes will be copied into the buffer.
332+
/// This function copies the bytes in `range` from the data into the buffer. If the count of the `range` is greater than `MemoryLayout<DestinationType>.stride * buffer.count` then the first N bytes will be copied into the buffer.
333333
/// - precondition: The range must be within the bounds of the data. Otherwise `fatalError` is called.
334334
/// - parameter buffer: A buffer to copy the data into.
335335
/// - parameter range: A range in the data to copy into the buffer. If the range is empty, this function will return 0 without copying anything. If the range is nil, as much data as will fit into `buffer` is copied.
@@ -347,9 +347,9 @@ public struct Data : ReferenceConvertible, Equatable, Hashable, RandomAccessColl
347347
precondition(r.upperBound >= 0)
348348
precondition(r.upperBound <= cnt, "The range is outside the bounds of the data")
349349

350-
copyRange = r.lowerBound..<(r.lowerBound + Swift.min(buffer.count * strideof(DestinationType.self), r.count))
350+
copyRange = r.lowerBound..<(r.lowerBound + Swift.min(buffer.count * MemoryLayout<DestinationType>.stride, r.count))
351351
} else {
352-
copyRange = 0..<Swift.min(buffer.count * strideof(DestinationType.self), cnt)
352+
copyRange = 0..<Swift.min(buffer.count * MemoryLayout<DestinationType>.stride, cnt)
353353
}
354354

355355
guard !copyRange.isEmpty else { return 0 }
@@ -458,7 +458,7 @@ public struct Data : ReferenceConvertible, Equatable, Hashable, RandomAccessColl
458458
/// - parameter buffer: The buffer of bytes to append. The size is calculated from `SourceType` and `buffer.count`.
459459
public mutating func append<SourceType>(_ buffer : UnsafeBufferPointer<SourceType>) {
460460
_applyUnmanagedMutation {
461-
$0.append(buffer.baseAddress!, length: buffer.count * strideof(SourceType.self))
461+
$0.append(buffer.baseAddress!, length: buffer.count * MemoryLayout<SourceType>.stride)
462462
}
463463
}
464464

@@ -502,7 +502,7 @@ public struct Data : ReferenceConvertible, Equatable, Hashable, RandomAccessColl
502502
/// - parameter buffer: The replacement bytes.
503503
public mutating func replaceSubrange<SourceType>(_ subrange: Range<Index>, with buffer: UnsafeBufferPointer<SourceType>) {
504504
let nsRange = NSMakeRange(subrange.lowerBound, subrange.upperBound - subrange.lowerBound)
505-
let bufferCount = buffer.count * strideof(SourceType.self)
505+
let bufferCount = buffer.count * MemoryLayout<SourceType>.stride
506506

507507
_applyUnmanagedMutation {
508508
$0.replaceBytes(in: nsRange, withBytes: buffer.baseAddress, length: bufferCount)

stdlib/public/SDK/Foundation/DateInterval.swift

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -157,7 +157,7 @@ public struct DateInterval : ReferenceConvertible, Comparable, Hashable {
157157
public var hashValue: Int {
158158
var buf: (UInt, UInt) = (UInt(start.timeIntervalSinceReferenceDate), UInt(end.timeIntervalSinceReferenceDate))
159159
return withUnsafeMutablePointer(to: &buf) {
160-
return Int(bitPattern: CFHashBytes(unsafeBitCast($0, to: UnsafeMutablePointer<UInt8>.self), CFIndex(sizeof(UInt.self) * 2)))
160+
return Int(bitPattern: CFHashBytes(unsafeBitCast($0, to: UnsafeMutablePointer<UInt8>.self), CFIndex(MemoryLayout<UInt>.size * 2)))
161161
}
162162
}
163163

stdlib/public/SDK/Foundation/IndexPath.swift

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -154,7 +154,7 @@ public struct IndexPath : ReferenceConvertible, Equatable, Hashable, MutableColl
154154
if count == 0 {
155155
_indexes = []
156156
} else {
157-
var ptr = malloc(count * sizeof(Element.self))
157+
var ptr = malloc(count * MemoryLayout<Element>.size)
158158
defer { free(ptr) }
159159

160160
let elementPtr = ptr!.bindMemory(to: Element.self, capacity: count)

stdlib/public/SDK/Foundation/UUID.swift

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -67,7 +67,7 @@ public struct UUID : ReferenceConvertible, Hashable, Equatable, CustomStringConv
6767
public var hashValue: Int {
6868
var localValue = uuid
6969
return withUnsafeMutablePointer(to: &localValue) {
70-
return Int(bitPattern: CFHashBytes(unsafeBitCast($0, to: UnsafeMutablePointer<UInt8>.self), CFIndex(sizeof(uuid_t.self))))
70+
return Int(bitPattern: CFHashBytes(unsafeBitCast($0, to: UnsafeMutablePointer<UInt8>.self), CFIndex(MemoryLayout<uuid_t>.size)))
7171
}
7272
}
7373

0 commit comments

Comments
 (0)