Debian Codegraph @

rpython/rlib/rutf8.py

raw symbols SCIP
1 """ This file is about supporting unicode strings in RPython,
2 represented by a byte string that is exactly the UTF-8 version
3 (for some definition of UTF-8).
4
5 This doesn't support Python 2's unicode characters beyond 0x10ffff,
6 which are theoretically possible to obtain using strange tricks like
7 the array or ctypes modules.
8
9 Fun comes from surrogates. Various functions don't normally accept
10 any unicode character betwen 0xd800 and 0xdfff, but do if you give
11 the 'allow_surrogates = True' flag.
12
13 This is a minimal reference implementation. A lot of interpreters
14 need their own copy-pasted copy of some of the logic here, with
15 extra code in the middle for error handlers and so on.
16 """
17
18 import sys
19 from rpython.rlib.objectmodel import enforceargs, we_are_translated, specialize
20 from rpython.rlib.objectmodel import always_inline, dont_inline, try_inline
21 from rpython.rlib.rstring import StringBuilder
22 from rpython.rlib import jit, types, rarithmetic
23 from rpython.rlib.signature import signature, finishsigs
24 from rpython.rlib.types import char, none
25 from rpython.rlib.rarithmetic import r_uint
26 from rpython.rlib.unicodedata import unicodedb
27 from rpython.rtyper.lltypesystem import lltype, rffi
28
29 # We always use MAXUNICODE = 0x10ffff when unicode objects use utf8
30 MAXUNICODE = 0x10ffff
31 allow_surrogate_by_default = False
32
33
34 class OutOfRange(Exception):
35 def __init__(self, code):
36 self.code = code
37
38 # we need a way to accept both r_uint and int(nonneg=True)
39 #@signature(types.int_nonneg(), types.bool(), returns=types.str())
40 def unichr_as_utf8(code, allow_surrogates=False):
41 """Encode code (numeric value) as utf8 encoded string
42 """
43 assert code >= 0
44 code = r_uint(code)
45 if code <= r_uint(0x7F):
46 # Encode ASCII
47 return chr(code)
48 if code <= r_uint(0x07FF):
49 return chr((0xc0 | (code >> 6))) + chr((0x80 | (code & 0x3f)))
50 if code <= r_uint(0xFFFF):
51 if not allow_surrogates and 0xD800 <= code <= 0xDfff:
52 raise OutOfRange(code)
53 return (chr((0xe0 | (code >> 12))) +
54 chr((0x80 | ((code >> 6) & 0x3f))) +
55 chr((0x80 | (code & 0x3f))))
56 if code <= r_uint(0x10FFFF):
57 return (chr((0xf0 | (code >> 18))) +
58 chr((0x80 | ((code >> 12) & 0x3f))) +
59 chr((0x80 | ((code >> 6) & 0x3f))) +
60 chr((0x80 | (code & 0x3f))))
61 raise OutOfRange(code)
62
63 @try_inline
64 def unichr_as_utf8_append(builder, code, allow_surrogates=False):
65 """Encode code (numeric value) as utf8 encoded string
66 and emit the result into the given StringBuilder.
67 Raises ValueError if the code is outside range(0x110000).
68 """
69 code = r_uint(code)
70 if code <= r_uint(0x7F):
71 # Encode ASCII
72 builder.append(chr(code))
73 else:
74 # Encode non-ASCII, uses a function call
75 if allow_surrogates:
76 _nonascii_unichr_as_utf8_append(builder, code)
77 else:
78 _nonascii_unichr_as_utf8_append_nosurrogates(builder, code)
79
80 @dont_inline
81 def _nonascii_unichr_as_utf8_append(builder, code):
82 if code <= r_uint(0x07FF):
83 builder.append(chr((0xc0 | (code >> 6))))
84 builder.append(chr((0x80 | (code & 0x3f))))
85 return
86 if code <= r_uint(0xFFFF):
87 builder.append(chr((0xe0 | (code >> 12))))
88 builder.append(chr((0x80 | ((code >> 6) & 0x3f))))
89 builder.append(chr((0x80 | (code & 0x3f))))
90 return
91 if code <= r_uint(0x10FFFF):
92 builder.append(chr((0xf0 | (code >> 18))))
93 builder.append(chr((0x80 | ((code >> 12) & 0x3f))))
94 builder.append(chr((0x80 | ((code >> 6) & 0x3f))))
95 builder.append(chr((0x80 | (code & 0x3f))))
96 return
97 raise OutOfRange(code)
98
99 @dont_inline
100 def _nonascii_unichr_as_utf8_append_nosurrogates(builder, code):
101 if code <= r_uint(0x07FF):
102 builder.append(chr((0xc0 | (code >> 6))))
103 builder.append(chr((0x80 | (code & 0x3f))))
104 return
105 if code <= r_uint(0xFFFF):
106 if 0xd800 <= code <= 0xdfff:
107 raise ValueError
108 builder.append(chr((0xe0 | (code >> 12))))
109 builder.append(chr((0x80 | ((code >> 6) & 0x3f))))
110 builder.append(chr((0x80 | (code & 0x3f))))
111 return
112 if code <= r_uint(0x10FFFF):
113 builder.append(chr((0xf0 | (code >> 18))))
114 builder.append(chr((0x80 | ((code >> 12) & 0x3f))))
115 builder.append(chr((0x80 | ((code >> 6) & 0x3f))))
116 builder.append(chr((0x80 | (code & 0x3f))))
117 return
118 raise OutOfRange(code)
119
120
121 # note - table lookups are really slow. Measured on various elements of obama
122 # chinese wikipedia, they're anywhere between 10% and 30% slower.
123 # In extreme cases (small, only chinese text), they're 40% slower
124
125 # The following was found by hand to be more optimal than both,
126 # on x86-64...
127 _is_64bit = sys.maxint > 2**32
128 _constant_ncp = rarithmetic.r_uint64(0xffff0000ffffffff)
129
130 @always_inline
131 def next_codepoint_pos(code, pos):
132 """Gives the position of the next codepoint after pos.
133 Assumes valid utf8. 'pos' must be before the end of the string.
134 """
135 assert pos >= 0
136 chr1 = ord(code[pos])
137 if chr1 <= 0x7F:
138 return pos + 1
139 if _is_64bit and not jit.we_are_jitted():
140 # optimized for Intel x86-64 by hand
141 res = pos + 1 + (
142 ((chr1 > 0xDF) << 1) +
143 (rarithmetic.intmask(_constant_ncp >> (chr1 & 0x3F)) & 1))
144 assert res >= 0
145 return res
146 if chr1 <= 0xDF:
147 return pos + 2
148 if chr1 <= 0xEF:
149 return pos + 3
150 return pos + 4
151
152 def prev_codepoint_pos(code, pos):
153 """Gives the position of the previous codepoint.
154 'pos' must not be zero.
155 """
156 pos -= 1
157 assert pos >= 0
158 if pos >= len(code): # for the case where pos - 1 == len(code):
159 return pos # assume there is an extra '\x00' character
160 chr1 = ord(code[pos])
161 if chr1 <= 0x7F:
162 return pos
163 pos -= 1
164 assert pos >= 0
165 if ord(code[pos]) >= 0xC0:
166 return pos
167 pos -= 1
168 assert pos >= 0
169 if ord(code[pos]) >= 0xC0:
170 return pos
171 pos -= 1
172 assert pos >= 0
173 return pos
174
175 def codepoint_at_pos(code, pos):
176 """ Give a codepoint in code at pos - assumes valid utf8, no checking!
177 """
178 lgt = len(code)
179 ordch1 = ord(code[pos])
180 if ordch1 <= 0x7F or pos +1 >= lgt:
181 return ordch1
182 ordch2 = ord(code[pos+1])
183 if ordch1 <= 0xDF or pos +2 >= lgt:
184 # 110yyyyy 10zzzzzz -> 00000000 00000yyy yyzzzzzz
185 return (ordch1 << 6) + ordch2 - (
186 (0xC0 << 6) + 0x80 )
187
188 ordch3 = ord(code[pos+2])
189 if ordch1 <= 0xEF or pos + 3 >= lgt:
190 # 1110xxxx 10yyyyyy 10zzzzzz -> 00000000 xxxxyyyy yyzzzzzz
191 return (ordch1 << 12) + (ordch2 << 6) + ordch3 - (
192 (0xE0 << 12) + (0x80 << 6) + 0x80 )
193
194 ordch4 = ord(code[pos+3])
195 if True:
196 # 11110www 10xxxxxx 10yyyyyy 10zzzzzz -> 000wwwxx xxxxyyyy yyzzzzzz
197 return (ordch1 << 18) + (ordch2 << 12) + (ordch3 << 6) + ordch4 - (
198 (0xF0 << 18) + (0x80 << 12) + (0x80 << 6) + 0x80 )
199 assert False, "unreachable"
200
201 def codepoint_before_pos(code, pos):
202 """Give a codepoint in code at the position immediately before pos
203 - assumes valid utf8, no checking!
204 """
205 pos = r_uint(pos)
206 ordch1 = ord(code[pos-1])
207 if ordch1 <= 0x7F:
208 return ordch1
209
210 ordch2 = ordch1
211 ordch1 = ord(code[pos-2])
212 if ordch1 >= 0xC0:
213 # 110yyyyy 10zzzzzz -> 00000000 00000yyy yyzzzzzz
214 return (((ordch1 & 0x1F) << 6) + # 0b00011111
215 (ordch2 & 0x3F)) # 0b00111111
216
217 ordch3 = ordch2
218 ordch2 = ordch1
219 ordch1 = ord(code[pos-3])
220 if ordch1 >= 0xC0:
221 # 1110xxxx 10yyyyyy 10zzzzzz -> 00000000 xxxxyyyy yyzzzzzz
222 return (((ordch1 & 0x0F) << 12) + # 0b00001111
223 ((ordch2 & 0x3F) << 6) + # 0b00111111
224 (ordch3 & 0x3F)) # 0b00111111
225
226 ordch4 = ordch3
227 ordch3 = ordch2
228 ordch2 = ordch1
229 ordch1 = ord(code[pos-4])
230 if True:
231 # 11110www 10xxxxxx 10yyyyyy 10zzzzzz -> 000wwwxx xxxxyyyy yyzzzzzz
232 return (((ordch1 & 0x07) << 18) + # 0b00000111
233 ((ordch2 & 0x3F) << 12) + # 0b00111111
234 ((ordch3 & 0x3F) << 6) + # 0b00111111
235 (ordch4 & 0x3F)) # 0b00111111
236 assert False, "unreachable"
237
238 class CheckError(Exception):
239 def __init__(self, pos):
240 self.pos = pos
241
242 def check_ascii(s):
243 res = first_non_ascii_char(s)
244 if res < 0:
245 return
246 raise CheckError(res)
247
248 @jit.elidable
249 def first_non_ascii_char(s):
250 for i in range(len(s)):
251 if ord(s[i]) > 0x7F:
252 return i
253 return -1
254
255 def islinebreak(s, pos):
256 chr1 = ord(s[pos])
257 if 0xa <= chr1 <= 0xd:
258 return True
259 if 0x1c <= chr1 <= 0x1e:
260 return True
261 if chr1 == 0xc2:
262 chr2 = ord(s[pos + 1])
263 return chr2 == 0x85
264 elif chr1 == 0xe2:
265 chr2 = ord(s[pos + 1])
266 if chr2 != 0x80:
267 return False
268 chr3 = ord(s[pos + 2])
269 return chr3 == 0xa8 or chr3 == 0xa9
270 return False
271
272 def isspace(s, pos):
273 chr1 = ord(s[pos])
274 if (chr1 == ord(' ') or chr1 == ord('\n') or chr1 == ord('\t') or
275 chr1 == ord('\r')):
276 return True # common
277 if chr1 == 0x0b or chr1 == 0x0c or (chr1 >= 0x1c and chr1 <= 0x1f):
278 return True # less common
279 if chr1 < 0x80:
280 return False
281 # obscure cases
282 chr2 = ord(s[pos + 1])
283 if chr1 == 0xc2:
284 return chr2 == 0x85 or chr2 == 0xa0
285 if chr1 == 0xe2:
286 if chr2 == 0x81 and s[pos + 2] == '\x9f':
287 return True
288 if chr2 != 0x80:
289 return False
290 chr3 = ord(s[pos + 2])
291 if chr3 >= 0x80 and chr3 <= 0x8a:
292 return True
293 if chr3 == 0xa9 or chr3 == 0xa8 or chr3 == 0xaf:
294 return True
295 return False
296 if chr1 == 0xe1:
297 chr3 = ord(s[pos + 2])
298 if chr2 == 0x9a and chr3 == 0x80:
299 return True
300 if chr2 == 0xa0 and chr3 == 0x8e:
301 return True
302 return False
303 if chr1 == 0xe3 and chr2 == 0x80 and s[pos + 2] == '\x80':
304 return True
305 return False
306
307 def utf8_in_chars(value, pos, chars):
308 """Equivalent of u'x' in u'xyz', where the left-hand side is
309 a single UTF-8 character extracted from the string 'value' at 'pos'.
310 Only works if both 'value' and 'chars' are correctly-formed UTF-8
311 strings.
312 """
313 end = next_codepoint_pos(value, pos)
314 i = 0
315 while i < len(chars):
316 k = pos
317 while value[k] == chars[i]:
318 k += 1
319 i += 1
320 if k == end:
321 return True
322 i += 1
323 return False
324
325
326 def _invalid_cont_byte(ordch):
327 signedchar = rffi.cast(rffi.SIGNEDCHAR, ordch)
328 return rffi.cast(lltype.Signed, signedchar) >= -0x40
329
330 _invalid_byte_2_of_2 = _invalid_cont_byte
331 _invalid_byte_3_of_3 = _invalid_cont_byte
332 _invalid_byte_3_of_4 = _invalid_cont_byte
333 _invalid_byte_4_of_4 = _invalid_cont_byte
334
335 def _surrogate_bytes(ch1, ch2):
336 return ch1 == 0xed and ch2 > 0x9f
337
338 @enforceargs(allow_surrogates=bool)
339 def _invalid_byte_2_of_3(ordch1, ordch2, allow_surrogates):
340 return (_invalid_cont_byte(ordch2) or
341 (ordch1 == 0xe0 and ordch2 < 0xa0)
342 # surrogates shouldn't be valid UTF-8!
343 or (ordch1 == 0xed and ordch2 > 0x9f and not allow_surrogates))
344
345 def _invalid_byte_2_of_4(ordch1, ordch2):
346 return (_invalid_cont_byte(ordch2) or
347 (ordch1 == 0xf0 and ordch2 < 0x90) or
348 (ordch1 == 0xf4 and ordch2 > 0x8f))
349
350
351 def check_utf8(s, allow_surrogates, start=0, stop=-1):
352 """Check that 's' is a utf-8-encoded byte string.
353
354 Returns the length (number of chars) or raise CheckError.
355 If allow_surrogates is False, then also raise if we see any.
356 Note also codepoints_in_utf8(), which also computes the length
357 faster by assuming that 's' is valid utf-8.
358 """
359 res = _check_utf8(s, allow_surrogates, start, stop)
360 if res >= 0:
361 return res
362 raise CheckError(~res)
363
364 def get_utf8_length(s, start=0, end=-1):
365 # DEPRECATED! use codepoints_in_utf8 instead
366 """ Get the length out of valid utf8.
367 """
368 if end < 0:
369 end = len(s)
370 return codepoints_in_utf8(s, start, end)
371
372 @jit.elidable
373 def _check_utf8(s, allow_surrogates, start, stop):
374 pos = start
375 continuation_bytes = 0
376 if stop < 0:
377 end = len(s)
378 else:
379 end = stop
380 while pos < end:
381 ordch1 = ord(s[pos])
382 pos += 1
383 # fast path for ASCII
384 if ordch1 <= 0x7F:
385 continue
386
387 if ordch1 <= 0xC1:
388 return ~(pos - 1)
389
390 if ordch1 <= 0xDF:
391 if pos >= end:
392 return ~(pos - 1)
393 ordch2 = ord(s[pos])
394 pos += 1
395
396 if _invalid_byte_2_of_2(ordch2):
397 return ~(pos - 2)
398 # 110yyyyy 10zzzzzz -> 00000000 00000yyy yyzzzzzz
399 continuation_bytes += 1
400 continue
401
402 if ordch1 <= 0xEF:
403 if (pos + 2) > end:
404 return ~(pos - 1)
405 ordch2 = ord(s[pos])
406 ordch3 = ord(s[pos + 1])
407 pos += 2
408
409 if (_invalid_byte_2_of_3(ordch1, ordch2, allow_surrogates) or
410 _invalid_byte_3_of_3(ordch3)):
411 return ~(pos - 3)
412
413 # 1110xxxx 10yyyyyy 10zzzzzz -> 00000000 xxxxyyyy yyzzzzzz
414 continuation_bytes += 2
415 continue
416
417 if ordch1 <= 0xF4:
418 if (pos + 3) > end:
419 return ~(pos - 1)
420 ordch2 = ord(s[pos])
421 ordch3 = ord(s[pos + 1])
422 ordch4 = ord(s[pos + 2])
423 pos += 3
424
425 if (_invalid_byte_2_of_4(ordch1, ordch2) or
426 _invalid_byte_3_of_4(ordch3) or
427 _invalid_byte_4_of_4(ordch4)):
428 return ~(pos - 4)
429 # 11110www 10xxxxxx 10yyyyyy 10zzzzzz -> 000wwwxx xxxxyyyy yyzzzzzz
430 continuation_bytes += 3
431 continue
432
433 return ~(pos - 1)
434 assert pos == end
435 result = pos - continuation_bytes - start
436 assert result >= 0
437 return result
438
439 def has_surrogates(utf8):
440 return surrogate_in_utf8(utf8) >= 0
441
442 def reencode_utf8_with_surrogates(utf8):
443 """ Receiving valid UTF8 which contains surrogates, combine surrogate
444 pairs into correct UTF8 with pairs collpased. This is a rare case
445 and you should not be using surrogate pairs in the first place,
446 so the performance here is a bit secondary
447 """
448 s = StringBuilder(len(utf8))
449 stop = len(utf8)
450 i = 0
451 while i < stop:
452 uchr = codepoint_at_pos(utf8, i)
453 if 0xD800 <= uchr <= 0xDBFF:
454 high = uchr
455 i = next_codepoint_pos(utf8, i)
456 if i >= stop:
457 unichr_as_utf8_append(s, uchr, True)
458 break
459 low = codepoint_at_pos(utf8, i)
460 if 0xDC00 <= low <= 0xDFFF:
461 uchr = 0x10000 + (high - 0xD800) * 0x400 + (low - 0xDC00)
462 i = next_codepoint_pos(utf8, i)
463 # else not really a surrogate pair, just append high
464 else:
465 i = next_codepoint_pos(utf8, i)
466 unichr_as_utf8_append(s, uchr, True)
467 return s.build()
468
469
470 @jit.elidable
471 def codepoints_in_utf8(value, start=0, end=sys.maxint):
472 """Return the number of codepoints in the UTF-8 byte string
473 'value[start:end]'. Assumes 0 <= start <= len(value) and start <= end.
474 """
475 if end > len(value):
476 end = len(value)
477 assert 0 <= start <= end
478 length = 0
479 for i in range(start, end):
480 # we want to count the number of chars not between 0x80 and 0xBF;
481 # we do that by casting the char to a signed integer
482 signedchar = rffi.cast(rffi.SIGNEDCHAR, ord(value[i]))
483 if rffi.cast(lltype.Signed, signedchar) >= -0x40:
484 length += 1
485 return length
486
487
488 @jit.elidable
489 def surrogate_in_utf8(utf8):
490 """Check if the UTF-8 byte string 'value' contains a surrogate.
491 The 'value' argument must be otherwise correctly formed for UTF-8.
492 Returns the position of the first surrogate, otherwise -1.
493 """
494 # a surrogate starts with 0xed in utf-8 encoding
495 pos = 0
496 while True:
497 pos = utf8.find("\xed", pos)
498 if pos < 0:
499 return -1
500 assert pos <= len(utf8) - 1 # otherwise invalid utf-8
501 ordch2 = ord(utf8[pos + 1])
502 if _invalid_byte_2_of_3(0xed, ordch2, allow_surrogates=False):
503 return pos
504 pos += 1
505 return -1
506
507
508 UTF8_INDEX_STORAGE = lltype.GcArray(lltype.Struct('utf8_loc_elem',
509 ('baseindex', lltype.Signed),
510 ('ofs', lltype.FixedSizeArray(lltype.Char, 16)),
511 ))
512
513 def null_storage():
514 return lltype.nullptr(UTF8_INDEX_STORAGE)
515
516 def create_utf8_index_storage(utf8, utf8len):
517 """ Create an index storage which stores index of each 4th character
518 in utf8 encoded unicode string.
519 """
520 arraysize = utf8len // 64 + 1
521 storage = lltype.malloc(UTF8_INDEX_STORAGE, arraysize)
522 baseindex = 0
523 current = 0
524 while True:
525 storage[current].baseindex = baseindex
526 next = baseindex
527 for i in range(16):
528 if utf8len == 0:
529 next += 1 # assume there is an extra '\x00' character
530 else:
531 next = next_codepoint_pos(utf8, next)
532 storage[current].ofs[i] = chr(next - baseindex)
533 utf8len -= 4
534 if utf8len < 0:
535 assert current + 1 == len(storage)
536 break
537 next = next_codepoint_pos(utf8, next)
538 next = next_codepoint_pos(utf8, next)
539 next = next_codepoint_pos(utf8, next)
540 else:
541 current += 1
542 baseindex = next
543 continue
544 break
545 return storage
546
547 @jit.elidable
548 def codepoint_position_at_index(utf8, storage, index):
549 """ Return byte index of a character inside utf8 encoded string, given
550 storage of type UTF8_INDEX_STORAGE. The index must be smaller than
551 or equal to the utf8 length: if needed, check explicitly before calling
552 this function.
553 """
554 current = index >> 6
555 ofs = ord(storage[current].ofs[(index >> 2) & 0x0F])
556 bytepos = storage[current].baseindex + ofs
557 index &= 0x3
558 if index == 0:
559 return prev_codepoint_pos(utf8, bytepos)
560 elif index == 1:
561 assert bytepos >= 0
562 return bytepos
563 elif index == 2:
564 return next_codepoint_pos(utf8, bytepos)
565 else:
566 return next_codepoint_pos(utf8, next_codepoint_pos(utf8, bytepos))
567
568 def _pos_at_index(utf8, index):
569 # Slow!
570 pos = 0
571 for _ in range(index):
572 pos = next_codepoint_pos(utf8, pos)
573 return pos
574
575 @jit.elidable
576 def codepoint_at_index(utf8, storage, index):
577 """ Return codepoint of a character inside utf8 encoded string, given
578 storage of type UTF8_INDEX_STORAGE
579 """
580 current = index >> 6
581 ofs = ord(storage[current].ofs[(index >> 2) & 0x0F])
582 bytepos = storage[current].baseindex + ofs
583 index &= 0x3
584 if index == 0:
585 return codepoint_before_pos(utf8, bytepos)
586 if index == 3:
587 bytepos = next_codepoint_pos(utf8, bytepos)
588 index = 2 # fall-through to the next case
589 if index == 2:
590 bytepos = next_codepoint_pos(utf8, bytepos)
591 return codepoint_at_pos(utf8, bytepos)
592
593 @jit.elidable
594 def codepoint_index_at_byte_position(utf8, storage, bytepos, num_codepoints):
595 """ Return the character index for which
596 codepoint_position_at_index(index) == bytepos.
597 This is a relatively slow operation in that it runs in a time
598 logarithmic in the length of the string, plus some constant that
599 is not tiny either.
600 """
601 if bytepos < 0:
602 return bytepos
603 # binary search on elements of storage
604 bytes_remaining = len(utf8) - bytepos
605 # the fact that one codepoint is encoded in 1-4 bytes constrains the result.
606 # pick good min and max indexes based on this observation. saves a few
607 # bisection steps.
608 index_min = max(bytepos // 4, num_codepoints - bytes_remaining - 1) >> 6
609 index_max = min(bytepos, num_codepoints - bytes_remaining // 4) >> 6
610 while index_min < index_max:
611 # this addition can't overflow because storage has a length that is
612 # 1/64 of the length of a string
613 index_middle = (index_min + index_max + 1) // 2
614 base_bytepos = storage[index_middle].baseindex
615 if bytepos < base_bytepos:
616 index_max = index_middle - 1
617 else:
618 index_min = index_middle
619
620 baseindex = storage[index_min].baseindex
621 if baseindex == bytepos:
622 return index_min << 6
623
624 # use ofs to get closer to the correct character index
625 result = index_min << 6
626 bytepos1 = baseindex
627 if index_min == len(storage) - 1:
628 maxindex = ((num_codepoints - 1) >> 2) & 0x0F
629 else:
630 maxindex = 16
631 for i in range(maxindex):
632 x = baseindex + ord(storage[index_min].ofs[i])
633 if x >= bytepos:
634 break
635 bytepos1 = x
636 result = (index_min << 6) + (i << 2) + 1
637
638 # this loop should runs at most four times
639 while bytepos1 < bytepos:
640 bytepos1 = next_codepoint_pos(utf8, bytepos1)
641 result += 1
642 return result
643
644
645 TABLE = '0123456789abcdef'
646
647 def char_escape_helper(result, char):
648 if char >= 0x10000 or char < 0:
649 result.append("\\U")
650 zeros = 8
651 elif char >= 0x100:
652 result.append("\\u")
653 zeros = 4
654 else:
655 result.append("\\x")
656 zeros = 2
657 for i in range(zeros-1, -1, -1):
658 result.append(TABLE[(char >> (4 * i)) & 0x0f])
659
660 def make_utf8_escape_function(pass_printable=False, quotes=False, prefix=None, unicodedb=None):
661 if pass_printable:
662 assert unicodedb is not None, "need to give unicodedb explicitly!"
663
664 @jit.elidable
665 def unicode_escape(s):
666 size = len(s)
667 result = StringBuilder(size)
668
669 if quotes:
670 if prefix:
671 result.append(prefix)
672 if s.find('\'') != -1 and s.find('\"') == -1:
673 quote = ord('\"')
674 result.append('"')
675 else:
676 quote = ord('\'')
677 result.append('\'')
678 else:
679 quote = 0
680
681 if size == 0:
682 return ''
683
684 pos = 0
685 while pos < size:
686 oc = codepoint_at_pos(s, pos)
687 ch = s[pos]
688
689 # Escape quotes
690 if quotes and (oc == quote or ch == '\\'):
691 result.append('\\')
692 next_pos = next_codepoint_pos(s, pos)
693 result.append_slice(s, pos, next_pos)
694 pos = next_pos
695 continue
696
697 # The following logic is enabled only if MAXUNICODE == 0xffff, or
698 # for testing on top of a host Python where sys.maxunicode == 0xffff
699 if (not we_are_translated() and sys.maxunicode == 0xFFFF and
700 0xD800 <= oc < 0xDC00 and pos + 3 < size):
701 # Map UTF-16 surrogate pairs to Unicode \UXXXXXXXX escapes.
702
703 if 0xDC00 <= oc2 <= 0xDFFF:
704 ucs = (((oc & 0x03FF) << 10) | (oc2 & 0x03FF)) + 0x00010000
705 char_escape_helper(result, ucs)
706 pos += 6
707 continue
708 # Fall through: isolated surrogate, process ch/oc as-is below
709
710 # Map special whitespace to '\t', \n', '\r'
711 if ch == '\t':
712 result.append('\\t')
713 elif ch == '\n':
714 result.append('\\n')
715 elif ch == '\r':
716 result.append('\\r')
717 elif ch == '\\':
718 result.append('\\\\')
719
720 # Map non-printable or non-ascii to '\xhh' or '\uhhhh'
721 elif pass_printable and not (oc <= 0x10ffff and unicodedb.isprintable(oc)):
722 char_escape_helper(result, oc)
723 elif not pass_printable and (oc < 32 or oc >= 0x7F):
724 char_escape_helper(result, oc)
725
726 # Copy everything else as-is
727 else:
728 if oc < 128:
729 result.append(ch)
730 else:
731 next_pos = next_codepoint_pos(s, pos)
732 result.append_slice(s, pos, next_pos)
733 pos = next_codepoint_pos(s, pos)
734
735 if quotes:
736 result.append(chr(quote))
737 return result.build()
738
739 return unicode_escape #, char_escape_helper
740
741 @finishsigs
742 class Utf8StringBuilder(object):
743 @always_inline
744 def __init__(self, size=0):
745 self._s = StringBuilder(size)
746 self._lgt = 0
747
748 @always_inline
749 def append(self, s):
750 # for strings
751 self._s.append(s)
752 newlgt = codepoints_in_utf8(s)
753 self._lgt += newlgt
754
755 @always_inline
756 def append_slice(self, s, start, end):
757 self._s.append_slice(s, start, end)
758 newlgt = codepoints_in_utf8(s, start, end)
759 self._lgt += newlgt
760
761 @signature(types.self(), char(), returns=none())
762 @always_inline
763 def append_char(self, s):
764 # for characters, ascii
765 self._s.append(s)
766 self._lgt += 1
767
768 @try_inline
769 def append_code(self, code):
770 unichr_as_utf8_append(self._s, code, True)
771 self._lgt += 1
772
773 @always_inline
774 def append_utf8(self, utf8, length):
775 self._s.append(utf8)
776 self._lgt += length
777
778 @always_inline
779 def append_utf8_slice(self, utf8, start, end, slicelength):
780 self._s.append_slice(utf8, start, end)
781 self._lgt += slicelength
782 if not we_are_translated():
783 assert len(utf8[start: end].decode("utf-8")) == slicelength
784
785 @always_inline
786 def append_multiple_char(self, utf8, times):
787 self._s.append(utf8 * times)
788 self._lgt += times
789
790 @always_inline
791 def build(self):
792 return self._s.build()
793
794 @always_inline
795 def getlength(self):
796 return self._lgt
797
798 class Utf8StringIterator(object):
799 def __init__(self, utf8s):
800 self._utf8 = utf8s
801 self._end = len(utf8s)
802 self._pos = 0
803
804 def __iter__(self):
805 return self
806
807 def get_pos(self):
808 return self._pos
809
810 def done(self):
811 return self._pos == self._end
812
813 @always_inline
814 def next(self):
815 pos = self._pos
816 if pos == self._end:
817 raise StopIteration
818 #----- sane-looking version: ------
819 #ret = codepoint_at_pos(self._utf8, self._pos)
820 #self._pos = next_codepoint_pos(self._utf8, self._pos)
821 #return ret
822 #----- manually inlined version follows, with merged checks -----
823
824 code = self._utf8
825 ordch1 = ord(code[pos])
826 if ordch1 <= 0x7F:
827 self._pos = pos + 1
828 return ordch1
829 if pos + 1 >= len(code):
830 self._pos = pos + 1
831 return ordch1
832
833 ordch2 = ord(code[pos+1])
834 if ordch1 <= 0xDF:
835 # 110yyyyy 10zzzzzz -> 00000000 00000yyy yyzzzzzz
836 self._pos = pos + 2
837 return (ordch1 << 6) + ordch2 - (
838 (0xC0 << 6) + 0x80 )
839
840 ordch3 = ord(code[pos+2])
841 if ordch1 <= 0xEF:
842 # 1110xxxx 10yyyyyy 10zzzzzz -> 00000000 xxxxyyyy yyzzzzzz
843 self._pos = pos + 3
844 return (ordch1 << 12) + (ordch2 << 6) + ordch3 - (
845 (0xE0 << 12) + (0x80 << 6) + 0x80 )
846
847 ordch4 = ord(code[pos+3])
848 if True:
849 # 11110www 10xxxxxx 10yyyyyy 10zzzzzz -> 000wwwxx xxxxyyyy yyzzzzzz
850 self._pos = pos + 4
851 return (ordch1 << 18) + (ordch2 << 12) + (ordch3 << 6) + ordch4 - (
852 (0xF0 << 18) + (0x80 << 12) + (0x80 << 6) + 0x80 )
853 assert False, "unreachable"
854
855 class Utf8StringPosIterator(object):
856 def __init__(self, utf8s):
857 self.it = Utf8StringIterator(utf8s)
858
859 def __iter__(self):
860 return self
861
862 def next(self):
863 pos = self.it.get_pos()
864 return (self.it.next(), pos)
865
866
867 def decode_latin_1(s):
868 if len(s) == 0:
869 return s
870 if len(s) == 1 and ord(s[0]) <= 0x7F:
871 return s
872 try:
873 check_ascii(s)
874 return s
875 except CheckError:
876 return _decode_latin_1_slowpath(s)
877
878 def _decode_latin_1_slowpath(s):
879 res = StringBuilder(len(s))
880 i = 0
881 while i < len(s):
882 if ord(s[i]) > 0x7F:
883 while i < len(s) and ord(s[i]) > 0x7F:
884 unichr_as_utf8_append(res, ord(s[i]))
885 i += 1
886 else:
887 start = i
888 end = i + 1
889 while end < len(s) and ord(s[end]) <= 0x7F:
890 end += 1
891 res.append_slice(s, start, end)
892 i = end
893 return res.build()