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

100% Statements 108/108
100% Branches 15/15
100% Functions 30/30
100% Lines 89/89

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                          105x 105x                       678x 678x     678x 678x         422558x 422558x 12x 12x 12x         78170x 78170x       344388x 344388x         40143x         1951x 1951x 1951x                         678x 678x       1591x       414940x       678x             42127x 42127x 28x 10x         363x 363x 363x 363x   361x         454570x       40145x 40145x 40145x       469x 469x 469x 469x 469x       333x 333x 5369x 331x 331x       119x 119x 119x 119x 1370x 232x 117x       659x 659x 659x 659x 3482x 654x 654x 654x       29x 29x 29x 29x 29x 27x 27x       10x 10x 10x 10x 10x 112x   8x 8x       356x       7x         193x 193x 193x 1x   177x       99x       94x       111x 111x       110x      
// The list `asList` returns: every list operation over the caller's own array. Changes made through
// the list write to the array; changes made to the array directly show through, and a direct change
// of its length counts as a structural change the next time the list looks, so open iterators,
// cursors and sub-lists fail fast. Elements move with index loops, never the array's own methods.
 
import { ConcurrentModificationError } from '../../errors/errors'
import type { List } from '../../interfaces/list'
import { type HashFunction, hashCodeSymbol } from '../equality'
import { isExtensible, isFrozen } from '../intrinsics'
import type { ChangeCounter } from '../revision'
import { AbstractList } from '../skeletons/abstract-list'
import { reversedOf, subListOf, type ViewLabels } from './list-views'
 
const TAG = 'ArrayListView'
const LABELS: ViewLabels = { subList: TAG, reversed: TAG }
 
/**
 * A change counter that also watches an array's length: reading `revision` or `structure` first
 * compares the length with the last one seen and records a structural change when it differs.
 * Every fail-fast check reads `structure`, so all of them notice a direct `push` or `splice`.
 *
 * @internal
 */
export class ArrayLengthCounter {
  private readonly array: readonly unknown[]
  private seenLength: number
  private revisions = 0
  private structures = 0
 
  constructor(array: readonly unknown[]) {
    this.array = array
    this.seenLength = array.length
  }
 
  /** Records a direct change of the array's length, if there was one. */
  private sync(): void {
    const length = this.array.length
    if (length !== this.seenLength) {
      this.seenLength = length
      this.revisions++
      this.structures++
    }
  }
 
  get revision(): number {
    this.sync()
    return this.revisions
  }
 
  get structure(): number {
    this.sync()
    return this.structures
  }
 
  /** Records a change through the list that replaced an element. */
  replaced(): void {
    this.revisions++
  }
 
  /** Records a change through the list that added or removed elements. */
  structural(): void {
    this.seenLength = this.array.length
    this.revisions++
    this.structures++
  }
}
 
/**
 * A list whose elements are the caller's array.
 *
 * @internal
 */
export class ArrayListView<E> extends AbstractList<E> {
  private readonly items: E[]
 
  constructor(items: E[]) {
    super(new ArrayLengthCounter(items) as unknown as ChangeCounter)
    this.items = items
  }
 
  get [Symbol.toStringTag](): string {
    return TAG
  }
 
  get size(): number {
    return this.items.length
  }
 
  /** Set while a bulk write (`sort`, `replaceAll`) runs after one check, so each step skips it. */
  private checked = false
 
  /**
   * Throws before a write when the array cannot take it. An extensible array is neither sealed nor
   * frozen, so the common case is one O(1) test; the full check runs only for a non-extensible one.
   */
  private writable(method: string, resizes: boolean): void {
    const items = this.items
    if (isExtensible(items) || (this.checked && !resizes)) return
    if (resizes) throw new TypeError(`${TAG}.${method}: the array cannot change its length`)
    if (isFrozen(items)) throw new TypeError(`${TAG}.${method}: the array is frozen`)
  }
 
  /** Runs a bulk write after one check of the array. */
  private bulk<R>(method: string, body: () => R): R {
    this.writable(method, false)
    this.checked = true
    try {
      return body()
    } finally {
      this.checked = false
    }
  }
 
  getAt(index: number): E {
    return this.items[index] as E
  }
 
  setAt(index: number, element: E): void {
    this.writable('set', false)
    this.items[index] = element
    this.changes.replaced()
  }
 
  override add(element: E): this {
    this.writable('add', true)
    const items = this.items
    items[items.length] = element
    this.changes.structural()
    return this
  }
 
  insertAt(index: number, element: E): void {
    this.writable('insert', true)
    const items = this.items
    for (let j = items.length; j > index; j--) items[j] = items[j - 1] as E
    items[index] = element
    this.changes.structural()
  }
 
  insertItems(index: number, elements: readonly E[]): void {
    this.writable('insertAll', true)
    const items = this.items
    const count = elements.length
    const oldLength = items.length
    for (let j = oldLength - 1; j >= index; j--) items[j + count] = items[j] as E
    for (let k = 0; k < count; k++) items[index + k] = elements[k] as E
    this.changes.structural()
  }
 
  removeAtIndex(index: number): E {
    this.writable('removeAt', true)
    const items = this.items
    const element = items[index] as E
    const last = items.length - 1
    for (let j = index; j < last; j++) items[j] = items[j + 1] as E
    items.length = last
    this.changes.structural()
    return element
  }
 
  removeRange(from: number, to: number): void {
    this.writable('clear', true)
    const items = this.items
    const count = to - from
    const length = items.length
    for (let j = to; j < length; j++) items[j - count] = items[j] as E
    items.length = length - count
    this.changes.structural()
  }
 
  protected override removeMarked(flags: readonly boolean[]): void {
    this.writable('removeIf', true)
    const items = this.items
    let kept = 0
    const length = items.length
    for (let i = 0; i < length; i++) {
      if (flags[i] !== true) items[kept++] = items[i] as E
    }
    items.length = kept
    this.changes.structural()
  }
 
  override sort(comparator?: Parameters<AbstractList<E>['sort']>[0]): this {
    return this.bulk('sort', () => super.sort(comparator))
  }
 
  override replaceAll(op: Parameters<AbstractList<E>['replaceAll']>[0]): void {
    this.bulk('replaceAll', () => super.replaceAll(op))
  }
 
  /** Runs `body`, then throws if element code changed the array's length meanwhile. */
  private unchanged<R>(method: string, body: () => R): R {
    const expected = this.changes.structure
    const result = body()
    if (this.changes.structure !== expected) {
      throw new ConcurrentModificationError(`${TAG}.${method}: the array was changed meanwhile`)
    }
    return result
  }
 
  override equals(other: unknown): boolean {
    return this.unchanged('equals', () => super.equals(other))
  }
 
  override [hashCodeSymbol](hash: HashFunction): number {
    return this.unchanged('[hashCodeSymbol]', () => super[hashCodeSymbol](hash))
  }
 
  subList(from: number, to: number): List<E> {
    this.checkSubList(from, to)
    return subListOf(this, from, to, LABELS)
  }
 
  reversed(): List<E> {
    return reversedOf(this, LABELS)
  }
}