All files / src/internal/engines hash-map-engine.ts

100% Statements 243/243
100% Branches 94/94
100% Functions 49/49
100% Lines 217/217

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                                                                                                                    9514x 9514x 9514x 9514x 9514x 9514x       12053x       43255x       59609x       39682x       71666x       95049x       8001x         12x         116200x       41987x 41987x 41987x 30823x 30823x                             4907x 4907x 4907x 4907x 12x       4881x       17449x 17449x 3931x 3931x 2691x 2691x       9877x 9877x 4727x 4727x 2199x       47x 47x 25x 25x 17x 17x   22x 22x   22x             20451x 20451x       16055x 16055x       10942x 10942x             22x 22x 9x 9x   13x 13x 13x 35x           1125370x 1125370x 64038x 64038x   1061332x 1061332x 1061332x 6185x         32914x 32914x 9896x 9686x 9686x         8505x 23x           18860x 18860x 18860x 18860x         23793x 23793x 23793x 23793x         65484x 65484x   370x 370x 370x 370x 370x 309x 309x   61x 61x   65114x 65114x 65114x 65114x 65114x 52865x 52865x 52865x       1446x 1446x         59x 81x         25637x 25637x 991x 991x 991x 788x 788x   24646x 24646x       2430x 2430x       2961x 2961x 2961x 2961x 2961x 2708x 2708x 2708x       1389x 1389x 1389x 1389x 1389x 1389x 1389x 1199x   1199x 1199x 1199x 7x   1190x 1190x   1197x             2516x 2516x 2516x 2516x 2516x 2516x 2516x 2516x 2516x 2516x 2516x 81x 2409x 86x   2323x 2323x   2490x             36x 36x 36x 36x 36x 25x 25x     25x 25x 9x 16x               8400x 8400x 8400x 8400x 8400x 8400x 8400x 2863x 2863x 2863x   5536x 5536x           5536x 5536x 5472x 5527x       28x 28x 28x 28x 28x 457x 457x         457x 457x         1130x 999x 999x               5076x 69x         253x 253x         151x 151x 151x 435x   143x 197x 130x 130x                 982x     1298x   253x   1131x           4613x       1772x       3905x       617x         6x      
// The engine behind `HashMap`. The public class holds one engine and delegates to it, so nothing
// here reaches the published types.
//
// The engine picks one store at construction and keeps it (see `map-stores.ts`). Every operation
// turns a `-0` key into `0`, derives the key's probe once, looks up before it writes, and records
// the change: `structural()` when a mapping is added or removed, `replaced()` when a value is
// written.
 
import { ConcurrentModificationError } from '../../errors/errors'
import type { Collection, Cursor } from '../../interfaces/collection'
import type { MapCollection, MapEntry } from '../../interfaces/map'
import type { SetCollection } from '../../interfaces/set'
import { requireFunction } from '../checks'
import type { HashFunction } from '../equality'
import { apply } from '../intrinsics'
import { LiveCursor, MappedLiveIterator, NativeMapIterator } from '../iteration'
import { deriveKey } from '../key'
import { readPairs } from '../map-input'
import { AbstractMap } from '../skeletons/abstract-map'
import { MapEntryHandle } from '../views/map-entry'
import { HashMapEntrySet, HashMapKeySet, HashMapValues } from '../views/map-views'
import { type HashEquality, normalise, Operation } from './hash-support'
import { type KeyedMap, type KeyedRecord, type MapStore, MISSING, newMapStore } from './map-stores'
 
/** A mapping a cursor has reached: its handle and the value it had then. */
type Reached<V> = readonly [unknown, V]
 
/**
 * A map whose keys are compared with SameValueZero, by derived key, or by an equivalence, kept in
 * insertion order with live iteration.
 *
 * @internal
 */
export class HashMapEngine<K, V> extends AbstractMap<K, V> {
  readonly store: MapStore<K, V>
  private readonly facade: MapCollection<K, V>
  private readonly equality: HashEquality<K>
  /**
   * The store's native `Map` when no user code runs on a lookup (the default SameValueZero map):
   * reads and writes then call it directly, with no `Operation` and one call where one suffices.
   */
  private readonly native: Map<K, V> | undefined
  /**
   * The store's key function and derived-key `Map` when keys are compared by a `key` option:
   * reads then call the key function and the `Map` directly, with no `Operation`.
   */
  private readonly keyed: KeyedMap<K, V> | undefined
 
  /**
   * @param facade - The public map, for identity and callbacks.
   * @param equality - How keys are compared.
   * @param store - The storage to use; a new empty one by default.
   */
  constructor(
    facade: MapCollection<K, V>,
    equality: HashEquality<K>,
    store: MapStore<K, V> = newMapStore<K, V>(equality),
  ) {
    super()
    this.facade = facade
    this.equality = equality
    this.store = store
    this.native = store.nativeMap()
    this.keyed = store.keyedMap()
  }
 
