All files / src/internal/views linked-hash-map-views.ts

100% Statements 131/131
100% Branches 12/12
100% Functions 88/88
100% Lines 114/114

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                                                  14707x       1792x                       67159x 67159x         70077x       521x       66490x         195x       2416x       36095x         78x       32214x       255x       48x 18x       36x       36x       250x       241x       209x       205x       414x 414x 414x       16862x       40x             49x       14916x       94x       286x               380x 1380x 344x 344x 344x 344x 1462x               230x 1002x           179x                                 130199x 130199x         7113x       125x       690668x         170x       1364x       3993x 7698x         83x       688774x       25x       12x 6x       36x       36x       53x       485x       472x       18x         490x 490x 490x 490x       440x 440x 16x 16x       7x                     17x       11x 11x       7x       4x                 11x 11x 11x 11x 11x 11x 21x 21x   40x               8x 8x 26x           47x                           26839x       26839x 26839x         32504x       2320x         170x       1272x       29825x         57x         167645x 20463x       31x       48x 18x       18x       18x       432x       50x       24x 24x       392x 392x       400x       36x       487x             385x 1665x          
// The live views of a linked hash map or its reversed view — its keys, its entries and its values,
// in the order of the map they came from, with that map's ends. Each view works on the map's table
// and shares its change counter, so changes show everywhere and iteration is live; every call that
// can run user code counts as a call on the map. None can add.
//
// A view keeps the map it came from as `source` and reaches it through `map`, which first moves a
// map in the native layout to linked records. `size`, `isEmpty`, `has` and `revision` use `source`
// directly, so they keep the native layout.
 
import type { Cursor } from '../../interfaces/collection'
import type { SequencedCollection } from '../../interfaces/list'
import type { MapEntry } from '../../interfaces/map'
import type { SequencedSet } from '../../interfaces/sequenced-set'
import { SEQUENCED_COLLECTION_BRAND } from '../brand'
import { normalise } from '../engines/hash-support'
import type { LinkedRecord } from '../engines/linked-hash-table'
import { MISSING } from '../engines/map-stores'
import { type HashFunction, sameValueZero } from '../equality'
import { MappedLiveIterator } from '../iteration'
import { AbstractCollection } from '../skeletons/abstract-collection'
import type { AbstractLinkedMap } from '../skeletons/abstract-linked-map'
import { AbstractSet } from '../skeletons/abstract-set'
import { unsupportedAdd } from './map-entry'
 
function keyOf<K, V>(record: LinkedRecord<K, V>): K {
  return record.key
}
 
function valueOfRecord<K, V>(record: LinkedRecord<K, V>): V {
  return record.value
}
 
/**
 * The live view of a linked hash map's keys, under the map's key equality.
 *
 * @internal
 */
export class LinkedHashMapKeySet<K, V> extends AbstractSet<K> implements SequencedSet<K> {
  private readonly source: AbstractLinkedMap<K, V>
 
  constructor(map: AbstractLinkedMap<K, V>) {
    super(map.changes)
    this.source = map
  }
 
  /** The map, in linked records. */
  private get map(): AbstractLinkedMap<K, V> {
    return this.source.promote()
  }
 
  get owner(): SequencedSet<K> {
    return this
  }
 
  get [Symbol.toStringTag](): string {
    return 'LinkedHashMapKeySet'
  }
 
  /** Marks every sequenced collection for `isSequencedCollection`, across loaded copies. */
  get [SEQUENCED_COLLECTION_BRAND](): true {
    return true
  }
 
  get size(): number {
    return this.source.size
  }
 
  [Symbol.iterator](): IterableIterator<K> {
    return this.map.keys()
  }
 
  /** The key view of the reversed map. */
  reversed(): SequencedSet<K> {
    return new LinkedHashMapKeySet(this.map.opposite())
  }
 
  protected hasMember(key: K, method: string): boolean {
    return this.source.hasKey(key, `${this.className}.${method}`)
  }
 
  add(_key: K): this {
    throw unsupportedAdd(this.className)
  }
 
  override addAll(elements: Iterable<K>): boolean {
    if (this.readAll(elements, 'addAll').length === 0) return false
    throw unsupportedAdd(this.className, 'addAll')
  }
 
  addFirst(_key: K): this {
    throw unsupportedAdd(this.className, 'addFirst')
  }
 
  addLast(_key: K): this {
    throw unsupportedAdd(this.className, 'addLast')
  }
 
  getFirst(): K {
    return this.map.endRecord(false, `${this.className}.getFirst`, 'set').key
  }
 
  getLast(): K {
    return this.map.endRecord(true, `${this.className}.getLast`, 'set').key
  }
 
  removeFirst(): K {
    return this.removeEnd(false, 'removeFirst')
  }
 
  removeLast(): K {
    return this.removeEnd(true, 'removeLast')
  }
 
  private removeEnd(back: boolean, method: string): K {
    const record = this.map.endRecord(back, `${this.className}.${method}`, 'set')
    this.map.removeRecord(record)
    return record.key
  }
 
