-
Notifications
You must be signed in to change notification settings - Fork 10.5k
/
Copy pathMutableSpan.swift
883 lines (802 loc) · 27.9 KB
/
MutableSpan.swift
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
//===--- MutableSpan.swift ------------------------------------------------===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2024 - 2025 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See https://swift.org/LICENSE.txt for license information
// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
//===----------------------------------------------------------------------===//
// A MutableSpan<Element> represents a span of memory which
// contains initialized `Element` instances.
@safe
@frozen
@available(SwiftStdlib 6.2, *)
public struct MutableSpan<Element: ~Copyable>
: ~Copyable, ~Escapable {
@usableFromInline
internal let _pointer: UnsafeMutableRawPointer?
@usableFromInline
internal let _count: Int
@_alwaysEmitIntoClient
internal func _start() -> UnsafeMutableRawPointer {
unsafe _pointer._unsafelyUnwrappedUnchecked
}
@unsafe
@_unsafeNonescapableResult
@_alwaysEmitIntoClient
@lifetime(borrow start)
internal init(
_unchecked start: UnsafeMutableRawPointer?,
count: Int
) {
unsafe _pointer = start
_count = count
}
}
@available(SwiftStdlib 6.2, *)
extension MutableSpan: @unchecked Sendable where Element: Sendable {}
@available(SwiftStdlib 6.2, *)
extension MutableSpan where Element: ~Copyable {
@unsafe
@_unsafeNonescapableResult
@usableFromInline
@lifetime(borrow elements)
internal init(
_unchecked elements: UnsafeMutableBufferPointer<Element>
) {
unsafe _pointer = .init(elements.baseAddress)
_count = elements.count
}
@unsafe
@_alwaysEmitIntoClient
@lifetime(borrow buffer)
public init(
_unsafeElements buffer: UnsafeMutableBufferPointer<Element>
) {
_precondition(
((Int(bitPattern: buffer.baseAddress) &
(MemoryLayout<Element>.alignment &- 1)) == 0),
"baseAddress must be properly aligned to access Element"
)
let ms = unsafe MutableSpan<Element>(_unchecked: buffer)
self = unsafe _overrideLifetime(ms, borrowing: buffer)
}
@unsafe
@_alwaysEmitIntoClient
@lifetime(borrow start)
public init(
_unsafeStart start: UnsafeMutablePointer<Element>,
count: Int
) {
_precondition(count >= 0, "Count must not be negative")
let buffer = unsafe UnsafeMutableBufferPointer(start: start, count: count)
let ms = unsafe MutableSpan(_unsafeElements: buffer)
self = unsafe _overrideLifetime(ms, borrowing: start)
}
}
@available(SwiftStdlib 6.2, *)
extension MutableSpan {
@unsafe
@_alwaysEmitIntoClient
@lifetime(borrow elements)
public init(
_unsafeElements elements: borrowing Slice<UnsafeMutableBufferPointer<Element>>
) {
let rb = unsafe UnsafeMutableBufferPointer(rebasing: elements)
let ms = unsafe MutableSpan(_unsafeElements: rb)
self = unsafe _overrideLifetime(ms, borrowing: elements)
}
}
@available(SwiftStdlib 6.2, *)
extension MutableSpan where Element: BitwiseCopyable {
@unsafe
@_alwaysEmitIntoClient
@lifetime(borrow buffer)
public init(
_unsafeBytes buffer: UnsafeMutableRawBufferPointer
) {
_precondition(
((Int(bitPattern: buffer.baseAddress) &
(MemoryLayout<Element>.alignment &- 1)) == 0),
"baseAddress must be properly aligned to access Element"
)
let (byteCount, stride) = (buffer.count, MemoryLayout<Element>.stride)
let (count, remainder) = byteCount.quotientAndRemainder(dividingBy: stride)
_precondition(remainder == 0, "Span must contain a whole number of elements")
let elements = unsafe UnsafeMutableBufferPointer<Element>(
start: buffer.baseAddress?.assumingMemoryBound(to: Element.self),
count: count
)
let ms = unsafe MutableSpan(_unsafeElements: elements)
self = unsafe _overrideLifetime(ms, borrowing: buffer)
}
@unsafe
@_alwaysEmitIntoClient
@lifetime(borrow pointer)
public init(
_unsafeStart pointer: UnsafeMutableRawPointer,
byteCount: Int
) {
_precondition(byteCount >= 0, "Count must not be negative")
let bytes = unsafe UnsafeMutableRawBufferPointer(
start: pointer, count: byteCount
)
let ms = unsafe MutableSpan(_unsafeBytes: bytes)
self = unsafe _overrideLifetime(ms, borrowing: pointer)
}
@unsafe
@_alwaysEmitIntoClient
@lifetime(borrow buffer)
public init(
_unsafeBytes buffer: borrowing Slice<UnsafeMutableRawBufferPointer>
) {
let bytes = unsafe UnsafeMutableRawBufferPointer(rebasing: buffer)
let ms = unsafe MutableSpan(_unsafeBytes: bytes)
self = unsafe _overrideLifetime(ms, borrowing: buffer)
}
}
@available(SwiftStdlib 6.2, *)
extension Span where Element: ~Copyable {
@_alwaysEmitIntoClient
@lifetime(borrow mutableSpan)
public init(_mutableSpan mutableSpan: borrowing MutableSpan<Element>) {
let pointer =
unsafe mutableSpan._pointer?.assumingMemoryBound(to: Element.self)
let buffer = unsafe UnsafeBufferPointer(
start: pointer, count: mutableSpan.count
)
let span = unsafe Span(_unsafeElements: buffer)
self = unsafe _overrideLifetime(span, borrowing: mutableSpan)
}
}
@available(SwiftStdlib 6.2, *)
extension MutableSpan where Element: ~Copyable {
@_alwaysEmitIntoClient
public var span: Span<Element> {
@lifetime(borrow self)
borrowing get {
Span(_mutableSpan: self)
}
}
}
@available(SwiftStdlib 6.2, *)
extension RawSpan {
@_alwaysEmitIntoClient
@lifetime(borrow mutableSpan)
public init<Element: BitwiseCopyable>(
_mutableSpan mutableSpan: borrowing MutableSpan<Element>
) {
let pointer = unsafe mutableSpan._pointer
let byteCount = mutableSpan.count &* MemoryLayout<Element>.stride
let buffer = unsafe UnsafeRawBufferPointer(start: pointer, count: byteCount)
let rawSpan = unsafe RawSpan(_unsafeBytes: buffer)
self = unsafe _overrideLifetime(rawSpan, borrowing: mutableSpan)
}
}
@available(SwiftStdlib 6.2, *)
extension MutableSpan where Element: ~Copyable {
@_alwaysEmitIntoClient
public var _description: String {
let addr = unsafe String(
UInt(bitPattern: _pointer), radix: 16, uppercase: false
)
return "(0x\(addr), \(_count))"
}
}
//MARK: Collection, RandomAccessCollection
@available(SwiftStdlib 6.2, *)
extension MutableSpan where Element: ~Copyable {
@_alwaysEmitIntoClient
public var count: Int { _count }
@_alwaysEmitIntoClient
public var isEmpty: Bool { _count == 0 }
public typealias Index = Int
@_alwaysEmitIntoClient
public var indices: Range<Index> {
unsafe Range(_uncheckedBounds: (0, _count))
}
}
@available(SwiftStdlib 6.2, *)
extension MutableSpan where Element: BitwiseCopyable {
/// Construct a RawSpan over the memory represented by this span
///
/// - Returns: a RawSpan over the memory represented by this span
@_alwaysEmitIntoClient
public var bytes: RawSpan {
@lifetime(borrow self)
borrowing get {
RawSpan(_mutableSpan: self)
}
}
/// Construct a MutableRawSpan over the memory represented by this span
///
/// - Returns: a MutableRawSpan over the memory represented by this span
@_alwaysEmitIntoClient
public var mutableBytes: MutableRawSpan {
@lifetime(&self)
mutating get {
MutableRawSpan(_elements: &self)
}
}
}
@available(SwiftStdlib 6.2, *)
extension MutableSpan where Element: ~Copyable {
/// Accesses the element at the specified position in the `Span`.
///
/// - Parameter position: The offset of the element to access. `position`
/// must be greater or equal to zero, and less than `count`.
///
/// - Complexity: O(1)
@_alwaysEmitIntoClient
public subscript(_ position: Index) -> Element {
unsafeAddress {
_precondition(indices.contains(position), "index out of bounds")
return unsafe UnsafePointer(_unsafeAddressOfElement(unchecked: position))
}
@lifetime(self: copy self)
unsafeMutableAddress {
_precondition(indices.contains(position), "index out of bounds")
return unsafe _unsafeAddressOfElement(unchecked: position)
}
}
/// Accesses the element at the specified position in the `Span`.
///
/// This subscript does not validate `position`; this is an unsafe operation.
///
/// - Parameter position: The offset of the element to access. `position`
/// must be greater or equal to zero, and less than `count`.
///
/// - Complexity: O(1)
@unsafe
@_alwaysEmitIntoClient
public subscript(unchecked position: Index) -> Element {
unsafeAddress {
unsafe UnsafePointer(_unsafeAddressOfElement(unchecked: position))
}
@lifetime(self: copy self)
unsafeMutableAddress {
unsafe _unsafeAddressOfElement(unchecked: position)
}
}
@unsafe
@_alwaysEmitIntoClient
internal func _unsafeAddressOfElement(
unchecked position: Index
) -> UnsafeMutablePointer<Element> {
let elementOffset = position &* MemoryLayout<Element>.stride
let address = unsafe _start().advanced(by: elementOffset)
return unsafe address.assumingMemoryBound(to: Element.self)
}
}
@available(SwiftStdlib 6.2, *)
extension MutableSpan where Element: ~Copyable {
@_alwaysEmitIntoClient
@lifetime(self: copy self)
public mutating func swapAt(_ i: Index, _ j: Index) {
_precondition(indices.contains(Index(i)))
_precondition(indices.contains(Index(j)))
unsafe swapAt(unchecked: i, unchecked: j)
}
@unsafe
@_alwaysEmitIntoClient
@lifetime(self: copy self)
public mutating func swapAt(unchecked i: Index, unchecked j: Index) {
let pi = unsafe _unsafeAddressOfElement(unchecked: i)
let pj = unsafe _unsafeAddressOfElement(unchecked: j)
let temporary = unsafe pi.move()
unsafe pi.initialize(to: pj.move())
unsafe pj.initialize(to: consume temporary)
}
}
@available(SwiftStdlib 6.2, *)
extension MutableSpan where Element: BitwiseCopyable {
/// Accesses the element at the specified position in the `Span`.
///
/// - Parameter position: The offset of the element to access. `position`
/// must be greater or equal to zero, and less than `count`.
///
/// - Complexity: O(1)
@_alwaysEmitIntoClient
public subscript(_ position: Index) -> Element {
get {
_precondition(indices.contains(position), "index out of bounds")
return unsafe self[unchecked: position]
}
@lifetime(self: copy self)
set {
_precondition(indices.contains(position), "index out of bounds")
unsafe self[unchecked: position] = newValue
}
}
/// Accesses the element at the specified position in the `Span`.
///
/// This subscript does not validate `position`; this is an unsafe operation.
///
/// - Parameter position: The offset of the element to access. `position`
/// must be greater or equal to zero, and less than `count`.
///
/// - Complexity: O(1)
@unsafe
@_alwaysEmitIntoClient
public subscript(unchecked position: Index) -> Element {
get {
let offset = position&*MemoryLayout<Element>.stride
return unsafe _start().loadUnaligned(
fromByteOffset: offset, as: Element.self
)
}
@lifetime(self: copy self)
set {
let offset = position&*MemoryLayout<Element>.stride
unsafe _start().storeBytes(
of: newValue, toByteOffset: offset, as: Element.self
)
}
}
}
@available(SwiftStdlib 6.2, *)
extension MutableSpan where Element: ~Copyable {
//FIXME: mark closure parameter as non-escaping
@_alwaysEmitIntoClient
public func withUnsafeBufferPointer<E: Error, Result: ~Copyable>(
_ body: (_ buffer: UnsafeBufferPointer<Element>) throws(E) -> Result
) throws(E) -> Result {
try unsafe Span(_mutableSpan: self).withUnsafeBufferPointer(body)
}
//FIXME: mark closure parameter as non-escaping
@_alwaysEmitIntoClient
@lifetime(self: copy self)
public mutating func withUnsafeMutableBufferPointer<
E: Error, Result: ~Copyable
>(
_ body: (UnsafeMutableBufferPointer<Element>) throws(E) -> Result
) throws(E) -> Result {
guard let pointer = unsafe _pointer, count > 0 else {
return try unsafe body(.init(start: nil, count: 0))
}
// bind memory by hand to sidestep alignment concerns
let binding = Builtin.bindMemory(
pointer._rawValue, count._builtinWordValue, Element.self
)
defer { Builtin.rebindMemory(pointer._rawValue, binding) }
return try unsafe body(.init(start: .init(pointer._rawValue), count: count))
}
}
@available(SwiftStdlib 6.2, *)
extension MutableSpan where Element: BitwiseCopyable {
//FIXME: mark closure parameter as non-escaping
@_alwaysEmitIntoClient
public func withUnsafeBytes<E: Error, Result: ~Copyable>(
_ body: (_ buffer: UnsafeRawBufferPointer) throws(E) -> Result
) throws(E) -> Result {
try unsafe RawSpan(_mutableSpan: self).withUnsafeBytes(body)
}
//FIXME: mark closure parameter as non-escaping
@_alwaysEmitIntoClient
@lifetime(self: copy self)
public mutating func withUnsafeMutableBytes<E: Error, Result: ~Copyable>(
_ body: (_ buffer: UnsafeMutableRawBufferPointer) throws(E) -> Result
) throws(E) -> Result {
let bytes = unsafe UnsafeMutableRawBufferPointer(
start: (_count == 0) ? nil : _start(),
count: _count &* MemoryLayout<Element>.stride
)
return try unsafe body(bytes)
}
}
//MARK: bulk-update functions
@available(SwiftStdlib 6.2, *)
extension MutableSpan {
@_alwaysEmitIntoClient
@lifetime(self: copy self)
public mutating func update(repeating repeatedValue: consuming Element) {
unsafe _start().withMemoryRebound(to: Element.self, capacity: count) {
unsafe $0.update(repeating: repeatedValue, count: count)
}
}
@_alwaysEmitIntoClient
@lifetime(self: copy self)
public mutating func update<S: Sequence>(
from source: S
) -> (unwritten: S.Iterator, index: Index) where S.Element == Element {
var iterator = source.makeIterator()
let index = update(from: &iterator)
return (iterator, index)
}
@_alwaysEmitIntoClient
@lifetime(self: copy self)
public mutating func update(
from elements: inout some IteratorProtocol<Element>
) -> Index {
var index = 0
while index < _count {
guard let element = elements.next() else { break }
unsafe self[unchecked: index] = element
index &+= 1
}
return index
}
@_alwaysEmitIntoClient
@lifetime(self: copy self)
public mutating func update(
fromContentsOf source: some Collection<Element>
) -> Index {
let updated = source.withContiguousStorageIfAvailable {
self.update(fromContentsOf: unsafe Span(_unsafeElements: $0))
}
if let updated {
return updated
}
//TODO: use _copyContents here
var iterator = source.makeIterator()
let index = update(from: &iterator)
_precondition(
iterator.next() == nil,
"destination buffer view cannot contain every element from source."
)
return index
}
@_alwaysEmitIntoClient
@lifetime(self: copy self)
public mutating func update(fromContentsOf source: Span<Element>) -> Index {
guard !source.isEmpty else { return 0 }
_precondition(
source.count <= self.count,
"destination span cannot contain every element from source."
)
unsafe _start().withMemoryRebound(
to: Element.self, capacity: source.count
) { dest in
unsafe source.withUnsafeBufferPointer {
unsafe dest.update(from: $0.baseAddress!, count: $0.count)
}
}
return source.count
}
@_alwaysEmitIntoClient
@lifetime(self: copy self)
public mutating func update(
fromContentsOf source: borrowing MutableSpan<Element>
) -> Index {
update(fromContentsOf: source.span)
}
}
@available(SwiftStdlib 6.2, *)
extension MutableSpan where Element: ~Copyable {
// @_alwaysEmitIntoClient
// public mutating func moveUpdate(
// fromContentsOf source: consuming OutputSpan<Element>
// ) -> Index {
// guard !source.isEmpty else { return 0 }
// _precondition(
// source.count <= self.count,
// "destination span cannot contain every element from source."
// )
// let buffer = unsafe source.relinquishBorrowedMemory()
// // we must now deinitialize the returned UMBP
// unsafe _start().moveInitializeMemory(
// as: Element.self, from: buffer.baseAddress!, count: buffer.count
// )
// return buffer.count
// }
@_alwaysEmitIntoClient
@lifetime(self: copy self)
public mutating func moveUpdate(
fromContentsOf source: UnsafeMutableBufferPointer<Element>
) -> Index {
// let source = OutputSpan(_initializing: source, initialized: source.count)
// return self.moveUpdate(fromContentsOf: source)
unsafe withUnsafeMutableBufferPointer {
unsafe $0.moveUpdate(fromContentsOf: source)
}
}
}
@available(SwiftStdlib 6.2, *)
extension MutableSpan {
@_alwaysEmitIntoClient
@lifetime(self: copy self)
public mutating func moveUpdate(
fromContentsOf source: Slice<UnsafeMutableBufferPointer<Element>>
) -> Index {
unsafe moveUpdate(fromContentsOf: .init(rebasing: source))
}
}
@available(SwiftStdlib 6.2, *)
extension MutableSpan where Element: BitwiseCopyable {
@_alwaysEmitIntoClient
@lifetime(self: copy self)
public mutating func update(
repeating repeatedValue: Element
) where Element: BitwiseCopyable {
guard count > 0 else { return }
// rebind _start manually in order to avoid assumptions about alignment.
let rp = unsafe _start()._rawValue
let binding = Builtin.bindMemory(rp, count._builtinWordValue, Element.self)
let rebound = unsafe UnsafeMutablePointer<Element>(rp)
unsafe rebound.update(repeating: repeatedValue, count: count)
Builtin.rebindMemory(rp, binding)
}
@_alwaysEmitIntoClient
@lifetime(self: copy self)
public mutating func update<S: Sequence>(
from source: S
) -> (unwritten: S.Iterator, index: Index)
where S.Element == Element, Element: BitwiseCopyable {
var iterator = source.makeIterator()
let index = update(from: &iterator)
return (iterator, index)
}
@_alwaysEmitIntoClient
@lifetime(self: copy self)
public mutating func update(
from elements: inout some IteratorProtocol<Element>
) -> Index {
var index = 0
while index < _count {
guard let element = elements.next() else { break }
unsafe self[unchecked: index] = element
index &+= 1
}
return index
}
@_alwaysEmitIntoClient
@lifetime(self: copy self)
public mutating func update(
fromContentsOf source: some Collection<Element>
) -> Index where Element: BitwiseCopyable {
let updated = source.withContiguousStorageIfAvailable {
self.update(fromContentsOf: unsafe Span(_unsafeElements: $0))
}
if let updated {
return updated
}
//TODO: use _copyContents here
var iterator = source.makeIterator()
let index = update(from: &iterator)
_precondition(
iterator.next() == nil,
"destination buffer view cannot contain every element from source."
)
return index
}
@_alwaysEmitIntoClient
@lifetime(self: copy self)
public mutating func update(
fromContentsOf source: Span<Element>
) -> Index where Element: BitwiseCopyable {
guard !source.isEmpty else { return 0 }
_precondition(
source.count <= self.count,
"destination span cannot contain every element from source."
)
unsafe source.withUnsafeBufferPointer {
unsafe _start().copyMemory(
from: $0.baseAddress!,
byteCount: $0.count &* MemoryLayout<Element>.stride
)
}
return source.count
}
@_alwaysEmitIntoClient
@lifetime(self: copy self)
public mutating func update(
fromContentsOf source: borrowing MutableSpan<Element>
) -> Index where Element: BitwiseCopyable {
update(fromContentsOf: source.span)
}
}
// MARK: sub-spans
@available(SwiftStdlib 6.2, *)
extension MutableSpan where Element: ~Copyable {
/// Constructs a new span over the items within the supplied range of
/// positions within this span.
///
/// The returned span's first item is always at offset 0; unlike buffer
/// slices, extracted spans do not share their indices with the
/// span from which they are extracted.
///
/// - Parameter bounds: A valid range of positions. Every position in
/// this range must be within the bounds of this `MutableSpan`.
///
/// - Returns: A `MutableSpan` over the items within `bounds`
///
/// - Complexity: O(1)
@_alwaysEmitIntoClient
@lifetime(borrow self)
mutating public func extracting(_ bounds: Range<Index>) -> Self {
_precondition(
UInt(bitPattern: bounds.lowerBound) <= UInt(bitPattern: _count) &&
UInt(bitPattern: bounds.upperBound) <= UInt(bitPattern: _count),
"Index range out of bounds"
)
return unsafe extracting(unchecked: bounds)
}
/// Constructs a new span over the items within the supplied range of
/// positions within this span.
///
/// The returned span's first item is always at offset 0; unlike buffer
/// slices, extracted spans do not share their indices with the
/// span from which they are extracted.
///
/// This function does not validate `bounds`; this is an unsafe operation.
///
/// - Parameter bounds: A valid range of positions. Every position in
/// this range must be within the bounds of this `MutableSpan`.
///
/// - Returns: A `MutableSpan` over the items within `bounds`
///
/// - Complexity: O(1)
@unsafe
@_alwaysEmitIntoClient
@lifetime(borrow self)
mutating public func extracting(unchecked bounds: Range<Index>) -> Self {
let delta = bounds.lowerBound &* MemoryLayout<Element>.stride
let newStart = unsafe _pointer?.advanced(by: delta)
let newSpan = unsafe Self(_unchecked: newStart, count: bounds.count)
return unsafe _overrideLifetime(newSpan, mutating: &self)
}
/// Constructs a new span over the items within the supplied range of
/// positions within this span.
///
/// The returned span's first item is always at offset 0; unlike buffer
/// slices, extracted spans do not share their indices with the
/// span from which they are extracted.
///
/// - Parameter bounds: A valid range of positions. Every position in
/// this range must be within the bounds of this `MutableSpan`.
///
/// - Returns: A `MutableSpan` over the items within `bounds`
///
/// - Complexity: O(1)
@_alwaysEmitIntoClient
@lifetime(borrow self)
mutating public func extracting(
_ bounds: some RangeExpression<Index>
) -> Self {
extracting(bounds.relative(to: indices))
}
/// Constructs a new span over the items within the supplied range of
/// positions within this span.
///
/// The returned span's first item is always at offset 0; unlike buffer
/// slices, extracted spans do not share their indices with the
/// span from which they are extracted.
///
/// This function does not validate `bounds`; this is an unsafe operation.
///
/// - Parameter bounds: A valid range of positions. Every position in
/// this range must be within the bounds of this `MutableSpan`.
///
/// - Returns: A `MutableSpan` over the items within `bounds`
///
/// - Complexity: O(1)
@unsafe
@_alwaysEmitIntoClient
@lifetime(borrow self)
mutating public func extracting(
unchecked bounds: ClosedRange<Index>
) -> Self {
let range = unsafe Range(
_uncheckedBounds: (bounds.lowerBound, bounds.upperBound&+1)
)
return unsafe extracting(unchecked: range)
}
/// Constructs a new span over all the items of this span.
///
/// The returned span's first item is always at offset 0; unlike buffer
/// slices, extracted spans do not share their indices with the
/// span from which they are extracted.
///
/// - Returns: A `MutableSpan` over all the items of this span.
///
/// - Complexity: O(1)
@_alwaysEmitIntoClient
@lifetime(borrow self)
mutating public func extracting(_: UnboundedRange) -> Self {
let newSpan = unsafe Self(_unchecked: _start(), count: _count)
return unsafe _overrideLifetime(newSpan, mutating: &self)
}
}
// MARK: prefixes and suffixes
@available(SwiftStdlib 6.2, *)
extension MutableSpan where Element: ~Copyable {
/// Returns a span containing the initial elements of this span,
/// up to the specified maximum length.
///
/// If the maximum length exceeds the length of this span,
/// the result contains all the elements.
///
/// The returned span's first item is always at offset 0; unlike buffer
/// slices, extracted spans do not share their indices with the
/// span from which they are extracted.
///
/// - Parameter maxLength: The maximum number of elements to return.
/// `maxLength` must be greater than or equal to zero.
/// - Returns: A span with at most `maxLength` elements.
///
/// - Complexity: O(1)
@_alwaysEmitIntoClient
@lifetime(borrow self)
mutating public func extracting(first maxLength: Int) -> Self {
_precondition(maxLength >= 0, "Can't have a prefix of negative length")
let newCount = min(maxLength, count)
let newSpan = unsafe Self(_unchecked: _pointer, count: newCount)
return unsafe _overrideLifetime(newSpan, mutating: &self)
}
/// Returns a span over all but the given number of trailing elements.
///
/// If the number of elements to drop exceeds the number of elements in
/// the span, the result is an empty span.
///
/// The returned span's first item is always at offset 0; unlike buffer
/// slices, extracted spans do not share their indices with the
/// span from which they are extracted.
///
/// - Parameter k: The number of elements to drop off the end of
/// the span. `k` must be greater than or equal to zero.
/// - Returns: A span leaving off the specified number of elements at the end.
///
/// - Complexity: O(1)
@_alwaysEmitIntoClient
@lifetime(borrow self)
mutating public func extracting(droppingLast k: Int) -> Self {
_precondition(k >= 0, "Can't drop a negative number of elements")
let droppedCount = min(k, count)
let newCount = count &- droppedCount
let newSpan = unsafe Self(_unchecked: _pointer, count: newCount)
return unsafe _overrideLifetime(newSpan, mutating: &self)
}
/// Returns a span containing the final elements of the span,
/// up to the given maximum length.
///
/// If the maximum length exceeds the length of this span,
/// the result contains all the elements.
///
/// The returned span's first item is always at offset 0; unlike buffer
/// slices, extracted spans do not share their indices with the
/// span from which they are extracted.
///
/// - Parameter maxLength: The maximum number of elements to return.
/// `maxLength` must be greater than or equal to zero.
/// - Returns: A span with at most `maxLength` elements.
///
/// - Complexity: O(1)
@_alwaysEmitIntoClient
@lifetime(borrow self)
mutating public func extracting(last maxLength: Int) -> Self {
_precondition(maxLength >= 0, "Can't have a suffix of negative length")
let newCount = min(maxLength, count)
let offset = (count &- newCount) * MemoryLayout<Element>.stride
let newStart = unsafe _pointer?.advanced(by: offset)
let newSpan = unsafe Self(_unchecked: newStart, count: newCount)
return unsafe _overrideLifetime(newSpan, mutating: &self)
}
/// Returns a span over all but the given number of initial elements.
///
/// If the number of elements to drop exceeds the number of elements in
/// the span, the result is an empty span.
///
/// The returned span's first item is always at offset 0; unlike buffer
/// slices, extracted spans do not share their indices with the
/// span from which they are extracted.
///
/// - Parameter k: The number of elements to drop from the beginning of
/// the span. `k` must be greater than or equal to zero.
/// - Returns: A span starting after the specified number of elements.
///
/// - Complexity: O(1)
@_alwaysEmitIntoClient
@lifetime(borrow self)
mutating public func extracting(droppingFirst k: Int) -> Self {
_precondition(k >= 0, "Can't drop a negative number of elements")
let droppedCount = min(k, count)
let offset = droppedCount * MemoryLayout<Element>.stride
let newStart = unsafe _pointer?.advanced(by: offset)
let newCount = count &- droppedCount
let newSpan = unsafe Self(_unchecked: newStart, count: newCount)
return unsafe _overrideLifetime(newSpan, mutating: &self)
}
}