  get owner(): MapCollection<K, V> {
    return this.facade
  }
 
  get [Symbol.toStringTag](): string {
    return 'HashMap'
  }
 
  get size(): number {
    return this.store.size
  }
 
  handles(_where?: string): Iterator<unknown> {
    return this.store.handles()
  }
 
  keyAt(handle: unknown): K {
    return this.store.keyAt(handle)
  }
 
  valueAt(handle: unknown): V {
    return this.store.valueAt(handle)
  }
 
  keyHash(handle: unknown, hash: HashFunction): number {
    return this.store.keyHash(handle, hash)
  }
 
  /** `<Class>.<method>`, built only when an error names it. */
  errorLabel(method: string): string {
    return this.at(method)
  }
 
  /** Starts an operation whose errors name `where`. */
  operation(where: string): Operation {
    return new Operation(this.changes, where, 'map')
  }
 
  find(key: K, where: string): unknown {
    const normalised = normalise(key)
    const native = this.native
    if (native !== undefined) return native.has(normalised) ? normalised : MISSING
    const op = this.operation(where)
    return this.store.find(normalised, this.store.probe(normalised, op), op)
  }
 
  // ── Hot paths: one native call where one suffices, no Operation on the native store ──
 
  /**
   * Finds the record of `key` in the keyed store: one call of the key function, its result
   * checked, then one `Map.get`. Throws as an `Operation` would when the key function added or
   * removed mappings; the label is built only then.
   */
  private keyedRecord(
    keyed: KeyedMap<K, V>,
    key: K,
    method: string,
  ): KeyedRecord<K, V> | undefined {
    const changes = this.changes
    const start = changes.structure
    const derived = deriveKey(keyed.key, normalise(key), this, method)
    if (changes.structure !== start) {
      throw new ConcurrentModificationError(
        `${this.at(method)}: the map was changed by a key, equals or hash function`,
      )
    }
    return keyed.map.get(derived)
  }
 
  override get(key: K): V | undefined {
    const native = this.native
    if (native !== undefined) return native.get(normalise(key))
    const keyed = this.keyed
    if (keyed === undefined) return super.get(key)
    const record = this.keyedRecord(keyed, key, 'get')
    return record === undefined ? undefined : record.value
  }
 
  override has(key: K): boolean {
    const native = this.native
    if (native !== undefined) return native.has(normalise(key))
    const keyed = this.keyed
    if (keyed === undefined) return super.has(key)
    return this.keyedRecord(keyed, key, 'has') !== undefined
  }
 
  override getOrDefault<D>(key: K, fallback: D): V | D {
    const native = this.native
    if (native === undefined) {
      const keyed = this.keyed
      if (keyed === undefined) return super.getOrDefault(key, fallback)
      const record = this.keyedRecord(keyed, key, 'getOrDefault')
      return record === undefined ? fallback : record.value
    }
    const normalised = normalise(key)
    const value = native.get(normalised)
    // `undefined` is a stored value or an absent key; only then is a second call needed.
    return value !== undefined || native.has(normalised) ? (value as V) : fallback
  }
 
  // Iteration of the native store is the native `Map`'s own: live, in insertion order, with no
  // lookup per step.
 
  override keys(): IterableIterator<K> {
    const native = this.native
    return native === undefined ? super.keys() : new NativeMapIterator(native.keys())
  }
 
  override values(): IterableIterator<V> {
    const native = this.native
    return native === undefined ? super.values() : new NativeMapIterator(native.values())
  }
 
  override entries(): IterableIterator<[K, V]> {
    const native = this.native
    return native === undefined ? super.entries() : new NativeMapIterator(native.entries())
  }
 
  override forEach(
    action: (value: V, key: K, map: MapCollection<K, V>) => void,
    thisArg?: unknown,
  ): void {
    const native = this.native
    if (native === undefined) {
      super.forEach(action, thisArg)
      return
    }
    requireFunction(action, 'HashMap.forEach', 'action')
    const owner = this.facade
    native.forEach((value, key) => {
      apply(action, thisArg, [value, key, owner])
    })
  }
 
  /** `set`: maps `key` to `value`. One native call: the size tells a new key from an old one. */
  setKey(key: K, value: V, where: string): void {
    const native = this.native
    if (native === undefined) {
      this.setValue(key, value, where)
      return
    }
    const before = native.size
    native.set(normalise(key), value)
    if (native.size !== before) this.changes.structural()
    else this.changes.replaced()
  }
 
  /** `delete`: removes the mapping of `key`; one native call. */
  deleteKey(key: K, where: string): boolean {
    const native = this.native
    if (native === undefined) return this.removeKey(key, where) !== MISSING
    if (!native.delete(normalise(key))) return false
    this.changes.structural()
    return true
  }
 
