File: BitArray%2BRangeReplaceableCollection.swift

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 (551 lines) | stat: -rw-r--r-- 19,811 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
//===----------------------------------------------------------------------===//
//
// This source file is part of the Swift Collections open source project
//
// Copyright (c) 2021 - 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
//
//===----------------------------------------------------------------------===//

#if !COLLECTIONS_SINGLE_MODULE
import InternalCollectionsUtilities
#endif

extension BitArray: RangeReplaceableCollection {}

extension BitArray {
  /// Prepares the bit array to store the specified number of bits.
  ///
  /// If you are adding a known number of elements to an array, use this
  /// method to avoid multiple reallocations.
  ///
  /// - Parameter n: The requested number of bits to store.
  public mutating func reserveCapacity(_ n: Int) {
    let wordCount = _Word.wordCount(forBitCount: UInt(n))
    _storage.reserveCapacity(wordCount)
  }
  
  /// Creates a new, empty bit array.
  ///
  /// - Complexity: O(1)
  public init() {
    self.init(_storage: [], count: 0)
  }

  /// Creates a new bit array containing the specified number of a single,
  /// repeated Boolean value.
  ///
  /// - Parameters:
  ///   - repeatedValue: The Boolean value to repeat.
  ///   - count: The number of times to repeat the value passed in the
  ///     `repeating` parameter. `count` must be zero or greater.
  public init(repeating repeatedValue: Bool, count: Int) {
    let wordCount = _Word.wordCount(forBitCount: UInt(count))
    var storage: [_Word] = .init(
      repeating: repeatedValue ? .allBits : .empty, count: wordCount)
    if repeatedValue, _BitPosition(count).bit != 0 {
      // Clear upper bits of last word.
      storage[wordCount - 1] = _Word(upTo: _BitPosition(count).bit)
    }
    self.init(_storage: storage, count: count)
  }
}

extension BitArray {
  /// Creates a new bit array containing the Boolean values in a sequence.
  ///
  /// - Parameter elements: The sequence of elements for the new collection.
  ///   `elements` must be finite.
  /// - Complexity: O(*count*) where *count* is the number of values in
  ///   `elements`.
  @inlinable
  public init(_ elements: some Sequence<Bool>) {
    defer { _checkInvariants() }
    if let elements = _specialize(elements, for: BitArray.self) {
      self.init(elements)
      return
    }
    if let elements = _specialize(elements, for: BitArray.SubSequence.self) {
      self.init(elements)
      return
    }
    self.init()
    self.reserveCapacity(elements.underestimatedCount)
    self.append(contentsOf: elements)
  }
  
  // Specializations

  /// Creates a new bit array containing the Boolean values in a sequence.
  ///
  /// - Parameter elements: The sequence of elements for the new collection.
  ///   `elements` must be finite.
  /// - Complexity: O(*count*) where *count* is the number of values in
  ///   `elements`.
  @inlinable
  public init(_ elements: BitArray) {
    self = elements
  }

  /// Creates a new bit array containing the Boolean values in a sequence.
  ///
  /// - Parameter elements: The sequence of elements for the new collection.
  ///   `elements` must be finite.
  /// - Complexity: O(*count*) where *count* is the number of values in
  ///   `elements`.
  public init(_ elements: BitArray.SubSequence) {
    let wordCount = _Word.wordCount(forBitCount: UInt(elements.count))
    let storage = Array(repeating: _Word.empty, count: wordCount)
    self.init(_storage: storage, count: elements.count)
    self._copy(from: elements, to: 0)
    _checkInvariants()
  }
}

extension BitArray {
  internal mutating func _prepareForReplaceSubrange(
    _ range: Range<Int>, replacementCount c: Int
  ) {
    precondition(range.lowerBound >= 0 && range.upperBound <= self.count)

    let origCount = self.count
    if range.count < c {
      _extend(by: c - range.count)
    }
  
    _copy(from: range.upperBound ..< origCount, to: range.lowerBound + c)

    if c < range.count {
      _removeLast(range.count - c)
    }
  }

