File: UnsafeBufferPointer.swift.gyb

package info (click to toggle)
swiftlang 6.0.3-2
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid, trixie
  • size: 2,519,992 kB
  • sloc: cpp: 9,107,863; ansic: 2,040,022; asm: 1,135,751; python: 296,500; objc: 82,456; f90: 60,502; lisp: 34,951; pascal: 19,946; sh: 18,133; perl: 7,482; ml: 4,937; javascript: 4,117; makefile: 3,840; awk: 3,535; xml: 914; fortran: 619; cs: 573; ruby: 573
file content (1423 lines) | stat: -rw-r--r-- 55,787 bytes parent folder | download
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
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
//===--- UnsafeBufferPointer.swift.gyb ------------------------*- swift -*-===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2024 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
//
//===----------------------------------------------------------------------===//


% for mutable in (True, False):
%  Self = 'UnsafeMutableBufferPointer' if mutable else 'UnsafeBufferPointer'
%  Mutable = 'Mutable' if mutable else ''
/// A nonowning collection interface to a buffer of ${Mutable.lower()}
/// elements stored contiguously in memory.
///
/// You can use an `${Self}` instance in low level operations to eliminate
/// uniqueness checks and, in release mode, bounds checks. Bounds checks are
/// always performed in debug mode.
///
/// ${Self} Semantics
/// =================
///
/// An `${Self}` instance is a view into memory and does not own the memory
/// that it references. Copying a value of type `${Self}` does not copy the
/// instances stored in the underlying memory. However, initializing another
/// collection with an `${Self}` instance copies the instances out of the
/// referenced memory and into the new collection.
@frozen // unsafe-performance
public struct Unsafe${Mutable}BufferPointer<Element: ~Copyable>: Copyable {

  @usableFromInline
  @_preInverseGenerics
  let _position: Unsafe${Mutable}Pointer<Element>?

  /// The number of elements in the buffer.
  ///
  /// If the `baseAddress` of this buffer is `nil`, the count is zero. However,
  /// a buffer can have a `count` of zero even with a non-`nil` base address.
  @_preInverseGenerics
  public let count: Int

  // This works around _debugPrecondition() impacting the performance of
  // optimized code. (rdar://72246338)
  @_alwaysEmitIntoClient
  internal init(
    @_nonEphemeral _uncheckedStart start: Unsafe${Mutable}Pointer<Element>?,
    count: Int
  ) {
    _position = start
    self.count = count
  }

  /// Creates a new buffer pointer over the specified number of contiguous
  /// instances beginning at the given pointer.
  ///
  /// - Parameters:
  ///   - start: A pointer to the start of the buffer, or `nil`. If `start` is
  ///     `nil`, `count` must be zero. However, `count` may be zero even for a
  ///     non-`nil` `start`. The pointer passed as `start` must be aligned to
  ///     `MemoryLayout<Element>.alignment`.
  ///   - count: The number of instances in the buffer. `count` must not be
  ///     negative.
  @inlinable // unsafe-performance
  @_preInverseGenerics
  public init(
    @_nonEphemeral start: Unsafe${Mutable}Pointer<Element>?, count: Int
  ) {
    _debugPrecondition(
      count >= 0, "Unsafe${Mutable}BufferPointer with negative count")
    _debugPrecondition(
      count == 0 || start != nil,
      "Unsafe${Mutable}BufferPointer has a nil start and nonzero count")
    self.init(_uncheckedStart: start, count: _assumeNonNegative(count))
  }

  @inlinable // unsafe-performance
  @_preInverseGenerics
  public init(_empty: ()) {
    _position = nil
    count = 0
  }

% if Mutable:
  /// Creates a mutable typed buffer pointer referencing the same memory as the 
  /// given immutable buffer pointer.
  ///
  /// - Parameter other: The immutable buffer pointer to convert.
  @inlinable // unsafe-performance
  @_preInverseGenerics
  public init(mutating other: UnsafeBufferPointer<Element>) {
    _position = UnsafeMutablePointer<Element>(mutating: other._position)
    count = other.count
  }
% else:
  /// Creates an immutable typed buffer pointer referencing the same memory as the 
  /// given mutable buffer pointer.
  ///
  /// - Parameter other: The mutable buffer pointer to convert.
  @inlinable // unsafe-performance
  @_preInverseGenerics
  public init(_ other: UnsafeMutableBufferPointer<Element>) {
    _position = UnsafePointer<Element>(other._position)
    count = other.count
  }
% end
}

@available(*, unavailable)
extension Unsafe${Mutable}BufferPointer: Sendable where Element: ~Copyable {}

extension Unsafe${Mutable}BufferPointer where Element: ~Copyable {
  /// A pointer to the first element of the buffer.
  ///
  /// If the `baseAddress` of this buffer is `nil`, the count is zero. However,
  /// a buffer can have a `count` of zero even with a non-`nil` base address.
  @inlinable
  @_preInverseGenerics
  public var baseAddress: Unsafe${Mutable}Pointer<Element>? {
    _position
  }
}

%if not mutable:
extension UnsafeBufferPointer {
  /// An iterator for the elements in the buffer referenced by an
  /// `UnsafeBufferPointer` or `UnsafeMutableBufferPointer` instance.
  @frozen // unsafe-performance
  public struct Iterator {
    @usableFromInline
    internal var _position, _end: UnsafePointer<Element>?

    @inlinable // unsafe-performance
    public init(
      _position: UnsafePointer<Element>?,
      _end: UnsafePointer<Element>?
    ) {
        self._position = _position
        self._end = _end
    }
  }
}

@available(*, unavailable)
extension UnsafeBufferPointer.Iterator: Sendable {}

extension UnsafeBufferPointer.Iterator: IteratorProtocol {
  /// Advances to the next element and returns it, or `nil` if no next element
  /// exists.
  ///
  /// Once `nil` has been returned, all subsequent calls return `nil`.
  @inlinable // unsafe-performance
  public mutating func next() -> Element? {
    guard let start = _position else {
      return nil
    }
    _internalInvariant(_end != nil, "inconsistent _position, _end pointers")

    if start == _end._unsafelyUnwrappedUnchecked { return nil }

    let result = start.pointee
    _position  = start + 1
    return result
  }
}
%else:
extension UnsafeMutableBufferPointer {
  public typealias Iterator = UnsafeBufferPointer<Element>.Iterator
}
%end

extension Unsafe${Mutable}BufferPointer: Sequence {
  /// Returns an iterator over the elements of this buffer.
  ///
  /// - Returns: An iterator over the elements of this buffer.
  @inlinable // unsafe-performance
  public func makeIterator() -> Iterator {
    guard let start = _position else {
      return Iterator(_position: nil, _end: nil)
    }
    return Iterator(_position: start, _end: start + count)
  }