  /** Throws when a callback of `where` added or removed mappings since `start`. */
  private checkCallback(start: number, where: string): void {
    if (this.changes.structure !== start) {
      throw new ConcurrentModificationError(`${where}: the map was changed by the callback`)
    }
  }
 
  /** Writes `value` to a stored mapping and returns the value it replaced. */
  overwrite(handle: unknown, value: V): V {
    const old = this.store.valueAt(handle)
    this.store.write(handle, value)
    this.changes.replaced()
    return old
  }
 
  /** Removes a stored mapping and returns its value. */
  removeAt(handle: unknown): V {
    const old = this.store.valueAt(handle)
    this.store.removeHandle(handle)
    this.changes.structural()
    return old
  }
 
  /** Maps `key` to `value`; returns the previous value, or `MISSING` when the key was absent. */
  setValue(key: K, value: V, where: string): unknown {
    const native = this.native
    if (native !== undefined) {
      // Two native calls: the old value, then the write; the size tells a new key from an old one.
      const normalised = normalise(key)
      const old = native.get(normalised)
      const before = native.size
      native.set(normalised, value)
      if (native.size !== before) {
        this.changes.structural()
        return MISSING
      }
      this.changes.replaced()
      return old
    }
    const op = this.operation(where)
    const normalised = normalise(key)
    const probe = this.store.probe(normalised, op)
    const handle = this.store.find(normalised, probe, op)
    if (handle !== MISSING) return this.overwrite(handle, value)
    this.store.insert(normalised, probe, value)
    this.changes.structural()
    return MISSING
  }
 
  put(key: K, value: V): V | undefined {
    const old = this.setValue(key, value, 'HashMap.put')
    return old === MISSING ? undefined : (old as V)
  }
 
  /** Sets every mapping of `entries` after reading and checking them all. */
  putAll(entries: unknown): void {
    const pairs = readPairs<K, V>(entries, 'HashMap.putAll')
    for (const pair of pairs) this.setKey(pair[0], pair[1], 'HashMap.putAll')
  }
 
  /** Removes the mapping of `key`; returns its value, or `MISSING`. */
  removeKey(key: K, where: string): unknown {
    const native = this.native
    if (native !== undefined) {
      const normalised = normalise(key)
      const old = native.get(normalised)
      if (!native.delete(normalised)) return MISSING
      this.changes.structural()
      return old
    }
    const handle = this.find(key, where)
    return handle === MISSING ? MISSING : this.removeAt(handle)
  }
 
  replace(key: K, value: V): V | undefined {
    const handle = this.find(key, 'HashMap.replace')
    return handle === MISSING ? undefined : this.overwrite(handle, value)
  }
 
  getOrInsert(key: K, value: V): V {
    const op = this.operation('HashMap.getOrInsert')
    const normalised = normalise(key)
    const probe = this.store.probe(normalised, op)
    const handle = this.store.find(normalised, probe, op)
    if (handle !== MISSING) return this.store.valueAt(handle)
    this.store.insert(normalised, probe, value)
    this.changes.structural()
    return value
  }
 
  getOrInsertComputed(key: K, fn: (key: K) => V): V {
    const where = 'HashMap.getOrInsertComputed'
    requireFunction(fn, where, 'fn')
    const normalised = normalise(key)
    const op = this.operation(where)
    const probe = this.store.probe(normalised, op)
    const handle = this.store.find(normalised, probe, op)
    if (handle !== MISSING) return this.store.valueAt(handle)
    const value = apply(fn, undefined, [normalised]) as V
    // The callback may have changed the map: look again, with the probe already derived.
    const again = this.operation(where)
    const now = this.store.find(normalised, probe, again)
    if (now !== MISSING) {
      this.overwrite(now, value)
    } else {
      this.store.insert(normalised, probe, value)
      this.changes.structural()
    }
    return value
  }
 
  compute(
    key: K,
    fn: (value: V | undefined, key: K, map: MapCollection<K, V>) => V | undefined,
  ): V | undefined {
    const where = 'HashMap.compute'
    requireFunction(fn, where, 'fn')
    const normalised = normalise(key)
    const op = this.operation(where)
    const probe = this.store.probe(normalised, op)
    const handle = this.store.find(normalised, probe, op)
    const start = this.changes.structure
    const old = handle === MISSING ? undefined : this.store.valueAt(handle)
    const result = apply(fn, undefined, [old, normalised, this.facade]) as V | undefined
    this.checkCallback(start, where)
    if (result === undefined) {
      if (handle !== MISSING) this.removeAt(handle)
    } else if (handle !== MISSING) {
      this.overwrite(handle, result)
    } else {
      this.store.insert(normalised, probe, result)
      this.changes.structural()
    }
    return result
  }
 
