All files / src/internal/engines map-stores.ts

100% Statements 93/93
93.33% Branches 14/15
100% Functions 62/62
100% Lines 88/88

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                                    108x                                                                                                           411640x       1991510x       224608x       9875x       3933x 3933x       6331x       111296x       1759810x       81316x       694770x       191331x       5353x       415481x       5131x 16704x       7776x       199986x       411640x       8133x                                                           2495x 2495x       103940x       150048x       151368x 151368x       77561x 77561x 77561x       25673x       87391x       68476x       42730x       3804x       36340x       1040x       12495x       60x 112x 184x       847x       2495x       712x       10x 10x 427x   10x                                     424x                         2637x 2637x 2637x       168261x         285339x 285339x       285339x       287498x 287498x 287498x 1038402x   287498x       140525x       40372x       152922x       120036x       10575x       6171x 6171x       64229x       2012x       18653x       91x 167x 89x 89x 232x 232x   157x             6077x 6077x       2637x       669x       8x                   1931x                 214837x   209723x   2485x   2629x              
// Storage for a hash map, one per key equality: a native `Map` (SameValueZero), a native `Map` from
// derived key to record (a `key` function), or seeded buckets of records (an equivalence). Every
// store keeps insertion order in native storage, so iteration is live exactly as a native `Map`'s
// is. A key's derived key or hash is computed once, when the mapping is stored, and reused for every
// later lookup by stored mapping.
 
import { type HashFunction, type KeyOf, type ProtocolMethods, protocolOf } from '../equality'
import type { CheckedEquivalence } from '../equivalence'
import { deriveKey } from '../key'
import type { HashEquality, Operation } from './hash-support'
import { type BucketEntry, BucketTable } from './hash-table'
 
/**
 * What `find` returns when no mapping matches. No key can be this object: it never leaves the
 * library.
 *
 * @internal
 */
export const MISSING: object = {}
 
/**
 * Storage for one key equality.
 *
 * A *probe* is what a key is found by — the key itself, its derived key, or its hash — computed
 * once per operation by `probe` (the only place `key` or `hash` runs) and reusable for a second
 * lookup. A *handle* is what the store's live iteration yields for one mapping; reading, writing
 * and removing by handle never call user code.
 *
 * @internal
 */
export interface MapStore<K, V> {
  readonly size: number
  /** Derives the probe of `key`: calls `key` or `hash` once. */
  probe(key: K, op: Operation): unknown
  /** Returns the handle of the mapping whose key equals `key`, or `MISSING`. */
  find(key: K, probe: unknown, op: Operation): unknown
  /** Appends a mapping for a key known to be absent; returns its handle. */
  insert(key: K, probe: unknown, value: V): unknown
  keyAt(handle: unknown): K
  valueAt(handle: unknown): V
  /** Writes the value of a stored mapping, keeping its key and position. */
  write(handle: unknown, value: V): void
  /** Whether the mapping `handle` stands for is still stored. */
  holds(handle: unknown): boolean
  /** The stored probe of a mapping, for finding it again without user calls. */
  probeAt(handle: unknown): unknown
  removeHandle(handle: unknown): void
  clear(): void
  /** A live iterator over the handles in insertion order. */
  handles(): Iterator<unknown>
  /** A test of stored handles against `keys`, under this store's equality. */
  lookup(keys: readonly K[], op: Operation): (handle: unknown) => boolean
  /** The hash of a stored key: by the given function, or the stored hash of a user equivalence. */
  keyHash(handle: unknown, hash: HashFunction): number
  copy(): MapStore<K, V>
  /**
   * The native `Map` that holds the mappings, when keys are compared with SameValueZero and no
   * user code runs on a lookup; `undefined` for the keyed and bucket stores. The engine uses it
   * directly on its hot paths.
   */
  nativeMap(): Map<K, V> | undefined
  /**
   * The key function and the native `Map` from derived key to record, for the keyed store;
   * `undefined` for the others. The engine reads through it on its keyed hot paths.
   */
  keyedMap(): KeyedMap<K, V> | undefined
}
 
class NativeMapStore<K, V> implements MapStore<K, V> {
  private readonly map: Map<K, V>
 
  constructor(map: Map<K, V>) {
    this.map = map
  }
 
  get size(): number {
    return this.map.size
  }
 
  probe(key: K): unknown {
    return key
  }
 
  find(key: K): unknown {
    return this.map.has(key) ? key : MISSING
  }
 