  /// Replaces the specified subrange of bits with the values in the given
  /// collection.
  ///
  /// This method has the effect of removing the specified range of elements
  /// from the collection and inserting the new elements at the same location.
  /// The number of new elements need not match the number of elements being
  /// removed.
  ///
  /// If you pass a zero-length range as the `range` parameter, this method
  /// inserts the elements of `newElements` at `range.startIndex`. Calling
  /// the `insert(contentsOf:at:)` method instead is preferred.
  ///
  /// Likewise, if you pass a zero-length collection as the `newElements`
  /// parameter, this method removes the elements in the given subrange
  /// without replacement. Calling the `removeSubrange(_:)` method instead is
  /// preferred.
  ///
  /// - Parameters:
  ///   - range: The subrange of the collection to replace. The bounds of
  ///     the range must be valid indices of the collection.
  ///   - newElements: The new elements to add to the collection.
  ///
  /// - Complexity: O(*n* + *m*), where *n* is length of this collection and
  ///   *m* is the length of `newElements`. If the call to this method simply
  ///   appends the contents of `newElements` to the collection, this method is
  ///   equivalent to `append(contentsOf:)`.
  public mutating func replaceSubrange(
    _ range: Range<Int>,
    with newElements: __owned some Collection<Bool>
  ) {
    let c = newElements.count
    _prepareForReplaceSubrange(range, replacementCount: c)
    if let newElements = _specialize(newElements, for: BitArray.self) {
      _copy(from: newElements, to: range.lowerBound)
    } else if let newElements = _specialize(
      newElements, for: BitArray.SubSequence.self
    ) {
      _copy(from: newElements, to: range.lowerBound)
    } else {
      _copy(from: newElements, to: range.lowerBound ..< range.lowerBound + c)
    }
    _checkInvariants()
  }
  
  /// Replaces the specified subrange of bits with the values in the given
  /// collection.
  ///
  /// This method has the effect of removing the specified range of elements
  /// from the collection and inserting the new elements at the same location.
  /// The number of new elements need not match the number of elements being
  /// removed.
  ///
  /// If you pass a zero-length range as the `range` parameter, this method
  /// inserts the elements of `newElements` at `range.startIndex`. Calling
  /// the `insert(contentsOf:at:)` method instead is preferred.
  ///
  /// Likewise, if you pass a zero-length collection as the `newElements`
  /// parameter, this method removes the elements in the given subrange
  /// without replacement. Calling the `removeSubrange(_:)` method instead is
  /// preferred.
  ///
  /// - Parameters:
  ///   - range: The subrange of the collection to replace. The bounds of
  ///     the range must be valid indices of the collection.
  ///   - newElements: The new elements to add to the collection.
  ///
  /// - Complexity: O(*n* + *m*), where *n* is length of this collection and
  ///   *m* is the length of `newElements`. If the call to this method simply
  ///   appends the contents of `newElements` to the collection, this method is
  ///   equivalent to `append(contentsOf:)`.
  public mutating func replaceSubrange(
    _ range: Range<Int>,
    with newElements: __owned BitArray
  ) {
    replaceSubrange(range, with: newElements[...])
  }

  /// Replaces the specified subrange of bits with the values in the given
  /// collection.
  ///
  /// This method has the effect of removing the specified range of elements
  /// from the collection and inserting the new elements at the same location.
  /// The number of new elements need not match the number of elements being
  /// removed.
  ///
  /// If you pass a zero-length range as the `range` parameter, this method
  /// inserts the elements of `newElements` at `range.startIndex`. Calling
  /// the `insert(contentsOf:at:)` method instead is preferred.
  ///
  /// Likewise, if you pass a zero-length collection as the `newElements`
  /// parameter, this method removes the elements in the given subrange
  /// without replacement. Calling the `removeSubrange(_:)` method instead is
  /// preferred.
  ///
  /// - Parameters:
  ///   - range: The subrange of the collection to replace. The bounds of
  ///     the range must be valid indices of the collection.
  ///   - newElements: The new elements to add to the collection.
  ///
  /// - Complexity: O(*n* + *m*), where *n* is length of this collection and
  ///   *m* is the length of `newElements`. If the call to this method simply
  ///   appends the contents of `newElements` to the collection, this method is
  ///   equivalent to `append(contentsOf:)`.
  public mutating func replaceSubrange(
    _ range: Range<Int>,
    with newElements: __owned BitArray.SubSequence
  ) {
    _prepareForReplaceSubrange(range, replacementCount: newElements.count)
    _copy(from: newElements, to: range.lowerBound)
    _checkInvariants()
  }
}

extension BitArray {
  /// Adds a new element to the end of the bit array.
  ///
  /// - Parameter newElement: The element to append to the bit array.
  ///
  /// - Complexity: Amortized O(1), averaged over many calls to `append(_:)`
  ///    on the same bit array.
  public mutating func append(_ newElement: Bool) {
    let (word, bit) = _BitPosition(_count).split
    if bit == 0 {
      _storage.append(_Word.empty)
    }
    _count += 1
    if newElement {
      _update { handle in
        handle._mutableWords[word].value |= 1 &<< bit
      }
    }
    _checkInvariants()
  }
  
