-
Notifications
You must be signed in to change notification settings - Fork 99
/
Copy pathBuffer.mo
2660 lines (2457 loc) · 68.6 KB
/
Buffer.mo
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
/// Class `Buffer<X>` provides a mutable list of elements of type `X`.
/// The class wraps and resizes an underyling array that holds the elements,
/// and thus is comparable to ArrayLists or Vectors in other languages.
///
/// When required, the current state of a buffer object can be converted to a fixed-size array of its elements.
/// This is recommended for example when storing a buffer to a stable variable.
///
/// Throughout this documentation, two terms come up that can be confused: `size`
/// and `capacity`. `size` is the length of the list that the buffer represents.
/// `capacity` is the length of the underyling array that backs this list.
/// `capacity` >= `size` is an invariant for this class.
///
/// Like arrays, elements in the buffer are ordered by indices from 0 to `size`-1.
///
/// WARNING: Certain operations are amortized O(1) time, such as `add`, but run
/// in worst case O(n) time. These worst case runtimes may exceed the cycles limit
/// per message if the size of the buffer is large enough. Grow these structures
/// with discretion. All amortized operations below also list the worst case runtime.
///
/// Constructor:
/// The argument `initCapacity` determines the initial capacity of the array.
/// The underlying array grows by a factor of 1.5 when its current capacity is
/// exceeded. Further, when the size of the buffer shrinks to be less than 1/4th
/// of the capacity, the underyling array is shrunk by a factor of 2.
///
/// Example:
/// ```motoko name=initialize
/// import Buffer "mo:base/Buffer";
///
/// let buffer = Buffer.Buffer<Nat>(3); // Creates a new Buffer
/// ```
///
/// Runtime: O(initCapacity)
///
/// Space: O(initCapacity)
import Prim "mo:⛔";
import Result "Result";
import Order "Order";
import Array "Array";
module {
type Order = Order.Order;
// The following constants are used to manage the capacity.
// The length of `elements` is increased by `INCREASE_FACTOR` when capacity is reached.
// The length of `elements` is decreased by `DECREASE_FACTOR` when capacity is strictly less than
// `DECREASE_THRESHOLD`.
// INCREASE_FACTOR = INCREASE_FACTOR_NUME / INCREASE_FACTOR_DENOM (with floating point division)
// Keep INCREASE_FACTOR low to minimize cycle limit problem
private let INCREASE_FACTOR_NUME = 3;
private let INCREASE_FACTOR_DENOM = 2;
private let DECREASE_THRESHOLD = 4; // Don't decrease capacity too early to avoid thrashing
private let DECREASE_FACTOR = 2;
private let DEFAULT_CAPACITY = 8;
private func newCapacity(oldCapacity : Nat) : Nat {
if (oldCapacity == 0) {
1
} else {
// calculates ceil(oldCapacity * INCREASE_FACTOR) without floats
((oldCapacity * INCREASE_FACTOR_NUME) + INCREASE_FACTOR_DENOM - 1) / INCREASE_FACTOR_DENOM
}
};
public class Buffer<X>(initCapacity : Nat) = this {
var _size : Nat = 0; // avoid name clash with `size()` method
var elements : [var ?X] = Prim.Array_init(initCapacity, null);
/// Returns the current number of elements in the buffer.
///
/// Example:
/// ```motoko include=initialize
/// buffer.size() // => 0
/// ```
///
/// Runtime: O(1)
///
/// Space: O(1)
public func size() : Nat = _size;
/// Adds a single element to the end of the buffer, doubling
/// the size of the array if capacity is exceeded.
///
/// Example:
/// ```motoko include=initialize
///
/// buffer.add(0); // add 0 to buffer
/// buffer.add(1);
/// buffer.add(2);
/// buffer.add(3); // causes underlying array to increase in capacity
/// Buffer.toArray(buffer) // => [0, 1, 2, 3]
/// ```
///
/// Amortized Runtime: O(1), Worst Case Runtime: O(size)
///
/// Amortized Space: O(1), Worst Case Space: O(size)
public func add(element : X) {
if (_size == elements.size()) {
reserve(newCapacity(elements.size()))
};
elements[_size] := ?element;
_size += 1
};
/// Returns the element at index `index`. Traps if `index >= size`. Indexing is zero-based.
///
/// Example:
/// ```motoko include=initialize
///
/// buffer.add(10);
/// buffer.add(11);
/// buffer.get(0); // => 10
/// ```
///
/// Runtime: O(1)
///
/// Space: O(1)
public func get(index : Nat) : X {
switch (elements[index]) {
case (?element) element;
case null Prim.trap("Buffer index out of bounds in get")
}
};
/// Returns the element at index `index` as an option.
/// Returns `null` when `index >= size`. Indexing is zero-based.
///
/// Example:
/// ```motoko include=initialize
///
/// buffer.add(10);
/// buffer.add(11);
/// let x = buffer.getOpt(0); // => ?10
/// let y = buffer.getOpt(2); // => null
/// ```
///
/// Runtime: O(1)
///
/// Space: O(1)
public func getOpt(index : Nat) : ?X {
if (index < _size) {
elements[index]
} else {
null
}
};
/// Overwrites the current element at `index` with `element`. Traps if
/// `index` >= size. Indexing is zero-based.
///
/// Example:
/// ```motoko include=initialize
///
/// buffer.add(10);
/// buffer.put(0, 20); // overwrites 10 at index 0 with 20
/// Buffer.toArray(buffer) // => [20]
/// ```
///
/// Runtime: O(1)
///
/// Space: O(1)
public func put(index : Nat, element : X) {
if (index >= _size) {
Prim.trap "Buffer index out of bounds in put"
};
elements[index] := ?element
};
/// Removes and returns the last item in the buffer or `null` if
/// the buffer is empty.
///
/// Example:
/// ```motoko include=initialize
///
/// buffer.add(10);
/// buffer.add(11);
/// buffer.removeLast(); // => ?11
/// ```
///
/// Amortized Runtime: O(1), Worst Case Runtime: O(size)
///
/// Amortized Space: O(1), Worst Case Space: O(size)
public func removeLast() : ?X {
if (_size == 0) {
return null
};
_size -= 1;
let lastElement = elements[_size];
elements[_size] := null;
if (_size < elements.size() / DECREASE_THRESHOLD) {
// FIXME should this new capacity be a function of _size
// instead of the current capacity? E.g. _size * INCREASE_FACTOR
reserve(elements.size() / DECREASE_FACTOR)
};
lastElement
};
/// Removes and returns the element at `index` from the buffer.
/// All elements with index > `index` are shifted one position to the left.
/// This may cause a downsizing of the array.
///
/// Traps if index >= size.
///
/// WARNING: Repeated removal of elements using this method is ineffecient
/// and might be a sign that you should consider a different data-structure
/// for your use case.
///
/// Example:
/// ```motoko include=initialize
///
/// buffer.add(10);
/// buffer.add(11);
/// buffer.add(12);
/// let x = buffer.remove(1); // evaluates to 11. 11 no longer in list.
/// Buffer.toArray(buffer) // => [10, 12]
/// ```
///
/// Runtime: O(size)
///
/// Amortized Space: O(1), Worst Case Space: O(size)
public func remove(index : Nat) : X {
if (index >= _size) {
Prim.trap "Buffer index out of bounds in remove"
};
let element = elements[index];
// copy elements to new array and shift over in one pass
if ((_size - 1) : Nat < elements.size() / DECREASE_THRESHOLD) {
let elements2 = Prim.Array_init<?X>(elements.size() / DECREASE_FACTOR, null);
var i = 0;
var j = 0;
label l while (i < _size) {
if (i == index) {
i += 1;
continue l
};
elements2[j] := elements[i];
i += 1;
j += 1
};
elements := elements2
} else {
// just shift over elements
var i = index;
while (i < (_size - 1 : Nat)) {
elements[i] := elements[i + 1];
i += 1
};
elements[_size - 1] := null
};
_size -= 1;
switch (element) {
case (?element) {
element
};
case null {
Prim.trap "Malformed buffer in remove"
}
}
};
/// Resets the buffer. Capacity is set to 8.
///
/// Example:
/// ```motoko include=initialize
///
/// buffer.add(10);
/// buffer.add(11);
/// buffer.add(12);
/// buffer.clear(); // buffer is now empty
/// Buffer.toArray(buffer) // => []
/// ```
///
/// Runtime: O(1)
///
/// Space: O(1)
public func clear() {
_size := 0;
reserve(DEFAULT_CAPACITY)
};
/// Removes all elements from the buffer for which the predicate returns false.
/// The predicate is given both the index of the element and the element itself.
/// This may cause a downsizing of the array.
///
/// Example:
/// ```motoko include=initialize
///
/// buffer.add(10);
/// buffer.add(11);
/// buffer.add(12);
/// buffer.filterEntries(func(_, x) = x % 2 == 0); // only keep even elements
/// Buffer.toArray(buffer) // => [10, 12]
/// ```
///
/// Runtime: O(size)
///
/// Amortized Space: O(1), Worst Case Space: O(size)
public func filterEntries(predicate : (Nat, X) -> Bool) {
var numRemoved = 0;
let keep = Prim.Array_tabulate<Bool>(
_size,
func i {
switch (elements[i]) {
case (?element) {
if (predicate(i, element)) {
true
} else {
numRemoved += 1;
false
}
};
case null {
Prim.trap "Malformed buffer in filter()"
}
}
}
);
let capacity = elements.size();
if ((_size - numRemoved : Nat) < capacity / DECREASE_THRESHOLD) {
let elements2 = Prim.Array_init<?X>(capacity / DECREASE_FACTOR, null);
var i = 0;
var j = 0;
while (i < _size) {
if (keep[i]) {
elements2[j] := elements[i];
i += 1;
j += 1
} else {
i += 1
}
};
elements := elements2
} else {
var i = 0;
var j = 0;
while (i < _size) {
if (keep[i]) {
elements[j] := elements[i];
i += 1;
j += 1
} else {
i += 1
}
};
while (j < _size) {
elements[j] := null;
j += 1
}
};
_size -= numRemoved
};
/// Returns the capacity of the buffer (the length of the underlying array).
///
/// Example:
/// ```motoko include=initialize
///
/// let buffer = Buffer.Buffer<Nat>(2); // underlying array has capacity 2
/// buffer.add(10);
/// let c1 = buffer.capacity(); // => 2
/// buffer.add(11);
/// buffer.add(12); // causes capacity to increase by factor of 1.5
/// let c2 = buffer.capacity(); // => 3
/// ```
///
/// Runtime: O(1)
///
/// Space: O(1)
public func capacity() : Nat = elements.size();
/// Changes the capacity to `capacity`. Traps if `capacity` < `size`.
///
/// ```motoko include=initialize
///
/// buffer.reserve(4);
/// buffer.add(10);
/// buffer.add(11);
/// buffer.capacity(); // => 4
/// ```
///
/// Runtime: O(capacity)
///
/// Space: O(capacity)
public func reserve(capacity : Nat) {
if (capacity < _size) {
Prim.trap "capacity must be >= size in reserve"
};
let elements2 = Prim.Array_init<?X>(capacity, null);
var i = 0;
while (i < _size) {
elements2[i] := elements[i];
i += 1
};
elements := elements2
};
/// Adds all elements in buffer `b` to this buffer.
///
/// ```motoko include=initialize
/// let buffer1 = Buffer.Buffer<Nat>(2);
/// let buffer2 = Buffer.Buffer<Nat>(2);
/// buffer1.add(10);
/// buffer1.add(11);
/// buffer2.add(12);
/// buffer2.add(13);
/// buffer1.append(buffer2); // adds elements from buffer2 to buffer1
/// Buffer.toArray(buffer1) // => [10, 11, 12, 13]
/// ```
///
/// Amortized Runtime: O(size2), Worst Case Runtime: O(size1 + size2)
///
/// Amortized Space: O(1), Worst Case Space: O(size1 + size2)
public func append(buffer2 : Buffer<X>) {
let size2 = buffer2.size();
// Make sure you only allocate a new array at most once
if (_size + size2 > elements.size()) {
// FIXME would be nice to have a tabulate for var arrays here
reserve(newCapacity(_size + size2))
};
var i = 0;
while (i < size2) {
elements[_size + i] := buffer2.getOpt i;
i += 1
};
_size += size2
};
/// Inserts `element` at `index`, shifts all elements to the right of
/// `index` over by one index. Traps if `index` is greater than size.
///
/// ```motoko include=initialize
/// let buffer1 = Buffer.Buffer<Nat>(2);
/// let buffer2 = Buffer.Buffer<Nat>(2);
/// buffer.add(10);
/// buffer.add(11);
/// buffer.insert(1, 9);
/// Buffer.toArray(buffer) // => [10, 9, 11]
/// ```
///
/// Runtime: O(size)
///
/// Amortized Space: O(1), Worst Case Space: O(size)
public func insert(index : Nat, element : X) {
if (index > _size) {
Prim.trap "Buffer index out of bounds in insert"
};
let capacity = elements.size();
if (_size + 1 > capacity) {
let capacity = elements.size();
let elements2 = Prim.Array_init<?X>(newCapacity capacity, null);
var i = 0;
while (i < _size + 1) {
if (i < index) {
elements2[i] := elements[i]
} else if (i == index) {
elements2[i] := ?element
} else {
elements2[i] := elements[i - 1]
};
i += 1
};
elements := elements2
} else {
var i : Nat = _size;
while (i > index) {
elements[i] := elements[i - 1];
i -= 1
};
elements[index] := ?element
};
_size += 1
};
/// Inserts `buffer2` at `index`, and shifts all elements to the right of
/// `index` over by size2. Traps if `index` is greater than size.
///
/// ```motoko include=initialize
/// let buffer1 = Buffer.Buffer<Nat>(2);
/// let buffer2 = Buffer.Buffer<Nat>(2);
/// buffer1.add(10);
/// buffer1.add(11);
/// buffer2.add(12);
/// buffer2.add(13);
/// buffer1.insertBuffer(1, buffer2);
/// Buffer.toArray(buffer1) // => [10, 12, 13, 11]
/// ```
///
/// Runtime: O(size)
///
/// Amortized Space: O(1), Worst Case Space: O(size1 + size2)
public func insertBuffer(index : Nat, buffer2 : Buffer<X>) {
if (index > _size) {
Prim.trap "Buffer index out of bounds in insertBuffer"
};
let size2 = buffer2.size();
let capacity = elements.size();
// copy elements to new array and shift over in one pass
if (_size + size2 > capacity) {
let elements2 = Prim.Array_init<?X>(newCapacity(_size + size2), null);
var i = 0;
for (element in elements.vals()) {
if (i == index) {
i += size2
};
elements2[i] := element;
i += 1
};
i := 0;
while (i < size2) {
elements2[i + index] := buffer2.getOpt(i);
i += 1
};
elements := elements2
} // just insert
else {
var i = index;
while (i < index + size2) {
if (i < _size) {
elements[i + size2] := elements[i]
};
elements[i] := buffer2.getOpt(i - index);
i += 1
}
};
_size += size2
};
/// Sorts the elements in the buffer according to `compare`.
/// Sort is deterministic, stable, and in-place.
///
/// ```motoko include=initialize
///
/// import Nat "mo:base/Nat";
///
/// buffer.add(11);
/// buffer.add(12);
/// buffer.add(10);
/// buffer.sort(Nat.compare);
/// Buffer.toArray(buffer) // => [10, 11, 12]
/// ```
///
/// Runtime: O(size * log(size))
///
/// Space: O(size)
public func sort(compare : (X, X) -> Order.Order) {
// Stable merge sort in a bottom-up iterative style
if (_size == 0) {
return
};
let scratchSpace = Prim.Array_init<?X>(_size, null);
let sizeDec = _size - 1 : Nat;
var currSize = 1; // current size of the subarrays being merged
// when the current size == size, the array has been merged into a single sorted array
while (currSize < _size) {
var leftStart = 0; // selects the current left subarray being merged
while (leftStart < sizeDec) {
let mid : Nat = if (leftStart + currSize - 1 : Nat < sizeDec) {
leftStart + currSize - 1
} else { sizeDec };
let rightEnd : Nat = if (leftStart + (2 * currSize) - 1 : Nat < sizeDec) {
leftStart + (2 * currSize) - 1
} else { sizeDec };
// Merge subarrays elements[leftStart...mid] and elements[mid+1...rightEnd]
var left = leftStart;
var right = mid + 1;
var nextSorted = leftStart;
while (left < mid + 1 and right < rightEnd + 1) {
let leftOpt = elements[left];
let rightOpt = elements[right];
switch (leftOpt, rightOpt) {
case (?leftElement, ?rightElement) {
switch (compare(leftElement, rightElement)) {
case (#less or #equal) {
scratchSpace[nextSorted] := leftOpt;
left += 1
};
case (#greater) {
scratchSpace[nextSorted] := rightOpt;
right += 1
}
}
};
case (_, _) {
// only sorting non-null items
Prim.trap "Malformed buffer in sort"
}
};
nextSorted += 1
};
while (left < mid + 1) {
scratchSpace[nextSorted] := elements[left];
nextSorted += 1;
left += 1
};
while (right < rightEnd + 1) {
scratchSpace[nextSorted] := elements[right];
nextSorted += 1;
right += 1
};
// Copy over merged elements
var i = leftStart;
while (i < rightEnd + 1) {
elements[i] := scratchSpace[i];
i += 1
};
leftStart += 2 * currSize
};
currSize *= 2
}
};
/// Returns an Iterator (`Iter`) over the elements of this buffer.
/// Iterator provides a single method `next()`, which returns
/// elements in order, or `null` when out of elements to iterate over.
///
/// ```motoko include=initialize
///
/// buffer.add(10);
/// buffer.add(11);
/// buffer.add(12);
///
/// var sum = 0;
/// for (element in buffer.vals()) {
/// sum += element;
/// };
/// sum // => 33
/// ```
///
/// Runtime: O(1)
///
/// Space: O(1)
public func vals() : { next : () -> ?X } = object {
// FIXME either handle modification to underlying list
// or explicitly warn users in documentation
var nextIndex = 0;
public func next() : ?X {
if (nextIndex >= _size) {
return null
};
let nextElement = elements[nextIndex];
nextIndex += 1;
nextElement
}
};
// FOLLOWING METHODS ARE DEPRECATED
/// @deprecated Use static library function instead.
public func clone() : Buffer<X> {
let newBuffer = Buffer<X>(elements.size());
for (element in vals()) {
newBuffer.add(element)
};
newBuffer
};
/// @deprecated Use static library function instead.
public func toArray() : [X] =
// immutable clone of array
Prim.Array_tabulate<X>(
_size,
func(i : Nat) : X { get i }
);
/// @deprecated Use static library function instead.
public func toVarArray() : [var X] {
if (_size == 0) { [var] } else {
let newArray = Prim.Array_init<X>(_size, get 0);
var i = 0;
for (element in vals()) {
newArray[i] := element;
i += 1
};
newArray
}
}
};
/// Returns true if and only if the buffer is empty.
///
/// Example:
/// ```motoko include=initialize
/// buffer.add(2);
/// buffer.add(0);
/// buffer.add(3);
/// Buffer.isEmpty(buffer); // => false
/// ```
///
/// ```motoko include=initialize
/// Buffer.isEmpty(buffer); // => true
/// ```
///
/// Runtime: O(1)
///
/// Space: O(1)
public func isEmpty<X>(buffer : Buffer<X>) : Bool = buffer.size() == 0;
/// Returns true iff `buffer` contains `element` with respect to equality
/// defined by `equal`.
///
///
/// Example:
/// ```motoko include=initialize
/// import Nat "mo:base/Nat";
///
/// buffer.add(2);
/// buffer.add(0);
/// buffer.add(3);
/// Buffer.contains<Nat>(buffer, 2, Nat.equal); // => true
/// ```
///
/// Runtime: O(size)
///
/// Space: O(1)
///
/// *Runtime and space assumes that `equal` runs in O(1) time and space.
public func contains<X>(buffer : Buffer<X>, element : X, equal : (X, X) -> Bool) : Bool {
for (current in buffer.vals()) {
if (equal(current, element)) {
return true
}
};
false
};
/// Returns a copy of `buffer`, with the same capacity.
///
///
/// Example:
/// ```motoko include=initialize
///
/// buffer.add(1);
///
/// let clone = Buffer.clone(buffer);
/// Buffer.toArray(clone); // => [1]
/// ```
///
/// Runtime: O(size)
///
/// Space: O(size)
public func clone<X>(buffer : Buffer<X>) : Buffer<X> {
let newBuffer = Buffer<X>(buffer.capacity());
for (element in buffer.vals()) {
newBuffer.add(element)
};
newBuffer
};
/// Finds the greatest element in `buffer` defined by `compare`.
/// Returns `null` if `buffer` is empty.
///
///
/// Example:
/// ```motoko include=initialize
/// import Nat "mo:base/Nat";
///
/// buffer.add(1);
/// buffer.add(2);
///
/// Buffer.max(buffer, Nat.compare); // => ?2
/// ```
///
/// Runtime: O(size)
///
/// Space: O(1)
///
/// *Runtime and space assumes that `compare` runs in O(1) time and space.
public func max<X>(buffer : Buffer<X>, compare : (X, X) -> Order) : ?X {
if (buffer.size() == 0) {
return null
};
var maxSoFar = buffer.get(0);
for (current in buffer.vals()) {
switch (compare(current, maxSoFar)) {
case (#greater) {
maxSoFar := current
};
case _ {}
}
};
?maxSoFar
};
/// Finds the least element in `buffer` defined by `compare`.
/// Returns `null` if `buffer` is empty.
///
/// Example:
/// ```motoko include=initialize
/// import Nat "mo:base/Nat";
///
/// buffer.add(1);
/// buffer.add(2);
///
/// Buffer.min(buffer, Nat.compare); // => ?1
/// ```
///
/// Runtime: O(size)
///
/// Space: O(1)
///
/// *Runtime and space assumes that `compare` runs in O(1) time and space.
public func min<X>(buffer : Buffer<X>, compare : (X, X) -> Order) : ?X {
if (buffer.size() == 0) {
return null
};
var minSoFar = buffer.get(0);
for (current in buffer.vals()) {
switch (compare(current, minSoFar)) {
case (#less) {
minSoFar := current
};
case _ {}
}
};
?minSoFar
};
/// Defines equality for two buffers, using `equal` to recursively compare elements in the
/// buffers. Returns true iff the two buffers are of the same size, and `equal`
/// evaluates to true for every pair of elements in the two buffers of the same
/// index.
///
///
/// Example:
/// ```motoko include=initialize
/// import Nat "mo:base/Nat";
///
/// let buffer1 = Buffer.Buffer<Nat>(2);
/// buffer1.add(1);
/// buffer1.add(2);
///
/// let buffer2 = Buffer.Buffer<Nat>(5);
/// buffer2.add(1);
/// buffer2.add(2);
///
/// Buffer.equal(buffer1, buffer2, Nat.equal); // => true
/// ```
///
/// Runtime: O(size)
///
/// Space: O(1)
///
/// *Runtime and space assumes that `equal` runs in O(1) time and space.
public func equal<X>(buffer1 : Buffer<X>, buffer2 : Buffer<X>, equal : (X, X) -> Bool) : Bool {
let size1 = buffer1.size();
if (size1 != buffer2.size()) {
return false
};
var i = 0;
while (i < size1) {
if (not equal(buffer1.get(i), buffer2.get(i))) {
return false
};
i += 1
};
true
};
/// Defines comparison for two buffers, using `compare` to recursively compare elements in the
/// buffers. Comparison is defined lexicographically.
///
///
/// Example:
/// ```motoko include=initialize
/// import Nat "mo:base/Nat";
///
/// let buffer1 = Buffer.Buffer<Nat>(2);
/// buffer1.add(1);
/// buffer1.add(2);
///
/// let buffer2 = Buffer.Buffer<Nat>(3);
/// buffer2.add(3);
/// buffer2.add(4);
///
/// Buffer.compare<Nat>(buffer1, buffer2, Nat.compare); // => #less
/// ```
///
/// Runtime: O(size)
///
/// Space: O(1)
///
/// *Runtime and space assumes that `compare` runs in O(1) time and space.
public func compare<X>(buffer1 : Buffer<X>, buffer2 : Buffer<X>, compare : (X, X) -> Order.Order) : Order.Order {
let size1 = buffer1.size();
let size2 = buffer2.size();
let minSize = if (size1 < size2) { size1 } else { size2 };
var i = 0;
while (i < minSize) {
switch (compare(buffer1.get(i), buffer2.get(i))) {
case (#less) {
return #less
};
case (#greater) {
return #greater
};
case _ {}
};
i += 1
};
if (size1 < size2) {
#less
} else if (size1 == size2) {
#equal
} else {
#greater
}
};
/// Creates a textual representation of `buffer`, using `toText` to recursively
/// convert the elements into Text.
///
/// Example:
/// ```motoko include=initialize
/// import Nat "mo:base/Nat";
///
/// buffer.add(1);
/// buffer.add(2);
/// buffer.add(3);
/// buffer.add(4);
///
/// Buffer.toText(buffer, Nat.toText); // => "[1, 2, 3, 4]"
/// ```
///
/// Runtime: O(size)
///
/// Space: O(size)
///
/// *Runtime and space assumes that `toText` runs in O(1) time and space.
public func toText<X>(buffer : Buffer<X>, toText : X -> Text) : Text {
let size : Int = buffer.size();
var i = 0;
var text = "";
while (i < size - 1) {
text := text # toText(buffer.get(i)) # ", "; // Text implemented as rope
i += 1
};
if (size > 0) {
// avoid the trailing comma
text := text # toText(buffer.get(i))
};
"[" # text # "]"
};
/// Hashes `buffer` using `hash` to hash the underlying elements.
/// The deterministic hash function is a function of the elements in the Buffer, as well
/// as their ordering.
///
/// Example:
/// ```motoko include=initialize
/// import Hash "mo:base/Hash";
///
/// buffer.add(1);
/// buffer.add(2);
/// buffer.add(3);
/// buffer.add(1000);
///
/// Buffer.hash<Nat>(buffer, Hash.hash); // => 2_872_640_342