Skip to content

[stdlib] Create an offset based keypath at runtime #64904

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
Apr 12, 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
44 changes: 44 additions & 0 deletions stdlib/public/core/KeyPath.swift
Original file line number Diff line number Diff line change
Expand Up @@ -3893,6 +3893,50 @@ internal func _instantiateKeyPathBuffer(
return offset
}

@available(SwiftStdlib 5.9, *)
public func _createOffsetBasedKeyPath(
root: Any.Type,
value: Any.Type,
offset: Int
) -> AnyKeyPath {
func openRoot<Root>(_: Root.Type) -> AnyKeyPath.Type {
func openValue<Value>(_: Value.Type) -> AnyKeyPath.Type {
KeyPath<Root, Value>.self
}

return _openExistential(value, do: openValue(_:))
}

let kpTy = _openExistential(root, do: openRoot(_:))

// 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) {
var builder = KeyPathBuffer.Builder($0)
let header = KeyPathBuffer.Header(
size: kpBufferSize - MemoryLayout<Int>.size,
trivial: true,
hasReferencePrefix: false
)

builder.pushHeader(header)

let componentHeader = RawKeyPathComponent.Header(
stored: .struct,
mutable: false,
inlineOffset: UInt32(offset)
)

let component = RawKeyPathComponent(
header: componentHeader,
body: UnsafeRawBufferPointer(start: nil, count: 0)
)

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

#if SWIFT_ENABLE_REFLECTION

@_silgen_name("swift_keyPath_copySymbolName")
Expand Down
21 changes: 21 additions & 0 deletions test/stdlib/KeyPath.swift
Original file line number Diff line number Diff line change
Expand Up @@ -1065,5 +1065,26 @@ keyPath.test("ReferenceWritableKeyPath statically typed as WritableKeyPath") {
expectEqual(outer[keyPath: upcastKeyPath], 46)
}

struct Dog {
var name: String
var age: Int
}

if #available(SwiftStdlib 5.9, *) {
keyPath.test("_createOffsetBasedKeyPath") {
let dogAgeKp = _createOffsetBasedKeyPath(
root: Dog.self,
value: Int.self,
offset: 16
) as? KeyPath<Dog, Int>

expectNotNil(dogAgeKp)

let sparky = Dog(name: "Sparky", age: 7)

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

runAllTests()