/
List.chpl
2059 lines (1642 loc) · 55.7 KB
/
List.chpl
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 2020-2024 Hewlett Packard Enterprise Development LP
* Copyright 2004-2019 Cray Inc.
* Other additional copyright holders may be indicated within.
*
* The entirety of this work is licensed under the Apache License,
* Version 2.0 (the "License"); you may not use this file except
* in compliance with the License.
*
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/*
This module contains the implementation of Chapel's standard 'list' type.
A list is a lightweight container similar to an array that is suitable for
building up and iterating over a collection of elements in a structured
manner.
The highly parallel nature of Chapel means that great care should be taken
when performing operations that may invalidate references to list elements.
Inserts and removals into the middle of a list are example operations that
may invalidate references. Appending an element to the end of a list will
never invalidate references to elements contained in the list.
The following operations may invalidate references to elements contained in
a list:
- insert
- remove
- pop
- clear
- sort
Additionally, all references to list elements are invalidated when the list
is deinitialized.
Lists are not parallel safe by default, but can be made parallel safe by
setting the param formal `parSafe` to true in any list constructor. When
constructed from another list, the new list will inherit the parallel safety
mode of its originating list. Note that the ``parSafe`` mode is currently
unstable and will eventually be replaced by a standalone parallel-safe list
type.
Inserts and removals into a list are O(n) worst case and should be performed
with care. Appends into a list have an amortized speed of O(1). Indexing
into a list is O(1).
*/
module List {
import ChapelLocks;
private use HaltWrappers;
private use Sort;
private use Math;
@chpldoc.nodoc
private const _initialCapacity = 8;
@chpldoc.nodoc
private const _initialArrayCapacity = 16;
@chpldoc.nodoc
private param _sanityChecks = false;
//
// Some asserts are useful while developing, but can be turned off when the
// implementation is correct.
//
private inline proc _sanity(expr: bool) {
if _sanityChecks then
assert(expr);
}
//
// We can change the lock type later. Use a spinlock for now, even if it
// is suboptimal in cases where long critical sections have high
// contention (IE, lots of tasks trying to insert into the middle of this
// list, or any operation that is O(n)).
//
@chpldoc.nodoc
type _lockType = ChapelLocks.chpl_LocalSpinlock;
//
// Use a wrapper class to let list methods have a const ref receiver even
// when `parSafe` is `true` and the list lock is used.
//
@chpldoc.nodoc
class _LockWrapper {
var lockVar = new _lockType();
inline proc lock() {
lockVar.lock();
}
inline proc unlock() {
lockVar.unlock();
}
}
/* Check that element type is supported by list */
@chpldoc.nodoc
proc _checkType(type eltType) param {
if isGenericType(eltType) {
compilerWarning("creating a list with element type " +
eltType:string);
if isClassType(eltType) && !isGenericType(eltType:borrowed) {
compilerWarning("which is a class type with generic management");
}
compilerError("list element type cannot currently be generic");
// In the future we might support it if the list is not default-inited
}
if eltType == nothing {
compilerError("cannot initialize list with element type 'nothing'");
}
}
@chpldoc.nodoc
proc _dummyFieldType(type t) type {
if isBorrowedClass(t) {
return t?;
} else {
return nothing;
}
}
private use IO;
/* Impacts whether the copy initializer that takes a list will generate a
warning when the other list has a different ``parSafe`` setting than the
destination. Compile with ``-swarnForListParsafeMismatch=false`` to turn
off this warning.
Defaults to ``true``
*/
config param warnForListParsafeMismatch = true;
/*
A list is a lightweight container suitable for building up and iterating
over a collection of elements in a structured manner. Unlike a stack, the
list type also supports inserts or removals into the middle of the list.
The list type is close in spirit to its Python counterpart, with fast O(1)
random access and append operations.
The list type is not parallel safe by default. For situations in which
such protections are desirable, parallel safety can be enabled by setting
`parSafe = true` in any list constructor.
Unlike an array, the set of indices of a list is always `0..<size`.
*/
record list : serializable {
/* The type of the elements contained in this list. */
type eltType;
/*If `true`, this list will perform parallel safe operations.*/
@unstable("'list.parSafe' is unstable and is expected to be replaced by a separate list type in the future")
param parSafe = false;
@chpldoc.nodoc
var _size = 0;
@chpldoc.nodoc
var _lock = if parSafe then new _LockWrapper() else none;
@chpldoc.nodoc
var _arrays: _ddata(_ddata(eltType)) = nil;
@chpldoc.nodoc
var _arrayCapacity = 0;
@chpldoc.nodoc
var _totalCapacity = 0;
//
// If the list element type is a borrowed class, instantiate this dummy
// field as a `borrowed c?` and let it default initialize to `nil`.
// Otherwise, instantiate it as a `nothing` and let the compiler fold
// it away. See #15575.
//
@chpldoc.nodoc
var _dummyFieldToForceBorrowChecking: _dummyFieldType(eltType);
/*
Initializes an empty list.
:arg eltType: The type of the elements of this list.
*/
proc init(type eltType) {
_checkType(eltType);
this.eltType = eltType;
this.parSafe = false;
init this;
this._firstTimeInitializeArrays();
}
/*
Initializes an empty list.
:arg eltType: The type of the elements of this list.
:arg parSafe: If `true`, this list will use parallel safe operations.
:type parSafe: `param bool`
*/
pragma "last resort"
@unstable("'list.parSafe' is unstable and is expected to be replaced by a separate list type in the future")
proc init(type eltType, param parSafe=false) {
_checkType(eltType);
this.eltType = eltType;
this.parSafe = parSafe;
init this;
this._firstTimeInitializeArrays();
}
/*
Initializes a list containing elements that are copy initialized from
the elements contained in another list.
Used in new expressions.
:arg other: The list to initialize from.
*/
proc init(other: list(?t)) {
if !isCopyableType(this.type.eltType) then
compilerError("Cannot copy list with element type that " +
"cannot be copied");
this.eltType = t;
this.parSafe = other.parSafe;
init this;
_commonInitFromIterable(other);
}
/*
Initializes a list containing elements that are copy initialized from
the elements contained in another list.
Used in new expressions.
:arg other: The list to initialize from.
:arg parSafe: If `true`, this list will use parallel safe operations.
:type parSafe: `param bool`
*/
pragma "last resort"
@unstable("'list.parSafe' is unstable and is expected to be replaced by a separate list type in the future")
proc init(other: list(?t), param parSafe=other.parSafe) {
if !isCopyableType(this.type.eltType) then
compilerError("Cannot copy list with element type that " +
"cannot be copied");
this.eltType = t;
this.parSafe = parSafe;
init this;
_commonInitFromIterable(other);
}
/*
Initializes a list containing elements that are copy initialized from
the elements contained in an array.
Used in new expressions.
:arg other: The array to initialize from.
*/
proc init(other: [?d] ?t) {
_checkType(t);
if !isCopyableType(t) then
compilerError("Cannot construct list from array with element " +
"type that cannot be copied");
this.eltType = t;
this.parSafe = false;
init this;
_commonInitFromIterable(other);
}
/*
Initializes a list containing elements that are copy initialized from
the elements contained in an array.
Used in new expressions.
:arg other: The array to initialize from.
:arg parSafe: If `true`, this list will use parallel safe operations.
:type parSafe: `param bool`
*/
pragma "last resort"
@unstable("'list.parSafe' is unstable and is expected to be replaced by a separate list type in the future")
proc init(other: [?d] ?t, param parSafe=false) {
_checkType(t);
if !isCopyableType(t) then
compilerError("Cannot construct list from array with element " +
"type that cannot be copied");
this.eltType = t;
this.parSafe = parSafe;
init this;
_commonInitFromIterable(other);
}
/*
Initializes a list containing elements that are copy initialized from
the elements yielded by a range.
Used in new expressions.
.. note::
Attempting to initialize a list from an unbounded range will trigger
a compiler error.
:arg other: The range to initialize from.
*/
proc init(other: range(?t)) {
_checkType(t);
this.eltType = t;
this.parSafe = false;
if other.bounds != boundKind.both {
param e = this.type:string;
param f = other.type:string;
param msg = "Cannot init " + e + " from unbounded " + f;
compilerError(msg);
}
init this;
_commonInitFromIterable(other);
}
/*
Initializes a list containing elements that are copy initialized from
the elements yielded by a range.
Used in new expressions.
.. note::
Attempting to initialize a list from an unbounded range will trigger
a compiler error.
:arg other: The range to initialize from.
:arg parSafe: If `true`, this list will use parallel safe operations.
:type parSafe: `param bool`
*/
pragma "last resort"
@unstable("'list.parSafe' is unstable and is expected to be replaced by a separate list type in the future")
proc init(other: range(?t), param parSafe=false) {
_checkType(t);
this.eltType = t;
this.parSafe = parSafe;
if other.bounds != boundKind.both {
param e = this.type:string;
param f = other.type:string;
param msg = "Cannot init " + e + " from unbounded " + f;
compilerError(msg);
}
init this;
_commonInitFromIterable(other);
}
/*
Initializes a list containing elements that are copy initialized from
the elements yielded by an iterator expression.
Used in new expressions.
:arg other: The iterator expression to initialize from.
*/
@chpldoc.nodoc
proc init(other: _iteratorRecord) {
// get the type yielded by the iterator
type t = __primitive("scalar promotion type", other.type);
_checkType(t);
this.eltType = t;
this.parSafe = false;
init this;
_commonInitFromIterable(other);
}
/*
Initializes a list containing elements that are copy initialized from
the elements yielded by an iterator expression.
Used in new expressions.
:arg other: The iterator expression to initialize from.
:arg parSafe: If `true`, this list will use parallel safe operations.
:type parSafe: `param bool`
*/
pragma "last resort"
@unstable("'list.parSafe' is unstable and is expected to be replaced by a separate list type in the future")
@chpldoc.nodoc
proc init(other: _iteratorRecord, param parSafe=false) {
// get the type yielded by the iterator
type t = __primitive("scalar promotion type", other.type);
_checkType(t);
this.eltType = t;
this.parSafe = parSafe;
init this;
_commonInitFromIterable(other);
}
/*
Initializes a list containing elements that are copy initialized from
the elements contained in another list.
:arg other: The list to initialize from.
*/
proc init=(other: list) {
if !isCopyableType(this.type.eltType) then
compilerError("Cannot copy list with element type that " +
"cannot be copied");
// set eltType to other.eltType if it was not already provided in lhs type
this.eltType = if this.type.eltType != ?
then this.type.eltType
else other.eltType;
// set parSafe to other.parSafe if it was not already provided in lhs type
this.parSafe = if this.type.parSafe != ?
then this.type.parSafe
else other.parSafe;
if (this.parSafe != other.parSafe && warnForListParsafeMismatch) {
compilerWarning("initializing between two lists with different " +
"parSafe settings\n" + "Note: this warning can be " +
"silenced with '-swarnForListParsafeMismatch=false'");
}
init this;
_commonInitFromIterable(other);
}
/*
Initializes a list containing elements that are copy initialized from
the elements contained in an array.
``this.parSafe`` will default to ``false`` if it is not yet set.
:arg other: The array to initialize from.
*/
proc init=(other: []) {
if !isCopyableType(other.eltType) then
compilerError("Cannot copy list from array with element type " +
"that cannot be copied");
// set eltType to other.eltType if it was not already provided in lhs type
this.eltType = if this.type.eltType != ?
then this.type.eltType
else other.eltType;
// set parSafe to false if it was not already provided in lhs type
this.parSafe = if this.type.parSafe != ?
then this.type.parSafe
else false;
init this;
_commonInitFromIterable(other);
}
/*
Initializes a list containing elements that are copy initialized from
the elements yielded by a range.
``this.parSafe`` will default to ``false`` if it is not yet set.
.. note::
Attempting to initialize a list from an unbounded range will trigger
a compiler error.
:arg other: The range to initialize from.
*/
proc init=(other: range(?)) {
if other.bounds != boundKind.both {
param e = this.type:string;
param f = other.type:string;
param msg = "Cannot init " + e + " from unbounded " + f;
compilerError(msg);
}
// set eltType to other.idxType if it was not already provided in lhs type
this.eltType = if this.type.eltType != ?
then this.type.eltType
else other.idxType;
// set parSafe to false if it was not already provided in lhs type
this.parSafe = if this.type.parSafe != ?
then this.type.parSafe
else false;
init this;
_commonInitFromIterable(other);
}
/*
Initializes a list containing elements that are copy initialized from
the elements yielded by an iterator expression.
``this.parSafe`` will default to ``false`` if it is not yet set.
:arg other: The iterator expression to initialize from.
*/
@chpldoc.nodoc
proc init=(other: _iteratorRecord) {
// get the type yielded by the iterator
type t = __primitive("scalar promotion type", other.type);
// set eltType to other.idxType if it was not already provided in lhs type
this.eltType = if this.type.eltType != ?
then this.type.eltType
else t;
// set parSafe to false if it was not already provided in lhs type
this.parSafe = if this.type.parSafe != ?
then this.type.parSafe
else false;
init this;
_commonInitFromIterable(other);
}
@chpldoc.nodoc
proc ref _commonInitFromIterable(iterable) lifetime this < iterable {
this._firstTimeInitializeArrays();
if isSubtype(this.eltType, list) || isArrayType(this.eltType) {
for x in iterable {
var tmp: this.eltType = x;
pushBack(tmp);
}
} else {
for x in iterable {
pushBack(x);
}
}
}
@chpldoc.nodoc
proc ref _firstTimeInitializeArrays() {
_sanity(_arrays == nil);
_sanity(_totalCapacity == 0);
_sanity(_size == 0);
_arrays = _makeBlockArray(_initialArrayCapacity);
_arrayCapacity = _initialArrayCapacity;
_arrays[0] = _makeArray(_initialCapacity);
_totalCapacity = _initialCapacity;
}
@chpldoc.nodoc
inline proc ref deinit() {
_fireAllDestructors();
_freeAllArrays();
_sanity(_totalCapacity == 0);
_sanity(_size == 0);
_sanity(_arrays == nil);
}
@chpldoc.nodoc
inline proc _destroy(ref item: eltType) {
chpl__autoDestroy(item);
}
pragma "unsafe"
@chpldoc.nodoc
inline proc _move(ref src: ?t, ref dst: t) lifetime src == dst {
__primitive("=", dst, src);
}
@chpldoc.nodoc
inline proc _getArrayCapacity(array: int): int {
const exp = array + log2(_initialCapacity);
const result = 2 ** exp;
return result;
}
@chpldoc.nodoc
inline proc _getArrayIdx(zpos: int): int {
const adj = zpos + _initialCapacity;
const result = log2(adj) - log2(_initialCapacity);
return result;
}
@chpldoc.nodoc
inline proc _getLastArrayIdx(): int {
const result = _getArrayIdx(_size - 1);
_sanity(result >= 0);
return result;
}
@chpldoc.nodoc
inline proc _getItemIdx(zpos: int): int {
const adj = zpos + _initialCapacity;
const result = adj ^ (1 << log2(adj));
return result;
}
//
// A helper function for getting a reference to a list element.
// May be less important now that lists use 0-based indexing(?).
//
@chpldoc.nodoc
inline proc const ref _getRef(idx: int) ref {
_sanity(idx >= 0 && idx < _totalCapacity);
const arrayIdx = _getArrayIdx(idx);
const itemIdx = _getItemIdx(idx);
const array = _arrays[arrayIdx];
_sanity(array != nil);
ref result = array[itemIdx];
return result;
}
@chpldoc.nodoc
inline proc _enter() {
if parSafe then
_lock.lock();
}
@chpldoc.nodoc
inline proc _leave() {
if parSafe then
_lock.unlock();
}
@chpldoc.nodoc
inline proc const _withinBounds(idx: int): bool {
return (idx >= 0 && idx < _size);
}
//
// This call assumes that a lock (acquired by `_enter`) is already
// held (if parSafe==true), and releases it before throwing an error if
// a bounds check fails.
//
@chpldoc.nodoc
inline proc const _boundsCheckLeaveOnThrow(i: int, umsg: string="") throws {
if !_withinBounds(i) {
_leave();
const msg = if umsg != "" then umsg else
"Index out of bounds: " + i:string;
throw new owned
IllegalArgumentError(msg);
}
}
@chpldoc.nodoc
proc _makeBlockArray(size: int) {
return _ddata_allocate(_ddata(eltType), size);
}
@chpldoc.nodoc
proc _freeBlockArray(data: _ddata(_ddata(eltType)), size: int) {
_ddata_free(data, size);
}
@chpldoc.nodoc
proc _makeArray(size: int) {
var callPostAlloc = false;
var ret = _ddata_allocate_noinit(eltType, size, callPostAlloc);
if callPostAlloc then _ddata_allocate_postalloc(ret, size);
return ret;
}
@chpldoc.nodoc
proc _freeArray(data: _ddata(eltType), size: int) {
_ddata_free(data, size);
}
@chpldoc.nodoc
proc ref _maybeAcquireMem(amount: int) {
const remaining = _totalCapacity - _size;
_sanity(remaining >= 0);
if remaining >= amount then
return;
var lastArrayIdx = if _size == 0 then 0 else _getLastArrayIdx();
var req = amount - remaining;
while req > 0 {
//
// Double the block array if we've run out of space.
//
if lastArrayIdx >= (_arrayCapacity - 1) then
on this {
var _narrays = _makeBlockArray(_arrayCapacity * 2);
for i in 0..#_arrayCapacity do
_narrays[i] = _arrays[i];
_freeBlockArray(_arrays, _arrayCapacity);
_arrays = _narrays;
_arrayCapacity *= 2;
}
//
// Add a new block to the block array that is twice the size of the
// previous block.
//
on this {
const oldLast = _arrays[lastArrayIdx];
const oldLastCapacity = _getArrayCapacity(lastArrayIdx);
lastArrayIdx += 1;
ref newLast = _arrays[lastArrayIdx];
const newLastCapacity = oldLastCapacity * 2;
_sanity(oldLast != nil);
_sanity(newLast == nil);
newLast = _makeArray(newLastCapacity);
_totalCapacity += newLastCapacity;
req -= newLastCapacity;
}
}
return;
}
//
// If the current size (occupied slots) minus a given amount is small
// enough such that no slots in the last "sub-block" are occupied, then
// preemptively free that block.
//
// This method _does not_ fire destructors!
//
@chpldoc.nodoc
proc ref _maybeReleaseMem(amount: int) {
//
// If we're down to one single "sub array", then there's no sense in
// doing anymore work (upon repeated appends/pops, we'd just have to
// reinitialize/deinitialize the whole segment array repeatedly).
//
if _totalCapacity <= _initialCapacity then
return;
const lastArrayIdx = _getLastArrayIdx();
_sanity(lastArrayIdx != 0);
const lastArrayCapacity = _getArrayCapacity(lastArrayIdx);
const threshold = _totalCapacity - lastArrayCapacity;
const nsize = _size - amount;
if nsize > threshold then
return;
ref array = _arrays[lastArrayIdx];
_sanity(array != nil);
_freeArray(array, lastArrayCapacity);
_totalCapacity -= lastArrayCapacity;
array = nil;
}
//
// Shift elements including and after index `idx` so that they are moved
// `shift` positions to the right in memory, possibly resizing. May
// expand memory if necessary.
//
@chpldoc.nodoc
proc ref _expand(idx: int, shift: int=1) {
_sanity(_withinBounds(idx));
if shift <= 0 then
return;
on this {
_maybeAcquireMem(shift);
for i in idx.._size-1 by -1 {
ref src = _getRef(i);
ref dst = _getRef(i + shift);
_move(src, dst);
}
}
return;
}
//
// Shift all elements following "idx" one to the left.
// May release memory if possible.
//
// This method does not fire destructors, so do so before calling it.
//
@chpldoc.nodoc
proc ref _collapse(idx: int) {
_sanity(_withinBounds(idx));
if idx == _size-1 {
on this do _maybeReleaseMem(1);
return;
}
on this {
for i in idx..(_size - 2) {
ref src = _getRef(i + 1);
ref dst = _getRef(i);
_move(src, dst);
}
_maybeReleaseMem(1);
}
return;
}
//
// Assumes that a copy of the input element has already been made at some
// previous boundary, IE giving a parameter the "in" intent. Whatever
// copy you've made, make sure that the "no auto destroy" pragma is
// attached so that you avoid firing a destructor early (and in the worst
// case, fire it twice).
//
@chpldoc.nodoc
proc ref _appendByRef(ref x: eltType) {
_maybeAcquireMem(1);
ref src = x;
ref dst = _getRef(_size);
_move(src, dst);
_size += 1;
}
/*
Add an element to the end of this list.
:arg x: An element to append.
:type x: `eltType`
:return: List index where element was inserted.
:rtype: `int`
*/
proc ref pushBack(pragma "no auto destroy" in x: this.eltType) : int
lifetime this < x {
_enter();
//
// TODO: Can't use on statement here without getting a memory leak on
// gasnet/multilocale configurations.
//
_appendByRef(x);
var result = _size - 1;
_leave();
return result;
}
@chpldoc.nodoc
inline proc ref _appendGeneric(collection) {
var startSize: int;
var endSize: int;
//
// TODO: This could avoid repeated resizes at smaller total capacities
// if we resized once and then performed repeated moves, rather than
// calling _append().
//
on this {
startSize = _size;
for item in collection {
pragma "no auto destroy"
var cpy = item;
_appendByRef(cpy);
}
endSize = _size;
}
return startSize..(endSize-1);
}
/*
Push a copy of each element contained in another list to the end of this
list.
:arg other: A list containing elements of the same type as those
contained in this list.
:type other: `list(eltType)`
:return: List indices where elements were inserted.
:rtype: `range`
*/
proc ref pushBack(other: list(eltType, ?p)) lifetime this < other {
var ret: range;
on this {
_enter();
ret = _appendGeneric(other);
_leave();
}
return ret;
}
/*
Push a copy of each element contained in an array to the end of this
list.
:arg other: An array containing elements of the same type as those
contained in this list.
:type other: `[?d] eltType`
:return: List indices where elements were inserted.
:rtype: `range`
*/
proc ref pushBack(other: [?d] eltType) lifetime this < other {
var ret: range;
on this {
_enter();
ret = _appendGeneric(other);
_leave();
}
return ret;
}
/*
Push a copy of each element yielded by a range to the end of this list.
.. note::
Attempting to initialize a list from an unbounded range will trigger
a compiler error.
:arg other: The range to initialize from.
:type other: `range(eltType)`
:return: List indices where elements were inserted.
:rtype: `range`
*/
proc ref pushBack(other: range(eltType, ?b, ?d)) lifetime this < other {
if other.bounds != boundKind.both {
param e = this.type:string;
param f = other.type:string;
param msg = "Cannot extend " + e + " with unbounded " + f;
compilerError(msg);
}
var ret: range;
on this {
_enter();
ret = _appendGeneric(other);
_leave();
}
return ret;
}
/*
Returns `true` if this list contains an element equal to the value of
`x`, and `false` otherwise.
:arg x: An element to search for.
:type x: `eltType`
:return: `true` if this list contains `x`.
:rtype: `bool`
*/
proc const contains(x: eltType): bool {
var result = false;
on this {
_enter();
for item in this do
if item == x {
result = true;
break;
}
_leave();
}
return result;
}
/*
Returns a reference to the first item in this list.
.. warning::
Calling this method on an empty list will cause the currently running
program to halt. If the `--fast` flag is used, no safety checks will
be performed.
:return: A reference to the first item in this list.
:rtype: `ref eltType`
*/
@deprecated(parenful=true, notes="`list.first()` is deprecated; please use the parenless version `list.first` instead")
proc ref first ref {
if parSafe then
compilerWarning('Calling `first()` on a list initialized with ' +
'`parSafe=true` has been deprecated, consider ' +
'using `set()` or `update()` instead');
_enter();