-
Notifications
You must be signed in to change notification settings - Fork 61
Expand file tree
/
Copy pathPyByteArray.java
More file actions
2669 lines (2384 loc) · 104 KB
/
PyByteArray.java
File metadata and controls
2669 lines (2384 loc) · 104 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
package org.python.core;
import java.lang.ref.WeakReference;
import java.util.Arrays;
import org.python.core.buffer.BaseBuffer;
import org.python.core.buffer.SimpleWritableBuffer;
import org.python.core.util.Allocator;
import org.python.expose.ExposedClassMethod;
import org.python.expose.ExposedMethod;
import org.python.expose.ExposedNew;
import org.python.expose.ExposedType;
import org.python.expose.MethodType;
/**
* Implementation of Python <code>bytearray</code> with a Java API that includes equivalents to most
* of the Python API. These Python equivalents accept a {@link PyObject} as argument, where you
* might have expected a <code>byte[]</code> or <code>PyByteArray</code>, in order to accommodate
* the full range of types accepted by the Python equivalent: usually, any <code>PyObject</code>
* that implements {@link BufferProtocol}, providing a one-dimensional array of bytes, is an
* acceptable argument. In the documentation, the reader will often see the terms "byte array" or
* "object viewable as bytes" instead of <code>bytearray</code> when this broader scope is intended.
* This may relate to parameters, or to the target object itself (in text that applies equally to
* base or sibling classes).
*/
@Untraversable
@ExposedType(name = "bytearray", base = PyObject.class, doc = BuiltinDocs.bytearray_doc)
public class PyByteArray extends BaseBytes implements BufferProtocol {
/** The {@link PyType} of <code>bytearray</code>. */
public static final PyType TYPE = PyType.fromClass(PyByteArray.class);
/**
* Constructs a zero-length Python <code>bytearray</code> of explicitly-specified sub-type
*
* @param type explicit Jython type
*/
public PyByteArray(PyType type) {
super(type);
}
/**
* Constructs a zero-length Python <code>bytearray</code>.
*/
public PyByteArray() {
super(TYPE);
}
/**
* Constructs zero-filled Python <code>bytearray</code> of specified size.
*
* @param size of <code>bytearray</code>
*/
public PyByteArray(int size) {
super(TYPE);
init(size);
}
/**
* Constructs a <code>bytearray</code> by copying values from int[].
*
* @param value source of the bytes (and size)
*/
public PyByteArray(int[] value) {
super(TYPE, value);
}
/**
* Constructs a new array filled exactly by a copy of the contents of the source, which is a
* <code>bytearray</code> (or <code>bytes</code>).
*
* @param value source of the bytes (and size)
*/
public PyByteArray(BaseBytes value) {
super(TYPE);
init(value);
}
/**
* Constructs a new array filled exactly by a copy of the contents of the source, which is a
* byte-oriented {@link PyBuffer}.
*
* @param value source of the bytes (and size)
*/
PyByteArray(PyBuffer value) {
super(TYPE);
init(value);
}
/**
* Constructs a new array filled exactly by a copy of the contents of the source, which is an
* object supporting the Jython version of the PEP 3118 buffer API.
*
* @param value source of the bytes (and size)
*/
public PyByteArray(BufferProtocol value) {
super(TYPE);
init(value);
}
/**
* Constructs a new array filled from an iterable of PyObject. The iterable must yield objects
* convertible to Python bytes (non-negative integers less than 256 or strings of length 1).
*
* @param value source of the bytes (and size)
*/
public PyByteArray(Iterable<? extends PyObject> value) {
super(TYPE);
init(value);
}
/**
* Constructs a new array by encoding a PyString argument to bytes. If the PyString is actually
* a PyUnicode, the encoding must be explicitly specified.
*
* @param arg primary argument from which value is taken
* @param encoding name of optional encoding (must be a string type)
* @param errors name of optional errors policy (must be a string type)
*/
public PyByteArray(PyString arg, PyObject encoding, PyObject errors) {
super(TYPE);
init(arg, encoding, errors);
}
/**
* Constructs a new array by encoding a PyString argument to bytes. If the PyString is actually
* a PyUnicode, the encoding must be explicitly specified.
*
* @param arg primary argument from which value is taken
* @param encoding name of optional encoding (may be <code>null</code> to select the default for
* this installation)
* @param errors name of optional errors policy
*/
public PyByteArray(PyString arg, String encoding, String errors) {
super(TYPE);
init(arg, encoding, errors);
}
/**
* Constructs a new array by encoding a PyString argument to bytes. If the PyString is actually
* a PyUnicode, an exception is thrown saying that the encoding must be explicitly specified.
*
* @param arg primary argument from which value is taken
*/
public PyByteArray(PyString arg) {
super(TYPE);
init(arg, (String)null, (String)null);
}
/**
* Constructs a <code>bytearray</code> by re-using an array of byte as storage initialised by
* the client.
*
* @param storage pre-initialised with desired value: the caller should not keep a reference
*/
public PyByteArray(byte[] storage) {
super(TYPE);
setStorage(storage);
}
/**
* Constructs a <code>bytearray</code> by re-using an array of byte as storage initialised by
* the client.
*
* @param storage pre-initialised with desired value: the caller should not keep a reference
* @param size number of bytes actually used
* @throws IllegalArgumentException if the range [0:size] is not within the array bounds of the
* storage.
*/
public PyByteArray(byte[] storage, int size) {
super(TYPE);
setStorage(storage, size);
}
/**
* Constructs a new <code>bytearray</code> object from an arbitrary Python object according to
* the same rules as apply in Python to the <code>bytearray()</code> constructor:
* <ul>
* <li><code>bytearray()</code> Construct a zero-length <code>bytearray</code>.</li>
* <li><code>bytearray(int)</code> Construct a zero-initialized <code>bytearray</code> of the
* given length.</li>
* <li><code>bytearray(iterable_of_ints)</code> Construct from iterable yielding integers in
* [0..255]</li>
* <li><code>bytearray(buffer)</code> Construct by reading from any object implementing
* {@link BufferProtocol}, including <code>str/bytes</code> or another <code>bytearray</code>.</li>
* </ul>
* When it is necessary to specify an encoding, as in the Python signature
* <code>bytearray(string, encoding [, errors])</code>, use the constructor
* {@link #PyByteArray(PyString, String, String)}. If the <code>PyString</code> is actually a
* <code>PyUnicode</code>, an encoding must be specified, and using this constructor will throw
* an exception about that.
*
* @param arg primary argument from which value is taken (may be <code>null</code>)
* @throws PyException (TypeError) for non-iterable,
* @throws PyException (ValueError) if iterables do not yield byte [0..255] values.
*/
public PyByteArray(PyObject arg) throws PyException {
super(TYPE);
init(arg);
}
/*
* ============================================================================================
* Support for the Buffer API
* ============================================================================================
*
* The buffer API allows other classes to access the storage directly.
*/
/**
* Hold weakly a reference to a PyBuffer export not yet released, used to prevent untimely
* resizing.
*/
private WeakReference<BaseBuffer> export;
/**
* {@inheritDoc}
* <p>
* The {@link PyBuffer} returned from this method is a one-dimensional array of single byte
* items that allows modification of the object state. The existence of this export <b>prohibits
* resizing</b> the byte array. This prohibition is not only on the consumer of the view but
* extends to any other operations, such as any kind or insertion or deletion.
*/
@Override
public synchronized PyBuffer getBuffer(int flags) {
// If we have already exported a buffer it may still be available for re-use
BaseBuffer pybuf = getExistingBuffer(flags);
if (pybuf == null) {
// No existing export we can re-use: create a new one
pybuf = new SimpleWritableBuffer(flags, storage, offset, size);
// Hold a reference for possible re-use
export = new WeakReference<BaseBuffer>(pybuf);
}
return pybuf;
}
/**
* Try to re-use an existing exported buffer, or return <code>null</code> if we can't.
*
* @throws PyException (BufferError) if the the flags are incompatible with the buffer
*/
private BaseBuffer getExistingBuffer(int flags) throws PyException {
BaseBuffer pybuf = null;
if (export != null) {
// A buffer was exported at some time.
pybuf = export.get();
if (pybuf != null) {
/*
* We do not test for pybuf.isReleased() as, if any operation had taken place that
* invalidated the buffer, resizeCheck() would have set export=null. The exported
* buffer (navigation, buf member, etc.) remains valid through any operation that
* does not need a resizeCheck.
*/
pybuf = pybuf.getBufferAgain(flags);
}
}
return pybuf;
}
/**
* Test to see if the byte array may be resized and raise a BufferError if not. This must be
* called by the implementation of any append or insert that changes the number of bytes in the
* array.
*
* @throws PyException (BufferError) if there are buffer exports preventing a resize
*/
protected void resizeCheck() throws PyException {
if (export != null) {
// A buffer was exported at some time and we have not explicitly discarded it.
PyBuffer pybuf = export.get();
if (pybuf != null && !pybuf.isReleased()) {
// A consumer still has the exported buffer
throw Py.BufferError("Existing exports of data: object cannot be re-sized");
} else {
/*
* Either the reference has expired or all consumers have released it. Either way,
* the weak reference is useless now.
*/
export = null;
}
}
}
/*
* ============================================================================================
* API for org.python.core.PySequence
* ============================================================================================
*/
/**
* Returns a slice of elements from this sequence as a <code>PyByteArray</code>.
*
* @param start the position of the first element.
* @param stop one more than the position of the last element.
* @param step the step size.
* @return a <code>PyByteArray</code> corresponding the the given range of elements.
*/
@Override
protected synchronized PyByteArray getslice(int start, int stop, int step) {
if (step == 1) {
// Efficiently copy contiguous slice
return this.getslice(start, stop);
} else {
int n = sliceLength(start, stop, step);
PyByteArray ret = new PyByteArray(n);
n += ret.offset;
byte[] dst = ret.storage;
for (int io = start + offset, jo = ret.offset; jo < n; io += step, jo++) {
dst[jo] = storage[io];
}
return ret;
}
}
/**
* Specialisation of {@link #getslice(int, int, int)} to contiguous slices (of step size 1) for
* brevity and efficiency.
*/
@Override
protected synchronized PyByteArray getslice(int start, int stop) {
// If this were immutable, start==0 and end==size we would return (this).
// Efficiently copy contiguous slice
int n = stop - start;
if (n <= 0) {
return new PyByteArray();
} else {
PyByteArray ret = new PyByteArray(n);
System.arraycopy(storage, offset + start, ret.storage, ret.offset, n);
return ret;
}
}
/**
* Returns a <code>PyByteArray</code> that repeats this sequence the given number of times, as
* in the implementation of <tt>__mul__</tt> for strings.
*
* @param count the number of times to repeat this.
* @return this byte array repeated count times.
*/
@Override
protected synchronized PyByteArray repeat(int count) {
PyByteArray ret = new PyByteArray();
ret.setStorage(repeatImpl(count));
return ret;
}
/**
* Replace the contents of this <code>PyByteArray</code> with the given number of repeats of the
* original contents, as in the implementation of <tt>__mul__</tt> for strings.
*
* @param count the number of times to repeat this.
*/
protected synchronized void irepeat(int count) {
// There are several special cases
if (size == 0 || count == 1) {
// No resize, so no check (consistent with CPython)
// Value is unchanged.
} else if (count <= 0) {
// Treat as if count == 0.
resizeCheck();
this.setStorage(emptyStorage);
} else {
// Open up space (remembering the original size)
int orginalSize = size;
storageExtend(orginalSize * (count - 1));
if (orginalSize == 1) {
// Do it efficiently for single bytes
byte b = storage[offset];
for (int i = 1, p = offset + 1; i < count; i++) {
storage[p++] = b;
}
} else {
// General case
for (int i = 1, p = offset + orginalSize; i < count; i++, p += orginalSize) {
System.arraycopy(storage, offset, storage, p, orginalSize);
}
}
}
}
/**
* Sets the indexed element of the <code>bytearray</code> to the given value. This is an
* extension point called by PySequence in its implementation of {@link #__setitem__} It is
* guaranteed by PySequence that the index is within the bounds of the array. Any other clients
* calling <code>pyset(int)</code> must make the same guarantee.
*
* @param index index of the element to set.
* @param value the value to set this element to.
* @throws PyException (AttributeError) if value cannot be converted to an integer
* @throws PyException (ValueError) if value<0 or value>255
*/
@Override
public synchronized void pyset(int index, PyObject value) throws PyException {
storage[index + offset] = byteCheck(value);
}
/**
* Insert the element (interpreted as a Python byte value) at the given index. Python
* <code>int</code>, <code>long</code> and <code>str</code> types of length 1 are allowed.
*
* @param index to insert at
* @param element to insert (by value)
* @throws PyException (IndexError) if the index is outside the array bounds
* @throws PyException (ValueError) if element<0 or element>255
* @throws PyException (TypeError) if the subclass is immutable
*/
@Override
public synchronized void pyinsert(int index, PyObject element) {
// Open a space at the right location.
storageReplace(index, 0, 1);
storage[offset + index] = byteCheck(element);
}
/**
* Sets the given range of elements according to Python slice assignment semantics. If the step
* size is one, it is a simple slice and the operation is equivalent to deleting that slice,
* then inserting the value at that position, regarding the value as a sequence (if possible) or
* as a single element if it is not a sequence. If the step size is not one, but start=stop, it
* is equivalent to insertion at that point. If the step size is not one, and start!=stop, the
* slice defines a certain number of elements to be replaced, and the value must be a sequence
* of exactly that many elements (or convertible to such a sequence).
* <p>
* When assigning from a sequence type or iterator, the sequence may contain arbitrary
* {@link PyObject}s, but acceptable ones are {@link PyInteger}, {@link PyLong} or
* {@link PyString} of length 1. If any one of them proves unsuitable for assignment to a Python
* <code>bytearray</code> element, an exception is thrown and this <code>bytearray</code> is
* unchanged.
*
* <pre>
* a = bytearray(b'abcdefghijklmnopqrst')
* a[2:12:2] = iter( [65, 66, 67, long(68), "E"] )
* </pre>
*
* Results in <code>a=bytearray(b'abAdBfChDjElmnopqrst')</code>.
* <p>
*
* @param start the position of the first element.
* @param stop one more than the position of the last element.
* @param step the step size.
* @param value an object consistent with the slice assignment
*/
@Override
protected synchronized void setslice(int start, int stop, int step, PyObject value) {
if (step == 1 && stop < start) {
// Because "b[5:2] = v" means insert v just before 5 not 2.
// ... although "b[5:2:-1] = v means b[5]=v[0], b[4]=v[1], b[3]=v[2]
stop = start;
}
/*
* The actual behaviour depends on the nature (type) of value. It may be any kind of
* PyObject (but not other kinds of Java Object). The function is implementing assignment to
* a slice. PEP 3137 declares that the value may be "any type that implements the PEP 3118
* buffer interface".
*
* The following is essentially equivalent to b[start:stop[:step]]=bytearray(value) except
* we avoid constructing a copy of value if we can easily do so. The logic is the same as
* BaseBytes.init(PyObject), without support for value==null.
*/
if (value instanceof PyString) {
/*
* Value is a string (but must be 8-bit).
*/
setslice(start, stop, step, (PyString)value);
} else if (value.isIndex()) {
/*
* Value behaves as a zero-initialised bytearray of the given length.
*/
setslice(start, stop, step, value.asIndex(Py.OverflowError));
} else if (value instanceof BaseBytes) {
/*
* Value behaves as a bytearray, and can be can be inserted without making a copy
* (unless it is this object).
*/
setslice(start, stop, step, (BaseBytes)value);
} else if (value instanceof BufferProtocol) {
/*
* Value supports Jython implementation of PEP 3118, and can be can be inserted without
* making a copy.
*/
setslice(start, stop, step, (BufferProtocol)value);
} else {
/*
* The remaining alternative is an iterable returning (hopefully) right-sized ints. If
* it isn't one, we get an exception about not being iterable, or about the values.
*/
setslice(start, stop, step, value.asIterable());
}
}
/**
* Sets the given range of elements according to Python slice assignment semantics from a
* zero-filled <code>bytearray</code> of the given length.
*
* @see #setslice(int, int, int, PyObject)
* @param start the position of the first element.
* @param stop one more than the position of the last element.
* @param step the step size.
* @param len number of zeros to insert consistent with the slice assignment
* @throws PyException (SliceSizeError) if the value size is inconsistent with an extended slice
*/
private void setslice(int start, int stop, int step, int len) throws PyException {
if (step == 1) {
// Delete this[start:stop] and open a space of the right size = len
storageReplace(start, stop - start, len);
Arrays.fill(storage, start + offset, (start + offset) + len, (byte)0);
} else {
// This is an extended slice which means we are replacing elements
int n = sliceLength(start, stop, step);
if (n != len) {
throw SliceSizeError("bytes", len, n);
}
for (int io = start + offset; n > 0; io += step, --n) {
storage[io] = 0;
}
}
}
/**
* Sets the given range of elements according to Python slice assignment semantics from a
* {@link PyString} that is not a {@link PyUnicode}.
*
* @see #setslice(int, int, int, PyObject)
* @param start the position of the first element.
* @param stop one more than the position of the last element.
* @param step the step size.
* @param value a PyString object consistent with the slice assignment
* @throws PyException (SliceSizeError) if the value size is inconsistent with an extended slice
* @throws PyException (ValueError) if the value is a <code>PyUnicode</code>
*/
private void setslice(int start, int stop, int step, PyString value) throws PyException {
if (value instanceof PyUnicode) {
// Has to be 8-bit PyString
throw Py.TypeError("can't set bytearray slice from unicode");
} else {
// Assignment is from 8-bit data
String v = value.asString();
int len = v.length();
if (step == 1) {
// Delete this[start:stop] and open a space of the right size
storageReplace(start, stop - start, len);
setBytes(start, v);
} else {
// This is an extended slice which means we are replacing elements
int n = sliceLength(start, stop, step);
if (n != len) {
throw SliceSizeError("bytes", len, n);
}
setBytes(start, step, v);
}
}
}
/**
* Sets the given range of elements according to Python slice assignment semantics from an
* object supporting the Jython implementation of PEP 3118.
*
* @see #setslice(int, int, int, PyObject)
* @param start the position of the first element.
* @param stop one more than the position of the last element.
* @param step the step size.
* @param value an object supporting the buffer API consistent with the slice assignment
* @throws PyException (SliceSizeError) if the value size is inconsistent with an extended slice
*/
private void setslice(int start, int stop, int step, BufferProtocol value) throws PyException {
try (PyBuffer view = value.getBuffer(PyBUF.FULL_RO)) {
int len = view.getLen();
if (step == 1) {
// Delete this[start:stop] and open a space of the right size
storageReplace(start, stop - start, len);
view.copyTo(storage, start + offset);
} else {
// This is an extended slice which means we are replacing elements
int n = sliceLength(start, stop, step);
if (n != len) {
throw SliceSizeError("bytes", len, n);
}
for (int io = start + offset, j = 0; j < n; io += step, j++) {
storage[io] = view.byteAt(j); // Assign this[i] = value[j]
}
}
}
}
/**
* Sets the given range of elements according to Python slice assignment semantics from a
* <code>bytearray</code> (or bytes).
*
* @see #setslice(int, int, int, PyObject)
* @param start the position of the first element.
* @param stop one more than the position of the last element.
* @param step the step size.
* @param value a <code>bytearray</code> (or bytes) object consistent with the slice assignment
* @throws PyException (SliceSizeError) if the value size is inconsistent with an extended slice
*/
private void setslice(int start, int stop, int step, BaseBytes value) throws PyException {
if (value == this) { // Must work with a copy
value = new PyByteArray(value);
}
int len = value.size;
if (step == 1) {
// Delete this[start:stop] and open a space of the right size
storageReplace(start, stop - start, len);
System.arraycopy(value.storage, value.offset, storage, start + offset, len);
} else {
// This is an extended slice which means we are replacing elements
int n = sliceLength(start, stop, step);
if (n != len) {
throw SliceSizeError("bytes", len, n);
}
int no = n + value.offset;
for (int io = start + offset, jo = value.offset; jo < no; io += step, jo++) {
storage[io] = value.storage[jo]; // Assign this[i] = value[j]
}
}
}
/**
* Sets the given range of elements according to Python slice assignment semantics from a
* <code>bytearray</code> (or bytes).
*
* @see #setslice(int, int, int, PyObject)
* @param start the position of the first element.
* @param stop one more than the position of the last element.
* @param step the step size.
* @param iter iterable source of values to enter in the array
* @throws PyException (SliceSizeError) if the iterable size is inconsistent with an extended
* slice
*/
private void setslice(int start, int stop, int step, Iterable<? extends PyObject> iter) {
/*
* As we don't know how many elements the iterable represents, we can't adjust the array
* until after we run the iterator. We use this elastic byte structure to hold the bytes
* until then.
*/
FragmentList fragList = new BaseBytes.FragmentList();
fragList.loadFrom(iter);
if (step == 1) {
// Delete this[start:stop] and open a space of the right size
storageReplace(start, stop - start, fragList.totalCount);
if (fragList.totalCount > 0) {
// Stitch the fragments together in the space we made
fragList.emptyInto(storage, start + offset);
}
} else {
// This is an extended slice which means we are replacing elements
int n = sliceLength(start, stop, step);
if (n != fragList.totalCount) {
throw SliceSizeError("bytes", fragList.totalCount, n);
}
fragList.emptyInto(storage, start + offset, step);
}
}
@Override
protected synchronized void del(int index) {
storageDelete(index, 1);
}
@Override
protected synchronized void delRange(int start, int stop) {
storageDelete(start, stop - start);
}
@Override
protected synchronized void delslice(int start, int stop, int step, int n) {
// This will not be possible if this object has buffer exports
resizeCheck();
if (step == 1) {
// Delete this[start:stop] and close up the space.
storageDelete(start, n);
} else if (step == -1) {
// Also a contiguous case, but start > stop.
storageDelete(stop + 1, n);
} else {
// This is an extended slice. We will be deleting n isolated elements.
int p, m;
// We delete by copying from high to low memory, whatever the sign of step.
if (step > 1) {
// The lowest numbered element to delete is x[start]
p = start;
m = step - 1;
} else {
// The lowest numbered element to delete is x[start+(n-1)*step]]
p = start + (n - 1) * step;
m = -1 - step;
}
// Offset p to be a storage index.
p += offset;
// Copy n-1 blocks blocks of m bytes, each time skipping the byte to be deleted.
for (int i = 1; i < n; i++) {
// Skip q over the one we are deleting
int q = p + i;
// Now copy the m elements that follow.
for (int j = 0; j < m; j++) {
storage[p++] = storage[q++];
}
}
// Close up the gap. Note that for the copy, p was adjusted by the storage offset.
storageDelete(p - offset, n);
}
}
/**
* Convenience method to build (but not throw) a <code>ValueError</code> PyException with the
* message "attempt to assign {type} of size {valueSize} to extended slice of size {sliceSize}"
*
* @param valueType
* @param valueSize size of sequence being assigned to slice
* @param sliceSize size of slice expected to receive
* @return PyException (ValueError) as detailed
*/
public static PyException SliceSizeError(String valueType, int valueSize, int sliceSize) {
String fmt = "attempt to assign %s of size %d to extended slice of size %d";
return Py.ValueError(String.format(fmt, valueType, valueSize, sliceSize));
// XXX consider moving to SequenceIndexDelegate.java or somewhere else generic, even Py
}
/**
* Initialise a mutable <code>bytearray</code> object from various arguments. This single
* initialisation must support:
* <ul>
* <li><code>bytearray()</code> Construct a zero-length <code>bytearray</code>.</li>
* <li><code>bytearray(int)</code> Construct a zero-initialized <code>bytearray</code> of the
* given length.</li>
* <li><code>bytearray(iterable_of_ints)</code> Construct from iterable yielding integers in
* [0..255]</li>
* <li><code>bytearray(buffer)</code> Construct by reading from any object implementing
* {@link BufferProtocol}, including <code>str/bytes</code> or another <code>bytearray</code>.</li>
* <li><code>bytearray(string, encoding [, errors])</code> Construct from a
* <code>str/bytes</code>, decoded using the system default encoding, and encoded to bytes using
* the specified encoding.</li>
* <li><code>bytearray(unicode, encoding [, errors])</code> Construct from a
* <code>unicode</code> string, encoded to bytes using the specified encoding.</li>
* </ul>
* Although effectively a constructor, it is possible to call <code>__init__</code> on a 'used'
* object so the method does not assume any particular prior state.
*
* @param args argument array according to Jython conventions
* @param kwds Keywords according to Jython conventions
* @throws PyException (TypeError) for non-iterable,
* @throws PyException (ValueError) if iterables do not yield byte [0..255] values.
*/
@ExposedNew
@ExposedMethod(doc = BuiltinDocs.bytearray___init___doc)
final synchronized void bytearray___init__(PyObject[] args, String[] kwds) {
ArgParser ap = new ArgParser("bytearray", args, kwds, "source", "encoding", "errors");
PyObject arg = ap.getPyObject(0, null);
// If not null, encoding and errors must be PyString (or PyUnicode)
PyObject encoding = ap.getPyObjectByType(1, PyBaseString.TYPE, null);
PyObject errors = ap.getPyObjectByType(2, PyBaseString.TYPE, null);
/*
* This method and the related init()s are modelled on CPython (see
* Objects/bytearrayobject.c : bytes_init()) but reorganised somewhat to maximise re-use
* with the implementation of assignment to a slice, which essentially has to construct a
* bytearray from the right-hand side. Hopefully, it still tries the same things in the same
* order and fails in the same way.
*/
if (encoding != null || errors != null) {
/*
* bytearray(string [, encoding [, errors]]) Construct from a text string by encoding it
* using the specified encoding.
*/
if (arg == null || !(arg instanceof PyString)) {
throw Py.TypeError("encoding or errors without sequence argument");
}
init((PyString)arg, encoding, errors);
} else {
// Now construct from arbitrary object (or null)
init(arg);
}
}
/*
* ============================================================================================
* Support for Builder
* ============================================================================================
*
* Extend BaseBytes.Builder so that it can return a PyByteArray and give the superclass a hook
* for it.
*/
@Override
protected Builder getBuilder(int capacity) {
// Return a Builder specialised for my class
return new Builder(capacity) {
@Override
PyByteArray getResult() {
// Create a PyByteArray from the storage that the builder holds
return new PyByteArray(getStorage(), getSize());
}
};
}
/*
* ============================================================================================
* Python API rich comparison operations
* ============================================================================================
*/
@Override
public PyObject __eq__(PyObject other) {
return basebytes___eq__(other);
}
@Override
public PyObject __ne__(PyObject other) {
return basebytes___ne__(other);
}
@Override
public PyObject __lt__(PyObject other) {
return basebytes___lt__(other);
}
@Override
public PyObject __le__(PyObject other) {
return basebytes___le__(other);
}
@Override
public PyObject __ge__(PyObject other) {
return basebytes___ge__(other);
}
@Override
public PyObject __gt__(PyObject other) {
return basebytes___gt__(other);
}
@ExposedMethod(type = MethodType.BINARY, doc = BuiltinDocs.bytearray___eq___doc)
final synchronized PyObject bytearray___eq__(PyObject other) {
return basebytes___eq__(other);
}
@ExposedMethod(type = MethodType.BINARY, doc = BuiltinDocs.bytearray___ne___doc)
final synchronized PyObject bytearray___ne__(PyObject other) {
return basebytes___ne__(other);
}
@ExposedMethod(type = MethodType.BINARY, doc = BuiltinDocs.bytearray___lt___doc)
final synchronized PyObject bytearray___lt__(PyObject other) {
return basebytes___lt__(other);
}
@ExposedMethod(type = MethodType.BINARY, doc = BuiltinDocs.bytearray___le___doc)
final synchronized PyObject bytearray___le__(PyObject other) {
return basebytes___le__(other);
}
@ExposedMethod(type = MethodType.BINARY, doc = BuiltinDocs.bytearray___ge___doc)
final synchronized PyObject bytearray___ge__(PyObject other) {
return basebytes___ge__(other);
}
@ExposedMethod(type = MethodType.BINARY, doc = BuiltinDocs.bytearray___gt___doc)
final synchronized PyObject bytearray___gt__(PyObject other) {
return basebytes___gt__(other);
}
/*
* ============================================================================================
* Python API for bytearray
* ============================================================================================
*/
@Override
public PyObject __add__(PyObject o) {
return bytearray___add__(o);
}
@ExposedMethod(type = MethodType.BINARY, doc = BuiltinDocs.bytearray___add___doc)
final synchronized PyObject bytearray___add__(PyObject o) {
PyByteArray sum = null;
// XXX re-write using buffer API
if (o instanceof BaseBytes) {
BaseBytes ob = (BaseBytes)o;
// Quick route: allocate the right size bytearray and copy the two parts in.
sum = new PyByteArray(size + ob.size);
System.arraycopy(storage, offset, sum.storage, sum.offset, size);
System.arraycopy(ob.storage, ob.offset, sum.storage, sum.offset + size, ob.size);
} else if (o.getType() == PyString.TYPE) {
// Support bytes type, which in in Python 2.7 is an alias of str. Remove in 3.0
PyString os = (PyString)o;
// Allocate the right size bytearray and copy the two parts in.
sum = new PyByteArray(size + os.__len__());
System.arraycopy(storage, offset, sum.storage, sum.offset, size);
sum.setslice(size, sum.size, 1, os);
} else {
// Unsuitable type
// XXX note reversed order relative to __iadd__ may be wrong, matches Python 2.7
throw ConcatenationTypeError(TYPE, o.getType());
}
return sum;
}
/**
* Returns the number of bytes actually allocated.
*/
public int __alloc__() {
return bytearray___alloc__();
}
@ExposedMethod(doc = BuiltinDocs.bytearray___alloc___doc)
final int bytearray___alloc__() {
return storage.length;
}
/**
* Equivalent to the standard Python <code>__imul__</code> method, that for a byte array returns
* a new byte array containing the same thing n times.
*/
@Override
public PyObject __imul__(PyObject n) {
return bytearray___imul__(n);
}
@ExposedMethod(type = MethodType.BINARY, doc = BuiltinDocs.bytearray___imul___doc)
final PyObject bytearray___imul__(PyObject n) {
if (!n.isIndex()) {
return null;
}
irepeat(n.asIndex(Py.OverflowError));
return this;
}
/**
* Equivalent to the standard Python <code>__mul__</code> method, that for a byte array returns
* a new byte array containing the same thing n times.
*/
@Override
public PyObject __mul__(PyObject n) {
return bytearray___mul__(n);
}
@ExposedMethod(type = MethodType.BINARY, doc = BuiltinDocs.bytearray___mul___doc)
final PyObject bytearray___mul__(PyObject n) {
if (!n.isIndex()) {
return null;
}
return repeat(n.asIndex(Py.OverflowError));
}
/**
* Equivalent to the standard Python <code>__rmul__</code> method, that for a byte array returns
* a new byte array containing the same thing n times.
*/
@Override
public PyObject __rmul__(PyObject n) {
return bytearray___rmul__(n);
}
@ExposedMethod(type = MethodType.BINARY, doc = BuiltinDocs.bytearray___rmul___doc)
final PyObject bytearray___rmul__(PyObject n) {
if (!n.isIndex()) {
return null;
}