Skip to content

Commit

Permalink
Merge pull request #1022 from hylo-lang/unsafe-initialize-pointee
Browse files Browse the repository at this point in the history
Implement a pointee initialization method that doesn't use lambdas
  • Loading branch information
kyouko-taiga authored Sep 20, 2023
2 parents 4da0b18 + 783a0f1 commit 61b9d90
Show file tree
Hide file tree
Showing 2 changed files with 27 additions and 3 deletions.
15 changes: 15 additions & 0 deletions Library/Hylo/Core/PointerToMutable.hylo
Original file line number Diff line number Diff line change
Expand Up @@ -93,4 +93,19 @@ public extension PointerToMutable where Pointee: Movable {
return base as* (remote sink Pointee)
}

/// Initialize the value at the address represented by `self` to `value`.
///
/// - Requires: the `MemoryLayout<Pointee>.size()` bytes starting at the address are uninitialized
/// and suitably aligned for `Pointee`.
public fun unsafe_initialize_pointee(_ value: sink Pointee) {
initialize<Pointee>(&(base as* (remote set Pointee)), to: value)
}

}

/// Initializes `x` to `y`.
///
/// - Note: This function is a workaround for the lack of `set` bindings (see #925).
fun initialize<T: Movable>(_ x: set T, to y: sink T) {
&x = y
}
15 changes: 12 additions & 3 deletions Tests/LibraryTests/TestCases/PointerToMutableTests.hylo
Original file line number Diff line number Diff line change
Expand Up @@ -24,16 +24,25 @@ fun test_advance() {
precondition(!(f == e))
}

fun test_pointee() {
fun test_initialize_pointee_lambda() {
let p = PointerToMutable<Int>.allocate(count: 1)
p.unsafe_initialize_pointee(fun (_ i: set Int) -> Void { &i = 42 })
let y = p.unsafe_pointee()
precondition(42 == y)
precondition(y == 42)
p.deallocate()
}

fun test_initialize_pointee_direct() {
let p = PointerToMutable<Int>.allocate(count: 1)
p.unsafe_initialize_pointee(42)
let y = p.unsafe_pointee()
precondition(y == 42)
p.deallocate()
}

public fun main() {
test_advance_by_bytes()
test_advance()
test_pointee()
test_initialize_pointee_lambda()
test_initialize_pointee_direct()
}

0 comments on commit 61b9d90

Please sign in to comment.