  /// Initializes the memory at `destination.baseAddress` with elements of
  /// `self`, stopping when either `self` or `destination` is exhausted.
  ///
  /// - Returns: an iterator over any remaining elements of `self` and the
  ///   number of elements initialized.
  @inlinable // unsafe-performance
  public func _copyContents(
    initializing destination: UnsafeMutableBufferPointer<Element>
  ) -> (Iterator, UnsafeMutableBufferPointer<Element>.Index) {
    guard !isEmpty && !destination.isEmpty else { return (makeIterator(), 0) }
    let s = self.baseAddress._unsafelyUnwrappedUnchecked
    let d = destination.baseAddress._unsafelyUnwrappedUnchecked
    let n = Swift.min(destination.count, self.count)
    d.initialize(from: s, count: n)
    return (Iterator(_position: s + n, _end: s + count), n)
  }

  @inlinable
  public func withContiguousStorageIfAvailable<R>(
    _ body: (UnsafeBufferPointer<Element>) throws -> R
  ) rethrows -> R? {
%if Mutable:
    return try body(UnsafeBufferPointer(self))
%else:
    return try body(self)
%end
  }
}

extension Unsafe${Mutable}BufferPointer where Element: ~Copyable {
  public typealias Index = Int

  /// A Boolean value indicating whether the buffer is empty.
  ///
  /// - Complexity: O(1)
  @_alwaysEmitIntoClient
  @_preInverseGenerics
  public var isEmpty: Bool { count == 0 }

  /// The index of the first element in a nonempty buffer.
  ///
  /// The `startIndex` property of an `Unsafe${Mutable}BufferPointer` instance
  /// is always zero.
  @inlinable
  @_preInverseGenerics
  public var startIndex: Int { 0 }

  /// The "past the end" position---that is, the position one greater than the
  /// last valid subscript argument.
  ///
  /// The `endIndex` property of an `Unsafe${Mutable}BufferPointer` instance is
  /// always identical to `count`.
  @inlinable
  @_preInverseGenerics
  public var endIndex: Int { count }

  @inlinable
  @_preInverseGenerics
  public func index(after i: Int) -> Int {
    // NOTE: this is a manual specialization of index movement for a Strideable
    // index that is required for UnsafeBufferPointer performance. The
    // optimizer is not capable of creating partial specializations yet.
    // NOTE: Range checks are not performed here, because it is done later by
    // the subscript function.
    // NOTE: Wrapping math because we allow unsafe buffer pointers not to verify
    // index preconditions in release builds. Our (optimistic) assumption is
    // that the caller is already ensuring that indices are valid, so we can
    // elide the usual checks to help the optimizer generate better code.
    // However, we still check for overflow in debug mode.
    let result = i.addingReportingOverflow(1)
    _debugPrecondition(!result.overflow)
    return result.partialValue
  }

  @inlinable
  @_preInverseGenerics
  public func formIndex(after i: inout Int) {
    // NOTE: this is a manual specialization of index movement for a Strideable
    // index that is required for UnsafeBufferPointer performance. The
    // optimizer is not capable of creating partial specializations yet.
    // NOTE: Range checks are not performed here, because it is done later by
    // the subscript function.
    // See note on wrapping arithmetic in `index(after:)` above.
    let result = i.addingReportingOverflow(1)
    _debugPrecondition(!result.overflow)
    i = result.partialValue
  }

  @inlinable
  @_preInverseGenerics
  public func index(before i: Int) -> Int {
    // NOTE: this is a manual specialization of index movement for a Strideable
    // index that is required for UnsafeBufferPointer performance. The
    // optimizer is not capable of creating partial specializations yet.
    // NOTE: Range checks are not performed here, because it is done later by
    // the subscript function.
    // See note on wrapping arithmetic in `index(after:)` above.
    let result = i.subtractingReportingOverflow(1)
    _debugPrecondition(!result.overflow)
    return result.partialValue
  }

  @inlinable
  @_preInverseGenerics
  public func formIndex(before i: inout Int) {
    // NOTE: this is a manual specialization of index movement for a Strideable
    // index that is required for UnsafeBufferPointer performance. The
    // optimizer is not capable of creating partial specializations yet.
    // NOTE: Range checks are not performed here, because it is done later by
    // the subscript function.
    // See note on wrapping arithmetic in `index(after:)` above.
    let result = i.subtractingReportingOverflow(1)
    _debugPrecondition(!result.overflow)
    i = result.partialValue
  }

  @inlinable
  @_preInverseGenerics
  public func index(_ i: Int, offsetBy n: Int) -> Int {
    // NOTE: this is a manual specialization of index movement for a Strideable
    // index that is required for UnsafeBufferPointer performance. The
    // optimizer is not capable of creating partial specializations yet.
    // NOTE: Range checks are not performed here, because it is done later by
    // the subscript function.
    // See note on wrapping arithmetic in `index(after:)` above.
    let result = i.addingReportingOverflow(n)
    _debugPrecondition(!result.overflow)
    return result.partialValue
  }

  @inlinable
  @_preInverseGenerics
  public func index(_ i: Int, offsetBy n: Int, limitedBy limit: Int) -> Int? {
    // NOTE: this is a manual specialization of index movement for a Strideable
    // index that is required for UnsafeBufferPointer performance. The
    // optimizer is not capable of creating partial specializations yet.
    // NOTE: Range checks are not performed here, because it is done later by
    // the subscript function.
    // See note on wrapping arithmetic in `index(after:)` above.
    let maxOffset = limit.subtractingReportingOverflow(i)
    _debugPrecondition(!maxOffset.overflow)
    let l = maxOffset.partialValue

    if n > 0 ? l >= 0 && l < n : l <= 0 && n < l {
      return nil
    }

    let result = i.addingReportingOverflow(n)
    _debugPrecondition(!result.overflow)
    return result.partialValue
  }

  @inlinable
  @_preInverseGenerics
  public func distance(from start: Int, to end: Int) -> Int {
    // NOTE: this is a manual specialization of index movement for a Strideable
    // index that is required for UnsafeBufferPointer performance. The
    // optimizer is not capable of creating partial specializations yet.
    // NOTE: Range checks are not performed here, because it is done later by
    // the subscript function.
    // NOTE: We allow the subtraction to silently overflow in release builds
    // to eliminate a superfluous check when `start` and `end` are both valid
    // indices. (The operation can only overflow if `start` is negative, which
    // implies it's an invalid index.) `Collection` does not specify what
    // `distance` should return when given an invalid index pair.
    let result = end.subtractingReportingOverflow(start)
    _debugPrecondition(!result.overflow)
    return result.partialValue
  }

