Debian Codegraph @

pypy/objspace/std/bytesobject.py

raw symbols SCIP
1 """The builtin bytes implementation"""
2
3 from rpython.rlib import jit, rutf8
4 from rpython.rlib.objectmodel import (
5 compute_hash, compute_unique_id, import_from_mixin)
6 from rpython.rlib.rstring import StringBuilder
7
8 from pypy.interpreter.baseobjspace import W_Root
9 from pypy.interpreter.buffer import SimpleView, StringBuffer
10 from pypy.interpreter.error import OperationError, oefmt
11 from pypy.interpreter.gateway import (
12 WrappedDefault, interp2app, interpindirect2app, unwrap_spec)
13 from pypy.interpreter.typedef import TypeDef
14 from pypy.objspace.std.stringmethods import StringMethods
15 from pypy.objspace.std.util import IDTAG_SPECIAL, IDTAG_SHIFT
16 from pypy.objspace.std.formatting import mod_format, FORMAT_BYTES
17 from pypy.objspace.std.unicodeobject import (encode_object, getdefaultencoding,
18 decode_object)
19
20 class W_AbstractBytesObject(W_Root):
21 __slots__ = ()
22 exact_class_applevel_name = 'bytes'
23
24 def is_w(self, space, w_other):
25 if not isinstance(w_other, W_AbstractBytesObject):
26 return False
27 if self is w_other:
28 return True
29 if self.user_overridden_class or w_other.user_overridden_class:
30 return False
31 s1 = space.bytes_w(self)
32 s2 = space.bytes_w(w_other)
33 if len(s2) > 1:
34 return s1 is s2
35 if len(s2) == 0:
36 return len(s1) == 0
37 else: # strings of len <= 1 are unique-ified
38 return len(s1) == 1 and s1[0] == s2[0]
39
40 def immutable_unique_id(self, space):
41 if self.user_overridden_class:
42 return None
43 s = space.bytes_w(self)
44 if len(s) > 1:
45 uid = compute_unique_id(s)
46 else: # strings of len <= 1 are unique-ified
47 if len(s) == 1:
48 base = ord(s[0]) # base values 0-255
49 else:
50 base = 256 # empty string: base value 256
51 uid = (base << IDTAG_SHIFT) | IDTAG_SPECIAL
52 return space.newint(uid)
53
54 def descr_add(self, space, w_other):
55 """x.__add__(y) <==> x+y"""
56
57 def descr_contains(self, space, w_sub):
58 """x.__contains__(y) <==> y in x"""
59
60 def descr_eq(self, space, w_other):
61 """x.__eq__(y) <==> x==y"""
62
63 def descr_ge(self, space, w_other):
64 """x.__ge__(y) <==> x>=y"""
65
66 def descr_getitem(self, space, w_index):
67 """x.__getitem__(y) <==> x[y]"""
68
69 def descr_getnewargs(self, space):
70 ""
71
72 def descr_gt(self, space, w_other):
73 """x.__gt__(y) <==> x>y"""
74
75 def descr_hash(self, space):
76 """x.__hash__() <==> hash(x)"""
77
78 def descr_isascii(self, space):
79 """B.isascii() -> bool
80
81 Return true if the string is empty or all characters in the string are ASCII, false otherwise.
82 ASCII characters have code points in the range U+0000-U+007F."""
83
84 def descr_iter(self, space):
85 """x.__iter__() <==> iter(x)"""
86
87 def descr_le(self, space, w_other):
88 """x.__le__(y) <==> x<=y"""
89
90 def descr_len(self, space):
91 """x.__len__() <==> len(x)"""
92
93 def descr_lt(self, space, w_other):
94 """x.__lt__(y) <==> x<y"""
95
96 def descr_mul(self, space, w_times):
97 """x.__mul__(n) <==> x*n"""
98
99 def descr_ne(self, space, w_other):
100 """x.__ne__(y) <==> x!=y"""
101
102 def descr_repr(self, space):
103 """x.__repr__() <==> repr(x)"""
104
105 def descr_rmod(self, space, w_values):
106 """x.__rmod__(y) <==> y%x"""
107
108 def descr_rmul(self, space, w_times):
109 """x.__rmul__(n) <==> n*x"""
110
111 def descr_str(self, space):
112 """x.__str__() <==> str(x)"""
113
114 def descr_capitalize(self, space):
115 """B.capitalize() -> copy of B
116
117 Return a capitalized version of B, i.e. make the first character
118 have upper case and the rest lower case.
119 """
120
121 @unwrap_spec(width=int, w_fillchar=WrappedDefault(' '))
122 def descr_center(self, space, width, w_fillchar):
123 """B.center(width[, fillchar]) -> copy of B
124
125 Return B centered in a string of length width. Padding is
126 done using the specified fill character (default is a space).
127 """
128
129 def descr_count(self, space, w_sub, w_start=None, w_end=None):
130 """B.count(sub[, start[, end]]) -> int
131
132 Return the number of non-overlapping occurrences of substring sub in
133 string B[start:end]. Optional arguments start and end are interpreted
134 as in slice notation.
135 """
136
137 def descr_decode(self, space, w_encoding=None, w_errors=None):
138 """B.decode(encoding=None, errors='strict') -> object
139
140 Decode B using the codec registered for encoding. encoding defaults
141 to the default encoding. errors may be given to set a different error
142 handling scheme. Default is 'strict' meaning that encoding errors raise
143 a UnicodeDecodeError. Other possible values are 'ignore' and 'replace'
144 as well as any other name registered with codecs.register_error that is
145 able to handle UnicodeDecodeErrors.
146 """
147
148 def descr_endswith(self, space, w_suffix, w_start=None, w_end=None):
149 """B.endswith(suffix[, start[, end]]) -> bool
150
151 Return True if B ends with the specified suffix, False otherwise.
152 With optional start, test B beginning at that position.
153 With optional end, stop comparing B at that position.
154 suffix can also be a tuple of bytes to try.
155 """
156
157 @unwrap_spec(tabsize=int)
158 def descr_expandtabs(self, space, tabsize=8):
159 """B.expandtabs([tabsize]) -> copy of B
160
161 Return a copy of B where all tab characters are expanded using spaces.
162 If tabsize is not given, a tab size of 8 characters is assumed.
163 """
164
165 def descr_find(self, space, w_sub, w_start=None, w_end=None):
166 """B.find(sub[, start[, end]]) -> int
167
168 Return the lowest index in B where substring sub is found,
169 such that sub is contained within B[start:end]. Optional
170 arguments start and end are interpreted as in slice notation.
171
172 Return -1 on failure.
173 """
174
175 def descr_index(self, space, w_sub, w_start=None, w_end=None):
176 """B.index(sub[, start[, end]]) -> int
177
178 Like B.find() but raise ValueError when the substring is not found.
179 """
180
181 def descr_isalnum(self, space):
182 """B.isalnum() -> bool
183
184 Return True if all characters in B are alphanumeric
185 and there is at least one character in B, False otherwise.
186 """
187
188 def descr_isalpha(self, space):
189 """B.isalpha() -> bool
190
191 Return True if all characters in B are alphabetic
192 and there is at least one character in B, False otherwise.
193 """
194
195 def descr_isdigit(self, space):
196 """B.isdigit() -> bool
197
198 Return True if all characters in B are digits
199 and there is at least one character in B, False otherwise.
200 """
201
202 def descr_islower(self, space):
203 """B.islower() -> bool
204
205 Return True if all cased characters in B are lowercase and there is
206 at least one cased character in B, False otherwise.
207 """
208
209 def descr_isspace(self, space):
210 """B.isspace() -> bool
211
212 Return True if all characters in B are whitespace
213 and there is at least one character in B, False otherwise.
214 """
215
216 def descr_istitle(self, space):
217 """B.istitle() -> bool
218
219 Return True if B is a titlecased string and there is at least one
220 character in B, i.e. uppercase characters may only follow uncased
221 characters and lowercase characters only cased ones. Return False
222 otherwise.
223 """
224
225 def descr_isupper(self, space):
226 """B.isupper() -> bool
227
228 Return True if all cased characters in B are uppercase and there is
229 at least one cased character in B, False otherwise.
230 """
231
232 def descr_join(self, space, w_list):
233 """B.join(iterable) -> bytes
234
235 Return a bytes object which is the concatenation of the bytes in the
236 iterable. The separator between elements is B.
237 """
238
239 @unwrap_spec(width=int, w_fillchar=WrappedDefault(' '))
240 def descr_ljust(self, space, width, w_fillchar):
241 """B.ljust(width[, fillchar]) -> copy of B
242
243 Return B left-justified in a string of length width. Padding is
244 done using the specified fill character (default is a space).
245 """
246
247 def descr_lower(self, space):
248 """B.lower() -> copy of B
249
250 Return a copy of the string B converted to lowercase.
251 """
252
253 def descr_lstrip(self, space, w_chars=None):
254 """B.lstrip([chars]) -> copy of B
255
256 Return a copy of the string B with leading whitespace removed.
257 If chars is given and not None, remove characters in chars instead.
258 """
259
260 def descr_partition(self, space, w_sub):
261 """B.partition(sep) -> (head, sep, tail)
262
263 Search for the separator sep in B, and return the part before it,
264 the separator itself, and the part after it. If the separator is not
265 found, return B and two empty bytes objects.
266 """
267
268 @unwrap_spec(count=int)
269 def descr_replace(self, space, w_old, w_new, count=-1):
270 """B.replace(old, new[, count]) -> copy of B
271
272 Return a copy of string B with all occurrences of substring
273 old replaced by new. If the optional argument count is
274 given, only the first count occurrences are replaced.
275 """
276
277 def descr_rfind(self, space, w_sub, w_start=None, w_end=None):
278 """B.rfind(sub[, start[, end]]) -> int
279
280 Return the highest index in B where substring sub is found,
281 such that sub is contained within B[start:end]. Optional
282 arguments start and end are interpreted as in slice notation.
283
284 Return -1 on failure.
285 """
286
287 def descr_rindex(self, space, w_sub, w_start=None, w_end=None):
288 """B.rindex(sub[, start[, end]]) -> int
289
290 Like B.rfind() but raise ValueError when the substring is not found.
291 """
292
293 @unwrap_spec(width=int, w_fillchar=WrappedDefault(' '))
294 def descr_rjust(self, space, width, w_fillchar):
295 """B.rjust(width[, fillchar]) -> copy of B
296
297 Return B right-justified in a string of length width. Padding is
298 done using the specified fill character (default is a space).
299 """
300
301 def descr_rpartition(self, space, w_sub):
302 """B.rpartition(sep) -> (head, sep, tail)
303
304 Search for the separator sep in B, starting at the end of B, and return
305 the part before it, the separator itself, and the part after it. If
306 the separator is not found, return two empty bytes objects and B.
307 """
308
309 @unwrap_spec(maxsplit=int)
310 def descr_rsplit(self, space, w_sep=None, maxsplit=-1):
311 """B.rsplit(sep=None, maxsplit=-1) -> list of bytes objects
312
313 Return a list of the words in the string B, using sep as the
314 delimiter string, starting at the end of the string and working
315 to the front. If maxsplit is given, at most maxsplit splits are
316 done. If sep is not specified or is None, any whitespace string
317 is a separator.
318 """
319
320 def descr_rstrip(self, space, w_chars=None):
321 """B.rstrip([chars]) -> copy of B
322
323 Return a copy of the string B with trailing whitespace removed.
324 If chars is given and not None, remove characters in chars instead.
325 """
326
327 @unwrap_spec(maxsplit=int)
328 def descr_split(self, space, w_sep=None, maxsplit=-1):
329 """B.split(sep=None, maxsplit=-1) -> list of bytes objects
330
331 Return a list of the words in the string B, using sep as the
332 delimiter string. If maxsplit is given, at most maxsplit
333 splits are done. If sep is not specified or is None, any
334 whitespace string is a separator and empty strings are removed
335 from the result.
336 """
337
338 @unwrap_spec(keepends=bool)
339 def descr_splitlines(self, space, keepends=False):
340 """B.splitlines(keepends=False) -> list of bytes objects
341
342 Return a list of the lines in B, breaking at line boundaries.
343 Line breaks are not included in the resulting list unless keepends
344 is given and true.
345 """
346
347 def descr_startswith(self, space, w_prefix, w_start=None, w_end=None):
348 """B.startswith(prefix[, start[, end]]) -> bool
349
350 Return True if B starts with the specified prefix, False otherwise.
351 With optional start, test B beginning at that position.
352 With optional end, stop comparing B at that position.
353 prefix can also be a tuple of bytes to try.
354 """
355
356 def descr_strip(self, space, w_chars=None):
357 """B.strip([chars]) -> copy of B
358
359 Return a copy of the string B with leading and trailing
360 whitespace removed.
361 If chars is given and not None, remove characters in chars instead.
362 """
363
364 def descr_swapcase(self, space):
365 """B.swapcase() -> copy of B
366
367 Return a copy of the string B with uppercase characters
368 converted to lowercase and vice versa.
369 """
370
371 def descr_title(self, space):
372 """B.title() -> copy of B
373
374 Return a titlecased version of B, i.e. words start with uppercase
375 characters, all remaining cased characters have lowercase.
376 """
377
378 @unwrap_spec(w_delete=WrappedDefault(''))
379 def descr_translate(self, space, w_table, w_delete):
380 """B.translate(table[, deletechars]) -> copy of B
381
382 Return a copy of the string B, where all characters occurring
383 in the optional argument deletechars are removed, and the
384 remaining characters have been mapped through the given
385 translation table, which must be a string of length 256 or None.
386 If the table argument is None, no translation is applied and
387 the operation simply removes the characters in deletechars.
388 """
389
390 def descr_upper(self, space):
391 """B.upper() -> copy of B
392
393 Return a copy of the string B converted to uppercase.
394 """
395
396 @unwrap_spec(width=int)
397 def descr_zfill(self, space, width):
398 """B.zfill(width) -> copy of B
399
400 Pad a numeric string B with zeros on the left, to fill a field
401 of the specified width. The string B is never truncated.
402 """
403
404 def descr_mod(self, space, w_values):
405 """B % values -> bytes
406
407 Format bytes objects
408 """
409
410 def descr_removeprefix(self, space, w_prefix):
411 """Return a str with the given prefix string removed if present.
412
413 If the string starts with the prefix string, return string[len(prefix):].
414 Otherwise, return a copy of the original string.
415 """
416
417 def descr_removesuffix(self, space, w_suffix):
418 """Return a str with the given suffix string removed if present.
419
420 If the string ends with the suffix string, return string[:len(suffix)].
421 Otherwise, return a copy of the original string.
422 """
423
424
425 class W_BytesObject(W_AbstractBytesObject):
426 import_from_mixin(StringMethods)
427 _immutable_fields_ = ['_value']
428 _KIND1 = "byte"
429 _KIND2 = "bytes"
430
431 def __init__(self, s):
432 assert s is not None
433 self._value = s
434
435 def __repr__(self):
436 """representation for debugging purposes"""
437 return "%s(%r)" % (self.__class__.__name__, self._value)
438
439 def unwrap(self, space):
440 return self._value
441
442 def bytes_w(self, space):
443 return self._value
444
445 def realunicode_w(self, space):
446 raise oefmt(space.w_TypeError,
447 "unicode object expected, received bytes instead")
448
449 def text_w(self, space):
450 return self._value
451
452 def buffer_w(self, space, flags):
453 space.check_buf_flags(flags, True)
454 return SimpleView(StringBuffer(self._value), w_obj=self)
455
456 def descr_getbuffer(self, space, w_flags):
457 #from pypy.objspace.std.bufferobject import W_Buffer
458 #return W_Buffer(StringBuffer(self._value))
459 return self
460
461 def listview_int(self):
462 return _create_list_from_bytes(self._value)
463
464 def ord(self, space):
465 if len(self._value) != 1:
466 raise oefmt(space.w_TypeError,
467 "ord() expected a character, but bytes of length %d "
468 "found", len(self._value))
469 return space.newint(ord(self._value[0]))
470
471 def _new(self, value):
472 return W_BytesObject(value)
473
474 def _new_from_list(self, value):
475 return W_BytesObject(''.join(value))
476
477 def _empty(self):
478 return W_BytesObject.EMPTY
479
480 def _len(self):
481 return len(self._value)
482
483 _val = bytes_w
484
485 @staticmethod
486 def _use_rstr_ops(space, w_other):
487 return True
488
489 @staticmethod
490 def _op_val(space, w_other, allow_char=False):
491 # Some functions (contains, find) allow a number to specify a
492 # single char.
493 if allow_char and space.isinstance_w(w_other, space.w_int):
494 return StringMethods._single_char(space, w_other)
495 try:
496 return space.bytes_w(w_other)
497 except OperationError as e:
498 if not e.match(space, space.w_TypeError):
499 raise
500 return space.buffer_w(w_other, space.BUF_SIMPLE).as_str()
501
502 def _chr(self, char):
503 assert len(char) == 1
504 return str(char)[0]
505
506 _builder = StringBuilder
507
508 def _isupper(self, ch):
509 return ch.isupper()
510
511 def _islower(self, ch):
512 return ch.islower()
513
514 def _istitle(self, ch):
515 return ch.isupper()
516
517 def _isspace(self, ch):
518 return ch.isspace()
519
520 def _isalpha(self, ch):
521 return ch.isalpha()
522
523 def _isalnum(self, ch):
524 return ch.isalnum()
525
526 def _isdigit(self, ch):
527 return ch.isdigit()
528
529 _iscased = _isalpha
530
531 def _islinebreak(self, ch):
532 return (ch == '\n') or (ch == '\r')
533
534 def _upper(self, ch):
535 if ch.islower():
536 o = ord(ch) - 32
537 return chr(o)
538 else:
539 return ch
540
541 def _lower(self, ch):
542 if ch.isupper():
543 o = ord(ch) + 32
544 return chr(o)
545 else:
546 return ch
547
548 _title = _upper
549
550 def _newlist_unwrapped(self, space, lst):
551 return space.newlist_bytes(lst)
552
553 @staticmethod
554 @unwrap_spec(encoding='text_or_none', errors='text_or_none')
555 def descr_new(space, w_stringtype, w_source=None, encoding=None,
556 errors=None):
557 if (w_source and space.is_w(w_stringtype, space.w_bytes)
558 and encoding is None and errors is None):
559 # special-case 'bytes(byte_object)'
560 w_srctype = space.type(w_source)
561 if w_srctype is space.w_bytes:
562 return w_source
563 # special-case 'bytes([single_integer])' or 'bytes((single_int,))'
564 # for JITted performance only, when we clearly see the
565 # length of the list/tuple being constant and equal to 1
566 if w_srctype is space.w_list or w_srctype is space.w_tuple:
567 length = space.len_w(w_source)
568 if jit.isconstant(length) and length == 1:
569 w_item = space.getitem(w_source, space.newint(0))
570 value = space.byte_w(w_item)
571 return W_BytesObject(value)
572 else:
573 # special-case 'bytes(X)' if X has a __bytes__() method:
574 # we must return the result unmodified even if it is a
575 # subclass of bytes
576 w_result = invoke_bytes_method(space, w_source)
577 if w_result is not None:
578 return w_result
579 value = newbytesdata_w_tail(space, w_source)
580 else:
581 value = newbytesdata_w(space, w_source, encoding, errors)
582 w_obj = space.allocate_instance(W_BytesObject, w_stringtype)
583 W_BytesObject.__init__(w_obj, value)
584 return w_obj
585
586 @staticmethod
587 def descr_fromhex(space, w_type, w_hexstring):
588 r"""bytes.fromhex(string) -> bytes
589
590 Create a bytes object from a string of hexadecimal numbers.
591 Spaces between two numbers are accepted.
592 Example: bytes.fromhex('B9 01EF') -> b'\xb9\x01\xef'.
593 """
594 if not space.isinstance_w(w_hexstring, space.w_unicode):
595 raise oefmt(space.w_TypeError, "fromhex() argument must be str, not %T", w_hexstring)
596 from pypy.objspace.std.bytearrayobject import _hexstring_to_array
597 hexstring = space.utf8_w(w_hexstring)
598 bytes = ''.join(_hexstring_to_array(space, hexstring))
599 w_result = W_BytesObject(bytes)
600 if w_type is not space.w_bytes:
601 w_result = space.call_function(w_type, w_result)
602 return w_result
603
604 def descr_repr(self, space):
605 return space.newtext(string_escape_encode(self._value, True))
606
607 def descr_str(self, space):
608 if space.sys.get_flag('bytes_warning'):
609 space.warn(space.newtext("str() on a bytes instance"),
610 space.w_BytesWarning)
611 return self.descr_repr(space)
612
613 def descr_hash(self, space):
614 x = compute_hash(self._value)
615 x -= (x == -1) # convert -1 to -2 without creating a bridge
616 return space.newint(x)
617
618 def descr_isascii(self, space):
619 for i in self._value:
620 if ord(i) > 127:
621 return space.w_False
622 return space.w_True
623
624 def descr_eq(self, space, w_other):
625 if not isinstance(w_other, W_BytesObject):
626 return space.w_NotImplemented
627 return space.newbool(self._value == w_other._value)
628
629 def descr_ne(self, space, w_other):
630 if not isinstance(w_other, W_BytesObject):
631 return space.w_NotImplemented
632 return space.newbool(self._value != w_other._value)
633
634 def descr_lt(self, space, w_other):
635 if not isinstance(w_other, W_BytesObject):
636 return space.w_NotImplemented
637 return space.newbool(self._value < w_other._value)
638
639 def descr_le(self, space, w_other):
640 if not isinstance(w_other, W_BytesObject):
641 return space.w_NotImplemented
642 return space.newbool(self._value <= w_other._value)
643
644 def descr_gt(self, space, w_other):
645 if not isinstance(w_other, W_BytesObject):
646 return space.w_NotImplemented
647 return space.newbool(self._value > w_other._value)
648
649 def descr_ge(self, space, w_other):
650 if not isinstance(w_other, W_BytesObject):
651 return space.w_NotImplemented
652 return space.newbool(self._value >= w_other._value)
653
654 # auto-conversion fun
655
656 @unwrap_spec(count=int)
657 def descr_replace(self, space, w_old, w_new, count=-1):
658 from rpython.rlib.rstring import replace
659 # almost copy of StringMethods.descr_replace :-(
660 input = self._value
661
662 sub = self._op_val(space, w_old)
663 by = self._op_val(space, w_new)
664 try:
665 res = replace(input, sub, by, count)
666 except OverflowError:
667 raise oefmt(space.w_OverflowError, "replace string is too long")
668 # difference: reuse self if no replacement was done
669 if type(self) is W_BytesObject and res is input:
670 return self
671
672 return self._new(res)
673
674 _StringMethods_descr_join = descr_join
675 def descr_join(self, space, w_list):
676 l = space.listview_bytes(w_list)
677 if l is not None:
678 if len(l) == 1:
679 return space.newbytes(l[0])
680 return space.newbytes(self._val(space).join(l))
681 return self._StringMethods_descr_join(space, w_list)
682
683 def _join_return_one(self, space, w_obj):
684 return space.is_w(space.type(w_obj), space.w_bytes)
685
686 def descr_lower(self, space):
687 return W_BytesObject(self._value.lower())
688
689 def descr_upper(self, space):
690 return W_BytesObject(self._value.upper())
691
692 def descr_hex(self, space, w_sep=None, w_bytes_per_sep=None):
693 """
694 Create a str of hexadecimal numbers from a bytes object.
695
696 sep
697 An optional single character or byte to separate hex bytes.
698 bytes_per_sep
699 How many bytes between separators. Positive values count from the
700 right, negative values count from the left.
701
702 Example:
703 >>> value = b'\\xb9\\x01\\xef'
704 >>> value.hex()
705 'b901ef'
706 >>> value.hex(':')
707 'b9:01:ef'
708 >>> value.hex(':', 2)
709 'b9:01ef'
710 >>> value.hex(':', -2)
711 'b901:ef'
712 """
713 from pypy.objspace.std.bytearrayobject import _array_to_hexstring, unwrap_hex_sep_arguments
714 sep, bytes_per_sep = unwrap_hex_sep_arguments(space, w_sep, w_bytes_per_sep)
715 return _array_to_hexstring(space, StringBuffer(self._value), 0, 1,
716 len(self._value), sep=sep, bytes_per_sep=bytes_per_sep)
717
718 def descr_mod(self, space, w_values):
719 return mod_format(space, self, w_values, fmt_type=FORMAT_BYTES)
720
721 def descr_rmod(self, space, w_values):
722 if not isinstance(w_values, W_AbstractBytesObject):
723 return space.w_NotImplemented
724 return mod_format(space, w_values, self, fmt_type=FORMAT_BYTES)
725
726 @staticmethod
727 def _iter_getitem_result(self, space, index):
728 assert isinstance(self, W_BytesObject)
729 return self._getitem_result(space, index)
730
731 def descr_bytes(self, space):
732 """Convert this value to exact type bytes."""
733 if type(self) is W_BytesObject:
734 return self
735 return W_BytesObject(self._value)
736
737 def _create_list_from_bytes(value):
738 # need this helper function to allow the jit to look inside and inline
739 # listview_int
740 return [ord(s) for s in value]
741
742 W_BytesObject.EMPTY = W_BytesObject('')
743
744
745 def invoke_bytes_method(space, w_source):
746 w_bytes_method = space.lookup(w_source, "__bytes__")
747 if w_bytes_method is not None:
748 w_bytes = space.get_and_call_function(w_bytes_method, w_source)
749 if not space.isinstance_w(w_bytes, space.w_bytes):
750 raise oefmt(space.w_TypeError,
751 "__bytes__ returned non-bytes (type '%T')", w_bytes)
752 return w_bytes
753 return None
754
755 def newbytesdata_w(space, w_source, encoding, errors):
756 # None value
757 if w_source is None:
758 if encoding is not None or errors is not None:
759 raise oefmt(space.w_TypeError,
760 "encoding or errors without sequence argument")
761 else:
762 return b""
763 # Unicode with encoding
764 if encoding is not None:
765 if not space.isinstance_w(w_source, space.w_unicode):
766 raise oefmt(space.w_TypeError,
767 "encoding without string argument (got '%T' instead)",
768 w_source)
769 w_source = encode_object(space, w_source, encoding, errors)
770 # and continue with the encoded string
771 elif errors is not None:
772 if not space.isinstance_w(w_source, space.w_unicode):
773 raise oefmt(space.w_TypeError,
774 "errors without string argument (got '%T' instead)",
775 w_source)
776 else:
777 raise oefmt(space.w_TypeError,
778 "string argument without an encoding")
779 # Fast-path for bytes
780 if space.type(w_source) is space.w_bytes:
781 return space.bytes_w(w_source)
782 # Some other object with a __bytes__ special method (could be str subclass)
783 w_result = invoke_bytes_method(space, w_source)
784 if w_result is not None:
785 return space.bytes_w(w_result)
786
787 return newbytesdata_w_tail(space, w_source)
788
789 def newbytesdata_w_tail(space, w_source):
790 # converts rare case of bytes constructor arguments: we don't have
791 # any encodings/errors, and the argument does not have __bytes__()
792 if space.isinstance_w(w_source, space.w_unicode):
793 raise oefmt(space.w_TypeError, "string argument without an encoding")
794
795 # Is it an integer?
796 # Note that we're calling space.getindex_w() instead of space.int_w().
797 try:
798 count = space.getindex_w(w_source, space.w_OverflowError)
799 except OperationError as e:
800 if not e.match(space, space.w_TypeError):
801 raise
802 else:
803 if count < 0:
804 raise oefmt(space.w_ValueError, "negative count")
805 return '\0' * count
806
807 return _convert_from_buffer_or_iterable(space, w_source)
808
809 def makebytesdata_w(space, w_source):
810 w_bytes_method = space.lookup(w_source, "__bytes__")
811 if w_bytes_method is not None:
812 w_bytes = space.get_and_call_function(w_bytes_method, w_source)
813 if not space.isinstance_w(w_bytes, space.w_bytes):
814 raise oefmt(space.w_TypeError,
815 "__bytes__ returned non-bytes (type '%T')", w_bytes)
816 return space.bytes_w(w_bytes)
817 return _convert_from_buffer_or_iterable(space, w_source)
818
819 def _convert_from_buffer_or_iterable(space, w_source):
820 # String-like argument
821 try:
822 buf = space.buffer_w(w_source, space.BUF_FULL_RO)
823 except OperationError as e:
824 if not e.match(space, space.w_TypeError):
825 raise
826 else:
827 return buf.as_str()
828
829 if space.isinstance_w(w_source, space.w_unicode):
830 raise oefmt(space.w_TypeError,
831 "cannot convert a (unicode) str object to bytes")
832 return _from_byte_sequence(space, w_source)
833
834
835 def _get_printable_location(w_type):
836 return ('bytearray_from_byte_sequence [w_type=%s]' %
837 w_type.getname(w_type.space))
838
839 _byteseq_jitdriver = jit.JitDriver(
840 name='bytearray_from_byte_sequence',
841 greens=['w_type'],
842 reds=['w_iter', 'builder'],
843 get_printable_location=_get_printable_location)
844
845 def _from_byte_sequence(space, w_source):
846 # Split off in a separate function for the JIT's benefit
847 # and add a jitdriver with the type of w_iter as the green key
848 w_iter = space.iter(w_source)
849 length_hint = space.length_hint(w_source, 0)
850 builder = StringBuilder(length_hint)
851 #
852 _from_byte_sequence_loop(space, w_iter, builder)
853 #
854 return builder.build()
855
856 def _from_byte_sequence_loop(space, w_iter, builder):
857 w_type = space.type(w_iter)
858 while True:
859 _byteseq_jitdriver.jit_merge_point(w_type=w_type,
860 w_iter=w_iter,
861 builder=builder)
862 try:
863 w_item = space.next(w_iter)
864 except OperationError as e:
865 if not e.match(space, space.w_StopIteration):
866 raise
867 break
868 builder.append(space.byte_w(w_item))
869
870 W_BytesObject.typedef = TypeDef(
871 "bytes", None, None, "read",
872 __new__ = interp2app(W_BytesObject.descr_new),
873 __doc__ = """bytes(iterable_of_ints) -> bytes
874 bytes(string, encoding[, errors]) -> bytes
875 bytes(bytes_or_buffer) -> immutable copy of bytes_or_buffer
876 bytes(int) -> bytes object of size given by the parameter initialized with null bytes
877 bytes() -> empty bytes object
878
879 Construct an immutable array of bytes from:
880 - an iterable yielding integers in range(256)
881 - a text string encoded using the specified encoding
882 - any object implementing the buffer API.
883 - an integer
884 """,
885
886 __repr__ = interpindirect2app(W_AbstractBytesObject.descr_repr),
887 __str__ = interpindirect2app(W_AbstractBytesObject.descr_str),
888 __hash__ = interpindirect2app(W_AbstractBytesObject.descr_hash),
889
890 __eq__ = interpindirect2app(W_AbstractBytesObject.descr_eq),
891 __ne__ = interpindirect2app(W_AbstractBytesObject.descr_ne),
892 __lt__ = interpindirect2app(W_AbstractBytesObject.descr_lt),
893 __le__ = interpindirect2app(W_AbstractBytesObject.descr_le),
894 __gt__ = interpindirect2app(W_AbstractBytesObject.descr_gt),
895 __ge__ = interpindirect2app(W_AbstractBytesObject.descr_ge),
896
897 __iter__ = interpindirect2app(W_AbstractBytesObject.descr_iter),
898 __len__ = interpindirect2app(W_AbstractBytesObject.descr_len),
899 __contains__ = interpindirect2app(W_AbstractBytesObject.descr_contains),
900
901 __add__ = interpindirect2app(W_AbstractBytesObject.descr_add),
902 __mul__ = interpindirect2app(W_AbstractBytesObject.descr_mul),
903 __rmul__ = interpindirect2app(W_AbstractBytesObject.descr_rmul),
904
905 __mod__ = interpindirect2app(W_AbstractBytesObject.descr_mod),
906 __rmod__ = interpindirect2app(W_AbstractBytesObject.descr_rmod),
907
908 __getitem__ = interpindirect2app(W_AbstractBytesObject.descr_getitem),
909
910 __bytes__ = interp2app(W_BytesObject.descr_bytes),
911
912 capitalize = interpindirect2app(W_AbstractBytesObject.descr_capitalize),
913 center = interpindirect2app(W_AbstractBytesObject.descr_center),
914 count = interpindirect2app(W_AbstractBytesObject.descr_count),
915 decode = interpindirect2app(W_AbstractBytesObject.descr_decode),
916 expandtabs = interpindirect2app(W_AbstractBytesObject.descr_expandtabs),
917 find = interpindirect2app(W_AbstractBytesObject.descr_find),
918 rfind = interpindirect2app(W_AbstractBytesObject.descr_rfind),
919 index = interpindirect2app(W_AbstractBytesObject.descr_index),
920 rindex = interpindirect2app(W_AbstractBytesObject.descr_rindex),
921 isalnum = interpindirect2app(W_AbstractBytesObject.descr_isalnum),
922 isalpha = interpindirect2app(W_AbstractBytesObject.descr_isalpha),
923 isdigit = interpindirect2app(W_AbstractBytesObject.descr_isdigit),
924 islower = interpindirect2app(W_AbstractBytesObject.descr_islower),
925 isspace = interpindirect2app(W_AbstractBytesObject.descr_isspace),
926 istitle = interpindirect2app(W_AbstractBytesObject.descr_istitle),
927 isupper = interpindirect2app(W_AbstractBytesObject.descr_isupper),
928 isascii = interpindirect2app(W_AbstractBytesObject.descr_isascii),
929 join = interpindirect2app(W_AbstractBytesObject.descr_join),
930 ljust = interpindirect2app(W_AbstractBytesObject.descr_ljust),
931 rjust = interpindirect2app(W_AbstractBytesObject.descr_rjust),
932 lower = interpindirect2app(W_AbstractBytesObject.descr_lower),
933 partition = interpindirect2app(W_AbstractBytesObject.descr_partition),
934 rpartition = interpindirect2app(W_AbstractBytesObject.descr_rpartition),
935 replace = interpindirect2app(W_AbstractBytesObject.descr_replace),
936 split = interpindirect2app(W_AbstractBytesObject.descr_split),
937 rsplit = interpindirect2app(W_AbstractBytesObject.descr_rsplit),
938 splitlines = interpindirect2app(W_AbstractBytesObject.descr_splitlines),
939 startswith = interpindirect2app(W_AbstractBytesObject.descr_startswith),
940 endswith = interpindirect2app(W_AbstractBytesObject.descr_endswith),
941 strip = interpindirect2app(W_AbstractBytesObject.descr_strip),
942 lstrip = interpindirect2app(W_AbstractBytesObject.descr_lstrip),
943 rstrip = interpindirect2app(W_AbstractBytesObject.descr_rstrip),
944 swapcase = interpindirect2app(W_AbstractBytesObject.descr_swapcase),
945 title = interpindirect2app(W_AbstractBytesObject.descr_title),
946 translate = interpindirect2app(W_AbstractBytesObject.descr_translate),
947 upper = interpindirect2app(W_AbstractBytesObject.descr_upper),
948 zfill = interpindirect2app(W_AbstractBytesObject.descr_zfill),
949
950 removeprefix = interpindirect2app(W_AbstractBytesObject.descr_removeprefix),
951 removesuffix = interpindirect2app(W_AbstractBytesObject.descr_removesuffix),
952
953 __getnewargs__ = interpindirect2app(
954 W_AbstractBytesObject.descr_getnewargs),
955
956 fromhex = interp2app(W_BytesObject.descr_fromhex, as_classmethod=True),
957 maketrans = interp2app(W_BytesObject.descr_maketrans, as_classmethod=True),
958 hex = interp2app(W_BytesObject.descr_hex),
959 )
960 W_BytesObject.typedef.flag_sequence_bug_compat = True
961
962
963 @jit.elidable
964 def string_escape_encode(s, quotes):
965 buf = StringBuilder(len(s) + 2)
966
967 quote = "'"
968 if quotes:
969 if quote in s and '"' not in s:
970 quote = '"'
971 buf.append('b"')
972 else:
973 buf.append("b'")
974
975 startslice = 0
976
977 for i in range(len(s)):
978 c = s[i]
979 use_bs_char = False # character quoted by backspace
980
981 if c == '\\' or c == quote:
982 bs_char = c
983 use_bs_char = True
984 elif c == '\t':
985 bs_char = 't'
986 use_bs_char = True
987 elif c == '\r':
988 bs_char = 'r'
989 use_bs_char = True
990 elif c == '\n':
991 bs_char = 'n'
992 use_bs_char = True
993 elif not '\x20' <= c < '\x7f':
994 n = ord(c)
995 if i != startslice:
996 buf.append_slice(s, startslice, i)
997 startslice = i + 1
998 buf.append('\\x')
999 buf.append("0123456789abcdef"[n >> 4])
1000 buf.append("0123456789abcdef"[n & 0xF])
1001
1002 if use_bs_char:
1003 if i != startslice:
1004 buf.append_slice(s, startslice, i)
1005 startslice = i + 1
1006 buf.append('\\')
1007 buf.append(bs_char)
1008
1009 if len(s) != startslice:
1010 buf.append_slice(s, startslice, len(s))
1011
1012 if quotes:
1013 buf.append(quote)
1014
1015 return buf.build()