Debian Codegraph @

rpython/rlib/rstring.py

raw symbols SCIP
1 """ String builder interface and string functions
2 """
3 import sys
4
5 from rpython.annotator.model import (SomeObject, SomeString, s_None, SomeChar,
6 SomeInteger, SomeUnicodeCodePoint, SomeUnicodeString, SomePBC)
7 from rpython.rtyper.llannotation import SomePtr
8 from rpython.rlib import jit
9 from rpython.rlib.objectmodel import newlist_hint, resizelist_hint, specialize, not_rpython
10 from rpython.rlib.rarithmetic import ovfcheck, LONG_BIT as BLOOM_WIDTH, intmask
11 from rpython.rtyper.extregistry import ExtRegistryEntry
12 from rpython.tool.pairtype import pairtype
13
14
15 # -------------- public API for string functions -----------------------
16
17 @specialize.ll_and_arg(2)
18 def _isspace(s, pos, isutf8=False):
19 from rpython.rlib.unicodedata import unicodedb_5_2_0 as unicodedb
20 if isutf8:
21 from rpython.rlib import rutf8
22 return rutf8.isspace(s, pos)
23 char = s[pos]
24 if isinstance(char, str):
25 return char.isspace()
26 else:
27 assert isinstance(char, unicode)
28 return unicodedb.isspace(ord(char))
29
30 @specialize.ll_and_arg(2)
31 def _incr(s, pos, isutf8):
32 if isutf8:
33 from rpython.rlib.rutf8 import next_codepoint_pos
34 assert pos >= 0
35 r = next_codepoint_pos(s, pos)
36 assert r >= 0
37 return r
38 else:
39 return pos + 1
40
41 @specialize.ll_and_arg(2)
42 def _decr(s, pos, isutf8):
43 if isutf8:
44 from rpython.rlib.rutf8 import prev_codepoint_pos
45 if pos <= 0:
46 return -1
47 return intmask(prev_codepoint_pos(s, pos))
48 else:
49 return pos - 1
50
51 @specialize.ll_and_arg(3)
52 def split(value, by=None, maxsplit=-1, isutf8=False):
53 if by is None:
54 length = len(value)
55 i = 0
56 res = []
57 while True:
58 # find the beginning of the next word
59 while i < length:
60 if not _isspace(value, i, isutf8):
61 break # found
62 i = _incr(value, i, isutf8)
63 else:
64 break # end of string, finished
65
66 # find the end of the word
67 if maxsplit == 0:
68 j = length # take all the rest of the string
69 else:
70 j = _incr(value, i, isutf8)
71 while j < length and not _isspace(value, j, isutf8):
72 j = _incr(value, j, isutf8)
73 maxsplit -= 1 # NB. if it's already < 0, it stays < 0
74
75 # the word is value[i:j]
76 res.append(value[i:j])
77
78 # continue to look from the character following the space after the word
79 if j < length:
80 i = _incr(value, j, isutf8)
81 else:
82 break
83 return res
84 else:
85 return _split_by(value, by, maxsplit)
86
87 @specialize.argtype(0)
88 def _split_by(value, by, maxsplit):
89 if isinstance(value, unicode):
90 assert isinstance(by, unicode)
91 if isinstance(value, str):
92 assert isinstance(by, str)
93 if isinstance(value, list):
94 assert isinstance(by, str)
95
96 bylen = len(by)
97 if bylen == 0:
98 raise ValueError("empty separator")
99 # XXX measure if preallocating the result list to the correct
100 # size is faster, should be
101
102 start = 0
103 if bylen == 1:
104 # fast path: uses str.find(character) and str.count(character)
105 by = by[0] # annotator hack: string -> char
106 cnt = count(value, by, 0, len(value))
107 if cnt == 0:
108 if isinstance(value, str):
109 return [value]
110 return [value[0:len(value)]]
111 if 0 <= maxsplit < cnt:
112 cnt = maxsplit
113 res = newlist_hint(cnt + 1)
114 while cnt > 0:
115 next = find(value, by, start, len(value))
116 assert next >= 0 # cannot fail due to the value.count above
117 res.append(value[start:next])
118 start = next + bylen
119 cnt -= 1
120 res.append(value[start:len(value)])
121 return res
122
123 if maxsplit > 0:
124 res = newlist_hint(min(maxsplit + 1, len(value)))
125 else:
126 res = []
127
128 while maxsplit != 0:
129 next = find(value, by, start, len(value))
130 if next < 0:
131 break
132 assert start >= 0
133 res.append(value[start:next])
134 start = next + bylen
135 maxsplit -= 1 # NB. if it's already < 0, it stays < 0
136
137 res.append(value[start:len(value)])
138 return res
139
140
141 @specialize.ll_and_arg(3)
142 def rsplit(value, by=None, maxsplit=-1, isutf8=False):
143 if by is None:
144 res = []
145
146 i = _decr(value, len(value), isutf8)
147 while True:
148 # starting from the end, find the end of the next word
149 while i >= 0:
150 if not _isspace(value, i, isutf8):
151 break # found
152 i = _decr(value, i, isutf8)
153 else:
154 break # end of string, finished
155
156 # find the start of the word as 'j1'
157 if maxsplit == 0:
158 j1 = 0 # take all the rest of the string
159 j = -1
160 else:
161 j1 = i
162 while True:
163 j = _decr(value, j1, isutf8)
164 if j < 0 or _isspace(value, j, isutf8):
165 break
166 j1 = j
167 maxsplit -= 1 # NB. if it's already < 0, it stays < 0
168
169 # the word is value[j1:i+1]
170 assert j1 >= 0
171 i1 = _incr(value, i, isutf8)
172 res.append(value[j1:i1])
173
174 # continue to look from the character before the space before the word
175 i = _decr(value, j, isutf8)
176
177 res.reverse()
178 return res
179 else:
180 return _rsplit_by(value, by, maxsplit)
181
182 @specialize.argtype(0)
183 def _rsplit_by(value, by, maxsplit):
184 if isinstance(value, unicode):
185 assert isinstance(by, unicode)
186 if isinstance(value, str):
187 assert isinstance(by, str)
188 if isinstance(value, list):
189 assert isinstance(by, str)
190
191 if maxsplit > 0:
192 res = newlist_hint(min(maxsplit + 1, len(value)))
193 else:
194 res = []
195 end = len(value)
196 bylen = len(by)
197 if bylen == 0:
198 raise ValueError("empty separator")
199
200 while maxsplit != 0:
201 next = rfind(value, by, 0, end)
202 if next < 0:
203 break
204 res.append(value[next + bylen:end])
205 end = next
206 maxsplit -= 1 # NB. if it's already < 0, it stays < 0
207
208 res.append(value[:end])
209 res.reverse()
210 return res
211
212
213 @specialize.argtype(0, 1)
214 @jit.elidable
215 def replace(input, sub, by, maxcount=-1):
216 return replace_count(input, sub, by, maxcount)[0]
217
218 @specialize.ll_and_arg(4)
219 @jit.elidable
220 def replace_count(input, sub, by, maxcount=-1, isutf8=False):
221 if isinstance(input, str):
222 Builder = StringBuilder
223 elif isinstance(input, unicode):
224 Builder = UnicodeBuilder
225 else:
226 assert isinstance(input, list)
227 Builder = ByteListBuilder
228 if maxcount == 0:
229 return input, 0
230
231
232 if not sub and not isutf8:
233 upper = len(input)
234 if maxcount > 0 and maxcount < upper + 2:
235 upper = maxcount - 1
236 assert upper >= 0
237
238 try:
239 result_size = ovfcheck(upper * len(by))
240 result_size = ovfcheck(result_size + upper)
241 result_size = ovfcheck(result_size + len(by))
242 remaining_size = len(input) - upper
243 result_size = ovfcheck(result_size + remaining_size)
244 except OverflowError:
245 raise
246 builder = Builder(result_size)
247 for i in range(upper):
248 builder.append(by)
249 builder.append(input[i])
250 builder.append(by)
251 builder.append_slice(input, upper, len(input))
252 replacements = upper + 1
253
254 elif isinstance(input, str) and len(sub) == 1:
255 if len(by) == 1:
256 return replace_count_str_chr_chr(input, sub[0], by[0], maxcount)
257 return replace_count_str_chr_str(input, sub[0], by, maxcount)
258
259 else:
260 # First compute the exact result size
261 if sub:
262 cnt = count(input, sub, 0, len(input))
263 if isinstance(input, str) and cnt == 0:
264 return input, 0
265 if isinstance(input, str):
266 return replace_count_str_str_str(input, sub, by, cnt, maxcount)
267 else:
268 assert isutf8
269 from rpython.rlib import rutf8
270 cnt = rutf8.codepoints_in_utf8(input) + 1
271
272 if cnt > maxcount and maxcount > 0:
273 cnt = maxcount
274 diff_len = len(by) - len(sub)
275 try:
276 result_size = ovfcheck(diff_len * cnt)
277 result_size = ovfcheck(result_size + len(input))
278 except OverflowError:
279 raise
280 replacements = cnt
281
282 builder = Builder(result_size)
283 start = 0
284 sublen = len(sub)
285
286 if sublen == 0:
287 assert isutf8
288 from rpython.rlib import rutf8
289 while True:
290 builder.append(by)
291 maxcount -= 1
292 if start == len(input) or maxcount == 0:
293 break
294 next = rutf8.next_codepoint_pos(input, start)
295 builder.append_slice(input, start, next)
296 start = next
297 else:
298 while maxcount != 0:
299 next = find(input, sub, start, len(input))
300 if next < 0:
301 break
302 builder.append_slice(input, start, next)
303 builder.append(by)
304 start = next + sublen
305 maxcount -= 1 # NB. if it's already < 0, it stays < 0
306
307 builder.append_slice(input, start, len(input))
308
309 return builder.build(), replacements
310
311 def replace_count_str_chr_chr(input, c1, c2, maxcount):
312 from rpython.rtyper.annlowlevel import llstr, hlstr
313 s = llstr(input)
314 length = len(s.chars)
315 start = find(input, c1, 0, len(input))
316 if start < 0:
317 return input, 0
318 newstr = s.malloc(length)
319 src = s.chars
320 dst = newstr.chars
321 s.copy_contents(s, newstr, 0, 0, len(input))
322 dst[start] = c2
323 count = 1
324 start += 1
325 maxcount -= 1
326 while maxcount != 0:
327 next = find(input, c1, start, len(input))
328 if next < 0:
329 break
330 dst[next] = c2
331 start = next + 1
332 maxcount -= 1
333 count += 1
334
335 return hlstr(newstr), count
336
337 def replace_count_str_chr_str(input, sub, by, maxcount):
338 from rpython.rtyper.annlowlevel import llstr, hlstr
339 cnt = count(input, sub, 0, len(input))
340 if cnt == 0:
341 return input, 0
342 if maxcount > 0 and cnt > maxcount:
343 cnt = maxcount
344 diff_len = len(by) - 1
345 try:
346 result_size = ovfcheck(diff_len * cnt)
347 result_size = ovfcheck(result_size + len(input))
348 except OverflowError:
349 raise
350
351 s = llstr(input)
352 by_ll = llstr(by)
353
354 newstr = s.malloc(result_size)
355 dst = 0
356 start = 0
357 while maxcount != 0:
358 next = find(input, sub, start, len(input))
359 if next < 0:
360 break
361 s.copy_contents(s, newstr, start, dst, next - start)
362 dst += next - start
363 s.copy_contents(by_ll, newstr, 0, dst, len(by))
364 dst += len(by)
365
366 start = next + 1
367 maxcount -= 1 # NB. if it's already < 0, it stays < 0
368
369 s.copy_contents(s, newstr, start, dst, len(input) - start)
370 assert dst - start + len(input) == result_size
371 return hlstr(newstr), cnt
372
373 def replace_count_str_str_str(input, sub, by, cnt, maxcount):
374 from rpython.rtyper.annlowlevel import llstr, hlstr
375 if cnt > maxcount and maxcount > 0:
376 cnt = maxcount
377 diff_len = len(by) - len(sub)
378 try:
379 result_size = ovfcheck(diff_len * cnt)
380 result_size = ovfcheck(result_size + len(input))
381 except OverflowError:
382 raise
383
384 s = llstr(input)
385 by_ll = llstr(by)
386 newstr = s.malloc(result_size)
387 sublen = len(sub)
388 bylen = len(by)
389 inputlen = len(input)
390 dst = 0
391 start = 0
392 while maxcount != 0:
393 next = find(input, sub, start, inputlen)
394 if next < 0:
395 break
396 s.copy_contents(s, newstr, start, dst, next - start)
397 dst += next - start
398 s.copy_contents(by_ll, newstr, 0, dst, bylen)
399 dst += bylen
400 start = next + sublen
401 maxcount -= 1 # NB. if it's already < 0, it stays < 0
402 s.copy_contents(s, newstr, start, dst, len(input) - start)
403 assert dst - start + len(input) == result_size
404 return hlstr(newstr), cnt
405
406
407 def _normalize_start_end(length, start, end):
408 if start < 0:
409 start += length
410 if start < 0:
411 start = 0
412 if end < 0:
413 end += length
414 if end < 0:
415 end = 0
416 elif end > length:
417 end = length
418 return start, end
419
420 @specialize.argtype(0, 1)
421 @jit.elidable
422 def startswith(u_self, prefix, start=0, end=sys.maxint):
423 length = len(u_self)
424 start, end = _normalize_start_end(length, start, end)
425 stop = start + len(prefix)
426 if stop > end:
427 return False
428 for i in range(len(prefix)):
429 if u_self[start+i] != prefix[i]:
430 return False
431 return True
432
433 @specialize.argtype(0, 1)
434 @jit.elidable
435 def endswith(u_self, suffix, start=0, end=sys.maxint):
436 length = len(u_self)
437 start, end = _normalize_start_end(length, start, end)
438 begin = end - len(suffix)
439 if begin < start:
440 return False
441 for i in range(len(suffix)):
442 if u_self[begin+i] != suffix[i]:
443 return False
444 return True
445
446 @specialize.argtype(0, 1)
447 def find(value, other, start, end):
448 if ((isinstance(value, str) and isinstance(other, str)) or
449 (isinstance(value, unicode) and isinstance(other, unicode))):
450 return value.find(other, start, end)
451 return _search(value, other, start, end, SEARCH_FIND)
452
453 @specialize.argtype(0, 1)
454 def rfind(value, other, start, end):
455 if ((isinstance(value, str) and isinstance(other, str)) or
456 (isinstance(value, unicode) and isinstance(other, unicode))):
457 return value.rfind(other, start, end)
458 return _search(value, other, start, end, SEARCH_RFIND)
459
460 @specialize.argtype(0, 1)
461 def count(value, other, start, end):
462 if ((isinstance(value, str) and isinstance(other, str)) or
463 (isinstance(value, unicode) and isinstance(other, unicode))):
464 return value.count(other, start, end)
465 return _search(value, other, start, end, SEARCH_COUNT)
466
467 # -------------- substring searching helper ----------------
468
469 SEARCH_COUNT = 0
470 SEARCH_FIND = 1
471 SEARCH_RFIND = 2
472
473 @specialize.ll()
474 def bloom_add(mask, c):
475 return mask | (1 << (ord(c) & (BLOOM_WIDTH - 1)))
476
477 @specialize.ll()
478 def bloom(mask, c):
479 return mask & (1 << (ord(c) & (BLOOM_WIDTH - 1)))
480
481 @specialize.argtype(0, 1)
482 def _search(value, other, start, end, mode):
483 if isinstance(value, str) and isinstance(other, str):
484 return _search_elidable(value, other, start, end, mode)
485 return _search_normal(value, other, start, end, mode)
486
487 @specialize.argtype(0, 1)
488 @jit.elidable
489 def _search_elidable(value, other, start, end, mode):
490 return _search_normal(value, other, start, end, mode)
491
492 @specialize.argtype(0, 1)
493 def _search_normal(value, other, start, end, mode):
494 assert value is not None
495 if isinstance(value, unicode):
496 NUL = u'\0'
497 else:
498 NUL = '\0'
499 if start < 0:
500 start = 0
501 if end > len(value):
502 end = len(value)
503 if start > end:
504 if mode == SEARCH_COUNT:
505 return 0
506 return -1
507
508 count = 0
509 n = end - start
510 m = len(other)
511
512 if m == 0:
513 if mode == SEARCH_COUNT:
514 return end - start + 1
515 elif mode == SEARCH_RFIND:
516 return end
517 else:
518 return start
519
520 w = n - m
521
522 if w < 0:
523 if mode == SEARCH_COUNT:
524 return 0
525 return -1
526
527 mlast = m - 1
528 skip = mlast
529 mask = 0
530
531 if mode != SEARCH_RFIND:
532 for i in range(mlast):
533 mask = bloom_add(mask, other[i])
534 if other[i] == other[mlast]:
535 skip = mlast - i - 1
536 mask = bloom_add(mask, other[mlast])
537
538 i = start - 1
539 while i + 1 <= start + w:
540 i += 1
541 if value[i + mlast] == other[mlast]:
542 for j in range(mlast):
543 if value[i + j] != other[j]:
544 break
545 else:
546 if mode != SEARCH_COUNT:
547 return i
548 count += 1
549 i += mlast
550 continue
551
552 if i + m < len(value):
553 c = value[i + m]
554 else:
555 c = NUL
556 if not bloom(mask, c):
557 i += m
558 else:
559 i += skip
560 else:
561 if i + m < len(value):
562 c = value[i + m]
563 else:
564 c = NUL
565 if not bloom(mask, c):
566 i += m
567 else:
568 mask = bloom_add(mask, other[0])
569 for i in range(mlast, 0, -1):
570 mask = bloom_add(mask, other[i])
571 if other[i] == other[0]:
572 skip = i - 1
573
574 i = start + w + 1
575 while i - 1 >= start:
576 i -= 1
577 if value[i] == other[0]:
578 for j in xrange(mlast, 0, -1):
579 if value[i + j] != other[j]:
580 break
581 else:
582 return i
583 if i - 1 >= 0 and not bloom(mask, value[i - 1]):
584 i -= m
585 else:
586 i -= skip
587 else:
588 if i - 1 >= 0 and not bloom(mask, value[i - 1]):
589 i -= m
590
591 if mode != SEARCH_COUNT:
592 return -1
593 return count
594
595 # -------------- numeric parsing support --------------------
596
597 def strip_spaces(s):
598 # XXX this is not locale-dependent
599 p = 0
600 q = len(s)
601 while p < q and s[p] in ' \f\n\r\t\v':
602 p += 1
603 while p < q and s[q-1] in ' \f\n\r\t\v':
604 q -= 1
605 assert q >= p # annotator hint, don't remove
606 return s[p:q]
607
608 class ParseStringError(Exception):
609 def __init__(self, msg):
610 self.msg = msg
611
612 def __str__(self):
613 return self.msg
614
615 class InvalidBaseError(ParseStringError):
616 """Signals an invalid base argument"""
617
618 class ParseStringOverflowError(Exception):
619 def __init__(self, parser):
620 self.parser = parser
621
622 class MaxDigitsError(Exception):
623 def __init__(self, digits):
624 self.digits = digits
625
626 # iterator-like class
627 class NumberStringParser:
628
629 def error(self):
630 raise ParseStringError("invalid literal for %s() with base %d" %
631 (self.fname, self.original_base))
632
633 def __init__(self, s, literal, base, fname, allow_underscores=False,
634 no_implicit_octal=False, start=0, end=-1, max_str_digits=0,
635 disallow_whitespace_after_sign=False):
636 self.fname = fname
637 sign = 1
638 self.s = s
639 self.start = start
640 if end == -1:
641 end = len(s)
642 self.end = end
643 self._strip_spaces()
644 if self._startswith1('-'):
645 sign = -1
646 self.start += 1
647 if not disallow_whitespace_after_sign:
648 self._strip_spaces()
649 elif self._startswith1('+'):
650 self.start += 1
651 if not disallow_whitespace_after_sign:
652 self._strip_spaces()
653 self.sign = sign
654 self.original_base = base
655 self.allow_underscores = allow_underscores
656
657 if base == 0:
658 if self._startswith2('0x') or self._startswith2('0X'):
659 base = 16
660 elif self._startswith2('0b') or self._startswith2('0B'):
661 base = 2
662 elif self._startswith1('0'): # also covers the '0o' case
663 if no_implicit_octal and not (self._startswith2('0o') or
664 self._startswith2('0O')):
665 base = 1 # this makes only the digit '0' valid...
666 else:
667 base = 8
668 else:
669 base = 10
670 elif base < 2 or base > 36:
671 raise InvalidBaseError("%s() base must be >= 2 and <= 36, or 0" % fname)
672 self.base = base
673
674 # Leading underscores are not allowed
675 if self._startswith1('_'):
676 self.error()
677
678 if base == 16 and (self._startswith2('0x') or self._startswith2('0X')):
679 self.start += 2
680 if base == 8 and (self._startswith2('0o') or self._startswith2('0O')):
681 self.start += 2
682 if base == 2 and (self._startswith2('0b') or self._startswith2('0B')):
683 self.start += 2
684 if self.start == self.end:
685 self.error()
686 self.i = self.start
687 if max_str_digits > 0:
688 length = self.end - self.start - self.s.count('_')
689 if length > max_str_digits:
690 raise MaxDigitsError(length)
691
692 def _startswith1(self, prefix):
693 if self.start >= self.end:
694 return False
695 return self.s[self.start] == prefix[0]
696 return startswith(self.s, prefix, start=self.start, end=self.end)
697
698 def _startswith2(self, prefix):
699 if self.start + 1 >= self.end:
700 return False
701 return self.s[self.start] == prefix[0] and self.s[self.start + 1] == prefix[1]
702
703 def _strip_spaces(self):
704 # XXX this is not locale-dependent
705 p = self.start
706 q = self.end
707 s = self.s
708 while p < q and s[p] in ' \f\n\r\t\v':
709 p += 1
710 while p < q and s[q-1] in ' \f\n\r\t\v':
711 q -= 1
712 assert q >= p
713 self.start = p
714 self.end = q
715
716 def rewind(self):
717 self.i = self.start
718
719 def next_digit(self): # -1 => exhausted
720 if self.i < self.end:
721 c = self.s[self.i]
722 if self.allow_underscores and c == '_':
723 self.i += 1
724 if self.i >= self.end:
725 self.error()
726 c = self.s[self.i]
727 digit = ord(c)
728 if '0' <= c <= '9':
729 digit -= ord('0')
730 elif 'A' <= c <= 'Z':
731 digit = (digit - ord('A')) + 10
732 elif 'a' <= c <= 'z':
733 digit = (digit - ord('a')) + 10
734 else:
735 self.error()
736 if digit >= self.base:
737 self.error()
738 self.i += 1
739 return digit
740 else:
741 return -1
742
743 def _all_digits10(self):
744 for index in range(self.start, self.end):
745 c = self.s[index]
746 if not ('0' <= c <= '9'):
747 if c == "_" and self.allow_underscores:
748 break
749 else:
750 self.error()
751 else:
752 # don't need a copy, no underscores
753 return self.s, self.start, self.end
754 assert self.allow_underscores
755
756 builder = StringBuilder(self.end - self.start)
757 i = 0
758 while True:
759 d = self.next_digit()
760 if d < 0:
761 return builder.build(), 0, i
762 builder.append(chr(d + ord('0')))
763 i += 1
764
765 def prev_digit(self):
766 # After exhausting all n digits in next_digit(), you can walk them
767 # again in reverse order by calling prev_digit() exactly n times
768 i = self.i - 1
769 assert i >= self.start
770 self.i = i
771 c = self.s[i]
772 if self.allow_underscores and c == '_':
773 i = self.i - 1
774 assert i >= 0
775 self.i = i
776 c = self.s[i]
777 digit = ord(c)
778 if '0' <= c <= '9':
779 digit -= ord('0')
780 elif 'A' <= c <= 'Z':
781 digit = (digit - ord('A')) + 10
782 elif 'a' <= c <= 'z':
783 digit = (digit - ord('a')) + 10
784 else:
785 raise AssertionError
786 return digit
787
788 # -------------- public API ---------------------------------
789
790 INIT_SIZE = 100 # XXX tweak
791
792
793 class AbstractStringBuilder(object):
794 # This is not the real implementation!
795
796 @not_rpython
797 def __init__(self, init_size=INIT_SIZE):
798 self._l = []
799 self._size = 0
800
801 @not_rpython
802 def _grow(self, size):
803 self._size += size
804
805 @not_rpython
806 def append(self, s):
807 assert isinstance(s, self._tp)
808 self._l.append(s)
809 self._grow(len(s))
810
811 @not_rpython
812 def append_slice(self, s, start, end):
813 assert isinstance(s, self._tp)
814 assert 0 <= start <= end <= len(s)
815 s = s[start:end]
816 self._l.append(s)
817 self._grow(len(s))
818
819 @not_rpython
820 def append_multiple_char(self, c, times):
821 assert isinstance(c, self._tp)
822 self._l.append(c * times)
823 self._grow(times)
824
825 @not_rpython
826 def append_charpsize(self, s, size):
827 assert size >= 0
828 l = []
829 for i in xrange(size):
830 l.append(s[i])
831 self._l.append(self._tp("").join(l))
832 self._grow(size)
833
834 @not_rpython
835 def build(self):
836 result = self._tp("").join(self._l)
837 assert len(result) == self._size
838 self._l = [result]
839 return result
840
841 @not_rpython
842 def getlength(self):
843 return self._size
844
845
846 class StringBuilder(AbstractStringBuilder):
847 _tp = str
848
849
850 class UnicodeBuilder(AbstractStringBuilder):
851 _tp = unicode
852
853 class ByteListBuilder(object):
854 def __init__(self, init_size=INIT_SIZE):
855 assert init_size >= 0
856 self.l = newlist_hint(init_size)
857
858 @specialize.argtype(1)
859 def append(self, s):
860 l = self.l
861 for c in s:
862 l.append(c)
863
864 @specialize.argtype(1)
865 def append_slice(self, s, start, end):
866 l = self.l
867 for i in xrange(start, end):
868 l.append(s[i])
869
870 def append_multiple_char(self, c, times):
871 assert isinstance(c, str)
872 self.l.extend([c[0]] * times)
873
874 def append_charpsize(self, s, size):
875 assert size >= 0
876 l = self.l
877 for i in xrange(size):
878 l.append(s[i])
879
880 def build(self):
881 return self.l
882
883 def getlength(self):
884 return len(self.l)
885
886 # ------------------------------------------------------------
887 # ----------------- implementation details -------------------
888 # ------------------------------------------------------------
889
890 class SomeStringBuilder(SomeObject):
891 def method_append(self, s_str):
892 if s_str != s_None:
893 assert isinstance(s_str, (SomeString, SomeChar))
894 return s_None
895
896 def method_append_slice(self, s_str, s_start, s_end):
897 if s_str != s_None:
898 assert isinstance(s_str, SomeString)
899 assert isinstance(s_start, SomeInteger)
900 assert isinstance(s_end, SomeInteger)
901 return s_None
902
903 def method_append_multiple_char(self, s_char, s_times):
904 assert isinstance(s_char, (SomeString, SomeChar))
905 assert isinstance(s_times, SomeInteger)
906 return s_None
907
908 def method_append_charpsize(self, s_ptr, s_size):
909 assert isinstance(s_ptr, SomePtr)
910 assert isinstance(s_size, SomeInteger)
911 return s_None
912
913 def method_getlength(self):
914 return SomeInteger(nonneg=True)
915
916 def method_build(self):
917 return SomeString(can_be_None=False)
918
919 def rtyper_makerepr(self, rtyper):
920 from rpython.rtyper.lltypesystem.rbuilder import stringbuilder_repr
921 return stringbuilder_repr
922
923 def rtyper_makekey(self):
924 return self.__class__,
925
926 def noneify(self):
927 return self
928
929
930 class SomeUnicodeBuilder(SomeObject):
931 def method_append(self, s_str):
932 if s_str != s_None:
933 assert isinstance(s_str, (SomeUnicodeCodePoint, SomeUnicodeString))
934 return s_None
935
936 def method_append_slice(self, s_str, s_start, s_end):
937 if s_str != s_None:
938 assert isinstance(s_str, SomeUnicodeString)
939 assert isinstance(s_start, SomeInteger)
940 assert isinstance(s_end, SomeInteger)
941 return s_None
942
943 def method_append_multiple_char(self, s_char, s_times):
944 assert isinstance(s_char, SomeUnicodeCodePoint)
945 assert isinstance(s_times, SomeInteger)
946 return s_None
947
948 def method_append_charpsize(self, s_ptr, s_size):
949 assert isinstance(s_ptr, SomePtr)
950 assert isinstance(s_size, SomeInteger)
951 return s_None
952
953 def method_getlength(self):
954 return SomeInteger(nonneg=True)
955
956 def method_build(self):
957 return SomeUnicodeString(can_be_None=False)
958
959 def rtyper_makerepr(self, rtyper):
960 from rpython.rtyper.lltypesystem.rbuilder import unicodebuilder_repr
961 return unicodebuilder_repr
962
963 def rtyper_makekey(self):
964 return self.__class__,
965
966 def noneify(self):
967 return self
968
969
970 class BaseEntry(object):
971 def compute_result_annotation(self, s_init_size=None):
972 if s_init_size is not None:
973 assert isinstance(s_init_size, SomeInteger)
974 if self.use_unicode:
975 return SomeUnicodeBuilder()
976 return SomeStringBuilder()
977
978 def specialize_call(self, hop):
979 return hop.r_result.rtyper_new(hop)
980
981
982 class StringBuilderEntry(BaseEntry, ExtRegistryEntry):
983 _about_ = StringBuilder
984 use_unicode = False
985
986 class UnicodeBuilderEntry(BaseEntry, ExtRegistryEntry):
987 _about_ = UnicodeBuilder
988 use_unicode = True
989
990 class __extend__(pairtype(SomeStringBuilder, SomeStringBuilder)):
991
992 def union((obj1, obj2)):
993 return obj1
994
995 class __extend__(pairtype(SomeUnicodeBuilder, SomeUnicodeBuilder)):
996
997 def union((obj1, obj2)):
998 return obj1
999
1000 class PrebuiltStringBuilderEntry(ExtRegistryEntry):
1001 _type_ = StringBuilder
1002
1003 def compute_annotation(self):
1004 return SomeStringBuilder()
1005
1006 class PrebuiltUnicodeBuilderEntry(ExtRegistryEntry):
1007 _type_ = UnicodeBuilder
1008
1009 def compute_annotation(self):
1010 return SomeUnicodeBuilder()
1011
1012
1013 #___________________________________________________________________
1014 # Support functions for SomeString.no_nul
1015
1016 def assert_str0(fname):
1017 assert '\x00' not in fname, "NUL byte in string"
1018 return fname
1019
1020 class Entry(ExtRegistryEntry):
1021 _about_ = assert_str0
1022
1023 def compute_result_annotation(self, s_obj):
1024 if s_None.contains(s_obj):
1025 return s_obj
1026 assert isinstance(s_obj, (SomeString, SomeUnicodeString))
1027 if s_obj.no_nul:
1028 return s_obj
1029 new_s_obj = SomeObject.__new__(s_obj.__class__)
1030 new_s_obj.__dict__ = s_obj.__dict__.copy()
1031 new_s_obj.no_nul = True
1032 return new_s_obj
1033
1034 def specialize_call(self, hop):
1035 hop.exception_cannot_occur()
1036 return hop.inputarg(hop.args_r[0], arg=0)
1037
1038 def check_str0(fname):
1039 """A 'probe' to trigger a failure at translation time, if the
1040 string was not proved to not contain NUL characters."""
1041 assert '\x00' not in fname, "NUL byte in string"
1042
1043 class Entry(ExtRegistryEntry):
1044 _about_ = check_str0
1045
1046 def compute_result_annotation(self, s_obj):
1047 if not isinstance(s_obj, (SomeString, SomeUnicodeString)):
1048 return s_obj
1049 if not s_obj.no_nul:
1050 raise ValueError("Value is not no_nul")
1051
1052 def specialize_call(self, hop):
1053 hop.exception_cannot_occur()
1054
1055