-
Notifications
You must be signed in to change notification settings - Fork 182
Expand file tree
/
Copy pathBshArray.java
More file actions
590 lines (540 loc) · 23.6 KB
/
BshArray.java
File metadata and controls
590 lines (540 loc) · 23.6 KB
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
/** Copyright 2018 Nick nickl- Lombard
*
* 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 bsh;
import java.lang.reflect.Array;
import java.util.AbstractList;
import java.util.ArrayDeque;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.LinkedHashSet;
import java.util.LinkedList;
import java.util.List;
import java.util.ListIterator;
import java.util.Map;
import java.util.Queue;
import java.util.RandomAccess;
import java.util.function.IntSupplier;
import java.util.Map.Entry;
import static bsh.Types.MapEntry;
/** Collection of array manipulation functions. */
public class BshArray {
/** Constructor private no instance required. */
private BshArray() {}
/** Get object from array or list at index.
* @param array to retrieve from
* @param index of the element to retrieve
* @return Array.get for array or List.get for list
* @throws UtilTargetError wrapped Index out of bounds */
public static Object getIndex(Object array, int index)
throws UtilTargetError {
Interpreter.debug("getIndex: ", array, ", index=", index);
try {
if ( array instanceof List )
return ((List<?>) array).get(index);
Object val = Array.get(array, index);
return Primitive.wrap( val, Types.arrayElementType(array.getClass()) );
} catch( IndexOutOfBoundsException e1 ) {
int len = array instanceof List
? ((List<?>) array).size()
: Array.getLength(array);
throw new UtilTargetError("Index " + index
+ " out-of-bounds for length " + len, e1);
}
}
/** Set element value of array or list at index.
* Array.set for array or List.set for list.
* @param array to set value for.
* @param index of the element to set
* @param val the value to set
* @throws UtilTargetError wrapped target exceptions */
@SuppressWarnings("unchecked")
public static void setIndex(Object array, int index, Object val)
throws ReflectError, UtilTargetError {
try {
val = Primitive.unwrap(val);
if ( array instanceof List )
((List<Object>) array).set(index, val);
else
Array.set(array, index, val);
}
catch( IllegalArgumentException e1 ) {
// fabricated array store exception
throw new UtilTargetError(
new ArrayStoreException( e1.getMessage() ) );
} catch( IndexOutOfBoundsException e1 ) {
int len = array instanceof List
? ((List<?>) array).size()
: Array.getLength(array);
throw new UtilTargetError("Index " + index
+ " out-of-bounds for length " + len, e1);
}
}
/** Slice the supplied list for range and step.
* @param list to slice
* @param from start index inclusive
* @param to to index exclusive
* @param step size of step or 0 if no step
* @return a sliced view of the supplied list */
public static Object slice(List<Object> list, int from, int to, int step) {
int length = list.size();
if ( to > length ) to = length;
if ( 0 > from ) from = 0;
length = to - from;
if ( 0 >= length )
return list.subList(0, 0);
if ( step == 0 || step == 1 )
return list.subList(from, to);
List<Integer> slices = new ArrayList<>();
for ( int i = 0; i < length; i++ )
if ( i % step == 0 )
slices.add(step < 0 ? length-1-i : i+from);
return new SteppedSubList(list, slices);
}
/** Slice the supplied array for range and step.
* @param arr to slice
* @param from start index inclusive
* @param to to index exclusive
* @param step size of step or 0 if no step
* @return a new array instance sliced */
public static Object slice(Object arr, int from, int to, int step) {
Class<?> toType = Types.arrayElementType(arr.getClass());
int length = Array.getLength(arr);
if ( to > length ) to = length;
if ( 0 > from ) from = 0;
length = to - from;
if ( 0 >= length )
return Array.newInstance(toType, 0);
if ( step == 0 || step == 1 ) {
Object toArray = Array.newInstance(toType, length);
System.arraycopy(arr, from, toArray, 0, length);
return toArray;
}
Object[] tmp = new Object[(int)Math.ceil((0.0+length)/Math.abs(step))];
for ( int i = 0, j = 0; i < length; i++ )
if ( i % step == 0 )
tmp[j++] = Array.get(arr, step < 0 ? length-1-i : i+from);
Object toArray = Array.newInstance(toType, tmp.length);
copy(toType, toArray, (Object)tmp);
return toArray;
}
/** Repeat the contents of a list a number of times.
* @param list the list to repeat
* @param times number of repetitions
* @return a new list instance with repeated contents */
public static Object repeat(List<Object> list, int times) {
if ( times < 1 )
if (list instanceof Queue)
return new LinkedList<>();
else
return new ArrayList<>(0);
List<Object> lst = list instanceof Queue
? new LinkedList<>(list)
: new ArrayList<>(list);
if ( times == 1 )
return lst;
while ( times-- > 1 )
lst.addAll(list);
return lst;
}
/** Repeat the contents of an array a number of times.
* @param arr the array object to repeat
* @param times number of repetitions
* @return a new array instance with repeated contents */
public static Object repeat(Object arr, int times) {
Class<?> toType = Types.arrayElementType(arr.getClass());
if ( times < 1 )
return Array.newInstance(toType, 0);
int[] dims = dimensions(arr);
int length = dims[0];
dims[0] *= times;
int i = 0, total = dims[0];
Object toArray = Array.newInstance(toType, dims);
while ( i < total ) {
System.arraycopy(arr, 0, toArray, i, length);
i += length;
}
return toArray;
}
/** Concatenate two lists.
* @param lhs 1st list
* @param rhs 2nd list
* @return a new list instance of concatenated contents. */
public static Object concat(List<?> lhs, List<?> rhs) {
List<Object> list = lhs instanceof Queue
? new LinkedList<>(lhs)
: new ArrayList<>(lhs);
list.addAll(rhs);
return list;
}
/** Concatenate two arrays.
* @param lhs 1st array
* @param rhs 2nd array
* @return a new array instance of concatenated contents.
* @throws UtilEvalError for inconsistent dimensions. */
public static Object concat(Object lhs, Object rhs) throws UtilEvalError {
Class<?> lhsType = lhs.getClass();
Class<?> rhsType = rhs.getClass();
if ( Types.arrayDimensions(lhsType) != Types.arrayDimensions(rhsType) )
throw new UtilEvalError("Cannot concat arrays with inconsistent dimensions."
+ " Attempting to concat array of type " + StringUtil.typeString(lhs)
+ " with array of type " + StringUtil.typeString(rhs) + ".");
Class<?> toType = Types.getCommonType(
Types.arrayElementType(lhsType),
Types.arrayElementType(rhsType));
int[] dims = dimensions(lhs);
dims[0] = Array.getLength(lhs) + Array.getLength(rhs);
Object toArray = Array.newInstance(toType, dims);
copy(toType, toArray, lhs, rhs);
return toArray;
}
/** Collect dimensions array of supplied array object.
* Returns the integer array used for Array.newInstance.
* @param arr to inspect
* @return int array of dimensions */
public static int[] dimensions(Object arr) {
int[] dims = new int[Types.arrayDimensions(arr.getClass())];
if ( 0 == dims.length || 0 == (dims[0] = Array.getLength(arr)) )
return dims;
for ( int i = 1; i < dims.length; i++ )
if ( null != (arr = Array.get(arr, 0)) )
dims[i] = Array.getLength(arr);
else break;
return dims;
}
/** Copy and cast the elements of from arrays to type in to array.
* Recursively traverse dimensions to populate the elements at to array.
* @param toType the element type to cast to
* @param to the destination array
* @param from the list of origin arrays */
private static void copy(Class<?> toType, Object to, Object... from) {
int f = 0, fi = 0,
length = Array.getLength(from[0]),
total = from.length > 1 ? Array.getLength(to) : length;
if ( Types.arrayDimensions(to.getClass()) == 1 ) {
for ( int i = 0; i < total; i++ ) {
Object value = Array.get(from[f], fi++);
try {
value = Primitive.unwrap(
Types.castObject(value, toType, Types.CAST));
} catch (UtilEvalError e) { /* ignore cast errors */ }
if ( Byte.TYPE == toType )
Array.setByte(to, i, (byte) value);
else if ( Short.TYPE == toType )
Array.setShort(to, i, (short) value);
else if ( Integer.TYPE == toType )
Array.setInt(to, i, (int) value);
else if ( Long.TYPE == toType )
Array.setLong(to, i, (long) value);
else if ( Float.TYPE == toType )
Array.setFloat(to, i, (float) value);
else if ( Double.TYPE == toType )
Array.setDouble(to, i, (double) value);
else if ( Character.TYPE == toType )
Array.setChar(to, i, (char) value);
else if ( Boolean.TYPE == toType )
Array.setBoolean(to, i, (boolean) value);
else
Array.set(to, i, value);
// concatenate multiple from arrays
if ( length < total && fi == length && f+1 < from.length ) {
length = Array.getLength(from[++f]);
fi = 0;
}
}
} else for ( int i = 0; i < total; i++ ) {
// concatenate multiple from arrays
if ( length < total && fi == length && f+1 < from.length ) {
length = Array.getLength(from[++f]);
fi = 0;
}
Object frm = Array.get(from[f], fi++);
// null dimension example: new Integer[2][]
if ( null == frm ) {
Array.set(to, i, null);
continue;
}
Object tto = Array.get(to, i);
// mixed array lengths in multiple dimensions ex: {{1,2}, {3}}
if ( Array.getLength(frm) != Array.getLength(tto) )
Array.set(to, i,
tto = Array.newInstance(toType, dimensions(frm)));
// recurse copy for next array dimension
copy(toType, tto, frm);
}
}
/** Relaxed implementation of the java 9 Map.ofEntries.
* LinkedHashMap ensures element order remains as supplied.
* @param entries array of Map.Entry elements
* @return a mutable, type relaxed LinkedHashMap */
private static Map<?, ?> mapOfEntries( Entry<?, ?>... entries ) {
Map<Object, Object> looseTypedMap = new LinkedHashMap<>( entries.length );
for (Entry<?, ?> entry : entries)
looseTypedMap.put(entry.getKey(), entry.getValue());
return looseTypedMap;
}
/** Cast an array to the specified element type.
* @param toType element type of cast array
* @param fromType type of from value
* @param fromValue the array value to cast
* @return a new instance of to type
* @throws UtilEvalError cast error */
static Object castArray( Class<?> toType, Class<?> fromType, Object fromValue
) throws UtilEvalError {
// Collection type cast from array
if ( Collection.class.isAssignableFrom(toType) )
if ( List.class.isAssignableFrom(toType) || Queue.class == toType ) {
if ( toType.isAssignableFrom(ArrayList.class) )
// List type is implemented as a mutable ArrayList
return new ArrayList<>(Arrays.asList((Object[])
Types.castObject(fromValue, Object.class, Types.CAST)));
else if ( toType.isAssignableFrom(LinkedList.class) )
// Queue type is implemented as a mutable LinkedList
return new LinkedList<>(Arrays.asList((Object[])
Types.castObject(fromValue, Object.class, Types.CAST)));
} else if ( toType.isAssignableFrom(ArrayDeque.class) )
// Deque type is implemented as a mutable ArrayDeque
return new ArrayDeque<>(Arrays.asList((Object[])
Types.castObject(fromValue, Object.class, Types.CAST)));
else if ( toType.isAssignableFrom(LinkedHashSet.class) )
// Set type is implemented as a mutable LinkedHashSet
return new LinkedHashSet<>(Arrays.asList((Object[])
Types.castObject(fromValue, Object.class, Types.CAST)));
Class<?> baseType = Types.arrayElementType(fromType);
// Map type gets converted to a mutable LinkedHashMap
if ( Map.class.isAssignableFrom(toType) ) {
if ( Entry.class.isAssignableFrom(baseType) )
return mapOfEntries((Entry[]) fromValue);
if ( toType.isAssignableFrom(LinkedHashMap.class) ) {
int length = Array.getLength(fromValue);
Map<Object, Object> map = new LinkedHashMap<>(
(int) Math.ceil((0.0 + length) / 2));
for ( int i = 0; i < length; i++ )
map.put(Array.get(fromValue, i),
++i < length ? Array.get(fromValue, i) : null);
return map;
}
}
int[] dims = dimensions(fromValue);
int length = dims[0];
if (length == 0)
return Array.newInstance(toType, dims);
// if we have an Object[] try and find a more specific type
baseType = commonType(baseType, fromValue, () -> length);
// Entry type gets converted to LHS.MapEntry
if ( Entry.class.isAssignableFrom(toType) ) {
if ( Entry.class.isAssignableFrom(baseType) ) {
if ( MapEntry.class != baseType )
return fromValue;
// Cast to Map.Entry so as not to confuse it with maps
Entry<?, ?>[] toArray = new Entry[Array.getLength(fromValue)];
copy(Entry.class, (Object) toArray, fromValue);
return toArray;
}
if ( length == 1 )
return new MapEntry(Array.get(fromValue, 0), null);
if ( length == 2 )
return new MapEntry(Array.get(fromValue, 0), Array.get(fromValue, 1));
int size = (int) Math.ceil((0.0 + length) / 2);
// Using Map.Entry array so as not to confuse it with maps
Entry<?, ?>[] toArray = new Entry[size];
for ( int i = 0, j = 0; i < length; i++ )
toArray[j++] = new MapEntry(Array.get(fromValue, i),
++i < length ? Array.get(fromValue, i) : null);
return toArray;
}
// cast array to element type of toType
toType = Types.arrayElementType(toType);
Object toArray = Array.newInstance(toType, dims);
BshArray.copy(toType, toArray, fromValue);
return toArray;
}
/** Find a more specific type if the element type is Object.class.
* @param baseType the element type
* @param fromValue the array to inspect
* @param length the length of the array
* @return baseType unless baseType is Object.class and common is not */
public static Class<?> commonType(Class<?> baseType, Object fromValue, IntSupplier length) {
if ( Object.class != baseType )
return baseType;
Class<?> common = null;
int len = length.getAsInt();
for (int i = 0; i < len; i++)
if ( Object.class == (common = Types.getCommonType(common,
Types.getType(Array.get(fromValue, 0)))) )
break;
if ( null != common && common != baseType )
return common;
return baseType;
}
/** Provides a view of a parent list for a specific list of parent indexes (steps).
* Based on @see ArrayList.SubList. */
private static class SteppedSubList extends AbstractList<Object> implements RandomAccess {
private final List<Object> parent;
private final List<Integer> steps;
/** Default constructor.
* @param parent the referenced parent list
* @param steps a list of parent indexes for this view. */
SteppedSubList(List<Object> parent, List<Integer> steps) {
this.parent = parent;
this.steps = steps;
}
/** Overridden method to set the parent value for the parent index of
* the step at the supplied index.
* {@inheritDoc} */
@Override
public Object set(int index, Object e) {
return this.parent.set(this.steps.get(index), e);
}
/** Overridden method to get the parent value for the parent index of
* the step at the supplied index.
* {@inheritDoc} */
@Override
public Object get(int index) {
return this.parent.get(this.steps.get(index));
}
/** Overridden method to retrieve the size of the view.
* {@inheritDoc} */
@Override
public int size() {
return this.steps.size();
}
/** Overridden method to add a value to the parent at the parent index of
* the step at the supplied index. Update remaining step indexes moved down.
* {@inheritDoc} */
@Override
public void add(int index, Object e) {
int idx = index == this.size()
? this.steps.get(index - 1) + 1
: this.steps.get(index);
this.parent.add(idx, e);
for ( int i = index; i < this.size(); i++ )
this.steps.set(i, this.steps.get(i) + 1);
this.steps.add(index, idx);
}
/** Overridden method to remove a value from the parent at the parent index of
* the step at the supplied index. Update remaining step indexes moved up.
* {@inheritDoc} */
@Override
public Object remove(int index) {
int idx = this.steps.get(index);
for ( int i = index + 1; i < this.size(); i++ )
this.steps.set(i, this.steps.get(i) - 1);
this.steps.remove(index);
return this.parent.remove(idx);
}
/** Overridden method delegates to addAll at index size.
* {@inheritDoc} */
@Override
public boolean addAll(Collection<? extends Object> c) {
return addAll(this.steps.size(), c);
}
/** Overridden method traverses supplied list and delegates to add method for each.
* {@inheritDoc} */
@Override
public boolean addAll(int index, Collection<? extends Object> c) {
int cnt = 0;
for ( Object e : c )
this.add(index + cnt++, e);
return cnt > 0;
}
/** Overridden method to retrieve a stepped sub list of a sub list of this view.
* {@inheritDoc} */
@Override
public List<Object> subList(int fromIndex, int toIndex) {
return new SteppedSubList(this.parent, this.steps.subList(fromIndex, toIndex));
}
/** Overridden method delegates to list iterator method.
* {@inheritDoc} */
@Override
public Iterator<Object> iterator() {
return listIterator();
}
/** Overridden method supplying a modifiable list iterator which delegates to methods
* on this view.
* {@inheritDoc} */
@Override
public ListIterator<Object> listIterator(final int index) {
/** A copy of the list iterator to avoid concurrent modification issues. */
ListIterator<Integer> sliceIter = new ArrayList<>(this.steps).listIterator(index);
return new ListIterator<Object>() {
int lastIndex = 0;
/** Overridden method delegates to the copy.
* {@inheritDoc} */
@Override
public boolean hasNext() {
return sliceIter.hasNext();
}
/** Overridden method delegates to this view get method.
* {@inheritDoc} */
@Override
public Object next() {
sliceIter.next();
lastIndex = previousIndex();
return SteppedSubList.this.get(lastIndex);
}
/** Overridden method delegates to the copy.
* {@inheritDoc} */
@Override
public boolean hasPrevious() {
return sliceIter.hasPrevious();
}
/** Overridden method delegates to this view get method.
* {@inheritDoc} */
@Override
public Object previous() {
sliceIter.previous();
lastIndex = nextIndex();
return SteppedSubList.this.get(lastIndex);
}
/** Overridden method delegates to the copy.
* {@inheritDoc} */
@Override
public int nextIndex() {
return sliceIter.nextIndex();
}
/** Overridden method delegates to the copy.
* {@inheritDoc} */
@Override
public int previousIndex() {
return sliceIter.previousIndex();
}
/** Overridden method delegates to this view remove method.
* {@inheritDoc} */
@Override
public void remove() {
SteppedSubList.this.remove(lastIndex);
sliceIter.remove();
lastIndex = -1;
}
/** Overridden method delegates to this view set method.
* {@inheritDoc} */
@Override
public void set(Object e) {
SteppedSubList.this.set(lastIndex, e);
}
/** Overridden method delegates to this view add method.
* {@inheritDoc} */
@Override
public void add(Object e) {
SteppedSubList.this.add(lastIndex, e);
sliceIter.add(steps.get(lastIndex));
lastIndex = -1;
}
};
}
}
}