  insert(key: K, _probe: unknown, value: V): unknown {
    this.map.set(key, value)
    return key
  }
 
  keyAt(handle: unknown): K {
    return handle as K
  }
 
  valueAt(handle: unknown): V {
    return this.map.get(handle as K) as V
  }
 
  write(handle: unknown, value: V): void {
    this.map.set(handle as K, value)
  }
 
  holds(handle: unknown): boolean {
    return this.map.has(handle as K)
  }
 
  probeAt(handle: unknown): unknown {
    return handle
  }
 
  removeHandle(handle: unknown): void {
    this.map.delete(handle as K)
  }
 
  clear(): void {
    this.map.clear()
  }
 
  handles(): Iterator<unknown> {
    return this.map.keys()
  }
 
  lookup(keys: readonly K[]): (handle: unknown) => boolean {
    const set = new Set<unknown>(keys)
    return (handle) => set.has(handle)
  }
 
  keyHash(handle: unknown, hash: HashFunction): number {
    return hash(handle)
  }
 
  copy(): MapStore<K, V> {
    return new NativeMapStore(new Map(this.map))
  }
 
  nativeMap(): Map<K, V> {
    return this.map
  }
 
  keyedMap(): undefined {
    return undefined
  }
}
 
/**
 * A mapping stored under its derived key.
 *
 * @internal
 */
export interface KeyedRecord<K, V> {
  readonly derived: unknown
  readonly key: K
  value: V
}
 
/**
 * The keyed store's key function and its native `Map` from derived key to record.
 *
 * @internal
 */
export interface KeyedMap<K, V> {
  readonly key: KeyOf<K>
  readonly map: Map<unknown, KeyedRecord<K, V>>
}
 
class KeyedMapStore<K, V> implements MapStore<K, V>, KeyedMap<K, V> {
  readonly key: KeyOf<K>
  readonly map: Map<unknown, KeyedRecord<K, V>>
 
  constructor(key: KeyOf<K>, map: Map<unknown, KeyedRecord<K, V>>) {
    this.key = key
    this.map = map
  }
 
  get size(): number {
    return this.map.size
  }
 
  probe(key: K, op: Operation): unknown {
    return op.after(deriveKey(this.key, key, op.where))
  }
 
  find(_key: K, probe: unknown): unknown {
    const record = this.map.get(probe)
    return record === undefined ? MISSING : record
  }
 
  insert(key: K, probe: unknown, value: V): unknown {
    const record: KeyedRecord<K, V> = { derived: probe, key, value }
    this.map.set(probe, record)
    return record
  }
 
  keyAt(handle: unknown): K {
    return (handle as KeyedRecord<K, V>).key
  }
 
  valueAt(handle: unknown): V {
    return (handle as KeyedRecord<K, V>).value
  }
 
  write(handle: unknown, value: V): void {
    ;(handle as KeyedRecord<K, V>).value = value
  }
 
  holds(handle: unknown): boolean {
    return this.map.get((handle as KeyedRecord<K, V>).derived) === handle
  }
 
  probeAt(handle: unknown): unknown {
    return (handle as KeyedRecord<K, V>).derived
  }
 
  removeHandle(handle: unknown): void {
    Eif (this.holds(handle)) this.map.delete((handle as KeyedRecord<K, V>).derived)
  }
 
  clear(): void {
    this.map.clear()
  }
 
  handles(): Iterator<unknown> {
    return this.map.values()
  }
 
  lookup(keys: readonly K[], op: Operation): (handle: unknown) => boolean {
    const derived = new Set<unknown>()
    for (const key of keys) derived.add(this.probe(key, op))
    return (handle) => derived.has((handle as KeyedRecord<K, V>).derived)
  }
 
  keyHash(handle: unknown, hash: HashFunction): number {
    return hash((handle as KeyedRecord<K, V>).derived)
  }
 
  nativeMap(): undefined {
    return undefined
  }
 
  keyedMap(): KeyedMap<K, V> {
    return this
  }
 
  copy(): MapStore<K, V> {
    const map = new Map<unknown, KeyedRecord<K, V>>()
    for (const record of this.map.values()) {
      map.set(record.derived, { derived: record.derived, key: record.key, value: record.value })
    }
    return new KeyedMapStore(this.key, map)
  }
}
 
/** A mapping in a bucket entry, which keeps its hash. */
interface BucketRecord<K, V> {
  readonly key: K
  value: V
}
 
