forked from JetBrains/kotlin
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Arrays.kt
1768 lines (1635 loc) · 65.1 KB
/
Arrays.kt
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 2010-2020 JetBrains s.r.o. and Kotlin Programming Language contributors.
* Use of this source code is governed by the Apache 2.0 license that can be found in the license/LICENSE.txt file.
*/
package templates
import templates.DocExtensions.collection
import templates.Family.*
import templates.Ordering.appendStableSortNote
import templates.Ordering.stableSortNote
object ArrayOps : TemplateGroupBase() {
init {
defaultBuilder {
specialFor(ArraysOfUnsigned) {
sinceAtLeast("1.3")
annotation("@ExperimentalUnsignedTypes")
}
}
}
val f_isEmpty = fn("isEmpty()") {
include(ArraysOfObjects, ArraysOfPrimitives)
} builder {
inlineOnly()
doc { "Returns `true` if the array is empty." }
returns("Boolean")
body {
"return size == 0"
}
}
val f_isNotEmpty = fn("isNotEmpty()") {
include(ArraysOfObjects, ArraysOfPrimitives)
} builder {
inlineOnly()
doc { "Returns `true` if the array is not empty." }
returns("Boolean")
body {
"return !isEmpty()"
}
}
val f_lastIndex = pval("lastIndex") {
include(ArraysOfObjects, ArraysOfPrimitives, ArraysOfUnsigned)
} builder {
doc { "Returns the last valid index for the array." }
returns("Int")
body {
"get() = size - 1"
}
specialFor(ArraysOfUnsigned) {
// TODO: Make inlineOnly after KT-30015 is fixed.
// InlineOnly properties currently are not inlined and may lead to IllegalAccessException
// when accessed from an inline (or inlineOnly) method.
// It is because the method body contains access call to inlineOnly property in nonpublic multifile part,
// which may be inaccessible from method call site, where method body gets inlined.
inline()
body { "get() = storage.lastIndex" }
}
}
val f_indices = pval("indices") {
include(ArraysOfObjects, ArraysOfPrimitives, ArraysOfUnsigned)
} builder {
doc { "Returns the range of valid indices for the array." }
returns("IntRange")
body {
"get() = IntRange(0, lastIndex)"
}
specialFor(ArraysOfUnsigned) {
// TODO: Make inlineOnly after KT-30015 is fixed.
// InlineOnly properties currently are not inlined and may lead to IllegalAccessException
// when accessed from an inline (or inlineOnly) method.
// It is because the method body contains access call to inlineOnly property in nonpublic multifile part,
// which may be inaccessible from method call site, where method body gets inlined.
inline()
body { "get() = storage.indices" }
}
}
private fun MemberBuilder.deprecatedNonNullArrayFunction() {
deprecate("Use Kotlin compiler 1.4 to avoid deprecation warning.")
annotation("""@DeprecatedSinceKotlin(hiddenSince = "1.4")""")
}
val f_contentEquals = fn("contentEquals(other: SELF)") {
include(ArraysOfObjects, ArraysOfPrimitives, ArraysOfUnsigned)
} builder {
since("1.1")
deprecatedNonNullArrayFunction()
infix(true)
doc {
"""
Returns `true` if the two specified arrays are *structurally* equal to one another,
i.e. contain the same number of the same elements in the same order.
"""
}
returns("Boolean")
body { "return this.contentEquals(other)" }
if (f == ArraysOfUnsigned) {
return@builder
}
doc {
doc + """
The elements are compared for equality with the [equals][Any.equals] function.
For floating point numbers it means that `NaN` is equal to itself and `-0.0` is not equal to `0.0`.
"""
}
on(Platform.JVM) {
inlineOnly()
}
}
val f_contentEquals_nullable = fn("contentEquals(other: SELF?)") {
include(ArraysOfObjects, ArraysOfPrimitives, ArraysOfUnsigned)
} builder {
since("1.4")
infix(true)
doc {
"""
Returns `true` if the two specified arrays are *structurally* equal to one another,
i.e. contain the same number of the same elements in the same order.
"""
}
receiver("SELF?")
returns("Boolean")
if (family == ArraysOfUnsigned) {
body { "return this?.storage.contentEquals(other?.storage)" }
return@builder
}
doc {
doc + """
The elements are compared for equality with the [equals][Any.equals] function.
For floating point numbers it means that `NaN` is equal to itself and `-0.0` is not equal to `0.0`.
"""
}
on(Platform.JVM) {
inlineOnly()
annotation("""@JvmName("contentEqualsNullable")""")
body { "return java.util.Arrays.equals(this, other)" }
}
on(Platform.JS) {
on(Backend.Legacy) {
annotation("""@library("arrayEquals")""")
body { "definedExternally" }
}
on(Backend.IR) {
body { "return contentEqualsInternal(other)" }
}
}
on(Platform.Native) {
fun notEq(operand1: String, operand2: String) = when {
primitive?.isFloatingPoint() == true -> "!$operand1.equals($operand2)"
else -> "$operand1 != $operand2"
}
body {
"""
if (this === other) return true
if (this === null || other === null) return false
if (size != other.size) return false
for (i in indices) {
if (${notEq("this[i]", "other[i]")}) return false
}
return true
"""
}
}
}
val f_contentDeepEquals = fn("contentDeepEquals(other: SELF)") {
include(ArraysOfObjects)
} builder {
since("1.1")
annotation("@kotlin.internal.LowPriorityInOverloadResolution")
infix(true)
doc {
"""
Returns `true` if the two specified arrays are *deeply* equal to one another,
i.e. contain the same number of the same elements in the same order.
If two corresponding elements are nested arrays, they are also compared deeply.
If any of arrays contains itself on any nesting level the behavior is undefined.
The elements of other types are compared for equality with the [equals][Any.equals] function.
For floating point numbers it means that `NaN` is equal to itself and `-0.0` is not equal to `0.0`.
"""
}
returns("Boolean")
body { "return this.contentDeepEquals(other)" }
on(Platform.JVM) {
inlineOnly()
annotation("""@JvmName("contentDeepEqualsInline")""")
}
}
val f_contentDeepEquals_nullable = fn("contentDeepEquals(other: SELF?)") {
include(ArraysOfObjects)
} builder {
since("1.4")
infix(true)
doc {
"""
Returns `true` if the two specified arrays are *deeply* equal to one another,
i.e. contain the same number of the same elements in the same order.
The specified arrays are also considered deeply equal if both are `null`.
If two corresponding elements are nested arrays, they are also compared deeply.
If any of arrays contains itself on any nesting level the behavior is undefined.
The elements of other types are compared for equality with the [equals][Any.equals] function.
For floating point numbers it means that `NaN` is equal to itself and `-0.0` is not equal to `0.0`.
"""
}
receiver("SELF?")
returns("Boolean")
on(Platform.JVM) {
inlineOnly()
annotation("""@JvmName("contentDeepEqualsNullable")""")
body {
"""
if (kotlin.internal.apiVersionIsAtLeast(1, 3, 0))
return contentDeepEqualsImpl(other)
else
return java.util.Arrays.deepEquals(this, other)
"""
}
}
on(Platform.JS) {
on(Backend.Legacy) {
annotation("""@library("arrayDeepEquals")""")
body { "definedExternally" }
}
on(Backend.IR) {
body { "return contentDeepEqualsImpl(other)" }
}
}
on(Platform.Native) {
body { "return contentDeepEqualsImpl(other)" }
}
}
val f_contentToString = fn("contentToString()") {
include(ArraysOfObjects, ArraysOfPrimitives, ArraysOfUnsigned)
} builder {
since("1.1")
deprecatedNonNullArrayFunction()
doc {
"""
Returns a string representation of the contents of the specified array as if it is [List].
"""
}
sample("samples.collections.Arrays.ContentOperations.contentToString")
returns("String")
body { "return this.contentToString()" }
if (f == ArraysOfUnsigned) {
return@builder
}
on(Platform.JVM) {
inlineOnly()
}
}
val f_contentToString_nullable = fn("contentToString()") {
include(ArraysOfObjects, ArraysOfPrimitives, ArraysOfUnsigned)
} builder {
since("1.4")
doc {
"""
Returns a string representation of the contents of the specified array as if it is [List].
"""
}
sample("samples.collections.Arrays.ContentOperations.contentToString")
receiver("SELF?")
returns("String")
if (family == ArraysOfUnsigned) {
body { """return this?.joinToString(", ", "[", "]") ?: "null"""" }
return@builder
}
on(Platform.JVM) {
inlineOnly()
annotation("""@JvmName("contentToStringNullable")""")
body { "return java.util.Arrays.toString(this)" }
}
on(Platform.JS) {
on(Backend.Legacy) {
annotation("""@library("arrayToString")""")
body { "definedExternally" }
}
on(Backend.IR) {
body { """return this?.joinToString(", ", "[", "]") ?: "null"""" }
}
}
on(Platform.Native) {
body { """return this?.joinToString(", ", "[", "]") ?: "null"""" }
}
}
val f_contentDeepToString = fn("contentDeepToString()") {
include(ArraysOfObjects)
} builder {
since("1.1")
annotation("@kotlin.internal.LowPriorityInOverloadResolution")
doc {
"""
Returns a string representation of the contents of this array as if it is a [List].
Nested arrays are treated as lists too.
If any of arrays contains itself on any nesting level that reference
is rendered as `"[...]"` to prevent recursion.
"""
}
sample("samples.collections.Arrays.ContentOperations.contentDeepToString")
returns("String")
body { "return this.contentDeepToString()" }
on(Platform.JVM) {
inlineOnly()
annotation("""@JvmName("contentDeepToStringInline")""")
}
}
val f_contentDeepToString_nullable = fn("contentDeepToString()") {
include(ArraysOfObjects)
} builder {
since("1.4")
doc {
"""
Returns a string representation of the contents of this array as if it is a [List].
Nested arrays are treated as lists too.
If any of arrays contains itself on any nesting level that reference
is rendered as `"[...]"` to prevent recursion.
"""
}
sample("samples.collections.Arrays.ContentOperations.contentDeepToString")
receiver("SELF?")
returns("String")
on(Platform.JVM) {
inlineOnly()
annotation("""@JvmName("contentDeepToStringNullable")""")
body {
"""
if (kotlin.internal.apiVersionIsAtLeast(1, 3, 0))
return contentDeepToStringImpl()
else
return java.util.Arrays.deepToString(this)
"""
}
}
on(Platform.JS) {
on(Backend.Legacy) {
annotation("""@library("arrayDeepToString")""")
body { "definedExternally" }
}
on(Backend.IR) {
body { "return contentDeepToStringImpl()" }
}
}
on(Platform.Native) {
body { "return contentDeepToStringImpl()" }
}
}
val f_contentHashCode = fn("contentHashCode()") {
include(ArraysOfObjects, ArraysOfPrimitives, ArraysOfUnsigned)
} builder {
since("1.1")
deprecatedNonNullArrayFunction()
doc {
"Returns a hash code based on the contents of this array as if it is [List]."
}
returns("Int")
body { "return this.contentHashCode()" }
if (f == ArraysOfUnsigned) {
return@builder
}
on(Platform.JVM) {
inlineOnly()
}
}
val f_contentHashCode_nullable = fn("contentHashCode()") {
include(ArraysOfObjects, ArraysOfPrimitives, ArraysOfUnsigned)
} builder {
since("1.4")
doc {
"Returns a hash code based on the contents of this array as if it is [List]."
}
receiver("SELF?")
returns("Int")
if (family == ArraysOfUnsigned) {
body { "return this?.storage.contentHashCode()" }
return@builder
}
on(Platform.JVM) {
inlineOnly()
annotation("""@JvmName("contentHashCodeNullable")""")
body { "return java.util.Arrays.hashCode(this)" }
}
on(Platform.JS) {
on(Backend.Legacy) {
annotation("""@library("arrayHashCode")""")
body { "definedExternally" }
}
on(Backend.IR) {
body { "return contentHashCodeInternal()" }
}
}
on(Platform.Native) {
body {
"""
if (this === null) return 0
var result = 1
for (element in this)
result = 31 * result + element.hashCode()
return result
"""
}
}
}
val f_contentDeepHashCode = fn("contentDeepHashCode()") {
include(ArraysOfObjects)
} builder {
since("1.1")
annotation("@kotlin.internal.LowPriorityInOverloadResolution")
doc {
"""
Returns a hash code based on the contents of this array as if it is [List].
Nested arrays are treated as lists too.
If any of arrays contains itself on any nesting level the behavior is undefined.
"""
}
returns("Int")
body { "return this.contentDeepHashCode()" }
on(Platform.JVM) {
inlineOnly()
annotation("""@JvmName("contentDeepHashCodeInline")""")
}
}
val f_contentDeepHashCode_nullable = fn("contentDeepHashCode()") {
include(ArraysOfObjects)
} builder {
since("1.4")
doc {
"""
Returns a hash code based on the contents of this array as if it is [List].
Nested arrays are treated as lists too.
If any of arrays contains itself on any nesting level the behavior is undefined.
"""
}
receiver("SELF?")
returns("Int")
on(Platform.JVM) {
inlineOnly()
annotation("""@JvmName("contentDeepHashCodeNullable")""")
body {
"""
if (kotlin.internal.apiVersionIsAtLeast(1, 3, 0))
return contentDeepHashCodeImpl()
else
return java.util.Arrays.deepHashCode(this)
"""
}
}
on(Platform.JS) {
on(Backend.Legacy) {
annotation("""@library("arrayDeepHashCode")""")
body { "definedExternally" }
}
on(Backend.IR) {
body { "return contentDeepHashCodeInternal()" }
}
}
on(Platform.Native) {
body { "return contentDeepHashCodeImpl()" }
}
}
val f_toPrimitiveArray = fn("toPrimitiveArray()") {
include(ArraysOfObjects, PrimitiveType.values().toSet())
include(Collections, PrimitiveType.values().toSet())
} builder {
val primitive = checkNotNull(primitive)
val arrayType = primitive.name + "Array"
signature("to$arrayType()")
returns(arrayType)
if (primitive in PrimitiveType.unsignedPrimitives) {
since("1.3")
annotation("@ExperimentalUnsignedTypes")
}
// TODO: Use different implementations for JS
specialFor(ArraysOfObjects) {
if (primitive in PrimitiveType.unsignedPrimitives) {
sourceFile(SourceFile.UArrays)
}
doc { "Returns an array of ${primitive.name} containing all of the elements of this generic array." }
body {
"""
return $arrayType(size) { index -> this[index] }
"""
}
}
specialFor(Collections) {
if (primitive in PrimitiveType.unsignedPrimitives) {
sourceFile(SourceFile.UCollections)
}
doc { "Returns an array of ${primitive.name} containing all of the elements of this collection." }
body {
"""
val result = $arrayType(size)
var index = 0
for (element in this)
result[index++] = element
return result
"""
}
}
}
val f_asSignedArray = fn("asSignedArray()") {
include(ArraysOfUnsigned)
} builder {
val arrayType = primitive!!.name.drop(1) + "Array"
signature("as$arrayType()")
returns(arrayType)
doc {
"""
Returns an array of type [$arrayType], which is a view of this array where each element is a signed reinterpretation
of the corresponding element of this array.
"""
}
inlineOnly()
body { """return storage""" }
}
val f_toSignedArray = fn("toSignedArray()") {
include(ArraysOfUnsigned)
} builder {
val arrayType = primitive!!.name.drop(1) + "Array"
signature("to$arrayType()")
returns(arrayType)
doc {
"""
Returns an array of type [$arrayType], which is a copy of this array where each element is a signed reinterpretation
of the corresponding element of this array.
"""
}
inlineOnly()
body { """return storage.copyOf()""" }
}
val f_asUnsignedArray = fn("asUnsignedArray()") {
include(ArraysOfUnsigned)
} builder {
val arrayType = primitive!!.name.drop(1) + "Array"
receiver(arrayType)
signature("asU$arrayType()")
returns("SELF")
doc {
"""
Returns an array of type [U$arrayType], which is a view of this array where each element is an unsigned reinterpretation
of the corresponding element of this array.
"""
}
inlineOnly()
body { """return U$arrayType(this)""" }
}
val f_toUnsignedArray = fn("toUnsignedArray()") {
include(ArraysOfUnsigned)
} builder {
val arrayType = primitive!!.name.drop(1) + "Array"
receiver(arrayType)
signature("toU$arrayType()")
returns("SELF")
doc {
"""
Returns an array of type [U$arrayType], which is a copy of this array where each element is an unsigned reinterpretation
of the corresponding element of this array.
"""
}
inlineOnly()
body { """return U$arrayType(this.copyOf())""" }
}
val f_plusElement = fn("plusElement(element: T)") {
include(InvariantArraysOfObjects)
} builder {
returns("SELF")
doc { "Returns an array containing all elements of the original array and then the given [element]." }
on(Platform.JVM) {
inlineOnly()
body { "return plus(element)" }
}
on(Platform.Native) {
inlineOnly()
body { "return plus(element)" }
}
on(Platform.JS) {
family = ArraysOfObjects
inline(suppressWarning = true)
suppress("ACTUAL_WITHOUT_EXPECT") // TODO: KT-21937
returns("Array<T>")
body {
"""
return this.asDynamic().concat(arrayOf(element))
"""
}
}
on(Platform.Common) {
specialFor(InvariantArraysOfObjects) {
suppress("NO_ACTUAL_FOR_EXPECT") // TODO: KT-21937
}
}
}
val f_plus = fn("plus(element: T)") {
include(InvariantArraysOfObjects, ArraysOfPrimitives, ArraysOfUnsigned)
} builderWith { primitive ->
doc { "Returns an array containing all elements of the original array and then the given [element]." }
operator()
returns("SELF")
specialFor(ArraysOfUnsigned) {
inlineOnly()
val signedPrimitiveName = primitive!!.name.drop(1)
body {
"""
return SELF(storage + element.to$signedPrimitiveName())
"""
}
}
specialFor(InvariantArraysOfObjects, ArraysOfPrimitives) {
on(Platform.JVM) {
body {
"""
val index = size
val result = java.util.Arrays.copyOf(this, index + 1)
result[index] = element
return result
"""
}
}
on(Platform.JS) {
inline(suppressWarning = true)
specialFor(InvariantArraysOfObjects) {
family = ArraysOfObjects
suppress("ACTUAL_WITHOUT_EXPECT") // TODO: KT-21937
returns("Array<T>")
}
body {
if (primitive == null)
"return this.asDynamic().concat(arrayOf(element))"
else
"return plus(${primitive.name.lowercase()}ArrayOf(element))"
}
}
on(Platform.Native) {
body {
"""
val index = size
val result = copyOfUninitializedElements(index + 1)
result[index] = element
return result
"""
}
}
on(Platform.Common) {
specialFor(InvariantArraysOfObjects) {
suppress("NO_ACTUAL_FOR_EXPECT") // TODO: KT-21937
}
}
}
}
val f_plus_collection = fn("plus(elements: Collection<T>)") {
include(InvariantArraysOfObjects, ArraysOfPrimitives, ArraysOfUnsigned)
} builder {
operator()
returns("SELF")
doc { "Returns an array containing all elements of the original array and then all elements of the given [elements] collection." }
specialFor(ArraysOfUnsigned) {
val signedPrimitiveName = primitive!!.name.drop(1)
body {
"""
var index = size
val result = storage.copyOf(size + elements.size)
for (element in elements) result[index++] = element.to$signedPrimitiveName()
return SELF(result)
"""
}
}
specialFor(InvariantArraysOfObjects, ArraysOfPrimitives) {
on(Platform.JVM) {
body {
"""
var index = size
val result = java.util.Arrays.copyOf(this, index + elements.size)
for (element in elements) result[index++] = element
return result
"""
}
}
on(Platform.JS) {
// TODO: inline arrayPlusCollection when @PublishedAPI is available
// inline(Platform.JS, Inline.Yes)
// annotations(Platform.JS, """@Suppress("NOTHING_TO_INLINE")""")
specialFor(InvariantArraysOfObjects) {
family = ArraysOfObjects
suppress("ACTUAL_WITHOUT_EXPECT") // TODO: KT-21937
returns("Array<T>")
}
when (primitive) {
null, PrimitiveType.Boolean, PrimitiveType.Long ->
body { "return arrayPlusCollection(this, elements)" }
else -> {
on(Backend.Legacy) {
body {
"return fillFromCollection(this.copyOf(size + elements.size), this.size, elements)"
}
}
on(Backend.IR) {
// Don't use fillFromCollection because it treats arrays
// as `dynamic` but we need to concrete types to perform
// unboxing of collections elements
body {
"""
var index = size
val result = this.copyOf(size + elements.size)
for (element in elements) result[index++] = element
return result
"""
}
}
}
}
}
on(Platform.Native) {
body {
"""
var index = size
val result = copyOfUninitializedElements(index + elements.size)
for (element in elements) result[index++] = element
return result
"""
}
}
on(Platform.Common) {
specialFor(InvariantArraysOfObjects) {
suppress("NO_ACTUAL_FOR_EXPECT") // TODO: KT-21937
}
}
}
}
val f_plus_array = fn("plus(elements: SELF)") {
include(InvariantArraysOfObjects, ArraysOfPrimitives, ArraysOfUnsigned)
} builder {
operator(true)
doc { "Returns an array containing all elements of the original array and then all elements of the given [elements] array." }
returns("SELF")
specialFor(ArraysOfUnsigned) {
inlineOnly()
body { "return SELF(storage + elements.storage)" }
}
specialFor(InvariantArraysOfObjects, ArraysOfPrimitives) {
specialFor(InvariantArraysOfObjects) {
signature("plus(elements: Array<out T>)", notForSorting = true)
}
on(Platform.JVM) {
body {
"""
val thisSize = size
val arraySize = elements.size
val result = java.util.Arrays.copyOf(this, thisSize + arraySize)
System.arraycopy(elements, 0, result, thisSize, arraySize)
return result
"""
}
}
on(Platform.JS) {
inline(suppressWarning = true)
specialFor(InvariantArraysOfObjects) {
family = ArraysOfObjects
suppress("ACTUAL_WITHOUT_EXPECT") // TODO: KT-21937
returns("Array<T>")
body { """return this.asDynamic().concat(elements)""" }
}
specialFor(ArraysOfPrimitives) {
body { """return primitiveArrayConcat(this, elements)""" }
}
}
on(Platform.Native) {
body {
"""
val thisSize = size
val arraySize = elements.size
val result = copyOfUninitializedElements(thisSize + arraySize)
elements.copyInto(result, thisSize)
return result
"""
}
}
on(Platform.Common) {
specialFor(InvariantArraysOfObjects) {
suppress("NO_ACTUAL_FOR_EXPECT") // TODO: KT-21937
}
}
}
}
val f_copyInto = fn("copyInto(destination: SELF, destinationOffset: Int = 0, startIndex: Int = 0, endIndex: Int = size)") {
include(InvariantArraysOfObjects, ArraysOfPrimitives, ArraysOfUnsigned)
} builder {
since("1.3")
returns("SELF")
doc {
"""
Copies this array or its subrange into the [destination] array and returns that array.
It's allowed to pass the same array in the [destination] and even specify the subrange so that it overlaps with the destination range.
@param destination the array to copy to.
@param destinationOffset the position in the [destination] array to copy to, 0 by default.
@param startIndex the beginning (inclusive) of the subrange to copy, 0 by default.
@param endIndex the end (exclusive) of the subrange to copy, size of this array by default.
@throws IndexOutOfBoundsException or [IllegalArgumentException] when [startIndex] or [endIndex] is out of range of this array indices or when `startIndex > endIndex`.
@throws IndexOutOfBoundsException when the subrange doesn't fit into the [destination] array starting at the specified [destinationOffset],
or when that index is out of the [destination] array indices range.
@return the [destination] array.
"""
}
specialFor(ArraysOfUnsigned) {
inlineOnly()
body {
"""
storage.copyInto(destination.storage, destinationOffset, startIndex, endIndex)
return destination
"""
}
}
specialFor(ArraysOfPrimitives, InvariantArraysOfObjects) {
specialFor(InvariantArraysOfObjects) {
receiver("Array<out T>")
}
on(Platform.JVM) {
suppress("ACTUAL_FUNCTION_WITH_DEFAULT_ARGUMENTS")
signature("copyInto(destination: SELF, destinationOffset: Int = 0, startIndex: Int = 0, endIndex: Int = size)")
body {
"""
System.arraycopy(this, startIndex, destination, destinationOffset, endIndex - startIndex)
return destination
"""
}
}
on(Platform.JS) {
suppress("ACTUAL_FUNCTION_WITH_DEFAULT_ARGUMENTS")
signature("copyInto(destination: SELF, destinationOffset: Int = 0, startIndex: Int = 0, endIndex: Int = size)")
inlineOnly()
body {
val cast = ".unsafeCast<Array<$primitive>>()".takeIf { family == ArraysOfPrimitives } ?: ""
"""
arrayCopy(this$cast, destination$cast, destinationOffset, startIndex, endIndex)
return destination
"""
}
}
on(Platform.Native) {
suppress("ACTUAL_FUNCTION_WITH_DEFAULT_ARGUMENTS")
body {
"""
arrayCopy(this, startIndex, destination, destinationOffset, endIndex - startIndex)
return destination
"""
}
specialFor(InvariantArraysOfObjects) {
body {
"""
@Suppress("UNCHECKED_CAST")
arrayCopy(this as Array<Any?>, startIndex, destination as Array<Any?>, destinationOffset, endIndex - startIndex)
return destination
"""
}
}
on(Backend.Wasm) {
body {
"""
AbstractList.checkRangeIndexes(startIndex, endIndex, this.size)
val rangeSize = endIndex - startIndex
AbstractList.checkRangeIndexes(destinationOffset, destinationOffset + rangeSize, destination.size)
kotlin.wasm.internal.copyWasmArray(this.storage, destination.storage, startIndex, destinationOffset, rangeSize)
return destination
"""
}
}
}
}
}
val f_copyOfRangeJvmImpl = fn("copyOfRangeImpl(fromIndex: Int, toIndex: Int)") {
include(InvariantArraysOfObjects, ArraysOfPrimitives)
platforms(Platform.JVM)
} builderWith { _ ->
since("1.3")
visibility("internal")
annotation("@PublishedApi")
annotation("""@JvmName("copyOfRange")""")
returns("SELF")
body {
"""
copyOfRangeToIndexCheck(toIndex, size)
return java.util.Arrays.copyOfRange(this, fromIndex, toIndex)
"""
}
}
val f_copyOfRange = fn("copyOfRange(fromIndex: Int, toIndex: Int)") {
include(InvariantArraysOfObjects, ArraysOfPrimitives, ArraysOfUnsigned)
} builderWith { primitive ->
doc {
"""
Returns a new array which is a copy of the specified range of the original array.
${rangeDoc(hasDefault = false, action = "copy")}
"""
}
returns("SELF")
specialFor(ArraysOfUnsigned) {
inlineOnly()
body { "return SELF(storage.copyOfRange(fromIndex, toIndex))" }
}
specialFor(InvariantArraysOfObjects, ArraysOfPrimitives) {
on(Platform.JS) {
specialFor(InvariantArraysOfObjects) {
family = ArraysOfObjects
suppress("ACTUAL_WITHOUT_EXPECT") // TODO: KT-21937
returns("Array<T>")
}
val rangeCheck = "AbstractList.checkRangeIndexes(fromIndex, toIndex, size)"
when (primitive) {
PrimitiveType.Char, PrimitiveType.Boolean, PrimitiveType.Long ->
body { "return withType(\"${primitive}Array\", this.asDynamic().slice(fromIndex, toIndex))" }
else -> {
body { "return this.asDynamic().slice(fromIndex, toIndex)" }
}
}
body { rangeCheck + "\n" + body }
}
on(Platform.JVM) {
annotation("""@JvmName("copyOfRangeInline")""")
inlineOnly()
body {
"""
return if (kotlin.internal.apiVersionIsAtLeast(1, 3, 0)) {
copyOfRangeImpl(fromIndex, toIndex)
} else {
if (toIndex > size) throw IndexOutOfBoundsException("toIndex: ${'$'}toIndex, size: ${'$'}size")
java.util.Arrays.copyOfRange(this, fromIndex, toIndex)
}
"""
}
}