All files / src/internal/views list-views.ts

100% Statements 75/75
100% Branches 26/26
100% Functions 23/23
100% Lines 71/71

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                                                                78904x 78904x 78904x 78904x 78904x       424333x       583058x         5070x 5070x 5070x 27854x 27854x 27854x                     105x                                                   102763x 102763x 102763x 102763x 102763x 102763x       80512x       80429x       312741x 312741x       582986x 76x               236287x 236287x         2390x 2390x       213647x 213647x       21030x 21030x       1951x 1951x 1951x       440x 440x 440x 204x 582x 204x   440x 440x       1610x 1610x 1610x 1610x       280x 280x 280x 280x 280x 189x 280x       790x 790x 790x       75384x 75384x 75384x 75384x 75384x       25177x 25177x 25144x               72x                               1285x 1285x                 966x    
// The live list views: a sub-list (a window `[from, to)`) and a reversed list. Every view reads and
// writes the root list (the one that is not a view) directly, through a span — a span of the
// root's indexes — and a direction, so reads and `set` cost the same however deeply views are
// nested; a change of size also updates each enclosing span, one step per level, in a loop, and
// nothing recurses. Views share the root's change counter, so `revision` and fail-fast checks are
// the root's.
 
import { ConcurrentModificationError } from '../../errors/errors'
import type { List } from '../../interfaces/list'
import { INSPECT, type InspectOptions } from '../output'
import { AbstractList } from '../skeletons/abstract-list'
 
/**
 * A span of the root's indexes that one or more views show. A sub-list has its own span, made
 * inside its source's span (`parent`); a reversed view shares its source's span. The root's own
 * span (`parent === undefined`) always covers the whole root and never goes stale.
 *
 * A structural change made through a span updates its length and expected structure count and
 * those of every span it was made from, in a loop; any other structural change of the root leaves
 * `expected` behind, which makes the span, and every view showing it, stale.
 *
 * @internal
 */
class Span<E> {
  readonly root: AbstractList<E>
  readonly parent: Span<E> | undefined
  /** The root index of the span's first element. */
  readonly start: number
  private ownLength: number
  private expected: number
 
  constructor(root: AbstractList<E>, parent: Span<E> | undefined, start: number, length: number) {
    this.root = root
    this.parent = parent
    this.start = start
    this.ownLength = length
    this.expected = root.changeCounter.structure
  }
 
  get length(): number {
    return this.parent === undefined ? this.root.size : this.ownLength
  }
 
  isStale(): boolean {
    return this.parent !== undefined && this.root.changeCounter.structure !== this.expected
  }
 
  /** Records a structural change of `delta` elements made through this span. */
  changed(delta: number): void {
    const structure = this.root.changeCounter.structure
    let span: Span<E> | undefined = this
    while (span !== undefined && span.parent !== undefined) {
      span.ownLength += delta
      span.expected = structure
      span = span.parent
    }
  }
}
 
/** The names a list's views print with. @internal */
export interface ViewLabels {
  readonly subList: string
  readonly reversed: string
}
 
const DEFAULT_LABELS: ViewLabels = { subList: 'SubList', reversed: 'ReversedList' }
 
/**
 * A live view of another list: a sub-list (`SubList`) or a reversed list (`ReversedList`). Once
 * its span is stale, every method and `size` throw `ConcurrentModificationError`, while
 * `revision`, the tag, the brands and Node's inspect hook still work.
 *
 * @internal
 */
class ListView<E> extends AbstractList<E> {
  private readonly span: Span<E>
  /** Whether index 0 of the view is the last element of the span. */
  private readonly backwards: boolean
  private readonly kind: 'SubList' | 'ReversedList'
  /** The names views print with and start errors with, by kind. */
  private readonly labels: ViewLabels
  /** The list `reversed()` or `subList()` was called on: what `reversed().reversed()` returns. */
  private readonly source: List<E>
 
