Skip to content

Commit 31f8031

Browse files
committed
Add example of improved ergonomics
1 parent bf7a3d3 commit 31f8031

File tree

1 file changed

+25
-0
lines changed

1 file changed

+25
-0
lines changed

proposals/AAAA-stdlib-span-properties.md

Lines changed: 25 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -49,6 +49,31 @@ If we were to attempt using `b` again after the call to `modify(&a)`, the compil
4949

5050
Given this, we propose to enable the definition of a borrowing relationship via a computed property. With this feature we then propose to add `storage` computed properties to standard library types that can share their internal typed storage, as well as `bytes` computed properties to those standard library types that can safely share their internal storage as untyped memory.
5151

52+
One of the purposes of `Span` is to provide a safer alternative to `UnsafeBufferPointer`. This proposal builds on it and allows us to rewrite code reliant on `withUnsafeBufferPointer()` to use `storage` properties instead. Eventually, code that requires access to contiguous memory can be rewritten to use `Span`, gaining better composability in the process. For example:
53+
54+
```swift
55+
let result = try myArray.withUnsafeBufferPointer { buffer in
56+
let indices = findElements(buffer)
57+
var myResult = MyResult()
58+
for i in indices {
59+
try myResult.modify(buffer[i])
60+
}
61+
}
62+
```
63+
64+
This closure-based call is difficult to evolve, such as making `result` have a non-copyable type, adding a concurrent task, or adding typed throws. An alternative based on a vended `Span` property would look like this:
65+
66+
```swift
67+
let span = myArray.storage
68+
let indices = findElements(span)
69+
var myResult = MyResult()
70+
for i in indices {
71+
try myResult.modify(span[i])
72+
}
73+
```
74+
75+
In this version, code evolution is not constrained by a closure. Incorrect escapes of `span` will be diagnosed by the compiler, and the `modify()` function can be updated with typed throws, concurrency or other features as necessary.
76+
5277
## Detailed Design
5378

5479
A computed property getter of an `Escapable` type returning a non-escapable and copyable type (`~Escapable & Copyable`) establishes a borrowing lifetime relationship of the returned value on the callee's binding. As long as the returned value exists (including local copies,) then the callee's binding is being borrowed. In terms of the law of exclusivity, a borrow is a read-only access. Multiple borrows are allowed to overlap, but cannot overlap with any mutation.

0 commit comments

Comments
 (0)