Press n or j to go to the next uncovered block, b, p or k for the previous block.
| 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 | 271925x 12279x 17x 12262x 203065x 9486x 16x 9470x 613747x 613747x 613747x 613747x 613747x 613747x 377x 375x 764470x 1891099x 1891099x 45145x 1891099x 2504195x 2504195x 188445x 2504195x 1658153x 974608x 974608x 974608x 129351x 129351x 129351x 1059632x 41355x 951249x 86495x 86495x 864754x 864754x 27535x 27535x 27535x 27535x 271279x 271279x 27513x 1650722x 1646598x 125946x 91059x 91059x 247766x 47224x 47224x 47224x 47224x 47224x 86686x 47224x 119x 62x 527276x 44536x 44536x 44437x 1982x 1982x 1951x 15559x 20553x 17542x 18340x 71994x 71994x 71784x 71784x 163953x 163953x 163953x 92096x 1455x 90641x 90641x 71857x 1434x 70423x 70423x 162711x 405701x 405701x 405701x 96580x 96580x 96580x 59x 59x 59x 59x 92x 92x 18x 352x 529x 340x 81313x 81313x 30440x 30440x 30440x 37932x 30166x 44633x 29091x 125946x 125946x 125946x 125946x 112436x 112436x 129798x 1232x 22x 22x 34971x 34971x 12941x 12941x 12941x 20790x 18983x 7472x 7472x 5286x 7593x 7593x 5377x 50436x 35239x 35239x 35239x 6262x 6245x 4515x 4515x 4515x 17x 15126x 15126x 15126x 15126x 15126x 15126x 22963x 22963x 1415x 1415x 15073x 15055x 15055x 15055x 15055x 15055x 22598x 22598x 15002x 30497x 15002x 12460x 12460x 240636x 12460x 42552x 152539x 24257x 24257x 44392x 44392x 43805x 43805x 43785x 43785x 68891x 68891x 68891x 68891x 67098x 67098x 67098x 67076x 67076x 67076x 203032x 203032x 203027x 203023x 203032x 203032x 68873x 17x 202996x 202982x 202974x 271906x 224426x 224426x 271841x 271841x 271841x 271841x 212x 212x 271841x 198x 198x 271841x 22x 4532x 44x | // The skeleton of a sorted set and its views: everything is written once over an ordered tree, an
// optional range of it (low and high bounds, in ascending order) and a direction. The set itself is
// the whole tree in ascending order; a range view limits the range; a reversed view walks it the
// other way. Each operation compares first and changes the tree only after every comparison.
import {
ConcurrentModificationError,
IllegalArgumentError,
NoSuchElementError,
UnsupportedOperationError,
} from '../../errors/errors'
import type { Comparator } from '../../functions/comparators'
import type { Cursor } from '../../interfaces/collection'
import type { SetCollection } from '../../interfaces/set'
import type { BoundOptions, SortedSet, SubSetOptions } from '../../interfaces/sorted-set'
import { SEQUENCED_COLLECTION_BRAND, SORTED_SET_BRAND } from '../brand'
import { describeValue, requireElement } from '../checks'
import {
ABSENT,
type OrderedTree,
predecessor,
successor,
TreeCursor,
TreeIterator,
type TreeNode,
} from '../engines/ordered-tree'
import type { HashFunction } from '../equality'
import { apply } from '../intrinsics'
import { AbstractSet } from './abstract-set'
/**
* One end of a range, in ascending order.
*
* @internal
*/
export interface Bound<E> {
readonly value: E
readonly inclusive: boolean
}
/**
* The bounds of a range in ascending order: low, then high.
*
* @internal
*/
export type Range<E> = readonly [Bound<E> | undefined, Bound<E> | undefined]
/** Reads one inclusive flag: `undefined` gives the default; anything but a boolean is refused. */
function readFlag(flag: unknown, fallback: boolean, where: string, name: string): boolean {
if (flag === undefined) return fallback
if (typeof flag !== 'boolean') {
throw new TypeError(`${where}: ${name} is not a boolean (${describeValue(flag)})`)
}
return flag
}
/** Throws `TypeError` unless `options` is `undefined`, `null` or an object. */
function readOptions(options: unknown, where: string): Record<string, unknown> | undefined {
if (options === undefined || options === null) return undefined
if (typeof options !== 'object') {
throw new TypeError(`${where}: options is not an object (${describeValue(options)})`)
}
return options as Record<string, unknown>
}
/**
* Base class of a sorted set and its views.
*
* Subclasses give the tag, the public owner, `reversed()`, the comparator they report and how a
* new range view is made; the tree, the range and the direction are fixed at construction.
*
* @internal
*/
export abstract class AbstractSortedSet<E> extends AbstractSet<E> implements SortedSet<E> {
protected override readonly iterationMode = 'fail-fast' as const
/** The tree, shared by a set and all its views. */
readonly tree: OrderedTree<E>
/** The low end of the range in ascending order, or `undefined` for none. */
readonly low: Bound<E> | undefined
/** The high end of the range in ascending order, or `undefined` for none. */
readonly high: Bound<E> | undefined
/** Whether this set walks the range from the greatest member down. */
readonly descending: boolean
constructor(
tree: OrderedTree<E>,
low: Bound<E> | undefined,
high: Bound<E> | undefined,
descending: boolean,
) {
super(tree.changes)
this.tree = tree
this.low = low
this.high = high
this.descending = descending
}
abstract comparator(): Comparator<E> | undefined
abstract reversed(): SortedSet<E>
abstract override get owner(): SortedSet<E>
/** Returns a new view of the ascending range from `low` to `high`, in this set's direction. */
protected abstract openRange(low: Bound<E> | undefined, high: Bound<E> | undefined): SortedSet<E>
/** Marks every sequenced collection for `isSequencedCollection`, across loaded copies. */
get [SEQUENCED_COLLECTION_BRAND](): true {
return true
}
/** Marks every sorted set for `isSortedSet`, across loaded copies. */
get [SORTED_SET_BRAND](): true {
return true
}
// ── The range ──
/** Whether a range limits this set (always, for a range view). */
get ranged(): boolean {
return this.low !== undefined || this.high !== undefined
}
/**
* Whether `value` lies below the range. With `lenient`, a value natural order cannot compare
* counts as outside.
*/
private tooLow(value: E, where: string, expected: number, lenient: boolean): boolean {
const low = this.low
if (low === undefined) return false
const c = lenient
? this.tree.compareLenient(value, low.value, where, expected)
: this.tree.compare(value, low.value, where, expected)
return c === ABSENT || c < 0 || (c === 0 && !low.inclusive)
}
/** Whether `value` lies above the range; as `tooLow`. */
private tooHigh(value: E, where: string, expected: number, lenient: boolean): boolean {
const high = this.high
if (high === undefined) return false
const c = lenient
? this.tree.compareLenient(value, high.value, where, expected)
: this.tree.compare(value, high.value, where, expected)
return c === ABSENT || c > 0 || (c === 0 && !high.inclusive)
}
private inRange(value: E, where: string, expected: number, lenient: boolean): boolean {
return (
!this.tooLow(value, where, expected, lenient) &&
!this.tooHigh(value, where, expected, lenient)
)
}
/** The least node in range, or `null`. */
lowestNode(where: string, expected: number): TreeNode<E> | null {
const low = this.low
const node =
low === undefined
? this.tree.first()
: this.tree.nearest(low.value, false, low.inclusive, where, expected)
return node !== null && this.tooHigh(node.value, where, expected, false) ? null : node
}
/** The greatest node in range, or `null`. */
private highestNode(where: string, expected: number): TreeNode<E> | null {
const high = this.high
const node =
high === undefined
? this.tree.last()
: this.tree.nearest(high.value, true, high.inclusive, where, expected)
return node !== null && this.tooLow(node.value, where, expected, false) ? null : node
}
/** The first node in this set's direction, or `null`. */
firstNode(where: string, expected: number): TreeNode<E> | null {
return this.descending ? this.highestNode(where, expected) : this.lowestNode(where, expected)
}
/** The last node in this set's direction, or `null`. */
lastNode(where: string, expected: number): TreeNode<E> | null {
return this.descending ? this.lowestNode(where, expected) : this.highestNode(where, expected)
}
/** The node where a walk in this set's direction stops: the first one past the range, or `null`. */
stopNode(where: string, expected: number): TreeNode<E> | null {
if (this.descending) {
const low = this.low
return low === undefined
? null
: this.tree.nearest(low.value, true, !low.inclusive, where, expected)
}
const high = this.high
return high === undefined
? null
: this.tree.nearest(high.value, false, !high.inclusive, where, expected)
}
/** Every node in range, in this set's direction. */
nodes(where: string, expected: number): TreeNode<E>[] {
const out: TreeNode<E>[] = []
const stop = this.stopNode(where, expected)
let node = this.firstNode(where, expected)
while (node !== null && node !== stop) {
out.push(node)
node = this.descending ? predecessor(node) : successor(node)
}
return out
}
/**
* The node holding `value`, or `null` when no member in range compares equal to it; in natural
* order a value that cannot be compared is absent.
*/
lookup(value: E, where: string, expected: number): TreeNode<E> | null {
if (!this.inRange(value, where, expected, true)) return null
return this.tree.find(value, where, expected, true)
}
/** In natural order: refuses `null`/`undefined` and stores `-0` as `0`. */
private normalise(element: E, where: string): E {
if (this.tree.order !== undefined) return element
requireElement(element, where)
return (element as unknown) === 0 ? (0 as E) : element
}
// ── Reading ──
get size(): number {
if (!this.ranged) return this.tree.count
const where = `${this.className}.size`
const expected = this.changes.structure
const stop = this.stopNode(where, expected)
let count = 0
for (let node = this.firstNode(where, expected); node !== null && node !== stop; count++) {
node = this.descending ? predecessor(node) : successor(node)
}
return count
}
override isEmpty(): boolean {
if (!this.ranged) return this.tree.count === 0
return this.lowestNode(`${this.className}.isEmpty`, this.changes.structure) === null
}
protected hasMember(element: E, method: string): boolean {
return this.lookup(element, `${this.className}.${method}`, this.changes.structure) !== null
}
getFirst(): E {
const node = this.firstNode(`${this.className}.getFirst`, this.changes.structure)
if (node === null) throw this.empty('getFirst')
return node.value
}
getLast(): E {
const node = this.lastNode(`${this.className}.getLast`, this.changes.structure)
if (node === null) throw this.empty('getLast')
return node.value
}
lower(element: E): E | undefined {
return this.navigate(element, true, false, 'lower')
}
floor(element: E): E | undefined {
return this.navigate(element, true, true, 'floor')
}
ceiling(element: E): E | undefined {
return this.navigate(element, false, true, 'ceiling')
}
higher(element: E): E | undefined {
return this.navigate(element, false, false, 'higher')
}
/**
* The nearest member before (`before`) or after `element` in this set's order, counting an equal
* member when `inclusive`.
*/
private navigate(element: E, before: boolean, inclusive: boolean, method: string): E | undefined {
const where = `${this.className}.${method}`
if (this.tree.order === undefined) requireElement(element, where)
const node = this.nearestNode(element, before, inclusive, where)
return node === null ? undefined : node.value
}
/**
* The node nearest `element` before (`before`) or after it in this set's order, counting an
* equal node when `inclusive`, or `null`. The caller has refused `null`/`undefined` in natural
* order.
*/
nearestNode(element: E, before: boolean, inclusive: boolean, where: string): TreeNode<E> | null {
const expected = this.changes.structure
// In ascending terms: below means towards the least member.
const below = before !== this.descending
let node: TreeNode<E> | null
if (below) {
if (this.tooHigh(element, where, expected, false)) {
node = this.highestNode(where, expected)
} else {
node = this.tree.nearest(element, true, inclusive, where, expected)
if (node !== null && this.tooLow(node.value, where, expected, false)) node = null
}
} else if (this.tooLow(element, where, expected, false)) {
node = this.lowestNode(where, expected)
} else {
node = this.tree.nearest(element, false, inclusive, where, expected)
if (node !== null && this.tooHigh(node.value, where, expected, false)) node = null
}
return node
}
[Symbol.iterator](): IterableIterator<E> {
const where = `${this.className}[Symbol.iterator]().next`
const expected = this.changes.structure
return new TreeIterator(
this.firstNode(where, expected),
this.stopNode(where, expected),
this.descending,
this.changes,
where,
)
}
cursor(): Cursor<E> {
const where = `${this.className}.cursor`
const expected = this.changes.structure
return new TreeCursor(
this.tree,
this.firstNode(where, expected),
this.stopNode(where, expected),
this.descending,
where,
)
}
override forEach(
action: (element: E, same: E, set: SetCollection<E>) => void,
thisArg?: unknown,
): void {
this.requireFunction(action, 'forEach', 'action')
const owner = this.owner
const expected = this.changes.structure
for (const element of this) {
apply(action, thisArg, [element, element, owner])
if (this.changes.structure !== expected) {
throw new ConcurrentModificationError(
`${this.className}.forEach: the collection was changed by the callback`,
)
}
}
}
protected memberHashes(hash: HashFunction): number {
let sum = 0
for (const element of this) sum = (sum + hash(element)) | 0
return sum
}
// ── Adding ──
add(element: E): this {
this.insert(element, `${this.className}.add`)
return this
}
override addAll(elements: Iterable<E>): boolean {
const where = `${this.className}.addAll`
const items = this.readAll(elements, 'addAll')
if (this.tree.order === undefined) {
for (let i = 0; i < items.length; i++) requireElement(items[i], where)
}
let added = false
for (let i = 0; i < items.length; i++) if (this.insert(items[i] as E, where)) added = true
return added
}
private insert(element: E, where: string): boolean {
const value = this.normalise(element, where)
const expected = this.changes.structure
this.requireInRange(value, where, expected)
if (!this.tree.insert(value, where, expected)) return false
this.changes.structural()
return true
}
/** Throws `IllegalArgumentError` when a range limits this set and `value` lies outside it. */
requireInRange(value: E, where: string, expected: number): void {
if (this.ranged && !this.inRange(value, where, expected, false)) {
throw new IllegalArgumentError(
`${where}: ${describeValue(value)} is outside the range of the view`,
)
}
}
addFirst(_element: E): this {
throw this.unsupported('addFirst')
}
addLast(_element: E): this {
throw this.unsupported('addLast')
}
// ── Removing ──
override delete(element: E): boolean {
const node = this.lookup(element, `${this.className}.delete`, this.changes.structure)
if (node === null) return false
this.tree.remove(node)
this.changes.structural()
return true
}
pollFirst(): E | undefined {
return this.take(this.firstNode(`${this.className}.pollFirst`, this.changes.structure))
}
pollLast(): E | undefined {
return this.take(this.lastNode(`${this.className}.pollLast`, this.changes.structure))
}
removeFirst(): E {
const node = this.firstNode(`${this.className}.removeFirst`, this.changes.structure)
if (node === null) throw this.empty('removeFirst')
return this.take(node) as E
}
removeLast(): E {
const node = this.lastNode(`${this.className}.removeLast`, this.changes.structure)
if (node === null) throw this.empty('removeLast')
return this.take(node) as E
}
private take(node: TreeNode<E> | null): E | undefined {
if (node === null) return undefined
this.tree.remove(node)
this.changes.structural()
return node.value
}
override clear(): void {
if (!this.ranged) {
if (this.tree.count === 0) return
this.tree.clear()
this.changes.structural()
return
}
this.removeNodes(this.nodes(`${this.className}.clear`, this.changes.structure))
}
override removeAll(elements: Iterable<E>): boolean {
const where = `${this.className}.removeAll`
const items = this.readAll(elements, 'removeAll')
const expected = this.changes.structure
const doomed: TreeNode<E>[] = []
const seen = new Set<TreeNode<E>>()
for (let i = 0; i < items.length; i++) {
const node = this.lookup(items[i] as E, where, expected)
if (node !== null && !seen.has(node)) {
seen.add(node)
doomed.push(node)
}
}
return this.removeNodes(doomed)
}
override retainAll(elements: Iterable<E>): boolean {
const where = `${this.className}.retainAll`
const items = this.readAll(elements, 'retainAll')
const expected = this.changes.structure
const kept = new Set<TreeNode<E>>()
for (let i = 0; i < items.length; i++) {
const node = this.lookup(items[i] as E, where, expected)
if (node !== null) kept.add(node)
}
const doomed: TreeNode<E>[] = []
for (const node of this.nodes(where, expected)) if (!kept.has(node)) doomed.push(node)
return this.removeNodes(doomed)
}
/** Unlinks the members marked in `flags` (iteration order); no comparisons once found. */
protected override removeMarked(flags: readonly boolean[], method: string): void {
const all = this.nodes(`${this.className}.${method}`, this.changes.structure)
const doomed: TreeNode<E>[] = []
for (let i = 0; i < all.length; i++) if (flags[i] === true) doomed.push(all[i] as TreeNode<E>)
this.removeNodes(doomed)
}
/** Unlinks every node of `doomed` and records one change when there was any. */
private removeNodes(doomed: readonly TreeNode<E>[]): boolean {
if (doomed.length === 0) return false
for (let i = 0; i < doomed.length; i++) this.tree.remove(doomed[i] as TreeNode<E>)
this.changes.structural()
return true
}
// ── Range views ──
subSet(from: E, to: E, options?: SubSetOptions | null): SortedSet<E> {
const range = this.subRange(from, to, options, `${this.className}.subSet`)
return this.openRange(range[0], range[1])
}
headSet(to: E, options?: BoundOptions | null): SortedSet<E> {
const range = this.headRange(to, options, `${this.className}.headSet`)
return this.openRange(range[0], range[1])
}
tailSet(from: E, options?: BoundOptions | null): SortedSet<E> {
const range = this.tailRange(from, options, `${this.className}.tailSet`)
return this.openRange(range[0], range[1])
}
/** Reads the options of `subSet` (or `subMap`) and checks the range from `from` to `to`. */
subRange(from: E, to: E, options: unknown, where: string): Range<E> {
const read = readOptions(options, where)
const fromInclusive = readFlag(
read === undefined ? undefined : read.fromInclusive,
true,
where,
'fromInclusive',
)
const toInclusive = readFlag(
read === undefined ? undefined : read.toInclusive,
false,
where,
'toInclusive',
)
return this.checkRange(
{ value: from, inclusive: fromInclusive },
{ value: to, inclusive: toInclusive },
where,
)
}
/** Reads the options of `headSet` (or `headMap`) and checks the range up to `to`. */
headRange(to: E, options: unknown, where: string): Range<E> {
const read = readOptions(options, where)
const inclusive = readFlag(
read === undefined ? undefined : read.inclusive,
false,
where,
'inclusive',
)
return this.checkRange(undefined, { value: to, inclusive }, where)
}
/** Reads the options of `tailSet` (or `tailMap`) and checks the range from `from`. */
tailRange(from: E, options: unknown, where: string): Range<E> {
const read = readOptions(options, where)
const inclusive = readFlag(
read === undefined ? undefined : read.inclusive,
true,
where,
'inclusive',
)
return this.checkRange({ value: from, inclusive }, undefined, where)
}
/**
* Checks the range from `from` to `to`, given in this set's order: each bound as an element,
* then that `from` is not after `to`, then that the range lies within this one. Returns the
* new range's bounds in ascending order.
*/
private checkRange(
from: Bound<E> | undefined,
to: Bound<E> | undefined,
where: string,
): Range<E> {
const expected = this.changes.structure
if (from !== undefined) this.checkBound(from.value, where, expected)
if (to !== undefined) this.checkBound(to.value, where, expected)
const low = this.descending ? to : from
const high = this.descending ? from : to
if (low !== undefined && high !== undefined) {
if (this.tree.compare(low.value, high.value, where, expected) > 0) {
throw new IllegalArgumentError(
`${where}: from ${describeValue((from as Bound<E>).value)} is after to ${describeValue((to as Bound<E>).value)}`,
)
}
}
if (low !== undefined) this.checkWithin(low, where, expected)
if (high !== undefined) this.checkWithin(high, where, expected)
return [low === undefined ? this.low : low, high === undefined ? this.high : high]
}
/** In natural order, refuses a bound that could not be added as an element. */
private checkBound(value: E, where: string, expected: number): void {
if (this.tree.order !== undefined) return
requireElement(value, where)
this.tree.checkNatural(value, where, expected)
}
/**
* Refuses a new bound outside this set's range: an inclusive bound must be in range; an exclusive
* one may also sit on an end of the range.
*/
private checkWithin(bound: Bound<E>, where: string, expected: number): void {
const low = this.low
const high = this.high
let outside = false
if (low !== undefined) {
const c = this.tree.compare(bound.value, low.value, where, expected)
outside = c < 0 || (c === 0 && bound.inclusive && !low.inclusive)
}
if (!outside && high !== undefined) {
const c = this.tree.compare(bound.value, high.value, where, expected)
outside = c > 0 || (c === 0 && bound.inclusive && !high.inclusive)
}
if (outside) {
throw new IllegalArgumentError(
`${where}: ${describeValue(bound.value)} is outside the range of the view`,
)
}
}
// ── Errors ──
private empty(method: string): NoSuchElementError {
return new NoSuchElementError(`${this.className}.${method}: the set is empty`)
}
private unsupported(method: string): UnsupportedOperationError {
return new UnsupportedOperationError(
`${this.className}.${method}: a sorted set places each member by its order; use add`,
)
}
}
|