-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathdict.lisp
More file actions
2932 lines (2517 loc) · 137 KB
/
dict.lisp
File metadata and controls
2932 lines (2517 loc) · 137 KB
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
;;;; DICTs, a.k.a. Hash Array-Mapped Tries
;;; HAMTs are introduced by Phil Bagwell in the paper "Ideal Hash Trees," Nov 2001,
;;; https://lampwww.epfl.ch/papers/idealhashtrees.pdf . This implementation makes a few simplifications to
;;; Bagwell's data structure:
;;; - The root table is a node like any other, with a maximum radix of +BRACH-RATE+.
;;; - We never rehash conflicting keys. If two keys hash to the same index, we construct a CONFLICT-NODE, for
;;; which lookup and insertion do a linear scan.
;;; - We use the low bits of the hash to index into the root table, and progressively higher bits to index
;;; into later nodes, where Bagwell does the opposite. This simplifies our traversal, and has the convenient
;;; side effect that we don't need to check if we've run out of bits in the hash; after that point, LDB will
;;; always return all-zeros or all-ones, depending on sign.
(uiop:define-package :immutable/dict
(:import-from :alexandria
#:array-index #:array-length #:define-constant #:when-let #:once-only #:with-gensyms #:if-let)
(:import-from #:immutable/%atomic
#:define-atomic-counter
#:increment-atomic-counter)
(:shadow #:get #:remove #:do #:union)
(:use :cl :iterate :immutable/%generator :immutable/%simple-vector-utils)
(:import-from :immutable/hash
#:==
#:hash
#:unsigned-fixnum)
(:export
;; Type definitions.
#:dict
#:transient
;; Converting between dicts and transients.
#:transient #:persistent!
;; Stale transient error, when attempting to mutate a transient that has already been made `persistent!'.
#:stale-transient
#:stale-transient-operation
#:stale-transient-transient
;; Unknown hash function error.
#:no-hash-function-for-test
#:no-hash-function-for-test-function
#:no-hash-function-for-test-known-hash-functions
;; Invalid hash table test error, for `to-hash-table'.
#:invalid-hash-table-test
#:invalid-hash-table-test-test
;; Malformed plist and alist errors, for `from-alist', `insert-alist' and plist equivalents.
#:malformed-plist
#:malformed-plist-plist
#:malformed-plist-operator
#:malformed-alist
#:malformed-alist-alist
#:malformed-alist-operator
;; Error when converting a collection would cause a collision due to different hash/test functions.
#:convert-overwrite
#:convert-overwrite-key
#:convert-overwrite-old-value
#:convert-overwrite-new-value
#:convert-overwrite-operation
#:convert-overwrite-source
;; Error on unexpected conflict during rehashes.
#:rehash-conflict
#:rehash-conflict-key
#:rehash-conflict-value-1
#:rehash-conflict-value-2
#:rehash-conflict-source
#:rehash-conflict-new-test-function
#:rehash-conflict-new-hash-function
;; Reading properties of dicts and transients.
#:size #:test-function #:hash-function
;; Registering new test-function/hash-function pairs.
#:define-test-hash-function
;; GETHASH analogue.
#:get
;; (SETF GETHASH) analogue.
#:insert #:insert!
;; Specifying the behavior of insertion when a dict already contains a mapping for the given key.
#:merge-function #:new-value #:old-value
;; REMHASH analogue.
#:remove #:remove!
;; MAKE-HASH-TABLE analogue to construct an empty dict.
#:empty #:empty-transient
;; Batched insertions and removals.
#:insert-plist
#:insert-alist
#:insert-multiple
#:remove-multiple
;; Iteration over dicts.
#:for-each
#:map-values
#:do
;; Combining dicts.
#:union
;; Changing hash and test function of a dict.
#:rehash
;; Converting to/from CL mapping collections.
#:from-hash-table #:to-hash-table
#:from-alist #:to-alist
#:from-plist #:to-plist))
(in-package :immutable/dict)
#+immutable-dict-debug
(declaim (optimize (speed 1) (safety 3) (space 1) (debug 3) (compilation-speed 0)))
#-immutable-dict-debug
(declaim (optimize (speed 3) (safety 1) (space 1) (debug 1) (compilation-speed 0)))
;;; Early type definitions and whatnot
(eval-when (:compile-toplevel :load-toplevel)
(declaim (type array-length +branch-rate+))
(defconstant +branch-rate+ 32
"The maximum of child nodes contained in each node of a DICT.")
(declaim (type (and fixnum unsigned-byte) +node-index-bits+))
(defconstant +node-index-bits+ (floor (log +branch-rate+ 2))
"The number of bits used to index into a node of a DICT.")
(declaim (type (and fixnum unsigned-byte) +max-shift+))
(defconstant +max-shift+ (1- (floor (log most-positive-fixnum +branch-rate+)))))
(deftype size ()
"The size of a `dict', in number of entries."
'unsigned-fixnum)
(deftype hash-function ()
'(function (t) (values fixnum &optional)))
(deftype test-function ()
'(function (t t) (values boolean &optional)))
(deftype bitmap ()
"The bitmap held by a `hash-node' which marks the indices which hold children."
`(unsigned-byte ,+branch-rate+))
(deftype shift ()
"A bit offset, in units of +NODE-INDEX-BITS+, into a hash.
When extracting a `hash-node-logical-index' from a `hash', we use the +NODE-INDEX-BITS+ starting at (* SHIFT
+NODE-INDEX-BITS+). The SHIFT is the current node's depth in the trie."
`(integer 0 ,+max-shift+))
(deftype hash-node-logical-index ()
"An index into a `hash-node'."
`(integer 0 ,+branch-rate+))
(deftype transient-id ()
'(or null fixnum))
(define-atomic-counter current-transient-id 0
"Atomic counter used as a global resource for transient ids.
Nodes and `transient's hold a (nullable) fixnum transient-id. Transient operations are allowed to mutate a
node if and only if the node's id is non-null and matches the enclosing transient's id.
When creating a transient, this counter will be incremented with `increment-atomic-counter', and the new value
will be used as the new transient's id.")
(declaim (ftype (function () (values fixnum &optional))
get-transient-id))
(defun get-transient-id ()
(increment-atomic-counter current-transient-id))
;;; struct definitions for node variants
;;; HASH-NODE
;;
;; A branching node in a `dict' for elements with distinct hash parts.
;;
;; Each `hash-node' is implicitly associated with a `shift', determined by that node's depth in the trie, which
;; determines which bits of the `hash' are used as its indices.
;;
;; The ENTRIES is a sparse sequence of child nodes, and the BITMAP maps hash-part indices to true-indices into
;; the ENTRIES vector. (length ENTRIES) is always equal to (logcount BITMAP).
;;
;; The terminology for HASH-NODE indices is a little wonky, because there are four different kinds of indices:
;; - Logical indices, which are in the range 0 -- 32, are extracted from hashes. These are sparse, and are
;; mapped to dense counted indices by the hash-node's bitmap. Each corresponds to a two-element pair, which
;; may be:
;; - A key and a value.
;; - A hash and a `conflict-node'.
;; - A logical-index-bitmap and a child `hash-node'.
;; - Counted indices, which are in the range 0 -- 32, are dense. Transforming a logical index into a counted
;; index involves inspecting the hash-node's bitmap and counting the number of one bits below the logical
;; index. This is done by `hash-node-logical-index-to-counted-index'.
;; - Paired indices are counted indices multiplied by two. The paired index 2n contains the key or sub-bitmap
;; of the child at conted index n, and the paired index (2n + 1) contains the value or child node.
;; - True indices are paired indices added to some automatically-computed offset to skip the hash-node's
;; named slots. Paired indices are transformed to true indices by `hash-node-paired-index-to-true-index'.
(define-vector-struct hash-node
(:max-length #.(* +branch-rate+ 2)
:length hash-node-paired-count
:ref hash-node-paired-ref
:logical-index-to-true-index hash-node-paired-index-to-true-index
:logical-length-to-true-length hash-node-paired-length-to-true-length
:constructor %make-hash-node
:zero-index +hash-node-zero+)
(transient-id :type transient-id
:initform nil)
;; The CHILD-IS-ENTRY-P and CHILD-IS-CONFLICT-P bitmaps map counted-indices to whether the associated child
;; is a key/value pair or a hash/conflict-node pair. These are mutually exclusive. If both bits are 0, the
;; associated child is either not present, or is a logical-index-bitmap/hash-node pair.
(child-is-entry-p :type bitmap
:initform (error "Supply :CHILD-IS-ENTRY-P to %MAKE-HASH-NODE"))
(child-is-conflict-p :type bitmap
:initform (error "Supply :CHILD-IS-CONFLICT-P to %MAKE-HASH-NODE")))
(declaim (ftype (function (hash-node) (values array-length &optional))
hash-node-logical-count)
;; Trivial enough that call overhead is meaningful, so always inline.
(inline hash-node-logical-count))
(defun hash-node-logical-count (hash-node)
(ash (hash-node-paired-count hash-node) -1))
;;; CONFLICT-NODE
;;
;; A leaf-ish node in a `dict' for distinct elements with the same hash.
;;
;; The ENTRIES will be a vector of key/value pairs, all of which have keys with the same hash, but which are
;; not equal under the TEST-FUNCTION. Lookup in a `conflict-node' is a linear search of its ENTRIES.
;;
;; A `conflict-node' will always contain at least two key/value pairs.
;;
;; CONFLICT-NODE indices are not quite as wonky as those for hash-nodes, but still have three levels:
;; - Logical indices start from 0. Each logical index corresponds to a key/value pair.
;; - Paired indices are logical indices multiplied by two. The paired index 2n contains the key of the entry
;; at logical index n, and the paired index (2n + 1) contains the value.
;; - True indices are paired indices added to some automatically-computed offset to skip the hash-node's named
;; slots. Paired indices are transformed to true indices by `conflict-node-paired-index-to-true-index'.
(define-vector-struct conflict-node
(:length conflict-node-paired-count
:ref conflict-node-paired-ref
:logical-index-to-true-index conflict-node-paired-index-to-true-index
:logical-length-to-true-length conflict-node-paired-length-to-true-length
:constructor %make-conflict-node
:zero-index +conflict-node-zero+)
(transient-id :type transient-id
:initform nil))
(declaim (ftype (function (conflict-node) (values array-length &optional))
conflict-node-logical-length)
;; Trivial enough that call overhead is meaningful, so always inline.
(inline conflict-node-logical-length))
(defun conflict-node-logical-length (conflict-node)
(ash (conflict-node-paired-count conflict-node) -1))
(deftype node ()
'(or hash-node conflict-node))
(deftype child-type ()
'(member :hash-node :conflict-node :entry nil))
;;; The actual DEFSTRUCT!
(declaim (inline %make-dict %dict-size %dict-hash-function %dict-test-function %dict-key %dict-value %dict-child-type))
(defstruct (dict
(:constructor %make-dict)
(:copier nil)
(:conc-name %dict-))
"A persistent hash map, implemented as a hash array-mapped trie."
(size (error "Supply :SIZE to %MAKE-DICT")
:type size)
(hash-function (error "Supply :HASH-FUNCTION to %MAKE-DICT")
:type hash-function)
(test-function (error "Supply :TEST-FUNCTION to %MAKE-DICT")
:type test-function)
(child-type (error "Supply :CHILD-TYPE to %MAKE-DICT")
:type child-type)
(key (error "Supply :KEY to %MAKE-DICT"))
(value (error "Supply :VALUE to %MAKE-DICT")))
(declaim (inline %make-transient %transient-id %transient-size %transient-hash-function %transient-test-function %transient-key %transient-value %transient-child-type))
(eval-when (:compile-toplevel :load-toplevel)
(defparameter +transient-explanation+
"`transient's are mutable `dict's. Certain operations, namely `insert' and `remove', have transient analogues
`insert!' and `remove!' which may in some cases reduce consing by mutating otherwise inaccessible subparts. No
mutations to a `transient' will ever be visible to the `dict' from which it was constructed.
Construct a `transient' from a `dict' using the function `transient'.
Convert a `transient' into a `dict' using the function `persistent!'. A `transient' which has been made
`persistent!' is considered \"stale,\" and all future transient operations on it will fail, singaling an error
of class `stale-transient'.
The behavior of concurrently mutating a `transient' from multiple threads is undefined."))
(defstruct (transient
(:constructor %make-transient)
(:copier nil)
(:conc-name %transient-))
#.(concatenate 'string
"A temporarily mutable `dict', tracking a unique id to ensure it only mutates otherwise-inaccessible nodes.
"
+transient-explanation+)
(id (error "Supply :ID to %MAKE-TRANSIENT")
:type transient-id)
(size (error "Supply :SIZE to %MAKE-TRANSIENT")
:type size)
(hash-function (error "Supply :HASH-FUNCTION to %MAKE-TRANSIENT")
:type hash-function)
(test-function (error "Supply :TEST-FUNCTION to %MAKE-TRANSIENT")
:type test-function)
(child-type (error "Supply :CHILD-TYPE to %MAKE-TRANSIENT")
:type child-type)
(key (error "Supply :KEY to %MAKE-TRANSIENT"))
(value (error "Supply :VALUE to %MAKE-TRANSIENT")))
;;; error for using a stale transient, i.e. one which has already been made `persistent!'
(define-condition stale-transient (error)
((%transient :type transient
:initarg :transient
:accessor stale-transient-transient)
(%operation :type symbol
:initarg :operation
:accessor stale-transient-operation))
(:report (lambda (c s)
(format s "Attempt to ~s on a `transient' which has already been made `persistent!': ~s"
(stale-transient-operation c)
(stale-transient-transient c)))))
;;; converting between transient and persistent dicts
(declaim (ftype (function (dict) (values transient &optional))
transient))
(defun transient (dict)
#.(concatenate 'string
"Construct a `transient' with the contents of DICT.
This operation runs in constant time, and does not copy any substructure of DICT. Future transient operations
will begin by copying what substructure they need to, and will only mutate newly-constructed nodes which are
uniquely owned by the transient.
"
+transient-explanation+)
(%make-transient :id (get-transient-id)
:size (%dict-size dict)
:hash-function (%dict-hash-function dict)
:test-function (%dict-test-function dict)
:child-type (%dict-child-type dict)
:key (%dict-key dict)
:value (%dict-value dict)))
(declaim (ftype (function (transient) (values dict &optional))
persistent!))
(defun persistent! (transient)
#.(concatenate 'string "Convert TRANSIENT into a persistent `dict'.
This operation runs in constant time.
After this operation, TRANSIENT is considered \"stale,\" and all future transient operations on it will fail
with an error of class `stale-transient'.
"
+transient-explanation+)
(if (null (%transient-id transient))
(error 'stale-transient
:operation 'persistent!
:transient transient)
(progn
(setf (%transient-id transient) nil)
(%make-dict :size (%transient-size transient)
:hash-function (%transient-hash-function transient)
:test-function (%transient-test-function transient)
:child-type (%transient-child-type transient)
:key (%transient-key transient)
:value (%transient-value transient)))))
;;; accessors
(declaim (ftype (function ((or dict transient)) (values size &optional))
size)
;; Inlining may allow the compiler to eliminate `etypecase' dispatch.
(inline size))
(defun size (dict)
(etypecase dict
(dict (%dict-size dict))
(transient (%transient-size dict))))
(declaim (ftype (function ((or dict transient)) (values hash-function &optional))
hash-function)
;; Inlining may allow the compiler to eliminate `etypecase' dispatch.
(inline hash-function))
(defun hash-function (dict)
(etypecase dict
(dict (%dict-hash-function dict))
(transient (%transient-hash-function dict))))
(declaim (ftype (function ((or dict transient)) (values test-function &optional))
test-function)
;; Inlining may allow the compiler to eliminate `etypecase' dispatch.
(inline test-function))
(defun test-function (dict)
(etypecase dict
(dict (%dict-test-function dict))
(transient (%transient-test-function dict))))
(declaim (ftype (function ((or dict transient)) (values t &optional))
%key %value)
;; Inlining may allow the compiler to eliminate `etypecase' dispatch.
(inline %key %value))
(defun %key (dict)
(etypecase dict
(dict (%dict-key dict))
(transient (%transient-key dict))))
(defun %value (dict)
(etypecase dict
(dict (%dict-value dict))
(transient (%transient-value dict))))
(declaim (ftype (function ((or dict transient)) (values child-type &optional))
%child-type)
;; Inlining may allow the compiler to eliminate `etypecase' dispatch.
(inline %child-type))
(defun %child-type (dict)
(etypecase dict
(dict (%dict-child-type dict))
(transient (%transient-child-type dict))))
;;; lookup with GET
(declaim (ftype (function (array-index) (values array-index &optional))
conflict-node-key-true-index
conflict-node-value-true-index)
;; Trivial enough that call overhead is meaningful, so always inline.
(inline conflict-node-key-true-index
conflict-node-value-true-index))
(defun conflict-node-key-true-index (logical-index)
(conflict-node-paired-index-to-true-index (* logical-index 2)))
(defun conflict-node-value-true-index (logical-index)
(conflict-node-paired-index-to-true-index (1+ (* logical-index 2))))
(declaim (ftype (function (conflict-node array-index) (values t &optional))
conflict-node-true-ref)
;; Trivial enough that call overhead is meaningful, so always inline.
(inline conflict-node-true-ref))
(defun conflict-node-true-ref (conflict-node true-index)
(svref conflict-node true-index))
(declaim (ftype (function (t conflict-node array-index) (values t &optional))
(setf conflict-node-true-ref))
;; Trivial enough that call overhead is meaningful, so always inline.
(inline (setf conflict-node-true-ref)))
(defun (setf conflict-node-true-ref) (new-elt conflict-node true-index)
(setf (svref conflict-node true-index) new-elt))
(declaim (ftype (function (conflict-node array-index) (values t t &optional))
conflict-node-logical-ref)
;; Inlining may allow more efficient multiple-values usage, or for the compiler to eliminate unused
;; return values if we only need one of them.
(inline conflict-node-logical-ref))
(defun conflict-node-logical-ref (conflict-node logical-index)
(let* ((key-index (conflict-node-key-true-index logical-index)))
(values (conflict-node-true-ref conflict-node key-index)
(conflict-node-true-ref conflict-node (1+ key-index)))))
(declaim (ftype (function (conflict-node array-index t t) (values &optional))
set-conflict-node-logical-entry)
;; Trivial enough that call overhead is meaningful, so always inline.
(inline set-conflict-node-logical-entry))
(defun set-conflict-node-logical-entry (conflict-node logical-index new-key new-value)
(let* ((key-index (conflict-node-key-true-index logical-index)))
(setf (conflict-node-true-ref conflict-node key-index)
new-key)
(setf (conflict-node-true-ref conflict-node (1+ key-index))
new-value))
(values))
(declaim (ftype (function (conflict-node array-index) (values t &optional))
conflict-node-logical-key-ref
conflict-node-logical-value-ref)
;; Trivial enough that call overhead is meaningful, so always inline.
(inline conflict-node-logical-key-ref
conflict-node-logical-value-ref))
(defun conflict-node-logical-key-ref (conflict-node logical-index)
(conflict-node-true-ref conflict-node (conflict-node-key-true-index logical-index)))
(defun conflict-node-logical-value-ref (conflict-node logical-index)
(conflict-node-true-ref conflict-node (conflict-node-value-true-index logical-index)))
(declaim (ftype (function (t conflict-node array-index) (values t &optional))
(setf conflict-node-logical-key-ref)
(setf conflict-node-logical-value-ref))
;; Trivial enough that call overhead is meaningful, so always inline.
(inline (setf conflict-node-logical-key-ref)
(setf conflict-node-logical-value-ref)))
(defun (setf conflict-node-logical-key-ref) (new-key conflict-node logical-index)
(setf (conflict-node-true-ref conflict-node (conflict-node-key-true-index logical-index))
new-key))
(defun (setf conflict-node-logical-value-ref) (new-value conflict-node logical-index)
(setf (conflict-node-true-ref conflict-node (conflict-node-value-true-index logical-index))
new-value))
(declaim (ftype (function (bitmap hash-node-logical-index) (values boolean &optional))
bitmap-contains-p)
;; Trivial enough that call overhead is meaningful, so always inline.
(inline bitmap-contains-p))
(defun bitmap-contains-p (bitmap logical-index)
(logbitp logical-index bitmap))
(declaim (ftype (function (bitmap hash-node-logical-index) (values array-index &optional))
bitmap-logical-index-to-counted-index)
;; Trivial enough that call overhead is meaningful, so always inline.
(inline bitmap-logical-index-to-counted-index))
(defun bitmap-logical-index-to-counted-index (bitmap logical-index)
"Find the true-index into a hash-node's entries vector associated with INDEX.
Precondition: the associated hash-node must contain the INDEX, i.e. the INDEXth bit in BITMAP must be 1."
(let* ((bits-before (ldb (byte logical-index 0)
bitmap)))
(logcount bits-before)))
(declaim (ftype (function (hash-node bitmap hash-node-logical-index) (values child-type &optional))
hash-node-child-type)
;; Inlining may allow the compiler to eliminate references to and comparisons with the actual
;; keywords in `child-type'.
(inline hash-node-child-type))
(defun hash-node-child-type (hash-node bitmap logical-index)
"Does this HASH-NODE contain a child at the index LOGICAL-INDEX?"
(when (bitmap-contains-p bitmap logical-index)
(let* ((counted-index (bitmap-logical-index-to-counted-index bitmap logical-index)))
(cond ((bitmap-contains-p (hash-node-child-is-entry-p hash-node) counted-index) :entry)
((bitmap-contains-p (hash-node-child-is-conflict-p hash-node) counted-index) :conflict-node)
(:else :hash-node)))))
(declaim (ftype (function (bitmap hash-node-logical-index) (values array-index &optional))
hash-node-key-true-index
hash-node-value-true-index)
;; Trivial enough that call overhead is meaningful, so always inline.
(inline hash-node-key-true-index
hash-node-value-true-index))
(defun hash-node-key-true-index (bitmap logical-index)
"Find the true-index into a hash-node's entries vector associated with INDEX.
Precondition: the HASH-NODE must `hash-node-contains-p' the INDEX."
(hash-node-paired-index-to-true-index (* (bitmap-logical-index-to-counted-index bitmap logical-index)
2)))
(defun hash-node-value-true-index (bitmap logical-index)
(hash-node-paired-index-to-true-index (1+ (* (bitmap-logical-index-to-counted-index bitmap logical-index)
2))))
(declaim (ftype (function (hash-node array-index) (values t &optional))
hash-node-true-ref)
;; Trivial enough that call overhead is meaningful, so always inline.
(inline hash-node-true-ref))
(defun hash-node-true-ref (hash-node true-index)
"Look up a child of HASH-NODE by its TRUE-INDEX.
Precondition: the TRUE-INDEX must have resulted from a valid call to `bitmap-true-index' or
`hash-node-true-index' using the HASH-NODE or its bitmap."
(svref hash-node true-index))
(declaim (ftype (function (t hash-node array-index) (values t &optional))
(setf hash-node-true-ref))
;; Trivial enough that call overhead is meaningful, so always inline.
(inline (setf hash-node-true-ref)))
(defun (setf hash-node-true-ref) (new-value hash-node true-index)
(setf (svref hash-node true-index)
new-value))
(declaim (ftype (function (hash-node bitmap hash-node-logical-index) (values t t &optional))
hash-node-logical-ref)
;; Inlining may allow more efficient multiple-values usage, or for the compiler to eliminate unused
;; return values if we only need one of them.
(inline hash-node-logical-ref))
(defun hash-node-logical-ref (hash-node bitmap logical-index)
"Look up a child of HASH-NODE by its LOGICAL-INDEX.
Precondition: the HASH-NODE must `hash-node-contains-p' the INDEX."
(let* ((key-index (hash-node-key-true-index bitmap logical-index)))
(values (hash-node-true-ref hash-node key-index)
(hash-node-true-ref hash-node (1+ key-index)))))
(declaim (ftype (function (bitmap hash-node hash-node-logical-index t t) (values &optional))
set-hash-node-logical-entry)
;; Trivial enough that call overhead is meaningful, so always inline.
(inline set-hash-node-logical-entry))
(defun set-hash-node-logical-entry (bitmap hash-node logical-index new-key new-value)
"Write the pair (NEW-KEY => NEW-VALUE) into HASH-NODE at LOGICAL-INDEX.
It is the caller's responsibility to update HASH-NODE's child-is-entry-p and child-is-conflict-p bitmaps to
suit the new entry."
(let* ((key-index (hash-node-key-true-index bitmap logical-index)))
(setf (hash-node-true-ref hash-node key-index)
new-key)
(setf (hash-node-true-ref hash-node (1+ key-index))
new-value))
(values))
(declaim (ftype (function (shift fixnum) (values hash-node-logical-index))
extract-hash-part-for-shift)
;; Trivial enough that call overhead is meaningful, so always inline.
(inline extract-hash-part-for-shift))
(defun extract-hash-part-for-shift (shift hash)
"Extract a `hash-node-logical-index' from HASH for a `hash-node' at SHIFT, i.e. a hash-node that is SHIFT steps removed from the trie's root."
(let ((shift-low-bit (* shift +node-index-bits+)))
(ldb (byte +node-index-bits+ shift-low-bit)
hash)))
(declaim (ftype (function (conflict-node t test-function t) (values t boolean &optional))
conflict-node-lookup))
(defun conflict-node-lookup (conflict-node key test-function not-found)
(declare (inline child-lookup))
(iter (declare (declare-variables))
(for index below (conflict-node-logical-length conflict-node))
(for (values other-key value) = (conflict-node-logical-ref conflict-node index))
(when (funcall test-function key other-key)
(return (values value t)))
(finally (return (values not-found nil)))))
;; Predeclarations for better type inference in recursive calls by HASH-NODE-LOOKUP
(declaim (ftype (function (child-type t t t fixnum shift test-function t)
(values t boolean &optional))
child-lookup))
(declaim (ftype (function (hash-node bitmap t fixnum shift hash-node-logical-index test-function t)
(values t boolean &optional))
hash-node-lookup))
(defun hash-node-lookup (hash-node bitmap key hash shift logical-index test-function not-found)
"Get the value associated with KEY in NODE.
HASH is the result of applying the containing `dict' 's HASH-FUNCTION to KEY.
SHIFT is the depth into the trie of NODE. For a `dict' 's BODY, this will be 0.
TEST-FUNCTION is the containing `dict' 's TEST-FUNCTION, which must satisfy the hash-test-function laws with
the HASH-FUNCTION used to generate HASH.
NOT-FOUND is an arbitrary value to be returned as primary value if NODE does not contain a mapping for KEY."
(if-let ((child-type (hash-node-child-type hash-node bitmap logical-index)))
(multiple-value-bind (subkey value) (hash-node-logical-ref hash-node bitmap logical-index)
(child-lookup child-type
subkey
value
key
hash
(1+ shift)
test-function
not-found))
(values not-found nil)))
(defun child-lookup (child-type entry-key entry-value sought-key hash shift test-function not-found)
(ecase child-type
((nil) (values not-found nil))
(:entry (if (funcall test-function entry-key sought-key)
(values entry-value t)
(values not-found nil)))
(:conflict-node (if (= (the fixnum entry-key)
hash)
(conflict-node-lookup entry-value sought-key test-function not-found)
(values not-found nil)))
(:hash-node (let* ((logical-index (extract-hash-part-for-shift shift hash)))
(if (bitmap-contains-p (the bitmap entry-key)
logical-index)
(hash-node-lookup entry-value
(the bitmap entry-key)
sought-key
hash
shift
logical-index
test-function
not-found)
(values not-found nil))))))
(declaim (ftype (function ((or dict transient) t &optional t) (values t boolean))
get))
(defun get (dict key &optional not-found)
"Get the value associated with KEY in DICT, or NOT-FOUND if the KEY is not present.
Like `gethash', returns (values VALUE PRESENTP). If DICT contains a mapping for KEY, returns the associated
value as VALUE, and T as PRESENTP. If DICT does not contain a mapping for KEY, returns (values NOT-FOUND
nil)."
(with-accessors ((hash-function hash-function)
(test-function test-function)
(child-type %child-type)
(body-key %key)
(body-value %value))
dict
(child-lookup child-type
body-key
body-value
key
(funcall hash-function key)
0
test-function
not-found)))
;;; INSERT and helpers
;; all of the INSERT helpers which construct nodes will return (values KEY ENTRY CHILD-TYPE
;; NUM-ADDED-ELEMENTS), where the KEY is a thing that goes in the key-index of its parent, and the VALUE is a
;; thing that goes in the value-index of its parent.
(deftype merge-function (&optional (key t) (value t))
"A function used to compute the resulting value in an `insert' operation when the key is already present.
During (insert DICT KEY NEW-VALUE), if DICT already associates KEY with OLD-VALUE, the `merge-function' will
be called with (KEY OLD-VALUE NEW-VALUE).
The default `merge-function' is `new-value', which ignores the KEY and OLD-VALUE and uses the NEW-VALUE."
`(function (,key ,value ,value) (values ,value &optional)))
(declaim (ftype merge-function
new-value
old-value))
(defun new-value (key old-value new-value)
"The default `merge-function', which inserts the NEW-VALUE, overwriting the OLD-VALUE."
(declare (ignore key old-value))
new-value)
(defun old-value (key old-value new-value)
"A `merge-function' which leaves the OLD-VALUE, effectively aborting the `insert' operation."
(declare (ignore key new-value))
old-value)
(declaim (ftype (function (hash-node-logical-index)
(values bitmap &optional))
bit-from-index)
;; Trivial enough that call overhead is meaningful, so always inline.
(inline bit-from-index))
(defun bit-from-index (index)
(ash 1 index))
(declaim (ftype (function (bitmap hash-node-logical-index)
(values bitmap &optional))
set-bit)
;; Trivial enough that call overhead is meaningful, so always inline.
(inline set-bit))
(defun set-bit (bitmap index)
(logior bitmap (bit-from-index index)))
(declaim (ftype (function (bitmap hash-node-logical-index)
(values bitmap &optional))
unset-bit)
;; Trivial enough that call overhead is meaningful, so always inline.
(inline unset-bit))
(defun unset-bit (bitmap index)
(logandc2 bitmap (bit-from-index index)))
(declaim (ftype (function (&rest hash-node-logical-index) (values bitmap &optional))
bitmap-from-indices)
(inline bitmap-from-indices))
;; TODO: determine if inlines of this function generate good machine code, and if not, optimize with a
;; compiler-macro.
(defun bitmap-from-indices (&rest indices)
(declare (dynamic-extent indices))
(reduce #'set-bit
indices
:initial-value 0))
(declaim (ftype (function (array-length) (values array-length &optional))
logical-count-to-paired-length)
;; Trivial enough that call overhead is meaningful, so always inline.
(inline logical-count-to-paired-length))
(defun logical-count-to-paired-length (logical-count)
(* logical-count 2))
(declaim (ftype (function (transient-id
t t child-type hash-node-logical-index
t t child-type hash-node-logical-index
t)
(values bitmap hash-node (eql :hash-node) t &optional))
make-two-entry-hash-node))
(defun make-two-entry-hash-node (transient-id
left-key left-value left-child-type left-idx
right-key right-value right-child-type right-idx
additional-return-value)
(multiple-value-bind (lower-key lower-value lower-type lower-idx
higher-key higher-value higher-type higher-idx)
(if (< left-idx right-idx)
(values left-key left-value left-child-type left-idx
right-key right-value right-child-type right-idx)
(values right-key right-value right-child-type right-idx
left-key left-value left-child-type left-idx))
(let* ((child-is-conflict-p 0)
(child-is-entry-p 0))
(declare (bitmap child-is-conflict-p child-is-entry-p))
(flet ((set-child-type-bits (child-type counted-index)
(case child-type
(:entry (setf child-is-entry-p
(set-bit child-is-entry-p
counted-index)))
(:conflict-node (setf child-is-conflict-p
(set-bit child-is-conflict-p
counted-index))))))
(set-child-type-bits lower-type 0)
(set-child-type-bits higher-type 1))
(let* ((new-node (%make-hash-node :transient-id transient-id
:child-is-entry-p child-is-entry-p
:child-is-conflict-p child-is-conflict-p
:length (logical-count-to-paired-length 2))))
(sv-initialize new-node (:start-from +hash-node-zero+)
lower-key
lower-value
higher-key
higher-value)
(values (bitmap-from-indices lower-idx higher-idx)
new-node
:hash-node
additional-return-value)))))
(declaim (ftype (function (transient-id t t child-type hash-node-logical-index t)
(values bitmap hash-node (eql :hash-node) t &optional))
make-one-entry-hash-node))
(defun make-one-entry-hash-node (transient-id key value child-type logical-index additional-return-value
&aux )
(let* ((bitmap (bitmap-from-indices logical-index))
(new-node (%make-hash-node :transient-id transient-id
:child-is-entry-p (if (eq child-type :entry)
1
0)
:child-is-conflict-p (if (eq child-type :conflict-node)
1
0)
:length (logical-count-to-paired-length 1))))
(sv-initialize new-node (:start-from +hash-node-zero+)
key value)
(values bitmap
new-node
:hash-node
additional-return-value)))
(declaim (ftype (function (transient-id fixnum array-length t &rest t)
(values fixnum conflict-node (eql :conflict-node) t &optional))
make-conflict-node))
(defun make-conflict-node (transient-id hash logical-count additional-return-value &rest keys-and-values)
(declare (dynamic-extent keys-and-values))
(values
hash
(with-list-generator (gen-initial-contents keys-and-values)
(%make-conflict-node :transient-id transient-id
:length (logical-count-to-paired-length logical-count)
:initial-contents gen-initial-contents))
:conflict-node
additional-return-value))
(declaim (ftype (function (transient-id
t t fixnum child-type
t t fixnum child-type
shift
t)
(values bitmap hash-node (eql :hash-node) t &optional))
promote-node))
(defun promote-node (transient-id
left-key left-value left-hash left-child-type
right-key right-value right-hash right-child-type
shift
additional-return-value)
"Combine the LEFT-NODE and RIGHT-NODE into a new `hash-node', which should be SHIFT steps deep into the trie.
LEFT-HASH is the hash of the entries in the LEFT-NODE.
RIGHT-HASH is the hash of the entries in the RIGHT-NODE.
Precondition: (/= LEFT-HASH RIGHT-HASH), or else we would construct a unified `conflict-node' instead of a
`hash-node'."
(let* ((left-index (extract-hash-part-for-shift shift left-hash))
(right-index (extract-hash-part-for-shift shift right-hash)))
(if (= left-index right-index)
(multiple-value-bind (sub-bitmap sub-node hash-node additional-return-value)
(promote-node transient-id
left-key left-value left-hash left-child-type
right-key right-value right-hash right-child-type
(1+ shift)
additional-return-value)
(make-one-entry-hash-node transient-id
sub-bitmap sub-node hash-node
left-index
additional-return-value))
(make-two-entry-hash-node transient-id
left-key left-value left-child-type left-index
right-key right-value right-child-type right-index
additional-return-value))))
(declaim (ftype (function (transient-id t t t t fixnum shift test-function hash-function merge-function)
(values t t child-type bit &optional))
insert-alongside-entry))
(defun insert-alongside-entry (transient-id
neighbor-key neighbor-value
key value
hash shift
test-function hash-function merge-function
&aux (neighbor-hash (funcall hash-function neighbor-key)))
(cond ((and (= neighbor-hash hash)
(funcall test-function neighbor-key key))
(values key (funcall merge-function key neighbor-value value) :entry 0))
((= neighbor-hash hash)
(make-conflict-node transient-id hash 2 1 neighbor-key neighbor-value key value))
(:else (promote-node transient-id
neighbor-key neighbor-value neighbor-hash :entry
key value hash :entry
shift 1))))
(declaim (ftype (function (conflict-node t test-function)
(values (or null array-index) &optional))
conflict-node-logical-index-of))
(defun conflict-node-logical-index-of (conflict-node key test-function)
"If CONFLICT-NODE contains a mapping for KEY under TEST-FUNCTION, return the index into the CONFLICT-NODE's entries vector for that mapping."
(iter (declare (declare-variables))
(for logical-index below (conflict-node-logical-length conflict-node))
(when (funcall test-function
key
(conflict-node-logical-key-ref conflict-node logical-index))
(return logical-index))))
(declaim (ftype (function (transient-id conflict-node fixnum t t array-index t)
(values fixnum conflict-node (eql :conflict-node) t &optional))
conflict-node-copy-replace-at-logical-index))
(defun conflict-node-copy-replace-at-logical-index (transient-id
conflict-node hash
new-key new-value
logical-index
additional-return-value)
"Do a functional update of CONFLICT-NODE, replacing the entry at LOGICAL-INDEX with (NEW-KEY => NEW-VALUE).
The resulting node will have the TRANSIENT-ID installed.
Return four values suitable for the insertion operation: (values MY-KEY MY-VALUE MY-TYPE DELTA-SIZE)."
(let* ((new-node (%make-conflict-node :transient-id transient-id
:length (conflict-node-paired-count conflict-node)))
(replaced-key-true-index (conflict-node-key-true-index logical-index)))
(sv-initialize new-node (:start-from +conflict-node-zero+)
(:subrange conflict-node
:count (- replaced-key-true-index +conflict-node-zero+)
:start +conflict-node-zero+)
new-key
new-value
(:subrange conflict-node :start (+ 2 replaced-key-true-index)))
(values hash new-node :conflict-node additional-return-value)))
(declaim (ftype (function (conflict-node fixnum t t array-index)
(values fixnum conflict-node (eql :conflict-node) (eql 0) &optional))
conflict-node-set-at-logical-index))
(defun conflict-node-set-at-logical-index (conflict-node hash new-key new-value logical-index)
"Mutate the CONFLICT-NODE, replacing the entry at LOGICAL-INDEX with (NEW-KEY => NEW-VALUE).
Invariant: the enclosing `transient' on which the current `insert!' operation is running must uniquely own the
CONFLICT-NODE, that is, their ids must match.
Return four values suitable for the insertion operation: (values MY-KEY MY-VALUE MY-TYPE DELTA-SIZE)."
(set-conflict-node-logical-entry conflict-node logical-index new-key new-value)
(values hash
conflict-node
:conflict-node
0))
(declaim (ftype (function (transient-id transient-id) (values boolean &optional))
same-transient-id-p)
;; Inlining may allow the compiler to avoid reifying the result into a `cl:boolean'.
(inline same-transient-id-p))
(defun same-transient-id-p (a b)
(and a b (= a b)))
(declaim (ftype (function (transient-id conflict-node fixnum t t array-index)
(values fixnum conflict-node (eql :conflict-node) (eql 0) &optional))
conflict-node-replace-at-logical-index))
(defun conflict-node-replace-at-logical-index (transient-id conflict-node hash new-key new-value logical-index)
(if (same-transient-id-p transient-id (conflict-node-transient-id conflict-node))
;; If we're a transient and we uniquely own this node, mutate it.
(conflict-node-set-at-logical-index conflict-node hash new-key new-value logical-index)
;; Otherwise, do a functional update.
(conflict-node-copy-replace-at-logical-index transient-id conflict-node hash new-key new-value logical-index 0)))
(declaim (ftype (function (transient-id fixnum conflict-node t t t)
(values fixnum conflict-node (eql :conflict-node) t &optional))
add-to-conflict-node))
(defun add-to-conflict-node (transient-id hash conflict-node new-key new-value additional-return-value)