  /// Accesses the element at the specified position.
  ///
%if Mutable:
  /// The following example uses the buffer pointer's subscript to access and
  /// modify the elements of a mutable buffer pointing to the contiguous
  /// contents of an array:
  ///
  ///     var numbers = [1, 2, 3, 4, 5]
  ///     numbers.withUnsafeMutableBufferPointer { buffer in
  ///         for i in stride(from: buffer.startIndex, to: buffer.endIndex - 1, by: 2) {
  ///             let x = buffer[i]
  ///             buffer[i + 1] = buffer[i]
  ///             buffer[i] = x
  ///         }
  ///     }
  ///     print(numbers)
  ///     // Prints "[2, 1, 4, 3, 5]"
  ///
  ///     Uninitialized memory cannot be initialized to a nontrivial type
  ///     using this subscript. Instead, use an initializing method, such as
  ///     `initializeElement(at:to:)`
%else:
  /// The following example uses the buffer pointer's subscript to access every
  /// other element of the buffer:
  ///
  ///     let numbers = [1, 2, 3, 4, 5]
  ///     let sum = numbers.withUnsafeBufferPointer { buffer -> Int in
  ///         var result = 0
  ///         for i in stride(from: buffer.startIndex, to: buffer.endIndex, by: 2) {
  ///             result += buffer[i]
  ///         }
  ///         return result
  ///     }
  ///     // 'sum' == 9
%end
  ///
  /// - Note: Bounds checks for `i` are performed only in debug mode.
  ///
  /// - Parameter i: The position of the element to access. `i` must be in the
  ///   range `0..<count`.
  @_alwaysEmitIntoClient
  public subscript(i: Int) -> Element {
    @_transparent
    unsafeAddress {
      _debugPrecondition(i >= 0)
      _debugPrecondition(i < endIndex)
      return UnsafePointer(_position._unsafelyUnwrappedUnchecked) + i
    }
%if Mutable:
    @_transparent
    nonmutating unsafeMutableAddress {
      _debugPrecondition(i >= 0)
      _debugPrecondition(i < endIndex)
      return _position._unsafelyUnwrappedUnchecked + i
    }
%end
  }

  // Skip all debug and runtime checks
  @_alwaysEmitIntoClient
  internal subscript(_unchecked i: Int) -> Element {
    @_transparent
    unsafeAddress {
      _internalInvariant(i >= 0)
      _internalInvariant(i < endIndex)
      return UnsafePointer(_position._unsafelyUnwrappedUnchecked) + i
    }
%if Mutable:
    nonmutating unsafeMutableAddress {
      _internalInvariant(i >= 0)
      _internalInvariant(i < endIndex)
      return _position._unsafelyUnwrappedUnchecked + i
    }
%end
  }

% if mutable:
  /// Exchanges the values at the specified indices of the buffer.
  ///
  /// Both parameters must be valid indices of the buffer, and not
  /// equal to `endIndex`. Passing the same index as both `i` and `j` has no
  /// effect.
  ///
  /// - Parameters:
  ///   - i: The index of the first value to swap.
  ///   - j: The index of the second value to swap.
  @inlinable
  @_preInverseGenerics
  public func swapAt(_ i: Int, _ j: Int) {
    guard i != j else { return }
    _debugPrecondition(i >= 0 && j >= 0)
    _debugPrecondition(i < endIndex && j < endIndex)
    let pi = (_position! + i)
    let pj = (_position! + j)
    let tmp = pi.move()
    pi.moveInitialize(from: pj, count: 1)
    pj.initialize(to: tmp)
  }
% end # mutable

}

extension Unsafe${Mutable}BufferPointer where Element: ~Copyable {
  /// Constructs a standalone buffer pointer over the items within the supplied
  /// range of positions in the memory region addressed by this buffer pointer.
  ///
  /// The returned buffer's first item is always at index 0; unlike buffer
  /// slices, extracted buffers do not generally share their indices with the
  /// original buffer pointer.
  ///
  ///     withUnsafeTemporaryAllocation(of: Int.self, capacity: 5) { buffer in
  ///       buffer.initialize(repeating: 0)
  ///       // buffer contains [0, 0, 0, 0, 0]
  ///       let part = buffer.extracting(2 ..< 4)
  ///       part[0] = 1
  ///       part[1] = 2
  ///       // buffer now contains [0, 0, 1, 2, 0]
  ///     }
  ///
  /// When `Element` is copyable, the `extracting` operation is equivalent to
  /// slicing the buffer then rebasing the resulting buffer slice:
  ///
  ///     let a = buffer.extracting(i ..< j)
  ///     let b = UnsafeBufferPointer(rebasing: buffer[i ..< j])
  ///     // `a` and `b` are now holding the same buffer
  ///
  /// However, unlike slicing, the `extracting` operation remains available even
  /// if `Element` happens to be noncopyable.
  ///
  /// - Parameter bounds: A valid range of indices within this buffer.
  /// - Returns: A new buffer pointer over the items at `bounds`.
  @_alwaysEmitIntoClient
  public func extracting(_ bounds: Range<Int>) -> Self {
    _precondition(bounds.lowerBound >= 0 && bounds.upperBound <= count,
      "Index out of range")
    guard let start = self.baseAddress else {
      return Self(start: nil, count: 0)
    }
    return Self(start: start + bounds.lowerBound, count: bounds.count)
  }

  /// Constructs a standalone buffer pointer over the items within the supplied
  /// range of positions in the memory region addressed by this buffer pointer.
  ///
  /// The returned buffer's first item is always at index 0; unlike buffer
  /// slices, extracted buffers do not generally share their indices with the
  /// original buffer pointer.
  ///
  ///     withUnsafeTemporaryAllocation(of: Int.self, capacity: 5) { buffer in
  ///       buffer.initialize(repeating: 0)
  ///       // buffer contains [0, 0, 0, 0, 0]
  ///       let part = buffer.extracting(2...)
  ///       part[0] = 1
  ///       part[1] = 2
  ///       // buffer now contains [0, 0, 1, 2, 0]
  ///     }
  ///
  /// When `Element` is copyable, the `extracting` operation is equivalent to
  /// slicing the buffer then rebasing the resulting buffer slice:
  ///
  ///     let a = buffer.extracting(i ..< j)
  ///     let b = UnsafeBufferPointer(rebasing: buffer[i ..< j])
  ///     // `a` and `b` are now holding the same buffer
  ///
  /// However, unlike slicing, the `extracting` operation remains available even
  /// if `Element` happens to be noncopyable.
  ///
  /// - Parameter bounds: A valid range of indices within this buffer.
  /// - Returns: A new buffer pointer over the items at `bounds`.
  @_alwaysEmitIntoClient
  public func extracting(_ bounds: some RangeExpression<Int>) -> Self {
    extracting(bounds.relative(to: Range(uncheckedBounds: (0, count))))
  }

  /// Extracts and returns a copy of the entire buffer.
  ///
  /// When `Element` is copyable, the `extracting` operation is equivalent to
  /// slicing the buffer then rebasing the resulting buffer slice:
  ///
  ///     let a = buffer
  ///     let b = buffer.extracting(...)
  ///     let c = UnsafeBufferPointer(rebasing: buffer[...])
  ///     // `a`, `b` and `c` are now all referring to the same buffer
  ///
  /// Note that unlike slicing, the `extracting` operation remains available
  /// even if `Element` happens to be noncopyable.
  //
  /// - Returns: The same buffer as `self`.
  @_alwaysEmitIntoClient
  public func extracting(_ bounds: UnboundedRange) -> Self {
    self
  }
}

