-
Notifications
You must be signed in to change notification settings - Fork 227
Expand file tree
/
Copy path_codecs.java
More file actions
1749 lines (1555 loc) · 72.3 KB
/
_codecs.java
File metadata and controls
1749 lines (1555 loc) · 72.3 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)2013 Jython Developers. Original Java version copyright 2000 Finn Bock.
*
* This program contains material copyrighted by: Copyright (c) Corporation for National Research
* Initiatives. Originally written by Marc-Andre Lemburg (mal@lemburg.com).
*/
package org.python.modules;
import java.nio.ByteBuffer;
import java.nio.charset.Charset;
import java.util.Iterator;
import org.python.core.Py;
import org.python.core.PyDictionary;
import org.python.core.PyInteger;
import org.python.core.PyNone;
import org.python.core.PyObject;
import org.python.core.PyString;
import org.python.core.PySystemState;
import org.python.core.PyTuple;
import org.python.core.PyUnicode;
import org.python.core.codecs;
import org.python.core.Untraversable;
import org.python.expose.ExposedType;
/**
* This class corresponds to the Python _codecs module, which in turn lends its functions to the
* codecs module (in Lib/codecs.py). It exposes the implementing functions of several codec families
* called out in the Python codecs library Lib/encodings/*.py, where it is usually claimed that they
* are bound "as C functions". Obviously, C stands for "compiled" in this context, rather than
* dependence on a particular implementation language. Actual transcoding methods often come from
* the related {@link codecs} class.
*/
public class _codecs {
public static void register(PyObject search_function) {
codecs.register(search_function);
}
private static String _castString(PyString pystr) {
// Jython used to treat String as equivalent to PyString, or maybe PyUnicode, as
// it made sense. We need to be more careful now! Insert this cast check as necessary
// to ensure the appropriate compliance.
if (pystr == null) {
return null;
}
String s = pystr.toString();
if (pystr instanceof PyUnicode) {
return s;
} else {
// May throw UnicodeEncodeError, per CPython behavior
return codecs.PyUnicode_EncodeASCII(s, s.length(), null);
}
}
public static PyTuple lookup(PyString encoding) {
return codecs.lookup(_castString(encoding));
}
public static PyObject lookup_error(PyString handlerName) {
return codecs.lookup_error(_castString(handlerName));
}
public static void register_error(String name, PyObject errorHandler) {
codecs.register_error(name, errorHandler);
}
/**
* Decode <code>bytes</code> using the system default encoding (see
* {@link codecs#getDefaultEncoding()}). Decoding errors raise a <code>ValueError</code>.
*
* @param bytes to be decoded
* @return Unicode string decoded from <code>bytes</code>
*/
public static PyObject decode(PyString bytes) {
return decode(bytes, null, null);
}
/**
* Decode <code>bytes</code> using the codec registered for the <code>encoding</code>. The
* <code>encoding</code> defaults to the system default encoding (see
* {@link codecs#getDefaultEncoding()}). Decoding errors raise a <code>ValueError</code>.
*
* @param bytes to be decoded
* @param encoding name of encoding (to look up in codec registry)
* @return Unicode string decoded from <code>bytes</code>
*/
public static PyObject decode(PyString bytes, PyString encoding) {
return decode(bytes, encoding, null);
}
/**
* Decode <code>bytes</code> using the codec registered for the <code>encoding</code>. The
* <code>encoding</code> defaults to the system default encoding (see
* {@link codecs#getDefaultEncoding()}). The string <code>errors</code> may name a different
* error handling policy (built-in or registered with {@link #register_error(String, PyObject)}
* ). The default error policy is 'strict' meaning that decoding errors raise a
* <code>ValueError</code>.
*
* @param bytes to be decoded
* @param encoding name of encoding (to look up in codec registry)
* @param errors error policy name (e.g. "ignore")
* @return Unicode string decoded from <code>bytes</code>
*/
public static PyObject decode(PyString bytes, PyString encoding, PyString errors) {
return codecs.decode(bytes, _castString(encoding), _castString(errors));
}
/**
* Encode <code>unicode</code> using the system default encoding (see
* {@link codecs#getDefaultEncoding()}). Encoding errors raise a <code>ValueError</code>.
*
* @param unicode string to be encoded
* @return bytes object encoding <code>unicode</code>
*/
public static PyString encode(PyUnicode unicode) {
return encode(unicode, null, null);
}
/**
* Encode <code>unicode</code> using the codec registered for the <code>encoding</code>. The
* <code>encoding</code> defaults to the system default encoding (see
* {@link codecs#getDefaultEncoding()}). Encoding errors raise a <code>ValueError</code>.
*
* @param unicode string to be encoded
* @param encoding name of encoding (to look up in codec registry)
* @return bytes object encoding <code>unicode</code>
*/
public static PyString encode(PyUnicode unicode, PyString encoding) {
return encode(unicode, encoding, null);
}
/**
* Encode <code>unicode</code> using the codec registered for the <code>encoding</code>. The
* <code>encoding</code> defaults to the system default encoding (see
* {@link codecs#getDefaultEncoding()}). The string <code>errors</code> may name a different
* error handling policy (built-in or registered with {@link #register_error(String, PyObject)}
* ). The default error policy is 'strict' meaning that encoding errors raise a
* <code>ValueError</code>.
*
* @param unicode string to be encoded
* @param encoding name of encoding (to look up in codec registry)
* @param errors error policy name (e.g. "ignore")
* @return bytes object encoding <code>unicode</code>
*/
public static PyString encode(PyUnicode unicode, PyString encoding, PyString errors) {
return Py.newString(codecs.encode(unicode, _castString(encoding), _castString(errors)));
}
/* --- Some codec support methods -------------------------------------------- */
public static PyObject charmap_build(PyUnicode map) {
return EncodingMap.buildEncodingMap(map);
}
/**
* Enumeration representing the possible endianness of UTF-32 (possibly UTF-16) encodings.
* Python uses integers <code>{-1, 0, 1}</code>, but we can be more expressive. For encoding
* UNDEFINED means choose the endianness of the platform and insert a byte order mark (BOM). But
* since the platform is Java, that is always big-endian. For decoding it means read the BOM
* from the stream, and it is an error not to find one (compare
* <code>Lib/encodings/utf_32.py</code>).
*/
enum ByteOrder {
LE, UNDEFINED, BE;
/** Returns the Python equivalent code -1 = LE, 0 = as marked/platform, +1 = BE */
int code() {
return ordinal() - 1;
}
/** Returns equivalent to the Python code -1 = LE, 0 = as marked/platform, +1 = BE */
static ByteOrder fromInt(int byteorder) {
switch (byteorder) {
case -1:
return LE;
case 1:
return BE;
default:
return UNDEFINED;
}
}
}
/**
* Convenience method to construct the return value of decoders, providing the Unicode result as
* a String, and the number of bytes consumed.
*
* @param u the unicode result as a UTF-16 Java String
* @param bytesConsumed the number of bytes consumed
* @return the tuple (unicode(u), bytesConsumed)
*/
private static PyTuple decode_tuple(String u, int bytesConsumed) {
return new PyTuple(new PyUnicode(u), Py.newInteger(bytesConsumed));
}
/**
* Convenience method to construct the return value of decoders, providing the Unicode result as
* a String, and the number of bytes consumed in decoding as either a single-element array or an
* int to be used if the array argument is null.
*
* @param u the unicode result as a UTF-16 Java String
* @param consumed if not null, element [0] is the number of bytes consumed
* @param defConsumed if consumed==null, use this as the number of bytes consumed
* @return the tuple (unicode(u), bytesConsumed)
*/
private static PyTuple decode_tuple(String u, int[] consumed, int defConsumed) {
return decode_tuple(u, consumed != null ? consumed[0] : defConsumed);
}
/**
* Convenience method to construct the return value of decoders that infer the byte order from
* the byte-order mark.
*
* @param u the unicode result as a UTF-16 Java String
* @param bytesConsumed the number of bytes consumed
* @param order the byte order (deduced by codec)
* @return the tuple (unicode(u), bytesConsumed, byteOrder)
*/
private static PyTuple decode_tuple(String u, int bytesConsumed, ByteOrder order) {
int bo = order.code();
return new PyTuple(new PyUnicode(u), Py.newInteger(bytesConsumed), Py.newInteger(bo));
}
private static PyTuple decode_tuple_str(String s, int len) {
return new PyTuple(new PyString(s), Py.newInteger(len));
}
private static PyTuple encode_tuple(String s, int len) {
return new PyTuple(new PyString(s), Py.newInteger(len));
}
/* --- UTF-8 Codec --------------------------------------------------- */
public static PyTuple utf_8_decode(String str) {
return utf_8_decode(str, null);
}
public static PyTuple utf_8_decode(String str, String errors) {
return utf_8_decode(str, errors, false);
}
public static PyTuple utf_8_decode(String str, String errors, PyObject final_) {
return utf_8_decode(str, errors, final_.__nonzero__());
}
public static PyTuple utf_8_decode(String str, String errors, boolean final_) {
int[] consumed = final_ ? null : new int[1];
return decode_tuple(codecs.PyUnicode_DecodeUTF8Stateful(str, errors, consumed), final_
? str.length() : consumed[0]);
}
public static PyTuple utf_8_encode(String str) {
return utf_8_encode(str, null);
}
public static PyTuple utf_8_encode(String str, String errors) {
int size = str.length();
return encode_tuple(codecs.PyUnicode_EncodeUTF8(str, errors), size);
}
/* --- UTF-7 Codec --------------------------------------------------- */
public static PyTuple utf_7_decode(String bytes) {
return utf_7_decode(bytes, null);
}
public static PyTuple utf_7_decode(String bytes, String errors) {
return utf_7_decode(bytes, null, false);
}
public static PyTuple utf_7_decode(String bytes, String errors, boolean finalFlag) {
int[] consumed = finalFlag ? null : new int[1];
String decoded = codecs.PyUnicode_DecodeUTF7Stateful(bytes, errors, consumed);
return decode_tuple(decoded, consumed, bytes.length());
}
public static PyTuple utf_7_encode(String str) {
return utf_7_encode(str, null);
}
public static PyTuple utf_7_encode(String str, String errors) {
int size = str.length();
return encode_tuple(codecs.PyUnicode_EncodeUTF7(str, false, false, errors), size);
}
/* --- string-escape Codec -------------------------------------------- */
public static PyTuple escape_decode(String str) {
return escape_decode(str, null);
}
public static PyTuple escape_decode(String str, String errors) {
return decode_tuple_str(PyString.decode_UnicodeEscape(str, 0, str.length(), errors, true),
str.length());
}
public static PyTuple escape_encode(String str) {
return escape_encode(str, null);
}
public static PyTuple escape_encode(String str, String errors) {
return encode_tuple(PyString.encode_UnicodeEscape(str, false), str.length());
}
/* --- Character Mapping Codec --------------------------------------- */
/**
* Equivalent to <code>charmap_decode(bytes, errors, null)</code>. This method is here so the
* error and mapping arguments can be optional at the Python level.
*
* @param bytes sequence of bytes to decode
* @return decoded string and number of bytes consumed
*/
public static PyTuple charmap_decode(String bytes) {
return charmap_decode(bytes, null, null);
}
/**
* Equivalent to <code>charmap_decode(bytes, errors, null)</code>. This method is here so the
* error argument can be optional at the Python level.
*
* @param bytes sequence of bytes to decode
* @param errors error policy
* @return decoded string and number of bytes consumed
*/
public static PyTuple charmap_decode(String bytes, String errors) {
return charmap_decode(bytes, errors, null);
}
/**
* Decode a sequence of bytes into Unicode characters via a mapping supplied as a container to
* be indexed by the byte values (as unsigned integers). If the mapping is null or None, decode
* with latin-1 (essentially treating bytes as character codes directly).
*
* @param bytes sequence of bytes to decode
* @param errors error policy
* @param mapping to convert bytes to characters
* @return decoded string and number of bytes consumed
*/
public static PyTuple charmap_decode(String bytes, String errors, PyObject mapping) {
if (mapping == null || mapping == Py.None) {
// Default to Latin-1
return latin_1_decode(bytes, errors);
} else {
return charmap_decode(bytes, errors, mapping, false);
}
}
/**
* Decode a sequence of bytes into Unicode characters via a mapping supplied as a container to
* be indexed by the byte values (as unsigned integers).
*
* @param bytes sequence of bytes to decode
* @param errors error policy
* @param mapping to convert bytes to characters
* @param ignoreUnmapped if true, pass unmapped byte values as character codes [0..256)
* @return decoded string and number of bytes consumed
*/
public static PyTuple charmap_decode(String bytes, String errors, PyObject mapping,
boolean ignoreUnmapped) {
// XXX bytes: would prefer to accept any object with buffer API
int size = bytes.length();
StringBuilder v = new StringBuilder(size);
for (int i = 0; i < size; i++) {
// Process the i.th input byte
int b = bytes.charAt(i);
if (b > 0xff) {
i = codecs.insertReplacementAndGetResume(v, errors, "charmap", bytes, //
i, i + 1, "ordinal not in range(255)") - 1;
continue;
}
// Map the byte to an output character code (or possibly string)
PyObject w = Py.newInteger(b);
PyObject x = mapping.__finditem__(w);
// Apply to the output
if (x == null) {
// Error case: mapping not found
if (ignoreUnmapped) {
v.appendCodePoint(b);
} else {
i = codecs.insertReplacementAndGetResume(v, errors, "charmap", bytes, //
i, i + 1, "no mapping found") - 1;
}
} else if (x instanceof PyInteger) {
// Mapping was to an int: treat as character code
int value = ((PyInteger)x).getValue();
if (value < 0 || value > PySystemState.maxunicode) {
throw Py.TypeError("character mapping must return "
+ "integer greater than 0 and less than sys.maxunicode");
}
v.appendCodePoint(value);
} else if (x == Py.None) {
i = codecs.insertReplacementAndGetResume(v, errors, "charmap", bytes, //
i, i + 1, "character maps to <undefined>") - 1;
} else if (x instanceof PyString) {
String s = x.toString();
if (s.charAt(0) == 0xfffe) {
// Invalid indicates "undefined" see C-API PyUnicode_DecodeCharmap()
i = codecs.insertReplacementAndGetResume(v, errors, "charmap", bytes, //
i, i + 1, "character maps to <undefined>") - 1;
} else {
v.append(s);
}
} else {
/* wrong return value */
throw Py.TypeError("character mapping must return " + "integer, None or str");
}
}
return decode_tuple(v.toString(), size);
}
// parallel to CPython's PyUnicode_TranslateCharmap
public static PyObject translateCharmap(PyUnicode str, String errors, PyObject mapping) {
StringBuilder buf = new StringBuilder(str.toString().length());
for (Iterator<Integer> iter = str.newSubsequenceIterator(); iter.hasNext();) {
int codePoint = iter.next();
PyObject result = mapping.__finditem__(Py.newInteger(codePoint));
if (result == null) {
// No mapping found means: use 1:1 mapping
buf.appendCodePoint(codePoint);
} else if (result == Py.None) {
// XXX: We don't support the fancier error handling CPython does here of
// capturing regions of chars removed by the None mapping to optionally
// pass to an error handler. Though we don't seem to even use this
// functionality anywhere either
;
} else if (result instanceof PyInteger) {
int value = result.asInt();
if (value < 0 || value > PySystemState.maxunicode) {
throw Py.TypeError(String.format("character mapping must be in range(0x%x)",
PySystemState.maxunicode + 1));
}
buf.appendCodePoint(value);
} else if (result instanceof PyUnicode) {
buf.append(result.toString());
} else {
// wrong return value
throw Py.TypeError("character mapping must return integer, None or unicode");
}
}
return new PyUnicode(buf.toString());
}
/**
* Equivalent to <code>charmap_encode(str, null, null)</code>. This method is here so the error
* and mapping arguments can be optional at the Python level.
*
* @param str to be encoded
* @return (encoded data, size(str)) as a pair
*/
public static PyTuple charmap_encode(String str) {
return charmap_encode(str, null, null);
}
/**
* Equivalent to <code>charmap_encode(str, errors, null)</code>. This method is here so the
* mapping can be optional at the Python level.
*
* @param str to be encoded
* @param errors error policy name (e.g. "ignore")
* @return (encoded data, size(str)) as a pair
*/
public static PyTuple charmap_encode(String str, String errors) {
return charmap_encode(str, errors, null);
}
/**
* Encoder based on an optional character mapping. This mapping is either an
* <code>EncodingMap</code> of 256 entries, or an arbitrary container indexable with integers
* using <code>__finditem__</code> and yielding byte strings. If the mapping is null, latin-1
* (effectively a mapping of character code to the numerically-equal byte) is used
*
* @param str to be encoded
* @param errors error policy name (e.g. "ignore")
* @param mapping from character code to output byte (or string)
* @return (encoded data, size(str)) as a pair
*/
public static PyTuple charmap_encode(String str, String errors, PyObject mapping) {
if (mapping == null || mapping == Py.None) {
// Default to Latin-1
return latin_1_encode(str, errors);
} else {
return charmap_encode_internal(str, errors, mapping, new StringBuilder(str.length()),
true);
}
}
/**
* Helper to implement the several variants of <code>charmap_encode</code>, given an optional
* mapping. This mapping is either an <code>EncodingMap</code> of 256 entries, or an arbitrary
* container indexable with integers using <code>__finditem__</code> and yielding byte strings.
*
* @param str to be encoded
* @param errors error policy name (e.g. "ignore")
* @param mapping from character code to output byte (or string)
* @param v to contain the encoded bytes
* @param letLookupHandleError
* @return (encoded data, size(str)) as a pair
*/
private static PyTuple charmap_encode_internal(String str, String errors, PyObject mapping,
StringBuilder v, boolean letLookupHandleError) {
EncodingMap encodingMap = mapping instanceof EncodingMap ? (EncodingMap)mapping : null;
int size = str.length();
for (int i = 0; i < size; i++) {
// Map the i.th character of str to some value
char ch = str.charAt(i);
PyObject x;
if (encodingMap != null) {
// The mapping given was an EncodingMap [0,256) => on-negative int
int result = encodingMap.lookup(ch);
x = (result == -1) ? null : Py.newInteger(result);
} else {
// The mapping was a map or similar: non-negative int -> object
x = mapping.__finditem__(Py.newInteger(ch));
}
// And map this object to an output character
if (x == null) {
// Error during lookup
if (letLookupHandleError) {
// Some kind of substitute can be placed in the output
i = handleBadMapping(str, errors, mapping, v, size, i);
} else {
// Hard error
throw Py.UnicodeEncodeError("charmap", str, i, i + 1,
"character maps to <undefined>");
}
} else if (x instanceof PyInteger) {
// Look-up had integer result: output as byte value
int value = ((PyInteger)x).getValue();
if (value < 0 || value > 255) {
throw Py.TypeError("character mapping must be in range(256)");
}
v.append((char)value);
} else if (x instanceof PyString && !(x instanceof PyUnicode)) {
// Look-up had str or unicode result: output as Java String
// XXX: (Py3k) Look-up had bytes or str result: output as ... this is a problem
v.append(x.toString());
} else if (x instanceof PyNone) {
i = handleBadMapping(str, errors, mapping, v, size, i);
} else {
/* wrong return value */
throw Py.TypeError("character mapping must return " + "integer, None or str");
}
}
return encode_tuple(v.toString(), size);
}
/**
* Helper for {@link #charmap_encode_internal(String, String, PyObject, StringBuilder, boolean)}
* called when we need some kind of substitute in the output for an invalid input.
*
* @param str to be encoded
* @param errors error policy name (e.g. "ignore")
* @param mapping from character code to output byte (or string)
* @param v to contain the encoded bytes
* @param size of str
* @param i index in str of current (and problematic) character
* @return index of last character of problematic section
*/
private static int handleBadMapping(String str, String errors, PyObject mapping,
StringBuilder v, int size, int i) {
// If error policy specified, execute it
if (errors != null) {
if (errors.equals(codecs.IGNORE)) {
return i;
} else if (errors.equals(codecs.REPLACE)) {
String replStr = "?";
charmap_encode_internal(replStr, errors, mapping, v, false);
return i;
} else if (errors.equals(codecs.XMLCHARREFREPLACE)) {
String replStr = codecs.xmlcharrefreplace(i, i + 1, str).toString();
charmap_encode_internal(replStr, errors, mapping, v, false);
return i;
} else if (errors.equals(codecs.BACKSLASHREPLACE)) {
String replStr = codecs.backslashreplace(i, i + 1, str).toString();
charmap_encode_internal(replStr, errors, mapping, v, false);
return i;
}
}
// Default behaviour (error==null or does not match known case)
String msg = "character maps to <undefined>";
PyObject replacement = codecs.encoding_error(errors, "charmap", str, i, i + 1, msg);
String replStr = replacement.__getitem__(0).toString();
charmap_encode_internal(replStr, errors, mapping, v, false);
return codecs.calcNewPosition(size, replacement) - 1;
}
/* --- ascii Codec ---------------------------------------------- */
public static PyTuple ascii_decode(String str) {
return ascii_decode(str, null);
}
public static PyTuple ascii_decode(String str, String errors) {
int size = str.length();
return decode_tuple(codecs.PyUnicode_DecodeASCII(str, size, errors), size);
}
public static PyTuple ascii_encode(String str) {
return ascii_encode(str, null);
}
public static PyTuple ascii_encode(String str, String errors) {
int size = str.length();
return encode_tuple(codecs.PyUnicode_EncodeASCII(str, size, errors), size);
}
/* --- Latin-1 Codec -------------------------------------------- */
public static PyTuple latin_1_decode(String str) {
return latin_1_decode(str, null);
}
public static PyTuple latin_1_decode(String str, String errors) {
int size = str.length();
return decode_tuple(codecs.PyUnicode_DecodeLatin1(str, size, errors), size);
}
public static PyTuple latin_1_encode(String str) {
return latin_1_encode(str, null);
}
public static PyTuple latin_1_encode(String str, String errors) {
int size = str.length();
return encode_tuple(codecs.PyUnicode_EncodeLatin1(str, size, errors), size);
}
/* --- UTF-16 Codec ------------------------------------------- */
public static PyTuple utf_16_encode(String str) {
return utf_16_encode(str, null);
}
public static PyTuple utf_16_encode(String str, String errors) {
return encode_tuple(encode_UTF16(str, errors, 0), str.length());
}
public static PyTuple utf_16_encode(String str, String errors, int byteorder) {
return encode_tuple(encode_UTF16(str, errors, byteorder), str.length());
}
public static PyTuple utf_16_le_encode(String str) {
return utf_16_le_encode(str, null);
}
public static PyTuple utf_16_le_encode(String str, String errors) {
return encode_tuple(encode_UTF16(str, errors, -1), str.length());
}
public static PyTuple utf_16_be_encode(String str) {
return utf_16_be_encode(str, null);
}
public static PyTuple utf_16_be_encode(String str, String errors) {
return encode_tuple(encode_UTF16(str, errors, 1), str.length());
}
public static String encode_UTF16(String str, String errors, int byteorder) {
final Charset utf16;
if (byteorder == 0) {
utf16 = Charset.forName("UTF-16");
} else if (byteorder == -1) {
utf16 = Charset.forName("UTF-16LE");
} else {
utf16 = Charset.forName("UTF-16BE");
}
// XXX errors argument ignored: Java's codecs implement "replace"
final ByteBuffer bbuf = utf16.encode(str);
final StringBuilder v = new StringBuilder(bbuf.limit());
while (bbuf.remaining() > 0) {
int val = bbuf.get();
if (val < 0) {
val = 256 + val;
}
v.appendCodePoint(val);
}
return v.toString();
}
public static PyTuple utf_16_decode(String str) {
return utf_16_decode(str, null);
}
public static PyTuple utf_16_decode(String str, String errors) {
return utf_16_decode(str, errors, false);
}
public static PyTuple utf_16_decode(String str, String errors, boolean final_) {
int[] bo = new int[] {0};
int[] consumed = final_ ? null : new int[1];
return decode_tuple(decode_UTF16(str, errors, bo, consumed), final_ ? str.length()
: consumed[0]);
}
public static PyTuple utf_16_le_decode(String str) {
return utf_16_le_decode(str, null);
}
public static PyTuple utf_16_le_decode(String str, String errors) {
return utf_16_le_decode(str, errors, false);
}
public static PyTuple utf_16_le_decode(String str, String errors, boolean final_) {
int[] bo = new int[] {-1};
int[] consumed = final_ ? null : new int[1];
return decode_tuple(decode_UTF16(str, errors, bo, consumed), final_ ? str.length()
: consumed[0]);
}
public static PyTuple utf_16_be_decode(String str) {
return utf_16_be_decode(str, null);
}
public static PyTuple utf_16_be_decode(String str, String errors) {
return utf_16_be_decode(str, errors, false);
}
public static PyTuple utf_16_be_decode(String str, String errors, boolean final_) {
int[] bo = new int[] {1};
int[] consumed = final_ ? null : new int[1];
return decode_tuple(decode_UTF16(str, errors, bo, consumed), final_ ? str.length()
: consumed[0]);
}
public static PyTuple utf_16_ex_decode(String str) {
return utf_16_ex_decode(str, null);
}
public static PyTuple utf_16_ex_decode(String str, String errors) {
return utf_16_ex_decode(str, errors, 0);
}
public static PyTuple utf_16_ex_decode(String str, String errors, int byteorder) {
return utf_16_ex_decode(str, errors, byteorder, false);
}
public static PyTuple
utf_16_ex_decode(String str, String errors, int byteorder, boolean final_) {
int[] bo = new int[] {0};
int[] consumed = final_ ? null : new int[1];
String decoded = decode_UTF16(str, errors, bo, consumed);
return new PyTuple(new PyUnicode(decoded), Py.newInteger(final_ ? str.length()
: consumed[0]), Py.newInteger(bo[0]));
}
private static String decode_UTF16(String str, String errors, int[] byteorder) {
return decode_UTF16(str, errors, byteorder, null);
}
private static String decode_UTF16(String str, String errors, int[] byteorder, int[] consumed) {
int bo = 0;
if (byteorder != null) {
bo = byteorder[0];
}
int size = str.length();
StringBuilder v = new StringBuilder(size / 2);
int i;
for (i = 0; i < size; i += 2) {
char ch1 = str.charAt(i);
if (i + 1 == size) {
if (consumed != null) {
break;
}
i = codecs.insertReplacementAndGetResume(v, errors, "utf-16", str, //
i, i + 1, "truncated data");
continue;
}
char ch2 = str.charAt(i + 1);
if (ch1 == 0xFE && ch2 == 0xFF) {
bo = 1;
continue;
} else if (ch1 == 0xFF && ch2 == 0xFE) {
bo = -1;
continue;
}
int W1;
if (bo == -1) {
W1 = (ch2 << 8 | ch1);
} else {
W1 = (ch1 << 8 | ch2);
}
if (W1 < 0xD800 || W1 > 0xDFFF) {
v.appendCodePoint(W1);
continue;
} else if (W1 >= 0xD800 && W1 <= 0xDBFF && i < size - 1) {
i += 2;
char ch3 = str.charAt(i);
char ch4 = str.charAt(i + 1);
int W2;
if (bo == -1) {
W2 = (ch4 << 8 | ch3);
} else {
W2 = (ch3 << 8 | ch4);
}
if (W2 >= 0xDC00 && W2 <= 0xDFFF) {
int U = (((W1 & 0x3FF) << 10) | (W2 & 0x3FF)) + 0x10000;
v.appendCodePoint(U);
continue;
}
i = codecs.insertReplacementAndGetResume(v, errors, "utf-16", str, //
i, i + 1, "illegal UTF-16 surrogate");
continue;
}
i = codecs.insertReplacementAndGetResume(v, errors, "utf-16", str, //
i, i + 1, "illegal encoding");
}
if (byteorder != null) {
byteorder[0] = bo;
}
if (consumed != null) {
consumed[0] = i;
}
return v.toString();
}
/* --- UTF-32 Codec ------------------------------------------- */
/**
* Encode a Unicode Java String as UTF-32 with byte order mark. (Encoding is in platform byte
* order, which is big-endian for Java.)
*
* @param unicode to be encoded
* @return tuple (encoded_bytes, unicode_consumed)
*/
public static PyTuple utf_32_encode(String unicode) {
return utf_32_encode(unicode, null);
}
/**
* Encode a Unicode Java String as UTF-32 with byte order mark. (Encoding is in platform byte
* order, which is big-endian for Java.)
*
* @param unicode to be encoded
* @param errors error policy name or null meaning "strict"
* @return tuple (encoded_bytes, unicode_consumed)
*/
public static PyTuple utf_32_encode(String unicode, String errors) {
return PyUnicode_EncodeUTF32(unicode, errors, ByteOrder.UNDEFINED);
}
/**
* Encode a Unicode Java String as UTF-32 in specified byte order with byte order mark.
*
* @param unicode to be encoded
* @param errors error policy name or null meaning "strict"
* @param byteorder decoding "endianness" specified (in the Python -1, 0, +1 convention)
* @return tuple (encoded_bytes, unicode_consumed)
*/
public static PyTuple utf_32_encode(String unicode, String errors, int byteorder) {
ByteOrder order = ByteOrder.fromInt(byteorder);
return PyUnicode_EncodeUTF32(unicode, errors, order);
}
/**
* Encode a Unicode Java String as UTF-32 with little-endian byte order. No byte-order mark is
* generated.
*
* @param unicode to be encoded
* @return tuple (encoded_bytes, unicode_consumed)
*/
public static PyTuple utf_32_le_encode(String unicode) {
return utf_32_le_encode(unicode, null);
}
/**
* Encode a Unicode Java String as UTF-32 with little-endian byte order. No byte-order mark is
* generated.
*
* @param unicode to be encoded
* @param errors error policy name or null meaning "strict"
* @return tuple (encoded_bytes, unicode_consumed)
*/
public static PyTuple utf_32_le_encode(String unicode, String errors) {
return PyUnicode_EncodeUTF32(unicode, errors, ByteOrder.LE);
}
/**
* Encode a Unicode Java String as UTF-32 with big-endian byte order. No byte-order mark is
* generated.
*
* @param unicode to be encoded
* @return tuple (encoded_bytes, unicode_consumed)
*/
public static PyTuple utf_32_be_encode(String unicode) {
return utf_32_be_encode(unicode, null);
}
/**
* Encode a Unicode Java String as UTF-32 with big-endian byte order. No byte-order mark is
* generated.
*
* @param unicode to be encoded
* @param errors error policy name or null meaning "strict"
* @return tuple (encoded_bytes, unicode_consumed)
*/
public static PyTuple utf_32_be_encode(String unicode, String errors) {
return PyUnicode_EncodeUTF32(unicode, errors, ByteOrder.BE);
}
/**
* Encode a Unicode Java String as UTF-32 in specified byte order. A byte-order mark is
* generated if <code>order = ByteOrder.UNDEFINED</code>, and the byte order in that case will
* be the platform default, which is BE since the platform is Java.
* <p>
* The input String <b>must</b> be valid UTF-16, in particular, if it contains surrogate code
* units they must be ordered and paired correctly. The last char in <code>unicode</code> is not
* allowed to be an unpaired surrogate. These criteria will be met if the String
* <code>unicode</code> is the contents of a valid {@link PyUnicode} or {@link PyString}.
*
* @param unicode to be encoded
* @param errors error policy name or null meaning "strict"
* @param order byte order to use BE, LE or UNDEFINED (a BOM will be written)
* @return tuple (encoded_bytes, unicode_consumed)
*/
private static PyTuple PyUnicode_EncodeUTF32(String unicode, String errors, ByteOrder order) {
// We use a StringBuilder but we are really storing encoded bytes
StringBuilder v = new StringBuilder(4 * (unicode.length() + 1));
int uptr = 0;
// Write a BOM (if required to)
if (order == ByteOrder.UNDEFINED) {
v.append("\u0000\u0000\u00fe\u00ff");
order = ByteOrder.BE;
}
if (order != ByteOrder.LE) {
uptr = PyUnicode_EncodeUTF32BELoop(v, unicode, errors);
} else {
uptr = PyUnicode_EncodeUTF32LELoop(v, unicode, errors);
}
// XXX Issue #2002: should probably report length consumed in Unicode characters
return encode_tuple(v.toString(), uptr);
}
/**
* Helper to {@link #PyUnicode_EncodeUTF32(String, String, ByteOrder)} when big-endian encoding
* is to be carried out.
*
* @param v output buffer building String of bytes (Jython PyString convention)
* @param unicode character input
* @param errors error policy name (e.g. "ignore", "replace")
* @return number of Java characters consumed from unicode
*/
private static int PyUnicode_EncodeUTF32BELoop(StringBuilder v, String unicode, String errors) {
int len = unicode.length();
int uptr = 0;
char[] buf = new char[6]; // first 3 elements always zero
/*
* Main codec loop outputs arrays of 4 bytes at a time.
*/
while (uptr < len) {
int ch = unicode.charAt(uptr++);
if ((ch & 0xF800) == 0xD800) {
/*
* This is a surrogate. In Jython, unicode should always be the internal value of a
* PyUnicode, and since this should never contain invalid data, it should be a lead
* surrogate, uptr < len, and the next char must be the trail surrogate. We ought
* not to have to chech that, however ...
*/
if ((ch & 0x0400) == 0) {
// Yes, it's a lead surrogate
if (uptr < len) {
// And there is something to follow
int ch2 = unicode.charAt(uptr++);
if ((ch2 & 0xFC00) == 0xDC00) {
// And it is a trail surrogate, so we can get on with the encoding
ch = ((ch & 0x3ff) << 10) + (ch2 & 0x3ff) + 0x10000;
buf[3] = (char)((ch >> 16) & 0xff);
buf[4] = (char)((ch >> 8) & 0xff);