/
PersistentVector.cs
1257 lines (1042 loc) · 38 KB
/
PersistentVector.cs
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
/**
* Copyright (c) Rich Hickey. All rights reserved.
* The use and distribution terms for this software are covered by the
* Eclipse Public License 1.0 (http://opensource.org/licenses/eclipse-1.0.php)
* which can be found in the file epl-v10.html at the root of this distribution.
* By using this software in any fashion, you are agreeing to be bound by
* the terms of this license.
* You must not remove this notice, or any other, from this software.
**/
/**
* Author: David Miller
**/
using System;
using System.Collections;
using System.Threading;
using System.Collections.Generic;
namespace clojure.lang
{
/// <summary>
/// Implements a persistent vector using a specialized form of array-mapped hash trie.
/// </summary>
[Serializable]
public class PersistentVector: APersistentVector, IObj, IEditableCollection, IEnumerable, IReduce, IKVReduce, IDrop
{
#region Node class
[Serializable]
public sealed class Node
{
#region Data
[NonSerialized]
readonly AtomicReference<Thread> _edit;
public AtomicReference<Thread> Edit
{
get { return _edit; }
}
readonly object[] _array;
public object[] Array
{
get { return _array; }
}
#endregion
#region C-tors
public Node(AtomicReference<Thread> edit, object[] array)
{
_edit = edit;
_array = array;
}
public Node(AtomicReference<Thread> edit)
{
_edit = edit;
_array = new object[32];
}
#endregion
}
#endregion
#region Data
static readonly AtomicReference<Thread> NoEdit = new AtomicReference<Thread>();
internal static readonly Node EmptyNode = new Node(NoEdit, new object[32]);
readonly int _cnt;
readonly int _shift;
readonly Node _root;
readonly object[] _tail;
public int Shift { get { return _shift; } }
public Node Root { get { return _root; } }
public object[] Tail() { return _tail; }
readonly IPersistentMap _meta;
/// <summary>
/// An empty <see cref="PersistentVector">PersistentVector</see>.
/// </summary>
static public readonly PersistentVector EMPTY = new PersistentVector(0,5,EmptyNode, new object[0]);
#endregion
#region Transient vector conj
private sealed class TransientVectorConjer : AFn
{
public override object invoke(object coll, object val)
{
return ((ITransientVector)coll).conj(val);
}
public override object invoke(object coll)
{
return coll;
}
}
static readonly IFn _transientVectorConj = new TransientVectorConjer();
#endregion
#region C-tors and factory methods
[System.Diagnostics.CodeAnalysis.SuppressMessage("Style", "IDE1006:Naming Styles", Justification = "ClojureJVM name match")]
public static PersistentVector adopt(Object[] items)
{
return new PersistentVector(items.Length, 5, EmptyNode, items);
}
/// <summary>
/// Create a <see cref="PersistentVector">PersistentVector</see> from an <see cref="ISeq">IReduceInit</see>.
/// </summary>
/// <param name="items"></param>
/// <returns></returns>
[System.Diagnostics.CodeAnalysis.SuppressMessage("Style", "IDE1006:Naming Styles", Justification = "ClojureJVM name match")]
static public PersistentVector create(IReduceInit items)
{
TransientVector ret = (TransientVector)EMPTY.asTransient();
items.reduce(_transientVectorConj, ret);
return (PersistentVector)ret.persistent();
}
/// <summary>
/// Create a <see cref="PersistentVector">PersistentVector</see> from an <see cref="ISeq">ISeq</see>.
/// </summary>
/// <param name="items">A sequence of items.</param>
/// <returns>An initialized vector.</returns>
[System.Diagnostics.CodeAnalysis.SuppressMessage("Style", "IDE1006:Naming Styles", Justification = "ClojureJVM name match")]
static public PersistentVector create(ISeq items)
{
Object[] arr = new Object[32];
int i = 0;
for (; items != null && i < 32; items = items.next())
arr[i++] = items.first();
if (items != null)
{
// >32, construct with array directly
PersistentVector start = new PersistentVector(32, 5, EmptyNode, arr);
TransientVector ret = (TransientVector)start.asTransient();
for (; items != null; items = items.next())
ret = (TransientVector)ret.conj(items.first());
return (PersistentVector)ret.persistent();
}
else if (i == 32)
{
// exactly 32, skip copy
return new PersistentVector(32, 5, EmptyNode, arr);
}
else
{
// <32, copy to minimum array and construct
Object[] arr2 = new Object[i];
Array.Copy(arr, 0, arr2, 0, i);
return new PersistentVector(i, 5, EmptyNode, arr2);
}
}
/// <summary>
/// Create a <see cref="PersistentVector">PersistentVector</see> from an array of items.
/// </summary>
/// <param name="items"></param>
/// <returns></returns>
[System.Diagnostics.CodeAnalysis.SuppressMessage("Style", "IDE1006:Naming Styles", Justification = "ClojureJVM name match")]
static public PersistentVector create(params object[] items)
{
ITransientCollection ret = EMPTY.asTransient();
foreach (object item in items)
ret = ret.conj(item);
return (PersistentVector)ret.persistent();
}
/// <summary>
/// Create a <see cref="PersistentVector">PersistentVector</see> from an IEnumerable.
/// </summary>
/// <param name="items"></param>
/// <returns></returns>
[System.Diagnostics.CodeAnalysis.SuppressMessage("Style", "IDE1006:Naming Styles", Justification = "ClojureJVM name match")]
static public PersistentVector create1(IEnumerable items)
{
// optimize common case
if (items is IList ilist)
{
int size = ilist.Count;
if (size <= 32)
{
Object[] arr = new Object[size];
ilist.CopyTo(arr, 0);
return new PersistentVector(size, 5, PersistentVector.EmptyNode, arr);
}
}
ITransientCollection ret = EMPTY.asTransient();
foreach (object item in items)
{
ret = ret.conj(item);
}
return (PersistentVector)ret.persistent();
}
/// <summary>
/// Initialize a <see cref="PersistentVector">PersistentVector</see> from basic components.
/// </summary>
/// <param name="cnt"></param>
/// <param name="shift"></param>
/// <param name="root"></param>
/// <param name="tail"></param>
public PersistentVector(int cnt, int shift, Node root, object[] tail)
{
_meta = null;
_cnt = cnt;
_shift = shift;
_root = root;
_tail = tail;
}
/// <summary>
/// Initialize a <see cref="PersistentVector">PersistentVector</see> from given metadata and basic components.
/// </summary>
/// <param name="meta"></param>
/// <param name="cnt"></param>
/// <param name="shift"></param>
/// <param name="root"></param>
/// <param name="tail"></param>
PersistentVector(IPersistentMap meta, int cnt, int shift, Node root, object[] tail)
{
_meta = meta;
_cnt = cnt;
_shift = shift;
_root = root;
_tail = tail;
}
#endregion
#region IObj members
public IObj withMeta(IPersistentMap meta)
{
if (_meta == meta)
return this;
return new PersistentVector(meta, _cnt, _shift, _root, _tail);
}
#endregion
#region IMeta Members
public IPersistentMap meta()
{
return _meta;
}
#endregion
#region IPersistentVector members
[System.Diagnostics.CodeAnalysis.SuppressMessage("Style", "IDE1006:Naming Styles", Justification = "ClojureJVM name match")]
int tailoff()
{
if (_cnt < 32)
return 0;
return ((_cnt - 1) >> 5) << 5;
}
/// <summary>
/// Get the i-th item in the vector.
/// </summary>
/// <param name="i">The index of the item to retrieve/</param>
/// <returns>The i-th item</returns>
/// <remarks>Throws an exception if the index <c>i</c> is not in the range of the vector's elements.</remarks>
public override object nth(int i)
{
object[] node = ArrayFor(i);
return node[i & 0x01f];
}
public override Object nth(int i, Object notFound)
{
if (i >= 0 && i < _cnt)
return nth(i);
return notFound;
}
object[] ArrayFor(int i)
{
if (i >= 0 && i < _cnt)
{
if (i >= tailoff())
return _tail;
Node node = _root;
for (int level = _shift; level > 0; level -= 5)
node = (Node)node.Array[(i >> level) & 0x01f];
return node.Array;
}
throw new ArgumentOutOfRangeException("i");
}
/// <summary>
/// Return a new vector with the i-th value set to <c>val</c>.
/// </summary>
/// <param name="i">The index of the item to set.</param>
/// <param name="val">The new value</param>
/// <returns>A new (immutable) vector v with v[i] == val.</returns>
public override IPersistentVector assocN(int i, Object val)
{
if (i >= 0 && i < _cnt)
{
if (i >= tailoff())
{
object[] newTail = new object[_tail.Length];
Array.Copy(_tail, newTail, _tail.Length);
newTail[i & 0x01f] = val;
return new PersistentVector(meta(), _cnt, _shift, _root, newTail);
}
return new PersistentVector(meta(), _cnt, _shift, doAssoc(_shift, _root, i, val), _tail);
}
if (i == _cnt)
return cons(val);
throw new ArgumentOutOfRangeException("i");
}
[System.Diagnostics.CodeAnalysis.SuppressMessage("Style", "IDE1006:Naming Styles", Justification = "ClojureJVM name match")]
static private Node doAssoc(int level, Node node, int i, object val)
{
Node ret = new Node(node.Edit, (object[])node.Array.Clone());
if (level == 0)
ret.Array[i & 0x01f] = val;
else
{
int subidx = ( i >> level ) & 0x01f;
ret.Array[subidx] = doAssoc(level-5,(Node) node.Array[subidx], i, val);
}
return ret;
}
/// <summary>
/// Creates a new vector with a new item at the end.
/// </summary>
/// <param name="o">The item to add to the vector.</param>
/// <returns>A new (immutable) vector with the objected added at the end.</returns>
/// <remarks>Overrides <c>cons</c> in <see cref="IPersistentCollection">IPersistentCollection</see> to specialize the return value.</remarks>
public override IPersistentVector cons(object o)
{
//if (_tail.Length < 32)
if ( _cnt - tailoff() < 32 )
{
object[] newTail = new object[_tail.Length + 1];
Array.Copy(_tail, newTail, _tail.Length);
newTail[_tail.Length] = o;
return new PersistentVector(meta(), _cnt + 1, _shift, _root, newTail);
}
// full tail, push into tree
Node newroot;
Node tailnode = new Node(_root.Edit, _tail);
int newshift = _shift;
// overflow root?
if ((_cnt >> 5) > (1 << _shift))
{
newroot = new Node(_root.Edit);
newroot.Array[0] = _root;
newroot.Array[1] = newPath(_root.Edit, _shift, tailnode);
newshift += 5;
}
else
newroot = pushTail(_shift, _root, tailnode);
return new PersistentVector(meta(), _cnt + 1, newshift, newroot, new object[] { o });
}
[System.Diagnostics.CodeAnalysis.SuppressMessage("Style", "IDE1006:Naming Styles", Justification = "ClojureJVM name match")]
private Node pushTail(int level, Node parent, Node tailnode)
{
// if parent is leaf, insert node,
// else does it map to existing child? -> nodeToInsert = pushNode one more level
// else alloc new path
// return nodeToInsert placed in copy of parent
int subidx = ((_cnt - 1) >> level) & 0x01f;
Node ret = new Node(parent.Edit, (object[])parent.Array.Clone());
Node nodeToInsert;
if (level == 5)
nodeToInsert = tailnode;
else
{
Node child = (Node)parent.Array[subidx];
nodeToInsert = (child != null
? pushTail(level - 5, child, tailnode)
: newPath(_root.Edit, level - 5, tailnode));
}
ret.Array[subidx] = nodeToInsert;
return ret;
}
[System.Diagnostics.CodeAnalysis.SuppressMessage("Style", "IDE1006:Naming Styles", Justification = "ClojureJVM name match")]
static Node newPath(AtomicReference<Thread> edit, int level, Node node)
{
if (level == 0)
return node;
Node ret = new Node(edit);
ret.Array[0] = newPath(edit, level - 5, node);
return ret;
}
#endregion
#region IPersistentCollection members
/// <summary>
/// Gets the number of items in the collection.
/// </summary>
/// <returns>The number of items in the collection.</returns>
public override int count()
{
return _cnt;
}
/// <summary>
/// Gets an empty collection of the same type.
/// </summary>
/// <returns>An emtpy collection.</returns>
public override IPersistentCollection empty()
{
return (IPersistentCollection)EMPTY.withMeta(meta());
}
#endregion
#region IPersistentStack members
/// <summary>
/// Returns a new stack with the top element popped.
/// </summary>
/// <returns>The new stack.</returns>
public override IPersistentStack pop()
{
if ( _cnt == 0 )
throw new InvalidOperationException("Can't pop empty vector");
if ( _cnt == 1)
return (IPersistentStack)EMPTY.withMeta(meta());
//if ( _tail.Length > 1 )
if (_cnt - tailoff() > 1)
{
object[] newTail = new object[_tail.Length-1];
Array.Copy(_tail,newTail,newTail.Length);
return new PersistentVector(meta(),_cnt-1,_shift,_root,newTail);
}
object[] newtail = ArrayFor(_cnt - 2);
Node newroot = popTail(_shift,_root);
int newshift = _shift;
if ( newroot == null )
newroot = EmptyNode;
if ( _shift > 5 && newroot.Array[1] == null )
{
newroot = (Node)newroot.Array[0];
newshift -= 5;
}
return new PersistentVector(meta(), _cnt - 1, newshift, newroot, newtail);
}
[System.Diagnostics.CodeAnalysis.SuppressMessage("Style", "IDE1006:Naming Styles", Justification = "ClojureJVM name match")]
private Node popTail(int level, Node node)
{
int subidx = ((_cnt - 2) >> level) & 0x01f;
if (level > 5)
{
Node newchild = popTail(level - 5, (Node)node.Array[subidx]);
if (newchild == null && subidx == 0)
return null;
else
{
Node ret = new Node(_root.Edit, (object[])node.Array.Clone());
ret.Array[subidx] = newchild;
return ret;
}
}
else if (subidx == 0)
return null;
else
{
Node ret = new Node(_root.Edit, (object[])node.Array.Clone());
ret.Array[subidx] = null;
return ret;
}
}
#endregion
#region IFn members
#endregion
#region Seqable members
public override ISeq seq()
{
return chunkedSeq();
}
#endregion
#region ChunkedSeq
[System.Diagnostics.CodeAnalysis.SuppressMessage("Style", "IDE1006:Naming Styles", Justification = "ClojureJVM name match")]
public IChunkedSeq chunkedSeq()
{
if (count() == 0)
return null;
return new ChunkedSeq(this, 0, 0);
}
[Serializable]
sealed public class ChunkedSeq : ASeq, IChunkedSeq, Counted, IReduce, IDrop, IEnumerable
{
#region Data
readonly PersistentVector _vec;
readonly object[] _node;
readonly int _i;
readonly int _offset;
public int Offset
{
get { return _offset; }
}
public PersistentVector Vec
{
get { return _vec; }
}
#endregion
#region C-tors
public ChunkedSeq(PersistentVector vec, int i, int offset)
{
_vec = vec;
_i = i;
_offset = offset;
_node = vec.ArrayFor(i);
}
ChunkedSeq(IPersistentMap meta, PersistentVector vec, object[] node, int i, int offset)
: base(meta)
{
_vec = vec;
_node = node;
_i = i;
_offset = offset;
}
public ChunkedSeq(PersistentVector vec, object[] node, int i, int offset)
{
_vec = vec;
_node = node;
_i = i;
_offset = offset;
}
#endregion
#region IObj members
public override IObj withMeta(IPersistentMap meta)
{
return (meta == _meta)
? this
: new ChunkedSeq(meta, _vec, _node, _i, _offset);
}
#endregion
#region IChunkedSeq Members
public IChunk chunkedFirst()
{
return new ArrayChunk(_node, _offset);
}
public ISeq chunkedNext()
{
if (_i + _node.Length < _vec._cnt)
return new ChunkedSeq(_vec, _i + _node.Length, 0);
return null;
}
public ISeq chunkedMore()
{
ISeq s = chunkedNext();
if (s == null)
return PersistentList.EMPTY;
return s;
}
#endregion
#region IPersistentCollection Members
//public new IPersistentCollection cons(object o)
//{
// throw new NotImplementedException();
//}
#endregion
#region ISeq members
public override object first()
{
return _node[_offset];
}
public override ISeq next()
{
if (_offset + 1 < _node.Length)
return new ChunkedSeq(_vec, _node, _i, _offset + 1);
return chunkedNext();
}
#endregion
#region Counted members
public override int count()
{
return _vec._cnt - (_i + _offset);
}
#endregion
#region IReduce members
public object reduce(IFn f)
{
object acc;
if (_i + _offset < _vec._cnt)
acc = _node[_offset];
else
return f.invoke();
for (int j = _offset + 1; j < _node.Length; j++)
{
acc = f.invoke(acc, _node[j]);
if (RT.isReduced(acc))
return ((IDeref)acc).deref();
}
int step = 0;
for (int ii = _i + _node.Length; ii < _vec._cnt; ii += step)
{
object[] array = _vec.ArrayFor(ii);
for (int j = 0; j < array.Length; j++)
{
acc = f.invoke(acc, array[j]);
if (RT.isReduced(acc))
return ((IDeref)acc).deref();
}
step = array.Length;
}
return acc;
}
public object reduce(IFn f, object start)
{
object acc = start;
for (int j = _offset; j < _node.Length; j++)
{
acc = f.invoke(acc, _node[j]);
if (RT.isReduced(acc))
return ((IDeref)acc).deref();
}
int step = 0;
for (int ii = _i + _node.Length; ii < _vec._cnt; ii += step)
{
object[] array = _vec.ArrayFor(ii);
for (int j = 0; j < array.Length; j++)
{
acc = f.invoke(acc, array[j]);
if (RT.isReduced(acc))
return ((IDeref)acc).deref();
}
step = array.Length;
}
return acc;
}
#endregion
#region IDrop members
public Sequential drop(int n)
{
int o = _offset + n;
if (o < _node.Length) // in current array
return new ChunkedSeq(_vec, _node, _i, o);
else
{
int i = _i + o;
if (i < _vec._cnt) // in vec
{
var array = _vec.ArrayFor(i);
int newOffset = i % 32;
return new ChunkedSeq(_vec, array, i - newOffset, newOffset);
}
else
return null;
}
}
#endregion
#region IEnumerable
public override IEnumerator<object> GetEnumerator()
{
return _vec.RangedIteratorT(_i+_offset,_vec._cnt );
}
IEnumerator IEnumerable.GetEnumerator()
{
return GetEnumerator();
}
#endregion
}
#endregion
#region IEditableCollection Members
public ITransientCollection asTransient()
{
return new TransientVector(this);
}
#endregion
#region TransientVector class
class TransientVector : AFn, ITransientVector, ITransientAssociative2, Counted
{
#region Data
volatile int _cnt;
volatile int _shift;
volatile Node _root;
volatile object[] _tail;
#endregion
#region Ctors
TransientVector(int cnt, int shift, Node root, Object[] tail)
{
_cnt = cnt;
_shift = shift;
_root = root;
_tail = tail;
}
public TransientVector(PersistentVector v)
: this(v._cnt, v._shift, EditableRoot(v._root), EditableTail(v._tail))
{
}
#endregion
#region Counted Members
public int count()
{
EnsureEditable();
return _cnt;
}
#endregion
#region Implementation
void EnsureEditable()
{
Thread owner = _root.Edit.Get();
if (owner == null)
throw new InvalidOperationException("Transient used after persistent! call");
}
Node EnsureEditable(Node node)
{
if (node.Edit == _root.Edit)
return node;
return new Node(_root.Edit, (object[])node.Array.Clone());
}
static Node EditableRoot(Node node)
{
return new Node(new AtomicReference<Thread>(Thread.CurrentThread), (object[])node.Array.Clone());
}
static object[] EditableTail(object[] tl)
{
object[] ret = new object[32];
Array.Copy(tl, ret, tl.Length);
return ret;
}
Node PushTail(int level, Node parent, Node tailnode)
{
//if parent is leaf, insert node,
// else does it map to an existing child? -> nodeToInsert = pushNode one more level
// else alloc new path
//return nodeToInsert placed in copy of parent
int subidx = ((_cnt - 1) >> level) & 0x01f;
Node ret = new Node(parent.Edit, (object[])parent.Array.Clone());
Node nodeToInsert;
if (level == 5)
{
nodeToInsert = tailnode;
}
else
{
Node child = (Node)parent.Array[subidx];
nodeToInsert = (child != null)
? PushTail(level - 5, child, tailnode)
: newPath(_root.Edit, level - 5, tailnode);
}
ret.Array[subidx] = nodeToInsert;
return ret;
}
int Tailoff()
{
if (_cnt < 32)
return 0;
return ((_cnt - 1) >> 5) << 5;
}
object[] ArrayFor(int i)
{
if (i >= 0 && i < _cnt)
{
if (i >= Tailoff())
return _tail;
Node node = _root;
for (int level = _shift; level > 0; level -= 5)
node = (Node)node.Array[(i >> level) & 0x01f];
return node.Array;
}
throw new ArgumentOutOfRangeException("i");
}
object[] EditableArrayFor(int i)
{
if (i >= 0 && i < _cnt)
{
if (i >= Tailoff())
return _tail;
Node node = _root;
for (int level = _shift; level > 0; level -= 5)
node = EnsureEditable((Node)node.Array[(i >> level) & 0x01f]);
return node.Array;
}
throw new ArgumentOutOfRangeException("i");
}
#endregion
#region ITransientVector Members
public object nth(int i)
{
object[] node = ArrayFor(i);
return node[i & 0x01f];
}
public object nth(int i, object notFound)
{
if (i >= 0 && i < count())
return nth(i);
return notFound;
}
public ITransientVector assocN(int i, object val)
{
EnsureEditable();
if (i >= 0 && i < _cnt)
{
if (i >= Tailoff())
{
_tail[i & 0x01f] = val;
return this;
}
_root = doAssoc(_shift, _root, i, val);
return this;
}
if (i == _cnt)
return (ITransientVector)conj(val);
throw new ArgumentOutOfRangeException("i");
}
[System.Diagnostics.CodeAnalysis.SuppressMessage("Style", "IDE1006:Naming Styles", Justification = "ClojureJVM name match")]
Node doAssoc(int level, Node node, int i, Object val)
{
node = EnsureEditable(node);
Node ret = new Node(node.Edit, (object[])node.Array.Clone());
if (level == 0)
{
ret.Array[i & 0x01f] = val;
}
else
{
int subidx = (i >> level) & 0x01f;
ret.Array[subidx] = doAssoc(level - 5, (Node)node.Array[subidx], i, val);
}
return ret;
}
public ITransientVector pop()
{
EnsureEditable();
if (_cnt == 0)
throw new InvalidOperationException("Can't pop empty vector");
if (_cnt == 1)
{
_cnt = 0;
return this;
}
int i = _cnt - 1;
// pop in tail?
if ((i & 0x01f) > 0)
{
--_cnt;
return this;
}
object[] newtail = EditableArrayFor(_cnt - 2);
Node newroot = PopTail(_shift, _root);
int newshift = _shift;
if (newroot == null)
{
newroot = new Node(_root.Edit);
}
if (_shift > 5 && newroot.Array[1] == null)
{
newroot = EnsureEditable((Node)newroot.Array[0]);
newshift -= 5;
}
_root = newroot;
_shift = newshift;
--_cnt;
_tail = newtail;
return this;
}
private Node PopTail(int level, Node node)
{
node = EnsureEditable(node);