-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathvec.lisp
More file actions
1584 lines (1342 loc) · 70.4 KB
/
vec.lisp
File metadata and controls
1584 lines (1342 loc) · 70.4 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
;;;; VECs, a.k.a. Persistent Vectors, a.k.a. Bit-partitioned Binary Tries with Tails
;;; See Jean Niklas L'orange's series of blog posts, "Understanding Clojure's Persistent Vectors," for an
;;; explanation of this data structure.
;;; https://hypirion.com/musings/understanding-persistent-vector-pt-1
;;; https://hypirion.com/musings/understanding-persistent-vector-pt-2
;;; https://hypirion.com/musings/understanding-persistent-vector-pt-3
(uiop:define-package :immutable/vec
(:import-from :alexandria
#:array-index #:array-length #:define-constant #:when-let #:once-only #:with-gensyms)
(:use :cl :iterate #:immutable/%generator #:immutable/%simple-vector-utils)
(:shadow #:length #:equal #:map #:do #:concatenate)
(:export
;; condition classes and accessors
#:out-of-bounds
#:out-of-bounds-index
#:out-of-bounds-length
#:out-of-bounds-vec
#:out-of-bounds-operation
#:pop-back-empty
#:retract-not-enough-elements
#:retract-not-enough-elements-vec
#:retract-not-enough-elements-requested-length
#:retract-not-enough-elements-actual-length
;; type and constructor
#:vec
;; the empty vector
#:+empty+
;; element access
#:unsafe-ref
#:ref
;; reading length (shadowed over CL:LENGTH)
#:length
;; test if vec is empty
#:emptyp
;; append one to end
#:push-back
;; append multiple to end
#:extend
#:extend-from-list #:extend-from-vector
;; append vecs
#:concatenate
;; remove one from end
#:pop-back
;; remove multiple from end
#:retract
;; replace individual elements in a vec
#:update-at
#:replace-at
;; map function across vec
#:map
;; iterate over vec
#:for-each
#:do
;; test if two vectors are equal
#:equal
;; convert from CL sequences
#:from-list #:to-list
;; convert to CL sequences
#:from-vector #:to-specialized-vector #:to-vector))
(in-package :immutable/vec)
#+immutable-vec-debug
(declaim (optimize (speed 1) (safety 3) (space 1) (debug 3) (compilation-speed 0)))
;; #-immutable-vec-debug
;; (declaim (optimize (speed 3) (safety 1) (space 1) (debug 1) (compilation-speed 0)))
(eval-when (:compile-toplevel :load-toplevel)
(declaim (type array-length +branch-rate+))
(defconstant +branch-rate+ 32
"The number of child nodes or elements contained in each node of a vec.")
(declaim (type (and fixnum unsigned-byte) +node-index-bits+))
(defconstant +node-index-bits+ (floor (log +branch-rate+ 2)))
(declaim (type (and fixnum unsigned-byte) +max-length+))
(defconstant +max-length+ most-positive-fixnum
"The maximum number of elements contained in a vec.")
(declaim (type (and fixnum unsigned-byte) +max-height+))
(defconstant +max-height+ (1- (floor (log +max-length+ +branch-rate+)))
"The number of chunks traversed from root to leaf in a vec of length +max-length+."))
(deftype node-length ()
`(integer 1 ,+branch-rate+))
(deftype tail-length ()
`(integer 0 ,+branch-rate+))
(deftype height ()
"The number of nodes to traverse from root to a leaf node.
Height of 0 means that the current node is a leaf node, i.e. its elements are the elements of the enclosing
VEC.
Height of 1 means that the current node's elements have height 0, i.e. are leaf nodes.
Height of N means that the current node's elements have height (1- N)."
`(integer 0 ,+max-height+))
(deftype length ()
`(integer 0 ,+max-length+))
(deftype index ()
`(integer 0 (,+max-length+)))
(deftype node ()
`(or ,@(iter (declare (declare-variables))
(for (the array-length i) from 1 to +branch-rate+)
(collect `(simple-vector ,i)))))
(deftype full-node ()
`(simple-vector ,+branch-rate+))
;; constructing nodes
(declaim (ftype (function (generator) (values node &optional))
alloc-leaf-node))
(defun alloc-leaf-node (contents-iterator)
(let* ((arr (make-array +branch-rate+)))
(iter (declare (declare-variables))
(for (the fixnum i) below +branch-rate+)
(setf (svref arr (the array-index i)) (advance contents-iterator)))
arr))
(deftype node-index ()
`(integer 0 (,+branch-rate+)))
(deftype tail-buf () '(or null node))
;;; the actual defstruct!
(declaim (inline %make-vec %vec-height %vec-length %vec-body %vec-tail))
(defstruct (vec
(:constructor %make-vec)
(:copier nil)
(:conc-name %vec-))
"A persistent vector, A.K.A. a bit-partitioned vector trie with a tail buffer.
Persistent vectors implement random-access indexing and updates in O(log_{32}(length)) time while sharing
structure, and push- and pop- at the end in amortized constant time.
As implemented here, vecs are untyped, unlike CL arrays, which allow specialization. CL's type system makes
implementing new specialized collections difficult.
The empty vec is called `+empty+'.
To query the length of a vec, use `length', which this package shadows.
To construct a vec from arbitrary elements, use the function (`vec' &rest ELEMENTS), which is analogous to the
functions `list' and `vector'.
To convert a CL sequence into a vec, use `from-list' or `from-vector' as appropriate.
To convert a vec into a CL sequence, use `to-list' or `to-vector'.
To convert a vec into a vector that is not a simple-vector, use `to-specialized-array', which takes keyword
arguments `:element-type', `:adjustable' and `:fill-pointer' analogous to `make-array'."
;; The number of array accesses between the body and the elements.
;; A height of 0 means that the body is a simple-vector of elements.
;; A height of N > 0 means that the body is a simple-vector of nodes of height N.
(height (error "Supply :HEIGHT to %MAKE-VEC")
:type height)
;; The total length of this vec, including both its body and its tail.
(length (error "Supply :LENGTH to %MAKE-VEC")
:type length)
;; The body part of this vec, a bit-partitioned trie. Leaf nodes in this trie (those with height 0) will
;; always be full, i.e. contain exactly +BRANCH-RATE+ elements. If the vec's length is not a multiple of
;; +BRANCH-RATE+, the remainder will be stored in the tail.
(body (error "Supply :BODY to %MAKE-VEC")
:type (or null node))
;; The tail part of this vec, a single simple-vector of length at most +BRANCH-RATE+. Storing such a tail
;; allows `push-back' and `pop-back' to run in amortized constant time.
(tail nil
:type tail-buf))
;;; condition class for out-of-bounds access
(define-condition out-of-bounds (error)
((%vec :type vec
:initarg :vec
:reader out-of-bounds-vec)
(%length :type unsigned-byte
:initarg :length
:reader out-of-bounds-length)
(%index :type unsigned-byte
:initarg :index
:reader out-of-bounds-index)
(%operation :type (member ref replace-at update-at)
:initarg :operation
:reader out-of-bounds-operation))
(:report (lambda (c s)
(format s "Invalid index ~d during ~s for VEC of length ~d: ~a"
(out-of-bounds-index c)
(out-of-bounds-operation c)
(out-of-bounds-length c)
(out-of-bounds-vec c)))))
;;; condition class for pop-back from empty
(define-condition pop-back-empty (error)
()
(:report (lambda (c s)
(declare (ignore c))
(write-string "Attempt to POP-BACK from empty VEC" s))))
;;; condition class for retract with not enough elements
(define-condition retract-not-enough-elements (error)
((%vec :initarg :vec
:reader retract-not-enough-elements-vec)
(%requested-length :type length
:initarg :requested-length
:reader retract-not-enough-elements-requested-length)
(%actual-length :type length
:initarg :actual-length
:reader retract-not-enough-elements-actual-length))
(:report (lambda (c s)
(format s "Attempt to RETRACT ~d elements from a VEC of length ~d: ~a"
(retract-not-enough-elements-requested-length c)
(retract-not-enough-elements-actual-length c)
(retract-not-enough-elements-vec c)))))
;;; length computations
(declaim (ftype (function (tail-buf) (values tail-length &optional))
tail-buf-length)
(inline tail-buf-length))
(defun tail-buf-length (tail-buf)
(if tail-buf
(cl:length tail-buf)
0))
(declaim (ftype (function (vec) (values tail-length &optional))
tail-length)
(inline tail-length))
(defun tail-length (vec)
(tail-buf-length (%vec-tail vec)))
(declaim (ftype (function (vec) (values length &optional))
length body-length)
(inline length body-length))
(defun length (vec)
(%vec-length vec))
(defun body-length (vec)
(- (length vec)
(tail-length vec)))
(declaim (ftype (function (vec) (values boolean &optional))
emptyp))
(defun emptyp (vec)
"Returns T if VEC is empty, or `nil' if it contains at least one element."
(zerop (length vec)))
(declaim (ftype (function (vec index) (values boolean &optional))
index-in-tail-p)
(inline index-in-tail-p))
(defun index-in-tail-p (vec idx)
"True if IDX is within or beyond the tail part of VEC, nil otherwise.
Does not necessarily imply that IDX is in-bounds for VEC."
(>= idx (body-length vec)))
(declaim (ftype (function (vec index) (values t &optional))
tailref)
(inline tailref))
(defun tailref (vec idx)
"Read from the tail of VEC. IDX must be in-bounds for VEC, and must be `index-in-tail-p'."
(svref (%vec-tail vec) (- idx (body-length vec))))
(declaim (ftype (function (height index) (values node-index index &optional))
extract-index-parts-for-height)
(inline extract-index-parts-for-height))
(defun extract-index-parts-for-height (height idx)
(let ((height-low-bit (* height +node-index-bits+)))
(values (ldb (byte +node-index-bits+ height-low-bit)
idx)
(ldb (byte height-low-bit 0)
idx))))
(declaim (ftype (function (node height index) (values t &optional))
trieref))
(defun trieref (body height idx)
"Index into the body part of a vector BODY at HEIGHT.
IDX must be inbounds for BODY at HEIGHT, meaning it must have no one bits higher than
(* (1+ height) +node-index-bits+) and must not pass into an unallocated node."
(if (zerop height)
(svref body idx)
(multiple-value-bind (curr remaining) (extract-index-parts-for-height height idx)
(trieref (svref body curr) (1- height) remaining))))
(declaim (ftype (function (vec index) (values t &optional))
bodyref)
(inline bodyref))
(defun bodyref (vec idx)
"Index into the body part of VEC. IDX must be in-bounds for VEC, and must not be `index-in-tail-p'."
(trieref (%vec-body vec) (%vec-height vec) idx))
(declaim (ftype (function (vec index) (values t &optional))
unsafe-ref))
(defun unsafe-ref (vec idx)
(if (index-in-tail-p vec idx)
(tailref vec idx)
(bodyref vec idx)))
(declaim (ftype (function (vec index) (values t &optional))
ref)
(inline ref))
(defun ref (vec idx &aux (length (length vec)))
(if (>= idx length)
(error 'out-of-bounds
:vec vec
:length length
:index idx
:operation 'ref)
(unsafe-ref vec idx)))
;;; computing required size, shape, height of new vecs
(declaim (ftype (function (length) (values length &optional))
length-without-tail-buf)
(inline length-without-tail-buf))
(defun length-without-tail-buf (total-length)
(let* ((tail-length (rem total-length +branch-rate+)))
(- total-length tail-length)))
(declaim (ftype (function (length) (values height &optional))
length-required-height)
(inline length-required-height))
(defun length-required-height (length &aux (length-without-tail (length-without-tail-buf length)))
(if (<= length-without-tail 1)
0
(values (floor (log (1- length-without-tail) +branch-rate+)))))
(declaim (ftype (function (height) (values length &optional))
elts-per-node-at-height)
(inline elts-per-node-at-height))
(defun elts-per-node-at-height (height)
(expt +branch-rate+ (1+ height)))
(declaim (ftype (function (length height) (values length &optional))
trie-length-in-nodes-at-height)
(inline trie-length-in-nodes-at-height))
(defun trie-length-in-nodes-at-height (length-in-elts height)
(values (ceiling length-in-elts (elts-per-node-at-height height))))
(declaim (ftype (function (fixnum fixnum fixnum) (values fixnum &optional))
bracket)
(inline bracket))
(defun bracket (min middle max)
(min max (max middle min)))
;;; constructing the body part of vecs
(declaim (ftype (function (height length generator)
(values (or null node) &optional))
alloc-trie))
(declaim (ftype (function (height length generator)
(values node &optional))
alloc-branch-node))
(defun alloc-trie (height length-in-elts contents)
(cond ((zerop length-in-elts) nil)
((zerop height) (alloc-leaf-node contents))
(:else (alloc-branch-node height length-in-elts contents))))
(declaim (ftype (function (node height length generator &optional (or node-index (eql 32)))
(values &optional))
initialize-node-from-elts-generator))
(defun initialize-node-from-elts-generator (node height remaining-length-in-elts contents &optional (nodes-already-filled 0))
(unless (= nodes-already-filled 32)
(let* ((child-height (1- height))
(length-in-nodes (trie-length-in-nodes-at-height remaining-length-in-elts child-height))
(per-child-length (elts-per-node-at-height child-height)))
(iter (declare (declare-variables))
(for (the fixnum i) from nodes-already-filled below (+ length-in-nodes nodes-already-filled))
(for (the fixnum remaining) from remaining-length-in-elts by (- per-child-length))
(for (the length this-length) = (bracket 0 per-child-length remaining))
(setf (svref node i)
(alloc-trie child-height this-length contents)))))
(values))
(defun alloc-branch-node (height length-in-elts contents)
(let* ((length-in-nodes (trie-length-in-nodes-at-height length-in-elts (1- height)))
(arr (make-array length-in-nodes)))
(initialize-node-from-elts-generator arr height length-in-elts contents)
arr))
;; TODO: use `define-generator' to offer a DX-allocatable version
(defun child-nodes-generator (child-height length-in-elts contents)
(generator ((per-child-length (elts-per-node-at-height child-height))
(remaining length-in-elts))
(declare (type length per-child-length)
(fixnum remaining))
(let ((this-length (bracket 0 per-child-length remaining)))
(declare (type length this-length))
(if (zerop this-length)
(done)
(progn (decf remaining this-length)
(alloc-trie child-height this-length contents))))))
;;; constructing the tail part of vecs
(declaim (ftype (function (tail-length generator) (values tail-buf &optional))
make-tail)
(inline make-tail))
(defun make-tail (tail-length contents)
(if (zerop tail-length)
nil
(let* ((tail (make-array tail-length)))
(iter (declare (declare-variables))
(for (the fixnum i) below tail-length)
(setf (svref tail i) (advance contents)))
tail)))
;;; constructing vecs
(declaim (type vec +empty+))
(defparameter +empty+ (%make-vec :length 0
:height 0
:body nil
:tail nil))
(declaim (ftype (function (length generator) (values vec &optional))
generator-vec)
;; `generator-vec' is private and will be accessed only by `vec', `from-list' and `from-vector', so
;; inlining is not a code size concern, and making the generator a local function may allow some
;; optimizations.
(inline generator-vec))
(defun generator-vec (length contents)
(if (zerop length)
+empty+
(let* ((body-length (length-without-tail-buf length))
(tail-length (- length body-length))
(height (length-required-height body-length)))
(%make-vec :height height
:length length
:body (alloc-trie height body-length contents)
:tail (make-tail tail-length contents)))))
;;; internal functional updates to vecs
(declaim (ftype (function (vec &key (:height height)
(:length length)
(:body (or null node))
(:tail tail-buf))
(values vec &optional))
copy-vec)
;; Private function that can be inlined without worrying about code size, and reducing to an
;; (also inline) struct constructor may allow some optimizations.
(inline copy-vec))
(defun copy-vec (vec &key (height (%vec-height vec))
(length (%vec-length vec))
(body (%vec-body vec))
(tail (%vec-tail vec)))
(%make-vec :height height
:length length
:body body
:tail tail))
;;; adding an element to the end of a vec
(declaim (ftype (function (tail-buf) (values boolean &optional))
tail-has-room-p)
;; Inlining `tail-has-room-p' may allow arithmetic optimizations and improved type inference.
(inline tail-has-room-p))
(defun tail-has-room-p (tail)
(if tail
(< (cl:length tail)
+branch-rate+)
t))
(declaim (ftype (function (height) (values length &optional))
max-body-length-at-height)
;; Inlining `max-body-length-at-height' may allow arithmetic optimizations.
(inline max-body-length-at-height))
(defun max-body-length-at-height (height)
(expt +branch-rate+ (1+ height)))
(declaim (ftype (function (height node) (values node &optional))
wrap-in-spine))
(defun wrap-in-spine (height body)
(if (plusp height)
(wrap-in-spine (1- height) (vector body))
body))
(declaim (ftype (function ((or null node) node height length)
(values node &optional))
grow-trie))
(defun grow-trie (trie new-node height new-length-in-elts)
(cond ((zerop height) new-node)
((null trie) (wrap-in-spine height new-node))
(t
(locally (declare (node trie)) ; for some reason, sbcl doesn't infer this, at least on 2.2.11
(let* ((length-before-in-elts (- new-length-in-elts (cl:length new-node)))
(elts-per-node (elts-per-node-at-height (1- height)))
(new-length-in-nodes (ceiling new-length-in-elts
elts-per-node))
(length-before-in-nodes (floor length-before-in-elts
elts-per-node))
(last-node-length-in-nodes (- new-length-in-nodes length-before-in-nodes))
(new-trie (make-array new-length-in-nodes)))
(declare (node-length new-length-in-nodes
length-before-in-nodes
last-node-length-in-nodes))
(sv-initialize new-trie ()
(:subrange trie :count length-before-in-nodes)
(if (= length-before-in-nodes (cl:length trie))
;; new node is the leftmost in its subtree
(wrap-in-spine (1- height) new-node)
;; new node has siblings
(grow-trie (svref trie length-before-in-nodes)
new-node
(1- height)
last-node-length-in-nodes)))
new-trie)))))
(declaim (ftype (function (vec t) (values vec &optional))
push-back))
(defun push-back (vec new-element)
"Return a new `vec' like VEC, with NEW-ELEMENT added to the end.
Attempts to share as much structure as possible with the original VEC.
# Time complexity
This operation has an amortized runtime of O(1). One out of every `+branch-rate+' `push-back's will run in
O(log_{+brach-rate+}N) time in the length of the input VEC, and the rest will run in constant time."
(with-accessors ((height %vec-height)
(length %vec-length)
(tail %vec-tail)
(body %vec-body))
vec
(cond ((not tail)
;; super fast path when you have no tail: grow a tail
(copy-vec vec
:tail (vector new-element)
:length (1+ length)))
((tail-has-room-p tail)
;; fast path when your tail is short: make it longer
(copy-vec vec
:tail (sv-push-back tail new-element)
:length (1+ length)))
((= (body-length vec) (max-body-length-at-height height))
;; fast path when your tail and body are both full: grow an extra layer of height, put your old tail
;; in the newly-expanded body, then grow a new tail
(copy-vec vec
:height (1+ height)
:length (1+ length)
:body (vector body (wrap-in-spine height tail))
:tail (vector new-element)))
(t
;; slow path when tail is full but body is not: move your full tail into your not-full body, then
;; grow a new tail.
(copy-vec vec
:height height
:length (1+ length)
:body (grow-trie body tail height length)
:tail (vector new-element))))))
;;; adding multiple elements with EXTEND (and helpers)
(declaim (ftype (function (height full-node generator length) (values node &optional))
fill-behind-direct-child))
(defun fill-behind-direct-child (direct-child-height leading-direct-child follow-elts length-in-elts)
"Make a trie that starts with the LEADING-DIRECT-CHILD, then filled from the FOLLOW-ELTS.
Allocate a node with height (1+ DIRECT-CHILD-HEIGHT) whose first child is LEADING-DIRECT-CHILD, and with
subsequent children to hold enough elements taken from the FOLLOW-ELTS that the node's total length is
LENGTH-IN-ELTS.
LENGTH-IN-ELTS must be a multiple of +BRANCH-RATE+, and includes the length of LEADING-DIRECT-CHILD."
(let* ((length-in-nodes (trie-length-in-nodes-at-height length-in-elts direct-child-height))
(trie (make-array length-in-nodes)))
(declare (node-length length-in-nodes)
(node trie))
(setf (svref trie 0) leading-direct-child)
(initialize-node-from-elts-generator trie
(1+ direct-child-height)
(- length-in-elts (elts-per-node-at-height direct-child-height))
follow-elts
1)
trie))
(declaim (ftype (function (height full-node height generator length) (values node &optional))
fill-behind-node-to-height))
(defun fill-behind-node-to-height (total-height leading-node leading-node-height follow-elts length-in-elts)
"Make a trie of TOTAL-HEIGHT that starts with the LEADING-NODE, then filled from the FOLLOW-ELTS.
LENGTH-IN-ELTS must be a multiple of +BRANCH-RATE+, and includes the length of LEADING-NODE."
(cond ((= total-height leading-node-height) leading-node)
((= total-height (1+ leading-node-height))
(fill-behind-direct-child leading-node-height leading-node follow-elts length-in-elts))
(t
(let* ((direct-child-height (1- total-height))
(direct-leading-child-length (max-body-length-at-height direct-child-height))
(leading-direct-child (fill-behind-node-to-height direct-child-height
leading-node
leading-node-height
follow-elts
direct-leading-child-length)))
(fill-behind-direct-child direct-child-height
leading-direct-child
follow-elts
length-in-elts)))))
(declaim (ftype (function (height node height full-node generator length) (values node &optional))
extend-full-body-to-new-height))
(defun extend-full-body-to-new-height (new-height full-body old-height full-tail new-elements new-body-length)
(if (= new-height (1+ old-height))
(let* ((node-with-tail-length-in-elts (min (max-body-length-at-height old-height)
new-body-length))
(new-nodes-length-in-elts (- new-body-length node-with-tail-length-in-elts))
(new-trie (make-array new-body-length)))
(setf (svref new-trie 0)
full-body)
(setf (svref new-trie 1)
(fill-behind-node-to-height old-height
full-tail
0
new-elements
node-with-tail-length-in-elts))
(initialize-node-from-elts-generator new-trie
new-height
new-nodes-length-in-elts
new-elements
2)
new-trie)
(let* ((one-more-height (1+ old-height))
(leading-node-length-in-elts (max-body-length-at-height one-more-height))
(leading-node (extend-full-body-to-new-height one-more-height
full-body
old-height
full-tail
new-elements
leading-node-length-in-elts)))
(fill-behind-node-to-height new-height leading-node one-more-height new-elements new-body-length))))
(declaim (ftype (function (node height length &optional index) (values generator &optional))
generate-trie))
(defun generate-trie (trie height length-in-elts &optional (start-at 0))
(let* ((next-idx start-at))
(declare (length next-idx))
(lambda ()
(if (>= next-idx length-in-elts)
(done)
(prog1 (trieref trie height next-idx)
(incf next-idx))))))
(declaim (ftype (function (node height length generator length) (values node &optional))
extend-node-at-height))
(defun extend-node-at-height (not-full-node height current-length-in-elts new-elements target-length-in-elts)
"Extend the trie NOT-FULL-NODE to be longer while maintaining its existing length."
(let* ((child-height (1- height))
(elts-per-full-child (elts-per-node-at-height child-height))
(num-full-leading-children (floor current-length-in-elts elts-per-full-child))
(partial-child-p (not (= num-full-leading-children (cl:length not-full-node))))
(length-in-children (trie-length-in-nodes-at-height target-length-in-elts
child-height))
(new-node (make-array length-in-children)))
(declare (height child-height)
(length elts-per-full-child)
((or (eql 0) node-length) num-full-leading-children)
(node-length length-in-children)
((and node (not null)) new-node))
(if (not partial-child-p)
;; If all our children are full, this operation is easy: construct a new node which has all of the
;; existing children, followed by new nodes taken from the NEW-ELEMENTS.
(progn (sv-copy-subrange new-node not-full-node)
(initialize-node-from-elts-generator new-node
height
(- target-length-in-elts current-length-in-elts)
new-elements
(cl:length not-full-node)))
;; If we have a partial child, things get a little trickier. The resulting node will have 3 parts, and
;; unfortunately, we'll have to do some math to compute each one.
;; 1. Any full direct children of NOT-FULL-NODE can be inserted as children of the new node without
;; copying.
;; 2. The NOT-FULL-NODE has exactly one child which is not full; recurse to extend it as far as
;; possible from the NEW-ELEMENTS.
;; 3. If there are more than enough NEW-ELEMENTS to fill 2 entirely, some entirely new nodes taken
;; from the NEW-ELEMENTS.
(let* ((full-leading-children-length-in-elts (* elts-per-full-child num-full-leading-children))
(partial-existing-child-length-in-elts (- current-length-in-elts
full-leading-children-length-in-elts))
(new-elts-to-fill-partial-existing-child (- elts-per-full-child
partial-existing-child-length-in-elts))
(available-new-elts (- target-length-in-elts current-length-in-elts))
(filled-partial-existing-child-length-in-elts (min elts-per-full-child
(+ partial-existing-child-length-in-elts
available-new-elts)))
(new-children-length-in-elts (max 0
(- available-new-elts
new-elts-to-fill-partial-existing-child))))
(declare (length full-leading-children-length-in-elts
partial-existing-child-length-in-elts
new-elts-to-fill-partial-existing-child
available-new-elts
filled-partial-existing-child-length-in-elts
new-children-length-in-elts))
(sv-copy-subrange new-node not-full-node :count num-full-leading-children)
(setf (svref new-node num-full-leading-children)
(extend-node-at-height (svref not-full-node num-full-leading-children)
child-height
partial-existing-child-length-in-elts
new-elements
filled-partial-existing-child-length-in-elts))
(initialize-node-from-elts-generator new-node
height
new-children-length-in-elts
new-elements
(1+ num-full-leading-children))))
new-node))
(declaim (ftype (function (height node height length generator length)
(values node &optional))
extend-partial-node-to-new-height))
(defun extend-partial-node-to-new-height (new-height
partial-node
current-height
current-length-in-elts
new-elements
target-length-in-elts)
(let* (;; we know that we will be filling the PARTIAL-NODE all the way, that is, that FULL-NODE-LENGTH is
;; less than TARGET-LENGTH-IN-ELTS, because NEW-HEIGHT > CURRENT-HEIGHT.
(full-node-length (elts-per-node-at-height current-height))
(full-node (extend-node-at-height partial-node
current-height
current-length-in-elts
new-elements
full-node-length)))
(fill-behind-node-to-height new-height full-node current-height new-elements target-length-in-elts)))
(declaim (ftype (function (tail-buf) (values generator &optional))
generate-tail)
;; Inlining generator constructors may allow optimizations from treating the generator closure as a
;; local.
(inline generate-tail))
;; TODO: use `define-generator' to offer a DX-allocatable version
(defun generate-tail (tail-buf)
(if tail-buf
(generate-vector tail-buf)
(lambda () (done))))
(declaim (ftype (function (vec generator length) (values vec &optional))
extend-from-generator)
;; `extend-from-generator' is private and will be called only by `extend', `extend-from-list',
;; `extend-from-vector' and `extend-from-vec', so inlining a large function is reasonable. Inlining
;; may allow optimizations by also inlining the NEW-ELEMENTS generator.
(inline extend-from-generator))
(defun extend-from-generator (vec new-elements added-length)
(with-accessors ((height %vec-height)
(length %vec-length)
(tail %vec-tail)
(body %vec-body))
vec
(let* ((new-length (+ length added-length))
(new-height (length-required-height new-length))
(new-body-length (length-without-tail-buf new-length))
(new-tail-length (- new-length new-body-length)))
(declare (length new-length new-body-length)
(height new-height)
(tail-length new-tail-length))
(cond ((and (not tail)
(< added-length +branch-rate+))
;; no tail and new items fit in tail: grow a tail
(copy-vec vec
:length new-length
:tail (make-tail added-length new-elements)))
((< (+ added-length (tail-length vec)) +branch-rate+)
;; have tail, but new elements will fit in it
(copy-vec vec
:length new-length
:tail (make-tail new-tail-length
;; TODO: dx-allocate
(generate-concat (generate-tail tail) new-elements))))
((and (not body)
(= (tail-length vec) +branch-rate+))
;; no body, full tail: fold tail buf into body, then grow from new-elements.
(%make-vec :height new-height
:length new-length
:body (fill-behind-node-to-height new-height tail 0 new-elements new-body-length)
:tail (make-tail new-tail-length new-elements)))
((not body)
;; no body, tail not full: construct vec from elements of old tail and new elements
(%make-vec :length new-length
:height new-height
:body (alloc-trie new-height
new-body-length
;; TODO: dx-allocate
(generate-concat (generate-tail tail) new-elements))
:tail (make-tail new-tail-length new-elements)))
((and (= (body-length vec) (max-body-length-at-height height))
(= (tail-buf-length tail) +branch-rate+))
;; tail and body are both full: grow one or more extra layers of height, move your old tail buf
;; into your newly-expanded body, distribute new-elements between body and new tail.
(%make-vec :height new-height
:length new-length
:body (extend-full-body-to-new-height new-height
body
height
tail
new-elements
new-body-length)
:tail (make-tail new-tail-length new-elements)))
((= (body-length vec) (max-body-length-at-height height))
;; body is full, tail is not: grow to new height, distribute elements from old tail and
;; NEW-ELEMENTS between extended body and new tail
(%make-vec :height new-height
:length new-length
:body (fill-behind-node-to-height new-height
body
height
;; TODO: dx-allocate
(generate-concat (generate-tail tail)
new-elements)
new-body-length)
:tail (make-tail new-tail-length new-elements)))
;; TODO: missed case: not full body, full tail. small win possible by sharing structure with
;; existing tail buf.
((= height new-height)
;; body is not full, but do not need to grow additional height: distribute elements from your old
;; tail and the NEW-ELEMENTS between body and new tail.
(%make-vec :height height
:length new-length
:body (extend-node-at-height body
height
(body-length vec)
;; TODO: dx-allocate
(generate-concat (generate-tail tail)
new-elements)
new-body-length)
:tail (make-tail new-tail-length new-elements)))
(t
;; body is not full; need to grow additional height to fit new elements
(%make-vec :height new-height
:length new-length
:body (extend-partial-node-to-new-height new-height
body
height
(body-length vec)
;; TODO: dx-allocate
(generate-concat (generate-tail tail)
new-elements)
new-body-length)
:tail (make-tail new-tail-length new-elements)))))))
(declaim (ftype (function (vec &rest t) (values vec &optional))
extend))
(defun extend (vec &rest new-elements)
"Return a new `vec' with all the contents of VEC followed by the NEW-ELEMENTS.
This operation will attempt to share as much structure as possible with the original VEC.
# Time complexity
Let N be the number of elements in VEC, and M be the number of NEW-ELEMENTS.
For M < +BRANCH-RATE+, this operation's amortized time complexity is O((M * log_{+branch-rate+}N) /
+branch-rate+), because every (+branch-rate+ / M) `extend's will overflow the tail buffer and require
log_{+branch-rate+}N operations to splice it into the body.
For M > +BRANCH-RATE+, this operation's time complexity is O(M * log_{+branch-rate+}(M + N))."
(declare (dynamic-extent new-elements))
(with-list-generator (elts-generator new-elements)
(extend-from-generator vec elts-generator (cl:length new-elements))))
(declaim (ftype (function (vec list) (values vec &optional))
extend-from-list))
(defun extend-from-list (vec new-elements)
"Return a new `vec' with all the contents of VEC followed by the NEW-ELEMENTS.
See `extend' for more information."
(with-list-generator (elts-generator new-elements)
(extend-from-generator vec elts-generator (cl:length new-elements))))
(declaim (ftype (function (vec vector) (values vec &optional))
extend-from-vector))
(defun extend-from-vector (vec new-elements)
"Return a new `vec' with all the contents of VEC followed by the NEW-ELEMENTS.
See `extend' for more information."
;; It would be nice to declare `extend-from-vector' as `inline' in order to optimize based on the
;; element-type and simple-ness of the NEW-ELEMENTS vector, but that would result in inlining the large
;; `extend-from-generator' into each callsite.
;; CONSIDER: locally declaring `extend-from-generator' as `notinline'.
;; CONSIDER: compiler-macro trickery to specialize.
#+sbcl (declare (sb-ext:muffle-conditions sb-ext:compiler-note))
(with-vector-generator (elts-generator new-elements)
(extend-from-generator vec elts-generator (cl:length new-elements))))
;;; POP-BACK and helpers
(declaim (ftype (function (node height) (values (or null node) full-node height &optional))
pop-last-node-from-body))
(defun pop-last-node-from-body (body height)
(cond ((zerop height)
;; height is zero: current body becomes tail, resulting body is empty
(values nil body 0))
((= (cl:length body) 1)
;; only one child: pop from child, decrease height
(pop-last-node-from-body (svref body 0) (1- height)))
((= height 1)
;; direct children are leaves: do a SV-POP-BACK to extract the last node
(multiple-value-bind (new-body new-tail)
(sv-pop-back body)
(values new-body new-tail height)))
(:otherwise
;; recurse to remove a tail from your last child
(let* ((child-height (1- height))
(num-children (cl:length body))
(num-copied-children (1- num-children))
(new-body (make-array num-children)))
(declare ((and node (not null)) new-body))
(sv-copy-subrange new-body body :count num-copied-children)
(multiple-value-bind (new-last-child new-tail new-last-child-height)
(pop-last-node-from-body (svref body num-copied-children)
child-height)
(setf (svref new-body num-copied-children)
(wrap-in-spine (- child-height new-last-child-height)
new-last-child))
(values new-body
new-tail
height))))))
(declaim (ftype (function (vec) (values vec t &optional))
pop-back))
(defun pop-back (vec)
"Remove the last element from VEC and return it as the secondary value.
Returns two values: a new `vec' like VEC but without its last element, and the element removed.
Signals an error of class `pop-back-empty' if VEC is empty.
# Time complexity
This operation runs in amortized O(1) time. One out of every `+branch-rate+' `pop-back's will run in
O(log_{+branch-rate+}N) time in the length of the input VEC, and the rest will run in constant time."
(with-accessors ((tail %vec-tail)
(body %vec-body)
(length %vec-length)
(height %vec-height))
vec
(cond ((zerop length) (error 'pop-back-empty))
(tail (multiple-value-bind (new-tail popped-element)
(sv-pop-back tail)
(values (copy-vec vec
:length (1- length)
:tail new-tail)
popped-element)))
(:else (multiple-value-bind (new-body full-tail new-height)
(pop-last-node-from-body body height)
(multiple-value-bind (new-tail popped-element)
(sv-pop-back full-tail)
(values (%make-vec :height new-height
:length (1- length)
:tail new-tail