  override delete(key: K): boolean {
    return this.map.removeKey(key, `${this.className}.delete`) !== MISSING
  }
 
  override clear(): void {
    this.map.clear()
  }
 
  override forEach(
    action: (element: K, same: K, set: SequencedSet<K>) => void,
    thisArg?: unknown,
  ): void {
    this.map.call(() => super.forEach(action as never, thisArg))
  }
 
  cursor(): Cursor<K> {
    return this.map.cursor(keyOf, `${this.className}.cursor`)
  }
 
  override removeAll(keys: Iterable<K>): boolean {
    return this.removeMatching('removeAll', keys, true)
  }
 
  override retainAll(keys: Iterable<K>): boolean {
    return this.removeMatching('retainAll', keys, false)
  }
 
  /**
   * Builds a lookup of `keys` under the map's key equality (user code runs only here and while
   * probing it), decides every mapping, then removes the decided ones by mapping.
   */
  private removeMatching(method: string, keys: Iterable<K>, remove: boolean): boolean {
    const items = this.readAll(keys, method)
    for (let i = 0; i < items.length; i++) items[i] = normalise(items[i] as K)
    const map = this.map
    const where = `${this.className}.${method}`
    return map.call(() => {
      const matches = map.table.lookup(items, map.operation(where))
      return map.removeDecidedRecords((record) => matches(record) === remove, where)
    })
  }
 
  protected override removeDecided(
    method: string,
    decide: (element: K, index: number) => boolean,
  ): boolean {
    return this.map.removeDecidedRecords(
      (record, index) => decide(record.key, index),
      `${this.className}.${method}`,
    )
  }
 
  protected memberHashes(hash: HashFunction): number {
    return this.map.table.keyHashes(hash)
  }
}
 
/**
 * The live view of a linked hash map's mappings as entries. A value is a member when it is a map
 * entry whose key is present under the map's key equality with a value equal under `equals`.
 *
 * @internal
 */
export class LinkedHashMapEntrySet<K, V>
  extends AbstractSet<MapEntry<K, V>>
  implements SequencedSet<MapEntry<K, V>>
{
  private readonly source: AbstractLinkedMap<K, V>
 
  constructor(map: AbstractLinkedMap<K, V>) {
    super(map.changes)
    this.source = map
  }
 
  /** The map, in linked records. */
  private get map(): AbstractLinkedMap<K, V> {
    return this.source.promote()
  }
 
  get owner(): SequencedSet<MapEntry<K, V>> {
    return this
  }
 
  get [Symbol.toStringTag](): string {
    return 'LinkedHashMapEntrySet'
  }
 
  /** Marks every sequenced collection for `isSequencedCollection`, across loaded copies. */
  get [SEQUENCED_COLLECTION_BRAND](): true {
    return true
  }
 
  get size(): number {
    return this.source.size
  }
 
  [Symbol.iterator](): IterableIterator<MapEntry<K, V>> {
    const map = this.map
    return new MappedLiveIterator(map.table.iterator(map.fromBack), (record) => map.entryAt(record))
  }
 
  /** The entry view of the reversed map. */
  reversed(): SequencedSet<MapEntry<K, V>> {
    return new LinkedHashMapEntrySet(this.map.opposite())
  }
 
  protected hasMember(entry: MapEntry<K, V>, method: string): boolean {
    return this.source.holdsEntry(entry, `${this.className}.${method}`)
  }
 
  add(_entry: MapEntry<K, V>): this {
    throw unsupportedAdd(this.className)
  }
 
  override addAll(elements: Iterable<MapEntry<K, V>>): boolean {
    if (this.readAll(elements, 'addAll').length === 0) return false
    throw unsupportedAdd(this.className, 'addAll')
  }
 
  addFirst(_entry: MapEntry<K, V>): this {
    throw unsupportedAdd(this.className, 'addFirst')
  }
 
  addLast(_entry: MapEntry<K, V>): this {
    throw unsupportedAdd(this.className, 'addLast')
  }
 
  getFirst(): MapEntry<K, V> {
    return this.map.entryAt(this.map.endRecord(false, `${this.className}.getFirst`, 'set'))
  }
 
  getLast(): MapEntry<K, V> {
    return this.map.entryAt(this.map.endRecord(true, `${this.className}.getLast`, 'set'))
  }
 
  removeFirst(): MapEntry<K, V> {
    return this.removeEnd(false, 'removeFirst')
  }
 
  removeLast(): MapEntry<K, V> {
    return this.removeEnd(true, 'removeLast')
  }
 
  /** Makes the entry first, so it reads the value the mapping had, then removes the mapping. */
  private removeEnd(back: boolean, method: string): MapEntry<K, V> {
    const record = this.map.endRecord(back, `${this.className}.${method}`, 'set')
    const entry = this.map.entryAt(record)
    this.map.removeRecord(record)
    return entry
  }
 
  override delete(entry: MapEntry<K, V>): boolean {
    const record = this.map.locate(entry, `${this.className}.delete`)
    if (record === undefined) return false
    this.map.removeRecord(record)
    return true
  }
 
  override clear(): void {
    this.map.clear()
  }
 
  override forEach(
    action: (
      element: MapEntry<K, V>,
      same: MapEntry<K, V>,
      set: SequencedSet<MapEntry<K, V>>,
    ) => void,
    thisArg?: unknown,
  ): void {
    this.map.call(() => super.forEach(action as never, thisArg))
  }
 
  cursor(): Cursor<MapEntry<K, V>> {
    const map = this.map
    return map.cursor((record) => map.entryAt(record), `${this.className}.cursor`)
  }
 
  override removeAll(entries: Iterable<MapEntry<K, V>>): boolean {
    return this.removeMatching('removeAll', entries, true)
  }
 
  override retainAll(entries: Iterable<MapEntry<K, V>>): boolean {
    return this.removeMatching('retainAll', entries, false)
  }
 
  /** Finds the mapping of every argument first (user code runs only here), then removes. */
  private removeMatching(
    method: string,
    entries: Iterable<MapEntry<K, V>>,
    remove: boolean,
  ): boolean {
    const items = this.readAll(entries, method)
    const map = this.map
    const where = `${this.className}.${method}`
    return map.call(() => {
      const matched = new Set<unknown>()
      for (let i = 0; i < items.length; i++) {
        const record = map.locate(items[i], where)
        if (record !== undefined) matched.add(record.handle)
      }
      return map.removeDecidedRecords((record) => matched.has(record.handle) === remove, where)
    })
  }
 
  protected override removeDecided(
    method: string,
    decide: (element: MapEntry<K, V>, index: number) => boolean,
  ): boolean {
    const map = this.map
    return map.removeDecidedRecords(
      (record, index) => decide(map.entryAt(record), index),
      `${this.className}.${method}`,
    )
  }
 
  protected memberHashes(hash: HashFunction): number {
    return this.map.mappingHashes(hash)
  }
}
 