  computeIfPresent(
    key: K,
    fn: (value: V, key: K, map: MapCollection<K, V>) => V | undefined,
  ): V | undefined {
    const where = 'HashMap.computeIfPresent'
    requireFunction(fn, where, 'fn')
    const normalised = normalise(key)
    const handle = this.find(normalised, where)
    if (handle === MISSING) return undefined
    const start = this.changes.structure
    const result = apply(fn, undefined, [this.store.valueAt(handle), normalised, this.facade]) as
      | V
      | undefined
    this.checkCallback(start, where)
    if (result === undefined) this.removeAt(handle)
    else this.overwrite(handle, result)
    return result
  }
 
  merge(
    key: K,
    value: V,
    fn: (old: V, value: V, key: K, map: MapCollection<K, V>) => V | undefined,
  ): V | undefined {
    const where = 'HashMap.merge'
    requireFunction(fn, where, 'fn')
    const normalised = normalise(key)
    const op = this.operation(where)
    const probe = this.store.probe(normalised, op)
    const handle = this.store.find(normalised, probe, op)
    if (handle === MISSING) {
      this.store.insert(normalised, probe, value)
      this.changes.structural()
      return value
    }
    const start = this.changes.structure
    const result = apply(fn, undefined, [
      this.store.valueAt(handle),
      value,
      normalised,
      this.facade,
    ]) as V | undefined
    this.checkCallback(start, where)
    if (result === undefined) this.removeAt(handle)
    else this.overwrite(handle, result)
    return result
  }
 
  replaceAll(fn: (value: V, key: K, map: MapCollection<K, V>) => V): void {
    const where = 'HashMap.replaceAll'
    requireFunction(fn, where, 'fn')
    const start = this.changes.structure
    const handles = this.store.handles()
    for (let step = handles.next(); step.done !== true; step = handles.next()) {
      const handle = step.value
      const result = apply(fn, undefined, [
        this.store.valueAt(handle),
        this.store.keyAt(handle),
        this.facade,
      ]) as V
      this.checkCallback(start, where)
      this.overwrite(handle, result)
    }
  }
 
  clear(): void {
    if (this.store.size === 0) return
    this.store.clear()
    this.changes.structural()
  }
 
  /**
   * Returns the handle of the mapping `handle` stood for: `handle` itself while stored, otherwise a
   * mapping with an equal key found by the stored probe (no `key` or `hash` call), or `MISSING`.
   */
  relocate(handle: unknown, key: K, probe: unknown, where: string): unknown {
    if (this.store.holds(handle)) return handle
    return this.store.find(key, probe, this.operation(where))
  }
 
  /** Removes a mapping by handle, or by its stored probe when that handle is gone. */
  removeHandle(handle: unknown, where: string): void {
    const found = this.relocate(handle, this.store.keyAt(handle), this.store.probeAt(handle), where)
    if (found !== MISSING) this.removeAt(found)
  }
 
  /** Removes the mappings `doomed` accepts, deciding all of them first; returns whether any. */
  removeWhere(doomed: (handle: unknown) => boolean): boolean {
    const chosen: unknown[] = []
    const handles = this.store.handles()
    for (let step = handles.next(); step.done !== true; step = handles.next()) {
      if (doomed(step.value)) chosen.push(step.value)
    }
    if (chosen.length === 0) return false
    for (const handle of chosen) this.store.removeHandle(handle)
    this.changes.structural()
    return true
  }
 
  /**
   * A live cursor over the mappings, projected by `project` from the handle and the value read
   * when the mapping was reached (so a mapping deleted after `hasNext()` still yields its value);
   * removal is by stored mapping.
   */
  cursor<E>(project: (handle: unknown, value: V) => E, where: string): Cursor<E> {
    return new LiveCursor<E, Reached<V>>(
      new MappedLiveIterator(
        this.store.handles(),
        (handle): Reached<V> => [handle, this.valueAt(handle)],
      ),
      (reached) => this.removeHandle(reached[0], where),
      where,
      (reached) => project(reached[0], reached[1]),
    )
  }
 
  /** A new entry for a stored mapping; `value` is its value when known (a reached mapping). */
  entryAt(handle: unknown, value: V = this.valueAt(handle)): MapEntry<K, V> {
    return new MapEntryHandle(this, handle, this.store.probeAt(handle), value)
  }
 
  keySet(): SetCollection<K> {
    return new HashMapKeySet(this)
  }
 
  entrySet(): SetCollection<MapEntry<K, V>> {
    return new HashMapEntrySet(this)
  }
 
  valueCollection(): Collection<V> {
    return new HashMapValues(this)
  }
 
  /** A new engine for `facade` with the same equality and the same stored keys and hashes. */
  copy(facade: MapCollection<K, V>): HashMapEngine<K, V> {
    return new HashMapEngine(facade, this.equality, this.store.copy())
  }
}