  /// Adds the elements of a sequence or collection to the end of this
  /// bit array.
  ///
  /// The collection being appended to allocates any additional necessary
  /// storage to hold the new elements.
  ///
  /// - Parameter newElements: The elements to append to the bit array.
  ///
  /// - Complexity: O(*m*), where *m* is the length of `newElements`, if
  ///    `self` is the only copy of this bit array. Otherwise O(`count` + *m*).
  public mutating func append(
    contentsOf newElements: __owned some Sequence<Bool>
  ) {
    if let newElements = _specialize(newElements, for: BitArray.self) {
      self.append(contentsOf: newElements)
      return
    }
    if let newElements = _specialize(
      newElements, for: BitArray.SubSequence.self
    ) {
      self.append(contentsOf: newElements)
      return
    }
    var it = newElements.makeIterator()
    var pos = _BitPosition(_count)
    if pos.bit > 0 {
      let (bits, count) = it._nextChunk(
        maximumCount: UInt(_Word.capacity) - pos.bit)
      guard count > 0 else { return }
      _count += count
      _update { $0._copy(bits: bits, count: count, to: pos) }
      pos.value += count
    }
    while true {
      let (bits, count) = it._nextChunk()
      guard count > 0 else { break }
      assert(pos.bit == 0)
      _storage.append(.empty)
      _count += count
      _update { $0._copy(bits: bits, count: count, to: pos) }
      pos.value += count
    }
    _checkInvariants()
  }
  
  /// Adds the elements of a sequence or collection to the end of this
  /// bit array.
  ///
  /// The collection being appended to allocates any additional necessary
  /// storage to hold the new elements.
  ///
  /// - Parameter newElements: The elements to append to the bit array.
  ///
  /// - Complexity: O(*m*), where *m* is the length of `newElements`, if
  ///    `self` is the only copy of this bit array. Otherwise O(`count` + *m*).
  public mutating func append(contentsOf newElements: BitArray) {
    _extend(by: newElements.count)
    _copy(from: newElements, to: count - newElements.count)
    _checkInvariants()
  }

  /// Adds the elements of a sequence or collection to the end of this
  /// bit array.
  ///
  /// The collection being appended to allocates any additional necessary
  /// storage to hold the new elements.
  ///
  /// - Parameter newElements: The elements to append to the bit array.
  ///
  /// - Complexity: O(*m*), where *m* is the length of `newElements`, if
  ///    `self` is the only copy of this bit array. Otherwise O(`count` + *m*).
  public mutating func append(contentsOf newElements: BitArray.SubSequence) {
    _extend(by: newElements.count)
    _copy(from: newElements, to: count - newElements.count)
    _checkInvariants()
  }
}

extension BitArray {
  /// Inserts a new element into the bit array at the specified position.
  ///
  /// The new element is inserted before the element currently at the
  /// specified index. If you pass the bit array's `endIndex` as
  /// the `index` parameter, then the new element is appended to the
  /// collection.
  ///
  ///     var bits = [false, true, true, false, true]
  ///     bits.insert(true, at: 3)
  ///     bits.insert(false, at: numbers.endIndex)
  ///
  ///     print(bits)
  ///     // Prints "[false, true, true, true, false, true, false]"
  ///
  /// - Parameter newElement: The new element to insert into the bit array.
  /// - Parameter i: The position at which to insert the new element.
  ///   `index` must be a valid index into the bit array.
  ///
  /// - Complexity: O(`count` - i), if `self` is the only copy of this bit
  ///    array. Otherwise O(`count`).
  public mutating func insert(_ newElement: Bool, at i: Int) {
    if _BitPosition(_count).bit == 0 {
      _storage.append(_Word.empty)
    }
    let c = count
    _count += 1
    _update { handle in
      handle.copy(from: i ..< c, to: i + 1)
      handle[i] = newElement
    }
    _checkInvariants()
  }
  
  /// Inserts the elements of a collection into the bit array at the specified
  /// position.
  ///
  /// The new elements are inserted before the element currently at the
  /// specified index. If you pass the collection's `endIndex` property as the
  /// `index` parameter, the new elements are appended to the collection.
  ///
  /// - Parameter newElements: The new elements to insert into the bit array.
  /// - Parameter i: The position at which to insert the new elements. `index`
  ///   must be a valid index of the collection.
  ///
  /// - Complexity: O(`self.count` + `newElements.count`).
  ///   If `i == endIndex`, this method is equivalent to `append(contentsOf:)`.
  public mutating func insert(
    contentsOf newElements: __owned some Collection<Bool>,
    at i: Int
  ) {
    precondition(i >= 0 && i <= count)
    let c = newElements.count
    guard c > 0 else { return }
    _extend(by: c)
    _copy(from: i ..< count - c, to: i + c)
    
    if let newElements = _specialize(newElements, for: BitArray.self) {
      _copy(from: newElements, to: i)
    } else if let newElements = _specialize(
      newElements, for: BitArray.SubSequence.self
    ) {
      _copy(from: newElements, to: i)
    } else {
      _copy(from: newElements, to: i ..< i + c)
    }

    _checkInvariants()
  }