/**
 * The live view of a linked hash map's values, compared with SameValueZero. Removing a value
 * removes the first mapping with that value. It equals only itself.
 *
 * @internal
 */
export class LinkedHashMapValues<K, V>
  extends AbstractCollection<V>
  implements SequencedCollection<V>
{
  protected readonly iterationMode = 'live' as const
  private readonly source: AbstractLinkedMap<K, V>
 
  constructor(map: AbstractLinkedMap<K, V>) {
    super(map.changes)
    this.source = map
  }
 
  /** The map, in linked records. */
  private get map(): AbstractLinkedMap<K, V> {
    return this.source.promote()
  }
 
  get [Symbol.toStringTag](): string {
    return 'LinkedHashMapValues'
  }
 
  /** Marks every sequenced collection for `isSequencedCollection`, across loaded copies. */
  get [SEQUENCED_COLLECTION_BRAND](): true {
    return true
  }
 
  get size(): number {
    return this.source.size
  }
 
  [Symbol.iterator](): IterableIterator<V> {
    return this.map.values()
  }
 
  /** The value view of the reversed map. */
  reversed(): SequencedCollection<V> {
    return new LinkedHashMapValues(this.map.opposite())
  }
 
  /** Whether a value is SameValueZero to `value`, scanning in order; keeps the native layout. */
  override has(value: V): boolean {
    for (const candidate of this.source.values()) if (sameValueZero(candidate, value)) return true
    return false
  }
 
  add(_value: V): this {
    throw unsupportedAdd(this.className)
  }
 
  override addAll(elements: Iterable<V>): boolean {
    if (this.readAll(elements, 'addAll').length === 0) return false
    throw unsupportedAdd(this.className, 'addAll')
  }
 
  addFirst(_value: V): this {
    throw unsupportedAdd(this.className, 'addFirst')
  }
 
  addLast(_value: V): this {
    throw unsupportedAdd(this.className, 'addLast')
  }
 
  getFirst(): V {
    return this.map.endRecord(false, `${this.className}.getFirst`, 'collection').value
  }
 
  getLast(): V {
    return this.map.endRecord(true, `${this.className}.getLast`, 'collection').value
  }
 
  removeFirst(): V {
    const where = `${this.className}.removeFirst`
    return this.map.removeRecord(this.map.endRecord(false, where, 'collection'))
  }
 
  removeLast(): V {
    const where = `${this.className}.removeLast`
    return this.map.removeRecord(this.map.endRecord(true, where, 'collection'))
  }
 
  override clear(): void {
    this.map.clear()
  }
 
  override forEach(action: (element: V) => void, thisArg?: unknown): void {
    this.map.call(() => super.forEach(action, thisArg))
  }
 
  cursor(): Cursor<V> {
    return this.map.cursor(valueOfRecord, `${this.className}.cursor`)
  }
 
  protected override removeDecided(
    method: string,
    decide: (element: V, index: number) => boolean,
  ): boolean {
    return this.map.removeDecidedRecords(
      (record, index) => decide(record.value, index),
      `${this.className}.${method}`,
    )
  }
}