Skip to content

[5.9] [stdlib] Add support for classes in _createOffsetBasedKeyPath #66932

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
Jun 27, 2023
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
14 changes: 10 additions & 4 deletions stdlib/public/core/KeyPath.swift
Original file line number Diff line number Diff line change
Expand Up @@ -3893,6 +3893,8 @@ internal func _instantiateKeyPathBuffer(
return offset
}

#if SWIFT_ENABLE_REFLECTION

@available(SwiftStdlib 5.9, *)
public func _createOffsetBasedKeyPath(
root: Any.Type,
Expand All @@ -3912,7 +3914,7 @@ public func _createOffsetBasedKeyPath(
// The buffer header is 32 bits, but components must start on a word
// boundary.
let kpBufferSize = MemoryLayout<Int>.size + MemoryLayout<Int32>.size
return kpTy._create(capacityInBytes: kpBufferSize) {
let kp = kpTy._create(capacityInBytes: kpBufferSize) {
var builder = KeyPathBuffer.Builder($0)
let header = KeyPathBuffer.Header(
size: kpBufferSize - MemoryLayout<Int>.size,
Expand All @@ -3923,7 +3925,7 @@ public func _createOffsetBasedKeyPath(
builder.pushHeader(header)

let componentHeader = RawKeyPathComponent.Header(
stored: .struct,
stored: _MetadataKind(root) == .struct ? .struct : .class,
mutable: false,
inlineOffset: UInt32(offset)
)
Expand All @@ -3935,9 +3937,13 @@ public func _createOffsetBasedKeyPath(

component.clone(into: &builder.buffer, endOfReferencePrefix: false)
}
}

#if SWIFT_ENABLE_REFLECTION
if _MetadataKind(root) == .struct {
kp.assignOffsetToStorage(offset: offset)
}

return kp
}

@_silgen_name("swift_keyPath_copySymbolName")
fileprivate func keyPath_copySymbolName(
Expand Down
22 changes: 22 additions & 0 deletions test/stdlib/KeyPath.swift
Original file line number Diff line number Diff line change
Expand Up @@ -1070,6 +1070,16 @@ struct Dog {
var age: Int
}

class Cat {
var name: String
var age: Int

init(name: String, age: Int) {
self.name = name
self.age = age
}
}

if #available(SwiftStdlib 5.9, *) {
keyPath.test("_createOffsetBasedKeyPath") {
let dogAgeKp = _createOffsetBasedKeyPath(
Expand All @@ -1083,6 +1093,18 @@ if #available(SwiftStdlib 5.9, *) {
let sparky = Dog(name: "Sparky", age: 7)

expectEqual(sparky[keyPath: dogAgeKp!], 7)

let catNameKp = _createOffsetBasedKeyPath(
root: Cat.self,
value: String.self,
offset: 16
) as? KeyPath<Cat, String>

expectNotNil(catNameKp)

let chloe = Cat(name: "Chloe", age: 4)

expectEqual(chloe[keyPath: catNameKp!], "Chloe")
}
}

Expand Down