@_disallowFeatureSuppression(NoncopyableGenerics)
extension Unsafe${Mutable}BufferPointer {
  /// Accesses the element at the specified position.
  ///
%if Mutable:
  /// The following example uses the buffer pointer's subscript to access and
  /// modify the elements of a mutable buffer pointing to the contiguous
  /// contents of an array:
  ///
  ///     var numbers = [1, 2, 3, 4, 5]
  ///     numbers.withUnsafeMutableBufferPointer { buffer in
  ///         for i in stride(from: buffer.startIndex, to: buffer.endIndex - 1, by: 2) {
  ///             let x = buffer[i]
  ///             buffer[i + 1] = buffer[i]
  ///             buffer[i] = x
  ///         }
  ///     }
  ///     print(numbers)
  ///     // Prints "[2, 1, 4, 3, 5]"
  ///
  ///     Uninitialized memory cannot be initialized to a nontrivial type
  ///     using this subscript. Instead, use an initializing method, such as
  ///     `initializeElement(at:to:)`
%else:
  /// The following example uses the buffer pointer's subscript to access every
  /// other element of the buffer:
  ///
  ///     let numbers = [1, 2, 3, 4, 5]
  ///     let sum = numbers.withUnsafeBufferPointer { buffer -> Int in
  ///         var result = 0
  ///         for i in stride(from: buffer.startIndex, to: buffer.endIndex, by: 2) {
  ///             result += buffer[i]
  ///         }
  ///         return result
  ///     }
  ///     // 'sum' == 9
%end
  ///
  /// - Note: Bounds checks for `i` are performed only in debug mode.
  ///
  /// - Parameter i: The position of the element to access. `i` must be in the
  ///   range `0..<count`.
  @inlinable
  public subscript(i: Int) -> Element {
    // Note: This is the original, copyable subscript.
    // It is still used to fulfill the collection conformance requirements,
    // and to maintain full ABI parity with pre-6.0 Swifts.
    @_transparent
    get {
      _debugPrecondition(i >= 0)
      _debugPrecondition(i < endIndex)
      return _position._unsafelyUnwrappedUnchecked[i]
    }
%if Mutable:
    @_transparent
    nonmutating _modify {
      _debugPrecondition(i >= 0)
      _debugPrecondition(i < endIndex)
      yield &_position._unsafelyUnwrappedUnchecked[i]
    }
%end
  }

  @_spi(SwiftStdlibLegacyABI) @available(swift, obsoleted: 1)
  @usableFromInline
  internal subscript(_unchecked i: Int) -> Element {
    get {
      _internalInvariant(i >= 0)
      _internalInvariant(i < endIndex)
      return _position._unsafelyUnwrappedUnchecked[i]
    }
%if Mutable:
    nonmutating _modify {
      _internalInvariant(i >= 0)
      _internalInvariant(i < endIndex)
      yield &_position._unsafelyUnwrappedUnchecked[i]
    }
%end
  }
}

extension Unsafe${Mutable}BufferPointer:
  Collection,
%if Mutable:
  MutableCollection,
%end
  BidirectionalCollection,
  RandomAccessCollection
{
  public typealias Indices = Range<Int>
  public typealias SubSequence = Slice<Unsafe${Mutable}BufferPointer<Element>>

  @inlinable // unsafe-performance
  public func _failEarlyRangeCheck(_ index: Int, bounds: Range<Int>) {
    // NOTE: In release mode, this method is a no-op for performance reasons.
    _debugPrecondition(index >= bounds.lowerBound)
    _debugPrecondition(index < bounds.upperBound)
  }

  @inlinable // unsafe-performance
  public func _failEarlyRangeCheck(_ range: Range<Int>, bounds: Range<Int>) {
    // NOTE: In release mode, this method is a no-op for performance reasons.
    _debugPrecondition(range.lowerBound >= bounds.lowerBound)
    _debugPrecondition(range.upperBound <= bounds.upperBound)
  }

  @inlinable // unsafe-performance
  public var indices: Indices {
    // Not checked because init forbids negative count.
    return Indices(uncheckedBounds: (startIndex, endIndex))
  }

  /// Accesses a contiguous subrange of the buffer's elements.
  ///
  /// The accessed slice uses the same indices for the same elements as the
  /// original buffer uses. Always use the slice's `startIndex` property
  /// instead of assuming that its indices start at a particular value.
  ///
  /// This example demonstrates getting a slice from a buffer of strings,
  /// finding the index of one of the strings in the slice, and then using that
  /// index in the original buffer.
  ///
%if Mutable:
  ///     var streets = ["Adams", "Bryant", "Channing", "Douglas", "Evarts"]
  ///     streets.withUnsafeMutableBufferPointer { buffer in
  ///         let streetSlice = buffer[2..<buffer.endIndex]
  ///         print(Array(streetSlice))
  ///         // Prints "["Channing", "Douglas", "Evarts"]"
  ///         let index = streetSlice.firstIndex(of: "Evarts")    // 4
  ///         buffer[index!] = "Eustace"
  ///     }
  ///     print(streets.last!)
  ///     // Prints "Eustace"
%else:
  ///     let streets = ["Adams", "Bryant", "Channing", "Douglas", "Evarts"]
  ///     streets.withUnsafeBufferPointer { buffer in
  ///         let streetSlice = buffer[2..<buffer.endIndex]
  ///         print(Array(streetSlice))
  ///         // Prints "["Channing", "Douglas", "Evarts"]"
  ///         let index = streetSlice.firstIndex(of: "Evarts")    // 4
  ///         print(buffer[index!])
  ///         // Prints "Evarts"
  ///     }
%end
  ///
  /// - Note: Bounds checks for `bounds` are performed only in debug mode.
  ///
  /// - Parameter bounds: A range of the buffer's indices. The bounds of
  ///   the range must be valid indices of the buffer.
  @inlinable // unsafe-performance
  public subscript(
    bounds: Range<Int>
  ) -> Slice<Unsafe${Mutable}BufferPointer<Element>> {
    get {
      _debugPrecondition(bounds.lowerBound >= startIndex)
      _debugPrecondition(bounds.upperBound <= endIndex)
      return Slice(
        base: self, bounds: bounds)
    }
%  if Mutable:
    nonmutating set {
      _debugPrecondition(bounds.lowerBound >= startIndex)
      _debugPrecondition(bounds.upperBound <= endIndex)
      _debugPrecondition(bounds.count == newValue.count)

      // FIXME: swift-3-indexing-model: tests.
      if !newValue.isEmpty {
        (_position! + bounds.lowerBound).update(
          from: newValue.base._position! + newValue.startIndex,
          count: newValue.count)
      }
    }
%  end
  }

%  if Mutable:
  @inlinable
  @available(*, deprecated, renamed: "withContiguousMutableStorageIfAvailable")
  public mutating func _withUnsafeMutableBufferPointerIfSupported<R>(
    _ body: (inout UnsafeMutableBufferPointer<Element>) throws -> R
  ) rethrows -> R? {
    return try body(&self)
  }

  @inlinable
  public mutating func withContiguousMutableStorageIfAvailable<R>(
    _ body: (inout UnsafeMutableBufferPointer<Element>) throws -> R
  ) rethrows -> R? {
    let (oldBase, oldCount) = (self.baseAddress, self.count)
    defer {
      _debugPrecondition((oldBase, oldCount) == (self.baseAddress, self.count),
      "UnsafeMutableBufferPointer.withContiguousMutableStorageIfAvailable: replacing the buffer is not allowed")
    }
    return try body(&self)
  }
%  end
}

