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
|
//===--- RangeSetRanges.swift ---------------------------------*- swift -*-===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2023 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
//
//===----------------------------------------------------------------------===//
@available(SwiftStdlib 6.0, *)
extension RangeSet {
/// A collection of the ranges that make up a range set.
public struct Ranges {
internal var _storage: ContiguousArray<Range<Bound>>
@usableFromInline
internal init() {
_storage = []
}
@usableFromInline
internal init(_range: Range<Bound>) {
_storage = [_range]
}
@usableFromInline
internal init(_ranges: [Range<Bound>]) {
_storage = ContiguousArray(_ranges)
}
@usableFromInline
internal init(_unorderedRanges: [Range<Bound>]) {
_storage = ContiguousArray(_unorderedRanges)
_storage.sort {
$0.lowerBound < $1.lowerBound
}
var i = 0
while i < _storage.count {
let current = _storage[i]
if i > 0 {
let previous = _storage[i - 1]
if previous.upperBound >= current.lowerBound {
let newUpper = Swift.max(previous.upperBound, current.upperBound)
_storage[i - 1] = previous.lowerBound ..< newUpper
_storage.remove(at: i)
continue
}
}
if current.isEmpty {
_storage.remove(at: i)
} else {
i += 1
}
}
}
}
}
@available(SwiftStdlib 6.0, *)
extension RangeSet.Ranges {
@usableFromInline
internal func _contains(_ bound: Bound) -> Bool {
let i = _storage._partitioningIndex { $0.upperBound > bound }
return i == _storage.endIndex ? false : _storage[i].lowerBound <= bound
}
/// Returns a range indicating the existing ranges that `range` overlaps
/// with.
///
/// For example, if `self` is `[0..<5, 10..<15, 20..<25, 30..<35]`, then:
///
/// - `_indicesOfRange(12..<14) == 1..<2`
/// - `_indicesOfRange(12..<19) == 1..<2`
/// - `_indicesOfRange(17..<19) == 2..<2`
/// - `_indicesOfRange(12..<22) == 1..<3`
@usableFromInline
internal func _indicesOfRange(
_ range: Range<Bound>,
in subranges: ContiguousArray<Range<Bound>>,
includeAdjacent: Bool = true
) -> Range<Int> {
guard subranges.count > 1 else {
if subranges.isEmpty {
return 0 ..< 0
} else {
let subrange = subranges[0]
if range.upperBound < subrange.lowerBound {
return 0 ..< 0
} else if range.lowerBound > subrange.upperBound {
return 1 ..< 1
} else {
return 0 ..< 1
}
}
}
// The beginning index for the position of `range` is the first range
// with an upper bound larger than `range`'s lower bound. The range
// at this position may or may not overlap `range`.
let beginningIndex = subranges._partitioningIndex {
if includeAdjacent {
$0.upperBound >= range.lowerBound
} else {
$0.upperBound > range.lowerBound
}
}
// The ending index for `range` is the first range with a lower bound
// greater than `range`'s upper bound. If this is the same as
// `beginningIndex`, than `range` doesn't overlap any of the existing
// ranges. If this is `ranges.endIndex`, then `range` overlaps the
// rest of the ranges. Otherwise, `range` overlaps one or
// more ranges in the set.
let endingIndex = subranges[beginningIndex...]._partitioningIndex {
if includeAdjacent {
$0.lowerBound > range.upperBound
} else {
$0.lowerBound >= range.upperBound
}
}
return beginningIndex ..< endingIndex
}
// Insert a non-empty range into the storage
@usableFromInline
@discardableResult
internal mutating func _insert(contentsOf range: Range<Bound>) -> Bool {
let indices = _indicesOfRange(range, in: _storage)
if indices.isEmpty {
_storage.insert(range, at: indices.lowerBound)
return true
} else {
let lower = Swift.min(
_storage[indices.lowerBound].lowerBound, range.lowerBound)
let upper = Swift.max(
_storage[indices.upperBound - 1].upperBound, range.upperBound)
let newRange = lower ..< upper
if indices.count == 1 && newRange == _storage[indices.lowerBound] {
return false
}
_storage.replaceSubrange(indices, with: CollectionOfOne(newRange))
return true
}
}
// Remove a non-empty range from the storage
@usableFromInline
internal mutating func _remove(contentsOf range: Range<Bound>) {
let indices = _indicesOfRange(range, in: _storage, includeAdjacent: false)
guard !indices.isEmpty else {
return
}
let overlapsLowerBound =
range.lowerBound > _storage[indices.lowerBound].lowerBound
let overlapsUpperBound =
range.upperBound < _storage[indices.upperBound - 1].upperBound
switch (overlapsLowerBound, overlapsUpperBound) {
case (false, false):
_storage.removeSubrange(indices)
case (false, true):
let newRange =
range.upperBound..<_storage[indices.upperBound - 1].upperBound
_storage.replaceSubrange(indices, with: CollectionOfOne(newRange))
case (true, false):
let newRange =
_storage[indices.lowerBound].lowerBound ..< range.lowerBound
_storage.replaceSubrange(indices, with: CollectionOfOne(newRange))
case (true, true):
_storage.replaceSubrange(indices, with: _Pair(
_storage[indices.lowerBound].lowerBound..<range.lowerBound,
range.upperBound..<_storage[indices.upperBound - 1].upperBound
))
}
}
/// Returns a that represents the ranges of values within the
/// given bounds that aren't represented by this range set.
@usableFromInline
internal func _gaps(boundedBy bounds: Range<Bound>) -> Self {
let indices = _indicesOfRange(bounds, in: _storage)
guard !indices.isEmpty else {
return Self(_range: bounds)
}
var result: [Range<Bound>] = []
var low = bounds.lowerBound
for range in _storage[indices] {
let gapRange = low ..< range.lowerBound
if !gapRange.isEmpty {
result.append(gapRange)
}
low = range.upperBound
}
let finalRange = low ..< bounds.upperBound
if !finalRange.isEmpty {
result.append(finalRange)
}
let resultVal = Self(_ranges: result)
return resultVal
}
@usableFromInline
internal func _intersection(_ other: Self) -> Self {
let left = self._storage
let right = other._storage
var otherRangeIndex = 0
var result: [Range<Bound>] = []
// Considering these two range sets:
//
// self = [0..<5, 9..<14]
// other = [1..<3, 4..<6, 8..<12]
//
// `self.intersection(other)` looks like this, where x's cover the
// ranges in `self`, y's cover the ranges in `other`, and z's cover the
// resulting ranges:
//
// 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
// xxxxxxxxxxxxxxxxxxx__ xxxxxxxxxxxxxxxxxxx__
// yyyyyyy__ yyyyyyy__ yyyyyyyyyyyyyyy__
// zzzzzzz__ zzz__ zzzzzzzzzzz__
//
// The same, but for `other.intersection(self)`:
//
// 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
// xxxxxxx__ xxxxxxx__ xxxxxxxxxxxxxxx__
// yyyyyyyyyyyyyyyyyyy__ yyyyyyyyyyyyyyyyyyy__
// zzzzzzz__ zzz__ zzzzzzzzzzz__
for currentRange in left {
// Search forward in `right` until finding either an overlapping
// range or one that is strictly higher than this range.
while otherRangeIndex < right.endIndex &&
right[otherRangeIndex].upperBound <= currentRange.lowerBound
{
otherRangeIndex += 1
}
// For each range in `right` that overlaps with the current range
// in `left`, append the intersection to the result.
while otherRangeIndex < right.endIndex &&
right[otherRangeIndex].lowerBound < currentRange.upperBound
{
let overlap = right[otherRangeIndex].clamped(to: currentRange)
result.append(overlap)
// If the range in `right` continues past the current range in
// `self`, it could overlap the next range in `self`, so break
// out of examining the current range.
guard
currentRange.upperBound > right[otherRangeIndex].upperBound
else {
break
}
otherRangeIndex += 1
}
}
return Self(_ranges: result)
}
@usableFromInline
internal func _union(_ other: Self) -> Self {
// Empty cases
if other.isEmpty {
return self
} else if self.isEmpty {
return other
}
// Instead of naively inserting the ranges of `other` into `self`,
// which can cause reshuffling with every insertion, this approach
// uses the guarantees that each array of ranges is non-overlapping and in
// increasing order to directly derive the union.
//
// Each range in the resulting range set is found by:
//
// 1. Finding the current lowest bound of the two range sets.
// 2. Searching for the first upper bound that is outside the merged
// boundaries of the two range sets.
// Use temporaries so that we can swap a/b, to simplify the logic below
var a = self._storage
var b = other._storage
var aIndex = a.startIndex
var bIndex = b.startIndex
var result: [Range<Bound>] = []
while aIndex < a.endIndex, bIndex < b.endIndex {
// Make sure that `a` is the source of the lower bound and `b` is the
// potential source for the upper bound.
if b[bIndex].lowerBound < a[aIndex].lowerBound {
swap(&a, &b)
swap(&aIndex, &bIndex)
}
var candidateRange = a[aIndex]
aIndex += 1
// Look for the correct upper bound, which is the first upper bound that
// isn't contained in the next range of the "other" ranges array.
while bIndex < b.endIndex, candidateRange.upperBound >= b[bIndex].lowerBound {
if candidateRange.upperBound >= b[bIndex].upperBound {
// The range `b[bIndex]` is entirely contained by `candidateRange`,
// so we need to advance and look at the next range in `b`.
bIndex += 1
} else {
// The range `b[bIndex]` extends past `candidateRange`, so:
//
// 1. We grow `candidateRange` to the upper bound of `b[bIndex]`
// 2. We swap the two range arrays, so that we're looking for the
// new upper bound in the other array.
candidateRange = candidateRange.lowerBound ..< b[bIndex].upperBound
bIndex += 1
swap(&a, &b)
swap(&aIndex, &bIndex)
}
}
result.append(candidateRange)
}
// Collect any remaining ranges without needing to merge.
if aIndex < a.endIndex {
result.append(contentsOf: a[aIndex...])
} else if bIndex < b.endIndex {
result.append(contentsOf: b[bIndex...])
}
return Self(_ranges: result)
}
}
@available(SwiftStdlib 6.0, *)
extension RangeSet.Ranges: Sequence {
public typealias Element = Range<Bound>
public typealias Iterator = IndexingIterator<Self>
}
@available(SwiftStdlib 6.0, *)
extension RangeSet.Ranges: Collection {
public typealias Index = Int
public typealias Indices = Range<Index>
public typealias SubSequence = Slice<Self>
public var startIndex: Index {
0
}
public var endIndex: Index {
_storage.count
}
public var count: Int {
self.endIndex
}
public subscript(i: Index) -> Element {
_storage[i]
}
}
@available(SwiftStdlib 6.0, *)
extension RangeSet.Ranges: RandomAccessCollection {}
@available(SwiftStdlib 6.0, *)
extension RangeSet.Ranges: Equatable {
public static func == (left: Self, right: Self) -> Bool {
left._storage == right._storage
}
}
@available(SwiftStdlib 6.0, *)
extension RangeSet.Ranges: Hashable where Bound: Hashable {
public func hash(into hasher: inout Hasher) {
hasher.combine(_storage)
}
}
@available(SwiftStdlib 6.0, *)
extension RangeSet.Ranges: Sendable where Bound: Sendable {}
@available(SwiftStdlib 6.0, *)
extension RangeSet.Ranges: CustomStringConvertible {
public var description: String {
_makeCollectionDescription()
}
}
/// A collection of two elements, to avoid heap allocation when calling
/// `replaceSubrange` with just two elements.
internal struct _Pair<Element>: RandomAccessCollection {
internal var pair: (first: Element, second: Element)
internal init(_ first: Element, _ second: Element) {
self.pair = (first, second)
}
internal var startIndex: Int { 0 }
internal var endIndex: Int { 2 }
internal subscript(position: Int) -> Element {
get {
switch position {
case 0: return pair.first
case 1: return pair.second
default: _preconditionFailure("Index is out of range")
}
}
}
}
|