| 1 |
"""The builtin bytearray implementation""" |
| 2 |
|
| 3 |
import sys |
| 4 |
from rpython.rlib.objectmodel import ( |
| 5 |
import_from_mixin, newlist_hint, resizelist_hint, specialize) |
| 6 |
from rpython.rlib.rarithmetic import intmask |
| 7 |
from rpython.rlib.rstring import ( |
| 8 |
StringBuilder, ByteListBuilder) |
| 9 |
from rpython.rlib.debug import check_list_of_chars, check_nonneg |
| 10 |
from rpython.rtyper.lltypesystem import rffi |
| 11 |
from rpython.rlib.rgc import (resizable_list_supporting_raw_ptr, |
| 12 |
nonmoving_raw_ptr_for_resizable_list) |
| 13 |
from rpython.rlib import jit |
| 14 |
from rpython.rlib.buffer import (GCBuffer, |
| 15 |
get_gc_data_for_list_of_chars, |
| 16 |
get_gc_data_offset_for_list_of_chars) |
| 17 |
from pypy.interpreter.baseobjspace import W_Root |
| 18 |
from pypy.interpreter.error import OperationError, oefmt |
| 19 |
from pypy.objspace.std.bytesobject import makebytesdata_w, newbytesdata_w |
| 20 |
from pypy.interpreter.gateway import WrappedDefault, interp2app, unwrap_spec |
| 21 |
from pypy.interpreter.typedef import TypeDef |
| 22 |
from pypy.interpreter.buffer import SimpleView |
| 23 |
from pypy.objspace.std.sliceobject import W_SliceObject, unwrap_start_stop |
| 24 |
from pypy.objspace.std.stringmethods import StringMethods |
| 25 |
from pypy.objspace.std.stringmethods import _descr_getslice_slowpath |
| 26 |
from pypy.objspace.std.bytesobject import W_BytesObject |
| 27 |
from pypy.objspace.std.util import get_positive_index |
| 28 |
from pypy.objspace.std.formatting import mod_format, FORMAT_BYTEARRAY |
| 29 |
|
| 30 |
|
| 31 |
class W_BytearrayObject(W_Root): |
| 32 |
import_from_mixin(StringMethods) |
| 33 |
_KIND1 = "bytearray" |
| 34 |
_KIND2 = "bytearray" |
| 35 |
|
| 36 |
def __init__(self, data): |
| 37 |
check_list_of_chars(data) |
| 38 |
|
| 39 |
data += "\0" |
| 40 |
self._data = resizable_list_supporting_raw_ptr(data) |
| 41 |
self._offset = 0 |
| 42 |
|
| 43 |
check_nonneg(self._offset) |
| 44 |
_tweak_for_tests(self) |
| 45 |
|
| 46 |
def getdata(self): |
| 47 |
if self._offset > 0: |
| 48 |
self._data = self._data[self._offset:] |
| 49 |
self._offset = 0 |
| 50 |
return self._data |
| 51 |
|
| 52 |
def __repr__(self): |
| 53 |
"""representation for debugging purposes""" |
| 54 |
return "%s(%s)" % (self.__class__.__name__, |
| 55 |
''.join(self._data[self._offset:-1])) |
| 56 |
|
| 57 |
def buffer_w(self, space, flags): |
| 58 |
return SimpleView(BytearrayBuffer(self), w_obj=self) |
| 59 |
|
| 60 |
def bytearray_list_of_chars_w(self, space): |
| 61 |
return self._val(space) |
| 62 |
|
| 63 |
def nonmovable_carray(self, space): |
| 64 |
return BytearrayBuffer(self).get_raw_address() |
| 65 |
|
| 66 |
def _new(self, value): |
| 67 |
if value is self._data: |
| 68 |
value = value[:-1] |
| 69 |
return W_BytearrayObject(value) |
| 70 |
|
| 71 |
def _new_from_buffer(self, buffer): |
| 72 |
return W_BytearrayObject([buffer[i] for i in range(len(buffer))]) |
| 73 |
|
| 74 |
def _new_from_list(self, value): |
| 75 |
return W_BytearrayObject(value) |
| 76 |
|
| 77 |
def _empty(self): |
| 78 |
return W_BytearrayObject([]) |
| 79 |
|
| 80 |
def _len(self): |
| 81 |
return len(self._data) - self._offset - 1 |
| 82 |
|
| 83 |
def _fixindex(self, space, index, errmsg="bytearray index out of range"): |
| 84 |
|
| 85 |
if index >= 0: |
| 86 |
index += self._offset |
| 87 |
if index >= len(self._data) - 1: |
| 88 |
raise OperationError(space.w_IndexError, space.newtext(errmsg)) |
| 89 |
else: |
| 90 |
index += len(self._data) - 1 |
| 91 |
if index < self._offset: |
| 92 |
raise OperationError(space.w_IndexError, space.newtext(errmsg)) |
| 93 |
check_nonneg(index) |
| 94 |
return index |
| 95 |
|
| 96 |
def _getitem_result(self, space, index): |
| 97 |
character = self._data[self._fixindex(space, index)] |
| 98 |
return space.newint(ord(character)) |
| 99 |
|
| 100 |
def _val(self, space): |
| 101 |
|
| 102 |
return self.getdata()[:-1] |
| 103 |
|
| 104 |
@staticmethod |
| 105 |
def _use_rstr_ops(space, w_other): |
| 106 |
return False |
| 107 |
|
| 108 |
@staticmethod |
| 109 |
def _op_val(space, w_other, allow_char=False): |
| 110 |
|
| 111 |
|
| 112 |
if allow_char and space.isinstance_w(w_other, space.w_int): |
| 113 |
return StringMethods._single_char(space, w_other) |
| 114 |
try: |
| 115 |
return space.bytes_w(w_other) |
| 116 |
except OperationError as e: |
| 117 |
if not e.match(space, space.w_TypeError): |
| 118 |
raise |
| 119 |
return space.buffer_w(w_other, space.BUF_SIMPLE).as_str() |
| 120 |
|
| 121 |
def _chr(self, char): |
| 122 |
assert len(char) == 1 |
| 123 |
return str(char)[0] |
| 124 |
|
| 125 |
def _multi_chr(self, char): |
| 126 |
return [char] |
| 127 |
|
| 128 |
@staticmethod |
| 129 |
def _builder(size=100): |
| 130 |
return ByteListBuilder(size) |
| 131 |
|
| 132 |
def _newlist_unwrapped(self, space, res): |
| 133 |
return space.newlist([W_BytearrayObject(i) for i in res]) |
| 134 |
|
| 135 |
def _isupper(self, ch): |
| 136 |
return ch.isupper() |
| 137 |
|
| 138 |
def _islower(self, ch): |
| 139 |
return ch.islower() |
| 140 |
|
| 141 |
def _istitle(self, ch): |
| 142 |
return ch.isupper() |
| 143 |
|
| 144 |
def _isspace(self, ch): |
| 145 |
return ch.isspace() |
| 146 |
|
| 147 |
def _isalpha(self, ch): |
| 148 |
return ch.isalpha() |
| 149 |
|
| 150 |
def _isalnum(self, ch): |
| 151 |
return ch.isalnum() |
| 152 |
|
| 153 |
def _isdigit(self, ch): |
| 154 |
return ch.isdigit() |
| 155 |
|
| 156 |
_iscased = _isalpha |
| 157 |
|
| 158 |
def _islinebreak(self, ch): |
| 159 |
return (ch == '\n') or (ch == '\r') |
| 160 |
|
| 161 |
def _upper(self, ch): |
| 162 |
if ch.islower(): |
| 163 |
o = ord(ch) - 32 |
| 164 |
return chr(o) |
| 165 |
else: |
| 166 |
return ch |
| 167 |
|
| 168 |
def _lower(self, ch): |
| 169 |
if ch.isupper(): |
| 170 |
o = ord(ch) + 32 |
| 171 |
return chr(o) |
| 172 |
else: |
| 173 |
return ch |
| 174 |
|
| 175 |
_title = _upper |
| 176 |
|
| 177 |
def _join_return_one(self, space, w_obj): |
| 178 |
return False |
| 179 |
|
| 180 |
def ord(self, space): |
| 181 |
length = self._len() |
| 182 |
if length != 1: |
| 183 |
raise oefmt(space.w_TypeError, |
| 184 |
"ord() expected a character, but string of length %d " |
| 185 |
"found", length) |
| 186 |
return space.newint(ord(self._data[self._offset])) |
| 187 |
|
| 188 |
@staticmethod |
| 189 |
def descr_new(space, w_bytearraytype, __args__): |
| 190 |
return new_bytearray(space, w_bytearraytype, []) |
| 191 |
|
| 192 |
def descr_reduce(self, space): |
| 193 |
from pypy.interpreter.unicodehelper import str_decode_latin_1 |
| 194 |
|
| 195 |
assert isinstance(self, W_BytearrayObject) |
| 196 |
w_state = space.call_method(self, '__getstate__') |
| 197 |
s_ = ''.join(self.getdata()[:-1]) |
| 198 |
w_s = space.newbytes(s_) |
| 199 |
s, _, lgt = str_decode_latin_1(space, s_, w_s, 'strict', |
| 200 |
True, None) |
| 201 |
return space.newtuple([ |
| 202 |
space.type(self), space.newtuple2( |
| 203 |
space.newutf8(s, lgt), space.newtext('latin-1')), |
| 204 |
w_state]) |
| 205 |
|
| 206 |
@staticmethod |
| 207 |
def descr_fromhex(space, w_bytearraytype, w_hexstring): |
| 208 |
if not space.isinstance_w(w_hexstring, space.w_unicode): |
| 209 |
raise oefmt(space.w_TypeError, "must be str, not %T", w_hexstring) |
| 210 |
hexstring = space.utf8_w(w_hexstring) |
| 211 |
data = _hexstring_to_array(space, hexstring) |
| 212 |
w_result = new_bytearray(space, space.w_bytearray, data) |
| 213 |
if w_bytearraytype is not space.w_bytearray: |
| 214 |
w_result = space.call_function(w_bytearraytype, w_result) |
| 215 |
return w_result |
| 216 |
|
| 217 |
@unwrap_spec(encoding='text_or_none', errors='text_or_none') |
| 218 |
def descr_init(self, space, w_source=None, encoding=None, errors=None): |
| 219 |
assert isinstance(self, W_BytearrayObject) |
| 220 |
data = [c for c in newbytesdata_w(space, w_source, encoding, errors)] |
| 221 |
data += "\0" |
| 222 |
self._data = resizable_list_supporting_raw_ptr(data) |
| 223 |
self._offset = 0 |
| 224 |
_tweak_for_tests(self) |
| 225 |
|
| 226 |
def descr_repr(self, space): |
| 227 |
s, start, end, _ = self._convert_idx_params(space, None, None) |
| 228 |
cls_name = space.type(self).getname(space) |
| 229 |
|
| 230 |
|
| 231 |
buf = StringBuilder(len(cls_name) + len("(b'')") + (end - start)) |
| 232 |
|
| 233 |
buf.append(cls_name) |
| 234 |
buf.append("(b") |
| 235 |
quote = "'" |
| 236 |
for i in range(start, end): |
| 237 |
c = s[i] |
| 238 |
if c == '"': |
| 239 |
quote = "'" |
| 240 |
break |
| 241 |
elif c == "'": |
| 242 |
quote = '"' |
| 243 |
buf.append(quote) |
| 244 |
|
| 245 |
for i in range(start, end): |
| 246 |
c = s[i] |
| 247 |
|
| 248 |
if c == '\\' or c == "'": |
| 249 |
buf.append('\\') |
| 250 |
buf.append(c) |
| 251 |
elif c == '\t': |
| 252 |
buf.append('\\t') |
| 253 |
elif c == '\r': |
| 254 |
buf.append('\\r') |
| 255 |
elif c == '\n': |
| 256 |
buf.append('\\n') |
| 257 |
elif not '\x20' <= c < '\x7f': |
| 258 |
n = ord(c) |
| 259 |
buf.append('\\x') |
| 260 |
buf.append("0123456789abcdef"[n >> 4]) |
| 261 |
buf.append("0123456789abcdef"[n & 0xF]) |
| 262 |
else: |
| 263 |
buf.append(c) |
| 264 |
|
| 265 |
buf.append(quote) |
| 266 |
buf.append(")") |
| 267 |
|
| 268 |
return space.newtext(buf.build()) |
| 269 |
|
| 270 |
def descr_str(self, space): |
| 271 |
if space.sys.get_flag('bytes_warning'): |
| 272 |
space.warn(space.newtext("str() on a bytearray instance"), |
| 273 |
space.w_BytesWarning) |
| 274 |
return self.descr_repr(space) |
| 275 |
|
| 276 |
def descr_eq(self, space, w_other): |
| 277 |
if isinstance(w_other, W_BytearrayObject): |
| 278 |
return space.newbool(self.getdata() == w_other.getdata()) |
| 279 |
|
| 280 |
try: |
| 281 |
buffer = space.readbuf_w(w_other) |
| 282 |
except OperationError as e: |
| 283 |
if e.match(space, space.w_TypeError): |
| 284 |
return space.w_NotImplemented |
| 285 |
raise |
| 286 |
|
| 287 |
value = self.getdata() |
| 288 |
buffer_len = buffer.getlength() |
| 289 |
|
| 290 |
if self._len() != buffer_len: |
| 291 |
return space.newbool(False) |
| 292 |
|
| 293 |
min_length = min(self._len(), buffer_len) |
| 294 |
return space.newbool(_memcmp(value, buffer, min_length) == 0) |
| 295 |
|
| 296 |
def descr_ne(self, space, w_other): |
| 297 |
if isinstance(w_other, W_BytearrayObject): |
| 298 |
return space.newbool(self.getdata() != w_other.getdata()) |
| 299 |
|
| 300 |
try: |
| 301 |
buffer = space.readbuf_w(w_other) |
| 302 |
except OperationError as e: |
| 303 |
if e.match(space, space.w_TypeError): |
| 304 |
return space.w_NotImplemented |
| 305 |
raise |
| 306 |
|
| 307 |
value = self.getdata() |
| 308 |
buffer_len = buffer.getlength() |
| 309 |
|
| 310 |
if self._len() != buffer_len: |
| 311 |
return space.newbool(True) |
| 312 |
|
| 313 |
min_length = min(self._len(), buffer_len) |
| 314 |
return space.newbool(_memcmp(value, buffer, min_length) != 0) |
| 315 |
|
| 316 |
def _comparison_helper(self, space, w_other): |
| 317 |
value = self.getdata() |
| 318 |
|
| 319 |
if isinstance(w_other, W_BytearrayObject): |
| 320 |
other = w_other.getdata() |
| 321 |
other_len = w_other._len() |
| 322 |
cmp = _memcmp(value, other, min(self._len(), other_len)) |
| 323 |
elif isinstance(w_other, W_BytesObject): |
| 324 |
other = w_other.bytes_w(space) |
| 325 |
other_len = len(other) |
| 326 |
cmp = _memcmp(value, other, min(self._len(), len(other))) |
| 327 |
else: |
| 328 |
try: |
| 329 |
buffer = space.readbuf_w(w_other) |
| 330 |
except OperationError as e: |
| 331 |
if e.match(space, space.w_TypeError): |
| 332 |
return False, 0, 0 |
| 333 |
raise |
| 334 |
other_len = len(buffer) |
| 335 |
cmp = _memcmp(value, buffer, min(self._len(), len(buffer))) |
| 336 |
|
| 337 |
return True, cmp, other_len |
| 338 |
|
| 339 |
def descr_lt(self, space, w_other): |
| 340 |
success, cmp, other_len = self._comparison_helper(space, w_other) |
| 341 |
if not success: |
| 342 |
return space.w_NotImplemented |
| 343 |
return space.newbool(cmp < 0 or (cmp == 0 and self._len() < other_len)) |
| 344 |
|
| 345 |
def descr_le(self, space, w_other): |
| 346 |
success, cmp, other_len = self._comparison_helper(space, w_other) |
| 347 |
if not success: |
| 348 |
return space.w_NotImplemented |
| 349 |
return space.newbool(cmp < 0 or (cmp == 0 and self._len() <= other_len)) |
| 350 |
|
| 351 |
def descr_gt(self, space, w_other): |
| 352 |
success, cmp, other_len = self._comparison_helper(space, w_other) |
| 353 |
if not success: |
| 354 |
return space.w_NotImplemented |
| 355 |
return space.newbool(cmp > 0 or (cmp == 0 and self._len() > other_len)) |
| 356 |
|
| 357 |
def descr_ge(self, space, w_other): |
| 358 |
success, cmp, other_len = self._comparison_helper(space, w_other) |
| 359 |
if not success: |
| 360 |
return space.w_NotImplemented |
| 361 |
return space.newbool(cmp > 0 or (cmp == 0 and self._len() >= other_len)) |
| 362 |
|
| 363 |
def descr_isascii(self, space): |
| 364 |
for i in self._data[self._offset:]: |
| 365 |
if ord(i) > 127: |
| 366 |
return space.w_False |
| 367 |
return space.w_True |
| 368 |
|
| 369 |
def descr_inplace_add(self, space, w_other): |
| 370 |
if isinstance(w_other, W_BytearrayObject): |
| 371 |
other_data = w_other.getdata()[:-1] |
| 372 |
else: |
| 373 |
other_data = list(self._op_val(space, w_other)) |
| 374 |
|
| 375 |
data = self.getdata() |
| 376 |
data.pop() |
| 377 |
data.extend(other_data) |
| 378 |
data.append("\0") |
| 379 |
return self |
| 380 |
|
| 381 |
def descr_inplace_mul(self, space, w_times): |
| 382 |
try: |
| 383 |
times = space.getindex_w(w_times, space.w_OverflowError) |
| 384 |
except OperationError as e: |
| 385 |
if e.match(space, space.w_TypeError): |
| 386 |
return space.w_NotImplemented |
| 387 |
raise |
| 388 |
data = self.getdata() |
| 389 |
|
| 390 |
if data: |
| 391 |
data.pop() |
| 392 |
data *= times |
| 393 |
data.append("\0") |
| 394 |
return self |
| 395 |
|
| 396 |
def descr_setitem(self, space, w_index, w_other): |
| 397 |
if isinstance(w_index, W_SliceObject): |
| 398 |
sequence2 = makebytesdata_w(space, w_other) |
| 399 |
start, stop, step, slicelength = self._unpack_slice(space, w_index) |
| 400 |
if start == 0 and step == 1 and len(sequence2) <= slicelength: |
| 401 |
self._delete_from_start(slicelength - len(sequence2)) |
| 402 |
slicelength = len(sequence2) |
| 403 |
if slicelength == 0: |
| 404 |
return |
| 405 |
data = self._data |
| 406 |
start += self._offset |
| 407 |
_setitem_slice_helper(space, data, start, step, |
| 408 |
slicelength, sequence2, empty_elem='\x00') |
| 409 |
else: |
| 410 |
idx = space.getindex_w(w_index, space.w_IndexError, "bytearray") |
| 411 |
newvalue = space.byte_w(w_other) |
| 412 |
self._data[self._fixindex(space, idx)] = newvalue |
| 413 |
|
| 414 |
def descr_delitem(self, space, w_idx): |
| 415 |
if isinstance(w_idx, W_SliceObject): |
| 416 |
start, stop, step, slicelength = self._unpack_slice(space, w_idx) |
| 417 |
if start == 0 and step == 1: |
| 418 |
self._delete_from_start(slicelength) |
| 419 |
else: |
| 420 |
_delitem_slice_helper(space, self._data, |
| 421 |
start + self._offset, step, slicelength) |
| 422 |
else: |
| 423 |
idx = space.getindex_w(w_idx, space.w_IndexError, "bytearray") |
| 424 |
idx = self._fixindex(space, idx) |
| 425 |
if idx == self._offset: |
| 426 |
self._delete_from_start(1) |
| 427 |
else: |
| 428 |
del self._data[idx] |
| 429 |
|
| 430 |
def _delete_from_start(self, n): |
| 431 |
assert n >= 0 |
| 432 |
self._offset += n |
| 433 |
jit.conditional_call(self._offset > (len(self._data) - 1) / 2, |
| 434 |
_shrink_after_delete_from_start, self) |
| 435 |
|
| 436 |
def descr_append(self, space, w_item): |
| 437 |
data = self.getdata() |
| 438 |
location = len(data) - 1 |
| 439 |
assert location >= 0 |
| 440 |
data.insert(location, space.byte_w(w_item)) |
| 441 |
|
| 442 |
def descr_extend(self, space, w_other): |
| 443 |
if isinstance(w_other, W_BytearrayObject): |
| 444 |
other_data = list(w_other.getdata()[:-1]) |
| 445 |
elif isinstance(w_other, W_BytesObject): |
| 446 |
other_data = list(w_other.bytes_w(space)) |
| 447 |
else: |
| 448 |
other_data = list(makebytesdata_w(space, w_other)) |
| 449 |
data = self.getdata() |
| 450 |
assert data[len(data) - 1] == "\0" |
| 451 |
|
| 452 |
data.pop() |
| 453 |
data += other_data |
| 454 |
data.append("\0") |
| 455 |
|
| 456 |
def descr_insert(self, space, w_idx, w_other): |
| 457 |
where = space.int_w(w_idx) |
| 458 |
data = self.getdata() |
| 459 |
index = get_positive_index(where, len(data) - 1) |
| 460 |
val = space.byte_w(w_other) |
| 461 |
data.insert(index, val) |
| 462 |
|
| 463 |
@unwrap_spec(w_idx=WrappedDefault(-1)) |
| 464 |
def descr_pop(self, space, w_idx): |
| 465 |
index = space.int_w(w_idx) |
| 466 |
if self._len() == 0: |
| 467 |
raise oefmt(space.w_IndexError, "pop from empty bytearray") |
| 468 |
index = self._fixindex(space, index, "pop index out of range") |
| 469 |
result = self._data.pop(index) |
| 470 |
return space.newint(ord(result)) |
| 471 |
|
| 472 |
def descr_remove(self, space, w_char): |
| 473 |
char = space.int_w(space.index(w_char)) |
| 474 |
_data = self._data |
| 475 |
for index in range(self._offset, len(_data) - 1): |
| 476 |
if ord(_data[index]) == char: |
| 477 |
del _data[index] |
| 478 |
return |
| 479 |
raise oefmt(space.w_ValueError, "value not found in bytearray") |
| 480 |
|
| 481 |
def descr_add(self, space, w_other): |
| 482 |
if isinstance(w_other, W_BytearrayObject): |
| 483 |
return self._new(self.getdata()[:-1] + w_other.getdata()[:-1]) |
| 484 |
|
| 485 |
try: |
| 486 |
byte_string = self._op_val(space, w_other) |
| 487 |
except OperationError as e: |
| 488 |
if e.match(space, space.w_TypeError): |
| 489 |
return space.w_NotImplemented |
| 490 |
raise |
| 491 |
return self._new(self.getdata()[:-1] + list(byte_string)) |
| 492 |
|
| 493 |
def descr_reverse(self, space): |
| 494 |
data = self.getdata() |
| 495 |
|
| 496 |
for i in range((len(data) - 1) // 2): |
| 497 |
tmp = data[-i - 2] |
| 498 |
data[-i - 2] = data[i] |
| 499 |
data[i] = tmp |
| 500 |
|
| 501 |
def descr_clear(self, space): |
| 502 |
self._data = ["\0"] |
| 503 |
self._offset = 0 |
| 504 |
|
| 505 |
def descr_copy(self, space): |
| 506 |
stop = len(self._data) - 1 |
| 507 |
assert stop >= 0 |
| 508 |
return self._new(self._data[self._offset:stop]) |
| 509 |
|
| 510 |
def descr_hex(self, space, w_sep=None, w_bytes_per_sep=None): |
| 511 |
""" |
| 512 |
Create a str of hexadecimal numbers from a bytearray object. |
| 513 |
|
| 514 |
sep |
| 515 |
An optional single character or byte to separate hex bytes. |
| 516 |
bytes_per_sep |
| 517 |
How many bytes between separators. Positive values count from the |
| 518 |
right, negative values count from the left. |
| 519 |
|
| 520 |
Example: |
| 521 |
>>> value = bytearray([0xb9, 0x01, 0xef]) |
| 522 |
>>> value.hex() |
| 523 |
'b901ef' |
| 524 |
>>> value.hex(':') |
| 525 |
'b9:01:ef' |
| 526 |
>>> value.hex(':', 2) |
| 527 |
'b9:01ef' |
| 528 |
>>> value.hex(':', -2) |
| 529 |
'b901:ef' |
| 530 |
""" |
| 531 |
sep, bytes_per_sep = unwrap_hex_sep_arguments(space, w_sep, w_bytes_per_sep) |
| 532 |
data = self.getdata() |
| 533 |
return _array_to_hexstring(space, data, 0, 1, len(data)-1, True, |
| 534 |
sep=sep, bytes_per_sep=bytes_per_sep) |
| 535 |
|
| 536 |
def descr_mod(self, space, w_values): |
| 537 |
return mod_format(space, self, w_values, fmt_type=FORMAT_BYTEARRAY) |
| 538 |
|
| 539 |
def descr_rmod(self, space, w_value): |
| 540 |
if not isinstance(w_value, W_BytearrayObject): |
| 541 |
return space.w_NotImplemented |
| 542 |
return mod_format(space, w_value, self, fmt_type=FORMAT_BYTEARRAY) |
| 543 |
|
| 544 |
@staticmethod |
| 545 |
def _iter_getitem_result(self, space, index): |
| 546 |
assert isinstance(self, W_BytearrayObject) |
| 547 |
return self._getitem_result(space, index) |
| 548 |
|
| 549 |
def descr_alloc(self, space): |
| 550 |
return space.newint(len(self._data)) |
| 551 |
|
| 552 |
def _convert_idx_params(self, space, w_start, w_end): |
| 553 |
|
| 554 |
|
| 555 |
length = self._len() |
| 556 |
start, end = unwrap_start_stop(space, length, w_start, w_end) |
| 557 |
ofs = self._offset |
| 558 |
if length < 1: |
| 559 |
ofs += 1 |
| 560 |
if end > length: |
| 561 |
end = length |
| 562 |
|
| 563 |
|
| 564 |
|
| 565 |
if start > length + 1: |
| 566 |
start = length + 1 |
| 567 |
return (self._data, start + ofs, end + ofs, ofs) |
| 568 |
|
| 569 |
def _unpack_slice(self, space, w_index): |
| 570 |
|
| 571 |
|
| 572 |
start, stop, step = w_index.unpack(space) |
| 573 |
length = self._len() |
| 574 |
return w_index.adjust_indices(start, stop, step, length) |
| 575 |
|
| 576 |
def descr_getitem(self, space, w_index): |
| 577 |
|
| 578 |
if isinstance(w_index, W_SliceObject): |
| 579 |
start, stop, step, sl = self._unpack_slice(space, w_index) |
| 580 |
if sl == 0: |
| 581 |
return self._empty() |
| 582 |
elif step == 1: |
| 583 |
assert start >= 0 and stop >= 0 |
| 584 |
ofs = self._offset |
| 585 |
return self._new(self._data[start + ofs : stop + ofs]) |
| 586 |
else: |
| 587 |
start += self._offset |
| 588 |
ret = _descr_getslice_slowpath(self._data, start, step, sl) |
| 589 |
return self._new_from_list(ret) |
| 590 |
|
| 591 |
index = space.getindex_w(w_index, space.w_IndexError, self._KIND1) |
| 592 |
return self._getitem_result(space, index) |
| 593 |
|
| 594 |
def descr_releasebuffer(self, w_view): |
| 595 |
|
| 596 |
|
| 597 |
return None |
| 598 |
|
| 599 |
|
| 600 |
|
| 601 |
|
| 602 |
def new_bytearray(space, w_bytearraytype, data): |
| 603 |
w_obj = space.allocate_instance(W_BytearrayObject, w_bytearraytype) |
| 604 |
W_BytearrayObject.__init__(w_obj, data) |
| 605 |
return w_obj |
| 606 |
|
| 607 |
|
| 608 |
def _hex_digit_to_int(d): |
| 609 |
val = ord(d) |
| 610 |
if 47 < val < 58: |
| 611 |
return val - 48 |
| 612 |
if 64 < val < 71: |
| 613 |
return val - 55 |
| 614 |
if 96 < val < 103: |
| 615 |
return val - 87 |
| 616 |
return -1 |
| 617 |
|
| 618 |
NON_HEX_MSG = "non-hexadecimal number found in fromhex() arg at position %d" |
| 619 |
|
| 620 |
def _hexstring_to_array(space, s): |
| 621 |
data = [] |
| 622 |
length = len(s) |
| 623 |
i = 0 |
| 624 |
while True: |
| 625 |
while i < length and s[i].isspace(): |
| 626 |
i += 1 |
| 627 |
if i >= length: |
| 628 |
break |
| 629 |
if i + 1 == length: |
| 630 |
raise oefmt(space.w_ValueError, NON_HEX_MSG, i) |
| 631 |
|
| 632 |
top = _hex_digit_to_int(s[i]) |
| 633 |
if top == -1: |
| 634 |
raise oefmt(space.w_ValueError, NON_HEX_MSG, i) |
| 635 |
bot = _hex_digit_to_int(s[i + 1]) |
| 636 |
if bot == -1: |
| 637 |
raise oefmt(space.w_ValueError, NON_HEX_MSG, i + 1) |
| 638 |
data.append(chr(top * 16 + bot)) |
| 639 |
i += 2 |
| 640 |
return data |
| 641 |
|
| 642 |
HEXDIGITS = "0123456789abcdef" |
| 643 |
PY_SIZE_T_MAX = intmask(2**(rffi.sizeof(rffi.SIZE_T)*8-1)-1) |
| 644 |
|
| 645 |
def unwrap_hex_sep_arguments(space, w_sep, w_bytes_per_sep): |
| 646 |
if w_sep is not None: |
| 647 |
if space.isinstance_w(w_sep, space.w_unicode): |
| 648 |
sep = space.text_w(w_sep) |
| 649 |
elif space.isinstance_w(w_sep, space.w_bytes): |
| 650 |
sep = space.bytes_w(w_sep) |
| 651 |
else: |
| 652 |
raise oefmt(space.w_TypeError, "sep must be str of bytes") |
| 653 |
if w_bytes_per_sep is None: |
| 654 |
bytes_per_sep = 1 |
| 655 |
else: |
| 656 |
bytes_per_sep = space.int_w(w_bytes_per_sep) |
| 657 |
else: |
| 658 |
sep = None |
| 659 |
bytes_per_sep = 0 |
| 660 |
return sep, bytes_per_sep |
| 661 |
|
| 662 |
|
| 663 |
@specialize.arg(5) |
| 664 |
def _array_to_hexstring(space, buf, start, step, length, rawaccess=False, sep=None, bytes_per_sep=0): |
| 665 |
from rpython.rlib.rutf8 import check_ascii, CheckError |
| 666 |
if sep is not None: |
| 667 |
try: |
| 668 |
check_ascii(sep) |
| 669 |
except CheckError: |
| 670 |
raise oefmt(space.w_ValueError, "sep must be ASCII.") |
| 671 |
if len(sep) != 1: |
| 672 |
raise oefmt(space.w_ValueError, "sep must be length 1.") |
| 673 |
else: |
| 674 |
bytes_per_sep = 0 |
| 675 |
hexstring = StringBuilder(length*2) |
| 676 |
|
| 677 |
if length > PY_SIZE_T_MAX/2: |
| 678 |
raise OperationError(space.w_MemoryError, space.w_None) |
| 679 |
|
| 680 |
if bytes_per_sep == 1: |
| 681 |
bytes_per_sep_prefix = 1 |
| 682 |
|
| 683 |
elif bytes_per_sep > 1: |
| 684 |
bytes_per_sep_prefix = length % bytes_per_sep |
| 685 |
if bytes_per_sep_prefix == 0: |
| 686 |
bytes_per_sep_prefix = bytes_per_sep |
| 687 |
elif bytes_per_sep < 0: |
| 688 |
bytes_per_sep_prefix = -bytes_per_sep |
| 689 |
bytes_per_sep = -bytes_per_sep |
| 690 |
else: |
| 691 |
assert bytes_per_sep == 0 |
| 692 |
bytes_per_sep_prefix = -1 |
| 693 |
|
| 694 |
sep_counter = bytes_per_sep_prefix |
| 695 |
|
| 696 |
stepped = 0 |
| 697 |
i = start |
| 698 |
while stepped < length: |
| 699 |
if rawaccess: |
| 700 |
byte = ord(buf[i]) |
| 701 |
else: |
| 702 |
byte = ord(buf.getitem(i)) |
| 703 |
c = (byte >> 4 & 0xf) |
| 704 |
hexstring.append(HEXDIGITS[c]) |
| 705 |
c = (byte & 0xf) |
| 706 |
hexstring.append(HEXDIGITS[c]) |
| 707 |
i += step |
| 708 |
stepped += 1 |
| 709 |
sep_counter -= 1 |
| 710 |
if sep_counter == 0 and sep is not None and stepped != length: |
| 711 |
hexstring.append(sep) |
| 712 |
sep_counter = bytes_per_sep |
| 713 |
|
| 714 |
s = hexstring.build() |
| 715 |
return space.newtext(s, len(s)) |
| 716 |
|
| 717 |
class BytearrayDocstrings: |
| 718 |
"""bytearray(iterable_of_ints) -> bytearray |
| 719 |
bytearray(string, encoding[, errors]) -> bytearray |
| 720 |
bytearray(bytes_or_bytearray) -> mutable copy of bytes_or_bytearray |
| 721 |
bytearray(memory_view) -> bytearray |
| 722 |
|
| 723 |
Construct an mutable bytearray object from: |
| 724 |
- an iterable yielding integers in range(256) |
| 725 |
- a text string encoded using the specified encoding |
| 726 |
- a bytes or a bytearray object |
| 727 |
- any object implementing the buffer API. |
| 728 |
|
| 729 |
bytearray(int) -> bytearray. |
| 730 |
|
| 731 |
Construct a zero-initialized bytearray of the given length. |
| 732 |
|
| 733 |
""" |
| 734 |
|
| 735 |
def __add__(): |
| 736 |
"""x.__add__(y) <==> x+y""" |
| 737 |
|
| 738 |
def __alloc__(): |
| 739 |
"""B.__alloc__() -> int |
| 740 |
|
| 741 |
CPython compatibility: return len(B) + 1. |
| 742 |
(The allocated size might be bigger, but getting it is |
| 743 |
involved and may create pointless compatibility troubles.) |
| 744 |
""" |
| 745 |
|
| 746 |
def __contains__(): |
| 747 |
"""x.__contains__(y) <==> y in x""" |
| 748 |
|
| 749 |
def __delitem__(): |
| 750 |
"""x.__delitem__(y) <==> del x[y]""" |
| 751 |
|
| 752 |
def __eq__(): |
| 753 |
"""x.__eq__(y) <==> x==y""" |
| 754 |
|
| 755 |
def __ge__(): |
| 756 |
"""x.__ge__(y) <==> x>=y""" |
| 757 |
|
| 758 |
def __getattribute__(): |
| 759 |
"""x.__getattribute__('name') <==> x.name""" |
| 760 |
|
| 761 |
def __getitem__(): |
| 762 |
"""x.__getitem__(y) <==> x[y]""" |
| 763 |
|
| 764 |
def __gt__(): |
| 765 |
"""x.__gt__(y) <==> x>y""" |
| 766 |
|
| 767 |
def __iadd__(): |
| 768 |
"""x.__iadd__(y) <==> x+=y""" |
| 769 |
|
| 770 |
def __imul__(): |
| 771 |
"""x.__imul__(y) <==> x*=y""" |
| 772 |
|
| 773 |
def __init__(): |
| 774 |
"""Initialize self. See help(type(self)) for accurate signature.""" |
| 775 |
|
| 776 |
def __iter__(): |
| 777 |
"""x.__iter__() <==> iter(x)""" |
| 778 |
|
| 779 |
def __le__(): |
| 780 |
"""x.__le__(y) <==> x<=y""" |
| 781 |
|
| 782 |
def __len__(): |
| 783 |
"""x.__len__() <==> len(x)""" |
| 784 |
|
| 785 |
def __lt__(): |
| 786 |
"""x.__lt__(y) <==> x<y""" |
| 787 |
|
| 788 |
def __mul__(): |
| 789 |
"""x.__mul__(n) <==> x*n""" |
| 790 |
|
| 791 |
def __mod__(): |
| 792 |
"""Return self%value.""" |
| 793 |
|
| 794 |
def __rmod__(): |
| 795 |
"""Return value%self.""" |
| 796 |
|
| 797 |
def __ne__(): |
| 798 |
"""x.__ne__(y) <==> x!=y""" |
| 799 |
|
| 800 |
def __reduce__(): |
| 801 |
"""Return state information for pickling.""" |
| 802 |
|
| 803 |
def __repr__(): |
| 804 |
"""x.__repr__() <==> repr(x)""" |
| 805 |
|
| 806 |
def __rmul__(): |
| 807 |
"""x.__rmul__(n) <==> n*x""" |
| 808 |
|
| 809 |
def __setitem__(): |
| 810 |
"""x.__setitem__(i, y) <==> x[i]=y""" |
| 811 |
|
| 812 |
def __sizeof__(): |
| 813 |
"""B.__sizeof__() -> int |
| 814 |
|
| 815 |
Returns the size of B in memory, in bytes |
| 816 |
""" |
| 817 |
|
| 818 |
def __str__(): |
| 819 |
"""x.__str__() <==> str(x)""" |
| 820 |
|
| 821 |
def append(): |
| 822 |
"""B.append(int) -> None |
| 823 |
|
| 824 |
Append a single item to the end of B. |
| 825 |
""" |
| 826 |
|
| 827 |
def capitalize(): |
| 828 |
"""B.capitalize() -> copy of B |
| 829 |
|
| 830 |
Return a copy of B with only its first character capitalized (ASCII) |
| 831 |
and the rest lower-cased. |
| 832 |
""" |
| 833 |
|
| 834 |
def center(): |
| 835 |
"""B.center(width[, fillchar]) -> copy of B |
| 836 |
|
| 837 |
Return B centered in a string of length width. Padding is |
| 838 |
done using the specified fill character (default is a space). |
| 839 |
""" |
| 840 |
|
| 841 |
def clear(): |
| 842 |
"""B.clear() -> None |
| 843 |
|
| 844 |
Remove all items from B. |
| 845 |
""" |
| 846 |
|
| 847 |
def copy(): |
| 848 |
"""B.copy() -> bytearray |
| 849 |
|
| 850 |
Return a copy of B. |
| 851 |
""" |
| 852 |
|
| 853 |
def count(): |
| 854 |
"""B.count(sub[, start[, end]]) -> int |
| 855 |
|
| 856 |
Return the number of non-overlapping occurrences of subsection sub in |
| 857 |
bytes B[start:end]. Optional arguments start and end are interpreted |
| 858 |
as in slice notation. |
| 859 |
""" |
| 860 |
|
| 861 |
def decode(): |
| 862 |
"""B.decode(encoding=None, errors='strict') -> unicode |
| 863 |
|
| 864 |
Decode B using the codec registered for encoding. encoding defaults to |
| 865 |
the default encoding. errors may be given to set a different error |
| 866 |
handling scheme. Default is 'strict' meaning that encoding errors |
| 867 |
raise a UnicodeDecodeError. Other possible values are 'ignore' and |
| 868 |
'replace' as well as any other name registered with |
| 869 |
codecs.register_error that is able to handle UnicodeDecodeErrors. |
| 870 |
""" |
| 871 |
|
| 872 |
def endswith(): |
| 873 |
"""B.endswith(suffix[, start[, end]]) -> bool |
| 874 |
|
| 875 |
Return True if B ends with the specified suffix, False otherwise. |
| 876 |
With optional start, test B beginning at that position. |
| 877 |
With optional end, stop comparing B at that position. |
| 878 |
suffix can also be a tuple of strings to try. |
| 879 |
""" |
| 880 |
|
| 881 |
def expandtabs(): |
| 882 |
"""B.expandtabs([tabsize]) -> copy of B |
| 883 |
|
| 884 |
Return a copy of B where all tab characters are expanded using spaces. |
| 885 |
If tabsize is not given, a tab size of 8 characters is assumed. |
| 886 |
""" |
| 887 |
|
| 888 |
def extend(): |
| 889 |
"""B.extend(iterable_of_ints) -> None |
| 890 |
|
| 891 |
Append all the elements from the iterator or sequence to the |
| 892 |
end of B. |
| 893 |
""" |
| 894 |
|
| 895 |
def find(): |
| 896 |
"""B.find(sub[, start[, end]]) -> int |
| 897 |
|
| 898 |
Return the lowest index in B where subsection sub is found, |
| 899 |
such that sub is contained within B[start,end]. Optional |
| 900 |
arguments start and end are interpreted as in slice notation. |
| 901 |
|
| 902 |
Return -1 on failure. |
| 903 |
""" |
| 904 |
|
| 905 |
def fromhex(): |
| 906 |
r"""bytearray.fromhex(string) -> bytearray (static method) |
| 907 |
|
| 908 |
Create a bytearray object from a string of hexadecimal numbers. |
| 909 |
Spaces between two numbers are accepted. |
| 910 |
Example: bytearray.fromhex('B9 01EF') -> bytearray(b'\xb9\x01\xef'). |
| 911 |
""" |
| 912 |
|
| 913 |
def index(): |
| 914 |
"""B.index(sub[, start[, end]]) -> int |
| 915 |
|
| 916 |
Like B.find() but raise ValueError when the subsection is not found. |
| 917 |
""" |
| 918 |
|
| 919 |
def insert(): |
| 920 |
"""B.insert(index, int) -> None |
| 921 |
|
| 922 |
Insert a single item into the bytearray before the given index. |
| 923 |
""" |
| 924 |
|
| 925 |
def isalnum(): |
| 926 |
"""B.isalnum() -> bool |
| 927 |
|
| 928 |
Return True if all characters in B are alphanumeric |
| 929 |
and there is at least one character in B, False otherwise. |
| 930 |
""" |
| 931 |
|
| 932 |
def isalpha(): |
| 933 |
"""B.isalpha() -> bool |
| 934 |
|
| 935 |
Return True if all characters in B are alphabetic |
| 936 |
and there is at least one character in B, False otherwise. |
| 937 |
""" |
| 938 |
|
| 939 |
def isascii(): |
| 940 |
"""B.isascii() -> bool |
| 941 |
|
| 942 |
Return true if the string is empty or all characters in the string are ASCII, false otherwise. |
| 943 |
ASCII characters have code points in the range U+0000-U+007F.""" |
| 944 |
|
| 945 |
def isdigit(): |
| 946 |
"""B.isdigit() -> bool |
| 947 |
|
| 948 |
Return True if all characters in B are digits |
| 949 |
and there is at least one character in B, False otherwise. |
| 950 |
""" |
| 951 |
|
| 952 |
def islower(): |
| 953 |
"""B.islower() -> bool |
| 954 |
|
| 955 |
Return True if all cased characters in B are lowercase and there is |
| 956 |
at least one cased character in B, False otherwise. |
| 957 |
""" |
| 958 |
|
| 959 |
def isspace(): |
| 960 |
"""B.isspace() -> bool |
| 961 |
|
| 962 |
Return True if all characters in B are whitespace |
| 963 |
and there is at least one character in B, False otherwise. |
| 964 |
""" |
| 965 |
|
| 966 |
def istitle(): |
| 967 |
"""B.istitle() -> bool |
| 968 |
|
| 969 |
Return True if B is a titlecased string and there is at least one |
| 970 |
character in B, i.e. uppercase characters may only follow uncased |
| 971 |
characters and lowercase characters only cased ones. Return False |
| 972 |
otherwise. |
| 973 |
""" |
| 974 |
|
| 975 |
def isupper(): |
| 976 |
"""B.isupper() -> bool |
| 977 |
|
| 978 |
Return True if all cased characters in B are uppercase and there is |
| 979 |
at least one cased character in B, False otherwise. |
| 980 |
""" |
| 981 |
|
| 982 |
def join(): |
| 983 |
"""B.join(iterable_of_bytes) -> bytearray |
| 984 |
|
| 985 |
Concatenate any number of str/bytearray objects, with B |
| 986 |
in between each pair, and return the result as a new bytearray. |
| 987 |
""" |
| 988 |
|
| 989 |
def ljust(): |
| 990 |
"""B.ljust(width[, fillchar]) -> copy of B |
| 991 |
|
| 992 |
Return B left justified in a string of length width. Padding is |
| 993 |
done using the specified fill character (default is a space). |
| 994 |
""" |
| 995 |
|
| 996 |
def lower(): |
| 997 |
"""B.lower() -> copy of B |
| 998 |
|
| 999 |
Return a copy of B with all ASCII characters converted to lowercase. |
| 1000 |
""" |
| 1001 |
|
| 1002 |
def lstrip(): |
| 1003 |
"""B.lstrip([bytes]) -> bytearray |
| 1004 |
|
| 1005 |
Strip leading bytes contained in the argument |
| 1006 |
and return the result as a new bytearray. |
| 1007 |
If the argument is omitted, strip leading ASCII whitespace. |
| 1008 |
""" |
| 1009 |
|
| 1010 |
def partition(): |
| 1011 |
"""B.partition(sep) -> (head, sep, tail) |
| 1012 |
|
| 1013 |
Search for the separator sep in B, and return the part before it, |
| 1014 |
the separator itself, and the part after it. If the separator is not |
| 1015 |
found, returns B and two empty bytearray objects. |
| 1016 |
""" |
| 1017 |
|
| 1018 |
def pop(): |
| 1019 |
"""B.pop([index]) -> int |
| 1020 |
|
| 1021 |
Remove and return a single item from B. If no index |
| 1022 |
argument is given, will pop the last value. |
| 1023 |
""" |
| 1024 |
|
| 1025 |
def remove(): |
| 1026 |
"""B.remove(int) -> None |
| 1027 |
|
| 1028 |
Remove the first occurrence of a value in B. |
| 1029 |
""" |
| 1030 |
|
| 1031 |
def replace(): |
| 1032 |
"""B.replace(old, new[, count]) -> bytearray |
| 1033 |
|
| 1034 |
Return a copy of B with all occurrences of subsection |
| 1035 |
old replaced by new. If the optional argument count is |
| 1036 |
given, only the first count occurrences are replaced. |
| 1037 |
""" |
| 1038 |
|
| 1039 |
def reverse(): |
| 1040 |
"""B.reverse() -> None |
| 1041 |
|
| 1042 |
Reverse the order of the values in B in place. |
| 1043 |
""" |
| 1044 |
|
| 1045 |
def rfind(): |
| 1046 |
"""B.rfind(sub[, start[, end]]) -> int |
| 1047 |
|
| 1048 |
Return the highest index in B where subsection sub is found, |
| 1049 |
such that sub is contained within B[start,end]. Optional |
| 1050 |
arguments start and end are interpreted as in slice notation. |
| 1051 |
|
| 1052 |
Return -1 on failure. |
| 1053 |
""" |
| 1054 |
|
| 1055 |
def rindex(): |
| 1056 |
"""B.rindex(sub[, start[, end]]) -> int |
| 1057 |
|
| 1058 |
Like B.rfind() but raise ValueError when the subsection is not found. |
| 1059 |
""" |
| 1060 |
|
| 1061 |
def rjust(): |
| 1062 |
"""B.rjust(width[, fillchar]) -> copy of B |
| 1063 |
|
| 1064 |
Return B right justified in a string of length width. Padding is |
| 1065 |
done using the specified fill character (default is a space) |
| 1066 |
""" |
| 1067 |
|
| 1068 |
def rpartition(): |
| 1069 |
"""B.rpartition(sep) -> (head, sep, tail) |
| 1070 |
|
| 1071 |
Search for the separator sep in B, starting at the end of B, |
| 1072 |
and return the part before it, the separator itself, and the |
| 1073 |
part after it. If the separator is not found, returns two empty |
| 1074 |
bytearray objects and B. |
| 1075 |
""" |
| 1076 |
|
| 1077 |
def rsplit(): |
| 1078 |
"""B.rsplit(sep=None, maxsplit=-1) -> list of bytearrays |
| 1079 |
|
| 1080 |
Return a list of the sections in B, using sep as the delimiter, |
| 1081 |
starting at the end of B and working to the front. |
| 1082 |
If sep is not given, B is split on ASCII whitespace characters |
| 1083 |
(space, tab, return, newline, formfeed, vertical tab). |
| 1084 |
If maxsplit is given, at most maxsplit splits are done. |
| 1085 |
""" |
| 1086 |
|
| 1087 |
def rstrip(): |
| 1088 |
"""B.rstrip([bytes]) -> bytearray |
| 1089 |
|
| 1090 |
Strip trailing bytes contained in the argument |
| 1091 |
and return the result as a new bytearray. |
| 1092 |
If the argument is omitted, strip trailing ASCII whitespace. |
| 1093 |
""" |
| 1094 |
|
| 1095 |
def split(): |
| 1096 |
"""B.split(sep=None, maxsplit=-1) -> list of bytearrays |
| 1097 |
|
| 1098 |
Return a list of the sections in B, using sep as the delimiter. |
| 1099 |
If sep is not given, B is split on ASCII whitespace characters |
| 1100 |
(space, tab, return, newline, formfeed, vertical tab). |
| 1101 |
If maxsplit is given, at most maxsplit splits are done. |
| 1102 |
""" |
| 1103 |
|
| 1104 |
def splitlines(): |
| 1105 |
"""B.splitlines(keepends=False) -> list of lines |
| 1106 |
|
| 1107 |
Return a list of the lines in B, breaking at line boundaries. |
| 1108 |
Line breaks are not included in the resulting list unless keepends |
| 1109 |
is given and true. |
| 1110 |
""" |
| 1111 |
|
| 1112 |
def startswith(): |
| 1113 |
"""B.startswith(prefix[, start[, end]]) -> bool |
| 1114 |
|
| 1115 |
Return True if B starts with the specified prefix, False otherwise. |
| 1116 |
With optional start, test B beginning at that position. |
| 1117 |
With optional end, stop comparing B at that position. |
| 1118 |
prefix can also be a tuple of strings to try. |
| 1119 |
""" |
| 1120 |
|
| 1121 |
def strip(): |
| 1122 |
"""B.strip([bytes]) -> bytearray |
| 1123 |
|
| 1124 |
Strip leading and trailing bytes contained in the argument |
| 1125 |
and return the result as a new bytearray. |
| 1126 |
If the argument is omitted, strip ASCII whitespace. |
| 1127 |
""" |
| 1128 |
|
| 1129 |
def swapcase(): |
| 1130 |
"""B.swapcase() -> copy of B |
| 1131 |
|
| 1132 |
Return a copy of B with uppercase ASCII characters converted |
| 1133 |
to lowercase ASCII and vice versa. |
| 1134 |
""" |
| 1135 |
|
| 1136 |
def title(): |
| 1137 |
"""B.title() -> copy of B |
| 1138 |
|
| 1139 |
Return a titlecased version of B, i.e. ASCII words start with uppercase |
| 1140 |
characters, all remaining cased characters have lowercase. |
| 1141 |
""" |
| 1142 |
|
| 1143 |
def translate(): |
| 1144 |
"""B.translate(table[, deletechars]) -> bytearray |
| 1145 |
|
| 1146 |
Return a copy of B, where all characters occurring in the |
| 1147 |
optional argument deletechars are removed, and the remaining |
| 1148 |
characters have been mapped through the given translation |
| 1149 |
table, which must be a bytes object of length 256. |
| 1150 |
""" |
| 1151 |
|
| 1152 |
def upper(): |
| 1153 |
"""B.upper() -> copy of B |
| 1154 |
|
| 1155 |
Return a copy of B with all ASCII characters converted to uppercase. |
| 1156 |
""" |
| 1157 |
|
| 1158 |
def zfill(): |
| 1159 |
"""B.zfill(width) -> copy of B |
| 1160 |
|
| 1161 |
Pad a numeric string B with zeros on the left, to fill a field |
| 1162 |
of the specified width. B is never truncated. |
| 1163 |
""" |
| 1164 |
|
| 1165 |
def hex(): |
| 1166 |
"""B.hex(...) -> unicode |
| 1167 |
|
| 1168 |
Create a string of hexadecimal numbers from a bytearray object. |
| 1169 |
|
| 1170 |
sep |
| 1171 |
An optional single character or byte to separate hex bytes. |
| 1172 |
bytes_per_sep |
| 1173 |
How many bytes between separators. Positive values count from the |
| 1174 |
right, negative values count from the left. |
| 1175 |
|
| 1176 |
Example: |
| 1177 |
>>> value = bytearray([0xb9, 0x01, 0xef]) |
| 1178 |
>>> value.hex() |
| 1179 |
'b901ef' |
| 1180 |
>>> value.hex(':') |
| 1181 |
'b9:01:ef' |
| 1182 |
>>> value.hex(':', 2) |
| 1183 |
'b9:01ef' |
| 1184 |
>>> value.hex(':', -2) |
| 1185 |
'b901:ef' |
| 1186 |
""" |
| 1187 |
|
| 1188 |
def removeprefix(): |
| 1189 |
"""Return a bytearray with the given prefix string removed if present. |
| 1190 |
|
| 1191 |
If the bytearray starts with the prefix string, return |
| 1192 |
bytearray[len(prefix):]. Otherwise, return a copy of the original |
| 1193 |
bytearray.""" |
| 1194 |
|
| 1195 |
def removesuffix(): |
| 1196 |
"""Return a bytearray with the given suffix string removed if present. |
| 1197 |
|
| 1198 |
If the bytearray ends with the suffix string and that suffix is not |
| 1199 |
empty, return bytearray[:-len(suffix)]. Otherwise, return a copy of |
| 1200 |
the original bytearray.""" |
| 1201 |
|
| 1202 |
|
| 1203 |
W_BytearrayObject.typedef = TypeDef( |
| 1204 |
"bytearray", None, None, "read-write", |
| 1205 |
__doc__ = BytearrayDocstrings.__doc__, |
| 1206 |
__new__ = interp2app(W_BytearrayObject.descr_new), |
| 1207 |
__hash__ = None, |
| 1208 |
__reduce__ = interp2app(W_BytearrayObject.descr_reduce, |
| 1209 |
doc=BytearrayDocstrings.__reduce__.__doc__), |
| 1210 |
fromhex = interp2app(W_BytearrayObject.descr_fromhex, as_classmethod=True, |
| 1211 |
doc=BytearrayDocstrings.fromhex.__doc__), |
| 1212 |
maketrans = interp2app(W_BytearrayObject.descr_maketrans, |
| 1213 |
as_classmethod=True), |
| 1214 |
|
| 1215 |
__repr__ = interp2app(W_BytearrayObject.descr_repr, |
| 1216 |
doc=BytearrayDocstrings.__repr__.__doc__), |
| 1217 |
__str__ = interp2app(W_BytearrayObject.descr_str, |
| 1218 |
doc=BytearrayDocstrings.__str__.__doc__), |
| 1219 |
|
| 1220 |
__eq__ = interp2app(W_BytearrayObject.descr_eq, |
| 1221 |
doc=BytearrayDocstrings.__eq__.__doc__), |
| 1222 |
__ne__ = interp2app(W_BytearrayObject.descr_ne, |
| 1223 |
doc=BytearrayDocstrings.__ne__.__doc__), |
| 1224 |
__lt__ = interp2app(W_BytearrayObject.descr_lt, |
| 1225 |
doc=BytearrayDocstrings.__lt__.__doc__), |
| 1226 |
__le__ = interp2app(W_BytearrayObject.descr_le, |
| 1227 |
doc=BytearrayDocstrings.__le__.__doc__), |
| 1228 |
__gt__ = interp2app(W_BytearrayObject.descr_gt, |
| 1229 |
doc=BytearrayDocstrings.__gt__.__doc__), |
| 1230 |
__ge__ = interp2app(W_BytearrayObject.descr_ge, |
| 1231 |
doc=BytearrayDocstrings.__ge__.__doc__), |
| 1232 |
|
| 1233 |
__iter__ = interp2app(W_BytearrayObject.descr_iter, |
| 1234 |
doc=BytearrayDocstrings.__iter__.__doc__), |
| 1235 |
__len__ = interp2app(W_BytearrayObject.descr_len, |
| 1236 |
doc=BytearrayDocstrings.__len__.__doc__), |
| 1237 |
__contains__ = interp2app(W_BytearrayObject.descr_contains, |
| 1238 |
doc=BytearrayDocstrings.__contains__.__doc__), |
| 1239 |
|
| 1240 |
__add__ = interp2app(W_BytearrayObject.descr_add, |
| 1241 |
doc=BytearrayDocstrings.__add__.__doc__), |
| 1242 |
__mul__ = interp2app(W_BytearrayObject.descr_mul, |
| 1243 |
doc=BytearrayDocstrings.__mul__.__doc__), |
| 1244 |
__rmul__ = interp2app(W_BytearrayObject.descr_mul, |
| 1245 |
doc=BytearrayDocstrings.__rmul__.__doc__), |
| 1246 |
|
| 1247 |
__getitem__ = interp2app(W_BytearrayObject.descr_getitem, |
| 1248 |
doc=BytearrayDocstrings.__getitem__.__doc__), |
| 1249 |
__release_buffer__ = interp2app(W_BytearrayObject.descr_releasebuffer), |
| 1250 |
capitalize = interp2app(W_BytearrayObject.descr_capitalize, |
| 1251 |
doc=BytearrayDocstrings.capitalize.__doc__), |
| 1252 |
center = interp2app(W_BytearrayObject.descr_center, |
| 1253 |
doc=BytearrayDocstrings.center.__doc__), |
| 1254 |
count = interp2app(W_BytearrayObject.descr_count, |
| 1255 |
doc=BytearrayDocstrings.count.__doc__), |
| 1256 |
decode = interp2app(W_BytearrayObject.descr_decode, |
| 1257 |
doc=BytearrayDocstrings.decode.__doc__), |
| 1258 |
expandtabs = interp2app(W_BytearrayObject.descr_expandtabs, |
| 1259 |
doc=BytearrayDocstrings.expandtabs.__doc__), |
| 1260 |
find = interp2app(W_BytearrayObject.descr_find, |
| 1261 |
doc=BytearrayDocstrings.find.__doc__), |
| 1262 |
rfind = interp2app(W_BytearrayObject.descr_rfind, |
| 1263 |
doc=BytearrayDocstrings.rfind.__doc__), |
| 1264 |
index = interp2app(W_BytearrayObject.descr_index, |
| 1265 |
doc=BytearrayDocstrings.index.__doc__), |
| 1266 |
rindex = interp2app(W_BytearrayObject.descr_rindex, |
| 1267 |
doc=BytearrayDocstrings.rindex.__doc__), |
| 1268 |
isalnum = interp2app(W_BytearrayObject.descr_isalnum, |
| 1269 |
doc=BytearrayDocstrings.isalnum.__doc__), |
| 1270 |
isalpha = interp2app(W_BytearrayObject.descr_isalpha, |
| 1271 |
doc=BytearrayDocstrings.isalpha.__doc__), |
| 1272 |
isascii = interp2app(W_BytearrayObject.descr_isascii, |
| 1273 |
doc=BytearrayDocstrings.isascii.__doc__), |
| 1274 |
isdigit = interp2app(W_BytearrayObject.descr_isdigit, |
| 1275 |
doc=BytearrayDocstrings.isdigit.__doc__), |
| 1276 |
islower = interp2app(W_BytearrayObject.descr_islower, |
| 1277 |
doc=BytearrayDocstrings.islower.__doc__), |
| 1278 |
isspace = interp2app(W_BytearrayObject.descr_isspace, |
| 1279 |
doc=BytearrayDocstrings.isspace.__doc__), |
| 1280 |
istitle = interp2app(W_BytearrayObject.descr_istitle, |
| 1281 |
doc=BytearrayDocstrings.istitle.__doc__), |
| 1282 |
isupper = interp2app(W_BytearrayObject.descr_isupper, |
| 1283 |
doc=BytearrayDocstrings.isupper.__doc__), |
| 1284 |
join = interp2app(W_BytearrayObject.descr_join, |
| 1285 |
doc=BytearrayDocstrings.join.__doc__), |
| 1286 |
ljust = interp2app(W_BytearrayObject.descr_ljust, |
| 1287 |
doc=BytearrayDocstrings.ljust.__doc__), |
| 1288 |
rjust = interp2app(W_BytearrayObject.descr_rjust, |
| 1289 |
doc=BytearrayDocstrings.rjust.__doc__), |
| 1290 |
lower = interp2app(W_BytearrayObject.descr_lower, |
| 1291 |
doc=BytearrayDocstrings.lower.__doc__), |
| 1292 |
partition = interp2app(W_BytearrayObject.descr_partition, |
| 1293 |
doc=BytearrayDocstrings.partition.__doc__), |
| 1294 |
rpartition = interp2app(W_BytearrayObject.descr_rpartition, |
| 1295 |
doc=BytearrayDocstrings.rpartition.__doc__), |
| 1296 |
replace = interp2app(W_BytearrayObject.descr_replace, |
| 1297 |
doc=BytearrayDocstrings.replace.__doc__), |
| 1298 |
split = interp2app(W_BytearrayObject.descr_split, |
| 1299 |
doc=BytearrayDocstrings.split.__doc__), |
| 1300 |
rsplit = interp2app(W_BytearrayObject.descr_rsplit, |
| 1301 |
doc=BytearrayDocstrings.rsplit.__doc__), |
| 1302 |
splitlines = interp2app(W_BytearrayObject.descr_splitlines, |
| 1303 |
doc=BytearrayDocstrings.splitlines.__doc__), |
| 1304 |
startswith = interp2app(W_BytearrayObject.descr_startswith, |
| 1305 |
doc=BytearrayDocstrings.startswith.__doc__), |
| 1306 |
endswith = interp2app(W_BytearrayObject.descr_endswith, |
| 1307 |
doc=BytearrayDocstrings.endswith.__doc__), |
| 1308 |
strip = interp2app(W_BytearrayObject.descr_strip, |
| 1309 |
doc=BytearrayDocstrings.strip.__doc__), |
| 1310 |
lstrip = interp2app(W_BytearrayObject.descr_lstrip, |
| 1311 |
doc=BytearrayDocstrings.lstrip.__doc__), |
| 1312 |
rstrip = interp2app(W_BytearrayObject.descr_rstrip, |
| 1313 |
doc=BytearrayDocstrings.rstrip.__doc__), |
| 1314 |
swapcase = interp2app(W_BytearrayObject.descr_swapcase, |
| 1315 |
doc=BytearrayDocstrings.swapcase.__doc__), |
| 1316 |
title = interp2app(W_BytearrayObject.descr_title, |
| 1317 |
doc=BytearrayDocstrings.title.__doc__), |
| 1318 |
translate = interp2app(W_BytearrayObject.descr_translate, |
| 1319 |
doc=BytearrayDocstrings.translate.__doc__), |
| 1320 |
upper = interp2app(W_BytearrayObject.descr_upper, |
| 1321 |
doc=BytearrayDocstrings.upper.__doc__), |
| 1322 |
zfill = interp2app(W_BytearrayObject.descr_zfill, |
| 1323 |
doc=BytearrayDocstrings.zfill.__doc__), |
| 1324 |
|
| 1325 |
__init__ = interp2app(W_BytearrayObject.descr_init, |
| 1326 |
doc=BytearrayDocstrings.__init__.__doc__), |
| 1327 |
|
| 1328 |
__iadd__ = interp2app(W_BytearrayObject.descr_inplace_add, |
| 1329 |
doc=BytearrayDocstrings.__iadd__.__doc__), |
| 1330 |
__imul__ = interp2app(W_BytearrayObject.descr_inplace_mul, |
| 1331 |
doc=BytearrayDocstrings.__imul__.__doc__), |
| 1332 |
__setitem__ = interp2app(W_BytearrayObject.descr_setitem, |
| 1333 |
doc=BytearrayDocstrings.__setitem__.__doc__), |
| 1334 |
__delitem__ = interp2app(W_BytearrayObject.descr_delitem, |
| 1335 |
doc=BytearrayDocstrings.__delitem__.__doc__), |
| 1336 |
__mod__ = interp2app(W_BytearrayObject.descr_mod, |
| 1337 |
doc=BytearrayDocstrings.__mod__.__doc__), |
| 1338 |
__rmod__ = interp2app(W_BytearrayObject.descr_rmod, |
| 1339 |
doc=BytearrayDocstrings.__rmod__.__doc__), |
| 1340 |
|
| 1341 |
append = interp2app(W_BytearrayObject.descr_append, |
| 1342 |
doc=BytearrayDocstrings.append.__doc__), |
| 1343 |
extend = interp2app(W_BytearrayObject.descr_extend, |
| 1344 |
doc=BytearrayDocstrings.extend.__doc__), |
| 1345 |
insert = interp2app(W_BytearrayObject.descr_insert, |
| 1346 |
doc=BytearrayDocstrings.insert.__doc__), |
| 1347 |
pop = interp2app(W_BytearrayObject.descr_pop, |
| 1348 |
doc=BytearrayDocstrings.pop.__doc__), |
| 1349 |
remove = interp2app(W_BytearrayObject.descr_remove, |
| 1350 |
doc=BytearrayDocstrings.remove.__doc__), |
| 1351 |
reverse = interp2app(W_BytearrayObject.descr_reverse, |
| 1352 |
doc=BytearrayDocstrings.reverse.__doc__), |
| 1353 |
clear = interp2app(W_BytearrayObject.descr_clear, |
| 1354 |
doc=BytearrayDocstrings.clear.__doc__), |
| 1355 |
copy = interp2app(W_BytearrayObject.descr_copy, |
| 1356 |
doc=BytearrayDocstrings.copy.__doc__), |
| 1357 |
hex = interp2app(W_BytearrayObject.descr_hex, |
| 1358 |
doc=BytearrayDocstrings.hex.__doc__), |
| 1359 |
__alloc__ = interp2app(W_BytearrayObject.descr_alloc, |
| 1360 |
doc=BytearrayDocstrings.__alloc__.__doc__), |
| 1361 |
|
| 1362 |
removeprefix = interp2app(W_BytearrayObject.descr_removeprefix, |
| 1363 |
doc=BytearrayDocstrings.removeprefix.__doc__), |
| 1364 |
|
| 1365 |
removesuffix = interp2app(W_BytearrayObject.descr_removesuffix, |
| 1366 |
doc=BytearrayDocstrings.removesuffix.__doc__), |
| 1367 |
) |
| 1368 |
W_BytearrayObject.typedef.flag_sequence_bug_compat = True |
| 1369 |
|
| 1370 |
|
| 1371 |
|
| 1372 |
def _delitem_slice_helper(space, items, start, step, slicelength): |
| 1373 |
if slicelength == 0: |
| 1374 |
return |
| 1375 |
|
| 1376 |
if step < 0: |
| 1377 |
start = start + step * (slicelength-1) |
| 1378 |
step = -step |
| 1379 |
|
| 1380 |
if step == 1: |
| 1381 |
assert start >= 0 |
| 1382 |
if slicelength > 0: |
| 1383 |
del items[start:start+slicelength] |
| 1384 |
else: |
| 1385 |
n = len(items) |
| 1386 |
i = start |
| 1387 |
|
| 1388 |
for discard in range(1, slicelength): |
| 1389 |
j = i+1 |
| 1390 |
i += step |
| 1391 |
while j < i: |
| 1392 |
items[j-discard] = items[j] |
| 1393 |
j += 1 |
| 1394 |
|
| 1395 |
j = i+1 |
| 1396 |
while j < n: |
| 1397 |
items[j-slicelength] = items[j] |
| 1398 |
j += 1 |
| 1399 |
start = n - slicelength |
| 1400 |
assert start >= 0 |
| 1401 |
del items[start:] |
| 1402 |
|
| 1403 |
|
| 1404 |
def _setitem_slice_helper(space, items, start, step, slicelength, sequence2, |
| 1405 |
empty_elem): |
| 1406 |
assert slicelength >= 0 |
| 1407 |
oldsize = len(items) |
| 1408 |
len2 = len(sequence2) |
| 1409 |
if step == 1: |
| 1410 |
delta = slicelength - len2 |
| 1411 |
if delta < 0: |
| 1412 |
delta = -delta |
| 1413 |
newsize = oldsize + delta |
| 1414 |
|
| 1415 |
items += [empty_elem] * delta |
| 1416 |
lim = start+len2 |
| 1417 |
i = newsize - 1 |
| 1418 |
while i >= lim: |
| 1419 |
items[i] = items[i-delta] |
| 1420 |
i -= 1 |
| 1421 |
elif delta == 0: |
| 1422 |
pass |
| 1423 |
else: |
| 1424 |
assert start >= 0 |
| 1425 |
del items[start:start+delta] |
| 1426 |
elif len2 != slicelength: |
| 1427 |
raise oefmt(space.w_ValueError, |
| 1428 |
"attempt to assign sequence of size %d to extended slice " |
| 1429 |
"of size %d", len2, slicelength) |
| 1430 |
|
| 1431 |
for i in range(len2): |
| 1432 |
items[start] = sequence2[i] |
| 1433 |
start += step |
| 1434 |
|
| 1435 |
|
| 1436 |
@GCBuffer.decorate |
| 1437 |
class BytearrayBuffer(GCBuffer): |
| 1438 |
_immutable_ = True |
| 1439 |
|
| 1440 |
def __init__(self, ba, readonly=False): |
| 1441 |
self.ba = ba |
| 1442 |
self.readonly = readonly |
| 1443 |
|
| 1444 |
def getlength(self): |
| 1445 |
return self.ba._len() |
| 1446 |
|
| 1447 |
def getitem(self, index): |
| 1448 |
ba = self.ba |
| 1449 |
return ba._data[ba._offset + index] |
| 1450 |
|
| 1451 |
def setitem(self, index, char): |
| 1452 |
ba = self.ba |
| 1453 |
ba._data[ba._offset + index] = char |
| 1454 |
|
| 1455 |
def getslice(self, start, step, size): |
| 1456 |
if size == 0: |
| 1457 |
return "" |
| 1458 |
if step == 1: |
| 1459 |
assert start >= 0 |
| 1460 |
assert size >= 0 |
| 1461 |
ba = self.ba |
| 1462 |
start += ba._offset |
| 1463 |
data = ba._data |
| 1464 |
if start != 0 or size != len(data): |
| 1465 |
data = data[start:start+size] |
| 1466 |
return "".join(data) |
| 1467 |
return GCBuffer.getslice(self, start, step, size) |
| 1468 |
|
| 1469 |
def setslice(self, start, string): |
| 1470 |
|
| 1471 |
ba = self.ba |
| 1472 |
start += ba._offset |
| 1473 |
for i in range(len(string)): |
| 1474 |
ba._data[start + i] = string[i] |
| 1475 |
|
| 1476 |
def get_raw_address(self): |
| 1477 |
ba = self.ba |
| 1478 |
p = nonmoving_raw_ptr_for_resizable_list(ba._data) |
| 1479 |
p = rffi.ptradd(p, ba._offset) |
| 1480 |
return p |
| 1481 |
|
| 1482 |
@staticmethod |
| 1483 |
def _get_gc_data_offset(): |
| 1484 |
return get_gc_data_offset_for_list_of_chars() |
| 1485 |
|
| 1486 |
def _get_gc_data_extra_offset(self): |
| 1487 |
return self.ba._offset |
| 1488 |
|
| 1489 |
def _get_gc_data(self): |
| 1490 |
return get_gc_data_for_list_of_chars(self.ba._data) |
| 1491 |
|
| 1492 |
|
| 1493 |
@specialize.argtype(1) |
| 1494 |
def _memcmp(selfvalue, buffer, length): |
| 1495 |
|
| 1496 |
for i in range(length): |
| 1497 |
if selfvalue[i] < buffer[i]: |
| 1498 |
return -1 |
| 1499 |
if selfvalue[i] > buffer[i]: |
| 1500 |
return 1 |
| 1501 |
return 0 |
| 1502 |
|
| 1503 |
def _tweak_for_tests(w_bytearray): |
| 1504 |
"Patched in test_bytearray.py" |
| 1505 |
|
| 1506 |
def _shrink_after_delete_from_start(w_bytearray): |
| 1507 |
w_bytearray.getdata() |