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 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 | 105x 105x 105x 105x 105x 1105542x 1105542x 1105542x 7247206x 7356900x 7356900x 7356900x 407x 407x 7356900x 7356900x 1927x 1927x 1927x 1927x 7356900x 8663060x 2601713x 202x 5x 1765929x 1765929x 1570969x 1570969x 1432566x 1432566x 1106286x 1053329x 1053329x 1005951x 5140749x 7331865x 7331865x 693x 543x 1540856x 1540856x 77548x 77548x 2199973x 2199973x 1246146x 1246146x 837568x 837568x 841644x 841644x 841644x 8311x 8311x 1961x 1961x 1961x 145304x 145304x 695x 695x 695x 695x 695x 144609x 144609x 144609x 144609x 144609x 347887x 347887x 347887x 12793x 12793x 12793x 335094x 335094x 335094x 13488x 13488x 15981x 14978x 14978x 14978x 14978x 303169x 303169x 303169x 303169x 303169x 303169x 303169x 303169x 342026x 342026x 39919x 39919x 302107x 302107x 302107x 228331x 228331x 170040x 120863x 120863x 120863x 85148x 85148x 85148x 332815x 332815x 332815x 332815x 48403x 48403x 48403x 48403x 48403x 48403x 48403x 48403x 284412x 284412x 284412x 181525x 133634x 133634x 133634x 133634x 133634x 84968x 31x 195314x 277284x 277284x 277284x 277284x 22528x 22528x 22528x 22528x 254756x 254756x 89005x 89005x 165751x 254756x 254756x 166112x 166112x 166112x 107715x 107715x 144969x 144969x 3661x 3661x 141308x 129986x 129986x 129986x 129986x 129986x 129986x 100650x 100650x 294221x 294221x 294221x 286912x 286912x 103459x 103459x 46988x 46988x 183453x 294221x 165810x 165810x 57297x 57297x 17643x 17643x 17643x 9409x 9409x 55533x 55533x 54886x 54886x 54886x 17730x 17730x 89658x 89658x 86209x 86209x 59744x 59744x 22546x 37198x 842659x 842659x 842163x 51718x 51718x 51125x 272131x 272131x 129224x 2554x 2554x 2554x 2554x 2554x 697x 697x 4089x 697x 1853x 1853x 8757x 8757x 123372x 82x 812073x 812073x 340394x 340394x 471679x 471679x 290851x 468987x 290851x 290851x 290851x 83708x 83708x 207143x 290851x 73426x 73426x 133717x 133717x 60659x 60659x 73058x 73058x 73058x 73058x 83708x 83708x 83708x 83708x 83708x 67767x 67767x 1013x 1013x 1013x 66754x 66754x 12748x 12748x 54006x 32933x 67767x 14343x 14343x 14343x 28817x 123561x 123561x 123561x 122545x 122545x 122545x 122545x 122545x 122545x 1016x 7587x 14202x 14202x 16477x 16477x 619x 619x 15858x 15858x 30060x 30060x 30060x 30060x 30060x 30060x 30060x 19025x 11033x 8629x 8629x 2404x 115211x 115211x 115211x 119401x 119401x 108959x 108959x 27933x 8314x 8314x 81026x 16455x 16455x 1511x 1511x 14944x 14944x 16614x 16614x 15384x 15384x 15384x 2460x 2460x 2460x 2460x 2460x 2460x 2460x 653x 653x 4005x 653x 4002x 4002x 4002x 4002x 650x 1807x 1807x 1807x 8679x 8679x 8679x 8679x 55213x 55213x 55213x 1799x 53414x 53414x 53414x 53414x 53414x 17623x 17623x 35791x 35791x 15139x 15139x 15139x 15132x 15132x 15132x 938x 14194x 14194x 14194x 14194x 14194x 5409x 5409x 8785x 8785x 8785x 8782x 8785x 48892x 48892x 48892x 48883x 48883x 48883x 1233x 47650x 47650x 47650x 47650x 47650x 47650x 48883x 48883x 48883x 48883x 13267x 34367x 10119x 24248x 47634x 14714x 14714x 14714x 14714x 14714x 14714x 697x 14017x 14017x 5304x 5304x 5304x 5304x 5304x 2932x 5303x 55181x 55181x 55181x 55181x 55181x 55181x 53946x 53946x 53946x 53946x 53946x 36604x 36604x 17342x 17342x 17342x 17342x 17342x 14666x 17341x 5902x 5902x 5902x 4785x 2200x 2200x 2585x 2585x 2585x 5902x 2567x 361x 2567x 6652x 6652x 360x 323x 323x 323x 323x 6292x 6292x 247x 244x 244x 247x 6045x 5620x 5620x 144942x 2831x 2831x 2622x 80412x 80412x 2246x 2246x 78166x 78166x 47002x 47002x 12628x 12628x 4040x 4040x 4040x 4040x 4028x 12628x 12628x 8355x 16943x 16021x 16021x 16021x 67081x 130116x 26782x 32214x 32214x 30330x 10045x 10041x 10041x 10041x 10041x 10041x 10041x 9349x 9349x 688774x 679190x 679190x 679190x 679190x 679190x 679190x 679190x 978x 978x 978x 978x 978x 978x 4195x 4195x 4195x 17x 4165x 948x 699x 1423x 699x 699x 15414x 15414x 4257x 4257x 2379x | // The skeleton of a linked hash map and its reversed view: every map and sequenced-map operation is
// written once, in the map's own order, over a shared state (a linked hash table, a change counter
// and the options) and a direction. The map walks the table from the front; the reversed view walks
// the same table from the back, so its front is the map's back.
//
// Each operation turns a `-0` key into `0`, derives the key's probe once, finds the mapping and only
// then changes the table. A new key goes to the walker's own back (the map's front for the reversed
// view); an access move always goes to the map's back and an eviction always takes from the map's
// front. A record held across a user callback is read again through `table.current`, because an
// access made by the callback can replace it.
//
// A map with SameValueZero keys and no access order starts in the native layout (`state.flat`, see
// flat-layout.ts): its mappings live directly in a native `Map`, and the calls a native `Map` can
// answer are answered from it, as one native call where they make one. Every other call reads
// `table`, which makes the linked hash table from the native `Map` first, once; the reversed view
// always does. In the native layout a mapping's handle is its key; after the switch it is its
// record. A call that runs user code finds its mapping again by key afterwards, in whatever layout
// the map is in by then.
//
// A map with SameValueZero keys in access order starts in the slotted layout instead (`state.slots`,
// see access-slots.ts). The map itself (not its reversed view) answers `get`, `has`, `set`,
// `put` (without `onEvict`), `delete`, `size` and `clear` from the slots, with the same results,
// moves, evictions and changes as the table gives; every other call reads `table`, which makes the
// table from the slots first, once. No record exists while the slots do, so nothing can hold one.
import { ConcurrentModificationError, NoSuchElementError } from '../../errors/errors'
import type { Cursor } from '../../interfaces/collection'
import type { SequencedCollection } from '../../interfaces/list'
import type { MapCollection, MapEntry } from '../../interfaces/map'
import type { SequencedMap } from '../../interfaces/sequenced-map'
import type { SequencedSet } from '../../interfaces/sequenced-set'
import { isBranded, MAP_COLLECTION_BRAND, MAP_ENTRY_BRAND, SEQUENCED_MAP_BRAND } from '../brand'
import { requireFunction } from '../checks'
import type { AccessSlots } from '../engines/access-slots'
import type { EvictionQueue } from '../engines/eviction-queue'
import {
ENTRIES,
type FlatLayout,
FlatMapIterator,
frontKey,
HANDLES,
isFront,
KEYS,
tableFromMap,
VALUES,
} from '../engines/flat-layout'
import { type HashEquality, normalise, Operation } from '../engines/hash-support'
import {
LinkedEntryIterator,
type LinkedHashTable,
LinkedKeyIterator,
type LinkedRecord,
LinkedValueIterator,
} from '../engines/linked-hash-table'
import { MISSING } from '../engines/map-stores'
import { equals, equalsSymbol, type HashFunction } from '../equality'
import { apply } from '../intrinsics'
import { LiveCursor } from '../iteration'
import { readPairs } from '../map-input'
import type { ChangeCounter } from '../revision'
import {
LinkedHashMapEntrySet,
LinkedHashMapKeySet,
LinkedHashMapValues,
} from '../views/linked-hash-map-views'
import { type EntrySource, MapEntryHandle } from '../views/map-entry'
import { AbstractMap } from './abstract-map'
type Entry<K, V> = LinkedRecord<K, V>
/** The kinds of `upsertFlat`. */
const COMPUTE = 0
const IF_PRESENT = 1
const MERGE = 2
const COMPUTED = 3
const GET_OR_INSERT = 4
/**
* What a linked hash map and its reversed view share: the layout (the native `Map` or the table),
* the change counter, the options read at construction and the eviction queue.
*
* @internal
*/
export interface LinkedMapState<K, V> extends FlatLayout<Map<K, V>, K, V> {
readonly changes: ChangeCounter
readonly equality: HashEquality<K>
readonly accessOrder: boolean
/** The most mappings kept, or `undefined` for no bound. */
readonly maxSize: number | undefined
readonly onEvict: ((value: V, key: K, map: never) => void) | undefined
/** The queue of evicted mappings, when both `maxSize` and `onEvict` are set. */
readonly queue: EvictionQueue<K, V> | undefined
/** The slotted layout of an access-ordered map; `undefined` once the table is made. */
slots: AccessSlots<K, V> | undefined
}
/**
* Base class of a linked hash map and its reversed view.
*
* Subclasses give the tag, the public owner, the map in the opposite order (`opposite`) and the
* public `reversed()`; the state and the direction are fixed at construction.
*
* @internal
*/
export abstract class AbstractLinkedMap<K, V>
extends AbstractMap<K, V>
implements SequencedMap<K, V>, EntrySource<K, V>
{
/** The state, shared by a map and its reversed view. */
readonly state: LinkedMapState<K, V>
/** Whether this map walks the table from the back. */
readonly fromBack: boolean
constructor(state: LinkedMapState<K, V>, fromBack: boolean) {
super(state.changes)
this.state = state
this.fromBack = fromBack
}
/** The table, shared by a map and its reversed view; made from the native layout on first use. */
get table(): LinkedHashTable<K, V> {
return this.promote().state.table as LinkedHashTable<K, V>
}
/**
* Leaves the native or slotted layout for good, if it is still in one: makes the table from the
* native `Map` or the slots (O(n), once). Returns this map.
*/
promote(): this {
const state = this.state
const slots = state.slots
if (slots !== undefined) {
state.table = slots.toTable(state.equality)
state.slots = undefined
}
const flat = state.flat
if (flat !== undefined) {
state.table = tableFromMap(flat, state.equality)
state.flat = undefined
state.front = undefined
state.frontKey = MISSING
}
return this
}
/** The native `Map` while the layout is native and this is the map, not its reversed view. */
private flatOf(): Map<K, V> | undefined {
return this.fromBack ? undefined : this.state.flat
}
/** The slots while the layout is slotted and this is the map, not its reversed view. */
private slotsOf(): AccessSlots<K, V> | undefined {
return this.fromBack ? undefined : this.state.slots
}
abstract override get owner(): SequencedMap<K, V>
/** The map over the same state in the opposite direction. */
abstract opposite(): AbstractLinkedMap<K, V>
abstract reversed(): SequencedMap<K, V>
/** Marks every map for `isMapCollection`, across loaded copies. */
get [MAP_COLLECTION_BRAND](): true {
return true
}
/** Marks every sequenced map, across loaded copies. */
get [SEQUENCED_MAP_BRAND](): true {
return true
}
get size(): number {
const flat = this.flatOf()
if (flat !== undefined) return flat.size
const slots = this.slotsOf()
return slots !== undefined ? slots.size : this.table.size
}
// ── Calls and handles ──
/**
* Runs `body` as one call on the map: with an eviction queue, the outermost call delivers the
* evictions when it ends.
*/
call<T>(body: () => T): T {
const queue = this.state.queue
return queue === undefined ? body() : queue.run(body)
}
/** Starts an operation whose errors name `where`. */
operation(where: string): Operation {
return new Operation(this.changes, where, 'map')
}
handles(_where?: string): Iterator<unknown> {
const flat = this.flatOf()
if (flat !== undefined) return new FlatMapIterator(this.state, flat, HANDLES)
return this.table.iterator(this.fromBack)
}
keyAt(handle: unknown): K {
return this.state.flat !== undefined ? (handle as K) : (handle as Entry<K, V>).key
}
valueAt(handle: unknown): V {
const flat = this.state.flat
return flat !== undefined ? (flat.get(handle as K) as V) : (handle as Entry<K, V>).value
}
keyHash(handle: unknown, hash: HashFunction): number {
if (this.state.flat !== undefined) return hash(handle)
return this.table.keyHash(handle as Entry<K, V>, hash)
}
/** The record of a key already normalised, or `undefined`. No access move. */
private lookup(key: K, where: string): Entry<K, V> | undefined {
const table = this.table
if (table.plain) return table.findPlain(key)
const op = this.operation(where)
return this.table.find(key, this.table.probe(key, op), op)
}
find(key: K, where: string): unknown {
const flat = this.flatOf()
if (flat !== undefined) return flat.has(key) ? normalise(key) : MISSING
const record = this.lookup(normalise(key), where)
return record === undefined ? MISSING : record
}
/** A new entry for a stored mapping. */
entryAt(handle: unknown): MapEntry<K, V> {
const probe = this.state.flat !== undefined ? handle : this.table.probeAt(handle as Entry<K, V>)
return new MapEntryHandle(this, handle, probe, this.valueAt(handle))
}
/**
* The handle standing for the mapping `handle` stood for: its current record while stored,
* otherwise a mapping with an equal key found by the stored probe, or `MISSING`. With
* SameValueZero keys both are the mapping of `key`, found in the current layout.
*/
relocate(handle: unknown, key: K, probe: unknown, where: string): unknown {
const state = this.state
// An entry exists only once the table does, so `state.table` is set here.
const table = state.table as LinkedHashTable<K, V>
if (state.flat !== undefined || table.plain) return this.find(key, where)
const current = table.current(handle as Entry<K, V>)
if (current !== undefined) return current
return this.call(() => {
const found = table.find(key, probe, this.operation(where))
return found === undefined ? MISSING : found
})
}
/** Writes `value` to a stored mapping, records the change and returns the value it replaced. */
overwrite(handle: unknown, value: V): V {
const flat = this.state.flat
if (flat !== undefined) {
const old = flat.get(handle as K) as V
flat.set(handle as K, value)
this.changes.replaced()
this.noteFront(handle as K, value)
return old
}
const record = handle as Entry<K, V>
const old = record.value
record.value = value
this.changes.replaced()
return old
}
// ── The native layout ──
/**
* Sets a mapping in the native layout with one native call: a new key is structural and evicts
* past `maxSize`, a present one is a written value.
*/
private setFlat(flat: Map<K, V>, key: K, value: V): void {
const size = flat.size
flat.set(key, value)
if (flat.size === size) {
this.changes.replaced()
this.noteFront(key, value)
return
}
this.changes.structural()
const maxSize = this.state.maxSize
if (maxSize !== undefined && flat.size > maxSize) this.evictFlat(flat, maxSize)
}
/** Keeps the front reader's value current where an eviction callback will be given it. */
private noteFront(key: K, value: V): void {
const state = this.state
if (state.queue !== undefined && isFront(state, key)) state.frontValue = value
}
/** Removes a present or absent key in the native layout with one native call. */
private deleteFlat(flat: Map<K, V>, key: K): boolean {
if (!flat.delete(key)) return false
const state = this.state
if (isFront(state, key)) state.frontKey = MISSING
this.changes.structural()
return true
}
/** Removes mappings from the front until `maxSize` holds: one `delete` each, no lookup. */
private evictFlat(flat: Map<K, V>, maxSize: number): void {
const state = this.state
const queue = state.queue
while (flat.size > maxSize) {
const key = frontKey(state, flat, true) as K
flat.delete(key)
state.frontKey = MISSING
this.changes.structural()
if (queue !== undefined) queue.push(key, state.frontValue as V)
}
}
/** `setFlat` as one call on the map, so evictions are delivered when it ends. */
private setFlatCall(flat: Map<K, V>, key: K, value: V): void {
const queue = this.state.queue
if (queue === undefined) {
this.setFlat(flat, key, value)
return
}
queue.enter()
this.setFlat(flat, key, value)
queue.leave(false)
}
// ── Changes ──
/** In access order, moves a present record to the map's back. */
private touch(record: Entry<K, V>): void {
// A record exists, so the layout is linked.
const state = this.state
if (state.accessOrder && (state.table as LinkedHashTable<K, V>).access(record)) {
this.changes.replaced()
}
}
/** Writes the value of a present record as a write of the key: an access in access order. */
private write(record: Entry<K, V>, value: V): V {
const old = this.overwrite(record, value)
this.touch(record)
return old
}
/** Removes a stored record and returns its value. */
removeRecord(record: Entry<K, V>): V {
this.table.remove(record)
this.changes.structural()
return record.value
}
/**
* Links a new mapping for a key known to be absent at the map's front or back, then evicts from
* the map's front, never the record just made, until the bound holds.
*/
private insert(key: K, probe: unknown, value: V, front: boolean): void {
const state = this.state
const table = this.table
const { maxSize, queue } = state
if (maxSize !== undefined && !front && table.size >= maxSize && table.recyclable) {
// Full: the first mapping is evicted and its record holds the new one, at the back. The
// changes and the eviction are recorded as for an insertion followed by an eviction.
const victim = table.head.next
const evictedKey = victim.key
const evictedValue = victim.value
table.recycleFirst(key, value)
this.changes.structural()
this.changes.structural()
if (queue !== undefined) queue.push(evictedKey, evictedValue)
return
}
const made = table.insert(key, probe, value, front)
this.changes.structural()
if (maxSize === undefined) return
while (table.size > maxSize) {
let victim = table.head.next
if (victim === made) victim = victim.next
table.remove(victim)
this.changes.structural()
if (queue !== undefined) queue.push(victim.key, victim.value)
}
}
/** 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`)
}
}
/**
* Whether writes may take the plain path: lookups run no user code and no eviction queue has to
* wrap the write.
*/
private get plainWrites(): boolean {
return this.table.plain && this.state.queue === undefined
}
/**
* `writeKey` in the slotted layout, as `writePlain` on the table: the same move, insertion,
* eviction (the first mapping's slot holds the new one) and changes. Runs no user code; with an
* eviction queue, the caller makes it one call.
*/
private writeSlots(slots: AccessSlots<K, V>, key: K, value: V): unknown {
const normalised = normalise(key)
const slot = slots.find(normalised)
const changes = this.changes
if (slot !== undefined) {
const old = slots.valueAt(slot)
changes.replaced()
if (slots.write(slot, value)) changes.replaced()
return old
}
const { maxSize, queue } = this.state
if (maxSize !== undefined && slots.size >= maxSize) {
// Recorded as an insertion followed by an eviction.
slots.recycleFirst(normalised, value, queue)
changes.structural()
} else slots.add(normalised, value)
changes.structural()
return MISSING
}
/**
* `writeKey` on a plain table: one native read, then at most one native write (plus one removal
* per evicted mapping). Runs no user code; with an eviction queue, the caller makes it one call.
*/
private writePlain(key: K, value: V): unknown {
const normalised = normalise(key)
const found = (this.state.table as LinkedHashTable<K, V>).findPlain(normalised)
if (found !== undefined) return this.write(found, value)
this.insert(normalised, normalised, value, this.fromBack)
return MISSING
}
/**
* Maps `key` to `value`; returns the previous value, or `MISSING` when the key was absent
* (`undefined` in the native layout, where no caller reads it).
*/
writeKey(key: K, value: V, where: string): unknown {
const flat = this.flatOf()
if (flat !== undefined) {
this.setFlat(flat, key, value)
return undefined
}
if (this.plainWrites) return this.writePlain(key, value)
const op = this.operation(where)
const normalised = normalise(key)
const table = this.table
const probe = table.probe(normalised, op)
const found = table.find(normalised, probe, op)
if (found !== undefined) return this.write(found, value)
this.insert(normalised, probe, value, this.fromBack)
return MISSING
}
// ── Reading ──
override get(key: K): V | undefined {
const state = this.state
const flat = state.flat
if (flat !== undefined && !this.fromBack) return flat.get(key)
const slots = state.slots
if (slots !== undefined && !this.fromBack) {
const slot = slots.find(normalise(key))
if (slot === undefined) return undefined
if (slots.access(slot)) this.changes.replaced()
return slots.valueAt(slot)
}
const table = state.table !== undefined ? state.table : this.table
if (table.plain) {
// No user code runs and a read never evicts, so no eviction queue has to wrap it: read the
// record directly.
const record = table.findPlain(normalise(key))
if (record === undefined) return undefined
this.touch(record)
return record.value
}
return this.call(() => {
const record = this.lookup(normalise(key), this.at('get'))
if (record === undefined) return undefined
this.touch(record)
return record.value
})
}
override getOrDefault<D>(key: K, fallback: D): V | D {
const flat = this.flatOf()
if (flat !== undefined) return flat.has(key) ? (flat.get(key) as V) : fallback
return this.call(() => {
const record = this.lookup(normalise(key), this.at('getOrDefault'))
if (record === undefined) return fallback
this.touch(record)
return record.value
})
}
override has(key: K): boolean {
const flat = this.flatOf()
if (flat !== undefined) return flat.has(key)
const slots = this.slotsOf()
if (slots !== undefined) return slots.find(normalise(key)) !== undefined
const table = this.table
if (table.plain && this.state.queue === undefined)
return table.findPlain(normalise(key)) !== undefined
return this.call(() => this.lookup(normalise(key), this.at('has')) !== undefined)
}
// ── Iterating ──
override keys(): IterableIterator<K> {
const flat = this.flatOf()
if (flat !== undefined) return new FlatMapIterator<K>(this.state, flat, KEYS)
return new LinkedKeyIterator(this.table.iterator(this.fromBack))
}
override values(): IterableIterator<V> {
const flat = this.flatOf()
if (flat !== undefined) return new FlatMapIterator<V>(this.state, flat, VALUES)
return new LinkedValueIterator(this.table.iterator(this.fromBack))
}
override entries(): IterableIterator<[K, V]> {
const flat = this.flatOf()
if (flat !== undefined) return new FlatMapIterator<[K, V]>(this.state, flat, ENTRIES)
return new LinkedEntryIterator(this.table.iterator(this.fromBack))
}
override forEach(
action: (value: V, key: K, map: MapCollection<K, V>) => void,
thisArg?: unknown,
): void {
this.call(() => {
requireFunction(action, this.at('forEach'), 'action')
const owner = this.owner
const flat = this.flatOf()
if (flat !== undefined) {
// One native iterator over the entries; it hands over to the records if a callback
// switches the layout.
const pairs = new FlatMapIterator<[K, V]>(this.state, flat, ENTRIES)
for (let step = pairs.next(); step.done !== true; step = pairs.next()) {
apply(action, thisArg, [step.value[1], step.value[0], owner])
}
return
}
const records = this.table.iterator(this.fromBack)
for (let step = records.next(); step.done !== true; step = records.next()) {
const record = step.value
apply(action, thisArg, [record.value, record.key, owner])
}
})
}
override equals(other: unknown): boolean {
return this.call(() => super.equals(other))
}
[equalsSymbol](other: unknown): boolean {
return this.equals(other)
}
// ── Writing ──
set(key: K, value: V): this {
const flat = this.flatOf()
if (flat !== undefined) {
this.setFlatCall(flat, key, value)
return this
}
// The slotted layout without an eviction queue writes directly: the shortest path for the
// engine to inline.
const slots = this.slotsOf()
if (slots !== undefined && this.state.queue === undefined) this.writeSlots(slots, key, value)
else this.setLinked(key, value)
return this
}
/** `set` in the linked layout. */
private setLinked(key: K, value: V): void {
const state = this.state
const slots = this.slotsOf()
if (slots !== undefined) {
this.setSlots(slots, key, value)
return
}
const table = state.table !== undefined ? state.table : this.table
if (!table.plain) {
this.call(() => this.writeKey(key, value, this.at('set')))
return
}
const queue = state.queue
if (queue === undefined) {
this.writePlain(key, value)
return
}
// `EvictionQueue.run` without a closure: the evictions are delivered when the call ends.
queue.enter()
try {
this.writePlain(key, value)
} catch (error) {
queue.leave(true)
throw error
}
queue.leave(false)
}
/** `set` in the slotted layout with an eviction queue, as one call: evictions are delivered when it ends. */
private setSlots(slots: AccessSlots<K, V>, key: K, value: V): void {
const queue = this.state.queue as EvictionQueue<K, V>
queue.enter()
try {
this.writeSlots(slots, key, value)
} catch (error) {
queue.leave(true)
throw error
}
queue.leave(false)
}
put(key: K, value: V): V | undefined {
const flat = this.flatOf()
if (flat !== undefined) {
const previous = flat.get(key)
this.setFlatCall(flat, key, value)
return previous
}
const slots = this.slotsOf()
if (slots !== undefined && this.state.queue === undefined) {
const previous = this.writeSlots(slots, key, value)
return previous === MISSING ? undefined : (previous as V)
}
const old = this.plainWrites
? this.writePlain(key, value)
: this.call(() => this.writeKey(key, value, this.at('put')))
return old === MISSING ? undefined : (old as V)
}
putAll(entries: Iterable<readonly [K, V] | MapEntry<K, V>>): void {
const where = this.at('putAll')
this.call(() => {
const pairs = readPairs<K, V>(entries, where)
for (const pair of pairs) this.writeKey(pair[0], pair[1], where)
})
}
/** Sets each checked pair in order as one call on the map, naming `where` in errors. */
build(pairs: Array<[K, V]>, where: string): void {
const state = this.state
const flat = this.flatOf()
if (flat !== undefined && flat.size === 0 && state.maxSize === undefined) {
// A new map: one native construction, counted as one set per pair.
const built = new Map<K, V>(pairs)
state.flat = built
const changes = this.changes
changes.revision += pairs.length
changes.structure += built.size
return
}
this.call(() => {
for (const pair of pairs) this.writeKey(pair[0], pair[1], where)
})
}
putFirst(key: K, value: V): this {
this.call(() => this.place(key, value, true, this.at('putFirst')))
return this
}
putLast(key: K, value: V): this {
const flat = this.flatOf()
if (flat !== undefined && !flat.has(key)) {
this.setFlatCall(flat, key, value)
return this
}
this.call(() => this.place(key, value, false, this.at('putLast')))
return this
}
/** Inserts or moves the mapping of `key` to this map's front (`ownFront`) or back. */
private place(key: K, value: V, ownFront: boolean, where: string): void {
const op = this.operation(where)
const normalised = normalise(key)
const table = this.table
const probe = table.probe(normalised, op)
const found = table.find(normalised, probe, op)
const front = ownFront !== this.fromBack
if (found === undefined) {
this.insert(normalised, probe, value, front)
} else if (table.move(found, front)) {
;(table.current(found) as Entry<K, V>).value = value
this.changes.structural()
} else {
this.overwrite(found, value)
}
}
/** Removes the mapping of `key`; returns its value, or `MISSING`. */
removeKey(key: K, where: string): unknown {
return this.call(() => {
const record = this.lookup(normalise(key), where)
return record === undefined ? MISSING : this.removeRecord(record)
})
}
delete(key: K): boolean {
const flat = this.flatOf()
if (flat !== undefined) return this.deleteFlat(flat, key)
const slots = this.slotsOf()
if (slots !== undefined) {
if (!slots.remove(normalise(key))) return false
this.changes.structural()
return true
}
return this.removeKey(key, this.at('delete')) !== MISSING
}
remove(key: K): V | undefined {
const flat = this.flatOf()
if (flat !== undefined) {
const value = flat.get(key)
return this.deleteFlat(flat, key) ? value : undefined
}
const removed = this.removeKey(key, this.at('remove'))
return removed === MISSING ? undefined : (removed as V)
}
replace(key: K, value: V): V | undefined {
const flat = this.flatOf()
if (flat !== undefined) return flat.has(key) ? this.overwrite(key, value) : undefined
return this.call(() => {
const record = this.lookup(normalise(key), this.at('replace'))
return record === undefined ? undefined : this.write(record, value)
})
}
replaceAll(fn: (value: V, key: K, map: MapCollection<K, V>) => V): void {
const where = this.at('replaceAll')
requireFunction(fn, where, 'fn')
this.call(() => {
const owner = this.owner
const start = this.changes.structure
const flat = this.flatOf()
if (flat !== undefined) {
// Each mapping is read and written by key, in whatever layout the callbacks leave the map.
const keys: K[] = []
const all = flat.keys()
for (let step = all.next(); step.done !== true; step = all.next()) keys.push(step.value)
for (let i = 0; i < keys.length; i++) {
const key = keys[i] as K
const result = apply(fn, undefined, [this.get(key), key, owner]) as V
this.checkCallback(start, where)
this.set(key, result)
}
return
}
const table = this.table
const records = table.records(this.fromBack)
for (let i = 0; i < records.length; i++) {
const record = table.current(records[i] as Entry<K, V>) as Entry<K, V>
const result = apply(fn, undefined, [record.value, record.key, owner]) as V
this.checkCallback(start, where)
this.overwrite(table.current(record) as Entry<K, V>, result)
}
})
}
getOrInsert(key: K, value: V): V {
return this.call(() => {
const flat = this.flatOf()
if (flat !== undefined)
return this.upsertFlat(flat, key, GET_OR_INSERT, value, undefined, '') as V
const op = this.operation(this.at('getOrInsert'))
const normalised = normalise(key)
const probe = this.table.probe(normalised, op)
const found = this.table.find(normalised, probe, op)
if (found !== undefined) {
this.touch(found)
return found.value
}
this.insert(normalised, probe, value, this.fromBack)
return value
})
}
getOrInsertComputed(key: K, fn: (key: K) => V): V {
const where = this.at('getOrInsertComputed')
requireFunction(fn, where, 'fn')
return this.call(() => {
const normalised = normalise(key)
const flat = this.flatOf()
if (flat !== undefined)
return this.upsertFlat(flat, normalised, COMPUTED, undefined, fn, where) as V
const table = this.table
const op = this.operation(where)
const probe = table.probe(normalised, op)
const found = table.find(normalised, probe, op)
if (found !== undefined) {
this.touch(found)
return found.value
}
const value = apply(fn, undefined, [normalised]) as V
// The callback may have changed the map: look again, with the probe already derived.
const now = table.find(normalised, probe, this.operation(where))
if (now !== undefined) this.write(now, value)
else this.insert(normalised, probe, value, this.fromBack)
return value
})
}
compute(
key: K,
fn: (value: V | undefined, key: K, map: MapCollection<K, V>) => V | undefined,
): V | undefined {
const where = this.at('compute')
requireFunction(fn, where, 'fn')
return this.call(() => {
const normalised = normalise(key)
const flat = this.flatOf()
if (flat !== undefined)
return this.upsertFlat(flat, normalised, COMPUTE, undefined, fn, where)
const table = this.table
const op = this.operation(where)
const probe = table.probe(normalised, op)
const found = table.find(normalised, probe, op)
const start = this.changes.structure
const old = found === undefined ? undefined : found.value
const result = apply(fn, undefined, [old, normalised, this.owner]) as V | undefined
this.checkCallback(start, where)
const record = found === undefined ? undefined : table.current(found)
if (result === undefined) {
if (record !== undefined) this.removeRecord(record)
} else if (record !== undefined) {
this.write(record, result)
} else {
this.insert(normalised, probe, result, this.fromBack)
}
return result
})
}
computeIfPresent(
key: K,
fn: (value: V, key: K, map: MapCollection<K, V>) => V | undefined,
): V | undefined {
const where = this.at('computeIfPresent')
requireFunction(fn, where, 'fn')
return this.call(() => {
const normalised = normalise(key)
const flat = this.flatOf()
if (flat !== undefined)
return this.upsertFlat(flat, normalised, IF_PRESENT, undefined, fn, where)
const found = this.lookup(normalised, where)
if (found === undefined) return undefined
const start = this.changes.structure
const result = apply(fn, undefined, [found.value, normalised, this.owner]) as V | undefined
this.checkCallback(start, where)
const record = this.table.current(found) as Entry<K, V>
if (result === undefined) this.removeRecord(record)
else this.write(record, 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 = this.at('merge')
requireFunction(fn, where, 'fn')
return this.call(() => {
const normalised = normalise(key)
const flat = this.flatOf()
if (flat !== undefined) return this.upsertFlat(flat, normalised, MERGE, value, fn, where)
const table = this.table
const op = this.operation(where)
const probe = table.probe(normalised, op)
const found = table.find(normalised, probe, op)
if (found === undefined) {
this.insert(normalised, probe, value, this.fromBack)
return value
}
const start = this.changes.structure
const result = apply(fn, undefined, [found.value, value, normalised, this.owner]) as
| V
| undefined
this.checkCallback(start, where)
const record = table.current(found) as Entry<K, V>
if (result === undefined) this.removeRecord(record)
else this.write(record, result)
return result
})
}
/**
* `compute`, `computeIfPresent`, `merge`, `getOrInsert` or `getOrInsertComputed` (`kind`) in the
* native layout, as one call on the map. The callback's result is applied by key in the layout
* the callback leaves the map in: `undefined` removes the mapping found before it ran (except for
* `getOrInsertComputed`), anything else writes or inserts it.
*/
private upsertFlat(
flat: Map<K, V>,
key: K,
kind: number,
value: V | undefined,
fn: ((...args: never[]) => unknown) | undefined,
where: string,
): V | undefined {
const old = flat.get(key)
const present = old !== undefined || flat.has(key)
if (present ? kind >= COMPUTED : kind === IF_PRESENT) return old
if (!present && kind !== COMPUTE && kind !== COMPUTED) {
this.setFlat(flat, key, value as V)
return value
}
const start = this.changes.structure
const owner = this.owner
const result = apply(
fn as (...args: never[]) => unknown,
undefined,
kind === COMPUTED ? [key] : kind === MERGE ? [old, value, key, owner] : [old, key, owner],
) as V | undefined
if (kind !== COMPUTED) this.checkCallback(start, where)
if (result !== undefined || kind === COMPUTED) this.writeKey(key, result as V, where)
else if (present) this.remove(key)
return result
}
clear(): void {
const flat = this.flatOf()
if (flat !== undefined) {
if (flat.size === 0) return
flat.clear()
this.state.frontKey = MISSING
this.changes.structural()
return
}
const slots = this.slotsOf()
if (slots !== undefined) {
if (slots.size > 0) {
slots.clear()
this.changes.structural()
}
return
}
if (this.table.size === 0) return
this.table.clear()
this.changes.structural()
}
// ── Ends ──
/** The record at this map's front (`back` false) or back, or `undefined` when empty. */
endOf(back: boolean): Entry<K, V> | undefined {
return this.table.first(back !== this.fromBack)
}
/** The record at this map's front or back, or `NoSuchElementError` naming `where`. */
endRecord(back: boolean, where: string, noun: string): Entry<K, V> {
const record = this.endOf(back)
if (record === undefined) throw new NoSuchElementError(`${where}: the ${noun} is empty`)
return record
}
firstEntry(): MapEntry<K, V> | undefined {
const flat = this.flatOf()
if (flat !== undefined) {
const key = frontKey(this.state, flat, true)
return key === MISSING ? undefined : this.entryAt(key)
}
const record = this.endOf(false)
return record === undefined ? undefined : this.entryAt(record)
}
lastEntry(): MapEntry<K, V> | undefined {
const record = this.endOf(true)
return record === undefined ? undefined : this.entryAt(record)
}
pollFirstEntry(): MapEntry<K, V> | undefined {
const flat = this.flatOf()
if (flat === undefined) return this.poll(this.endOf(false))
const state = this.state
// A fresh step of the front reader gives the value with the key.
const fresh = state.frontKey === MISSING
const key = frontKey(state, flat, true) as K
if (key === MISSING) return undefined
const entry = new MapEntryHandle(
this,
key,
key,
(fresh ? state.frontValue : flat.get(key)) as V,
)
this.deleteFlat(flat, key)
return entry
}
pollLastEntry(): MapEntry<K, V> | undefined {
return this.poll(this.endOf(true))
}
/** Makes the entry first, so it reads the value the mapping had, then removes the record. */
private poll(record: Entry<K, V> | undefined): MapEntry<K, V> | undefined {
if (record === undefined) return undefined
const entry = this.entryAt(record)
this.removeRecord(record)
return entry
}
// ── Views ──
keySet(): SequencedSet<K> {
return new LinkedHashMapKeySet(this)
}
entrySet(): SequencedSet<MapEntry<K, V>> {
return new LinkedHashMapEntrySet(this)
}
valueCollection(): SequencedCollection<V> {
return new LinkedHashMapValues(this)
}
/** Whether a key equal to `key` is present, for a view's errors naming `where`. No access. */
hasKey(key: K, where: string): boolean {
const flat = this.flatOf()
if (flat !== undefined) return flat.has(key)
return this.call(() => this.lookup(normalise(key), where) !== undefined)
}
/**
* The current record of the mapping `value` stands for, or `undefined` when it is not a map entry
* whose key is present with a value equal under `equals`. No access.
*/
locate(value: unknown, where: string): Entry<K, V> | undefined {
if (!isBranded(value, MAP_ENTRY_BRAND)) return undefined
const entry = value as MapEntry<K, V>
const key = entry.key
const expected = entry.value
return this.call(() => {
const record = this.lookup(normalise(key), where)
if (record === undefined) return undefined
const op = this.operation(where)
return op.after(equals(record.value, expected)) ? this.table.current(record) : undefined
})
}
/**
* Whether `value` is a map entry whose key is present with a value equal under `equals`, as
* `locate` decides it, in either layout. No access.
*/
holdsEntry(value: unknown, where: string): boolean {
if (this.flatOf() === undefined) return this.locate(value, where) !== undefined
Iif (!isBranded(value, MAP_ENTRY_BRAND)) return false
const entry = value as MapEntry<K, V>
const key = entry.key
const expected = entry.value
return this.call(() => {
const handle = this.find(key, where)
return (
handle !== MISSING && this.operation(where).after(equals(this.valueAt(handle), expected))
)
})
}
/**
* Decides every mapping in this map's order first (user code runs only here), then removes the
* decided ones by mapping. A structural change while deciding throws
* `ConcurrentModificationError` naming `where` and removes nothing.
*/
removeDecidedRecords(
decide: (record: Entry<K, V>, index: number) => boolean,
where: string,
): boolean {
return this.call(() => {
const table = this.table
const records = table.records(this.fromBack)
const start = this.changes.structure
const doomed: Entry<K, V>[] = []
for (let i = 0; i < records.length; i++) {
const record = records[i] as Entry<K, V>
const remove = decide(table.current(record) as Entry<K, V>, i)
if (this.changes.structure !== start) {
throw new ConcurrentModificationError(
`${where}: the collection was changed while deciding`,
)
}
if (remove) doomed.push(record)
}
if (doomed.length === 0) return false
for (let i = 0; i < doomed.length; i++) {
table.remove(table.current(doomed[i] as Entry<K, V>) as Entry<K, V>)
}
this.changes.structural()
return true
})
}
/** A live cursor over the records in this map's order, projected; removal by mapping. */
cursor<E>(project: (record: Entry<K, V>) => E, where: string): Cursor<E> {
const table = this.table
return new LiveCursor<E, Entry<K, V>>(
table.iterator(this.fromBack),
(record) => {
const current = table.current(record)
if (current !== undefined) this.removeRecord(current)
else this.removeKey(record.key, where)
},
where,
project,
)
}
}
|