extension Unsafe${Mutable}BufferPointer {
%  if not Mutable:
  /// Creates a buffer over the same memory as the given buffer slice.
  ///
  /// The new buffer represents the same region of memory as `slice`, but is
  /// indexed starting at zero instead of sharing indices with the original
  /// buffer. For example:
  ///
  ///     let buffer = returnsABuffer()
  ///     let n = 5
  ///     let slice = buffer[n...]
  ///     let rebased = UnsafeBufferPointer(rebasing: slice)
  ///
  /// After rebasing `slice` as the `rebased` buffer, the following are true:
  ///
  /// - `rebased.startIndex == 0`
  /// - `rebased[0] == slice[n]`
  /// - `rebased[0] == buffer[n]`
  /// - `rebased.count == slice.count`
  ///
  /// - Parameter slice: The buffer slice to rebase.
  @inlinable // unsafe-performance
  public init(rebasing slice: Slice<UnsafeBufferPointer<Element>>) {
    // NOTE: `Slice` does not guarantee that its start/end indices are valid
    // in `base` -- it merely ensures that `startIndex <= endIndex`.
    // We need manually check that we aren't given an invalid slice,
    // or the resulting collection would allow access that was
    // out-of-bounds with respect to the original base buffer.
    // We only do this in debug builds to prevent a measurable performance
    // degradation wrt passing around pointers not wrapped in a BufferPointer
    // construct.
    _debugPrecondition(
      slice.startIndex >= 0 && slice.endIndex <= slice.base.count,
      "Invalid slice")
    let base = slice.base.baseAddress?.advanced(by: slice.startIndex)
    let count = slice.endIndex &- slice.startIndex
    self.init(start: base, count: count)
  }

%  end

  /// Creates a buffer over the same memory as the given buffer slice.
  ///
  /// The new buffer represents the same region of memory as `slice`, but is
  /// indexed starting at zero instead of sharing indices with the original
  /// buffer. For example:
  ///
  ///     let buffer = returnsABuffer()
  ///     let n = 5
  ///     let slice = buffer[n...]
  ///     let rebased = Unsafe${Mutable}BufferPointer(rebasing: slice)
  ///
  /// After rebasing `slice` as the `rebased` buffer, the following are true:
  ///
  /// - `rebased.startIndex == 0`
  /// - `rebased[0] == slice[n]`
  /// - `rebased[0] == buffer[n]`
  /// - `rebased.count == slice.count`
  ///
  /// - Parameter slice: The buffer slice to rebase.
  @inlinable // unsafe-performance
  public init(rebasing slice: Slice<UnsafeMutableBufferPointer<Element>>) {
    let base = slice.base.baseAddress?.advanced(by: slice.startIndex)
    let count = slice.endIndex &- slice.startIndex
    self.init(start: base, count: count)
  }
}

extension Unsafe${Mutable}BufferPointer where Element: ~Copyable {
  /// Deallocates the memory block previously allocated at this buffer pointer’s
  /// base address.
  ///
  /// This buffer pointer's `baseAddress` must be `nil` or a pointer to a memory
  /// block previously returned by a Swift allocation method. If `baseAddress`
  /// is `nil`, this function does nothing. Otherwise, the memory must not be
  /// initialized or `Pointee` must be a trivial type. This buffer pointer's
  /// `count` must be equal to the originally allocated size of the memory
  /// block.
  @inlinable
  @_preInverseGenerics
  public func deallocate() {
    _position?.deallocate()
  }
}

% if Mutable:
extension UnsafeMutableBufferPointer where Element: ~Copyable {
  /// Allocates uninitialized memory for the specified number of instances of
  /// type `Element`.
  ///
  /// The resulting buffer references a region of memory that is bound to
  /// `Element` and is `count * MemoryLayout<Element>.stride` bytes in size.
  ///
  /// The following example allocates a buffer that can store four `Int`
  /// instances and then initializes that memory with the elements of a range:
  ///
  ///     let buffer = UnsafeMutableBufferPointer<Int>.allocate(capacity: 4)
  ///     _ = buffer.initialize(from: 1...4)
  ///     print(buffer[2])
  ///     // Prints "3"
  ///
  /// When you allocate memory, always remember to deallocate once you're
  /// finished.
  ///
  ///     buffer.deallocate()
  ///
  /// - Parameter count: The amount of memory to allocate, counted in instances
  ///   of `Element`.
  @inlinable
  @_preInverseGenerics
  public static func allocate(
    capacity count: Int
  ) -> UnsafeMutableBufferPointer<Element> {
    let base  = UnsafeMutablePointer<Element>.allocate(capacity: count)
    return UnsafeMutableBufferPointer(start: base, count: count)
  }
}

extension UnsafeMutableBufferPointer {
  /// Initializes every element in this buffer's memory to a copy of the given
  /// value.
  ///
  /// The destination memory must be uninitialized or the buffer's `Element`
  /// must be a trivial type. After a call to `initialize(repeating:)`, the
  /// entire region of memory referenced by this buffer is initialized.
  ///
  /// - Parameters:
  ///   - repeatedValue: The instance to initialize this buffer's memory with.
  @inlinable // unsafe-performance
  public func initialize(repeating repeatedValue: Element) {
    guard let dstBase = _position else {
      return
    }

    dstBase.initialize(repeating: repeatedValue, count: count)
  }

  /// Initializes the buffer's memory with the given elements.
  ///
  /// Prior to calling the `initialize(from:)` method on a buffer, the memory it
  /// references must be uninitialized, or its `Element` type must be a trivial
  /// type. After the call, the memory referenced by the buffer up to, but not
  /// including, the returned index is initialized. The buffer must contain
  /// sufficient memory to accommodate `source.underestimatedCount`.
  ///
  /// The returned index is the position of the next uninitialized element in
  /// the buffer, which is one past the last element written. If `source`
  /// contains no elements, the returned index is equal to the buffer's
  /// `startIndex`. If `source` contains an equal or greater number of elements
  /// than the buffer can hold, the returned index is equal to the buffer's
  /// `endIndex`.
  ///
  /// - Parameter source: A sequence of elements with which to initialize the
  ///   buffer.
  /// - Returns: An iterator to any elements of `source` that didn't fit in the
  ///   buffer, and an index to the next uninitialized element in the buffer.
  @inlinable // unsafe-performance
  @_silgen_name("$sSr10initialize4from8IteratorQyd___Sitqd___t7ElementQyd__RszSTRd__lF")
  public func initialize<S: Sequence>(
    from source: S
  ) -> (unwritten: S.Iterator, index: Index) where S.Element == Element {
    return source._copyContents(initializing: self)
  }

