Skip to content

[4.2] [SE-0210] Add a MemoryLayout<T>.offset(of:) method for getting the offset of inline storage #16499

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 2 commits into from
May 10, 2018
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
21 changes: 21 additions & 0 deletions stdlib/public/core/KeyPath.swift
Original file line number Diff line number Diff line change
Expand Up @@ -156,6 +156,27 @@ public class AnyKeyPath: Hashable, _AppendKeyPath {
let base = UnsafeRawPointer(Builtin.projectTailElems(self, Int32.self))
return try f(KeyPathBuffer(base: base))
}

@_inlineable // FIXME(sil-serialize-all)
@_versioned // FIXME(sil-serialize-all)
internal var _storedInlineOffset: Int? {
return withBuffer {
var buffer = $0
var offset = 0
while true {
let (rawComponent, optNextType) = buffer.next()
switch rawComponent.header.kind {
case .struct:
offset += rawComponent._structOrClassOffset

case .class, .computed, .optionalChain, .optionalForce, .optionalWrap:
return .none
}

if optNextType == nil { return .some(offset) }
}
}
}
}

/// A partially type-erased key path, from a concrete root type to any
Expand Down
55 changes: 55 additions & 0 deletions stdlib/public/core/MemoryLayout.swift
Original file line number Diff line number Diff line change
Expand Up @@ -162,4 +162,59 @@ extension MemoryLayout {
public static func alignment(ofValue value: T) -> Int {
return MemoryLayout.alignment
}

/// Returns the offset of an inline stored property of `T` within the
/// in-memory representation of `T`.
///
/// If the given `key` refers to inline, directly addressable storage within
/// the in-memory representation of `T`, then the return value is a distance
/// in bytes that can be added to a pointer of type `T` to get a pointer to
/// the storage accessed by `key`. If the return value is non-nil, then these
/// formulations are equivalent:
///
/// var root: T, value: U
/// var key: WritableKeyPath<T, U>
/// // Mutation through the key path...
/// root[keyPath: key] = value
/// // ...is exactly equivalent to mutation through the offset pointer...
/// withUnsafeMutablePointer(to: &root) {
/// (UnsafeMutableRawPointer($0) + MemoryLayout<T>.offset(of: key))
/// // ...which can be assumed to be bound to the target type
/// .assumingMemoryBound(to: U.self).pointee = value
/// }
///
/// - Parameter key: A key path referring to storage that can be accessed
/// through a value of type `T`.
/// - Returns: The offset in bytes from a pointer to a value of type `T`
/// to a pointer to the storage referenced by `key`, or `nil` if no
/// such offset is available for the storage referenced by `key`, such as
/// because `key` is computed, has observers, requires reabstraction, or
/// overlaps storage with other properties.
///
/// A property has inline, directly addressable storage when it is a stored
/// property for which no additional work is required to extract or set the
/// value. For example:
///
/// struct ProductCategory {
/// var name: String // inline, directly-addressable
/// var updateCounter: Int // inline, directly-addressable
/// var productCount: Int { // computed properties are not directly addressable
/// return products.count
/// }
/// var products: [Product] { // didSet/willSet properties are not directly addressable
/// didSet { updateCounter += 1 }
/// }
/// }
///
/// When using `offset(of:)` with a type imported from a library, don't assume
/// that future versions of the library will have the same behavior. If a
/// property is converted from a stored property to a computed property, the
/// result of `offset(of:)` changes to `nil`. That kind of conversion is
/// non-breaking in other contexts, but would trigger a runtime error if the
/// result of `offset(of:)` is force-unwrapped.
@_inlineable // FIXME(sil-serialize-all)
@_transparent
public static func offset(of key: PartialKeyPath<T>) -> Int? {
return key._storedInlineOffset
}
}
26 changes: 26 additions & 0 deletions test/stdlib/KeyPath.swift
Original file line number Diff line number Diff line change
Expand Up @@ -666,6 +666,32 @@ keyPath.test("subscripts") {
expectEqual(base[keyPath: ints_be], (17 + 38).bigEndian)
}

struct NonOffsetableProperties {
// observers
var x: Int { didSet {} }
// reabstracted
var y: () -> ()
// computed
var z: Int { return 0 }
}

keyPath.test("offsets") {
let SLayout = MemoryLayout<S<Int>>.self
expectNotNil(SLayout.offset(of: \S<Int>.x))
expectNotNil(SLayout.offset(of: \S<Int>.y))
expectNotNil(SLayout.offset(of: \S<Int>.z))
expectNotNil(SLayout.offset(of: \S<Int>.p))
expectNotNil(SLayout.offset(of: \S<Int>.p.x))
expectNotNil(SLayout.offset(of: \S<Int>.p.y))
expectNotNil(SLayout.offset(of: \S<Int>.c))
expectNil(SLayout.offset(of: \S<Int>.c.x))

let NOPLayout = MemoryLayout<NonOffsetableProperties>.self
expectNil(NOPLayout.offset(of: \NonOffsetableProperties.x))
expectNil(NOPLayout.offset(of: \NonOffsetableProperties.y))
expectNil(NOPLayout.offset(of: \NonOffsetableProperties.z))
}

// SR-6096

protocol Protocol6096 {}
Expand Down