Debian Codegraph @

pypy/interpreter/unicodehelper.py

raw symbols SCIP
1 import sys
2
3 from pypy.interpreter.error import OperationError, oefmt
4 from rpython.rlib.objectmodel import specialize
5 from rpython.rlib.rstring import StringBuilder
6 from rpython.rlib import rutf8
7 from rpython.rlib.rarithmetic import r_uint, intmask
8 from rpython.rtyper.lltypesystem import rffi
9 from pypy.module.unicodedata.interp_ucd import unicodedb
10 from rpython.rlib import runicode
11
12 @specialize.memo()
13 def decode_error_handler(space):
14 # Fast version of the "strict" errors handler.
15 def raise_unicode_exception_decode(errors, encoding, msg, w_s,
16 startingpos, endingpos):
17 raise OperationError(space.w_UnicodeDecodeError,
18 space.newtuple([space.newtext(encoding),
19 w_s,
20 space.newint(startingpos),
21 space.newint(endingpos),
22 space.newtext(msg)]))
23 return raise_unicode_exception_decode
24
25 @specialize.memo()
26 def make_decode_never_raise(space):
27 def decode_never_raise(errors, encoding, msg, w_s, startingpos, endingpos):
28 assert startingpos >= 0
29 assert endingpos >= 0
30 s= space.bytes_w(w_s)
31 ux = ['\ux' + hex(ord(x))[2:].upper() for x in s[startingpos:endingpos]]
32 return ''.join(ux), endingpos, 'b', '', w_s
33 return decode_never_raise
34
35 @specialize.memo()
36 def encode_error_handler(space):
37 # Fast version of the "strict" errors handler.
38 def raise_unicode_exception_encode(errors, encoding, msg, w_s,
39 startingpos, endingpos):
40 raise OperationError(space.w_UnicodeEncodeError,
41 space.newtuple([space.newtext(encoding),
42 w_s,
43 space.newint(startingpos),
44 space.newint(endingpos),
45 space.newtext(msg)]))
46 return raise_unicode_exception_encode
47
48 def default_error_encode(
49 errors, encoding, msg, w_u, startingpos, endingpos):
50 """A default handler, for tests"""
51 assert endingpos >= 0
52 if errors == 'replace':
53 return '?', endingpos
54 if errors == 'ignore':
55 return '', endingpos
56 raise ValueError
57
58 # ____________________________________________________________
59 _WIN32 = sys.platform == 'win32'
60 _MACOSX = sys.platform == 'darwin'
61
62 def fsdecode(space, w_string):
63 from pypy.module._codecs import interp_codecs
64 state = space.fromcache(interp_codecs.CodecState)
65 errorhandler=state.decode_error_handler
66 utf8 = space.bytes_w(w_string)
67 # fast path for ascii
68 if rutf8.first_non_ascii_char(utf8) < 0:
69 return space.newtext(utf8, len(utf8))
70 if _WIN32:
71 slen = len(utf8)
72 utf8, lgt, _ = str_decode_utf8(space, utf8, w_string, 'surrogateescape', True, errorhandler)
73 elif 0 and _MACOSX:
74 utf8, lgt, pos = str_decode_utf8(space, utf8, w_string, 'surrogateescape', True,
75 errorhandler, allow_surrogates=False)
76 elif space.sys.filesystemencoding is None or state.codec_need_encodings:
77 # bootstrap check: if the filesystemencoding isn't initialized
78 # or the filesystem codec is implemented in Python we cannot
79 # use it before the codecs are ready. use the locale codec
80 # instead
81 from pypy.module._codecs.locale import (
82 str_decode_locale_surrogateescape)
83 utf8, lgt = str_decode_locale_surrogateescape(utf8)
84 else:
85 from pypy.module.sys.interp_encoding import getfilesystemencoding
86 return space.call_method(w_string, 'decode',
87 getfilesystemencoding(space),
88 space.newtext('surrogateescape'))
89 return space.newtext(utf8, lgt)
90
91 def fsencode(space, w_uni):
92 from pypy.module._codecs import interp_codecs
93 state = space.fromcache(interp_codecs.CodecState)
94 if _WIN32:
95 errorhandler=state.encode_error_handler
96 utf8 = space.utf8_w(w_uni)
97 bytes = utf8_encode_utf_8(space, utf8, w_uni, 'surrogateescape', errorhandler)
98 elif 0 and _MACOSX:
99 utf8 = space.utf8_w(w_uni)
100 errorhandler=state.encode_error_handler,
101 bytes = utf8_encode_utf_8(space, utf8, w_uni, 'surrogateescape', errorhandler,
102 allow_surrogates=False)
103 elif space.sys.filesystemencoding is None or state.codec_need_encodings:
104 # bootstrap check: if the filesystemencoding isn't initialized
105 # or the filesystem codec is implemented in Python we cannot
106 # use it before the codecs are ready. use the locale codec
107 # instead
108 from pypy.module._codecs.locale import (
109 utf8_encode_locale_surrogateescape)
110 utf8 = space.utf8_w(w_uni)
111 ulen = space.len_w(w_uni)
112 if '\x00' in utf8:
113 raise oefmt(space.w_ValueError, "embedded null character")
114 bytes = utf8_encode_locale_surrogateescape(utf8, ulen)
115 else:
116 from pypy.module.sys.interp_encoding import getfilesystemencoding
117 return space.call_method(w_uni, 'encode',
118 getfilesystemencoding(space),
119 space.newtext('surrogateescape'))
120 return space.newbytes(bytes)
121
122 def encode(space, w_data, encoding=None, errors='strict'):
123 from pypy.objspace.std.unicodeobject import encode_object
124 return encode_object(space, w_data, encoding, errors)
125
126
127 # These functions take and return unwrapped rpython strings
128
129 def check_ascii_or_raise(space, string, w_s):
130 try:
131 rutf8.check_ascii(string)
132 except rutf8.CheckError as e:
133 decode_error_handler(space)('strict', 'ascii',
134 'ordinal not in range(128)', w_s,
135 e.pos, e.pos + 1)
136 assert False, "unreachable"
137
138 def check_utf8_or_raise(space, string, start=0, end=-1):
139 # Surrogates are accepted and not treated specially at all.
140 # If there happen to be two 3-bytes encoding a pair of surrogates,
141 # you still get two surrogate unicode characters in the result.
142 # These are the Python3 rules, Python2 differs
143 assert isinstance(string, str)
144 try:
145 return rutf8.check_utf8(string, True, start, end)
146 except rutf8.CheckError as e:
147 w_s = space.newbytes(string)
148 decode_error_handler(space)('strict', 'utf-8',
149 'unexpected end of data', w_s,
150 e.pos, e.pos + 1)
151
152 def str_decode_ascii(space, s, w_s, errors, final, errorhandler):
153 try:
154 rutf8.check_ascii(s)
155 return s, len(s), len(s)
156 except rutf8.CheckError:
157 return _str_decode_ascii_slowpath(space, s, w_s, errors, final, errorhandler)
158
159 def _str_decode_ascii_slowpath(space, s, w_s, errors, final, errorhandler):
160 i = 0
161 res = StringBuilder()
162 while i < len(s):
163 ch = s[i]
164 if ord(ch) > 0x7F:
165 r, i, rettype, s, w_s = errorhandler(errors, 'ascii', 'ordinal not in range(128)',
166 w_s, i, i + 1)
167 res.append(r)
168 else:
169 res.append(ch)
170 i += 1
171 ress = res.build()
172 lgt = rutf8.check_utf8(ress, True)
173 return ress, lgt, lgt
174
175 def str_decode_latin_1(space, s, w_s, errors, final, errorhandler):
176 try:
177 rutf8.check_ascii(s)
178 s_out = s
179 except rutf8.CheckError:
180 s_out = _str_decode_latin_1_slowpath(space, s)
181 return s_out, len(s), len(s)
182
183 def _str_decode_latin_1_slowpath(space, s):
184 res = StringBuilder(len(s))
185 i = 0
186 while i < len(s):
187 if ord(s[i]) > 0x7F:
188 while i < len(s) and ord(s[i]) > 0x7F:
189 rutf8.unichr_as_utf8_append(res, ord(s[i]))
190 i += 1
191 else:
192 start = i
193 end = i + 1
194 while end < len(s) and ord(s[end]) <= 0x7F:
195 end += 1
196 res.append_slice(s, start, end)
197 i = end
198 return res.build()
199
200 def utf8_encode_utf_8(space, s, w_s, errors, errorhandler, allow_surrogates=False):
201 if len(s) == 0:
202 return ''
203
204 # two fast paths
205 if allow_surrogates:
206 # already valid utf-8 with surrogates, surrogates are allowed, so just
207 # return
208 return s
209 if not rutf8.has_surrogates(s):
210 # already valid utf-8 and doesn't contain surrogates, so we don't need
211 # to do anything
212 return s
213 # annoying slow path
214 return _utf8_encode_utf_8_deal_with_surrogates(space, s, w_s, errors, errorhandler)
215
216 def _utf8_encode_utf_8_deal_with_surrogates(space, s, w_s, errors, errorhandler):
217 pos = 0
218 index = 0
219 result = StringBuilder(len(s))
220 while pos < len(s):
221 try:
222 rutf8.check_utf8(s, allow_surrogates=False, start=pos)
223 # otherwise the fast path above would have triggered
224 assert pos != 0
225 result.append_slice(s, pos, len(s))
226 break
227 except rutf8.CheckError as e:
228 end = e.pos
229 assert end >= 0
230 result.append_slice(s, pos, end)
231 index += rutf8.codepoints_in_utf8(s, start=pos, end=end)
232 pos = end
233 # Try to collect surrogates in one pass
234 # XXX do we care about performance in this case?
235 # XXX should this loop for more than one pair?
236 delta = 1
237 uchr = rutf8.codepoint_at_pos(s, pos)
238 if 0xD800 <= uchr <= 0xDBFF:
239 pos = rutf8.next_codepoint_pos(s, pos)
240 if pos < len(s):
241 uchr = rutf8.codepoint_at_pos(s, pos)
242 if 0xDC00 <= uchr <= 0xDFFF:
243 delta += 1
244 res, newindex, rettype, obj, w_obj = errorhandler(errors, 'utf-8',
245 'surrogates not allowed', w_s, index, index + delta)
246 if rettype == 'u':
247 try:
248 rutf8.check_ascii(res)
249 except rutf8.CheckError:
250 # this is a weird behaviour of CPython, but it's what happens
251 errorhandler("strict", 'utf-8', 'surrogates not allowed', w_s, index, index + delta)
252 assert 0, "unreachable"
253 s = obj
254 # It should be rare that w_s != w_obj
255 w_s = w_obj
256 result.append(res)
257 if index != newindex:
258 index = newindex
259 pos = w_obj._index_to_byte(index) # This should also be rare
260 return result.build()
261
262 def utf8_encode_latin_1(space, s, w_s, errors, errorhandler, allow_surrogates=False):
263 try:
264 rutf8.check_ascii(s)
265 return s
266 except rutf8.CheckError, e:
267 return _utf8_encode_latin_1_slowpath(space, s, w_s, e.pos, errors, errorhandler)
268
269 def _utf8_encode_latin_1_slowpath(space, s, w_s, first_non_ascii_char, errors, errorhandler):
270 result = StringBuilder(len(s))
271 result.append_slice(s, 0, first_non_ascii_char)
272 pos = index = first_non_ascii_char
273 while pos < len(s):
274 ch = rutf8.codepoint_at_pos(s, pos)
275 if ch <= 0xFF:
276 result.append(chr(ch))
277 index += 1
278 pos = rutf8.next_codepoint_pos(s, pos)
279 else:
280 startindex = index
281 pos = rutf8.next_codepoint_pos(s, pos)
282 index += 1
283 while pos < len(s) and rutf8.codepoint_at_pos(s, pos) > 0xFF:
284 pos = rutf8.next_codepoint_pos(s, pos)
285 index += 1
286 msg = "ordinal not in range(256)"
287 res, newindex, rettype, obj, w_obj = errorhandler(
288 errors, 'latin1', msg, w_s, startindex, index)
289 if rettype == 'u':
290 for cp in rutf8.Utf8StringIterator(res):
291 if cp > 0xFF:
292 errorhandler("strict", 'latin1', msg, w_s, startindex, index)
293 raise RuntimeError('error handler should not have returned')
294 result.append(chr(cp))
295 else:
296 for ch in res:
297 result.append(ch)
298 s = obj
299 # It should be rare that w_s != w_obj
300 w_s = w_obj
301 if index != newindex:
302 index = newindex
303 pos = w_obj._index_to_byte(index) # This should also be rare
304 return result.build()
305
306 def utf8_encode_ascii(space, s, w_s, errors, errorhandler, allow_surrogates=False):
307 """ Don't be confused - this is a slowpath for errors e.g. "ignore"
308 or an obscure errorhandler
309 """
310 result = StringBuilder(len(s))
311 index = 0
312 pos = 0
313 while pos < len(s):
314 ch = rutf8.codepoint_at_pos(s, pos)
315 startindex = index
316 index += 1
317 pos = rutf8.next_codepoint_pos(s, pos)
318 if ch <= 0x7F:
319 result.append(chr(ch))
320 else:
321 while pos < len(s) and rutf8.codepoint_at_pos(s, pos) > 0x7F:
322 pos = rutf8.next_codepoint_pos(s, pos)
323 index += 1
324 msg = "ordinal not in range(128)"
325 res, newindex, rettype, obj, w_obj = errorhandler(
326 errors, 'ascii', msg, w_s, startindex, index)
327 if rettype == 'u':
328 for cp in rutf8.Utf8StringIterator(res):
329 if cp > 0x80:
330 errorhandler("strict", 'ascii', msg, w_s, startindex, index)
331 raise RuntimeError('error handler should not have returned')
332 result.append(chr(cp))
333 else:
334 result.append(res)
335 # It should be rare that w_s != w_obj
336 w_s = w_obj
337 s = obj
338 if index != newindex: # Should be uncommon
339 index = newindex
340 pos = w_obj._index_to_byte(index) # This should also be rare
341 return result.build()
342
343 if _WIN32:
344 import pypy.interpreter.unicodehelper_win32 as win32
345 def utf8_encode_mbcs(space, s, w_s, errors, errorhandler, allow_surrogates=False):
346 return win32.utf8_encode_mbcs(space, s, w_s, errors, errorhandler)
347
348 def str_decode_mbcs(space, s, w_s, errors, final, errorhandler):
349 res, size = win32.str_decode_mbcs(space, s, w_s, errors, errorhandler, final=final)
350 return res, size, size
351
352 def utf8_encode_oem(space, s, w_s, errors, errorhandler, allow_surrogates=False):
353 res = win32.utf8_encode_oem(space, s, w_s, errors, errorhandler)
354 return res
355
356 def str_decode_oem(space, s, w_s, errors, final, errorhandler):
357 res, size = win32.str_decode_oem(space, s, w_s, errors, errorhandler, final)
358 return res, size, size
359
360 def utf8_encode_code_page(space, cp, s, w_s, errors, errorhandler, allow_surrogates=False):
361 res = win32.utf8_encode_code_page(space, cp, s, w_s, errors, errorhandler)
362 return res
363
364 def str_decode_code_page(space, cp, s, w_s, errors, final, errorhandler):
365 res, size = win32.str_decode_code_page(space, cp, s, w_s, errors, errorhandler, final)
366 return res, size, size
367
368
369 def str_decode_utf8(space, s, w_s, errors, final, errorhandler, allow_surrogates=False):
370 try:
371 # fast version first
372 return s, rutf8.check_utf8(s, allow_surrogates=allow_surrogates), len(s)
373 except rutf8.CheckError:
374 return _str_decode_utf8_slowpath(
375 space, s, w_s, errors, final, errorhandler, allow_surrogates=allow_surrogates)
376
377 def _str_decode_utf8_slowpath(space, s, w_s, errors, final, errorhandler, allow_surrogates):
378 """ Same as checking for the valid utf8, but we know the utf8 is not
379 valid so we're trying to either raise or pack stuff with error handler.
380 The key difference is that this is call_may_force.
381
382 In CPython this is done in unicode_decode_utf8, which has no
383 allow_surrogates. That argument is used in at least decode_utf8sp, in
384 interpreter.error._compute_value.
385 """
386 if errors is None:
387 errors = 'strict'
388 result = StringBuilder(len(s))
389 pos = 0
390 while pos < len(s):
391 ordch1 = ord(s[pos])
392 # fast path for ASCII
393 # XXX maybe use a while loop here
394 if ordch1 <= 0x7F:
395 pos += 1
396 result.append(chr(ordch1))
397 continue
398
399 n = ord(runicode._utf8_code_length[ordch1 - 0x80])
400 if pos + n > len(s):
401 # argh, this obscure block of code is mostly a copy of
402 # what follows :-(
403 charsleft = len(s) - pos - 1 # either 0, 1, 2
404 # note: when we get the 'unexpected end of data' we need
405 # to care about the pos returned; it can be lower than len(s),
406 # in case we need to continue running this loop
407 if not charsleft:
408 # there's only the start byte and nothing else
409 if not final:
410 break
411 r, pos, rettype, s, w_s = errorhandler(errors, 'utf-8',
412 'unexpected end of data',
413 w_s, pos, pos+1)
414 result.append(r)
415 continue
416 ordch2 = ord(s[pos+1])
417 if n == 3:
418 # 3-bytes seq with only a continuation byte
419 if rutf8._invalid_byte_2_of_3(ordch1, ordch2, allow_surrogates):
420 # second byte invalid, take the first and continue
421 r, pos, rettype, s, w_s = errorhandler(errors, 'utf-8',
422 'invalid continuation byte',
423 w_s, pos, pos+1)
424 result.append(r)
425 continue
426 else:
427 # second byte valid, but third byte missing
428 if not final:
429 break
430 r, pos, rettype, s, w_s = errorhandler(errors, 'utf-8',
431 'unexpected end of data',
432 w_s, pos, pos+2)
433 result.append(r)
434 continue
435 elif n == 4:
436 # 4-bytes seq with 1 or 2 continuation bytes
437 if rutf8._invalid_byte_2_of_4(ordch1, ordch2):
438 # second byte invalid, take the first and continue
439 r, pos, rettype, s, w_s = errorhandler(errors, 'utf-8',
440 'invalid continuation byte',
441 w_s, pos, pos+1)
442 result.append(r)
443 continue
444 elif charsleft == 2 and rutf8._invalid_byte_3_of_4(ord(s[pos+2])):
445 # third byte invalid, take the first two and continue
446 r, pos, rettype, s, w_s = errorhandler(errors, 'utf-8',
447 'invalid continuation byte',
448 w_s, pos, pos+2)
449 result.append(r)
450 continue
451 else:
452 # there's only 1 or 2 valid cb, but the others are missing
453 if not final:
454 break
455 r, pos, rettype, s, w_s = errorhandler(errors, 'utf-8',
456 'unexpected end of data',
457 w_s, pos, pos+charsleft+1)
458 result.append(r)
459 continue
460 raise AssertionError("unreachable")
461
462 if n == 0:
463 r, pos, rettype, s, w_s = errorhandler(errors, 'utf-8',
464 'invalid start byte',
465 w_s, pos, pos+1)
466 result.append(r)
467
468 elif n == 1:
469 assert 0, "ascii should have gone through the fast path"
470
471 elif n == 2:
472 ordch2 = ord(s[pos+1])
473 if rutf8._invalid_byte_2_of_2(ordch2):
474 r, pos, rettype, s, w_s = errorhandler(errors, 'utf-8',
475 'invalid continuation byte',
476 w_s, pos, pos+1)
477 result.append(r)
478 continue
479 # 110yyyyy 10zzzzzz -> 00000000 00000yyy yyzzzzzz
480 result.append(chr(ordch1))
481 result.append(chr(ordch2))
482 pos += 2
483
484 elif n == 3:
485 ordch2 = ord(s[pos+1])
486 ordch3 = ord(s[pos+2])
487 if rutf8._invalid_byte_2_of_3(ordch1, ordch2, allow_surrogates):
488 r, pos, rettype, s, w_s = errorhandler(errors, 'utf-8',
489 'invalid continuation byte',
490 w_s, pos, pos+1)
491 result.append(r)
492 continue
493 elif rutf8._invalid_byte_3_of_3(ordch3):
494 r, pos, rettype, s, w_s = errorhandler(errors, 'utf-8',
495 'invalid continuation byte',
496 w_s, pos, pos+2)
497 result.append(r)
498 continue
499 # 1110xxxx 10yyyyyy 10zzzzzz -> 00000000 xxxxyyyy yyzzzzzz
500 result.append(chr(ordch1))
501 result.append(chr(ordch2))
502 result.append(chr(ordch3))
503 pos += 3
504
505 elif n == 4:
506 ordch2 = ord(s[pos+1])
507 ordch3 = ord(s[pos+2])
508 ordch4 = ord(s[pos+3])
509 if rutf8._invalid_byte_2_of_4(ordch1, ordch2):
510 r, pos, rettype, s, w_s = errorhandler(errors, 'utf-8',
511 'invalid continuation byte',
512 w_s, pos, pos+1)
513 result.append(r)
514 continue
515 elif rutf8._invalid_byte_3_of_4(ordch3):
516 r, pos, rettype, s, w_s = errorhandler(errors, 'utf-8',
517 'invalid continuation byte',
518 w_s, pos, pos+2)
519 result.append(r)
520 continue
521 elif rutf8._invalid_byte_4_of_4(ordch4):
522 r, pos, rettype, s, w_s = errorhandler(errors, 'utf-8',
523 'invalid continuation byte',
524 w_s, pos, pos+3)
525 result.append(r)
526 continue
527 # 11110www 10xxxxxx 10yyyyyy 10zzzzzz -> 000wwwxx xxxxyyyy yyzzzzzz
528 result.append(chr(ordch1))
529 result.append(chr(ordch2))
530 result.append(chr(ordch3))
531 result.append(chr(ordch4))
532 pos += 4
533
534 r = result.build()
535 # XXX can keep track of the resulting length without calling check_utf8
536 # here
537 return r, rutf8.check_utf8(r, True), pos
538
539 hexdigits = "0123456789ABCDEFabcdef"
540
541 def hexescape(space, builder, s, w_s, pos, digits,
542 encoding, errorhandler, message, errors):
543 chr = 0
544 if pos + digits > len(s):
545 endinpos = pos
546 while endinpos < len(s) and s[endinpos] in hexdigits:
547 endinpos += 1
548 r, pos, rettype, s, w_s = errorhandler(
549 errors, encoding, message, w_s, pos - 2, endinpos)
550 builder.append(r)
551 else:
552 try:
553 chr = int(s[pos:pos + digits], 16)
554 except ValueError:
555 endinpos = pos
556 while s[endinpos] in hexdigits:
557 endinpos += 1
558 r, pos, rettype, s, w_s = errorhandler(
559 errors, encoding, message, w_s, pos - 2, endinpos)
560 builder.append(r)
561 else:
562 # when we get here, chr is a 32-bit unicode character
563 try:
564 builder.append_code(chr)
565 pos += digits
566 except rutf8.OutOfRange:
567 message = "illegal Unicode character"
568 r, pos, rettype, s, w_s = errorhandler(
569 errors, encoding, message, w_s, pos - 2, pos + digits)
570 builder.append(r)
571 return pos, s, w_s
572
573 def str_decode_unicode_escape(space, s, w_s, errors, final, errorhandler, ud_handler):
574 if len(s) == 0:
575 return '', 0, 0, None
576
577 builder = rutf8.Utf8StringBuilder(len(s))
578 pos = 0
579 first_escape_error_char = None
580 pos_delta = 0
581 while pos < len(s):
582 ch = s[pos]
583
584 # Non-escape characters are interpreted as Unicode ordinals
585 if ch != '\\':
586 if ord(ch) > 0x7F:
587 builder.append_code(ord(ch))
588 else:
589 builder.append(ch)
590 pos += 1
591 continue
592
593 # - Escapes
594 if pos + 1 >= len(s):
595 if not final:
596 break
597 message = "\\ at end of string"
598 prelen = len(s)
599 r, pos, rettype, s, w_s = errorhandler(errors, "unicodeescape",
600 message, w_s, pos - 1, len(s))
601 builder.append(r)
602 pos_delta += prelen - len(s)
603 continue
604 pos += 1
605
606 ch = s[pos]
607 pos += 1
608 # \x escapes
609 if ch == '\n':
610 pass
611 elif ch == '\\':
612 builder.append_char('\\')
613 elif ch == '\'':
614 builder.append_char('\'')
615 elif ch == '\"':
616 builder.append_char('\"')
617 elif ch == 'b':
618 builder.append_char('\b')
619 elif ch == 'f':
620 builder.append_char('\f')
621 elif ch == 't':
622 builder.append_char('\t')
623 elif ch == 'n':
624 builder.append_char('\n')
625 elif ch == 'r':
626 builder.append_char('\r')
627 elif ch == 'v':
628 builder.append_char('\v')
629 elif ch == 'a':
630 builder.append_char('\a')
631 elif '0' <= ch <= '7':
632 span = ch
633 x = ord(ch) - ord('0')
634 if pos < len(s):
635 ch = s[pos]
636 if '0' <= ch <= '7':
637 span += ch
638 pos += 1
639 x = (x << 3) + ord(ch) - ord('0')
640 if pos < len(s):
641 ch = s[pos]
642 if '0' <= ch <= '7':
643 span += ch
644 pos += 1
645 x = (x << 3) + ord(ch) - ord('0')
646 if x > 0x7F:
647 first_escape_error_char = span
648 builder.append_code(x)
649 else:
650 builder.append_char(chr(x))
651 # hex escapes
652 # \xXX
653 elif ch == 'x':
654 digits = 2
655 if pos + digits > len(s) and not final:
656 pos -= 2
657 break
658 message = "truncated \\xXX escape"
659 prelen = len(s)
660 pos, s, w_s = hexescape(space, builder, s, w_s, pos, digits,
661 "unicodeescape", errorhandler, message, errors)
662 pos_delta += prelen - len(s)
663 # \uXXXX
664 elif ch == 'u':
665 digits = 4
666 if pos + digits > len(s) and not final:
667 pos -= 2
668 break
669 message = "truncated \\uXXXX escape"
670 prelen = len(s)
671 pos, s, w_s = hexescape(space, builder, s, w_s, pos, digits,
672 "unicodeescape", errorhandler, message, errors)
673 pos_delta += prelen - len(s)
674 # \UXXXXXXXX
675 elif ch == 'U':
676 digits = 8
677 if pos + digits > len(s) and not final:
678 pos -= 2
679 break
680 message = "truncated \\UXXXXXXXX escape"
681 prelen = len(s)
682 pos, s, w_s = hexescape(space, builder, s, w_s, pos, digits,
683 "unicodeescape", errorhandler, message, errors)
684 pos_delta += prelen - len(s)
685 # \N{name}
686 elif ch == 'N' and ud_handler is not None:
687 message = "malformed \\N character escape"
688 look = pos
689
690 if look < len(s) and s[look] == '{':
691 # look for the closing brace
692 while look < len(s) and s[look] != '}':
693 look += 1
694 if look < len(s) and s[look] == '}':
695 # found a name. look it up in the unicode database
696 message = "unknown Unicode character name"
697 name = s[pos + 1:look]
698 code = ud_handler.call(name)
699 if code < 0:
700 prelen = len(s)
701 r, pos, rettype, s, w_s = errorhandler(
702 errors, "unicodeescape", message,
703 w_s, pos - 1, look + 1)
704 builder.append(r)
705 pos_delta += prelen - len(s)
706 continue
707 pos = look + 1
708 builder.append_code(code)
709 else:
710 if not final:
711 pos -= 2
712 break
713 prelen = len(s)
714 r, pos, rettype, s, w_s = errorhandler(errors, "unicodeescape",
715 message, w_s, pos - 1, look + 1)
716 builder.append(r)
717 pos_delta += prelen - len(s)
718 else:
719 if not final:
720 pos -= 2
721 break
722 prelen = len(s)
723 r, pos, rettype, s, w_s = errorhandler(errors, "unicodeescape",
724
725 message, w_s, pos - 1, look + 1)
726 builder.append(r)
727 pos_delta += prelen - len(s)
728 else:
729 builder.append_char('\\')
730 builder.append_code(ord(ch))
731 first_escape_error_char = ch
732
733 return builder.build(), builder.getlength(), pos + pos_delta, first_escape_error_char
734
735 def wcharpsize2utf8(space, wcharp, size):
736 """Safe version of rffi.wcharpsize2utf8.
737
738 Raises app-level ValueError if any wchar value is outside the valid
739 codepoint range.
740 """
741 if size < 1:
742 return ''
743 if _WIN32:
744 import pypy.interpreter.unicodehelper_win32 as win32
745 # wcharp is actually utf16
746 return win32._unibuf_to_utf8(wcharp, size)
747 else:
748 try:
749 return rffi.wcharpsize2utf8(wcharp, size)
750 except rutf8.OutOfRange as e:
751 raise wrap_unicode_out_of_range_error(space, e)
752
753 def wrap_unicode_out_of_range_error(space, e):
754 raise oefmt(space.w_ValueError,
755 "character %s is not in range [U+0000; U+10ffff]", 'U+%x' % e.code)
756
757
758 # ____________________________________________________________
759 # Raw unicode escape
760
761 def str_decode_raw_unicode_escape(space, s, w_s, errors, final=False,
762 errorhandler=None):
763 if len(s) == 0:
764 return '', 0, 0
765
766 builder = rutf8.Utf8StringBuilder(len(s))
767 pos = 0
768 while pos < len(s):
769 ch = s[pos]
770 pos += 1
771
772 # Non-escape characters are interpreted as Unicode ordinals
773 if ch != '\\':
774 builder.append_code(ord(ch))
775 continue
776
777 if pos == len(s):
778 if final:
779 # we have a backslash at the end of the string, stop here
780 builder.append_char('\\')
781 else:
782 pos -= 1
783 break
784 ch = s[pos]
785 if s[pos] == 'u':
786 digits = 4
787 message = "truncated \\uXXXX escape"
788 elif s[pos] == 'U':
789 digits = 8
790 message = "truncated \\UXXXXXXXX escape"
791 else:
792 builder.append_char('\\')
793 builder.append_code(ord(ch))
794 pos += 1
795 continue
796 pos += 1
797 if pos + digits > len(s) and not final:
798 pos -= 2
799 break
800 pos, s, w_s = hexescape(space, builder, s, w_s, pos, digits,
801 "rawunicodeescape", errorhandler, message, errors)
802
803 return builder.build(), builder.getlength(), pos
804
805 _utf8_encode_unicode_escape = rutf8.make_utf8_escape_function()
806
807
808 TABLE = '0123456789abcdef'
809
810 def raw_unicode_escape_helper(result, char):
811 if char >= 0x10000 or char < 0:
812 result.append("\\U")
813 zeros = 8
814 elif char >= 0x100:
815 result.append("\\u")
816 zeros = 4
817 else:
818 result.append("\\x")
819 zeros = 2
820 for i in range(zeros-1, -1, -1):
821 result.append(TABLE[(char >> (4 * i)) & 0x0f])
822
823 def utf8_encode_raw_unicode_escape(space, s, w_s, errors, errorhandler, allow_surrogates=False):
824 # errorhandler is not used: this function cannot cause Unicode errors
825 size = len(s)
826 if size == 0:
827 return ''
828 result = StringBuilder(size)
829 pos = 0
830 while pos < size:
831 oc = rutf8.codepoint_at_pos(s, pos)
832
833 if oc < 0x100:
834 result.append(chr(oc))
835 else:
836 raw_unicode_escape_helper(result, oc)
837 pos = rutf8.next_codepoint_pos(s, pos)
838
839 return result.build()
840
841
842 def utf8_encode_unicode_escape(space, s, w_s, errors, errorhandler, allow_surrogates=False):
843 return _utf8_encode_unicode_escape(s)
844
845 # ____________________________________________________________
846 # utf-7
847
848 # Three simple macros defining base-64
849
850 def _utf7_IS_BASE64(oc):
851 "Is c a base-64 character?"
852 c = chr(oc)
853 return c.isalnum() or c == '+' or c == '/'
854 def _utf7_TO_BASE64(n):
855 "Returns the base-64 character of the bottom 6 bits of n"
856 return "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"[n & 0x3f]
857 def _utf7_FROM_BASE64(c):
858 "given that c is a base-64 character, what is its base-64 value?"
859 if c >= 'a':
860 return ord(c) - 71
861 elif c >= 'A':
862 return ord(c) - 65
863 elif c >= '0':
864 return ord(c) + 4
865 elif c == '+':
866 return 62
867 else: # c == '/'
868 return 63
869
870 def _utf7_DECODE_DIRECT(oc):
871 return oc <= 127 and oc != ord('+')
872
873 # The UTF-7 encoder treats ASCII characters differently according to
874 # whether they are Set D, Set O, Whitespace, or special (i.e. none of
875 # the above). See RFC2152. This array identifies these different
876 # sets:
877 # 0 : "Set D"
878 # alphanumeric and '(),-./:?
879 # 1 : "Set O"
880 # !"#$%&*;<=>@[]^_`{|}
881 # 2 : "whitespace"
882 # ht nl cr sp
883 # 3 : special (must be base64 encoded)
884 # everything else (i.e. +\~ and non-printing codes 0-8 11-12 14-31 127)
885
886 utf7_category = [
887 # nul soh stx etx eot enq ack bel bs ht nl vt np cr so si
888 3, 3, 3, 3, 3, 3, 3, 3, 3, 2, 2, 3, 3, 2, 3, 3,
889 # dle dc1 dc2 dc3 dc4 nak syn etb can em sub esc fs gs rs us
890 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3,
891 # sp ! " # $ % & ' ( ) * + , - . /
892 2, 1, 1, 1, 1, 1, 1, 0, 0, 0, 1, 3, 0, 0, 0, 0,
893 # 0 1 2 3 4 5 6 7 8 9 : ; < = > ?
894 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 0,
895 # @ A B C D E F G H I J K L M N O
896 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
897 # P Q R S T U V W X Y Z [ \ ] ^ _
898 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 3, 1, 1, 1,
899 # ` a b c d e f g h i j k l m n o
900 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
901 # p q r s t u v w x y z { | } ~ del
902 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 3, 3,
903 ]
904
905 # ENCODE_DIRECT: this character should be encoded as itself. The
906 # answer depends on whether we are encoding set O as itself, and also
907 # on whether we are encoding whitespace as itself. RFC2152 makes it
908 # clear that the answers to these questions vary between
909 # applications, so this code needs to be flexible.
910
911 def _utf7_ENCODE_DIRECT(oc, directO, directWS):
912 return(oc < 128 and oc > 0 and
913 (utf7_category[oc] == 0 or
914 (directWS and utf7_category[oc] == 2) or
915 (directO and utf7_category[oc] == 1)))
916
917 def _utf7_ENCODE_CHAR(result, oc, base64bits, base64buffer):
918 if oc >= 0x10000:
919 # code first surrogate
920 base64bits += 16
921 base64buffer = (base64buffer << 16) | 0xd800 | ((oc-0x10000) >> 10)
922 while base64bits >= 6:
923 result.append(_utf7_TO_BASE64(base64buffer >> (base64bits-6)))
924 base64bits -= 6
925 # prepare second surrogate
926 oc = 0xDC00 | ((oc-0x10000) & 0x3FF)
927 base64bits += 16
928 base64buffer = (base64buffer << 16) | oc
929 while base64bits >= 6:
930 result.append(_utf7_TO_BASE64(base64buffer >> (base64bits-6)))
931 base64bits -= 6
932 return base64bits, base64buffer
933
934 def str_decode_utf_7(space, s, w_s, errors, final=False,
935 errorhandler=None):
936 if len(s) == 0:
937 return '', 0, 0
938
939 inShift = False
940 base64bits = 0
941 base64buffer = 0
942 surrogate = 0
943 outsize = 0
944
945 result = StringBuilder(len(s))
946 pos = 0
947 shiftOutStartPos = 0
948 startinpos = 0
949 while pos < len(s):
950 ch = s[pos]
951
952 if inShift: # in a base-64 section
953 if _utf7_IS_BASE64(ord(ch)): #consume a base-64 character
954 base64buffer = (base64buffer << 6) | _utf7_FROM_BASE64(ch)
955 assert base64buffer >= 0
956 base64bits += 6
957 pos += 1
958
959 if base64bits >= 16:
960 # enough bits for a UTF-16 value
961 outCh = base64buffer >> (base64bits - 16)
962 assert outCh >= 0
963 base64bits -= 16
964 base64buffer &= (1 << base64bits) - 1 # clear high bits
965 assert outCh <= 0xffff
966 if surrogate:
967 # expecting a second surrogate
968 if outCh >= 0xDC00 and outCh <= 0xDFFF:
969 code = (((surrogate & 0x3FF)<<10) |
970 (outCh & 0x3FF)) + 0x10000
971 rutf8.unichr_as_utf8_append(result, code)
972 outsize += 1
973 surrogate = 0
974 continue
975 else:
976 rutf8.unichr_as_utf8_append(result, surrogate,
977 allow_surrogates=True)
978 outsize += 1
979 surrogate = 0
980 # Not done with outCh: falls back to next line
981 if outCh >= 0xD800 and outCh <= 0xDBFF:
982 # first surrogate
983 surrogate = outCh
984 else:
985 outsize += 1
986 assert outCh >= 0
987 rutf8.unichr_as_utf8_append(result, outCh, True)
988
989 else:
990 # now leaving a base-64 section
991 inShift = False
992
993 if base64bits > 0: # left-over bits
994 if base64bits >= 6:
995 # We've seen at least one base-64 character
996 pos += 1
997 msg = "partial character in shift sequence"
998 r, pos, rettype, s, w_s = errorhandler(errors, 'utf7',
999 msg, w_s, pos-1, pos)
1000 reslen = rutf8.check_utf8(r, True)
1001 outsize += reslen
1002 result.append(r)
1003 continue
1004 else:
1005 # Some bits remain; they should be zero
1006 if base64buffer != 0:
1007 pos += 1
1008 msg = "non-zero padding bits in shift sequence"
1009 r, pos, rettype, s, w_s = errorhandler(errors, 'utf7',
1010 msg, w_s, pos-1, pos)
1011 reslen = rutf8.check_utf8(r, True)
1012 outsize += reslen
1013 result.append(r)
1014 continue
1015
1016 if surrogate and _utf7_DECODE_DIRECT(ord(ch)):
1017 outsize += 1
1018 rutf8.unichr_as_utf8_append(result, surrogate, True)
1019 surrogate = 0
1020
1021 if ch == '-':
1022 # '-' is absorbed; other terminating characters are
1023 # preserved
1024 pos += 1
1025
1026 elif ch == '+':
1027 startinpos = pos
1028 pos += 1 # consume '+'
1029 if pos < len(s) and s[pos] == '-': # '+-' encodes '+'
1030 pos += 1
1031 result.append('+')
1032 outsize += 1
1033 elif pos < len(s) and not _utf7_IS_BASE64(ord(s[pos])):
1034 msg = "ill-formed sequence"
1035 r, pos, rettype, s, w_s = errorhandler(errors, 'utf7', msg, w_s, pos-1, pos+1)
1036 reslen = rutf8.check_utf8(r, True)
1037 outsize += reslen
1038 result.append(r)
1039 else: # begin base64-encoded section
1040 inShift = 1
1041 surrogate = 0
1042 shiftOutStartPos = result.getlength()
1043 base64bits = 0
1044 base64buffer = 0
1045
1046 elif _utf7_DECODE_DIRECT(ord(ch)): # character decodes at itself
1047 result.append(ch)
1048 outsize += 1
1049 pos += 1
1050 else:
1051 startinpos = pos
1052 pos += 1
1053 msg = "unexpected special character"
1054 r, pos, rettype, s, w_s = errorhandler(errors, 'utf7', msg, w_s, pos-1, pos)
1055 reslen = rutf8.check_utf8(r, True)
1056 outsize += reslen
1057 result.append(r)
1058
1059 # end of string
1060 final_length = result.getlength()
1061 final_size = len(s)
1062 if inShift and final: # in shift sequence, no more to follow
1063 inShift = 0
1064 if (surrogate or
1065 base64bits >= 6 or
1066 (base64bits > 0 and base64buffer != 0)):
1067 # if we're in an inconsistent state, that's an error
1068 msg = "unterminated shift sequence"
1069 r, pos, rettype, s, w_s = errorhandler(errors, 'utf7', msg, w_s, shiftOutStartPos, pos)
1070 reslen = rutf8.check_utf8(r, True)
1071 outsize += reslen
1072 result.append(r)
1073 final_length = result.getlength()
1074 elif inShift:
1075 final_size = startinpos
1076 final_length = shiftOutStartPos # back off output
1077
1078 assert final_length >= 0
1079 return result.build()[:final_length], outsize, final_size
1080
1081 def utf8_encode_utf_7(space, s, w_s, errors, errorhandler, allow_surrogates=False):
1082 # only uses s, other arguments are ignored
1083 size = len(s)
1084 if size == 0:
1085 return ''
1086 result = StringBuilder(size)
1087
1088 encodeSetO = encodeWhiteSpace = False
1089
1090 inShift = False
1091 base64bits = 0
1092 base64buffer = 0
1093
1094 pos = 0
1095 while pos < size:
1096 oc = rutf8.codepoint_at_pos(s, pos)
1097 if not inShift:
1098 if oc == ord('+'):
1099 result.append('+-')
1100 elif _utf7_ENCODE_DIRECT(oc, not encodeSetO, not encodeWhiteSpace):
1101 result.append(chr(oc))
1102 else:
1103 result.append('+')
1104 inShift = True
1105 base64bits, base64buffer = _utf7_ENCODE_CHAR(
1106 result, oc, base64bits, base64buffer)
1107 else:
1108 if _utf7_ENCODE_DIRECT(oc, not encodeSetO, not encodeWhiteSpace):
1109 # shifting out
1110 if base64bits: # output remaining bits
1111 result.append(_utf7_TO_BASE64(base64buffer << (6-base64bits)))
1112 base64buffer = 0
1113 base64bits = 0
1114
1115 inShift = False
1116 ## Characters not in the BASE64 set implicitly unshift the
1117 ## sequence so no '-' is required, except if the character is
1118 ## itself a '-'
1119 if _utf7_IS_BASE64(oc) or oc == ord('-'):
1120 result.append('-')
1121 result.append(chr(oc))
1122 else:
1123 base64bits, base64buffer = _utf7_ENCODE_CHAR(
1124 result, oc, base64bits, base64buffer)
1125 pos = rutf8.next_codepoint_pos(s, pos)
1126
1127 if base64bits:
1128 result.append(_utf7_TO_BASE64(base64buffer << (6 - base64bits)))
1129 if inShift:
1130 result.append('-')
1131
1132 return result.build()
1133
1134 def decode_utf8sp(space, string):
1135 # Surrogate-preserving utf-8 decoding. Assuming there is no
1136 # encoding error, it should always be reversible, and the reverse is
1137 # unused encode_utf8sp().
1138 w_string = space.newbytes(string)
1139 decode_never_raise = make_decode_never_raise(space)
1140 return str_decode_utf8(space, string, w_string, "string", True, decode_never_raise,
1141 allow_surrogates=True)
1142
1143 # ____________________________________________________________
1144 # utf-16
1145
1146 BYTEORDER = sys.byteorder
1147 BYTEORDER2 = BYTEORDER[0] + 'e' # either "le" or "be"
1148 assert BYTEORDER2 in ('le', 'be')
1149
1150 def str_decode_utf_16(space, s, w_s, errors, final=True,
1151 errorhandler=None):
1152 return str_decode_utf_16_helper(space, s, w_s, errors, final, errorhandler,
1153 "native")[:3]
1154
1155 def str_decode_utf_16_be(space, s, w_s, errors, final=True,
1156 errorhandler=None):
1157 return str_decode_utf_16_helper(space, s, w_s, errors, final, errorhandler, "big",
1158 'utf16-be')[:3]
1159
1160 def str_decode_utf_16_le(space, s, w_s, errors, final=True,
1161 errorhandler=None):
1162 return str_decode_utf_16_helper(space, s, w_s, errors, final, errorhandler, "little",
1163 'utf16-le')[:3]
1164
1165 def str_decode_utf_16_helper(space, s, w_s, errors, final=True,
1166 errorhandler=None,
1167 byteorder="native",
1168 public_encoding_name='utf16'):
1169 bo = 0
1170
1171 if BYTEORDER == 'little':
1172 ihi = 1
1173 ilo = 0
1174 else:
1175 ihi = 0
1176 ilo = 1
1177
1178 # Check for BOM marks (U+FEFF) in the input and adjust current
1179 # byte order setting accordingly. In native mode, the leading BOM
1180 # mark is skipped, in all other modes, it is copied to the output
1181 # stream as-is (giving a ZWNBSP character).
1182 pos = 0
1183 if byteorder == 'native':
1184 if len(s) >= 2:
1185 bom = (ord(s[ihi]) << 8) | ord(s[ilo])
1186 if BYTEORDER == 'little':
1187 if bom == 0xFEFF:
1188 pos += 2
1189 bo = -1
1190 elif bom == 0xFFFE:
1191 pos += 2
1192 bo = 1
1193 else:
1194 if bom == 0xFEFF:
1195 pos += 2
1196 bo = 1
1197 elif bom == 0xFFFE:
1198 pos += 2
1199 bo = -1
1200 elif byteorder == 'little':
1201 bo = -1
1202 else:
1203 bo = 1
1204 if len(s) == 0:
1205 return '', 0, 0, bo
1206 if bo == -1:
1207 # force little endian
1208 ihi = 1
1209 ilo = 0
1210
1211 elif bo == 1:
1212 # force big endian
1213 ihi = 0
1214 ilo = 1
1215
1216 result = StringBuilder(len(s) // 2)
1217
1218 while pos < len(s):
1219 # remaining bytes at the end? (len(s) should be even)
1220 if len(s) - pos < 2:
1221 if not final:
1222 break
1223 r, pos, rettype, s, w_s = errorhandler(errors, public_encoding_name,
1224 "truncated data",
1225 w_s, pos, len(s))
1226 result.append(r)
1227 if len(s) - pos < 2:
1228 break
1229 ch = (ord(s[pos + ihi]) << 8) | ord(s[pos + ilo])
1230 pos += 2
1231 if ch < 0xD800 or ch > 0xDFFF:
1232 rutf8.unichr_as_utf8_append(result, ch)
1233 continue
1234 # unexpected low surrogate
1235 elif ch >= 0xDC00:
1236 r, pos, rettype, s, w_s = errorhandler(errors, public_encoding_name,
1237 "illegal encoding",
1238 w_s, pos - 2, pos)
1239 result.append(r)
1240 continue
1241 # UTF-16 code pair:
1242 if len(s) - pos < 2:
1243 pos -= 2
1244 if not final:
1245 break
1246 errmsg = "unexpected end of data"
1247 r, pos, rettype, s, w_s = errorhandler(errors, public_encoding_name,
1248 errmsg, w_s, pos, len(s))
1249 result.append(r)
1250 else:
1251 ch2 = (ord(s[pos+ihi]) << 8) | ord(s[pos+ilo])
1252 pos += 2
1253 if 0xDC00 <= ch2 <= 0xDFFF:
1254 ch = (((ch & 0x3FF)<<10) | (ch2 & 0x3FF)) + 0x10000
1255 rutf8.unichr_as_utf8_append(result, ch)
1256 continue
1257 else:
1258 r, pos, rettype, s, w_s = errorhandler(errors, public_encoding_name,
1259 "illegal UTF-16 surrogate",
1260 w_s, pos - 4, pos - 2)
1261 result.append(r)
1262 r = result.build()
1263 lgt = rutf8.check_utf8(r, True)
1264 return r, lgt, pos, bo
1265
1266 def _STORECHAR(result, CH, byteorder):
1267 hi = chr(((CH) >> 8) & 0xff)
1268 lo = chr((CH) & 0xff)
1269 if byteorder == 'little':
1270 result.append(lo)
1271 result.append(hi)
1272 else:
1273 result.append(hi)
1274 result.append(lo)
1275
1276 def utf8_encode_utf_16_helper(space, s, w_s, errors,
1277 errorhandler=None,
1278 allow_surrogates=True,
1279 byteorder='little',
1280 public_encoding_name='utf16'):
1281 if len(s) == 0:
1282 if byteorder == 'native':
1283 result = StringBuilder(2)
1284 _STORECHAR(result, 0xFEFF, BYTEORDER)
1285 return result.build()
1286 return ""
1287
1288 result = StringBuilder(len(s) * 2 + 2)
1289 if byteorder == 'native':
1290 _STORECHAR(result, 0xFEFF, BYTEORDER)
1291 byteorder = BYTEORDER
1292
1293 pos = 0
1294 index = 0
1295 while pos < len(s):
1296 cp = rutf8.codepoint_at_pos(s, pos)
1297 if cp < 0xD800:
1298 _STORECHAR(result, cp, byteorder)
1299 elif cp >= 0x10000:
1300 _STORECHAR(result, 0xD800 | ((cp-0x10000) >> 10), byteorder)
1301 _STORECHAR(result, 0xDC00 | ((cp-0x10000) & 0x3FF), byteorder)
1302 elif cp >= 0xE000 or allow_surrogates:
1303 _STORECHAR(result, cp, byteorder)
1304 else:
1305 r, newindex, rettype, s, w_s = errorhandler(
1306 errors, public_encoding_name, 'surrogates not allowed',
1307 w_s, index, index+1)
1308 if rettype == 'u':
1309 for cp in rutf8.Utf8StringIterator(r):
1310 if cp < 0xD800 or allow_surrogates:
1311 _STORECHAR(result, cp, byteorder)
1312 else:
1313 errorhandler('strict', public_encoding_name,
1314 'surrogates not allowed',
1315 w_s, index, index+1)
1316 else:
1317 # bytes are just copied to the output
1318 if len(r) & 1:
1319 # must be an even number of bytes
1320 errorhandler('strict', public_encoding_name,
1321 'surrogates not allowed',
1322 w_s, index, index+1)
1323 result.append(r)
1324 if index != newindex: # Should be uncommon
1325 index = newindex
1326 pos = rutf8._pos_at_index(s, newindex)
1327 continue
1328 pos = rutf8.next_codepoint_pos(s, pos)
1329 index += 1
1330
1331 return result.build()
1332
1333 def utf8_encode_utf_16(space, s, w_s, errors,
1334 errorhandler=None,
1335 allow_surrogates=False):
1336 return utf8_encode_utf_16_helper(space, s, w_s, errors, errorhandler,
1337 allow_surrogates, "native",
1338 'utf-16-' + BYTEORDER2)
1339
1340 def utf8_encode_utf_16_be(space, s, w_s, errors,
1341 errorhandler=None,
1342 allow_surrogates=False):
1343 return utf8_encode_utf_16_helper(space, s, w_s, errors, errorhandler,
1344 allow_surrogates, "big",
1345 'utf-16-be')
1346
1347 def utf8_encode_utf_16_le(space, s, w_s, errors,
1348 errorhandler=None,
1349 allow_surrogates=False):
1350 return utf8_encode_utf_16_helper(space, s, w_s, errors, errorhandler,
1351 allow_surrogates, "little",
1352 'utf-16-le')
1353
1354 # ____________________________________________________________
1355 # utf-32
1356
1357 def str_decode_utf_32(space, s, w_s, errors, final=True,
1358 errorhandler=None):
1359 return str_decode_utf_32_helper(
1360 space, s, w_s, errors, final, errorhandler, "native", 'utf-32-' + BYTEORDER2,
1361 allow_surrogates=False)[:3]
1362
1363 def str_decode_utf_32_be(space, s, w_s, errors, final=True,
1364 errorhandler=None):
1365 return str_decode_utf_32_helper(
1366 space, s, w_s, errors, final, errorhandler, "big", 'utf-32-be',
1367 allow_surrogates=False)[:3]
1368
1369 def str_decode_utf_32_le(space, s, w_s, errors, final=True,
1370 errorhandler=None):
1371 return str_decode_utf_32_helper(
1372 space, s, w_s, errors, final, errorhandler, "little", 'utf-32-le',
1373 allow_surrogates=False)[:3]
1374
1375 BOM32_DIRECT = intmask(0x0000FEFF)
1376 BOM32_REVERSE = intmask(0xFFFE0000)
1377
1378 def str_decode_utf_32_helper(space, s, w_s, errors, final,
1379 errorhandler,
1380 byteorder="native",
1381 public_encoding_name='utf32',
1382 allow_surrogates=True):
1383 assert errorhandler is not None
1384 bo = 0
1385
1386 if BYTEORDER == 'little':
1387 iorder0, iorder1, iorder2, iorder3 = 0, 1, 2, 3
1388 else:
1389 iorder0, iorder1, iorder2, iorder3 = 3, 2, 1, 0
1390
1391 # Check for BOM marks (U+FEFF) in the input and adjust current
1392 # byte order setting accordingly. In native mode, the leading BOM
1393 # mark is skipped, in all other modes, it is copied to the output
1394 # stream as-is (giving a ZWNBSP character).
1395 pos = 0
1396 if byteorder == 'native':
1397 if len(s) >= 4:
1398 bom = intmask(
1399 (ord(s[iorder3]) << 24) | (ord(s[iorder2]) << 16) |
1400 (ord(s[iorder1]) << 8) | ord(s[iorder0]))
1401 if BYTEORDER == 'little':
1402 if bom == BOM32_DIRECT:
1403 pos += 4
1404 bo = -1
1405 elif bom == BOM32_REVERSE:
1406 pos += 4
1407 bo = 1
1408 else:
1409 if bom == BOM32_DIRECT:
1410 pos += 4
1411 bo = 1
1412 elif bom == BOM32_REVERSE:
1413 pos += 4
1414 bo = -1
1415 elif byteorder == 'little':
1416 bo = -1
1417 else:
1418 bo = 1
1419 if len(s) == 0:
1420 return '', 0, 0, bo
1421 if bo == -1:
1422 # force little endian
1423 iorder0, iorder1, iorder2, iorder3 = 0, 1, 2, 3
1424 elif bo == 1:
1425 # force big endian
1426 iorder0, iorder1, iorder2, iorder3 = 3, 2, 1, 0
1427
1428 result = StringBuilder(len(s) // 4)
1429
1430 while pos < len(s):
1431 # remaining bytes at the end? (len(s) should be divisible by 4)
1432 if len(s) - pos < 4:
1433 if not final:
1434 break
1435 r, pos, rettype, s, w_s = errorhandler(errors, public_encoding_name,
1436 "truncated data",
1437 w_s, pos, len(s))
1438 result.append(r)
1439 if len(s) - pos < 4:
1440 break
1441 continue
1442 ch = ((ord(s[pos + iorder3]) << 24) | (ord(s[pos + iorder2]) << 16) |
1443 (ord(s[pos + iorder1]) << 8) | ord(s[pos + iorder0]))
1444 if not allow_surrogates and 0xD800 <= ch <= 0xDFFF:
1445 r, pos, rettype, obj, w_obj = errorhandler(errors, public_encoding_name,
1446 "code point in surrogate code point "
1447 "range(0xd800, 0xe000)",
1448 w_s, pos, pos + 4)
1449 result.append(r)
1450 continue
1451 elif r_uint(ch) >= 0x110000:
1452 r, pos, rettype, s, w_obj = errorhandler(errors, public_encoding_name,
1453 "codepoint not in range(0x110000)",
1454 w_s, pos, len(s))
1455 result.append(r)
1456 continue
1457
1458 rutf8.unichr_as_utf8_append(result, ch, allow_surrogates=allow_surrogates)
1459 pos += 4
1460 r = result.build()
1461 lgt = rutf8.check_utf8(r, True)
1462 return r, lgt, pos, bo
1463
1464 def _STORECHAR32(result, CH, byteorder):
1465 c0 = chr(((CH) >> 24) & 0xff)
1466 c1 = chr(((CH) >> 16) & 0xff)
1467 c2 = chr(((CH) >> 8) & 0xff)
1468 c3 = chr((CH) & 0xff)
1469 if byteorder == 'little':
1470 result.append(c3)
1471 result.append(c2)
1472 result.append(c1)
1473 result.append(c0)
1474 else:
1475 result.append(c0)
1476 result.append(c1)
1477 result.append(c2)
1478 result.append(c3)
1479
1480 def utf8_encode_utf_32_helper(space, s, w_s, errors,
1481 errorhandler=None,
1482 allow_surrogates=True,
1483 byteorder='little',
1484 public_encoding_name='utf32'):
1485 # s is utf8
1486 if len(s) == 0:
1487 if byteorder == 'native':
1488 result = StringBuilder(4)
1489 _STORECHAR32(result, 0xFEFF, BYTEORDER)
1490 return result.build()
1491 return ""
1492
1493 result = StringBuilder(len(s) * 4 + 4)
1494 if byteorder == 'native':
1495 _STORECHAR32(result, 0xFEFF, BYTEORDER)
1496 byteorder = BYTEORDER
1497
1498 pos = 0
1499 index = 0
1500 while pos < len(s):
1501 ch = rutf8.codepoint_at_pos(s, pos)
1502 if not allow_surrogates and 0xD800 <= ch < 0xE000:
1503 r, newindex, rettype, obj, w_obj = errorhandler(
1504 errors, public_encoding_name, 'surrogates not allowed',
1505 w_s, index, index+1)
1506 if rettype == 'u':
1507 for ch in rutf8.Utf8StringIterator(r):
1508 if ch < 0xD800:
1509 _STORECHAR32(result, ch, byteorder)
1510 else:
1511 errorhandler(
1512 'strict', public_encoding_name, 'surrogates not allowed',
1513 w_s, index, index+1)
1514 else:
1515 if len(r) & 0b11:
1516 # length must be divisible by 4
1517 errorhandler(
1518 'strict', public_encoding_name, 'surrogates not allowed',
1519 w_s, index, index+1)
1520 result.append(r)
1521 # It should be rare that w_s != w_obj
1522 s = obj
1523 w_s = w_obj
1524 if index != newindex: # Should be uncommon
1525 index = newindex
1526 pos = w_obj._index_to_byte(index) # This should also be rare
1527 continue
1528 pos = rutf8.next_codepoint_pos(s, pos)
1529 _STORECHAR32(result, ch, byteorder)
1530 index += 1
1531
1532 return result.build()
1533
1534 def utf8_encode_utf_32(space, s, w_s, errors,
1535 errorhandler=None, allow_surrogates=True):
1536 return utf8_encode_utf_32_helper(space, s, w_s, errors, errorhandler,
1537 allow_surrogates, "native",
1538 'utf-32-' + BYTEORDER2)
1539
1540 def utf8_encode_utf_32_be(space, s, w_s, errors,
1541 errorhandler=None, allow_surrogates=True):
1542 return utf8_encode_utf_32_helper(space, s, w_s, errors, errorhandler,
1543 allow_surrogates, "big",
1544 'utf-32-be')
1545
1546 def utf8_encode_utf_32_le(space, s, w_s, errors,
1547 errorhandler=None, allow_surrogates=True):
1548 return utf8_encode_utf_32_helper(space, s, w_s, errors, errorhandler,
1549 allow_surrogates, "little",
1550 'utf-32-le')
1551 # ____________________________________________________________
1552 # Charmap
1553
1554 ERROR_CHAR = u'\ufffe'.encode('utf8')
1555
1556 @specialize.argtype(4)
1557 def str_decode_charmap(space, s, w_s, errors, final=False,
1558 errorhandler=None, mapping=None):
1559 "mapping can be a rpython dictionary, or a dict-like object."
1560
1561 # Default to Latin-1
1562 if mapping is None:
1563 return str_decode_latin_1(space, s, w_s, errors, final=final,
1564 errorhandler=errorhandler)
1565 if len(s) == 0:
1566 return '', 0, 0
1567
1568 pos = 0
1569 result = StringBuilder(len(s))
1570 while pos < len(s):
1571 ch = s[pos]
1572
1573 c = mapping.get(ord(ch), ERROR_CHAR)
1574 if c == ERROR_CHAR:
1575 r, pos, rettype, s, w_s = errorhandler(errors, "charmap",
1576 "character maps to <undefined>",
1577 w_s, pos, pos + 1)
1578 result.append(r)
1579 continue
1580 result.append(c)
1581 pos += 1
1582 r = result.build()
1583 lgt = rutf8.codepoints_in_utf8(r)
1584 return r, lgt, pos
1585
1586 def utf8_encode_charmap(space, s, w_s, errors, errorhandler=None, mapping=None, allow_surrogates=False):
1587 if mapping is None:
1588 return utf8_encode_latin_1(space, s, w_s, errors, errorhandler=errorhandler)
1589 if len(s) == 0:
1590 return ''
1591 result = StringBuilder(len(s))
1592 pos = 0
1593 index = 0
1594 while pos < len(s):
1595 ch = rutf8.codepoint_at_pos(s, pos)
1596 c = mapping.get(ch, '')
1597 if len(c) == 0:
1598 # collect all unencodable chars.
1599 startindex = index
1600 pos = rutf8.next_codepoint_pos(s, pos)
1601 index += 1
1602 while (pos < len(s) and
1603 mapping.get(rutf8.codepoint_at_pos(s, pos), '') == ''):
1604 pos = rutf8.next_codepoint_pos(s, pos)
1605 index += 1
1606 r, newindex, rettype, obj, w_obj = errorhandler(errors, "charmap",
1607 "character maps to <undefined>",
1608 w_s, startindex, index)
1609 if rettype == 'u':
1610 for cp2 in rutf8.Utf8StringIterator(r):
1611 ch2 = mapping.get(cp2, '')
1612 if not ch2:
1613 errorhandler(
1614 "strict", "charmap", "character maps to <undefined>",
1615 w_s, startindex, index)
1616 result.append(ch2)
1617 else:
1618 for ch in r:
1619 result.append(ch)
1620 s = obj
1621 # It should be rare that w_s != w_obj
1622 w_s = w_obj
1623 if index != newindex:
1624 index = newindex
1625 pos = w_obj._index_to_byte(index) # This should also be rare
1626 continue
1627 result.append(c)
1628 index += 1
1629 pos = rutf8.next_codepoint_pos(s, pos)
1630 return result.build()
1631
1632 # ____________________________________________________________
1633 # Decimal Encoder
1634 def unicode_encode_decimal(space, s, w_s, errors, errorhandler=None, allow_surrogates=False):
1635 """Converts whitespace to ' ', decimal characters to their
1636 corresponding ASCII digit and all other Latin-1 characters except
1637 \0 as-is. Characters outside this range (Unicode ordinals 1-256)
1638 are treated as errors. This includes embedded NULL bytes.
1639 """
1640 if errorhandler is None:
1641 errorhandler = default_error_encode
1642 result = StringBuilder(len(s))
1643 pos = 0
1644 i = 0
1645 it = rutf8.Utf8StringIterator(s)
1646 for ch in it:
1647 if unicodedb.isspace(ch):
1648 result.append(' ')
1649 i += 1
1650 continue
1651 try:
1652 decimal = unicodedb.decimal(ch)
1653 except KeyError:
1654 pass
1655 else:
1656 result.append(chr(48 + decimal))
1657 i += 1
1658 continue
1659 if 0 < ch < 256:
1660 result.append(chr(ch))
1661 i += 1
1662 continue
1663 # All other characters are considered unencodable
1664 start_index = i
1665 i += 1
1666 while not it.done():
1667 ch = rutf8.codepoint_at_pos(s, it.get_pos())
1668 try:
1669 if (0 < ch < 256 or unicodedb.isspace(ch) or
1670 unicodedb.decimal(ch) >= 0):
1671 break
1672 except KeyError:
1673 # not a decimal
1674 pass
1675 if it.done():
1676 break
1677 ch = next(it)
1678 i += 1
1679 end_index = i
1680 msg = "invalid decimal Unicode string"
1681 r, pos, retype, obj, w_obj = errorhandler(
1682 errors, 'decimal', msg, w_s, start_index, end_index)
1683 for ch in rutf8.Utf8StringIterator(r):
1684 if unicodedb.isspace(ch):
1685 result.append(' ')
1686 continue
1687 try:
1688 decimal = unicodedb.decimal(ch)
1689 except KeyError:
1690 pass
1691 else:
1692 result.append(chr(48 + decimal))
1693 continue
1694 if 0 < ch < 256:
1695 result.append(chr(ch))
1696 continue
1697 errorhandler('strict', 'decimal', msg, w_s, start_index, end_index)
1698 return result.build()