forked from JetBrains/kotlin
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Arrays.kt
704 lines (645 loc) · 24 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
/*
* Copyright 2010-2017 JetBrains s.r.o.
*
* 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.
*/
package templates
import templates.Family.*
object ArrayOps : TemplateGroupBase() {
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)
} builder {
doc { "Returns the last valid index for the array." }
returns("Int")
body {
"get() = size - 1"
}
}
val f_indices = pval("indices") {
include(ArraysOfObjects, ArraysOfPrimitives)
} builder {
doc { "Returns the range of valid indices for the array." }
returns("IntRange")
body {
"get() = IntRange(0, lastIndex)"
}
}
val f_contentEquals = fn("contentEquals(other: SELF)") {
include(ArraysOfObjects, ArraysOfPrimitives)
} builder {
since("1.1")
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")
on(Platform.JVM) {
inlineOnly()
body { "return java.util.Arrays.equals(this, other)" }
}
on(Platform.JS) {
annotation("""@library("arrayEquals")""")
annotation("""@Suppress("UNUSED_PARAMETER")""")
body { "definedExternally" }
}
}
val f_contentDeepEquals = fn("contentDeepEquals(other: SELF)") {
include(ArraysOfObjects)
} builder {
since("1.1")
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.
"""
}
returns("Boolean")
on(Platform.JVM) {
inlineOnly()
body { "return java.util.Arrays.deepEquals(this, other)" }
}
on(Platform.JS) {
annotation("""@library("arrayDeepEquals")""")
annotation("""@Suppress("UNUSED_PARAMETER")""")
body { "definedExternally" }
}
}
val f_contentToString = fn("contentToString()") {
include(ArraysOfObjects, ArraysOfPrimitives)
} builder {
since("1.1")
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")
on(Platform.JVM) {
inlineOnly()
body { "return java.util.Arrays.toString(this)" }
}
on(Platform.JS) {
annotation("""@library("arrayToString")""")
body { "definedExternally" }
}
}
val f_contentDeepToString = fn("contentDeepToString()") {
include(ArraysOfObjects)
} builder {
since("1.1")
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")
on(Platform.JVM) {
inlineOnly()
body { "return java.util.Arrays.deepToString(this)" }
}
on(Platform.JS) {
annotation("""@library("arrayDeepToString")""")
body { "definedExternally" }
}
}
val f_contentHashCode = fn("contentHashCode()") {
include(ArraysOfObjects, ArraysOfPrimitives)
} builder {
since("1.1")
doc {
"Returns a hash code based on the contents of this array as if it is [List]."
}
returns("Int")
on(Platform.JVM) {
inlineOnly()
body { "return java.util.Arrays.hashCode(this)" }
}
on(Platform.JS) {
annotation("""@library("arrayHashCode")""")
body { "definedExternally" }
}
}
val f_contentDeepHashCode = fn("contentDeepHashCode()") {
include(ArraysOfObjects)
} builder {
since("1.1")
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")
on(Platform.JVM) {
inlineOnly()
body { "return java.util.Arrays.deepHashCode(this)" }
}
on(Platform.JS) {
annotation("""@library("arrayDeepHashCode")""")
body { "definedExternally" }
}
}
val f_toPrimitiveArray = fn("toPrimitiveArray()") {
include(ArraysOfObjects, PrimitiveType.defaultPrimitives)
include(Collections, PrimitiveType.defaultPrimitives)
} builder {
val primitive = checkNotNull(primitive)
val arrayType = primitive.name + "Array"
signature("to$arrayType()")
returns(arrayType)
// TODO: Use different implementations for JS
specialFor(ArraysOfObjects) {
doc { "Returns an array of ${primitive.name} containing all of the elements of this generic array." }
body {
"""
val result = $arrayType(size)
for (index in indices)
result[index] = this[index]
return result
"""
}
}
specialFor(Collections) {
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_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.JS) {
family = ArraysOfObjects
inline(suppressWarning = true)
returns("Array<T>")
body {
"""
return this.asDynamic().concat(arrayOf(element))
"""
}
}
}
val f_plus = fn("plus(element: T)") {
include(InvariantArraysOfObjects, ArraysOfPrimitives)
} builderWith { primitive ->
doc { "Returns an array containing all elements of the original array and then the given [element]." }
operator()
returns("SELF")
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
returns("Array<T>")
}
body {
if (primitive == null)
"return this.asDynamic().concat(arrayOf(element))"
else
"return plus(${primitive.name.toLowerCase()}ArrayOf(element))"
}
}
}
val f_plus_collection = fn("plus(elements: Collection<T>)") {
include(InvariantArraysOfObjects, ArraysOfPrimitives)
} builder {
operator()
returns("SELF")
doc { "Returns an array containing all elements of the original array and then all elements of the given [elements] collection." }
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
returns("Array<T>")
}
when (primitive) {
null, PrimitiveType.Boolean, PrimitiveType.Long ->
body { "return arrayPlusCollection(this, elements)" }
else ->
body { "return fillFromCollection(this.copyOf(size + elements.size), this.size, elements)" }
}
}
}
val f_plus_array = fn("plus(elements: SELF)") {
include(InvariantArraysOfObjects, ArraysOfPrimitives)
} 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(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
returns("Array<T>")
body { """return this.asDynamic().concat(elements)""" }
}
specialFor(ArraysOfPrimitives) {
body { """return primitiveArrayConcat(this, elements)""" }
}
}
}
val f_copyOfRange = fn("copyOfRange(fromIndex: Int, toIndex: Int)") {
include(InvariantArraysOfObjects, ArraysOfPrimitives)
} builderWith { primitive ->
doc { "Returns new array which is a copy of range of original array." }
returns("SELF")
on(Platform.JS) {
specialFor(InvariantArraysOfObjects) {
family = ArraysOfObjects
returns("Array<T>")
}
when(primitive) {
PrimitiveType.Char, PrimitiveType.Boolean, PrimitiveType.Long ->
body { "return withType(\"${primitive}Array\", this.asDynamic().slice(fromIndex, toIndex))" }
else -> {
inline(suppressWarning = true)
body { "return this.asDynamic().slice(fromIndex, toIndex)" }
}
}
}
on(Platform.JVM) {
inlineOnly()
body { "return java.util.Arrays.copyOfRange(this, fromIndex, toIndex)" }
}
}
val f_copyOf = fn("copyOf()") {
include(InvariantArraysOfObjects)
include(ArraysOfPrimitives, PrimitiveType.defaultPrimitives)
} builder {
doc { "Returns new array which is a copy of the original array." }
returns("SELF")
on(Platform.JVM) {
inlineOnly()
body { "return java.util.Arrays.copyOf(this, size)" }
}
on(Platform.JS) {
specialFor(InvariantArraysOfObjects) {
family = ArraysOfObjects
returns("Array<T>")
}
when (primitive) {
null -> {
inline(suppressWarning = true)
body { "return this.asDynamic().slice()" }
}
PrimitiveType.Char, PrimitiveType.Boolean, PrimitiveType.Long ->
body { "return withType(\"${primitive}Array\", this.asDynamic().slice())" }
else -> {
inline(suppressWarning = true)
body { "return this.asDynamic().slice()" }
}
}
}
}
val f_copyOf_newSize = fn("copyOf(newSize: Int)") {
include(ArraysOfPrimitives, PrimitiveType.defaultPrimitives)
include(InvariantArraysOfObjects)
} builder {
doc { "Returns new array which is a copy of the original array, resized to the given [newSize]." }
specialFor(ArraysOfPrimitives) {
returns("SELF")
on(Platform.JS) {
when (primitive!!) {
PrimitiveType.Boolean ->
body { "return withType(\"BooleanArray\", arrayCopyResize(this, newSize, false))" }
PrimitiveType.Char ->
body { "return withType(\"CharArray\", fillFrom(this, ${primitive}Array(newSize)))" }
PrimitiveType.Long ->
body { "return withType(\"LongArray\", arrayCopyResize(this, newSize, ZERO))" }
else ->
body { "return fillFrom(this, ${primitive}Array(newSize))" }
}
}
}
specialFor(InvariantArraysOfObjects) {
returns("Array<T?>")
on(Platform.JS) {
family = ArraysOfObjects
body { "return arrayCopyResize(this, newSize, null)" }
}
}
on(Platform.JVM) {
inlineOnly()
body {
"return java.util.Arrays.copyOf(this, newSize)"
}
}
}
val f_sort = fn("sort()") {
include(ArraysOfPrimitives, PrimitiveType.numericPrimitives + PrimitiveType.Char)
include(ArraysOfObjects)
} builder {
typeParam("T: Comparable<T>")
doc { "Sorts the array in-place according to the natural order of its elements." }
specialFor(ArraysOfPrimitives) {
doc { "Sorts the array in-place." }
}
returns("Unit")
on(Platform.JS) {
body {
"""
if (size > 1)
sort { a: T, b: T -> a.compareTo(b) }
"""
}
specialFor(ArraysOfPrimitives) {
if (primitive != PrimitiveType.Long) {
annotation("""@library("primitiveArraySort")""")
body { "definedExternally" }
}
}
}
on(Platform.JVM) {
specialFor(ArraysOfObjects) {
inlineOnly()
body {
"""
@Suppress("UNCHECKED_CAST")
(this as Array<Any?>).sort()
"""
}
}
specialFor(ArraysOfPrimitives) {
body {
"if (size > 1) java.util.Arrays.sort(this)"
}
}
}
}
val f_sortWith = fn("sortWith(comparator: Comparator<in T>)") {
include(ArraysOfObjects)
} builder {
doc { "Sorts the array in-place according to the order specified by the given [comparator]." }
returns("Unit")
on(Platform.JVM) {
body {
"if (size > 1) java.util.Arrays.sort(this, comparator)"
}
}
on(Platform.JS) {
body {
"""
if (size > 1)
sort { a, b -> comparator.compare(a, b) }
"""
}
}
}
val f_sort_comparison = fn("sort(noinline comparison: (a: T, b: T) -> Int)") {
platforms(Platform.JS)
include(ArraysOfObjects, ArraysOfPrimitives)
exclude(PrimitiveType.Boolean)
} builder {
inlineOnly()
returns("Unit")
doc { "Sorts the array in-place according to the order specified by the given [comparison] function." }
body { "asDynamic().sort(comparison)" }
}
val f_sort_objects = fn("sort()") {
// left with more generic signature for JVM only
platforms(Platform.JVM)
include(ArraysOfObjects)
} builder {
doc {
"""
Sorts the array in-place according to the natural order of its elements.
@throws ClassCastException if any element of the array is not [Comparable].
"""
}
returns("Unit")
body {
"if (size > 1) java.util.Arrays.sort(this)"
}
}
val f_sort_range = fn("sort(fromIndex: Int = 0, toIndex: Int = size)") {
platforms(Platform.JVM)
include(ArraysOfObjects, ArraysOfPrimitives)
exclude(PrimitiveType.Boolean)
} builder {
doc { "Sorts a range in the array in-place." }
returns("Unit")
body {
"java.util.Arrays.sort(this, fromIndex, toIndex)"
}
}
val f_sortWith_range = fn("sortWith(comparator: Comparator<in T>, fromIndex: Int = 0, toIndex: Int = size)") {
platforms(Platform.JVM)
include(ArraysOfObjects)
} builder {
doc { "Sorts a range in the array in-place with the given [comparator]." }
returns("Unit")
body {
"java.util.Arrays.sort(this, fromIndex, toIndex, comparator)"
}
}
val f_asList = fn("asList()") {
include(ArraysOfObjects, ArraysOfPrimitives)
} builder {
doc { "Returns a [List] that wraps the original array." }
returns("List<T>")
on(Platform.JVM) {
body { """return ArraysUtilJVM.asList(this)""" }
}
on(Platform.JS) {
body { """return ArrayList<T>(this.unsafeCast<Array<Any?>>())""" }
}
specialFor(ArraysOfPrimitives) {
val objectLiteralImpl = """
return object : AbstractList<T>(), RandomAccess {
override val size: Int get() = [email protected]
override fun isEmpty(): Boolean = [email protected]()
override fun contains(element: T): Boolean = [email protected](element)
override fun get(index: Int): T = this@asList[index]
override fun indexOf(element: T): Int = [email protected](element)
override fun lastIndexOf(element: T): Int = [email protected](element)
}
"""
on(Platform.JVM) {
body { objectLiteralImpl }
}
on(Platform.JS) {
if (primitive == PrimitiveType.Char) {
body { objectLiteralImpl }
}
else {
inlineOnly()
body { "return this.unsafeCast<Array<T>>().asList()" }
}
}
}
}
val f_toTypedArray = fn("toTypedArray()") {
include(ArraysOfPrimitives)
} builder {
returns("Array<T>")
doc {
"""
Returns a *typed* object array containing all of the elements of this primitive array.
"""
}
on(Platform.JVM) {
body {
"""
val result = arrayOfNulls<T>(size)
for (index in indices)
result[index] = this[index]
@Suppress("UNCHECKED_CAST")
return result as Array<T>
"""
}
}
on(Platform.JS) {
when (primitive) {
PrimitiveType.Char ->
body { "return Array<Char>(size, { i -> this[i] })" }
PrimitiveType.Boolean, PrimitiveType.Long ->
body { "return copyOf().unsafeCast<Array<T>>()" }
else ->
body { "return js(\"[]\").slice.call(this)" }
}
}
}
val f_fill = fn("fill(element: T, fromIndex: Int = 0, toIndex: Int = size)") {
platforms(Platform.JVM)
include(InvariantArraysOfObjects, ArraysOfPrimitives)
} builder {
doc { "Fills original array with the provided value." }
returns("Unit")
body {
"""
java.util.Arrays.fill(this, fromIndex, toIndex, element)
"""
}
}
val f_binarySearch = fn("binarySearch(element: T, fromIndex: Int = 0, toIndex: Int = size)") {
platforms(Platform.JVM)
include(ArraysOfObjects, ArraysOfPrimitives)
exclude(PrimitiveType.Boolean)
} builder {
doc {
"""
Searches the array or the range of the array for the provided [element] using the binary search algorithm.
The array is expected to be sorted, otherwise the result is undefined.
If the array contains multiple elements equal to the specified [element], there is no guarantee which one will be found.
@return the index of the element, if it is contained in the array within the specified range;
otherwise, the inverted insertion point `(-insertion point - 1)`.
The insertion point is defined as the index at which the element should be inserted,
so that the array (or the specified subrange of array) still remains sorted.
"""
}
returns("Int")
body {
"return java.util.Arrays.binarySearch(this, fromIndex, toIndex, element)"
}
}
val f_binarySearch_comparator = fn("binarySearch(element: T, comparator: Comparator<in T>, fromIndex: Int = 0, toIndex: Int = size)") {
platforms(Platform.JVM)
include(ArraysOfObjects)
} builder {
doc {
"""
Searches the array or the range of the array for the provided [element] using the binary search algorithm.
The array is expected to be sorted according to the specified [comparator], otherwise the result is undefined.
If the array contains multiple elements equal to the specified [element], there is no guarantee which one will be found.
@return the index of the element, if it is contained in the array within the specified range;
otherwise, the inverted insertion point `(-insertion point - 1)`.
The insertion point is defined as the index at which the element should be inserted,
so that the array (or the specified subrange of array) still remains sorted according to the specified [comparator].
"""
}
returns("Int")
body {
"return java.util.Arrays.binarySearch(this, fromIndex, toIndex, element, comparator)"
}
}
}