  /// Initializes the buffer's memory with every element of the source.
  ///
  /// Prior to calling the `initialize(fromContentsOf:)` method on a buffer, the
  /// memory referenced by the buffer must be uninitialized, or the `Element`
  /// type must be a trivial type. After the call, the memory referenced by the
  /// buffer up to, but not including, the returned index is initialized. The
  /// buffer must reference enough memory to accommodate `source.count`
  /// elements.
  ///
  /// The returned index is the position of the next uninitialized element in
  /// the buffer, one past the index of the last element written. If `source`
  /// contains no elements, the returned index is equal to the buffer's
  /// `startIndex`. If `source` contains as many elements as the buffer can
  /// hold, the returned index is equal to the buffer's `endIndex`.
  ///
  /// - Precondition: `self.count` >= `source.count`
  ///
  /// - Note: The memory regions referenced by `source` and this buffer
  ///     must not overlap.
  ///
  /// - Parameter source: A collection of elements to be used to
  ///     initialize the buffer's storage.
  /// - Returns: The index one past the last element of the buffer initialized
  ///     by this function.
  @_alwaysEmitIntoClient
  public func initialize(
    fromContentsOf source: some Collection<Element>
  ) -> Index {
    let count = source.withContiguousStorageIfAvailable {
      guard let sourceAddress = $0.baseAddress, !$0.isEmpty else {
        return 0
      }
      _precondition(
        $0.count <= self.count,
        "buffer cannot contain every element from source."
      )
      baseAddress?.initialize(from: sourceAddress, count: $0.count)
      return $0.count
    }
    if let count {
      return startIndex.advanced(by: count)
    }

    var (iterator, copied) = source._copyContents(initializing: self)
    _precondition(
      iterator.next() == nil,
      "buffer cannot contain every element from source."
    )
    return startIndex.advanced(by: copied)
  }
}

extension UnsafeMutableBufferPointer {
  /// Updates every element of this buffer's initialized memory.
  ///
  /// The buffer’s memory must be initialized or its `Element` type
  /// must be a trivial type.
  ///
  /// - Note: All buffer elements must already be initialized.
  ///
  /// - Parameters:
  ///   - repeatedValue: The value used when updating this pointer's memory.
  @inlinable // unsafe-performance
  @_silgen_name("$sSr6assign9repeatingyx_tF")
  public func update(repeating repeatedValue: Element) {
    guard let dstBase = _position else {
      return
    }

    dstBase.update(repeating: repeatedValue, count: count)
  }

  @_alwaysEmitIntoClient
  @available(*, deprecated, renamed: "update(repeating:)")
  @_silgen_name("_swift_se0370_UnsafeMutableBufferPointer_assign_repeating")
  public func assign(repeating repeatedValue: Element) {
    update(repeating: repeatedValue)
  }
}

extension UnsafeMutableBufferPointer {
  /// Updates the buffer's initialized memory with the given elements.
  ///
  /// The buffer’s memory must be initialized or its `Element` type
  /// must be a trivial type.
  ///
  /// - Parameter source: A sequence of elements to be used to update
  ///   the buffer's contents.
  /// - Returns: An iterator to any elements of `source` that didn't fit in the
  ///   buffer, and the index one past the last updated element in the buffer.
  @_alwaysEmitIntoClient
  public func update<S: Sequence>(
    from source: S
  ) -> (unwritten: S.Iterator, index: Index) where S.Element == Element {
    var iterator = source.makeIterator()
    guard !self.isEmpty else { return (iterator, startIndex) }
    _internalInvariant(_position != nil)
    var index = startIndex
    while index < endIndex {
      guard let element = iterator.next() else { break }
      _position._unsafelyUnwrappedUnchecked[index] = element
      formIndex(after: &index)
    }
    return (iterator, index)
  }

  /// Updates the buffer's initialized memory with every element of the source.
  ///
  /// Prior to calling the `update(fromContentsOf:)` method on a buffer, the
  /// first `source.count` elements of the buffer's memory must be initialized,
  /// or the buffer's `Element` type must be a trivial type. The buffer must
  /// reference enough initialized memory to accommodate `source.count`
  /// elements.
  ///
  /// The returned index is one past the index of the last element updated. If
  /// `source` contains no elements, the returned index is equal to the buffer's
  /// `startIndex`. If `source` contains as many elements as the buffer can
  /// hold, the returned index is equal to the buffer's `endIndex`.
  ///
  /// - Note: The memory regions referenced by `source` and this buffer
  ///     may overlap.
  ///
  /// - Precondition: `self.count` >= `source.count`
  ///
  /// - Parameter source: A collection of elements to be used to update
  ///   the buffer's contents.
  /// - Returns: An index one past the index of the last element updated.
  @_alwaysEmitIntoClient
  public func update(
    fromContentsOf source: some Collection<Element>
  ) -> Index {
    let count = source.withContiguousStorageIfAvailable {
      guard let sourceAddress = $0.baseAddress else {
        return 0
      }
      _precondition(
        $0.count <= self.count,
        "buffer cannot contain every element from source."
      )
      baseAddress?.update(from: sourceAddress, count: $0.count)
      return $0.count
    }
    if let count {
      return startIndex.advanced(by: count)
    }

    if self.isEmpty {
      _precondition(
        source.isEmpty,
        "buffer cannot contain every element from source."
      )
      return startIndex
    }
    _internalInvariant(_position != nil)
    var iterator = source.makeIterator()
    var index = startIndex
    while let value = iterator.next() {
      guard index < endIndex else {
        _preconditionFailure(
          "buffer cannot contain every element from source."
        )
        break
      }
      _position._unsafelyUnwrappedUnchecked[index] = value
      formIndex(after: &index)
    }
    return index
  }
}

extension UnsafeMutableBufferPointer where Element: ~Copyable {
  /// Moves every element of an initialized source buffer into the uninitialized
  /// memory referenced by this buffer, leaving the source memory uninitialized
  /// and this buffer's memory initialized.
  ///
  /// Prior to calling the `moveInitialize(fromContentsOf:)` method on a buffer,
  /// the memory it references must be uninitialized, or its `Element` type must
  /// be a trivial type. After the call, the memory referenced by the buffer up
  /// to, but not including, the returned index is initialized. The memory
  /// referenced by `source` is uninitialized after the function returns. The
  /// buffer must reference enough memory to accommodate `source.count`
  /// elements.
  ///
  /// The returned index is the position of the next uninitialized element in
  /// the buffer, one past the index of the last element written. If `source`
  /// contains no elements, the returned index is equal to the buffer's
  /// `startIndex`. If `source` contains as many elements as the buffer can
  /// hold, the returned index is equal to the buffer's `endIndex`.
  ///
  /// - Precondition: `self.count` >= `source.count`
  ///
  /// - Note: The memory regions referenced by `source` and this buffer
  ///     may overlap.
  ///
  /// - Parameter source: A buffer containing the values to copy. The memory
  ///     region underlying `source` must be initialized.
  /// - Returns: The index one past the last element of the buffer initialized
  ///     by this function.
  @_alwaysEmitIntoClient
  public func moveInitialize(fromContentsOf source: Self) -> Index {
    guard let sourceAddress = source.baseAddress, !source.isEmpty else {
      return startIndex
    }
    _precondition(
      source.count <= self.count,
      "buffer cannot contain every element from source."
    )
    baseAddress?.moveInitialize(from: sourceAddress, count: source.count)
    return startIndex.advanced(by: source.count)
  }
}