  /// Inserts the elements of a collection into the bit array at the specified
  /// position.
  ///
  /// The new elements are inserted before the element currently at the
  /// specified index. If you pass the collection's `endIndex` property as the
  /// `index` parameter, the new elements are appended to the collection.
  ///
  /// - Parameter newElements: The new elements to insert into the bit array.
  /// - Parameter i: The position at which to insert the new elements. `index`
  ///   must be a valid index of the collection.
  ///
  /// - Complexity: O(`self.count` + `newElements.count`).
  ///   If `i == endIndex`, this method is equivalent to `append(contentsOf:)`.
  public mutating func insert(
    contentsOf newElements: __owned BitArray,
    at i: Int
  ) {
    insert(contentsOf: newElements[...], at: i)
  }

  /// Inserts the elements of a collection into the bit array at the specified
  /// position.
  ///
  /// The new elements are inserted before the element currently at the
  /// specified index. If you pass the collection's `endIndex` property as the
  /// `index` parameter, the new elements are appended to the collection.
  ///
  /// - Parameter newElements: The new elements to insert into the bit array.
  /// - Parameter i: The position at which to insert the new elements. `index`
  ///   must be a valid index of the collection.
  ///
  /// - Complexity: O(`self.count` + `newElements.count`).
  ///   If `i == endIndex`, this method is equivalent to `append(contentsOf:)`.
  public mutating func insert(
    contentsOf newElements: __owned BitArray.SubSequence,
    at i: Int
  ) {
    let c = newElements.count
    guard c > 0 else { return }
    _extend(by: c)
    _copy(from: i ..< count - c, to: i + c)
    _copy(from: newElements, to: i)
    _checkInvariants()
  }
}

extension BitArray {
  /// Removes and returns the element at the specified position.
  ///
  /// All the elements following the specified position are moved to close the
  /// gap.
  ///
  /// - Parameter i: The position of the element to remove. `index` must be
  ///   a valid index of the collection that is not equal to the collection's
  ///   end index.
  /// - Returns: The removed element.
  ///
  /// - Complexity: O(`count`)
  @discardableResult
  public mutating func remove(at i: Int) -> Bool {
    let result = self[i]
    _copy(from: i + 1 ..< count, to: i)
    _removeLast()
    _checkInvariants()
    return result
  }

  /// Removes the specified subrange of elements from the collection.
  ///
  /// - Parameter range: The subrange of the collection to remove. The bounds
  ///   of the range must be valid indices of the collection.
  ///
  /// - Complexity: O(`count`)
  public mutating func removeSubrange(_ range: Range<Int>) {
    precondition(
      range.lowerBound >= 0 && range.upperBound <= count,
    "Bounds out of range")
    _copy(
      from: Range(uncheckedBounds: (range.upperBound, count)),
      to: range.lowerBound)
    _removeLast(range.count)
    _checkInvariants()
  }
  
  public mutating func _customRemoveLast() -> Bool? {
    precondition(_count > 0)
    let result = self[count - 1]
    _removeLast()
    _checkInvariants()
    return result
  }

  public mutating func _customRemoveLast(_ n: Int) -> Bool {
    precondition(n >= 0 && n <= count)
    _removeLast(n)
    _checkInvariants()
    return true
  }

  /// Removes and returns the first element of the bit array.
  ///
  /// The bit array must not be empty.
  ///
  /// - Returns: The removed element.
  ///
  /// - Complexity: O(`count`)
  @discardableResult
  public mutating func removeFirst() -> Bool {
    precondition(_count > 0)
    let result = self[0]
    _copy(from: 1 ..< count, to: 0)
    _removeLast()
    _checkInvariants()
    return result
  }
  
  /// Removes the specified number of elements from the beginning of the
  /// bit array.
  ///
  /// - Parameter k: The number of elements to remove from the bit array.
  ///   `k` must be greater than or equal to zero and must not exceed the
  ///   number of elements in the bit array.
  ///
  /// - Complexity: O(`count`)
  public mutating func removeFirst(_ k: Int) {
    precondition(k >= 0 && k <= _count)
    _copy(from: k ..< count, to: 0)
    _removeLast(k)
    _checkInvariants()
  }

  /// Removes all elements from the bit array.
  ///
  /// - Parameter keepCapacity: Pass `true` to request that the collection
  ///   avoid releasing its storage. Retaining the collection's storage can
  ///   be a useful optimization when you're planning to grow the collection
  ///   again. The default value is `false`.
  ///
  /// - Complexity: O(`count`)
  public mutating func removeAll(keepingCapacity keepCapacity: Bool = false) {
    _storage.removeAll(keepingCapacity: keepCapacity)
    _count = 0
    _checkInvariants()
  }
}