Debian Codegraph @

pypy/objspace/std/stringmethods.py

raw symbols SCIP
1 """Functionality shared between bytes/bytearray/unicode"""
2
3 from rpython.rlib import jit
4 from rpython.rlib.objectmodel import specialize, newlist_hint
5 from rpython.rlib.rarithmetic import ovfcheck
6 from rpython.rlib.rstring import (
7 find, rfind, count, endswith, replace, rsplit, split, startswith)
8 from pypy.interpreter.error import OperationError, oefmt
9 from pypy.interpreter.gateway import WrappedDefault, unwrap_spec
10 from pypy.interpreter.unicodehelper import str_decode_utf8
11 from pypy.objspace.std.sliceobject import W_SliceObject, unwrap_start_stop
12
13
14 class StringMethods(object):
15 def _sliced(self, space, s, start, stop, orig_obj):
16 assert start >= 0
17 assert stop >= 0
18 #if start == 0 and stop == len(s) and space.is_w(space.type(orig_obj),
19 # space.w_bytes):
20 # return orig_obj
21 return self._new(s[start:stop])
22
23 def _convert_idx_params(self, space, w_start, w_end):
24 value = self._val(space)
25 lenself = len(value)
26 start, end = unwrap_start_stop(space, lenself, w_start, w_end)
27 # the None means "no offset"; see bytearrayobject.py
28 return (value, start, end, None)
29
30 @staticmethod
31 def descr_maketrans(space, w_type, w_from, w_to):
32 """B.maketrans(frm, to) -> translation table
33
34 Return a translation table (a bytes object of length 256) suitable
35 for use in the bytes or bytearray translate method where each byte
36 in frm is mapped to the byte at the same position in to.
37 The bytes objects frm and to must be of the same length.
38 """
39 from pypy.objspace.std.bytesobject import makebytesdata_w
40
41 base_table = [chr(i) for i in range(256)]
42 list_from = makebytesdata_w(space, w_from)
43 list_to = makebytesdata_w(space, w_to)
44
45 if len(list_from) != len(list_to):
46 raise oefmt(space.w_ValueError,
47 "maketrans arguments must have same length")
48
49 for i in range(len(list_from)):
50 pos_from = ord(list_from[i])
51 char_to = list_to[i]
52 base_table[pos_from] = char_to
53
54 return space.newbytes(''.join(base_table))
55
56 def _multi_chr(self, c):
57 return c
58
59 @staticmethod
60 def _single_char(space, w_sub):
61 try:
62 char = space.int_w(w_sub)
63 except OperationError as e:
64 if e.match(space, space.w_OverflowError):
65 char = 256 # arbitrary value which will trigger the ValueError
66 # condition below
67 else:
68 raise
69 if not 0 <= char < 256:
70 raise oefmt(space.w_ValueError,
71 "byte must be in range(0, 256)")
72 return chr(char)
73
74 def descr_len(self, space):
75 return space.newint(self._len())
76
77 def descr_iter(self, space):
78 from pypy.objspace.std.iterobject import W_StringIterObject
79 return W_StringIterObject(self, self._iter_getitem_result)
80
81 def descr_contains(self, space, w_sub):
82 value, start, end, _ = self._convert_idx_params(space, None, None)
83 other = self._op_val(space, w_sub, allow_char=True)
84 if self._use_rstr_ops(space, w_sub):
85 res = value.find(other, start, end)
86 else:
87 res = find(value, other, start, end)
88 return space.newbool(res >= 0)
89
90 def descr_add(self, space, w_other):
91 if self._use_rstr_ops(space, w_other):
92 try:
93 other = self._op_val(space, w_other)
94 except OperationError as e:
95 if e.match(space, space.w_TypeError):
96 return space.w_NotImplemented
97 raise
98 return self._new(self._val(space) + other)
99
100 # Bytearray overrides this method, CPython doesn't support contacting
101 # buffers and strs, and unicodes are always handled above
102 return space.w_NotImplemented
103
104 def descr_mul(self, space, w_times):
105 try:
106 times = space.getindex_w(w_times, space.w_OverflowError)
107 except OperationError as e:
108 if e.match(space, space.w_TypeError):
109 return space.w_NotImplemented
110 raise
111 if times <= 0:
112 return self._empty()
113 if times == 1:
114 from pypy.objspace.std.bytesobject import W_BytesObject
115 if type(self) is W_BytesObject:
116 return self
117 if self._len() == 1:
118 return self._new(self._multi_chr(self._val(space)[0]) * times)
119 return self._new(self._val(space) * times)
120
121 descr_rmul = descr_mul
122
123 _KIND1 = "string"
124 _KIND2 = "string"
125
126 def descr_getitem(self, space, w_index):
127 if isinstance(w_index, W_SliceObject):
128 selfvalue = self._val(space)
129 length = len(selfvalue)
130 start, stop, step, sl = w_index.indices4(space, length)
131 if sl == 0:
132 return self._empty()
133 elif step == 1:
134 assert start >= 0 and stop >= 0
135 return self._sliced(space, selfvalue, start, stop, self)
136 else:
137 ret = _descr_getslice_slowpath(selfvalue, start, step, sl)
138 return self._new_from_list(ret)
139
140 index = space.getindex_w(w_index, space.w_IndexError, self._KIND1)
141 return self._getitem_result(space, index)
142
143 def _getitem_result(self, space, index):
144 # Returns the result of 'self[index]', where index is an unwrapped int.
145 # Used by descr_getitem() and by descr_iter().
146 selfvalue = self._val(space)
147 try:
148 character = selfvalue[index]
149 except IndexError:
150 raise oefmt(space.w_IndexError, self._KIND1 + " index out of range")
151 from pypy.objspace.std.bytesobject import W_BytesObject
152 if isinstance(self, W_BytesObject):
153 return space.newint(ord(character))
154 return self._new(character)
155
156 def descr_capitalize(self, space):
157 value = self._val(space)
158 if len(value) == 0:
159 return self._empty()
160
161 builder = self._builder(len(value))
162 builder.append(self._upper(value[0]))
163 for i in range(1, len(value)):
164 builder.append(self._lower_in_str(value, i))
165 return self._new(builder.build())
166
167 @unwrap_spec(width=int, w_fillchar=WrappedDefault(' '))
168 def descr_center(self, space, width, w_fillchar):
169 value = self._val(space)
170 fillchar = self._op_val(space, w_fillchar)
171 if len(fillchar) != 1:
172 raise oefmt(space.w_TypeError,
173 "center() argument 2 must be a single character")
174
175 d = width - len(value)
176 if d > 0:
177 offset = d//2 + (d & width & 1)
178 fillchar = self._multi_chr(fillchar[0])
179 centered = offset * fillchar + value + (d - offset) * fillchar
180 else:
181 centered = value
182
183 return self._new(centered)
184
185 def descr_count(self, space, w_sub, w_start=None, w_end=None):
186 value, start, end, _ = self._convert_idx_params(space, w_start, w_end)
187
188 sub = self._op_val(space, w_sub, allow_char=True)
189 if self._use_rstr_ops(space, w_sub):
190 return space.newint(value.count(sub, start, end))
191 else:
192 res = count(value, sub, start, end)
193 assert res >= 0
194 return space.newint(res)
195
196 def descr_decode(self, space, w_encoding=None, w_errors=None):
197 from pypy.objspace.std.unicodeobject import (
198 get_encoding_and_errors, decode_object)
199 encoding, errors = get_encoding_and_errors(space, w_encoding, w_errors)
200 if encoding is None:
201 encoding = 'utf8'
202 if encoding == 'utf8' or encoding == 'utf-8':
203 # fast path - do not call into app-level codecs.py
204 from pypy.module._codecs.interp_codecs import CodecState
205 state = space.fromcache(CodecState)
206 eh = state.decode_error_handler
207 s = space.charbuf_w(self)
208 w_s = space.newbytes(s)
209 ret, lgt, pos = str_decode_utf8(space, s, w_s, errors, True, eh)
210 return space.newtext(ret, lgt)
211 return decode_object(space, self, encoding, errors)
212
213 @unwrap_spec(tabsize=int)
214 def descr_expandtabs(self, space, tabsize=8):
215 value = self._val(space)
216 if not value:
217 return self._empty()
218
219 if self._use_rstr_ops(space, self):
220 splitted = value.split(self._chr('\t'))
221 else:
222 splitted = split(value, self._chr('\t'))
223
224 try:
225 if tabsize > 0:
226 ovfcheck(len(splitted) * tabsize)
227 except OverflowError:
228 raise oefmt(space.w_OverflowError, "new string is too long")
229 newlen = self._len() - len(splitted) + 1
230 builder = self._builder(len(value))
231 oldtoken = splitted[0]
232 builder.append(oldtoken)
233
234 for index in range(1, len(splitted)):
235 token = splitted[index]
236 dist = self._tabindent(oldtoken, tabsize)
237 builder.append_multiple_char(' ', dist)
238 builder.append(token)
239 newlen += dist
240 oldtoken = token
241 return self._new(builder.build())
242
243 def _tabindent(self, token, tabsize):
244 """calculates distance behind the token to the next tabstop"""
245
246 if tabsize <= 0:
247 return 0
248 distance = tabsize
249 if token:
250 distance = 0
251 offset = len(token)
252
253 while 1:
254 if token[offset-1] == "\n" or token[offset-1] == "\r":
255 break
256 distance += 1
257 offset -= 1
258 if offset == 0:
259 break
260
261 # the same like distance = len(token) - (offset + 1)
262 distance = (tabsize - distance) % tabsize
263 if distance == 0:
264 distance = tabsize
265
266 return distance
267
268 def descr_find(self, space, w_sub, w_start=None, w_end=None):
269 value, start, end, ofs = self._convert_idx_params(space, w_start, w_end)
270
271 sub = self._op_val(space, w_sub, allow_char=True)
272 if self._use_rstr_ops(space, w_sub):
273 res = value.find(sub, start, end)
274 else:
275 res = find(value, sub, start, end)
276 if ofs is not None and res >= 0:
277 res -= ofs
278 return space.newint(res)
279
280 def descr_rfind(self, space, w_sub, w_start=None, w_end=None):
281 value, start, end, ofs = self._convert_idx_params(space, w_start, w_end)
282
283 sub = self._op_val(space, w_sub, allow_char=True)
284 if self._use_rstr_ops(space, w_sub):
285 res = value.rfind(sub, start, end)
286 else:
287 res = rfind(value, sub, start, end)
288 if ofs is not None and res >= 0:
289 res -= ofs
290 return space.newint(res)
291
292 def descr_index(self, space, w_sub, w_start=None, w_end=None):
293 value, start, end, ofs = self._convert_idx_params(space, w_start, w_end)
294
295 sub = self._op_val(space, w_sub, allow_char=True)
296 if self._use_rstr_ops(space, w_sub):
297 res = value.find(sub, start, end)
298 else:
299 res = find(value, sub, start, end)
300
301 if res < 0:
302 raise oefmt(space.w_ValueError,
303 "substring not found in " + self._KIND2 + ".index")
304 if ofs is not None:
305 res -= ofs
306 return space.newint(res)
307
308 def descr_rindex(self, space, w_sub, w_start=None, w_end=None):
309 value, start, end, ofs = self._convert_idx_params(space, w_start, w_end)
310
311 sub = self._op_val(space, w_sub, allow_char=True)
312 if self._use_rstr_ops(space, w_sub):
313 res = value.rfind(sub, start, end)
314 else:
315 res = rfind(value, sub, start, end)
316
317 if res < 0:
318 raise oefmt(space.w_ValueError,
319 "substring not found in " + self._KIND2 + ".rindex")
320 if ofs is not None:
321 res -= ofs
322 return space.newint(res)
323
324 @specialize.arg(2)
325 def _is_generic(self, space, func_name):
326 func = getattr(self, func_name)
327 v = self._val(space)
328 if len(v) == 0:
329 return space.w_False
330 if len(v) == 1:
331 c = v[0]
332 return space.newbool(func(c))
333 else:
334 return self._is_generic_loop(space, v, func_name)
335
336 @specialize.arg(3)
337 def _is_generic_loop(self, space, v, func_name):
338 func = getattr(self, func_name)
339 for idx in range(len(v)):
340 if not func(v[idx]):
341 return space.w_False
342 return space.w_True
343
344 def descr_isalnum(self, space):
345 return self._is_generic(space, '_isalnum')
346
347 def descr_isalpha(self, space):
348 return self._is_generic(space, '_isalpha')
349
350 def descr_isdigit(self, space):
351 return self._is_generic(space, '_isdigit')
352
353 # this is only for bytes and bytesarray: unicodeobject overrides it
354 def _descr_islower_slowpath(self, space, v):
355 cased = False
356 for idx in range(len(v)):
357 if self._isupper(v[idx]):
358 return False
359 elif not cased and self._islower(v[idx]):
360 cased = True
361 return cased
362
363 def descr_islower(self, space):
364 v = self._val(space)
365 if len(v) == 1:
366 c = v[0]
367 return space.newbool(self._islower(c))
368 cased = self._descr_islower_slowpath(space, v)
369 return space.newbool(cased)
370
371 def descr_isspace(self, space):
372 return self._is_generic(space, '_isspace')
373
374 def descr_istitle(self, space):
375 input = self._val(space)
376 cased = False
377 previous_is_cased = False
378
379 for pos in range(0, len(input)):
380 ch = input[pos]
381 if self._istitle(ch):
382 if previous_is_cased:
383 return space.w_False
384 previous_is_cased = True
385 cased = True
386 elif self._islower(ch):
387 if not previous_is_cased:
388 return space.w_False
389 cased = True
390 else:
391 previous_is_cased = False
392
393 return space.newbool(cased)
394
395 # this is only for bytes and bytesarray: unicodeobject overrides it
396 def _descr_isupper_slowpath(self, space, v):
397 cased = False
398 for idx in range(len(v)):
399 if self._islower(v[idx]):
400 return False
401 elif not cased and self._isupper(v[idx]):
402 cased = True
403 return cased
404
405 def descr_isupper(self, space):
406 v = self._val(space)
407 if len(v) == 1:
408 c = v[0]
409 return space.newbool(self._isupper(c))
410 cased = self._descr_isupper_slowpath(space, v)
411 return space.newbool(cased)
412
413 def descr_join(self, space, w_list):
414 list_w = space.listview(w_list)
415 size = len(list_w)
416
417 if size == 0:
418 return self._empty()
419
420 if size == 1:
421 w_s = list_w[0]
422 # only one item, return it if it's not a subclass of str
423 if self._join_return_one(space, w_s):
424 return w_s
425
426 return self._str_join_many_items(space, list_w, size)
427
428 @jit.look_inside_iff(lambda self, space, list_w, size:
429 jit.loop_unrolling_heuristic(list_w, size))
430 def _str_join_many_items(self, space, list_w, size):
431 value = self._val(space)
432
433 prealloc_size = len(value) * (size - 1)
434 unwrapped = newlist_hint(size)
435 for i in range(size):
436 w_s = list_w[i]
437 try:
438 next_string = self._op_val(space, w_s)
439 except OperationError as e:
440 if not e.match(space, space.w_TypeError):
441 raise
442 raise oefmt(space.w_TypeError,
443 "sequence item %d: expected %s, %T found",
444 i, self._generic_name(), w_s)
445 # XXX Maybe the extra copy here is okay? It was basically going to
446 # happen anyway, what with being placed into the builder
447 unwrapped.append(next_string)
448 prealloc_size += len(unwrapped[i])
449
450 sb = self._builder(prealloc_size)
451 for i in range(size):
452 if value and i != 0:
453 sb.append(value)
454 sb.append(unwrapped[i])
455 return self._new(sb.build())
456
457 @unwrap_spec(width=int, w_fillchar=WrappedDefault(' '))
458 def descr_ljust(self, space, width, w_fillchar):
459 value = self._val(space)
460 fillchar = self._op_val(space, w_fillchar)
461 if len(fillchar) != 1:
462 raise oefmt(space.w_TypeError,
463 "ljust() argument 2 must be a single character")
464 d = width - len(value)
465 if d > 0:
466 fillchar = self._multi_chr(fillchar[0])
467 value = value + fillchar * d
468
469 return self._new(value)
470
471 @unwrap_spec(width=int, w_fillchar=WrappedDefault(' '))
472 def descr_rjust(self, space, width, w_fillchar):
473 value = self._val(space)
474 fillchar = self._op_val(space, w_fillchar)
475 if len(fillchar) != 1:
476 raise oefmt(space.w_TypeError,
477 "rjust() argument 2 must be a single character")
478 d = width - len(value)
479 if d > 0:
480 fillchar = self._multi_chr(fillchar[0])
481 value = d * fillchar + value
482
483 return self._new(value)
484
485 def descr_lower(self, space):
486 value = self._val(space)
487 builder = self._builder(len(value))
488 for i in range(len(value)):
489 builder.append(self._lower_in_str(value, i))
490 return self._new(builder.build())
491
492 def _lower_in_str(self, value, i):
493 # overridden in unicodeobject.py
494 return self._lower(value[i])
495
496 # This is not used for W_UnicodeObject.
497 def descr_partition(self, space, w_sub):
498 from pypy.objspace.std.bytearrayobject import W_BytearrayObject
499 value = self._val(space)
500
501 if self._use_rstr_ops(space, w_sub):
502 sub = self._op_val(space, w_sub)
503 sublen = len(sub)
504 if sublen == 0:
505 raise oefmt(space.w_ValueError, "empty separator")
506
507 pos = value.find(sub)
508 else:
509 sub = space.readbuf_w(w_sub)
510 sublen = sub.getlength()
511 if sublen == 0:
512 raise oefmt(space.w_ValueError, "empty separator")
513
514 pos = find(value, sub, 0, len(value))
515 if pos != -1 and isinstance(self, W_BytearrayObject):
516 w_sub = self._new_from_buffer(sub)
517
518 if pos == -1:
519 if isinstance(self, W_BytearrayObject):
520 self = self._new(value)
521 return space.newtuple([self, self._empty(), self._empty()])
522 else:
523 return space.newtuple(
524 [self._sliced(space, value, 0, pos, self), w_sub,
525 self._sliced(space, value, pos + sublen, len(value), self)])
526
527 def descr_rpartition(self, space, w_sub):
528 from pypy.objspace.std.bytearrayobject import W_BytearrayObject
529 value = self._val(space)
530
531 if self._use_rstr_ops(space, w_sub):
532 sub = self._op_val(space, w_sub)
533 sublen = len(sub)
534 if sublen == 0:
535 raise oefmt(space.w_ValueError, "empty separator")
536
537 pos = value.rfind(sub)
538 else:
539 sub = space.readbuf_w(w_sub)
540 sublen = sub.getlength()
541 if sublen == 0:
542 raise oefmt(space.w_ValueError, "empty separator")
543
544 pos = rfind(value, sub, 0, len(value))
545 if pos != -1 and isinstance(self, W_BytearrayObject):
546 w_sub = self._new_from_buffer(sub)
547
548 if pos == -1:
549 if isinstance(self, W_BytearrayObject):
550 self = self._new(value)
551 return space.newtuple([self._empty(), self._empty(), self])
552 else:
553 return space.newtuple(
554 [self._sliced(space, value, 0, pos, self), w_sub,
555 self._sliced(space, value, pos + sublen, len(value), self)])
556
557 @unwrap_spec(count=int)
558 def descr_replace(self, space, w_old, w_new, count=-1):
559 input = self._val(space)
560
561 sub = self._op_val(space, w_old)
562 by = self._op_val(space, w_new)
563 try:
564 res = replace(input, sub, by, count)
565 except OverflowError:
566 raise oefmt(space.w_OverflowError, "replace string is too long")
567
568 return self._new(res)
569
570 @unwrap_spec(maxsplit=int)
571 def descr_split(self, space, w_sep=None, maxsplit=-1):
572 res = []
573 value = self._val(space)
574 if space.is_none(w_sep):
575 res = split(value, maxsplit=maxsplit)
576 return self._newlist_unwrapped(space, res)
577
578 by = self._op_val(space, w_sep)
579 if len(by) == 0:
580 raise oefmt(space.w_ValueError, "empty separator")
581 res = split(value, by, maxsplit)
582
583 return self._newlist_unwrapped(space, res)
584
585 @unwrap_spec(maxsplit=int)
586 def descr_rsplit(self, space, w_sep=None, maxsplit=-1):
587 res = []
588 value = self._val(space)
589 if space.is_none(w_sep):
590 res = rsplit(value, maxsplit=maxsplit)
591 return self._newlist_unwrapped(space, res)
592
593 by = self._op_val(space, w_sep)
594 if len(by) == 0:
595 raise oefmt(space.w_ValueError, "empty separator")
596 res = rsplit(value, by, maxsplit)
597
598 return self._newlist_unwrapped(space, res)
599
600 @unwrap_spec(keepends=int)
601 def descr_splitlines(self, space, keepends=False):
602 value = self._val(space)
603 length = len(value)
604 strs = []
605 pos = 0
606 while pos < length:
607 sol = pos
608 while pos < length and not self._islinebreak(value[pos]):
609 pos += 1
610 eol = pos
611 pos += 1
612 # read CRLF as one line break
613 if pos < length and value[eol] == '\r' and value[pos] == '\n':
614 pos += 1
615 if keepends:
616 eol = pos
617 strs.append(value[sol:eol])
618 if pos < length:
619 # XXX is this code reachable?
620 strs.append(value[pos:length])
621 return self._newlist_unwrapped(space, strs)
622
623 def _generic_name(self):
624 return "bytes"
625
626 # This is overridden in unicodeobject, _startswith_tuple is not.
627 def descr_startswith(self, space, w_prefix, w_start=None, w_end=None):
628 value, start, end, _ = self._convert_idx_params(space, w_start, w_end)
629 if space.isinstance_w(w_prefix, space.w_tuple):
630 return self._startswith_tuple(space, value, w_prefix, start, end)
631 try:
632 res = self._startswith(space, value, w_prefix, start, end)
633 except OperationError as e:
634 if not e.match(space, space.w_TypeError):
635 raise
636 wanted = self._generic_name()
637 raise oefmt(space.w_TypeError,
638 "startswith first arg must be %s or a tuple of %s, "
639 "not %T", wanted, wanted, w_prefix)
640 return space.newbool(res)
641
642 def _startswith_tuple(self, space, value, w_prefix, start, end):
643 for w_prefix in space.fixedview(w_prefix):
644 if self._startswith(space, value, w_prefix, start, end):
645 return space.w_True
646 return space.w_False
647
648 # This is overridden in unicodeobject, _startswith_tuple is not.
649 # This is overridden in bytearrayobject to remove the trailing NULL
650 def _startswith(self, space, value, w_prefix, start, end):
651 prefix = self._op_val(space, w_prefix)
652 if start > len(value):
653 return False
654 return startswith(value, prefix, start, end)
655
656 # This is overridden in unicodeobject, _endswith_tuple is not.
657 def descr_endswith(self, space, w_suffix, w_start=None, w_end=None):
658 value, start, end, _ = self._convert_idx_params(space, w_start, w_end)
659 if space.isinstance_w(w_suffix, space.w_tuple):
660 return self._endswith_tuple(space, value, w_suffix, start, end)
661 try:
662 res = self._endswith(space, value, w_suffix, start, end)
663 except OperationError as e:
664 if not e.match(space, space.w_TypeError):
665 raise
666 wanted = self._generic_name()
667 raise oefmt(space.w_TypeError,
668 "endswith first arg must be %s or a tuple of %s, not "
669 "%T", wanted, wanted, w_suffix)
670 return space.newbool(res)
671
672 def _endswith_tuple(self, space, value, w_suffix, start, end):
673 for w_suffix in space.fixedview(w_suffix):
674 if self._endswith(space, value, w_suffix, start, end):
675 return space.w_True
676 return space.w_False
677
678 # This is overridden in unicodeobject, but _endswith_tuple is not.
679 # This is overridden in bytearrayobject
680 def _endswith(self, space, value, w_prefix, start, end):
681 prefix = self._op_val(space, w_prefix)
682 if start > len(value):
683 return False
684 return endswith(value, prefix, start, end)
685
686 def _strip(self, space, w_chars, left, right, name='strip'):
687 "internal function called by str_xstrip methods"
688 value = self._val(space)
689 chars = self._op_val(space, w_chars)
690
691 lpos = 0
692 rpos = len(value)
693
694 if left:
695 lpos = StringMethods._strip_bytes_unboxed_left(value, chars)
696
697 if right:
698 rpos = StringMethods._strip_bytes_unboxed_right(value, chars, lpos)
699
700 assert rpos >= lpos # annotator hint, don't remove
701 return self._sliced(space, value, lpos, rpos, self)
702
703 @staticmethod
704 @jit.elidable
705 @specialize.argtype(0)
706 def _strip_bytes_unboxed_left(value, chars):
707 lpos = 0
708 rpos = len(value)
709 while lpos < rpos and value[lpos] in chars:
710 lpos += 1
711 return lpos
712
713 @staticmethod
714 @jit.elidable
715 @specialize.argtype(0)
716 def _strip_bytes_unboxed_right(value, chars, lpos):
717 rpos = len(value)
718 while rpos > lpos and value[rpos - 1] in chars:
719 rpos -= 1
720 return rpos
721
722 def _strip_none(self, space, left, right):
723 "internal function called by str_xstrip methods"
724 value = self._val(space)
725
726 lpos = 0
727 rpos = len(value)
728
729 if left:
730 lpos = StringMethods._strip_none_bytes_unboxed_left(value)
731
732 if right:
733 rpos = StringMethods._strip_none_bytes_unboxed_right(value, lpos)
734
735 assert rpos >= lpos # annotator hint, don't remove
736 return self._sliced(space, value, lpos, rpos, self)
737
738 @staticmethod
739 @jit.elidable
740 @specialize.argtype(0)
741 def _strip_none_bytes_unboxed_left(value):
742 lpos = 0
743 rpos = len(value)
744 while lpos < rpos and value[lpos].isspace():
745 lpos += 1
746 return lpos
747
748 @staticmethod
749 @jit.elidable
750 @specialize.argtype(0)
751 def _strip_none_bytes_unboxed_right(value, lpos):
752 rpos = len(value)
753 while rpos > lpos and value[rpos - 1].isspace():
754 rpos -= 1
755 return rpos
756
757 def descr_strip(self, space, w_chars=None):
758 if space.is_none(w_chars):
759 return self._strip_none(space, left=1, right=1)
760 return self._strip(space, w_chars, left=1, right=1, name='strip')
761
762 def descr_lstrip(self, space, w_chars=None):
763 if space.is_none(w_chars):
764 return self._strip_none(space, left=1, right=0)
765 return self._strip(space, w_chars, left=1, right=0, name='lstrip')
766
767 def descr_rstrip(self, space, w_chars=None):
768 if space.is_none(w_chars):
769 return self._strip_none(space, left=0, right=1)
770 return self._strip(space, w_chars, left=0, right=1, name='rstrip')
771
772 def descr_swapcase(self, space):
773 selfvalue = self._val(space)
774 builder = self._builder(len(selfvalue))
775 for i in range(len(selfvalue)):
776 ch = selfvalue[i]
777 if self._isupper(ch):
778 builder.append(self._lower_in_str(selfvalue, i))
779 elif self._islower(ch):
780 builder.append(self._upper(ch))
781 else:
782 builder.append(ch)
783 return self._new(builder.build())
784
785 def descr_title(self, space):
786 selfval = self._val(space)
787 if len(selfval) == 0:
788 return self
789 return self._new(self.title(selfval))
790
791 @jit.elidable
792 def title(self, value):
793 builder = self._builder(len(value))
794 previous_is_cased = False
795 for i in range(len(value)):
796 ch = value[i]
797 if not previous_is_cased:
798 builder.append(self._title(ch))
799 else:
800 builder.append(self._lower_in_str(value, i))
801 previous_is_cased = self._iscased(ch)
802 return builder.build()
803
804 DEFAULT_NOOP_TABLE = ''.join([chr(i) for i in range(256)])
805
806 # for bytes and bytearray, overridden by unicode
807 @unwrap_spec(w_delete=WrappedDefault(''))
808 def descr_translate(self, space, w_table, w_delete):
809 if space.is_w(w_table, space.w_None):
810 table = self.DEFAULT_NOOP_TABLE
811 else:
812 table = self._op_val(space, w_table)
813 if len(table) != 256:
814 raise oefmt(space.w_ValueError,
815 "translation table must be 256 characters long")
816
817 string = self._val(space)
818 deletechars = self._op_val(space, w_delete)
819 if len(deletechars) == 0:
820 buf = self._builder(len(string))
821 for char in string:
822 buf.append(table[ord(char)])
823 else:
824 # XXX Why not preallocate here too?
825 buf = self._builder()
826 deletion_table = [False] * 256
827 for i in range(len(deletechars)):
828 deletion_table[ord(deletechars[i])] = True
829 for char in string:
830 if not deletion_table[ord(char)]:
831 buf.append(table[ord(char)])
832 return self._new(buf.build())
833
834 def descr_upper(self, space):
835 value = self._val(space)
836 builder = self._builder(len(value))
837 for i in range(len(value)):
838 builder.append(self._upper(value[i]))
839 return self._new(builder.build())
840
841 @unwrap_spec(width=int)
842 def descr_zfill(self, space, width):
843 selfval = self._val(space)
844 if len(selfval) == 0:
845 return self._new(self._multi_chr(self._chr('0')) * width)
846 num_zeros = width - len(selfval)
847 if num_zeros <= 0:
848 # cannot return self, in case it is a subclass of str
849 return self._new(selfval)
850
851 builder = self._builder(width)
852 if len(selfval) > 0 and (selfval[0] == '+' or selfval[0] == '-'):
853 # copy sign to first position
854 builder.append(selfval[0])
855 start = 1
856 else:
857 start = 0
858 builder.append_multiple_char(self._chr('0'), num_zeros)
859 builder.append_slice(selfval, start, len(selfval))
860 return self._new(builder.build())
861
862 def descr_getnewargs(self, space):
863 return space.newtuple([self._new(self._val(space))])
864
865 def descr_removeprefix(self, space, w_prefix):
866 prefix = self._op_val(space, w_prefix)
867 selfval = self._val(space)
868 if startswith(selfval, prefix):
869 return self._new(selfval[len(prefix):])
870 return self._new(selfval)
871
872 def descr_removesuffix(self, space, w_suffix):
873 suffix = self._op_val(space, w_suffix)
874 selfval = self._val(space)
875 if suffix and endswith(selfval, suffix):
876 end = len(selfval) - len(suffix)
877 assert end >= 0
878 return self._new(selfval[:end])
879 return self._new(selfval)
880
881 # ____________________________________________________________
882 # helpers for slow paths, moved out because they contain loops
883
884 @specialize.argtype(0)
885 def _descr_getslice_slowpath(selfvalue, start, step, sl):
886 return [selfvalue[start + i*step] for i in range(sl)]