You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
@@ -29,13 +30,13 @@ These functions have a few different drawbacks, most prominently their reliance
29
30
In addition to the new types, we will propose adding new API some standard library types to take advantage of `MutableSpan` and `MutableRawSpan`.
30
31
31
32
## Proposed solution
32
-
We previously introduced `Span` to provide shared read-only access to containers. A question can be raised as to whether this same type could be used for mutations. We cannot, due to the [law of exclusivity][SE-0176]. `Span` is copyable, and it should be copyable in order to properly model read access under the law of exclusivity: a value can be simultaneously accessed through multiple read-only accesses. Mutations, on the other hand, require _exclusive access_. Exclusive access cannot be modeled through a copyable type, since a copy of the value representing the access would violate exclusivity. We therefore need a type separate from `Span` in order to model mutations.
33
+
We introduced `Span` to provide shared read-only access to containers. We cannot use `Span`to also model container mutations, due to the [law of exclusivity][SE-0176]. `Span` is copyable, and must be copyable in order to properly model read access under the law of exclusivity: a value can be simultaneously accessed through multiple read-only accesses. Mutations, on the other hand, require _exclusive access_. Exclusive access cannot be modeled with a copyable type, since a copy of the value representing the access would violate exclusivity by adding a second access. We therefore need a non-copyable type separate from `Span` in order to model mutations.
33
34
34
35
#### MutableSpan
35
36
36
-
`MutableSpan` allows delegating mutations of a type's contiguous internal representation, by providing access to an exclusively-borrowed view of a range of contiguous, initialized memory. `MutableSpan` relies on guarantees that it has exclusive access to the range of memory it represents, and that the memory it represents will remain valid for the duration of the access. These guarantee data race safety and temporal safety. Like `Span`, `MutableSpan` performs bounds-checking on every access to preserve spatial safety.
37
+
`MutableSpan` allows delegating mutations of a type's contiguous internal representation, by providing access to an exclusively-borrowed view of a range of contiguous, initialized memory. `MutableSpan` relies on guarantees that it has exclusive access to the range of memory it represents, and that the memory it represents will remain valid for the duration of the access. These provide data race safety and temporal safety. Like `Span`, `MutableSpan` performs bounds-checking on every access to preserve spatial safety.
37
38
38
-
A `MutableSpan` provided by a container represents a mutation of that container, via an exclusive borrow. Mutations are implemented by mutating operations, which let the compiler statically enforce exclusivity.
39
+
A `MutableSpan` provided by a container represents a mutation of that container, via an exclusive borrow. Mutations are implemented by mutating functions and subscripts, which let the compiler statically enforce exclusivity.
These computed properties represent a case of lifetime relationships between two bindings that wasn't covered in [SE-0456][SE-0456]. There we defined lifetime relationships for computed property getters of non-escapable and copyable types (`~Escapable & Copyable`). We now need to define them for properties of non-escapable and non-copyable types (`~Escapable & ~Copyable`). A `~Escapable & ~Copyable` value borrows another binding; if this borrow is also a mutation then it is an exclusive borrow. The scope of the borrow, whether or not it is exclusive, extends until the last use of the dependent binding.
59
+
These computed properties represent a case of lifetime relationships not covered in [SE-0456][SE-0456]. In SE-0456 we defined lifetime relationships for computed property getters of non-escapable and copyable types (`~Escapable & Copyable`). We propose defining them for properties of non-escapable and non-copyable types (`~Escapable & ~Copyable`). A `~Escapable & ~Copyable` value borrows another binding; if this borrow is also a mutation then it is an exclusive borrow. The scope of the borrow, whether or not it is exclusive, extends until the last use of the dependent binding.
We store a `UnsafeMutableRawPointer` value internally in order to explicitly support reinterpreted views of memory as containing different types of `BitwiseCopyable` elements. Note that the the optionality of the pointer does not affect usage of `MutableSpan`, since accesses are bounds-checked and the pointer is only dereferenced when the `MutableSpan` isn't empty, when the pointer cannot be `nil`.
77
78
79
+
Initializers, required for library adoption, will be proposed alongside [lifetime annotations][PR-2305]; for details, see "[Initializers](#initializers)" in the [future directions](#Directions) section.
80
+
78
81
```swift
79
82
extensionMutableSpanwhereElement:~Copyable {
80
83
/// The number of initialized elements in this `MutableSpan`.
@@ -90,10 +93,14 @@ extension MutableSpan where Element: ~Copyable {
90
93
var indices: Range<Index> { get }
91
94
92
95
/// Accesses the element at the specified position.
// accessor syntax from accessors roadmap (https://forums.swift.org/t/76707)
94
98
95
99
/// Exchange the elements at the two given offsets
96
100
mutatingfuncswapAt(_i: Index, _j: Index)
101
+
102
+
/// Borrow the underlying memory for read-only access
103
+
var span: Span<Element> { borrowingget }
97
104
}
98
105
```
99
106
@@ -111,24 +118,33 @@ for i in myMutableSpan.indices {
111
118
}
112
119
```
113
120
114
-
##### `MutableSpan` API:
121
+
##### Unchecked access to elements:
115
122
116
-
Initializers, required for library adoption, will be proposed alongside [lifetime annotations][PR-2305]; for details, see "[Initializers](#initializers)" in the [future directions](#Directions) section.
123
+
The `subscript` mentioned above always checks the bounds of the `MutableSpan` before allowing access to the memory, preventing out-of-bounds accesses. We also provide an unchecked variant of the `subscript` and of the `swapAt` function as an alternative for situations where bounds-checking is costly and has already been performed:
117
124
118
125
```swift
119
126
extensionMutableSpanwhereElement:~Copyable {
127
+
/// Accesses the element at the specified `position`.
128
+
///
129
+
/// This subscript does not validate `position`; this is an unsafe operation.
130
+
///
131
+
/// - Parameter position: The offset of the element to access. `position`
132
+
/// must be greater or equal to zero, and less than `count`.
##### Bulk updating of a `MutableSpan`'s elements:
130
144
131
-
We include functions to perform bulk copies into the memory represented by a `MutableSpan`. Updating a `MutableSpan` from known-sized sources (such as `Collection` or `Span`) copies every element of a source. It is an error to do so when there is the span is too short to contain every element from the source. Updating a `MutableSpan` from `Sequence` or `IteratorProtocol` instances will copy as many items as possible, either until the input is empty or until the operation has updated the item at the last index.
145
+
We include functions to perform bulk copies of elements into the memory represented by a `MutableSpan`. Updating a `MutableSpan` from known-sized sources (such as `Collection` or `Span`) copies every element of a source. It is an error to do so when there is the span is too short to contain every element from the source. Updating a `MutableSpan` from `Sequence` or `IteratorProtocol` instances will copy as many items as possible, either until the input is empty or until the operation has updated the item at the last index.
146
+
147
+
<aname="slicing"></a>**Note:** This set of functions is sufficiently complete in functionality, but uses a minimal approach to slicing. This is only one of many possible approaches to slicing `MutableSpan`. We could revive the option of using a `some RangeExpression` parameter, or we could use the return value of a `func extracting(_: some RangeExpression)` such as was [recently added][SE-0437] to `UnsafeBufferPointer`. The latter option in combination with `mutating` functions requires the use of intermediate bindings. This section may change in response to feedback and our investigations.
@@ -203,7 +220,7 @@ These functions use a closure to define the scope of validity of `buffer`, ensur
203
220
204
221
#### MutableRawSpan
205
222
206
-
`MutableRawSpan` is similar to `MutableSpan<T>`, but reperesents untyped initialized bytes. `MutableRawSpan` specifically supports encoding and decoding applications. Its API supports `unsafeLoad(as:)` and `storeBytes(of: as:)`, as well as a variety of bulk copying operations.
223
+
`MutableRawSpan` is similar to `MutableSpan<T>`, but represents untyped initialized bytes. `MutableRawSpan` specifically supports encoding and decoding applications. Its API supports `unsafeLoad(as:)` and `storeBytes(of: as:)`, as well as a variety of bulk copying operations.
207
224
208
225
##### `MutableRawSpan` API:
209
226
@@ -230,12 +247,26 @@ extension MutableRawSpan {
230
247
/// The range of valid byte offsets into this `RawSpan`
231
248
var byteOffsets: Range<Int> { get }
232
249
}
233
-
234
250
```
235
251
236
252
##### Accessing and modifying the memory of a `MutableRawSpan`:
237
253
238
-
The basic operations available on `RawSpan` are available for `MutableRawSpan`. These operations are not type-safe, in that the loaded value returned by the operation can be invalid, and violate type invariants. Some types have a property that makes the `unsafeLoad(as:)` function safe, but we don't have a way to [formally identify](https://github.com/swiftlang/swift-evolution/blob/main/proposals/0447-span-access-shared-contiguous-storage.md#SurjectiveBitPattern) such types at this time.
254
+
`MutableRawSpan` supports storing the bytes of a `BitwiseCopyable` value to its underlying memory:
Additionally, the basic loading operations available on `RawSpan` are available for `MutableRawSpan`. These operations are not type-safe, in that the loaded value returned by the operation can be invalid, and violate type invariants. Some types have a property that makes the `unsafeLoad(as:)` function safe, but we don't have a way to [formally identify](https://github.com/swiftlang/swift-evolution/blob/main/proposals/0447-span-access-shared-contiguous-storage.md#SurjectiveBitPattern) such types at this time.
239
270
240
271
```swift
241
272
extensionMutableRawSpan {
@@ -261,22 +292,10 @@ extension MutableRawSpan {
261
292
}
262
293
```
263
294
264
-
To these, `MutableRawSpan` adds functions to store the bytes of a `BitwiseCopyable` value:
We include functions to perform bulk copies into the memory represented by a `MutableRawSpan`. Updating a `MutableRawSpan` from a `Collection` or a `Span` copies every element of a source. It is an error to do so when there is are not enough bytes in the span to contain every element from the source. Updating `MutableRawSpan` from `Sequence` or `IteratorProtocol` instance copies as many items as possible, either until the input is empty or until there are not enough bytes in the span to store another element.
**Note:** This set of functions is sufficiently complete in functionality, but uses a minimal approach to slicing. This is only one of many possible approaches to slicing `MutableRawSpan`. (See the <ahref="#slicing">note above</a> for more details on the same considerations.)
278
298
279
-
We include functions to perform bulk copies into the memory represented by a `MutableRawSpan`. Updating a `MutableRawSpan` from a `Collection` or a `Span` copies every element of a source. It is an error to do so when there is are not enough bytes in the span to contain every element from the source. Updating `MutableRawSpan` from `Sequence` or `IteratorProtocol` instance copies as many items as possible, either until the input is empty or until there are not enough bytes in the span to store another element.
280
299
```swift
281
300
extensionMutableRawSpan {
282
301
mutatingfuncupdate<S: Sequence>(
@@ -347,7 +366,7 @@ A `mutating` computed property getter defined on any type and returning a `~Esca
347
366
348
367
A `nonmutating` computed property getter returning a `~Escapable & ~Copyable` value establishes a borrowing lifetime relationship, as if returning a `~Escapable & Copyable` value (see [SE-0456][SE-0456].)
349
368
350
-
The standard library will provide `mutableSpan` computed properties. These return lifetime-dependent `MutableSpan`instances. These computed properties are the safe and composable replacements for the existing `withUnsafeMutableBufferPointer` closure-taking functions.
369
+
The standard library will provide `mutating` computed properties providing lifetime-dependent `MutableSpan`instances. These `mutableSpan`computed properties are intended as the safe and composable replacements for the existing `withUnsafeMutableBufferPointer` closure-taking functions.
351
370
352
371
```swift
353
372
extensionArray {
@@ -371,8 +390,6 @@ extension CollectionOfOne {
371
390
}
372
391
```
373
392
374
-
375
-
376
393
#### Extensions to unsafe buffer types
377
394
378
395
We hope that `MutableSpan` and `MutableRawSpan` will become the standard ways to delegate mutations of shared contiguous memory in Swift. Many current API delegate mutations with closure-based functions that receive an `UnsafeMutableBufferPointer` parameter to do this. We will provide ways to unsafely obtain `MutableSpan` instances from `UnsafeMutableBufferPointer` and `MutableRawSpan` instances from `UnsafeMutableRawBufferPointer`, in order to bridge these unsafe types to newer, safer contexts.
@@ -412,7 +429,7 @@ extension Foundation.Data {
412
429
413
430
The `mutableSpan` and `mutableBytes` properties should be performant and return their `MutableSpan` or `MutableRawSpan` with very little work, in O(1) time. In copy-on-write types, however, obtaining a `MutableSpan` is the start of the mutation, and if the backing buffer is not uniquely reference a copy must be made ahead of returning the `MutableSpan`.
414
431
415
-
Note that `MutableSpan` incurs no special behaviour for bridged types, since mutations always require a defensive copy of data bridged from Objective-C data structures.
432
+
Note that `MutableSpan` incurs no special behaviour for bridged types, since mutable bindings always require a defensive copy of data bridged from Objective-C data structures.
416
433
417
434
## Source compatibility
418
435
@@ -424,7 +441,7 @@ This proposal is additive and ABI-compatible with existing code.
424
441
425
442
## Implications on adoption
426
443
427
-
The additions described in this proposal require a new version of the Swift standard library and runtime.
444
+
The additions described in this proposal require a new version of the Swift standard library.
428
445
429
446
## Alternatives considered
430
447
@@ -478,7 +495,7 @@ extension MutableRawSpan {
478
495
```
479
496
We are subsetting functions that require lifetime annotations until such annotations are [proposed][PR-2305].
480
497
481
-
#### Splitting `MutableSpan` instances
498
+
#### Splitting `MutableSpan` instances – `MutableSpan` in divide-and-conquer algorithms
482
499
483
500
It is desirable to have a way to split a `MutableSpan` in multiple parts, for divide-and-conquer algorithms or other reasons:
484
501
@@ -488,11 +505,15 @@ extension MutableSpan where Element: ~Copyable {
488
505
}
489
506
```
490
507
491
-
Unfortunately, tuples do not support non-copyable values yet. We may be able to use the new `Vector`/`Slab`/`InlineArray` type proposed in [SE-0453][SE-0453], but destructuring its non-copyable elements remains a challenge. Solving this issue for `Span` as well as `MutableSpan` is a top priority.
508
+
Unfortunately, tuples do not support non-copyable values yet. We may be able to use `InlineArray` ([SE-0453][SE-0453]), or a bespoke type, but destructuring the non-copyable constituent part remains a challenge. Solving this issue for `Span` and `MutableSpan` is a top priority.
509
+
510
+
#### Mutating algorithms
511
+
512
+
Algorithms defined on `MutableCollection` such as `sort(by:)` and `partition(by:)` could be defined on `MutableSpan`. We believe we will be able to define these more generally once we have a generalized container protocol hierarchy.
492
513
493
514
#### <aname="OutputSpan"></a>Delegated initialization with `OutputSpan<T>`
494
515
495
516
Some data structures can delegate initialization of parts of their owned memory. The standard library added the `Array` initializer `init(unsafeUninitializedCapacity:initializingWith:)` in [SE-0223][SE-0223]. This initializer relies on `UnsafeMutableBufferPointer` and correct usage of initialization primitives. We should present a simpler and safer model of initialization by leveraging non-copyability and non-escapability.
496
517
497
-
## Acknowledgements
518
+
We expect to propose an `OutputSpan<T>` type to represent partially-initialized memory, and to support to the initialization of memory by appending to the initialized portion of the underlying storage.
0 commit comments