-
Notifications
You must be signed in to change notification settings - Fork 226
Expand file tree
/
Copy pathPyArray.java
More file actions
2777 lines (2483 loc) · 96.7 KB
/
PyArray.java
File metadata and controls
2777 lines (2483 loc) · 96.7 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
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 (c) Corporation for National Research Initiatives
package org.python.core;
import java.io.ByteArrayOutputStream;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.EOFException;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.lang.ref.WeakReference;
import java.lang.reflect.Array;
import java.math.BigInteger;
import java.nio.ByteBuffer;
import org.python.core.PyArray.ItemType;
import org.python.core.buffer.BaseBuffer;
import org.python.core.buffer.SimpleBuffer;
import org.python.core.buffer.SimpleStringBuffer;
import org.python.core.util.ByteSwapper;
import org.python.core.util.StringUtil;
import org.python.expose.ExposedGet;
import org.python.expose.ExposedMethod;
import org.python.expose.ExposedNew;
import org.python.expose.ExposedType;
import org.python.expose.MethodType;
import org.python.modules.gc;
/**
* The type {@code array.array}. This is a wrapper around native Java arrays. Instances of
* {@code PyArray} are created either by Java functions or directly by the {@code jarray} module
* (q.v.).
* <p>
* The range of possible element (item) types exceeds that in Python, since it allows for arbitrary
* Java classes. This extended behaviour is accessible from Python by supplying a Java type (class)
* to the constructor, where one might have used a single character type code. For example:<pre>
* >>> ax = array.array(BigDecimal, (BigDecimal(str(n)) for n in range(5)))
* >>> ax
* array(java.math.BigDecimal, [0, 1, 2, 3, 4])
* >>> type(ax[2])
* <type 'java.math.BigDecimal'>
* </pre>
*
* <table>
* <caption>Supported item types</caption>
* <tr>
* <th>typecode</th>
* <th>Python type</th>
* <th>Java type</th>
* <th>serialised size</th>
* <th>signed</th>
* </tr>
* <tr>
* <td>{@code b}</td>
* <td>{@code int}</td>
* <td>{@code byte}</td>
* <td>1</td>
* </tr>
* <tr>
* <td>{@code B}</td>
* <td>{@code int}</td>
* <td>{@code byte}</td>
* <td>1</td>
* <td>unsigned</td>
* </tr>
* <tr>
* <td>{@code h}</td>
* <td>{@code int}</td>
* <td>{@code short}</td>
* <td>2</td>
* </tr>
* <tr>
* <td>{@code H}</td>
* <td>{@code int}</td>
* <td>{@code short}</td>
* <td>2</td>
* <td>unsigned</td>
* </tr>
* <tr>
* <td>{@code i}</td>
* <td>{@code int}</td>
* <td>{@code int}</td>
* <td>4</td>
* </tr>
* <tr>
* <td>{@code I}</td>
* <td>{@code long}</td>
* <td>{@code int}</td>
* <td>4</td>
* <td>unsigned</td>
* </tr>
* <tr>
* <td>{@code l}</td>
* <td>{@code long}</td>
* <td>{@code long}</td>
* <td>8</td>
* </tr>
* <tr>
* <td>{@code L}</td>
* <td>{@code long}</td>
* <td>{@code long}</td>
* <td>8</td>
* <td>unsigned</td>
* </tr>
* <tr>
* <td>{@code f}</td>
* <td>{@code float}</td>
* <td>{@code float}</td>
* <td>4</td>
* </tr>
* <tr>
* <td>{@code d}</td>
* <td>{@code float}</td>
* <td>{@code double}</td>
* <td>8</td>
* </tr>
* <tr>
* <td>{@code c}</td>
* <td>{@code str}</td>
* <td>{@code byte}</td>
* <td>1</td>
* <td>unsigned</td>
* </tr>
* <tr>
* <td>{@code u}</td>
* <td>{@code unicode}</td>
* <td>{@code int}</td>
* <td>1</td>
* <td>unsigned</td>
* </tr>
* <tr>
* <td>{@code z}</td>
* <td>{@code bool}</td>
* <td>{@code boolean}</td>
* <td>1</td>
* </tr>
* </table>
* Types shown as "unsigned" represent positive values encoded in the same number of bits as the
* equivalent signed type. The Java value serialised makes no distinction. The consumer of the
* stream has to know whether to make a signed or unsigned interpretation of the bits. When reading
* a stream, the type code declared for the destination array decides the interpretation of the
* bytes.
*/
@ExposedType(name = "array.array", base = PyObject.class)
public class PyArray extends PySequence implements Cloneable, BufferProtocol, Traverseproc {
public static final PyType TYPE = PyType.fromClass(PyArray.class);
/** The underlying Java array, a Java Array in practice. */
private Object data;
/** The Java class of elements in the {@code data} array. */
private Class<?> itemClass;
/** Everything else we need to know about the type of elements in the {@code data} array. */
private ItemType itemType;
/**
* Mix in the mechanisms for manipulating the underlying array as this "delegate" object. Many
* operations on this {@code array.array} are actually operations on this delegate (an
* {@code AbstractArray} in practice), which in turn manipulates {@link #data}.
*/
private ArrayDelegate delegate;
/**
* Create a default {@code PyArray} of specific Python type (for sub-class use).
*
* @param subtype actual Python type
*/
public PyArray(PyType subtype) {
super(subtype);
}
/**
* Create a {@code PyArray} with the given array item type, specific item class and content.
*
* The primary specification is the {@link ItemType} parameter and if that is
* {@link ItemType#OBJECT} a specific Java class for the items.
*
* In a subtle twist, if {@code itemType =} {@link ItemType#OBJECT} but {@code itemClass} is one
* of the types used to implement the "single letter" type codes, the item type of the array
* will be the first signed type represented by that class, not {@code OBJECT}. This is to
* preserve a legacy behaviour of the {@code PyArray} constructors.
*
* @param subtype actual Python type
* @param itemType of the elements
* @param itemClass when {@code itemType =} {@link ItemType#OBJECT}
* @param data content array
*/
PyArray(PyType subtype, ItemType itemType, Class<?> itemClass, Object data) {
this(subtype);
setElementType(itemType, itemClass);
setData(data);
}
/**
* Create a {@code PyArray} with the given array item type, specific item class and length, but
* zero content.
*
* Roughly equivalent to<pre>
* PyArray(itemType, itemClass, Array.newInstance(itemClass, n))
* </pre> But with {@code itemClass} for the new array deduced from {@code itemType} as
* explained in {@link PyArray#PyArray(ItemType, Class, Object)}.
*
* @param subtype actual Python type
* @param itemType of the elements
* @param itemClass when {@code itemType =} {@link ItemType#OBJECT}
* @param n length of content array to create
*/
PyArray(PyType subtype, ItemType itemType, Class<?> itemClass, int n) {
this(subtype);
setElementType(itemType, itemClass);
setData(Array.newInstance(this.itemClass, n));
}
/**
* Create a {@code PyArray} with the given array item class and content initialised from a
* Python object (like an iterable).
*
* @param subtype actual Python type
* @param itemType of the elements
* @param itemClass when {@code itemType =} {@link ItemType#OBJECT}
* @param initial provider of initial contents
*/
PyArray(PyType subtype, ItemType itemType, Class<?> itemClass, PyObject initial) {
this(subtype, itemType, itemClass, 0);
useInitial(initial);
}
/**
* Create a {@code PyArray} with the given array item class and content. If {@code itemClass} is
* one of the primitive types used to implement the "single letter" type codes, the type code of
* the array will be a signed zero of that item class.
*
* @param itemClass of elements in the array
* @param data content array
*/
public PyArray(Class<?> itemClass, Object data) {
this(TYPE, ItemType.OBJECT, itemClass, data);
}
/**
* Create a {@code PyArray} with the given array item class and content initialised from a
* Python object (iterable).
*
* @param itemClass of elements in the array
* @param initial provider of initial contents
*/
public PyArray(Class<?> itemClass, PyObject initial) {
this(TYPE, ItemType.OBJECT, itemClass, initial);
}
/**
* Create a {@code PyArray} with the given array item class and number of zero or {@code null}
* elements. If {@code itemClass} is one of the primitive types used to implement the "single
* letter" type codes, the type code of the array will be a signed zero of that item class.
*
* @param itemClass of elements in the array
* @param n number of (zero or {@code null}) elements
*/
public PyArray(Class<?> itemClass, int n) {
this(TYPE, ItemType.OBJECT, itemClass, Array.newInstance(itemClass, n));
}
/**
* Create a {@code PyArray} as a copy of another.
*
* @param toCopy the other array
*/
public PyArray(PyArray toCopy) {
this(TYPE, toCopy.itemType, toCopy.itemClass, toCopy.delegate.copyArray());
}
/**
* Initialise this array from an {@link ItemType} (from a Python {@code array.array} type code
* character) and if that is {@link ItemType#OBJECT} a specific Java class for the items.
* <p>
* If {@code itemType =} {@link ItemType#OBJECT} but {@code itemClass} is one of the types used
* to implement the "single letter" type codes, the item type of the array will be the first
* signed type represented by that class, not {@code OBJECT}. This is to preserve a legacy
* behaviour of the {@code PyArray} constructors.
* <p>
* The way {@link #array_new(PyNewWrapper, boolean, PyType, PyObject[], String[]) array_new}
* works, and the constructors, is to create an instance with the almost parameterless
* {@link #PyArray(PyType)} with sub-type argument.
* <p>
* This blank canvas needs to be inscribed with a consistent state by a call to this method and
* either {@link #setData(Object) setData} or {@link #useInitial(PyObject) useInitial}.
*
* @param itemType of the elements
* @param itemClass when {@code itemType =} {@link ItemType#OBJECT}
*/
private void setElementType(ItemType itemType, Class<?> itemClass) {
if (itemType == ItemType.OBJECT) {
/*
* If itemClass is one of the types used to implement the "single letter" type codes,
* the item type of the array will be the first signed type represented by that class,
* not OBJECT. This is to preserve a legacy behaviour of the PyArray constructors.
*/
this.itemClass = itemClass;
this.itemType = ItemType.fromJavaClass(itemClass);
} else {
// itemType tells the whole story
this.itemType = itemType;
this.itemClass = itemType.itemClass;
}
}
/**
* Make a given object the storage for the array. Normally this is a Java array of type
* consistent with the element type. It will be manipulated by {@link #delegate}.
*
* @param data the storage (or {@code null} to to create at zero length consistent with type).
*/
private void setData(Object data) {
this.data = data != null ? data : Array.newInstance(itemClass, 0);
this.delegate = new ArrayDelegate();
}
/**
* Provide initial values to the internal storage array from one of several types in the broad
* categories of a byte string (which is treated as a machine representation of the data) or an
* iterable yielding values assignable to the elements. There is special treatment for typecode
* 'u', itemClass Unicode.
*
* @param initial source of values or {@code null}
*/
private void useInitial(PyObject initial) {
// If we do not yet have a representation array, provide one
if (this.data == null || this.delegate == null) {
setData(Array.newInstance(this.itemClass, 0));
}
// The initialiser may be omitted, or may validly be one of several types.
if (initial == null) {
// Fall through
} else if (initial instanceof PyList) {
fromlist(initial);
} else if (initial instanceof PyString && !(initial instanceof PyUnicode)) {
fromstring(initial.toString());
} else if (itemType == ItemType.UNICHAR) {
if (initial instanceof PyUnicode) {
extendArray((PyUnicode) initial);
} else {
extendUnicodeIter(initial);
}
} else {
extendInternal(initial);
}
}
@ExposedNew
static final PyObject array_new(PyNewWrapper new_, boolean init, PyType subtype,
PyObject[] args, String[] keywords) {
if (new_.for_type != subtype && keywords.length > 0) {
/*
* We're constructing as a base for a derived type (via PyDerived) and there are
* keywords. The effective args locally should not include the keywords.
*/
int argc = args.length - keywords.length;
PyObject[] justArgs = new PyObject[argc];
System.arraycopy(args, 0, justArgs, 0, argc);
args = justArgs;
}
// Create a 'blank canvas' of the appropriate concrete class.
PyArray self =
new_.for_type == subtype ? new PyArray(subtype) : new PyArrayDerived(subtype);
// Build the argument parser for this call
ArgParser ap = new ArgParser("array", args, Py.NoKeywords,
new String[] {"typecode", "initializer"}, 1);
ap.noKeywords();
// Retrieve the mandatory type code that determines the element itemClass
PyObject obj = ap.getPyObject(0);
if (obj instanceof PyString && !(obj instanceof PyUnicode)) {
if (obj.__len__() != 1) {
throw Py.TypeError("array() argument 1 must be char, not str");
}
char typecode = obj.toString().charAt(0);
self.setElementType(ItemType.fromTypecode(typecode), null);
} else if (obj instanceof PyJavaType) {
Class<?> itemClass = ((PyJavaType) obj).getProxyType();
self.setElementType(ItemType.OBJECT, itemClass);
} else {
throw Py.TypeError(
"array() argument 1 must be char, not " + obj.getType().fastGetName());
}
// Fill the array from the second argument (if there is one)
self.useInitial(ap.getPyObject(1, null));
return self;
}
/**
* Create a {@code PyArray} with the given array type code and number of zero elements.
*
* @param typecode of elements in the array
* @param n number of (zero or {@code null}) elements
* @return created array
*/
public static PyArray zeros(int n, char typecode) {
return new PyArray(TYPE, ItemType.fromTypecode(typecode), null, n);
}
/**
* Create a {@code PyArray} with the given array item class and number of zero or {@code null}
* elements. If {@code itemClass} is one of the primitive types used to implement the "single
* letter" type codes, the type code of the array will be a signed zero of that item class.
*
* @param itemClass
* @param n number of (zero or {@code null}) elements
* @return created array
*/
public static PyArray zeros(int n, Class<?> itemClass) {
return new PyArray(TYPE, ItemType.OBJECT, itemClass, n);
}
/**
* Create a {@code PyArray} with the given array item type and content initialised from a Python
* object (iterable).
*
* @param seq to suply content
* @param typecode
* @return created array
*/
public static PyArray array(PyObject seq, char typecode) {
return new PyArray(TYPE, ItemType.fromTypecode(typecode), null, seq);
}
public static Class<?> array_class(Class<?> type) {
return Array.newInstance(type, 0).getClass();
}
/**
* Create a {@code PyArray} storing {@code ctype} types and being initialised with {@code init}.
*
* @param init an initialiser for the array - can be {@code PyString} or {@code PySequence}
* (including {@code PyArray}) or iterable type.
* @param itemClass {@code Class} of the elements stored in the array.
* @return a new PyArray
*/
public static PyArray array(PyObject init, Class<?> itemClass) {
return new PyArray(TYPE, ItemType.OBJECT, itemClass, init);
}
@ExposedMethod(type = MethodType.BINARY)
final PyObject array___ne__(PyObject o) {
return seq___ne__(o);
}
@ExposedMethod(type = MethodType.BINARY)
final PyObject array___eq__(PyObject o) {
return seq___eq__(o);
}
@Override
public int hashCode() {
return array___hash__();
}
@ExposedMethod
final int array___hash__() {
throw Py.TypeError(String.format("unhashable type: '%.200s'", getType().fastGetName()));
}
@ExposedMethod(type = MethodType.BINARY)
final PyObject array___lt__(PyObject o) {
return seq___lt__(o);
}
@ExposedMethod(type = MethodType.BINARY)
final PyObject array___le__(PyObject o) {
return seq___le__(o);
}
@ExposedMethod(type = MethodType.BINARY)
final PyObject array___gt__(PyObject o) {
return seq___gt__(o);
}
@ExposedMethod(type = MethodType.BINARY)
final PyObject array___ge__(PyObject o) {
return seq___ge__(o);
}
@ExposedMethod
final boolean array___contains__(PyObject o) {
return object___contains__(o);
}
@ExposedMethod
final void array___delitem__(PyObject index) {
seq___delitem__(index);
}
@ExposedMethod
final void array___setitem__(PyObject o, PyObject def) {
seq___setitem__(o, def);
}
@ExposedMethod
final PyObject array___getitem__(PyObject o) {
PyObject ret = seq___finditem__(o);
if (ret == null) {
throw Py.IndexError("index out of range: " + o);
}
return ret;
}
@ExposedMethod
final boolean array___nonzero__() {
return seq___nonzero__();
}
@ExposedMethod
public PyObject array___iter__() {
return seq___iter__();
}
@ExposedMethod(defaults = "null")
final PyObject array___getslice__(PyObject start, PyObject stop, PyObject step) {
return seq___getslice__(start, stop, step);
}
@ExposedMethod(defaults = "null")
final void array___setslice__(PyObject start, PyObject stop, PyObject step, PyObject value) {
seq___setslice__(start, stop, step, value);
}
@ExposedMethod(defaults = "null")
final void array___delslice__(PyObject start, PyObject stop, PyObject step) {
seq___delslice__(start, stop, step);
}
@Override
public PyObject __imul__(PyObject o) {
return array___imul__(o);
}
@ExposedMethod(type = MethodType.BINARY)
final PyObject array___imul__(PyObject o) {
if (!o.isIndex()) {
return null;
}
resizeCheck(); // Prohibited if exporting a buffer
if (delegate.getSize() > 0) {
int count = o.asIndex(Py.OverflowError);
if (count <= 0) {
delegate.clear();
return this;
}
Object copy = delegate.copyArray();
delegate.ensureCapacity(delegate.getSize() * count);
for (int i = 1; i < count; i++) {
delegate.appendArray(copy);
}
}
return this;
}
@Override
public PyObject __mul__(PyObject o) {
return array___mul__(o);
}
@ExposedMethod(type = MethodType.BINARY)
final PyObject array___mul__(PyObject o) {
if (!o.isIndex()) {
return null;
}
return repeat(o.asIndex(Py.OverflowError));
}
@Override
public PyObject __rmul__(PyObject o) {
return array___rmul__(o);
}
@ExposedMethod(type = MethodType.BINARY)
final PyObject array___rmul__(PyObject o) {
if (!o.isIndex()) {
return null;
}
return repeat(o.asIndex(Py.OverflowError));
}
@Override
public PyObject __iadd__(PyObject other) {
return array___iadd__(other);
}
@ExposedMethod(type = MethodType.BINARY)
final PyObject array___iadd__(PyObject other) {
try {
PyArray otherArr = arrayChecked(other);
resizeCheck(); // Prohibited if exporting a buffer
delegate.appendArray(otherArr.delegate.copyArray());
return this;
} catch (ClassCastException e) {
// other wasn't a PyArray
return null;
}
}
@Override
public PyObject __add__(PyObject other) {
return array___add__(other);
}
/**
* Adds (appends) two PyArrays together
*
* @param other a {@code PyArray} to be added to the instance
* @return the result of the addition as a new {@code PyArray} instance
*/
@ExposedMethod(type = MethodType.BINARY)
final PyObject array___add__(PyObject other) {
try {
PyArray otherArr = arrayChecked(other);
PyArray ret = new PyArray(this);
ret.delegate.appendArray(otherArr.delegate.copyArray());
return ret;
} catch (ClassCastException e) {
// other wasn't a PyArray
return null;
}
}
/**
* Check the other array is an array and is compatible for element type. Raise {@code TypeError}
* if not.
*
* @param otherObject supposed {@code PyArray}
* @return {@code other}
* @throws ClassCastException if {@code other} not {@code PyArray}
*/
private PyArray arrayChecked(PyObject otherObject) throws ClassCastException {
PyArray other = (PyArray) otherObject;
if (itemType == other.itemType) {
if (itemType != ItemType.OBJECT) {
return other;
} else if (itemClass.isAssignableFrom(other.itemClass)) {
return other;
}
}
throw Py.TypeError(String.format("bad argument types for built-in operation: (%s, %s)",
reprTypecode(), other.reprTypecode()));
}
/**
* Length of the array (as the number of elements, not a storage size).
*
* @return number of elements in the array
*/
@Override
public int __len__() {
return array___len__();
}
@ExposedMethod
final int array___len__() {
return delegate.getSize();
}
@Override
public PyObject __reduce__() {
return array___reduce__();
}
@ExposedMethod
final PyObject array___reduce__() {
PyObject dict = __findattr__("__dict__");
if (dict == null) {
dict = Py.None;
}
PyString typecode = Py.newString(getTypecode());
if (__len__() > 0) {
return new PyTuple(getType(), new PyTuple(typecode, Py.newString(tostring())), dict);
} else {
return new PyTuple(getType(), new PyTuple(typecode), dict);
}
}
@Override
public String toString() {
if (__len__() == 0) {
return String.format("array(%s)", reprTypecode());
}
String value;
switch (itemType) {
case CHAR:
value = PyString.encode_UnicodeEscape(tostring(), true);
break;
case UNICHAR:
value = (new PyUnicode(tounicode())).__repr__().toString();
break;
default:
value = tolist().toString();
}
return String.format("array(%s, %s)", reprTypecode(), value);
}
private String reprTypecode() {
if (itemType == ItemType.OBJECT) {
return getTypecode();
} else {
return "'" + getTypecode() + "'";
}
}
/**
*
* @param c target {@code Class} for the conversion
* @return Java object converted to required class type if possible.
*/
@Override
public Object __tojava__(Class<?> c) {
boolean isArray = c.isArray();
Class<?> componentType = c.getComponentType();
if (c == Object.class || (isArray && componentType.isAssignableFrom(itemClass))) {
if (delegate.capacity != delegate.size) {
// when unboxing, shrink the array first, otherwise incorrect results to Java
return delegate.copyArray();
} else {
return data;
}
}
// rebox: this array is made of primitives but converting to Object[]
if (isArray && componentType == Object.class) {
Object[] boxed = new Object[delegate.size];
for (int i = 0; i < delegate.size; i++) {
boxed[i] = Array.get(data, i);
}
return boxed;
}
if (c.isInstance(this)) {
return this;
}
return Py.NoConversion;
}
@ExposedMethod
public final void array_append(PyObject value) {
resizeCheck(); // Prohibited if exporting a buffer
appendUnchecked(value);
}
/**
* Append new value x to the end of the array.
*
* @param value item to be appended to the array
*/
public void append(PyObject value) {
resizeCheck(); // Prohibited if exporting a buffer
appendUnchecked(value);
}
/**
* Common helper method used internally to append a new value x to the end of the array:
* {@link #resizeCheck()} is not called, so the client must do so in advance.
*
* @param value item to be appended to the array
*/
private final void appendUnchecked(PyObject value) {
int afterLast = delegate.getSize();
delegate.makeInsertSpace(afterLast);
try {
pyset(afterLast, value);
} catch (PyException e) {
delegate.setSize(afterLast);
throw new PyException(e.type, e.value);
}
}
@ExposedMethod
public void array_byteswap() {
byteswap();
}
/**
* "Byteswap" all items of the array. This is only supported for values which are 1, 2, 4, or 8
* bytes in size; for other types of values, {@code RuntimeError} is raised. It is useful when
* reading data from a file written on a machine with a different byte order.
*/
public void byteswap() {
if (itemType == ItemType.OBJECT) {
throw Py.RuntimeError("don't know how to byteswap this array type");
}
ByteSwapper.swap(data);
}
/**
* Implementation of {@code Cloneable} interface.
*
* @return copy of current PyArray
*/
@Override
public Object clone() {
return new PyArray(this);
}
/**
* Converts a character code for the array type to the Java {@code Class} of the elements of the
* implementation array.
*
* @param typecode character code for the array type
* @return {@code Class} of the native itemClass
*/
public static Class<?> char2class(char typecode) throws PyIgnoreMethodTag {
return ItemType.fromTypecode(typecode).itemClass;
}
@ExposedMethod
public final int array_count(PyObject value) {
// note: cpython does not raise type errors based on item type;
int iCount = 0;
int len = delegate.getSize();
for (int i = 0; i < len; i++) {
if (value.equals(itemType.get(this, i))) {
iCount++;
}
}
return iCount;
}
/**
* Return the number of occurrences of x in the array.
*
* @param value instances of the value to be counted
* @return number of time value was found in the array.
*/
public PyInteger count(PyObject value) {
return Py.newInteger(array_count(value));
}
/**
* Delete the element at position {@code i} from the array
*
* @param i index of the item to be deleted from the array
*/
@Override
protected void del(int i) {
resizeCheck(); // Prohibited if exporting a buffer
delegate.remove(i);
}
/**
* Delete the slice defined by {@code start} to {@code stop} from the array.
*
* @param start starting index of slice
* @param stop finishing index of slice
*/
@Override
protected void delRange(int start, int stop) {
resizeCheck(); // Prohibited if exporting a buffer
delegate.remove(start, stop);
}
@ExposedMethod
public final void array_extend(PyObject iterable) {
extendInternal(iterable);
}
/**
* Append items from {@code iterable} to the end of the array. If iterable is another array, it
* must have exactly the same type code; if not, TypeError will be raised. If iterable is not an
* array, it must be iterable and its elements must be the right type to be appended to the
* array.
*
* @param iterable iterable object used to extend the array
*/
public void extend(PyObject iterable) {
extendInternal(iterable);
}
/**
* Internal extend function, provides basic interface for extending arrays. Handles specific
* cases of {@code iterable} being PyStrings or PyArrays. Default behaviour is to defer to
* {@link #extendInternalIter(PyObject) extendInternalIter }
*
* @param iterable object of type PyString, PyArray or any object that can be iterated over.
*/
private void extendInternal(PyObject iterable) {
if (iterable instanceof PyUnicode) {
if (itemType == ItemType.UNICHAR) {
extendUnicodeIter(iterable);
} else if (itemType == ItemType.CHAR) {
throw Py.TypeError("array item must be char");
} else {
throw Py.TypeError("an integer is required");
}
} else if (iterable instanceof PyArray) {
PyArray source = (PyArray) iterable;
if (source.itemType == itemType) {
resizeCheck(); // Prohibited if exporting a buffer
delegate.appendArray(source.delegate.copyArray());
} else {
throw Py.TypeError("can only extend with array of same kind");
}
} else {
extendInternalIter(iterable);
}
}
/**
* Internal extend function to process iterable objects.
*
* @param iterable any object that can be iterated over.
*/
private void extendInternalIter(PyObject iterable) {
// Prohibited operation if exporting a buffer
resizeCheck();
if (iterable.__findattr__("__len__") != null) {
// Make room according to source length
int last = delegate.getSize();
delegate.ensureCapacity(last + iterable.__len__());
for (PyObject item : iterable.asIterable()) {
pyset(last++, item);
delegate.size++;
}
} else {
// iterable has no length property: cannot size the array so append each item.
for (PyObject item : iterable.asIterable()) {
appendUnchecked(item); // we already did a resizeCheck
}
}
}
/**
* Helper used only when the array elements are Unicode characters (<code>typecode=='u'</code>).
* (Characters are stored as integer point codes.) The parameter must be an iterable yielding
* {@link PyUnicode}s. Often this will be an instance of {@link PyUnicode}, which is an iterable
* yielding single-character {@code PyUnicode}s. But it is also acceptable to this method for
* the argument to yield arbitrary {@code PyUnicode}s, which will be concatenated in the array.
*
* @param iterable of {@link PyUnicode}s
*/
private void extendUnicodeIter(PyObject iterable) {
// Prohibited operation if exporting a buffer
resizeCheck();
try {
// Append all the code points of all the strings in the iterable
for (PyObject item : iterable.asIterable()) {
PyUnicode uitem = (PyUnicode) item;
// Append all the code points of this item
for (int codepoint : uitem.toCodePoints()) {
int afterLast = delegate.getSize();
delegate.makeInsertSpace(afterLast);
Array.setInt(data, afterLast, codepoint);
}
}
} catch (ClassCastException e) {
// One of the PyUnicodes wasn't
throw notCompatibleTypeError();
}
}
private void extendArray(PyUnicode codepoints) {
// Prohibited operation if exporting a buffer
resizeCheck();
int last = delegate.getSize();
int[] items = codepoints.toCodePoints();
delegate.ensureCapacity(last + items.length);
for (int item : items) {
Array.setInt(data, last++, item);
delegate.size++;
}
}
@ExposedMethod
public final void array_fromfile(PyObject f, int count) {
fromfile(f, count);
}