Debian Codegraph @

rpython/rlib/runicode.py

raw symbols SCIP
1 import sys
2 from rpython.rlib.objectmodel import specialize, we_are_translated, enforceargs
3 from rpython.rlib.rstring import StringBuilder, UnicodeBuilder
4 from rpython.rlib.rarithmetic import r_uint, intmask, widen
5 from rpython.rlib.unicodedata import unicodedb
6 from rpython.tool.sourcetools import func_with_new_name
7 from rpython.rtyper.lltypesystem import lltype, rffi
8 from rpython.rlib import jit, nonconst
9
10
11 # We always use MAXUNICODE = 0x10ffff when unicode objects use utf8,
12 # which is now the default for rpython
13 if 1 or rffi.sizeof(lltype.UniChar) == 4:
14 MAXUNICODE = 0x10ffff
15 allow_surrogate_by_default = False
16 else:
17 MAXUNICODE = 0xffff
18 allow_surrogate_by_default = True
19
20 BYTEORDER = sys.byteorder
21 BYTEORDER2 = BYTEORDER[0] + 'e' # either "le" or "be"
22 assert BYTEORDER2 in ('le', 'be')
23
24 # python 2.7 has a preview of py3k behavior, so those functions
25 # are used either when we're testing wide pypy on narrow cpython
26 # or in unicodedata in pypy
27
28 def unichr_returns_surrogate(c):
29 if c <= 0xffff or c > 0x10ffff:
30 return unichr(c)
31 else:
32 c -= 0x10000
33 return (unichr(0xD800 + (c >> 10)) +
34 unichr(0xDC00 + (c & 0x03FF)))
35
36 def ord_accepts_surrogate(u):
37 if isinstance(u, unicode) and len(u) == 2:
38 ch1 = ord(u[0])
39 ch2 = ord(u[1])
40 if 0xD800 <= ch1 <= 0xDBFF and 0xDC00 <= ch2 <= 0xDFFF:
41 return (((ch1 - 0xD800) << 10) | (ch2 - 0xDC00)) + 0x10000
42 if not we_are_translated():
43 return ord(u)
44 else:
45 if len(u) == 1:
46 return ord(u[0])
47 raise TypeError
48
49 if MAXUNICODE > sys.maxunicode:
50 # A version of unichr which allows codes outside the BMP
51 # even on narrow unicode builds.
52 # It will be used when interpreting code on top of a UCS2 CPython,
53 # when sizeof(wchar_t) == 4.
54 # Note that Python3 uses a similar implementation.
55 def UNICHR(c):
56 assert not we_are_translated()
57 return unichr_returns_surrogate(c)
58 UNICHR._flowspace_rewrite_directly_as_ = unichr
59 # ^^^ NB.: for translation, it's essential to use this hack instead
60 # of calling unichr() from UNICHR(), because unichr() detects if there
61 # is a "try:except ValueError" immediately around it.
62
63 def ORD(u):
64 assert not we_are_translated()
65 return ord_accepts_surrogate(u)
66 ORD._flowspace_rewrite_directly_as_ = ord
67
68 else:
69 UNICHR = unichr
70 ORD = ord
71
72 if MAXUNICODE > 0xFFFF:
73 def code_to_unichr(code):
74 if is_narrow_host():
75 # Host CPython is narrow build, generate surrogates
76 return unichr_returns_surrogate(code)
77 else:
78 return unichr(code)
79 else:
80 def code_to_unichr(code):
81 # generate surrogates for large codes
82 return unichr_returns_surrogate(widen(code))
83
84 def _STORECHAR(result, CH, byteorder):
85 hi = chr(((CH) >> 8) & 0xff)
86 lo = chr((CH) & 0xff)
87 if byteorder == 'little':
88 result.append(lo)
89 result.append(hi)
90 else:
91 result.append(hi)
92 result.append(lo)
93
94 def is_narrow_host():
95 return not we_are_translated() and sys.maxunicode == 0xFFFF
96
97 def default_unicode_error_decode(errors, encoding, msg, s,
98 startingpos, endingpos):
99 assert endingpos >= 0
100 if errors == 'replace':
101 return u'\ufffd', endingpos
102 if errors == 'ignore':
103 return u'', endingpos
104 raise UnicodeDecodeError(encoding, s, startingpos, endingpos, msg)
105
106 def default_unicode_error_encode(errors, encoding, msg, u,
107 startingpos, endingpos):
108 assert endingpos >= 0
109 if errors == 'replace':
110 return u'?', None, endingpos
111 if errors == 'ignore':
112 return u'', None, endingpos
113 raise UnicodeEncodeError(encoding, u, startingpos, endingpos, msg)
114
115 # ____________________________________________________________
116 # utf-8
117
118 _utf8_code_length = ''.join(map(chr, [
119 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, # 80-8F
120 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
121 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
122 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, # B0-BF
123 0, 0, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, # C0-C1 + C2-CF
124 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, # D0-DF
125 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, # E0-EF
126 4, 4, 4, 4, 4, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 # F0-F4 - F5-FF
127 ]))
128
129 # if you can't use the @elidable version, call str_decode_utf_8_impl()
130 # directly
131 @jit.elidable
132 def str_decode_utf_8(s, size, errors, final=False,
133 errorhandler=None, allow_surrogates=allow_surrogate_by_default):
134 if errorhandler is None:
135 errorhandler = default_unicode_error_decode
136 return str_decode_utf_8_elidable(s, size, errors, final, errorhandler,
137 allow_surrogates=allow_surrogates)
138
139 def _invalid_cont_byte(ordch):
140 return ordch>>6 != 0x2 # 0b10
141
142 _invalid_byte_2_of_2 = _invalid_cont_byte
143 _invalid_byte_3_of_3 = _invalid_cont_byte
144 _invalid_byte_3_of_4 = _invalid_cont_byte
145 _invalid_byte_4_of_4 = _invalid_cont_byte
146
147 @enforceargs(allow_surrogates=bool)
148 def _invalid_byte_2_of_3(ordch1, ordch2, allow_surrogates):
149 return (ordch2>>6 != 0x2 or # 0b10
150 (ordch1 == 0xe0 and ordch2 < 0xa0)
151 # surrogates shouldn't be valid UTF-8!
152 or (ordch1 == 0xed and ordch2 > 0x9f and not allow_surrogates))
153
154 def _invalid_byte_2_of_4(ordch1, ordch2):
155 return (ordch2>>6 != 0x2 or # 0b10
156 (ordch1 == 0xf0 and ordch2 < 0x90) or
157 (ordch1 == 0xf4 and ordch2 > 0x8f))
158
159 # NOTE: this is a slightly fixed algorithm when compared with
160 # CPython2's. It is closer to CPython3's. See comments in
161 # test_invalid_cb_for_3bytes_seq().
162 def str_decode_utf_8_impl(s, size, errors, final, errorhandler,
163 allow_surrogates):
164 if size == 0:
165 return u'', 0
166
167 result = UnicodeBuilder(size)
168 pos = 0
169 while pos < size:
170 ordch1 = ord(s[pos])
171 # fast path for ASCII
172 # XXX maybe use a while loop here
173 if ordch1 < 0x80:
174 result.append(unichr(ordch1))
175 pos += 1
176 continue
177
178 n = ord(_utf8_code_length[ordch1 - 0x80])
179 if pos + n > size:
180 if not final:
181 break
182 # argh, this obscure block of code is mostly a copy of
183 # what follows :-(
184 charsleft = size - pos - 1 # either 0, 1, 2
185 # note: when we get the 'unexpected end of data' we need
186 # to care about the pos returned; it can be lower than size,
187 # in case we need to continue running this loop
188 if not charsleft:
189 # there's only the start byte and nothing else
190 r, pos = errorhandler(errors, 'utf8',
191 'unexpected end of data',
192 s, pos, pos+1)
193 result.append(r)
194 continue
195 ordch2 = ord(s[pos+1])
196 if n == 3:
197 # 3-bytes seq with only a continuation byte
198 if _invalid_byte_2_of_3(ordch1, ordch2, allow_surrogates):
199 # second byte invalid, take the first and continue
200 r, pos = errorhandler(errors, 'utf8',
201 'invalid continuation byte',
202 s, pos, pos+1)
203 result.append(r)
204 continue
205 else:
206 # second byte valid, but third byte missing
207 r, pos = errorhandler(errors, 'utf8',
208 'unexpected end of data',
209 s, pos, pos+2)
210 result.append(r)
211 continue
212 elif n == 4:
213 # 4-bytes seq with 1 or 2 continuation bytes
214 if _invalid_byte_2_of_4(ordch1, ordch2):
215 # second byte invalid, take the first and continue
216 r, pos = errorhandler(errors, 'utf8',
217 'invalid continuation byte',
218 s, pos, pos+1)
219 result.append(r)
220 continue
221 elif charsleft == 2 and _invalid_byte_3_of_4(ord(s[pos+2])):
222 # third byte invalid, take the first two and continue
223 r, pos = errorhandler(errors, 'utf8',
224 'invalid continuation byte',
225 s, pos, pos+2)
226 result.append(r)
227 continue
228 else:
229 # there's only 1 or 2 valid cb, but the others are missing
230 r, pos = errorhandler(errors, 'utf8',
231 'unexpected end of data',
232 s, pos, pos+charsleft+1)
233 result.append(r)
234 continue
235 raise AssertionError("unreachable")
236
237 if n == 0:
238 r, pos = errorhandler(errors, 'utf8',
239 'invalid start byte',
240 s, pos, pos+1)
241 result.append(r)
242
243 elif n == 1:
244 assert 0, "ascii should have gone through the fast path"
245
246 elif n == 2:
247 ordch2 = ord(s[pos+1])
248 if _invalid_byte_2_of_2(ordch2):
249 r, pos = errorhandler(errors, 'utf8',
250 'invalid continuation byte',
251 s, pos, pos+1)
252 result.append(r)
253 continue
254 # 110yyyyy 10zzzzzz -> 00000000 00000yyy yyzzzzzz
255 result.append(unichr(((ordch1 & 0x1F) << 6) + # 0b00011111
256 (ordch2 & 0x3F))) # 0b00111111
257 pos += 2
258
259 elif n == 3:
260 ordch2 = ord(s[pos+1])
261 ordch3 = ord(s[pos+2])
262 if _invalid_byte_2_of_3(ordch1, ordch2, allow_surrogates):
263 r, pos = errorhandler(errors, 'utf8',
264 'invalid continuation byte',
265 s, pos, pos+1)
266 result.append(r)
267 continue
268 elif _invalid_byte_3_of_3(ordch3):
269 r, pos = errorhandler(errors, 'utf8',
270 'invalid continuation byte',
271 s, pos, pos+2)
272 result.append(r)
273 continue
274 # 1110xxxx 10yyyyyy 10zzzzzz -> 00000000 xxxxyyyy yyzzzzzz
275 result.append(unichr(((ordch1 & 0x0F) << 12) + # 0b00001111
276 ((ordch2 & 0x3F) << 6) + # 0b00111111
277 (ordch3 & 0x3F))) # 0b00111111
278 pos += 3
279
280 elif n == 4:
281 ordch2 = ord(s[pos+1])
282 ordch3 = ord(s[pos+2])
283 ordch4 = ord(s[pos+3])
284 if _invalid_byte_2_of_4(ordch1, ordch2):
285 r, pos = errorhandler(errors, 'utf8',
286 'invalid continuation byte',
287 s, pos, pos+1)
288 result.append(r)
289 continue
290 elif _invalid_byte_3_of_4(ordch3):
291 r, pos = errorhandler(errors, 'utf8',
292 'invalid continuation byte',
293 s, pos, pos+2)
294 result.append(r)
295 continue
296 elif _invalid_byte_4_of_4(ordch4):
297 r, pos = errorhandler(errors, 'utf8',
298 'invalid continuation byte',
299 s, pos, pos+3)
300 result.append(r)
301 continue
302 # 11110www 10xxxxxx 10yyyyyy 10zzzzzz -> 000wwwxx xxxxyyyy yyzzzzzz
303 c = (((ordch1 & 0x07) << 18) + # 0b00000111
304 ((ordch2 & 0x3F) << 12) + # 0b00111111
305 ((ordch3 & 0x3F) << 6) + # 0b00111111
306 (ordch4 & 0x3F)) # 0b00111111
307 if c <= MAXUNICODE:
308 result.append(UNICHR(c))
309 else:
310 # compute and append the two surrogates:
311 # translate from 10000..10FFFF to 0..FFFF
312 c -= 0x10000
313 # high surrogate = top 10 bits added to D800
314 result.append(unichr(0xD800 + (c >> 10)))
315 # low surrogate = bottom 10 bits added to DC00
316 result.append(unichr(0xDC00 + (c & 0x03FF)))
317 pos += 4
318
319 return result.build(), pos
320 str_decode_utf_8_elidable = jit.elidable(
321 func_with_new_name(str_decode_utf_8_impl, "str_decode_utf_8_elidable"))
322
323 def _encodeUCS4(result, ch):
324 # Encode UCS4 Unicode ordinals
325 result.append((chr((0xf0 | (ch >> 18)))))
326 result.append((chr((0x80 | ((ch >> 12) & 0x3f)))))
327 result.append((chr((0x80 | ((ch >> 6) & 0x3f)))))
328 result.append((chr((0x80 | (ch & 0x3f)))))
329
330 # if you can't use the @elidable version, call unicode_encode_utf_8_impl()
331 # directly
332 @jit.elidable
333 def unicode_encode_utf_8(s, size, errors, errorhandler=None,
334 allow_surrogates=allow_surrogate_by_default):
335 # In this function, allow_surrogates can be:
336 #
337 # * True: surrogates are always allowed. A valid surrogate pair
338 # is replaced with the non-BMP unicode char it stands for,
339 # which is then encoded as 4 bytes.
340 #
341 # * False: surrogates are always forbidden.
342 #
343 # See also unicode_encode_utf8sp().
344 #
345 if errorhandler is None:
346 errorhandler = default_unicode_error_encode
347 return unicode_encode_utf_8_elidable(s, size, errors, errorhandler,
348 allow_surrogates=allow_surrogates)
349
350 def unicode_encode_utf_8_impl(s, size, errors, errorhandler,
351 allow_surrogates=False):
352 assert(size >= 0)
353 result = StringBuilder(size)
354 pos = 0
355 while pos < size:
356 ch = ord(s[pos])
357 pos += 1
358 if ch < 0x80:
359 # Encode ASCII
360 result.append(chr(ch))
361 elif ch < 0x0800:
362 # Encode Latin-1
363 result.append(chr((0xc0 | (ch >> 6))))
364 result.append(chr((0x80 | (ch & 0x3f))))
365 else:
366 # Encode UCS2 Unicode ordinals
367 if ch < 0x10000:
368 # Special case: check for high surrogate
369 if 0xD800 <= ch <= 0xDFFF:
370 if pos != size:
371 ch2 = ord(s[pos])
372 # Check for low surrogate and combine the two to
373 # form a UCS4 value
374 if ((allow_surrogates or MAXUNICODE < 65536
375 or is_narrow_host()) and
376 ch <= 0xDBFF and 0xDC00 <= ch2 <= 0xDFFF):
377 ch3 = ((ch - 0xD800) << 10 | (ch2 - 0xDC00)) + 0x10000
378 assert ch3 >= 0
379 pos += 1
380 _encodeUCS4(result, ch3)
381 continue
382 # note: if the program only ever calls this with
383 # allow_surrogates=True, then we'll never annotate
384 # the following block of code, and errorhandler()
385 # will never be called. This causes RPython
386 # problems. Avoid it with the nonconst hack.
387 if not allow_surrogates or nonconst.NonConstant(False):
388 ru, rs, pos = errorhandler(errors, 'utf8',
389 'surrogates not allowed',
390 s, pos-1, pos)
391 if rs is not None:
392 # py3k only
393 result.append(rs)
394 continue
395 for ch in ru:
396 if ord(ch) < 0x80:
397 result.append(chr(ord(ch)))
398 else:
399 errorhandler('strict', 'utf8',
400 'surrogates not allowed',
401 s, pos-1, pos)
402 continue
403 # else: Fall through and handles isolated high surrogates
404 result.append((chr((0xe0 | (ch >> 12)))))
405 result.append((chr((0x80 | ((ch >> 6) & 0x3f)))))
406 result.append((chr((0x80 | (ch & 0x3f)))))
407 else:
408 _encodeUCS4(result, ch)
409 return result.build()
410 unicode_encode_utf_8_elidable = jit.elidable(
411 enforceargs(s=unicode, allow_surrogates=bool)(
412 func_with_new_name(unicode_encode_utf_8_impl,
413 "unicode_encode_utf_8_elidable")))
414
415 def unicode_encode_utf8sp(s, size):
416 # Surrogate-preserving utf-8 encoding. Any surrogate character
417 # turns into its 3-bytes encoding, whether it is paired or not.
418 # This should always be reversible, and the reverse is the regular
419 # str_decode_utf_8() with allow_surrogates=True.
420 assert(size >= 0)
421 result = StringBuilder(size)
422 pos = 0
423 while pos < size:
424 ch = ord(s[pos])
425 pos += 1
426 if ch < 0x80:
427 # Encode ASCII
428 result.append(chr(ch))
429 elif ch < 0x0800:
430 # Encode Latin-1
431 result.append(chr((0xc0 | (ch >> 6))))
432 result.append(chr((0x80 | (ch & 0x3f))))
433 elif ch < 0x10000:
434 # Encode UCS2 Unicode ordinals, and surrogates
435 result.append((chr((0xe0 | (ch >> 12)))))
436 result.append((chr((0x80 | ((ch >> 6) & 0x3f)))))
437 result.append((chr((0x80 | (ch & 0x3f)))))
438 else:
439 _encodeUCS4(result, ch)
440 return result.build()
441
442 class SurrogateError(Exception):
443 def __init__(self, char, index):
444 self.char = char
445 self.index = index
446
447 def unicode_encode_utf8_forbid_surrogates(s, size):
448 # Strict surrogate-forbidding utf-8 encoding. Any surrogate character
449 # raises an interp-level SurrogateError, even on 16-bit hosts.
450 # --- XXX check in detail what occurs on 16-bit hosts in PyPy 3 ---
451 assert(size >= 0)
452 result = StringBuilder(size)
453 pos = 0
454 while pos < size:
455 ch = ord(s[pos])
456 pos += 1
457 if ch < 0x80:
458 # Encode ASCII
459 result.append(chr(ch))
460 elif ch < 0x0800:
461 # Encode Latin-1
462 result.append(chr((0xc0 | (ch >> 6))))
463 result.append(chr((0x80 | (ch & 0x3f))))
464 elif ch < 0x10000:
465 if 0xD800 <= ch <= 0xDFFF:
466 raise SurrogateError(ch, pos)
467 # Encode UCS2 Unicode ordinals
468 result.append((chr((0xe0 | (ch >> 12)))))
469 result.append((chr((0x80 | ((ch >> 6) & 0x3f)))))
470 result.append((chr((0x80 | (ch & 0x3f)))))
471 else:
472 _encodeUCS4(result, ch)
473 return result.build()
474
475 # ____________________________________________________________
476 # utf-16
477
478 def str_decode_utf_16(s, size, errors, final=True,
479 errorhandler=None):
480 result, length, byteorder = str_decode_utf_16_helper(s, size, errors, final,
481 errorhandler, "native")
482 return result, length
483
484 def str_decode_utf_16_be(s, size, errors, final=True,
485 errorhandler=None):
486 result, length, byteorder = str_decode_utf_16_helper(s, size, errors, final,
487 errorhandler, "big")
488 return result, length
489
490 def str_decode_utf_16_le(s, size, errors, final=True,
491 errorhandler=None):
492 result, length, byteorder = str_decode_utf_16_helper(s, size, errors, final,
493 errorhandler, "little")
494 return result, length
495
496 def py3k_str_decode_utf_16(s, size, errors, final=True,
497 errorhandler=None):
498 result, length, byteorder = str_decode_utf_16_helper(s, size, errors, final,
499 errorhandler, "native",
500 'utf-16-' + BYTEORDER2)
501 return result, length
502
503 def py3k_str_decode_utf_16_be(s, size, errors, final=True,
504 errorhandler=None):
505 result, length, byteorder = str_decode_utf_16_helper(s, size, errors, final,
506 errorhandler, "big",
507 'utf-16-be')
508 return result, length
509
510 def py3k_str_decode_utf_16_le(s, size, errors, final=True,
511 errorhandler=None):
512 result, length, byteorder = str_decode_utf_16_helper(s, size, errors, final,
513 errorhandler, "little",
514 'utf-16-le')
515 return result, length
516
517 def str_decode_utf_16_helper(s, size, errors, final=True,
518 errorhandler=None,
519 byteorder="native",
520 public_encoding_name='utf16'):
521 if errorhandler is None:
522 errorhandler = default_unicode_error_decode
523 bo = 0
524
525 if BYTEORDER == 'little':
526 ihi = 1
527 ilo = 0
528 else:
529 ihi = 0
530 ilo = 1
531
532 # Check for BOM marks (U+FEFF) in the input and adjust current
533 # byte order setting accordingly. In native mode, the leading BOM
534 # mark is skipped, in all other modes, it is copied to the output
535 # stream as-is (giving a ZWNBSP character).
536 pos = 0
537 if byteorder == 'native':
538 if size >= 2:
539 bom = (ord(s[ihi]) << 8) | ord(s[ilo])
540 if BYTEORDER == 'little':
541 if bom == 0xFEFF:
542 pos += 2
543 bo = -1
544 elif bom == 0xFFFE:
545 pos += 2
546 bo = 1
547 else:
548 if bom == 0xFEFF:
549 pos += 2
550 bo = 1
551 elif bom == 0xFFFE:
552 pos += 2
553 bo = -1
554 elif byteorder == 'little':
555 bo = -1
556 else:
557 bo = 1
558 if size == 0:
559 return u'', 0, bo
560 if bo == -1:
561 # force little endian
562 ihi = 1
563 ilo = 0
564
565 elif bo == 1:
566 # force big endian
567 ihi = 0
568 ilo = 1
569
570 result = UnicodeBuilder(size // 2)
571
572 #XXX I think the errors are not correctly handled here
573 while pos < size:
574 # remaining bytes at the end? (size should be even)
575 if len(s) - pos < 2:
576 if not final:
577 break
578 r, pos = errorhandler(errors, public_encoding_name,
579 "truncated data",
580 s, pos, len(s))
581 result.append(r)
582 if len(s) - pos < 2:
583 break
584 ch = (ord(s[pos + ihi]) << 8) | ord(s[pos + ilo])
585 pos += 2
586 if ch < 0xD800 or ch > 0xDFFF:
587 result.append(unichr(ch))
588 continue
589 # UTF-16 code pair:
590 if len(s) - pos < 2:
591 pos -= 2
592 if not final:
593 break
594 errmsg = "unexpected end of data"
595 r, pos = errorhandler(errors, public_encoding_name,
596 errmsg, s, pos, len(s))
597 result.append(r)
598 if len(s) - pos < 2:
599 break
600 elif 0xD800 <= ch <= 0xDBFF:
601 ch2 = (ord(s[pos+ihi]) << 8) | ord(s[pos+ilo])
602 pos += 2
603 if 0xDC00 <= ch2 <= 0xDFFF:
604 if MAXUNICODE < 65536:
605 result.append(unichr(ch))
606 result.append(unichr(ch2))
607 else:
608 result.append(UNICHR((((ch & 0x3FF)<<10) |
609 (ch2 & 0x3FF)) + 0x10000))
610 continue
611 else:
612 r, pos = errorhandler(errors, public_encoding_name,
613 "illegal UTF-16 surrogate",
614 s, pos - 4, pos - 2)
615 result.append(r)
616 else:
617 r, pos = errorhandler(errors, public_encoding_name,
618 "illegal encoding",
619 s, pos - 2, pos)
620 result.append(r)
621 return result.build(), pos, bo
622
623 def unicode_encode_utf_16_helper(s, size, errors,
624 errorhandler=None,
625 allow_surrogates=True,
626 byteorder='little',
627 public_encoding_name='utf16'):
628 if errorhandler is None:
629 errorhandler = default_unicode_error_encode
630 if size == 0:
631 if byteorder == 'native':
632 result = StringBuilder(2)
633 _STORECHAR(result, 0xFEFF, BYTEORDER)
634 return result.build()
635 return ""
636
637 result = StringBuilder(size * 2 + 2)
638 if byteorder == 'native':
639 _STORECHAR(result, 0xFEFF, BYTEORDER)
640 byteorder = BYTEORDER
641
642 pos = 0
643 while pos < size:
644 ch = ord(s[pos])
645 pos += 1
646
647 if ch < 0xD800:
648 _STORECHAR(result, ch, byteorder)
649 elif ch >= 0x10000:
650 _STORECHAR(result, 0xD800 | ((ch-0x10000) >> 10), byteorder)
651 _STORECHAR(result, 0xDC00 | ((ch-0x10000) & 0x3FF), byteorder)
652 elif ch >= 0xE000 or allow_surrogates:
653 _STORECHAR(result, ch, byteorder)
654 else:
655 ru, rs, pos = errorhandler(errors, public_encoding_name,
656 'surrogates not allowed',
657 s, pos-1, pos)
658 if rs is not None:
659 # py3k only
660 if len(rs) % 2 != 0:
661 errorhandler('strict', public_encoding_name,
662 'surrogates not allowed',
663 s, pos-1, pos)
664 result.append(rs)
665 continue
666 for ch in ru:
667 if ord(ch) < 0xD800:
668 _STORECHAR(result, ord(ch), byteorder)
669 else:
670 errorhandler('strict', public_encoding_name,
671 'surrogates not allowed',
672 s, pos-1, pos)
673 continue
674
675 return result.build()
676
677 def unicode_encode_utf_16(s, size, errors,
678 errorhandler=None,
679 allow_surrogates=True):
680 return unicode_encode_utf_16_helper(s, size, errors, errorhandler,
681 allow_surrogates, "native")
682
683 def unicode_encode_utf_16_be(s, size, errors,
684 errorhandler=None,
685 allow_surrogates=True):
686 return unicode_encode_utf_16_helper(s, size, errors, errorhandler,
687 allow_surrogates, "big")
688
689 def unicode_encode_utf_16_le(s, size, errors,
690 errorhandler=None,
691 allow_surrogates=True):
692 return unicode_encode_utf_16_helper(s, size, errors, errorhandler,
693 allow_surrogates, "little")
694
695 def py3k_unicode_encode_utf_16(s, size, errors,
696 errorhandler=None,
697 allow_surrogates=True):
698 return unicode_encode_utf_16_helper(s, size, errors, errorhandler,
699 allow_surrogates, "native",
700 'utf-16-' + BYTEORDER2)
701
702 def py3k_unicode_encode_utf_16_be(s, size, errors,
703 errorhandler=None,
704 allow_surrogates=True):
705 return unicode_encode_utf_16_helper(s, size, errors, errorhandler,
706 allow_surrogates, "big",
707 'utf-16-be')
708
709 def py3k_unicode_encode_utf_16_le(s, size, errors,
710 errorhandler=None,
711 allow_surrogates=True):
712 return unicode_encode_utf_16_helper(s, size, errors, errorhandler,
713 allow_surrogates, "little",
714 'utf-16-le')
715
716
717 # ____________________________________________________________
718 # utf-32 (not used in PyPy any more)
719
720 def str_decode_utf_32(s, size, errors, final=True,
721 errorhandler=None):
722 result, length, byteorder = str_decode_utf_32_helper(
723 s, size, errors, final, errorhandler, "native")
724 return result, length
725
726 def str_decode_utf_32_be(s, size, errors, final=True,
727 errorhandler=None):
728 result, length, byteorder = str_decode_utf_32_helper(
729 s, size, errors, final, errorhandler, "big")
730 return result, length
731
732 def str_decode_utf_32_le(s, size, errors, final=True,
733 errorhandler=None):
734 result, length, byteorder = str_decode_utf_32_helper(
735 s, size, errors, final, errorhandler, "little")
736 return result, length
737
738 def py3k_str_decode_utf_32(s, size, errors, final=True,
739 errorhandler=None):
740 result, length, byteorder = str_decode_utf_32_helper(
741 s, size, errors, final, errorhandler, "native",
742 'utf-32-' + BYTEORDER2, allow_surrogates=False)
743 return result, length
744
745 def py3k_str_decode_utf_32_be(s, size, errors, final=True,
746 errorhandler=None):
747 result, length, byteorder = str_decode_utf_32_helper(
748 s, size, errors, final, errorhandler, "big",
749 'utf-32-be', allow_surrogates=False)
750 return result, length
751
752 def py3k_str_decode_utf_32_le(s, size, errors, final=True,
753 errorhandler=None):
754 result, length, byteorder = str_decode_utf_32_helper(
755 s, size, errors, final, errorhandler, "little",
756 'utf-32-le', allow_surrogates=False)
757 return result, length
758
759 BOM32_DIRECT = intmask(0x0000FEFF)
760 BOM32_REVERSE = intmask(0xFFFE0000)
761
762 def str_decode_utf_32_helper(s, size, errors, final=True,
763 errorhandler=None,
764 byteorder="native",
765 public_encoding_name='utf32',
766 allow_surrogates=True):
767 if errorhandler is None:
768 errorhandler = default_unicode_error_decode
769 bo = 0
770
771 if BYTEORDER == 'little':
772 iorder = [0, 1, 2, 3]
773 else:
774 iorder = [3, 2, 1, 0]
775
776 # Check for BOM marks (U+FEFF) in the input and adjust current
777 # byte order setting accordingly. In native mode, the leading BOM
778 # mark is skipped, in all other modes, it is copied to the output
779 # stream as-is (giving a ZWNBSP character).
780 pos = 0
781 if byteorder == 'native':
782 if size >= 4:
783 bom = intmask(
784 (ord(s[iorder[3]]) << 24) | (ord(s[iorder[2]]) << 16) |
785 (ord(s[iorder[1]]) << 8) | ord(s[iorder[0]]))
786 if BYTEORDER == 'little':
787 if bom == BOM32_DIRECT:
788 pos += 4
789 bo = -1
790 elif bom == BOM32_REVERSE:
791 pos += 4
792 bo = 1
793 else:
794 if bom == BOM32_DIRECT:
795 pos += 4
796 bo = 1
797 elif bom == BOM32_REVERSE:
798 pos += 4
799 bo = -1
800 elif byteorder == 'little':
801 bo = -1
802 else:
803 bo = 1
804 if size == 0:
805 return u'', 0, bo
806 if bo == -1:
807 # force little endian
808 iorder = [0, 1, 2, 3]
809
810 elif bo == 1:
811 # force big endian
812 iorder = [3, 2, 1, 0]
813
814 result = UnicodeBuilder(size // 4)
815
816 while pos < size:
817 # remaining bytes at the end? (size should be divisible by 4)
818 if len(s) - pos < 4:
819 if not final:
820 break
821 r, pos = errorhandler(errors, public_encoding_name,
822 "truncated data",
823 s, pos, len(s))
824 result.append(r)
825 if len(s) - pos < 4:
826 break
827 continue
828 ch = ((ord(s[pos + iorder[3]]) << 24) | (ord(s[pos + iorder[2]]) << 16) |
829 (ord(s[pos + iorder[1]]) << 8) | ord(s[pos + iorder[0]]))
830 if not allow_surrogates and 0xD800 <= ch <= 0xDFFFF:
831 r, pos = errorhandler(errors, public_encoding_name,
832 "code point in surrogate code point "
833 "range(0xd800, 0xe000)",
834 s, pos, len(s))
835 result.append(r)
836 elif ch >= 0x110000:
837 r, pos = errorhandler(errors, public_encoding_name,
838 "codepoint not in range(0x110000)",
839 s, pos, len(s))
840 result.append(r)
841 continue
842
843 if MAXUNICODE < 65536 and ch >= 0x10000:
844 ch -= 0x10000L
845 result.append(unichr(0xD800 + (ch >> 10)))
846 result.append(unichr(0xDC00 + (ch & 0x03FF)))
847 else:
848 result.append(UNICHR(ch))
849 pos += 4
850 return result.build(), pos, bo
851
852 def _STORECHAR32(result, CH, byteorder):
853 c0 = chr(((CH) >> 24) & 0xff)
854 c1 = chr(((CH) >> 16) & 0xff)
855 c2 = chr(((CH) >> 8) & 0xff)
856 c3 = chr((CH) & 0xff)
857 if byteorder == 'little':
858 result.append(c3)
859 result.append(c2)
860 result.append(c1)
861 result.append(c0)
862 else:
863 result.append(c0)
864 result.append(c1)
865 result.append(c2)
866 result.append(c3)
867
868 def unicode_encode_utf_32_helper(s, size, errors,
869 errorhandler=None,
870 allow_surrogates=True,
871 byteorder='little',
872 public_encoding_name='utf32'):
873 if errorhandler is None:
874 errorhandler = default_unicode_error_encode
875 if size == 0:
876 if byteorder == 'native':
877 result = StringBuilder(4)
878 _STORECHAR32(result, 0xFEFF, BYTEORDER)
879 return result.build()
880 return ""
881
882 result = StringBuilder(size * 4 + 4)
883 if byteorder == 'native':
884 _STORECHAR32(result, 0xFEFF, BYTEORDER)
885 byteorder = BYTEORDER
886
887 pos = 0
888 while pos < size:
889 ch = ord(s[pos])
890 pos += 1
891 ch2 = 0
892 if not allow_surrogates and 0xD800 <= ch < 0xE000:
893 ru, rs, pos = errorhandler(errors, public_encoding_name,
894 'surrogates not allowed',
895 s, pos-1, pos)
896 if rs is not None:
897 # py3k only
898 if len(rs) % 4 != 0:
899 errorhandler('strict', public_encoding_name,
900 'surrogates not allowed',
901 s, pos-1, pos)
902 result.append(rs)
903 continue
904 for ch in ru:
905 if ord(ch) < 0xD800:
906 _STORECHAR32(result, ord(ch), byteorder)
907 else:
908 errorhandler('strict', public_encoding_name,
909 'surrogates not allowed',
910 s, pos-1, pos)
911 continue
912 if 0xD800 <= ch < 0xDC00 and MAXUNICODE < 65536 and pos < size:
913 ch2 = ord(s[pos])
914 if 0xDC00 <= ch2 < 0xE000:
915 ch = (((ch & 0x3FF)<<10) | (ch2 & 0x3FF)) + 0x10000;
916 pos += 1
917 _STORECHAR32(result, ch, byteorder)
918
919 return result.build()
920
921 def unicode_encode_utf_32(s, size, errors,
922 errorhandler=None, allow_surrogates=True):
923 return unicode_encode_utf_32_helper(s, size, errors, errorhandler,
924 allow_surrogates, "native")
925
926 def unicode_encode_utf_32_be(s, size, errors,
927 errorhandler=None, allow_surrogates=True):
928 return unicode_encode_utf_32_helper(s, size, errors, errorhandler,
929 allow_surrogates, "big")
930
931 def unicode_encode_utf_32_le(s, size, errors,
932 errorhandler=None, allow_surrogates=True):
933 return unicode_encode_utf_32_helper(s, size, errors, errorhandler,
934 allow_surrogates, "little")
935
936 def py3k_unicode_encode_utf_32(s, size, errors,
937 errorhandler=None, allow_surrogates=True):
938 return unicode_encode_utf_32_helper(s, size, errors, errorhandler,
939 allow_surrogates, "native",
940 'utf-32-' + BYTEORDER2)
941
942 def py3k_unicode_encode_utf_32_be(s, size, errors,
943 errorhandler=None, allow_surrogates=True):
944 return unicode_encode_utf_32_helper(s, size, errors, errorhandler,
945 allow_surrogates, "big",
946 'utf-32-be')
947
948 def py3k_unicode_encode_utf_32_le(s, size, errors,
949 errorhandler=None, allow_surrogates=True):
950 return unicode_encode_utf_32_helper(s, size, errors, errorhandler,
951 allow_surrogates, "little",
952 'utf-32-le')
953
954
955 # ____________________________________________________________
956 # utf-7
957
958 # Three simple macros defining base-64
959
960 def _utf7_IS_BASE64(oc):
961 "Is c a base-64 character?"
962 c = chr(oc)
963 return c.isalnum() or c == '+' or c == '/'
964 def _utf7_TO_BASE64(n):
965 "Returns the base-64 character of the bottom 6 bits of n"
966 return "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"[n & 0x3f]
967 def _utf7_FROM_BASE64(c):
968 "given that c is a base-64 character, what is its base-64 value?"
969 if c >= 'a':
970 return ord(c) - 71
971 elif c >= 'A':
972 return ord(c) - 65
973 elif c >= '0':
974 return ord(c) + 4
975 elif c == '+':
976 return 62
977 else: # c == '/'
978 return 63
979
980 def _utf7_DECODE_DIRECT(oc):
981 return oc <= 127 and oc != ord('+')
982
983 # The UTF-7 encoder treats ASCII characters differently according to
984 # whether they are Set D, Set O, Whitespace, or special (i.e. none of
985 # the above). See RFC2152. This array identifies these different
986 # sets:
987 # 0 : "Set D"
988 # alphanumeric and '(),-./:?
989 # 1 : "Set O"
990 # !"#$%&*;<=>@[]^_`{|}
991 # 2 : "whitespace"
992 # ht nl cr sp
993 # 3 : special (must be base64 encoded)
994 # everything else (i.e. +\~ and non-printing codes 0-8 11-12 14-31 127)
995
996 utf7_category = [
997 # nul soh stx etx eot enq ack bel bs ht nl vt np cr so si
998 3, 3, 3, 3, 3, 3, 3, 3, 3, 2, 2, 3, 3, 2, 3, 3,
999 # dle dc1 dc2 dc3 dc4 nak syn etb can em sub esc fs gs rs us
1000 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3,
1001 # sp ! " # $ % & ' ( ) * + , - . /
1002 2, 1, 1, 1, 1, 1, 1, 0, 0, 0, 1, 3, 0, 0, 0, 0,
1003 # 0 1 2 3 4 5 6 7 8 9 : ; < = > ?
1004 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 0,
1005 # @ A B C D E F G H I J K L M N O
1006 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
1007 # P Q R S T U V W X Y Z [ \ ] ^ _
1008 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 3, 1, 1, 1,
1009 # ` a b c d e f g h i j k l m n o
1010 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
1011 # p q r s t u v w x y z { | } ~ del
1012 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 3, 3,
1013 ]
1014
1015 # ENCODE_DIRECT: this character should be encoded as itself. The
1016 # answer depends on whether we are encoding set O as itself, and also
1017 # on whether we are encoding whitespace as itself. RFC2152 makes it
1018 # clear that the answers to these questions vary between
1019 # applications, so this code needs to be flexible.
1020
1021 def _utf7_ENCODE_DIRECT(oc, directO, directWS):
1022 return(oc < 128 and oc > 0 and
1023 (utf7_category[oc] == 0 or
1024 (directWS and utf7_category[oc] == 2) or
1025 (directO and utf7_category[oc] == 1)))
1026
1027 def _utf7_ENCODE_CHAR(result, oc, base64bits, base64buffer):
1028 if MAXUNICODE > 65535 and oc >= 0x10000:
1029 # code first surrogate
1030 base64bits += 16
1031 base64buffer = (base64buffer << 16) | 0xd800 | ((oc-0x10000) >> 10)
1032 while base64bits >= 6:
1033 result.append(_utf7_TO_BASE64(base64buffer >> (base64bits-6)))
1034 base64bits -= 6
1035 # prepare second surrogate
1036 oc = 0xDC00 | ((oc-0x10000) & 0x3FF)
1037 base64bits += 16
1038 base64buffer = (base64buffer << 16) | oc
1039 while base64bits >= 6:
1040 result.append(_utf7_TO_BASE64(base64buffer >> (base64bits-6)))
1041 base64bits -= 6
1042 return base64bits, base64buffer
1043
1044 def str_decode_utf_7(s, size, errors, final=False,
1045 errorhandler=None):
1046 if errorhandler is None:
1047 errorhandler = default_unicode_error_decode
1048 if size == 0:
1049 return u'', 0
1050
1051 inShift = False
1052 base64bits = 0
1053 base64buffer = 0
1054 surrogate = 0
1055
1056 result = UnicodeBuilder(size)
1057 pos = 0
1058 shiftOutStartPos = 0
1059 startinpos = 0
1060 while pos < size:
1061 ch = s[pos]
1062
1063 if inShift: # in a base-64 section
1064 if _utf7_IS_BASE64(ord(ch)): #consume a base-64 character
1065 base64buffer = (base64buffer << 6) | _utf7_FROM_BASE64(ch)
1066 base64bits += 6
1067 pos += 1
1068
1069 if base64bits >= 16:
1070 # enough bits for a UTF-16 value
1071 outCh = base64buffer >> (base64bits - 16)
1072 base64bits -= 16
1073 base64buffer &= (1 << base64bits) - 1 # clear high bits
1074 assert outCh <= 0xffff
1075 if surrogate:
1076 # expecting a second surrogate
1077 if outCh >= 0xDC00 and outCh <= 0xDFFF:
1078 if MAXUNICODE < 65536:
1079 result.append(unichr(surrogate))
1080 result.append(unichr(outCh))
1081 else:
1082 result.append(
1083 UNICHR((((surrogate & 0x3FF)<<10) |
1084 (outCh & 0x3FF)) + 0x10000))
1085 surrogate = 0
1086 continue
1087 else:
1088 result.append(unichr(surrogate))
1089 surrogate = 0
1090 # Not done with outCh: falls back to next line
1091 if outCh >= 0xD800 and outCh <= 0xDBFF:
1092 # first surrogate
1093 surrogate = outCh
1094 else:
1095 result.append(unichr(outCh))
1096
1097 else:
1098 # now leaving a base-64 section
1099 inShift = False
1100
1101 if base64bits > 0: # left-over bits
1102 if base64bits >= 6:
1103 # We've seen at least one base-64 character
1104 pos += 1
1105 msg = "partial character in shift sequence"
1106 res, pos = errorhandler(errors, 'utf7',
1107 msg, s, pos-1, pos)
1108 result.append(res)
1109 continue
1110 else:
1111 # Some bits remain; they should be zero
1112 if base64buffer != 0:
1113 pos += 1
1114 msg = "non-zero padding bits in shift sequence"
1115 res, pos = errorhandler(errors, 'utf7',
1116 msg, s, pos-1, pos)
1117 result.append(res)
1118 continue
1119
1120 if surrogate and _utf7_DECODE_DIRECT(ord(ch)):
1121 result.append(unichr(surrogate))
1122 surrogate = 0
1123
1124 if ch == '-':
1125 # '-' is absorbed; other terminating characters are
1126 # preserved
1127 pos += 1
1128
1129 elif ch == '+':
1130 startinpos = pos
1131 pos += 1 # consume '+'
1132 if pos < size and s[pos] == '-': # '+-' encodes '+'
1133 pos += 1
1134 result.append(u'+')
1135 else: # begin base64-encoded section
1136 inShift = 1
1137 surrogate = 0
1138 shiftOutStartPos = result.getlength()
1139 base64bits = 0
1140 base64buffer = 0
1141
1142 elif _utf7_DECODE_DIRECT(ord(ch)): # character decodes at itself
1143 result.append(unichr(ord(ch)))
1144 pos += 1
1145 else:
1146 startinpos = pos
1147 pos += 1
1148 msg = "unexpected special character"
1149 res, pos = errorhandler(errors, 'utf7', msg, s, pos-1, pos)
1150 result.append(res)
1151
1152 # end of string
1153 final_length = result.getlength()
1154 if inShift and final: # in shift sequence, no more to follow
1155 # if we're in an inconsistent state, that's an error
1156 inShift = 0
1157 if (surrogate or
1158 base64bits >= 6 or
1159 (base64bits > 0 and base64buffer != 0)):
1160 msg = "unterminated shift sequence"
1161 res, pos = errorhandler(errors, 'utf7', msg, s, shiftOutStartPos, pos)
1162 result.append(res)
1163 final_length = result.getlength()
1164 elif inShift:
1165 pos = startinpos
1166 final_length = shiftOutStartPos # back off output
1167
1168 assert final_length >= 0
1169 return result.build()[:final_length], pos
1170
1171 def unicode_encode_utf_7(s, size, errors, errorhandler=None):
1172 if size == 0:
1173 return ''
1174 result = StringBuilder(size)
1175
1176 encodeSetO = encodeWhiteSpace = False
1177
1178 inShift = False
1179 base64bits = 0
1180 base64buffer = 0
1181
1182 pos = 0
1183 while pos < size:
1184 ch = s[pos]
1185 oc = ord(ch)
1186 if not inShift:
1187 if ch == u'+':
1188 result.append('+-')
1189 elif _utf7_ENCODE_DIRECT(oc, not encodeSetO, not encodeWhiteSpace):
1190 result.append(chr(oc))
1191 else:
1192 result.append('+')
1193 inShift = True
1194 base64bits, base64buffer = _utf7_ENCODE_CHAR(
1195 result, oc, base64bits, base64buffer)
1196 else:
1197 if _utf7_ENCODE_DIRECT(oc, not encodeSetO, not encodeWhiteSpace):
1198 # shifting out
1199 if base64bits: # output remaining bits
1200 result.append(_utf7_TO_BASE64(base64buffer << (6-base64bits)))
1201 base64buffer = 0
1202 base64bits = 0
1203
1204 inShift = False
1205 ## Characters not in the BASE64 set implicitly unshift the
1206 ## sequence so no '-' is required, except if the character is
1207 ## itself a '-'
1208 if _utf7_IS_BASE64(oc) or ch == u'-':
1209 result.append('-')
1210 result.append(chr(oc))
1211 else:
1212 base64bits, base64buffer = _utf7_ENCODE_CHAR(
1213 result, oc, base64bits, base64buffer)
1214 pos += 1
1215
1216 if base64bits:
1217 result.append(_utf7_TO_BASE64(base64buffer << (6 - base64bits)))
1218 if inShift:
1219 result.append('-')
1220
1221 return result.build()
1222
1223 # ____________________________________________________________
1224 # ascii and latin-1
1225
1226 def str_decode_latin_1(s, size, errors, final=False,
1227 errorhandler=None):
1228 # latin1 is equivalent to the first 256 ordinals in Unicode.
1229 pos = 0
1230 result = UnicodeBuilder(size)
1231 while pos < size:
1232 result.append(unichr(ord(s[pos])))
1233 pos += 1
1234 return result.build(), pos
1235
1236
1237 def str_decode_ascii(s, size, errors, final=False,
1238 errorhandler=None):
1239 if errorhandler is None:
1240 errorhandler = default_unicode_error_decode
1241 # ASCII is equivalent to the first 128 ordinals in Unicode.
1242 result = UnicodeBuilder(size)
1243 pos = 0
1244 while pos < size:
1245 c = s[pos]
1246 if ord(c) < 128:
1247 result.append(unichr(ord(c)))
1248 pos += 1
1249 else:
1250 r, pos = errorhandler(errors, "ascii", "ordinal not in range(128)",
1251 s, pos, pos + 1)
1252 result.append(r)
1253 return result.build(), pos
1254
1255 # An elidable version, for a subset of the cases
1256 @jit.elidable
1257 def fast_str_decode_ascii(s):
1258 result = UnicodeBuilder(len(s))
1259 for c in s:
1260 if ord(c) >= 128:
1261 raise ValueError
1262 result.append(unichr(ord(c)))
1263 return result.build()
1264
1265
1266 def unicode_encode_ucs1_helper(p, size, errors,
1267 errorhandler=None, limit=256):
1268 if errorhandler is None:
1269 errorhandler = default_unicode_error_encode
1270 if limit == 256:
1271 reason = "ordinal not in range(256)"
1272 encoding = "latin-1"
1273 else:
1274 reason = "ordinal not in range(128)"
1275 encoding = "ascii"
1276
1277 if size == 0:
1278 return ''
1279 result = StringBuilder(size)
1280 pos = 0
1281 while pos < size:
1282 ch = p[pos]
1283
1284 if ord(ch) < limit:
1285 result.append(chr(ord(ch)))
1286 pos += 1
1287 else:
1288 # startpos for collecting unencodable chars
1289 collstart = pos
1290 collend = pos+1
1291 while collend < len(p) and ord(p[collend]) >= limit:
1292 collend += 1
1293 ru, rs, pos = errorhandler(errors, encoding, reason, p,
1294 collstart, collend)
1295 if rs is not None:
1296 # py3k only
1297 result.append(rs)
1298 continue
1299 for ch in ru:
1300 if ord(ch) < limit:
1301 result.append(chr(ord(ch)))
1302 else:
1303 errorhandler("strict", encoding, reason, p,
1304 collstart, collend)
1305
1306 return result.build()
1307
1308 def unicode_encode_latin_1(p, size, errors, errorhandler=None):
1309 res = unicode_encode_ucs1_helper(p, size, errors, errorhandler, 256)
1310 return res
1311
1312 def unicode_encode_ascii(p, size, errors, errorhandler=None):
1313 res = unicode_encode_ucs1_helper(p, size, errors, errorhandler, 128)
1314 return res
1315
1316 # ____________________________________________________________
1317 # Charmap
1318
1319 ERROR_CHAR = u'\ufffe'
1320
1321 @specialize.argtype(5)
1322 def str_decode_charmap(s, size, errors, final=False,
1323 errorhandler=None, mapping=None):
1324 "mapping can be a rpython dictionary, or a dict-like object."
1325
1326 # Default to Latin-1
1327 if mapping is None:
1328 return str_decode_latin_1(s, size, errors, final=final,
1329 errorhandler=errorhandler)
1330 if errorhandler is None:
1331 errorhandler = default_unicode_error_decode
1332 if size == 0:
1333 return u'', 0
1334
1335 pos = 0
1336 result = UnicodeBuilder(size)
1337 while pos < size:
1338 ch = s[pos]
1339
1340 c = mapping.get(ch, ERROR_CHAR)
1341 if c == ERROR_CHAR:
1342 r, pos = errorhandler(errors, "charmap",
1343 "character maps to <undefined>",
1344 s, pos, pos + 1)
1345 result.append(r)
1346 continue
1347 result.append(c)
1348 pos += 1
1349 return result.build(), pos
1350
1351 def unicode_encode_charmap(s, size, errors, errorhandler=None,
1352 mapping=None):
1353 if mapping is None:
1354 return unicode_encode_latin_1(s, size, errors,
1355 errorhandler=errorhandler)
1356
1357 if errorhandler is None:
1358 errorhandler = default_unicode_error_encode
1359
1360 if size == 0:
1361 return ''
1362 result = StringBuilder(size)
1363 pos = 0
1364 while pos < size:
1365 ch = s[pos]
1366
1367 c = mapping.get(ch, '')
1368 if len(c) == 0:
1369 # collect all unencodable chars. Important for narrow builds.
1370 collend = pos + 1
1371 while collend < size and mapping.get(s[collend], '') == '':
1372 collend += 1
1373 ru, rs, pos = errorhandler(errors, "charmap",
1374 "character maps to <undefined>",
1375 s, pos, collend)
1376 if rs is not None:
1377 # py3k only
1378 result.append(rs)
1379 continue
1380 for ch2 in ru:
1381 c2 = mapping.get(ch2, '')
1382 if len(c2) == 0:
1383 errorhandler(
1384 "strict", "charmap",
1385 "character maps to <undefined>",
1386 s, pos, pos + 1)
1387 result.append(c2)
1388 continue
1389 result.append(c)
1390 pos += 1
1391 return result.build()
1392
1393 # ____________________________________________________________
1394 # Unicode escape
1395
1396 hexdigits = "0123456789ABCDEFabcdef"
1397
1398 def hexescape(builder, s, pos, digits,
1399 encoding, errorhandler, message, errors):
1400 chr = 0
1401 if pos + digits > len(s):
1402 endinpos = pos
1403 while endinpos < len(s) and s[endinpos] in hexdigits:
1404 endinpos += 1
1405 res, pos = errorhandler(errors, encoding,
1406 message, s, pos-2, endinpos)
1407 builder.append(res)
1408 else:
1409 try:
1410 chr = r_uint(int(s[pos:pos+digits], 16))
1411 except ValueError:
1412 endinpos = pos
1413 while s[endinpos] in hexdigits:
1414 endinpos += 1
1415 res, pos = errorhandler(errors, encoding,
1416 message, s, pos-2, endinpos)
1417 builder.append(res)
1418 else:
1419 # when we get here, chr is a 32-bit unicode character
1420 if chr <= MAXUNICODE:
1421 builder.append(UNICHR(chr))
1422 pos += digits
1423
1424 elif chr <= 0x10ffff:
1425 chr -= 0x10000L
1426 builder.append(unichr(0xD800 + (chr >> 10)))
1427 builder.append(unichr(0xDC00 + (chr & 0x03FF)))
1428 pos += digits
1429 else:
1430 message = "illegal Unicode character"
1431 res, pos = errorhandler(errors, encoding,
1432 message, s, pos-2, pos+digits)
1433 builder.append(res)
1434 return pos
1435
1436 def str_decode_unicode_escape(s, size, errors, final=False,
1437 errorhandler=None,
1438 unicodedata_handler=None):
1439 if errorhandler is None:
1440 errorhandler = default_unicode_error_decode
1441
1442 if size == 0:
1443 return u'', 0
1444
1445 builder = UnicodeBuilder(size)
1446 pos = 0
1447 while pos < size:
1448 ch = s[pos]
1449
1450 # Non-escape characters are interpreted as Unicode ordinals
1451 if ch != '\\':
1452 builder.append(unichr(ord(ch)))
1453 pos += 1
1454 continue
1455
1456 # - Escapes
1457 pos += 1
1458 if pos >= size:
1459 message = "\\ at end of string"
1460 res, pos = errorhandler(errors, "unicodeescape",
1461 message, s, pos-1, size)
1462 builder.append(res)
1463 continue
1464
1465 ch = s[pos]
1466 pos += 1
1467 # \x escapes
1468 if ch == '\n': pass
1469 elif ch == '\\': builder.append(u'\\')
1470 elif ch == '\'': builder.append(u'\'')
1471 elif ch == '\"': builder.append(u'\"')
1472 elif ch == 'b' : builder.append(u'\b')
1473 elif ch == 'f' : builder.append(u'\f')
1474 elif ch == 't' : builder.append(u'\t')
1475 elif ch == 'n' : builder.append(u'\n')
1476 elif ch == 'r' : builder.append(u'\r')
1477 elif ch == 'v' : builder.append(u'\v')
1478 elif ch == 'a' : builder.append(u'\a')
1479 elif '0' <= ch <= '7':
1480 x = ord(ch) - ord('0')
1481 if pos < size:
1482 ch = s[pos]
1483 if '0' <= ch <= '7':
1484 pos += 1
1485 x = (x<<3) + ord(ch) - ord('0')
1486 if pos < size:
1487 ch = s[pos]
1488 if '0' <= ch <= '7':
1489 pos += 1
1490 x = (x<<3) + ord(ch) - ord('0')
1491 builder.append(unichr(x))
1492 # hex escapes
1493 # \xXX
1494 elif ch == 'x':
1495 digits = 2
1496 message = "truncated \\xXX escape"
1497 pos = hexescape(builder, s, pos, digits,
1498 "unicodeescape", errorhandler, message, errors)
1499
1500 # \uXXXX
1501 elif ch == 'u':
1502 digits = 4
1503 message = "truncated \\uXXXX escape"
1504 pos = hexescape(builder, s, pos, digits,
1505 "unicodeescape", errorhandler, message, errors)
1506
1507 # \UXXXXXXXX
1508 elif ch == 'U':
1509 digits = 8
1510 message = "truncated \\UXXXXXXXX escape"
1511 pos = hexescape(builder, s, pos, digits,
1512 "unicodeescape", errorhandler, message, errors)
1513
1514 # \N{name}
1515 elif ch == 'N' and unicodedata_handler is not None:
1516 message = "malformed \\N character escape"
1517 look = pos
1518
1519 if look < size and s[look] == '{':
1520 # look for the closing brace
1521 while look < size and s[look] != '}':
1522 look += 1
1523 if look < size and s[look] == '}':
1524 # found a name. look it up in the unicode database
1525 message = "unknown Unicode character name"
1526 name = s[pos+1:look]
1527 code = unicodedata_handler.call(name)
1528 if code < 0:
1529 res, pos = errorhandler(errors, "unicodeescape",
1530 message, s, pos-1, look+1)
1531 builder.append(res)
1532 continue
1533 pos = look + 1
1534 if code <= MAXUNICODE:
1535 builder.append(UNICHR(code))
1536 else:
1537 code -= 0x10000L
1538 builder.append(unichr(0xD800 + (code >> 10)))
1539 builder.append(unichr(0xDC00 + (code & 0x03FF)))
1540 else:
1541 res, pos = errorhandler(errors, "unicodeescape",
1542 message, s, pos-1, look+1)
1543 builder.append(res)
1544 else:
1545 res, pos = errorhandler(errors, "unicodeescape",
1546 message, s, pos-1, look+1)
1547 builder.append(res)
1548 else:
1549 builder.append(u'\\')
1550 builder.append(unichr(ord(ch)))
1551
1552 return builder.build(), pos
1553
1554 def make_unicode_escape_function(pass_printable=False, unicode_output=False,
1555 quotes=False, prefix=None):
1556 # Python3 has two similar escape functions: One to implement
1557 # encode('unicode_escape') and which outputs bytes, and unicode.__repr__
1558 # which outputs unicode. They cannot share RPython code, so we generate
1559 # them with the template below.
1560 # Python2 does not really need this, but it reduces diffs between branches.
1561
1562 if unicode_output:
1563 STRING_BUILDER = UnicodeBuilder
1564 STR = unicode
1565 CHR = UNICHR
1566 else:
1567 STRING_BUILDER = StringBuilder
1568 STR = str
1569 CHR = chr
1570
1571 def unicode_escape(s, size, errors, errorhandler=None):
1572 # errors and errorhandler are not used: this function cannot cause
1573 # Unicode errors
1574 return _unicode_escape(s, size)
1575
1576 @jit.elidable
1577 def _unicode_escape(s, size):
1578 result = STRING_BUILDER(size)
1579
1580 if quotes:
1581 if prefix:
1582 result.append(STR(prefix))
1583 if s.find(STR("'")) != -1 and s.find(STR('"')) == -1:
1584 quote = ord('\"')
1585 result.append(STR('"'))
1586 else:
1587 quote = ord('\'')
1588 result.append(STR('\''))
1589 else:
1590 quote = 0
1591
1592 if size == 0:
1593 return STR('')
1594
1595 pos = 0
1596 while pos < size:
1597 ch = s[pos]
1598 oc = ord(ch)
1599
1600 # Escape quotes
1601 if quotes and (oc == quote or ch == STR('\\')):
1602 result.append(STR('\\'))
1603 result.append(CHR(oc))
1604 pos += 1
1605 continue
1606
1607 # The following logic is enabled only if MAXUNICODE == 0xffff, or
1608 # for testing on top of a host Python where sys.maxunicode == 0xffff
1609 if ((MAXUNICODE < 65536 or is_narrow_host())
1610 and 0xD800 <= oc < 0xDC00 and pos + 1 < size):
1611 # Map UTF-16 surrogate pairs to Unicode \UXXXXXXXX escapes.
1612 oc2 = ord(s[pos + 1])
1613
1614 if 0xDC00 <= oc2 <= 0xDFFF:
1615 ucs = (((oc & 0x03FF) << 10) | (oc2 & 0x03FF)) + 0x00010000
1616 char_escape_helper(result, ucs)
1617 pos += 2
1618 continue
1619 # Fall through: isolated surrogate, process ch/oc as-is below
1620
1621 # Map special whitespace to '\t', \n', '\r'
1622 if ch == STR('\t'):
1623 result.append(STR('\\t'))
1624 elif ch == STR('\n'):
1625 result.append(STR('\\n'))
1626 elif ch == STR('\r'):
1627 result.append(STR('\\r'))
1628 elif ch == STR('\\'):
1629 result.append(STR('\\\\'))
1630
1631 # Map non-printable or non-ascii to '\xhh' or '\uhhhh'
1632 elif pass_printable and not (oc <= 0x10ffff and unicodedb.isprintable(oc)):
1633 char_escape_helper(result, oc)
1634 elif not pass_printable and (oc < 32 or oc >= 0x7F):
1635 char_escape_helper(result, oc)
1636
1637 # Copy everything else as-is
1638 else:
1639 result.append(CHR(oc))
1640 pos += 1
1641
1642 if quotes:
1643 result.append(CHR(quote))
1644 return result.build()
1645
1646 TABLE = STR('0123456789abcdef')
1647
1648 def char_escape_helper(result, char):
1649 if char >= 0x10000 or char < 0:
1650 result.append(STR("\\U"))
1651 zeros = 8
1652 elif char >= 0x100:
1653 result.append(STR("\\u"))
1654 zeros = 4
1655 else:
1656 result.append(STR("\\x"))
1657 zeros = 2
1658 for i in range(zeros-1, -1, -1):
1659 result.append(TABLE[(char >> (4 * i)) & 0x0f])
1660
1661 return unicode_escape, char_escape_helper
1662
1663 # This function is also used by _codecs/interp_codecs.py
1664 (unicode_encode_unicode_escape, raw_unicode_escape_helper
1665 ) = make_unicode_escape_function()
1666 (_, raw_unicode_escape_helper_unicode
1667 ) = make_unicode_escape_function(unicode_output=True)
1668
1669 # ____________________________________________________________
1670 # Raw unicode escape
1671
1672 def str_decode_raw_unicode_escape(s, size, errors, final=False,
1673 errorhandler=None):
1674 if errorhandler is None:
1675 errorhandler = default_unicode_error_decode
1676 if size == 0:
1677 return u'', 0
1678
1679 result = UnicodeBuilder(size)
1680 pos = 0
1681 while pos < size:
1682 ch = s[pos]
1683
1684 # Non-escape characters are interpreted as Unicode ordinals
1685 if ch != '\\':
1686 result.append(unichr(ord(ch)))
1687 pos += 1
1688 continue
1689
1690 # \u-escapes are only interpreted iff the number of leading
1691 # backslashes is odd
1692 bs = pos
1693 while pos < size:
1694 pos += 1
1695 if pos == size or s[pos] != '\\':
1696 break
1697 result.append(u'\\')
1698
1699 # we have a backslash at the end of the string, stop here
1700 if pos >= size:
1701 result.append(u'\\')
1702 break
1703
1704 if ((pos - bs) & 1 == 0 or
1705 pos >= size or
1706 (s[pos] != 'u' and s[pos] != 'U')):
1707 result.append(u'\\')
1708 result.append(unichr(ord(s[pos])))
1709 pos += 1
1710 continue
1711
1712 digits = 4 if s[pos] == 'u' else 8
1713 message = "truncated \\uXXXX"
1714 pos += 1
1715 pos = hexescape(result, s, pos, digits,
1716 "rawunicodeescape", errorhandler, message, errors)
1717
1718 return result.build(), pos
1719
1720 def unicode_encode_raw_unicode_escape(s, size, errors, errorhandler=None):
1721 # errorhandler is not used: this function cannot cause Unicode errors
1722 if size == 0:
1723 return ''
1724 result = StringBuilder(size)
1725 pos = 0
1726 while pos < size:
1727 oc = ord(s[pos])
1728
1729 if MAXUNICODE < 65536 and 0xD800 <= oc < 0xDC00 and pos + 1 < size:
1730 # Map UTF-16 surrogate pairs to Unicode \UXXXXXXXX escapes.
1731 # Peek at pos+1 without advancing so pos never needs to be
1732 oc2 = ord(s[pos + 1])
1733
1734 if 0xDC00 <= oc2 <= 0xDFFF:
1735 ucs = (((oc & 0x03FF) << 10) | (oc2 & 0x03FF)) + 0x00010000
1736 raw_unicode_escape_helper(result, ucs)
1737 pos += 2
1738 continue
1739 # Fall through: isolated surrogate, process oc as-is below
1740
1741 if oc < 0x100:
1742 result.append(chr(oc))
1743 else:
1744 raw_unicode_escape_helper(result, oc)
1745 pos += 1
1746
1747 return result.build()
1748
1749 # ____________________________________________________________
1750 # unicode-internal
1751
1752 def str_decode_unicode_internal(s, size, errors, final=False,
1753 errorhandler=None):
1754 if errorhandler is None:
1755 errorhandler = default_unicode_error_decode
1756 if size == 0:
1757 return u'', 0
1758
1759 if MAXUNICODE < 65536:
1760 unicode_bytes = 2
1761 else:
1762 unicode_bytes = 4
1763 if BYTEORDER == "little":
1764 start = 0
1765 stop = unicode_bytes
1766 step = 1
1767 else:
1768 start = unicode_bytes - 1
1769 stop = -1
1770 step = -1
1771
1772 result = UnicodeBuilder(size // unicode_bytes)
1773 pos = 0
1774 while pos < size:
1775 if pos > size - unicode_bytes:
1776 res, pos = errorhandler(errors, "unicode_internal",
1777 "truncated input",
1778 s, pos, size)
1779 result.append(res)
1780 continue
1781 t = r_uint(0)
1782 h = 0
1783 for j in range(start, stop, step):
1784 t += r_uint(ord(s[pos + j])) << (h*8)
1785 h += 1
1786 if t > MAXUNICODE:
1787 res, pos = errorhandler(errors, "unicode_internal",
1788 "unichr(%d) not in range" % (t,),
1789 s, pos, pos + unicode_bytes)
1790 result.append(res)
1791 continue
1792 result.append(UNICHR(t))
1793 pos += unicode_bytes
1794 return result.build(), pos
1795
1796 def unicode_encode_unicode_internal(s, size, errors, errorhandler=None):
1797 if size == 0:
1798 return ''
1799
1800 if MAXUNICODE < 65536:
1801 unicode_bytes = 2
1802 else:
1803 unicode_bytes = 4
1804
1805 result = StringBuilder(size * unicode_bytes)
1806 pos = 0
1807 while pos < size:
1808 oc = ord(s[pos])
1809 if MAXUNICODE < 65536:
1810 if BYTEORDER == "little":
1811 result.append(chr(oc & 0xFF))
1812 result.append(chr(oc >> 8 & 0xFF))
1813 else:
1814 result.append(chr(oc >> 8 & 0xFF))
1815 result.append(chr(oc & 0xFF))
1816 else:
1817 if BYTEORDER == "little":
1818 result.append(chr(oc & 0xFF))
1819 result.append(chr(oc >> 8 & 0xFF))
1820 result.append(chr(oc >> 16 & 0xFF))
1821 result.append(chr(oc >> 24 & 0xFF))
1822 else:
1823 result.append(chr(oc >> 24 & 0xFF))
1824 result.append(chr(oc >> 16 & 0xFF))
1825 result.append(chr(oc >> 8 & 0xFF))
1826 result.append(chr(oc & 0xFF))
1827 pos += 1
1828
1829 return result.build()
1830
1831 # ____________________________________________________________
1832 # Decimal Encoder
1833 def unicode_encode_decimal(s, size, errors, errorhandler=None):
1834 """Converts whitespace to ' ', decimal characters to their
1835 corresponding ASCII digit and all other Latin-1 characters except
1836 \0 as-is. Characters outside this range (Unicode ordinals 1-256)
1837 are treated as errors. This includes embedded NULL bytes.
1838 """
1839 if errorhandler is None:
1840 errorhandler = default_unicode_error_encode
1841 if size == 0:
1842 return ''
1843 result = StringBuilder(size)
1844 pos = 0
1845 while pos < size:
1846 ch = ord(s[pos])
1847 if unicodedb.isspace(ch):
1848 result.append(' ')
1849 pos += 1
1850 continue
1851 try:
1852 decimal = unicodedb.decimal(ch)
1853 except KeyError:
1854 pass
1855 else:
1856 result.append(chr(48 + decimal))
1857 pos += 1
1858 continue
1859 if 0 < ch < 256:
1860 result.append(chr(ch))
1861 pos += 1
1862 continue
1863 # All other characters are considered unencodable
1864 collstart = pos
1865 collend = collstart + 1
1866 while collend < size:
1867 ch = ord(s[collend])
1868 try:
1869 if (0 < ch < 256 or
1870 unicodedb.isspace(ch) or
1871 unicodedb.decimal(ch) >= 0):
1872 break
1873 except KeyError:
1874 # not a decimal
1875 pass
1876 collend += 1
1877 msg = "invalid decimal Unicode string"
1878 ru, rs, pos = errorhandler(errors, 'decimal',
1879 msg, s, collstart, collend)
1880 if rs is not None:
1881 # py3k only
1882 errorhandler('strict', 'decimal', msg, s, collstart, collend)
1883 for char in ru:
1884 ch = ord(char)
1885 if unicodedb.isspace(ch):
1886 result.append(' ')
1887 continue
1888 try:
1889 decimal = unicodedb.decimal(ch)
1890 except KeyError:
1891 pass
1892 else:
1893 result.append(chr(48 + decimal))
1894 continue
1895 if 0 < ch < 256:
1896 result.append(chr(ch))
1897 continue
1898 errorhandler('strict', 'decimal',
1899 msg, s, collstart, collend)
1900 return result.build()