/** The probe of the bucket store: the hash, and the key's protocol methods when already read. */
interface BucketProbe {
  readonly hash: number
  readonly methods: ProtocolMethods | undefined
}
 
type Bucketed<K, V> = BucketEntry<BucketRecord<K, V>>
 
function cloneRecord<K, V>(record: BucketRecord<K, V>): BucketRecord<K, V> {
  return { key: record.key, value: record.value }
}
 
class BucketMapStore<K, V> implements MapStore<K, V> {
  private readonly equivalence: CheckedEquivalence
  private readonly builtIn: boolean
  private readonly table: BucketTable<BucketRecord<K, V>>
 
  constructor(
    equivalence: CheckedEquivalence,
    builtIn: boolean,
    table: BucketTable<BucketRecord<K, V>>,
  ) {
    this.equivalence = equivalence
    this.builtIn = builtIn
    this.table = table
  }
 
  get size(): number {
    return this.table.size
  }
 
  probe(key: K, op: Operation): unknown {
    // The protocol methods of the key are read once per operation, for the built-in equivalence.
    const methods = this.builtIn ? protocolOf(key) : undefined
    const probe: BucketProbe = {
      hash: op.after(this.equivalence.hash(key, op.where, methods)),
      methods,
    }
    return probe
  }
 
  find(key: K, probe: unknown, op: Operation): unknown {
    const { hash, methods } = probe as BucketProbe
    const equivalence = this.equivalence
    const entry = this.table.find(hash, (stored) =>
      op.after(equivalence.equals(key, stored.key, op.where, methods)),
    )
    return entry === undefined ? MISSING : entry
  }
 
  insert(key: K, probe: unknown, value: V): unknown {
    return this.table.insert((probe as BucketProbe).hash, { key, value })
  }
 
  keyAt(handle: unknown): K {
    return (handle as Bucketed<K, V>).value.key
  }
 
  valueAt(handle: unknown): V {
    return (handle as Bucketed<K, V>).value.value
  }
 
  write(handle: unknown, value: V): void {
    ;(handle as Bucketed<K, V>).value.value = value
  }
 
  holds(handle: unknown): boolean {
    return this.table.contains(handle as Bucketed<K, V>)
  }
 
  probeAt(handle: unknown): unknown {
    const probe: BucketProbe = { hash: (handle as Bucketed<K, V>).hash, methods: undefined }
    return probe
  }
 
  removeHandle(handle: unknown): void {
    this.table.remove(handle as Bucketed<K, V>)
  }
 
  clear(): void {
    this.table.clear()
  }
 
  handles(): Iterator<unknown> {
    return this.table.entries()
  }
 
  lookup(keys: readonly K[], op: Operation): (handle: unknown) => boolean {
    const argument = new BucketTable<K>()
    for (const key of keys) argument.insert((this.probe(key, op) as BucketProbe).hash, key)
    const equivalence = this.equivalence
    return (handle) => {
      const entry = handle as Bucketed<K, V>
      return (
        argument.find(entry.hash, (key) =>
          op.after(equivalence.equals(entry.value.key, key, op.where)),
        ) !== undefined
      )
    }
  }
 
  keyHash(handle: unknown, hash: HashFunction): number {
    const entry = handle as Bucketed<K, V>
    return this.builtIn ? hash(entry.value.key) : entry.hash
  }
 
  nativeMap(): undefined {
    return undefined
  }
 
  keyedMap(): undefined {
    return undefined
  }
 
  copy(): MapStore<K, V> {
    return new BucketMapStore(this.equivalence, this.builtIn, this.table.copy(cloneRecord))
  }
}
 
/**
 * Returns a store over `map`, a native `Map` compared with SameValueZero.
 *
 * @internal
 */
export function nativeMapStore<K, V>(map: Map<K, V>): MapStore<K, V> {
  return new NativeMapStore(map)
}
 
/**
 * Returns a new empty store for `equality`.
 *
 * @internal
 */
export function newMapStore<K, V>(equality: HashEquality<K>): MapStore<K, V> {
  switch (equality.kind) {
    case 'native':
      return new NativeMapStore(new Map<K, V>())
    case 'keyed':
      return new KeyedMapStore(equality.key, new Map<unknown, KeyedRecord<K, V>>())
    default:
      return new BucketMapStore(
        equality.equivalence,
        equality.builtIn,
        new BucketTable<BucketRecord<K, V>>(),
      )
  }
}