extension UnsafeMutableBufferPointer {
  /// Moves every element of an initialized source buffer into the
  /// uninitialized memory referenced by this buffer, leaving the source memory
  /// uninitialized and this buffer's memory initialized.
  ///
  /// Prior to calling the `moveInitialize(fromContentsOf:)` method on a buffer,
  /// the memory it references must be uninitialized,
  /// or its `Element` type must be a trivial type. After the call,
  /// the memory referenced by the buffer up to, but not including,
  /// the returned index is initialized. The memory referenced by
  /// `source` is uninitialized after the function returns.
  /// The buffer must reference enough memory to accommodate
  /// `source.count` elements.
  ///
  /// The returned index is the position of the next uninitialized element
  /// in the buffer, one past the index of the last element written.
  /// If `source` contains no elements, the returned index is equal to the
  /// buffer's `startIndex`. If `source` contains as many elements as the buffer
  /// can hold, the returned index is equal to the buffer's `endIndex`.
  ///
  /// - Precondition: `self.count` >= `source.count`
  ///
  /// - Note: The memory regions referenced by `source` and this buffer
  ///     may overlap.
  ///
  /// - Parameter source: A buffer containing the values to copy. The memory
  ///     region underlying `source` must be initialized.
  /// - Returns: The index one past the last element of the buffer initialized
  ///     by this function.
  @_alwaysEmitIntoClient
  public func moveInitialize(fromContentsOf source: Slice<Self>) -> Index {
    return moveInitialize(fromContentsOf: Self(rebasing: source))
  }
}

extension UnsafeMutableBufferPointer where Element: ~Copyable {
  /// Updates this buffer's initialized memory initialized memory by moving
  /// every element from the source buffer, leaving the source memory
  /// uninitialized.
  ///
  /// Prior to calling the `moveUpdate(fromContentsOf:)` method on a buffer,
  /// the first `source.count` elements of the buffer's memory must be
  /// initialized, or the buffer's `Element` type must be a trivial type.
  /// The memory referenced by `source` is uninitialized after the function
  /// returns. The buffer must reference enough initialized memory
  /// to accommodate `source.count` elements.
  ///
  /// The returned index is one past the index of the last element updated.
  /// If `source` contains no elements, the returned index is equal to the
  /// buffer's `startIndex`. If `source` contains as many elements as the buffer
  /// can hold, the returned index is equal to the buffer's `endIndex`.
  ///
  /// - Note: The memory regions referenced by `source` and this buffer
  ///     must not overlap.
  ///
  /// - Precondition: `self.count` >= `source.count`
  ///
  /// - Parameter source: A buffer containing the values to move.
  ///     The memory region underlying `source` must be initialized.
  /// - Returns: An index one past the index of the last element updated.
  @_alwaysEmitIntoClient
  public func moveUpdate(fromContentsOf source: Self) -> Index {
    guard let sourceAddress = source.baseAddress, !source.isEmpty else {
      return startIndex
    }
    _precondition(
      source.count <= self.count,
      "buffer cannot contain every element from source."
    )
    baseAddress?.moveUpdate(from: sourceAddress, count: source.count)
    return startIndex.advanced(by: source.count)
  }
}

extension UnsafeMutableBufferPointer {
  /// Updates this buffer's initialized memory initialized memory by
  /// moving every element from the source buffer slice,
  /// leaving the source memory uninitialized.
  ///
  /// Prior to calling the `moveUpdate(fromContentsOf:)` method on a buffer,
  /// the first `source.count` elements of the buffer's memory must be
  /// initialized, or the buffer's `Element` type must be a trivial type.
  /// The memory referenced by `source` is uninitialized after the function
  /// returns. The buffer must reference enough initialized memory
  /// to accommodate `source.count` elements.
  ///
  /// The returned index is one past the index of the last element updated.
  /// If `source` contains no elements, the returned index is equal to the
  /// buffer's `startIndex`. If `source` contains as many elements as the buffer
  /// can hold, the returned index is equal to the buffer's `endIndex`.
  ///
  /// - Note: The memory regions referenced by `source` and this buffer
  ///     must not overlap.
  ///
  /// - Precondition: `self.count` >= `source.count`
  ///
  /// - Parameter source: A buffer slice containing the values to move.
  ///     The memory region underlying `source` must be initialized.
  /// - Returns: An index one past the index of the last element updated.
  @_alwaysEmitIntoClient
  public func moveUpdate(fromContentsOf source: Slice<Self>) -> Index {
    return moveUpdate(fromContentsOf: Self(rebasing: source))
  }
}

extension UnsafeMutableBufferPointer where Element: ~Copyable {
  /// Deinitializes every instance in this buffer.
  ///
  /// The region of memory underlying this buffer must be fully initialized.
  /// After calling `deinitialize(count:)`, the memory is uninitialized,
  /// but still bound to the `Element` type.
  ///
  /// - Note: All buffer elements must already be initialized.
  ///
  /// - Returns: A raw buffer to the same range of memory as this buffer.
  ///   The range of memory is still bound to `Element`.
  @discardableResult
  @_alwaysEmitIntoClient
  public func deinitialize() -> UnsafeMutableRawBufferPointer {
    guard let rawValue = baseAddress?._rawValue
      else { return .init(start: nil, count: 0) }
    Builtin.destroyArray(Element.self, rawValue, count._builtinWordValue)
    return .init(start: UnsafeMutableRawPointer(rawValue),
                 count: count*MemoryLayout<Element>.stride)
   }

  /// Initializes the element at `index` to the given value.
  ///
  /// The memory underlying the destination element must be uninitialized,
  /// or `Element` must be a trivial type. After a call to `initialize(to:)`,
  /// the memory underlying this element of the buffer is initialized.
  ///
  /// - Parameters:
  ///   - value: The value used to initialize the buffer element's memory.
  ///   - index: The index of the element to initialize
  @_alwaysEmitIntoClient
  public func initializeElement(at index: Index, to value: consuming Element) {
    _debugPrecondition(startIndex <= index && index < endIndex)
    let p = baseAddress._unsafelyUnwrappedUnchecked.advanced(by: index)
    p.initialize(to: value)
  }