  constructor(
    span: Span<E>,
    backwards: boolean,
    kind: 'SubList' | 'ReversedList',
    source: List<E>,
    labels: ViewLabels,
  ) {
    super(span.root.changeCounter)
    this.span = span
    this.backwards = backwards
    this.kind = kind
    this.labels = labels
    this.source = source
  }
 
  private get tag(): string {
    return this.kind === 'SubList' ? this.labels.subList : this.labels.reversed
  }
 
  get [Symbol.toStringTag](): string {
    return this.tag
  }
 
  get size(): number {
    this.assertUsable()
    return this.span.length
  }
 
  override assertUsable(): void {
    if (this.span.isStale()) {
      throw new ConcurrentModificationError(
        `${this.tag}: the list it shows was changed other than through this view`,
      )
    }
  }
 
  /** The root index of the view's element `index`. */
  private at(index: number): number {
    const span = this.span
    return this.backwards ? span.start + span.length - 1 - index : span.start + index
  }
 
  /** The root insertion position for the view's position `position`. */
  private position(position: number): number {
    const span = this.span
    return this.backwards ? span.start + span.length - position : span.start + position
  }
 
  getAt(index: number): E {
    this.assertUsable()
    return this.span.root.getAt(this.at(index))
  }
 
  setAt(index: number, element: E): void {
    this.assertUsable()
    this.span.root.setAt(this.at(index), element)
  }
 
  insertAt(index: number, element: E): void {
    this.assertUsable()
    this.span.root.insertAt(this.position(index), element)
    this.span.changed(1)
  }
 
  insertItems(index: number, elements: readonly E[]): void {
    this.assertUsable()
    let items = elements
    if (this.backwards) {
      const reversed: E[] = []
      for (let i = elements.length - 1; i >= 0; i--) reversed.push(elements[i] as E)
      items = reversed
    }
    this.span.root.insertItems(this.position(index), items)
    this.span.changed(elements.length)
  }
 
  removeAtIndex(index: number): E {
    this.assertUsable()
    const element = this.span.root.removeAtIndex(this.at(index))
    this.span.changed(-1)
    return element
  }
 
  removeRange(from: number, to: number): void {
    this.assertUsable()
    const span = this.span
    const start = span.start
    const end = start + span.length
    if (this.backwards) span.root.removeRange(end - to, end - from)
    else span.root.removeRange(start + from, start + to)
    span.changed(from - to)
  }
 
  override markStructural(): void {
    this.assertUsable()
    this.span.root.markStructural()
    this.span.changed(0)
  }
 
  subList(from: number, to: number): List<E> {
    this.checkSubList(from, to)
    const span = this.span
    const start = this.backwards ? span.start + span.length - to : span.start + from
    const inner = new Span(span.root, span, start, to - from)
    return new ListView(inner, this.backwards, 'SubList', this, this.labels)
  }
 
  reversed(): List<E> {
    this.assertUsable()
    if (this.kind === 'ReversedList') return this.source
    return new ListView(this.span, !this.backwards, 'ReversedList', this, this.labels)
  }
 
  override [INSPECT](
    depth: number | null,
    options: InspectOptions,
    inspect: (value: unknown, options: InspectOptions) => string,
  ): string {
    return this.span.isStale() ? `${this.tag} <stale>` : super[INSPECT](depth, options, inspect)
  }
}
 
/**
 * Returns the live view `[from, to)` of `root`, a list that is not a view. The range is already
 * checked.
 *
 * @internal
 */
export function subListOf<E>(
  root: AbstractList<E>,
  from: number,
  to: number,
  labels: ViewLabels = DEFAULT_LABELS,
): List<E> {
  const whole = new Span(root, undefined, 0, 0)
  return new ListView(new Span(root, whole, from, to - from), false, 'SubList', root.owner, labels)
}
 
/**
 * Returns the live reversed view of `root`, a list that is not a view.
 *
 * @internal
 */
export function reversedOf<E>(root: AbstractList<E>, labels: ViewLabels = DEFAULT_LABELS): List<E> {
  return new ListView(new Span(root, undefined, 0, 0), true, 'ReversedList', root.owner, labels)
}