  /// Retrieves and returns the element at `index`, leaving that element's
  /// underlying memory uninitialized.
  ///
  /// The memory underlying the element at `index` must be initialized.
  /// After calling `moveElement(from:)`, the memory underlying this element
  /// of the buffer is uninitialized, and still bound to type `Element`.
  ///
  /// - Parameters:
  ///   - index: The index of the buffer element to retrieve and deinitialize.
  /// - Returns: The instance referenced by this index in this buffer.
  @_alwaysEmitIntoClient
  public func moveElement(from index: Index) -> Element {
    _debugPrecondition(startIndex <= index && index < endIndex)
    return baseAddress._unsafelyUnwrappedUnchecked.advanced(by: index).move()
  }

  /// Deinitializes the memory underlying the element at `index`.
  ///
  /// The memory underlying the element at `index` must be initialized.
  /// After calling `deinitializeElement()`, the memory underlying this element
  /// of the buffer is uninitialized, and still bound to type `Element`.
  ///
  /// - Parameters:
  ///   - index: The index of the buffer element to deinitialize.
  @_alwaysEmitIntoClient
  public func deinitializeElement(at index: Index) {
    _debugPrecondition(startIndex <= index && index < endIndex)
    let p = baseAddress._unsafelyUnwrappedUnchecked.advanced(by: index)
    p.deinitialize(count: 1)
  }
}
% end

extension Unsafe${Mutable}BufferPointer where Element: ~Copyable {
  /// Executes the given closure while temporarily binding the memory referenced
  /// by this buffer to the given type.
  ///
  /// Use this method when you have a buffer of memory bound to one type and
  /// you need to access that memory as a buffer of another type. Accessing
  /// memory as type `T` requires that the memory be bound to that type. A
  /// memory location may only be bound to one type at a time, so accessing
  /// the same memory as an unrelated type without first rebinding the memory
  /// is undefined.
  ///
  /// The number of instances of `T` referenced by the rebound buffer may be
  /// different than the number of instances of `Element` referenced by the
  /// original buffer. The number of instances of `T` will be calculated
  /// at runtime.
  /// 
  /// Any instance of `T` within the re-bound region may be initialized or
  /// uninitialized. Every instance of `Pointee` overlapping with a given
  /// instance of `T` should have the same initialization state (i.e.
  /// initialized or uninitialized.) Accessing a `T` whose underlying
  /// `Pointee` storage is in a mixed initialization state shall be
  /// undefined behaviour.
  ///
  /// Because this buffer's memory is no longer bound to its `Element` type
  /// while the `body` closure executes, do not access memory using the
  /// original buffer from within `body`. Instead, use the `body` closure's
  /// buffer argument to access the values in memory as instances of type
  /// `T`.
  ///
  /// After executing `body`, this method rebinds memory back to the original
  /// `Element` type.
  ///
  /// - Note: Only use this method to rebind the buffer's memory to a type
  ///   that is layout compatible with the currently bound `Element` type.
  ///   The stride of the temporary type (`T`) may be an integer multiple
  ///   or a whole fraction of `Element`'s stride.
  ///   To bind a region of memory to a type that does not match these
  ///   requirements, convert the buffer to a raw buffer and use the
  ///   raw buffer's `withMemoryRebound(to:)` method.
  ///   If `T` and `Element` have different alignments, this buffer's
  ///   `baseAddress` must be aligned with the larger of the two alignments.
  ///
  /// - Parameters:
  ///   - type: The type to temporarily bind the memory referenced by this
  ///     buffer. The type `T` must be layout compatible
  ///     with the pointer's `Element` type.
  ///   - body: A closure that takes a ${Mutable.lower()} typed buffer to the
  ///     same memory as this buffer, only bound to type `T`. The buffer
  ///     parameter contains a number of complete instances of `T` based
  ///     on the capacity of the original buffer and the stride of `Element`.
  ///     The closure's buffer argument is valid only for the duration of the
  ///     closure's execution. If `body` has a return value, that value
  ///     is also used as the return value for the `withMemoryRebound(to:_:)`
  ///     method.
  ///   - buffer: The buffer temporarily bound to `T`.
  /// - Returns: The return value, if any, of the `body` closure parameter.
  @_alwaysEmitIntoClient
  public func withMemoryRebound<T: ~Copyable, E: Error, Result: ~Copyable>(
    to type: T.Type,
    _ body: (_ buffer: ${Self}<T>) throws(E) -> Result
  ) throws(E) -> Result {
    guard let base = _position?._rawValue else {
      return try body(.init(start: nil, count: 0))
    }

    _debugPrecondition(
      Int(bitPattern: .init(base)) & (MemoryLayout<T>.alignment-1) == 0,
      "baseAddress must be a properly aligned pointer for types Element and T"
    )

    let newCount: Int
    if MemoryLayout<T>.stride == MemoryLayout<Element>.stride {
      newCount = count
    } else {
      newCount = count * MemoryLayout<Element>.stride / MemoryLayout<T>.stride
      _debugPrecondition(
        MemoryLayout<T>.stride > MemoryLayout<Element>.stride
        ? MemoryLayout<T>.stride % MemoryLayout<Element>.stride == 0
        : MemoryLayout<Element>.stride % MemoryLayout<T>.stride == 0,
        "Buffer must contain a whole number of Element instances"
      )
    }
    let binding = Builtin.bindMemory(base, newCount._builtinWordValue, T.self)
    defer { Builtin.rebindMemory(base, binding) }
    return try body(.init(start: .init(base), count: newCount))
  }
}

extension Unsafe${Mutable}BufferPointer {
  // This unavailable implementation uses the expected mangled name
  // of `withMemoryRebound<T, Result>(to:_:)`, and provides
  // an entry point for any binary linked against the stdlib binary
  // for Swift 5.6 and older.
  @_spi(SwiftStdlibLegacyABI) @available(swift, obsoleted: 1)
% if Mutable:
  @_silgen_name("$sSr17withMemoryRebound2to_qd_0_qd__m_qd_0_Sryqd__GKXEtKr0_lF")
% else:
  @_silgen_name("$sSR17withMemoryRebound2to_qd_0_qd__m_qd_0_SRyqd__GKXEtKr0_lF")
% end
  @usableFromInline
  internal func _legacy_se0333_withMemoryRebound<T, Result>(
    to type: T.Type,
    _ body: (${Self}<T>) throws -> Result
  ) rethrows -> Result {
    return try withMemoryRebound(to: T.self, body)
  }
}

@_unavailableInEmbedded
@_preInverseGenerics
extension Unsafe${Mutable}BufferPointer: CustomDebugStringConvertible
where Element: ~Copyable {
  /// A textual representation of the buffer, suitable for debugging.
  @_preInverseGenerics
  public var debugDescription: String {
    return "Unsafe${Mutable}BufferPointer"
      + "(start: \(_position.map(String.init(describing:)) ?? "nil"), count: \(count))"
  }
}
%end

// ${'Local Variables'}:
// eval: (read-only-mode 1)
// End: