Rename buffer -> bytearray.

This commit is contained in:
Guido van Rossum 2007-11-21 19:29:53 +00:00
parent 905a904723
commit 254348e201
31 changed files with 290 additions and 290 deletions

View File

@ -27,13 +27,13 @@ __all__ = [
]
bytes_buffer = (bytes, buffer) # Types acceptable as binary data
bytes_types = (bytes, bytearray) # Types acceptable as binary data
def _translate(s, altchars):
if not isinstance(s, bytes_buffer):
if not isinstance(s, bytes_types):
raise TypeError("expected bytes, not %s" % s.__class__.__name__)
translation = buffer(range(256))
translation = bytearray(range(256))
for k, v in altchars.items():
translation[ord(k)] = v[0]
return s.translate(translation)
@ -52,12 +52,12 @@ def b64encode(s, altchars=None):
The encoded byte string is returned.
"""
if not isinstance(s, bytes_buffer):
if not isinstance(s, bytes_types):
s = bytes(s, "ascii")
# Strip off the trailing newline
encoded = binascii.b2a_base64(s)[:-1]
if altchars is not None:
if not isinstance(altchars, bytes_buffer):
if not isinstance(altchars, bytes_types):
altchars = bytes(altchars, "ascii")
assert len(altchars) == 2, repr(altchars)
return _translate(encoded, {'+': altchars[0:1], '/': altchars[1:2]})
@ -75,10 +75,10 @@ def b64decode(s, altchars=None):
s were incorrectly padded or if there are non-alphabet characters
present in the string.
"""
if not isinstance(s, bytes_buffer):
if not isinstance(s, bytes_types):
s = bytes(s)
if altchars is not None:
if not isinstance(altchars, bytes_buffer):
if not isinstance(altchars, bytes_types):
altchars = bytes(altchars, "ascii")
assert len(altchars) == 2, repr(altchars)
s = _translate(s, {chr(altchars[0]): b'+', chr(altchars[1]): b'/'})
@ -147,7 +147,7 @@ def b32encode(s):
s is the byte string to encode. The encoded byte string is returned.
"""
if not isinstance(s, bytes_buffer):
if not isinstance(s, bytes_types):
s = bytes(s)
quanta, leftover = divmod(len(s), 5)
# Pad the last quantum with zero bits if necessary
@ -204,7 +204,7 @@ def b32decode(s, casefold=False, map01=None):
the input is incorrectly padded or if there are non-alphabet
characters present in the input.
"""
if not isinstance(s, bytes_buffer):
if not isinstance(s, bytes_types):
s = bytes(s)
quanta, leftover = divmod(len(s), 8)
if leftover:
@ -213,7 +213,7 @@ def b32decode(s, casefold=False, map01=None):
# False, or the character to map the digit 1 (one) to. It should be
# either L (el) or I (eye).
if map01:
if not isinstance(map01, bytes_buffer):
if not isinstance(map01, bytes_types):
map01 = bytes(map01)
assert len(map01) == 1, repr(map01)
s = _translate(s, {b'0': b'O', b'1': map01})
@ -283,7 +283,7 @@ def b16decode(s, casefold=False):
s were incorrectly padded or if there are non-alphabet characters
present in the string.
"""
if not isinstance(s, bytes_buffer):
if not isinstance(s, bytes_types):
s = bytes(s)
if casefold:
s = s.upper()
@ -330,7 +330,7 @@ def encodestring(s):
Argument and return value are bytes.
"""
if not isinstance(s, bytes_buffer):
if not isinstance(s, bytes_types):
raise TypeError("expected bytes, not %s" % s.__class__.__name__)
pieces = []
for i in range(0, len(s), MAXBINSIZE):
@ -344,7 +344,7 @@ def decodestring(s):
Argument and return value are bytes.
"""
if not isinstance(s, bytes_buffer):
if not isinstance(s, bytes_types):
raise TypeError("expected bytes, not %s" % s.__class__.__name__)
return binascii.a2b_base64(s)

View File

@ -163,7 +163,7 @@ class _Database(UserDict.DictMixin):
if not isinstance(key, bytes):
raise TypeError("keys must be bytes")
key = key.decode("latin-1") # hashable bytes
if not isinstance(val, (buffer, bytes)):
if not isinstance(val, (bytes, bytearray)):
raise TypeError("values must be byte strings")
if key not in self._index:
self._addkey(key, self._addval(val))

View File

@ -153,7 +153,7 @@ class Codec(codecs.Codec):
if not input:
return b'', 0
result = buffer()
result = bytearray()
labels = dots.split(input)
if labels and not labels[-1]:
trailing_dot = b'.'
@ -216,7 +216,7 @@ class IncrementalEncoder(codecs.BufferedIncrementalEncoder):
if labels:
trailing_dot = b'.'
result = buffer()
result = bytearray()
size = 0
for label in labels:
if size:

View File

@ -10,7 +10,7 @@ import codecs
def segregate(str):
"""3.1 Basic code point segregation"""
base = buffer()
base = bytearray()
extended = set()
for c in str:
if ord(c) < 128:
@ -78,7 +78,7 @@ def T(j, bias):
digits = b"abcdefghijklmnopqrstuvwxyz0123456789"
def generate_generalized_integer(N, bias):
"""3.3 Generalized variable-length integers"""
result = buffer()
result = bytearray()
j = 0
while 1:
t = T(j, bias)
@ -107,7 +107,7 @@ def adapt(delta, first, numchars):
def generate_integers(baselen, deltas):
"""3.4 Bias adaptation"""
# Punycode parameters: initial bias = 72, damp = 700, skew = 38
result = buffer()
result = bytearray()
bias = 72
for points, delta in enumerate(deltas):
s = generate_generalized_integer(delta, bias)

View File

@ -391,7 +391,7 @@ class IOBase(metaclass=abc.ABCMeta):
return 1
if limit is None:
limit = -1
res = buffer()
res = bytearray()
while limit < 0 or len(res) < limit:
b = self.read(nreadahead())
if not b:
@ -454,14 +454,14 @@ class RawIOBase(IOBase):
n = -1
if n < 0:
return self.readall()
b = buffer(n.__index__())
b = bytearray(n.__index__())
n = self.readinto(b)
del b[n:]
return bytes(b)
def readall(self):
"""readall() -> bytes. Read until EOF, using multiple read() call."""
res = buffer()
res = bytearray()
while True:
data = self.read(DEFAULT_BUFFER_SIZE)
if not data:
@ -655,7 +655,7 @@ class BytesIO(BufferedIOBase):
# XXX More docs
def __init__(self, initial_bytes=None):
buf = buffer()
buf = bytearray()
if initial_bytes is not None:
buf += initial_bytes
self._buffer = buf
@ -823,7 +823,7 @@ class BufferedWriter(_BufferedIOMixin):
self.max_buffer_size = (2*buffer_size
if max_buffer_size is None
else max_buffer_size)
self._write_buf = buffer()
self._write_buf = bytearray()
def write(self, b):
if self.closed:
@ -1276,7 +1276,7 @@ class TextIOWrapper(TextIOBase):
try:
decoder.setstate((b"", decoder_state))
n = 0
bb = buffer(1)
bb = bytearray(1)
for i, bb[0] in enumerate(readahead):
n += len(decoder.decode(bb))
if n >= needed:

View File

@ -39,7 +39,7 @@ __all__ = ["PickleError", "PicklingError", "UnpicklingError", "Pickler",
"Unpickler", "dump", "dumps", "load", "loads"]
# Shortcut for use in isinstance testing
bytes_types = (bytes, buffer, memoryview)
bytes_types = (bytes, bytearray, memoryview)
# These are purely informational; no code uses these.
format_version = "2.0" # File format version we write

View File

@ -98,7 +98,7 @@ def pack(x, forcetype = None):
return AE.AECreateDesc(b'long', struct.pack('l', x))
if isinstance(x, float):
return AE.AECreateDesc(b'doub', struct.pack('d', x))
if isinstance(x, (bytes, buffer)):
if isinstance(x, (bytes, bytearray)):
return AE.AECreateDesc(b'TEXT', x)
if isinstance(x, str):
# See http://developer.apple.com/documentation/Carbon/Reference/Apple_Event_Manager/Reference/reference.html#//apple_ref/doc/constant_group/typeUnicodeText

View File

@ -22,7 +22,7 @@ def _four_char_code(four_chars):
four_chars must contain only ASCII characters.
"""
if isinstance(four_chars, (bytes, buffer)):
if isinstance(four_chars, (bytes, bytearray)):
b = bytes(four_chars[:4])
n = len(b)
if n < 4:

View File

@ -53,7 +53,7 @@ def maketrans(frm: bytes, to: bytes) -> bytes:
raise ValueError("maketrans arguments must have same length")
if not (isinstance(frm, bytes) and isinstance(to, bytes)):
raise TypeError("maketrans arguments must be bytes objects")
L = buffer(range(256))
L = bytearray(range(256))
for i, c in enumerate(frm):
L[c] = to[i]
return bytes(L)

View File

@ -222,7 +222,7 @@ def itn(n, digits=8, format=DEFAULT_FORMAT):
# this could raise OverflowError.
n = struct.unpack("L", struct.pack("l", n))[0]
s = buffer()
s = bytearray()
for i in range(digits - 1):
s.insert(0, n & 0o377)
n >>= 8

View File

@ -532,8 +532,8 @@ class BaseTest(unittest.TestCase):
# XXX Commented out. Is there any reason to support buffer objects
# as arguments for str.replace()? GvR
## ba = buffer('a')
## bb = buffer('b')
## ba = bytearray('a')
## bb = bytearray('b')
## EQ("bbc", "abc", "replace", ba, bb)
## EQ("aac", "abc", "replace", bb, ba)

View File

@ -87,7 +87,7 @@ def testadd(data):
print('add')
data2 = []
for d in data:
str = buffer(len(d))
str = bytearray(len(d))
for i,b in enumerate(d):
str[i] = 2*b
data2.append(str)
@ -177,7 +177,7 @@ def testmul(data):
print('mul')
data2 = []
for d in data:
str = buffer(len(d))
str = bytearray(len(d))
for i,b in enumerate(d):
str[i] = 2*b
data2.append(str)
@ -207,7 +207,7 @@ def testreverse(data):
def testtomono(data):
if verbose:
print('tomono')
data2 = buffer()
data2 = bytearray()
for d in data[0]:
data2.append(d)
data2.append(d)
@ -218,7 +218,7 @@ def testtomono(data):
def testtostereo(data):
if verbose:
print('tostereo')
data2 = buffer()
data2 = bytearray()
for d in data[0]:
data2.append(d)
data2.append(d)

View File

@ -56,7 +56,7 @@ class BinASCIITest(unittest.TestCase):
a = binascii.b2a_base64(b)
lines.append(a)
fillers = buffer()
fillers = bytearray()
valid = b"abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789+/"
for i in range(256):
if i not in valid:
@ -64,7 +64,7 @@ class BinASCIITest(unittest.TestCase):
def addnoise(line):
noise = fillers
ratio = len(line) // len(noise)
res = buffer()
res = bytearray()
while line and noise:
if len(line) // len(noise) > ratio:
c, line = line[0], line[1:]
@ -72,7 +72,7 @@ class BinASCIITest(unittest.TestCase):
c, noise = noise[0], noise[1:]
res.append(c)
return res + noise + line
res = buffer()
res = bytearray()
for line in map(addnoise, lines):
b = binascii.a2b_base64(line)
res += b

View File

@ -1,4 +1,4 @@
"""Unit tests for the bytes and buffer types.
"""Unit tests for the bytes and bytearray types.
XXX This is a mess. Common tests should be moved to buffer_tests.py,
which itself ought to be unified with string_tests.py (and the latter
@ -27,12 +27,12 @@ class BytesTest(unittest.TestCase):
warnings.filters = self.warning_filters
def test_basics(self):
b = buffer()
self.assertEqual(type(b), buffer)
self.assertEqual(b.__class__, buffer)
b = bytearray()
self.assertEqual(type(b), bytearray)
self.assertEqual(b.__class__, bytearray)
def test_empty_sequence(self):
b = buffer()
b = bytearray()
self.assertEqual(len(b), 0)
self.assertRaises(IndexError, lambda: b[0])
self.assertRaises(IndexError, lambda: b[1])
@ -48,7 +48,7 @@ class BytesTest(unittest.TestCase):
def test_from_list(self):
ints = list(range(256))
b = buffer(i for i in ints)
b = bytearray(i for i in ints)
self.assertEqual(len(b), 256)
self.assertEqual(list(b), ints)
@ -58,57 +58,57 @@ class BytesTest(unittest.TestCase):
self.i = i
def __index__(self):
return self.i
b = buffer([C(), C(1), C(254), C(255)])
b = bytearray([C(), C(1), C(254), C(255)])
self.assertEqual(list(b), [0, 1, 254, 255])
self.assertRaises(ValueError, buffer, [C(-1)])
self.assertRaises(ValueError, buffer, [C(256)])
self.assertRaises(ValueError, bytearray, [C(-1)])
self.assertRaises(ValueError, bytearray, [C(256)])
def test_from_ssize(self):
self.assertEqual(buffer(0), b'')
self.assertEqual(buffer(1), b'\x00')
self.assertEqual(buffer(5), b'\x00\x00\x00\x00\x00')
self.assertRaises(ValueError, buffer, -1)
self.assertEqual(bytearray(0), b'')
self.assertEqual(bytearray(1), b'\x00')
self.assertEqual(bytearray(5), b'\x00\x00\x00\x00\x00')
self.assertRaises(ValueError, bytearray, -1)
self.assertEqual(buffer('0', 'ascii'), b'0')
self.assertEqual(buffer(b'0'), b'0')
self.assertEqual(bytearray('0', 'ascii'), b'0')
self.assertEqual(bytearray(b'0'), b'0')
def test_constructor_type_errors(self):
self.assertRaises(TypeError, buffer, 0.0)
self.assertRaises(TypeError, bytearray, 0.0)
class C:
pass
self.assertRaises(TypeError, buffer, ["0"])
self.assertRaises(TypeError, buffer, [0.0])
self.assertRaises(TypeError, buffer, [None])
self.assertRaises(TypeError, buffer, [C()])
self.assertRaises(TypeError, bytearray, ["0"])
self.assertRaises(TypeError, bytearray, [0.0])
self.assertRaises(TypeError, bytearray, [None])
self.assertRaises(TypeError, bytearray, [C()])
def test_constructor_value_errors(self):
self.assertRaises(ValueError, buffer, [-1])
self.assertRaises(ValueError, buffer, [-sys.maxint])
self.assertRaises(ValueError, buffer, [-sys.maxint-1])
self.assertRaises(ValueError, buffer, [-sys.maxint-2])
self.assertRaises(ValueError, buffer, [-10**100])
self.assertRaises(ValueError, buffer, [256])
self.assertRaises(ValueError, buffer, [257])
self.assertRaises(ValueError, buffer, [sys.maxint])
self.assertRaises(ValueError, buffer, [sys.maxint+1])
self.assertRaises(ValueError, buffer, [10**100])
self.assertRaises(ValueError, bytearray, [-1])
self.assertRaises(ValueError, bytearray, [-sys.maxint])
self.assertRaises(ValueError, bytearray, [-sys.maxint-1])
self.assertRaises(ValueError, bytearray, [-sys.maxint-2])
self.assertRaises(ValueError, bytearray, [-10**100])
self.assertRaises(ValueError, bytearray, [256])
self.assertRaises(ValueError, bytearray, [257])
self.assertRaises(ValueError, bytearray, [sys.maxint])
self.assertRaises(ValueError, bytearray, [sys.maxint+1])
self.assertRaises(ValueError, bytearray, [10**100])
def test_repr_str(self):
warnings.simplefilter('ignore', BytesWarning)
for f in str, repr:
self.assertEqual(f(buffer()), "buffer(b'')")
self.assertEqual(f(buffer([0])), "buffer(b'\\x00')")
self.assertEqual(f(buffer([0, 1, 254, 255])),
"buffer(b'\\x00\\x01\\xfe\\xff')")
self.assertEqual(f(bytearray()), "bytearray(b'')")
self.assertEqual(f(bytearray([0])), "bytearray(b'\\x00')")
self.assertEqual(f(bytearray([0, 1, 254, 255])),
"bytearray(b'\\x00\\x01\\xfe\\xff')")
self.assertEqual(f(b"abc"), "b'abc'")
self.assertEqual(f(b"'"), '''b"'"''')
self.assertEqual(f(b"'\""), r"""b'\'"'""")
def test_compare(self):
b1 = buffer([1, 2, 3])
b2 = buffer([1, 2, 3])
b3 = buffer([1, 3])
b1 = bytearray([1, 2, 3])
b2 = bytearray([1, 2, 3])
b3 = bytearray([1, 3])
self.assertEqual(b1, b2)
self.failUnless(b2 != b3)
@ -128,7 +128,7 @@ class BytesTest(unittest.TestCase):
self.failIf(b3 < b2)
self.failIf(b3 <= b2)
def test_compare_bytes_to_buffer(self):
def test_compare_bytes_to_bytearray(self):
self.assertEqual(b"abc" == bytes(b"abc"), True)
self.assertEqual(b"ab" != bytes(b"abc"), True)
self.assertEqual(b"ab" <= bytes(b"abc"), True)
@ -165,19 +165,19 @@ class BytesTest(unittest.TestCase):
self.assertEqual(b"\0\0\0a\0\0\0b\0\0\0c" == "abc", False)
self.assertEqual(b"a\0b\0c\0" == "abc", False)
self.assertEqual(b"a\0\0\0b\0\0\0c\0\0\0" == "abc", False)
self.assertEqual(buffer() == str(), False)
self.assertEqual(buffer() != str(), True)
self.assertEqual(bytearray() == str(), False)
self.assertEqual(bytearray() != str(), True)
def test_nohash(self):
self.assertRaises(TypeError, hash, buffer())
self.assertRaises(TypeError, hash, bytearray())
def test_doc(self):
self.failUnless(buffer.__doc__ != None)
self.failUnless(buffer.__doc__.startswith("buffer("), buffer.__doc__)
self.failUnless(bytearray.__doc__ != None)
self.failUnless(bytearray.__doc__.startswith("bytearray("), bytearray.__doc__)
self.failUnless(bytes.__doc__ != None)
self.failUnless(bytes.__doc__.startswith("bytes("), bytes.__doc__)
def test_buffer_api(self):
def test_bytearray_api(self):
short_sample = b"Hello world\n"
sample = short_sample + b"\0"*(20 - len(short_sample))
tfn = tempfile.mktemp()
@ -187,7 +187,7 @@ class BytesTest(unittest.TestCase):
f.write(short_sample)
# Test readinto
with open(tfn, "rb") as f:
b = buffer(20)
b = bytearray(20)
n = f.readinto(b)
self.assertEqual(n, len(short_sample))
self.assertEqual(list(b), list(sample))
@ -205,25 +205,25 @@ class BytesTest(unittest.TestCase):
def test_reversed(self):
input = list(map(ord, "Hello"))
b = buffer(input)
b = bytearray(input)
output = list(reversed(b))
input.reverse()
self.assertEqual(output, input)
def test_reverse(self):
b = buffer(b'hello')
b = bytearray(b'hello')
self.assertEqual(b.reverse(), None)
self.assertEqual(b, b'olleh')
b = buffer(b'hello1') # test even number of items
b = bytearray(b'hello1') # test even number of items
b.reverse()
self.assertEqual(b, b'1olleh')
b = buffer()
b = bytearray()
b.reverse()
self.assertFalse(b)
def test_getslice(self):
def by(s):
return buffer(map(ord, s))
return bytearray(map(ord, s))
b = by("Hello, world")
self.assertEqual(b[:5], by("Hello"))
@ -244,33 +244,33 @@ class BytesTest(unittest.TestCase):
def test_extended_getslice(self):
# Test extended slicing by comparing with list slicing.
L = list(range(255))
b = buffer(L)
b = bytearray(L)
indices = (0, None, 1, 3, 19, 100, -1, -2, -31, -100)
for start in indices:
for stop in indices:
# Skip step 0 (invalid)
for step in indices[1:]:
self.assertEqual(b[start:stop:step], buffer(L[start:stop:step]))
self.assertEqual(b[start:stop:step], bytearray(L[start:stop:step]))
def test_regexps(self):
def by(s):
return buffer(map(ord, s))
return bytearray(map(ord, s))
b = by("Hello, world")
self.assertEqual(re.findall(r"\w+", b), [by("Hello"), by("world")])
def test_setitem(self):
b = buffer([1, 2, 3])
b = bytearray([1, 2, 3])
b[1] = 100
self.assertEqual(b, buffer([1, 100, 3]))
self.assertEqual(b, bytearray([1, 100, 3]))
b[-1] = 200
self.assertEqual(b, buffer([1, 100, 200]))
self.assertEqual(b, bytearray([1, 100, 200]))
class C:
def __init__(self, i=0):
self.i = i
def __index__(self):
return self.i
b[0] = C(10)
self.assertEqual(b, buffer([10, 100, 200]))
self.assertEqual(b, bytearray([10, 100, 200]))
try:
b[3] = 0
self.fail("Didn't raise IndexError")
@ -298,35 +298,35 @@ class BytesTest(unittest.TestCase):
pass
def test_delitem(self):
b = buffer(range(10))
b = bytearray(range(10))
del b[0]
self.assertEqual(b, buffer(range(1, 10)))
self.assertEqual(b, bytearray(range(1, 10)))
del b[-1]
self.assertEqual(b, buffer(range(1, 9)))
self.assertEqual(b, bytearray(range(1, 9)))
del b[4]
self.assertEqual(b, buffer([1, 2, 3, 4, 6, 7, 8]))
self.assertEqual(b, bytearray([1, 2, 3, 4, 6, 7, 8]))
def test_setslice(self):
b = buffer(range(10))
b = bytearray(range(10))
self.assertEqual(list(b), list(range(10)))
b[0:5] = buffer([1, 1, 1, 1, 1])
self.assertEqual(b, buffer([1, 1, 1, 1, 1, 5, 6, 7, 8, 9]))
b[0:5] = bytearray([1, 1, 1, 1, 1])
self.assertEqual(b, bytearray([1, 1, 1, 1, 1, 5, 6, 7, 8, 9]))
del b[0:-5]
self.assertEqual(b, buffer([5, 6, 7, 8, 9]))
self.assertEqual(b, bytearray([5, 6, 7, 8, 9]))
b[0:0] = buffer([0, 1, 2, 3, 4])
self.assertEqual(b, buffer(range(10)))
b[0:0] = bytearray([0, 1, 2, 3, 4])
self.assertEqual(b, bytearray(range(10)))
b[-7:-3] = buffer([100, 101])
self.assertEqual(b, buffer([0, 1, 2, 100, 101, 7, 8, 9]))
b[-7:-3] = bytearray([100, 101])
self.assertEqual(b, bytearray([0, 1, 2, 100, 101, 7, 8, 9]))
b[3:5] = [3, 4, 5, 6]
self.assertEqual(b, buffer(range(10)))
self.assertEqual(b, bytearray(range(10)))
b[3:0] = [42, 42, 42]
self.assertEqual(b, buffer([0, 1, 2, 42, 42, 42, 3, 4, 5, 6, 7, 8, 9]))
self.assertEqual(b, bytearray([0, 1, 2, 42, 42, 42, 3, 4, 5, 6, 7, 8, 9]))
def test_extended_set_del_slice(self):
indices = (0, None, 1, 3, 19, 300, -1, -2, -31, -300)
@ -335,50 +335,50 @@ class BytesTest(unittest.TestCase):
# Skip invalid step 0
for step in indices[1:]:
L = list(range(255))
b = buffer(L)
b = bytearray(L)
# Make sure we have a slice of exactly the right length,
# but with different data.
data = L[start:stop:step]
data.reverse()
L[start:stop:step] = data
b[start:stop:step] = data
self.assertEquals(b, buffer(L))
self.assertEquals(b, bytearray(L))
del L[start:stop:step]
del b[start:stop:step]
self.assertEquals(b, buffer(L))
self.assertEquals(b, bytearray(L))
def test_setslice_trap(self):
# This test verifies that we correctly handle assigning self
# to a slice of self (the old Lambert Meertens trap).
b = buffer(range(256))
b = bytearray(range(256))
b[8:] = b
self.assertEqual(b, buffer(list(range(8)) + list(range(256))))
self.assertEqual(b, bytearray(list(range(8)) + list(range(256))))
def test_encoding(self):
sample = "Hello world\n\u1234\u5678\u9abc\udef0"
for enc in ("utf8", "utf16"):
b = buffer(sample, enc)
self.assertEqual(b, buffer(sample.encode(enc)))
self.assertRaises(UnicodeEncodeError, buffer, sample, "latin1")
b = buffer(sample, "latin1", "ignore")
self.assertEqual(b, buffer(sample[:-4], "utf-8"))
b = bytearray(sample, enc)
self.assertEqual(b, bytearray(sample.encode(enc)))
self.assertRaises(UnicodeEncodeError, bytearray, sample, "latin1")
b = bytearray(sample, "latin1", "ignore")
self.assertEqual(b, bytearray(sample[:-4], "utf-8"))
def test_decode(self):
sample = "Hello world\n\u1234\u5678\u9abc\def0\def0"
for enc in ("utf8", "utf16"):
b = buffer(sample, enc)
b = bytearray(sample, enc)
self.assertEqual(b.decode(enc), sample)
sample = "Hello world\n\x80\x81\xfe\xff"
b = buffer(sample, "latin1")
b = bytearray(sample, "latin1")
self.assertRaises(UnicodeDecodeError, b.decode, "utf8")
self.assertEqual(b.decode("utf8", "ignore"), "Hello world\n")
def test_from_buffer(self):
def test_from_bytearray(self):
sample = bytes(b"Hello world\n\x80\x81\xfe\xff")
buf = memoryview(sample)
b = buffer(buf)
self.assertEqual(b, buffer(sample))
b = bytearray(buf)
self.assertEqual(b, bytearray(sample))
def test_to_str(self):
warnings.simplefilter('ignore', BytesWarning)
@ -387,12 +387,12 @@ class BytesTest(unittest.TestCase):
self.assertEqual(str(b'\x80'), "b'\\x80'")
def test_from_int(self):
b = buffer(0)
self.assertEqual(b, buffer())
b = buffer(10)
self.assertEqual(b, buffer([0]*10))
b = buffer(10000)
self.assertEqual(b, buffer([0]*10000))
b = bytearray(0)
self.assertEqual(b, bytearray())
b = bytearray(10)
self.assertEqual(b, bytearray([0]*10))
b = bytearray(10000)
self.assertEqual(b, bytearray([0]*10000))
def test_concat(self):
b1 = b"abc"
@ -404,21 +404,21 @@ class BytesTest(unittest.TestCase):
self.assertRaises(TypeError, lambda: "abc" + b2)
def test_repeat(self):
for b in b"abc", buffer(b"abc"):
for b in b"abc", bytearray(b"abc"):
self.assertEqual(b * 3, b"abcabcabc")
self.assertEqual(b * 0, b"")
self.assertEqual(b * -1, b"")
self.assertRaises(TypeError, lambda: b * 3.14)
self.assertRaises(TypeError, lambda: 3.14 * b)
# XXX Shouldn't bytes and buffer agree on what to raise?
# XXX Shouldn't bytes and bytearray agree on what to raise?
self.assertRaises((OverflowError, MemoryError),
lambda: b * sys.maxint)
def test_repeat_1char(self):
self.assertEqual(b'x'*100, buffer([ord('x')]*100))
self.assertEqual(b'x'*100, bytearray([ord('x')]*100))
def test_iconcat(self):
b = buffer(b"abc")
b = bytearray(b"abc")
b1 = b
b += b"def"
self.assertEqual(b, b"abcdef")
@ -434,7 +434,7 @@ class BytesTest(unittest.TestCase):
self.fail("bytes += unicode didn't raise TypeError")
def test_irepeat(self):
b = buffer(b"abc")
b = bytearray(b"abc")
b1 = b
b *= 3
self.assertEqual(b, b"abcabcabc")
@ -442,7 +442,7 @@ class BytesTest(unittest.TestCase):
self.failUnless(b is b1)
def test_irepeat_1char(self):
b = buffer(b"x")
b = bytearray(b"x")
b1 = b
b *= 100
self.assertEqual(b, b"x"*100)
@ -450,7 +450,7 @@ class BytesTest(unittest.TestCase):
self.failUnless(b is b1)
def test_contains(self):
for b in b"abc", buffer(b"abc"):
for b in b"abc", bytearray(b"abc"):
self.failUnless(ord('a') in b)
self.failUnless(int(ord('a')) in b)
self.failIf(200 in b)
@ -460,7 +460,7 @@ class BytesTest(unittest.TestCase):
self.assertRaises(TypeError, lambda: None in b)
self.assertRaises(TypeError, lambda: float(ord('a')) in b)
self.assertRaises(TypeError, lambda: "a" in b)
for f in bytes, buffer:
for f in bytes, bytearray:
self.failUnless(f(b"") in b)
self.failUnless(f(b"a") in b)
self.failUnless(f(b"b") in b)
@ -474,7 +474,7 @@ class BytesTest(unittest.TestCase):
self.failIf(f(b"abd") in b)
def test_alloc(self):
b = buffer()
b = bytearray()
alloc = b.__alloc__()
self.assert_(alloc >= 0)
seq = [alloc]
@ -486,19 +486,19 @@ class BytesTest(unittest.TestCase):
seq.append(alloc)
def test_fromhex(self):
self.assertRaises(TypeError, buffer.fromhex)
self.assertRaises(TypeError, buffer.fromhex, 1)
self.assertEquals(buffer.fromhex(''), buffer())
b = buffer([0x1a, 0x2b, 0x30])
self.assertEquals(buffer.fromhex('1a2B30'), b)
self.assertEquals(buffer.fromhex(' 1A 2B 30 '), b)
self.assertEquals(buffer.fromhex('0000'), b'\0\0')
self.assertRaises(TypeError, buffer.fromhex, b'1B')
self.assertRaises(ValueError, buffer.fromhex, 'a')
self.assertRaises(ValueError, buffer.fromhex, 'rt')
self.assertRaises(ValueError, buffer.fromhex, '1a b cd')
self.assertRaises(ValueError, buffer.fromhex, '\x00')
self.assertRaises(ValueError, buffer.fromhex, '12 \x00 34')
self.assertRaises(TypeError, bytearray.fromhex)
self.assertRaises(TypeError, bytearray.fromhex, 1)
self.assertEquals(bytearray.fromhex(''), bytearray())
b = bytearray([0x1a, 0x2b, 0x30])
self.assertEquals(bytearray.fromhex('1a2B30'), b)
self.assertEquals(bytearray.fromhex(' 1A 2B 30 '), b)
self.assertEquals(bytearray.fromhex('0000'), b'\0\0')
self.assertRaises(TypeError, bytearray.fromhex, b'1B')
self.assertRaises(ValueError, bytearray.fromhex, 'a')
self.assertRaises(ValueError, bytearray.fromhex, 'rt')
self.assertRaises(ValueError, bytearray.fromhex, '1a b cd')
self.assertRaises(ValueError, bytearray.fromhex, '\x00')
self.assertRaises(ValueError, bytearray.fromhex, '12 \x00 34')
def test_join(self):
self.assertEqual(b"".join([]), b"")
@ -518,20 +518,20 @@ class BytesTest(unittest.TestCase):
(br"\xaa\x00\000\200", r"\xaa\x00\000\200"),
]
for b, s in tests:
self.assertEqual(b, buffer(s, 'latin-1'))
self.assertEqual(b, bytearray(s, 'latin-1'))
for c in range(128, 256):
self.assertRaises(SyntaxError, eval,
'b"%s"' % chr(c))
def test_extend(self):
orig = b'hello'
a = buffer(orig)
a = bytearray(orig)
a.extend(a)
self.assertEqual(a, orig + orig)
self.assertEqual(a[5:], orig)
def test_remove(self):
b = buffer(b'hello')
b = bytearray(b'hello')
b.remove(ord('l'))
self.assertEqual(b, b'helo')
b.remove(ord('l'))
@ -546,15 +546,15 @@ class BytesTest(unittest.TestCase):
self.assertRaises(TypeError, lambda: b.remove(b'e'))
def test_pop(self):
b = buffer(b'world')
b = bytearray(b'world')
self.assertEqual(b.pop(), ord('d'))
self.assertEqual(b.pop(0), ord('w'))
self.assertEqual(b.pop(-2), ord('r'))
self.assertRaises(IndexError, lambda: b.pop(10))
self.assertRaises(OverflowError, lambda: buffer().pop())
self.assertRaises(OverflowError, lambda: bytearray().pop())
def test_nosort(self):
self.assertRaises(AttributeError, lambda: buffer().sort())
self.assertRaises(AttributeError, lambda: bytearray().sort())
def test_index(self):
b = b'parrot'
@ -570,17 +570,17 @@ class BytesTest(unittest.TestCase):
self.assertEqual(b.count(b'w'), 0)
def test_append(self):
b = buffer(b'hell')
b = bytearray(b'hell')
b.append(ord('o'))
self.assertEqual(b, b'hello')
self.assertEqual(b.append(100), None)
b = buffer()
b = bytearray()
b.append(ord('A'))
self.assertEqual(len(b), 1)
self.assertRaises(TypeError, lambda: b.append(b'o'))
def test_insert(self):
b = buffer(b'msssspp')
b = bytearray(b'msssspp')
b.insert(1, ord('i'))
b.insert(4, ord('i'))
b.insert(-2, ord('i'))
@ -590,7 +590,7 @@ class BytesTest(unittest.TestCase):
def test_startswith(self):
b = b'hello'
self.assertFalse(buffer().startswith(b"anything"))
self.assertFalse(bytearray().startswith(b"anything"))
self.assertTrue(b.startswith(b"hello"))
self.assertTrue(b.startswith(b"hel"))
self.assertTrue(b.startswith(b"h"))
@ -599,7 +599,7 @@ class BytesTest(unittest.TestCase):
def test_endswith(self):
b = b'hello'
self.assertFalse(buffer().endswith(b"anything"))
self.assertFalse(bytearray().endswith(b"anything"))
self.assertTrue(b.endswith(b"hello"))
self.assertTrue(b.endswith(b"llo"))
self.assertTrue(b.endswith(b"o"))
@ -645,7 +645,7 @@ class BytesTest(unittest.TestCase):
def test_translate(self):
b = b'hello'
rosetta = buffer(range(0, 256))
rosetta = bytearray(range(0, 256))
rosetta[ord('o')] = ord('e')
c = b.translate(rosetta, b'l')
self.assertEqual(b, b'hello')
@ -668,7 +668,7 @@ class BytesTest(unittest.TestCase):
self.assertEqual(b' a bb c '.split(None, 2), [b'a', b'bb', b'c '])
self.assertEqual(b' a bb c '.split(None, 3), [b'a', b'bb', b'c'])
def test_split_buffer(self):
def test_split_bytearray(self):
self.assertEqual(b'a b'.split(memoryview(b' ')), [b'a', b'b'])
def test_split_string_error(self):
@ -691,7 +691,7 @@ class BytesTest(unittest.TestCase):
self.assertEqual(b' a bb c '.rsplit(None,2), [b' a', b'bb', b'c'])
self.assertEqual(b' a bb c '.rsplit(None, 3), [b'a', b'bb', b'c'])
def test_rsplit_buffer(self):
def test_rsplit_bytearray(self):
self.assertEqual(b'a b'.rsplit(memoryview(b' ')), [b'a', b'b'])
def test_rsplit_string_error(self):
@ -745,7 +745,7 @@ class BytesTest(unittest.TestCase):
self.assertEqual(b.lstrip(), b'abc \t\n\r\f\v')
self.assertEqual(b.rstrip(), b' \t\n\r\f\vabc')
def test_strip_buffer(self):
def test_strip_bytearray(self):
self.assertEqual(b'abc'.strip(memoryview(b'ac')), b'b')
self.assertEqual(b'abc'.lstrip(memoryview(b'ac')), b'bc')
self.assertEqual(b'abc'.rstrip(memoryview(b'ac')), b'ab')
@ -760,24 +760,24 @@ class BytesTest(unittest.TestCase):
self.assertEqual([ord(b[i:i+1]) for i in range(len(b))],
[0, 65, 127, 128, 255])
def test_partition_buffer_doesnt_share_nullstring(self):
a, b, c = buffer(b"x").partition(b"y")
def test_partition_bytearray_doesnt_share_nullstring(self):
a, b, c = bytearray(b"x").partition(b"y")
self.assertEqual(b, b"")
self.assertEqual(c, b"")
self.assert_(b is not c)
b += b"!"
self.assertEqual(c, b"")
a, b, c = buffer(b"x").partition(b"y")
a, b, c = bytearray(b"x").partition(b"y")
self.assertEqual(b, b"")
self.assertEqual(c, b"")
# Same for rpartition
b, c, a = buffer(b"x").rpartition(b"y")
b, c, a = bytearray(b"x").rpartition(b"y")
self.assertEqual(b, b"")
self.assertEqual(c, b"")
self.assert_(b is not c)
b += b"!"
self.assertEqual(c, b"")
c, b, a = buffer(b"x").rpartition(b"y")
c, b, a = bytearray(b"x").rpartition(b"y")
self.assertEqual(b, b"")
self.assertEqual(c, b"")
@ -793,22 +793,22 @@ class BytesTest(unittest.TestCase):
# Unfortunately they are all bundled with tests that
# are not appropriate for bytes
# I've started porting some of those into buffer_tests.py, we should port
# I've started porting some of those into bytearray_tests.py, we should port
# the rest that make sense (the code can be cleaned up to use modern
# unittest methods at the same time).
class BufferPEP3137Test(unittest.TestCase,
class BytearrayPEP3137Test(unittest.TestCase,
test.buffer_tests.MixinBytesBufferCommonTests):
def marshal(self, x):
return buffer(x)
return bytearray(x)
# TODO this should become:
#return buffer(x)
# once the bytes -> buffer and str8 -> bytes rename happens
#return bytearray(x)
# once the bytes -> bytearray and str8 -> bytes rename happens
def test_returns_new_copy(self):
val = self.marshal(b'1234')
# On immutable types these MAY return a reference to themselves
# but on mutable types like buffer they MUST return a new copy.
# but on mutable types like bytearray they MUST return a new copy.
for methname in ('zfill', 'rjust', 'ljust', 'center'):
method = getattr(val, methname)
newval = method(3)
@ -818,7 +818,7 @@ class BufferPEP3137Test(unittest.TestCase,
class BytesAsStringTest(test.string_tests.BaseTest):
type2test = buffer
type2test = bytearray
def fixtype(self, obj):
if isinstance(obj, str):
@ -838,17 +838,17 @@ class BytesAsStringTest(test.string_tests.BaseTest):
pass
class BufferSubclass(buffer):
class ByteArraySubclass(bytearray):
pass
class BufferSubclassTest(unittest.TestCase):
class ByteArraySubclassTest(unittest.TestCase):
def test_basic(self):
self.assert_(issubclass(BufferSubclass, buffer))
self.assert_(isinstance(BufferSubclass(), buffer))
self.assert_(issubclass(ByteArraySubclass, bytearray))
self.assert_(isinstance(ByteArraySubclass(), bytearray))
a, b = b"abcd", b"efgh"
_a, _b = BufferSubclass(a), BufferSubclass(b)
_a, _b = ByteArraySubclass(a), ByteArraySubclass(b)
# test comparison operators with subclass instances
self.assert_(_a == _a)
@ -871,19 +871,19 @@ class BufferSubclassTest(unittest.TestCase):
# Make sure join returns a NEW object for single item sequences
# involving a subclass.
# Make sure that it is of the appropriate type.
s1 = BufferSubclass(b"abcd")
s2 = buffer().join([s1])
s1 = ByteArraySubclass(b"abcd")
s2 = bytearray().join([s1])
self.assert_(s1 is not s2)
self.assert_(type(s2) is buffer, type(s2))
self.assert_(type(s2) is bytearray, type(s2))
# Test reverse, calling join on subclass
s3 = s1.join([b"abcd"])
self.assert_(type(s3) is buffer)
self.assert_(type(s3) is bytearray)
def test_pickle(self):
a = BufferSubclass(b"abcd")
a = ByteArraySubclass(b"abcd")
a.x = 10
a.y = BufferSubclass(b"efgh")
a.y = ByteArraySubclass(b"efgh")
for proto in range(pickle.HIGHEST_PROTOCOL):
b = pickle.loads(pickle.dumps(a, proto))
self.assertNotEqual(id(a), id(b))
@ -894,9 +894,9 @@ class BufferSubclassTest(unittest.TestCase):
self.assertEqual(type(a.y), type(b.y))
def test_copy(self):
a = BufferSubclass(b"abcd")
a = ByteArraySubclass(b"abcd")
a.x = 10
a.y = BufferSubclass(b"efgh")
a.y = ByteArraySubclass(b"efgh")
for copy_method in (copy.copy, copy.deepcopy):
b = copy_method(a)
self.assertNotEqual(id(a), id(b))
@ -907,9 +907,9 @@ class BufferSubclassTest(unittest.TestCase):
self.assertEqual(type(a.y), type(b.y))
def test_init_override(self):
class subclass(buffer):
class subclass(bytearray):
def __init__(self, newarg=1, *args, **kwargs):
buffer.__init__(self, *args, **kwargs)
bytearray.__init__(self, *args, **kwargs)
x = subclass(4, source=b"abcd")
self.assertEqual(x, b"abcd")
x = subclass(newarg=4, source=b"abcd")
@ -919,8 +919,8 @@ class BufferSubclassTest(unittest.TestCase):
def test_main():
test.test_support.run_unittest(BytesTest)
test.test_support.run_unittest(BytesAsStringTest)
test.test_support.run_unittest(BufferSubclassTest)
test.test_support.run_unittest(BufferPEP3137Test)
test.test_support.run_unittest(ByteArraySubclassTest)
test.test_support.run_unittest(BytearrayPEP3137Test)
if __name__ == "__main__":
test_main()

View File

@ -33,13 +33,13 @@ class BadObjectUnicodeEncodeError(UnicodeEncodeError):
# A UnicodeDecodeError object without an end attribute
class NoEndUnicodeDecodeError(UnicodeDecodeError):
def __init__(self):
UnicodeDecodeError.__init__(self, "ascii", buffer(b""), 0, 1, "bad")
UnicodeDecodeError.__init__(self, "ascii", bytearray(b""), 0, 1, "bad")
del self.end
# A UnicodeDecodeError object with a bad object attribute
class BadObjectUnicodeDecodeError(UnicodeDecodeError):
def __init__(self):
UnicodeDecodeError.__init__(self, "ascii", buffer(b""), 0, 1, "bad")
UnicodeDecodeError.__init__(self, "ascii", bytearray(b""), 0, 1, "bad")
self.object = []
# A UnicodeTranslateError object without a start attribute
@ -363,12 +363,12 @@ class CodecCallbackTest(unittest.TestCase):
def test_unicodedecodeerror(self):
self.check_exceptionobjectargs(
UnicodeDecodeError,
["ascii", buffer(b"g\xfcrk"), 1, 2, "ouch"],
["ascii", bytearray(b"g\xfcrk"), 1, 2, "ouch"],
"'ascii' codec can't decode byte 0xfc in position 1: ouch"
)
self.check_exceptionobjectargs(
UnicodeDecodeError,
["ascii", buffer(b"g\xfcrk"), 1, 3, "ouch"],
["ascii", bytearray(b"g\xfcrk"), 1, 3, "ouch"],
"'ascii' codec can't decode bytes in position 1-2: ouch"
)
@ -442,7 +442,7 @@ class CodecCallbackTest(unittest.TestCase):
)
self.assertEquals(
codecs.ignore_errors(
UnicodeDecodeError("ascii", buffer(b"\xff"), 0, 1, "ouch")),
UnicodeDecodeError("ascii", bytearray(b"\xff"), 0, 1, "ouch")),
("", 1)
)
self.assertEquals(
@ -482,7 +482,7 @@ class CodecCallbackTest(unittest.TestCase):
)
self.assertEquals(
codecs.replace_errors(
UnicodeDecodeError("ascii", buffer(b"\xff"), 0, 1, "ouch")),
UnicodeDecodeError("ascii", bytearray(b"\xff"), 0, 1, "ouch")),
("\ufffd", 1)
)
self.assertEquals(
@ -508,7 +508,7 @@ class CodecCallbackTest(unittest.TestCase):
self.assertRaises(
TypeError,
codecs.xmlcharrefreplace_errors,
UnicodeDecodeError("ascii", buffer(b"\xff"), 0, 1, "ouch")
UnicodeDecodeError("ascii", bytearray(b"\xff"), 0, 1, "ouch")
)
self.assertRaises(
TypeError,
@ -542,7 +542,7 @@ class CodecCallbackTest(unittest.TestCase):
self.assertRaises(
TypeError,
codecs.backslashreplace_errors,
UnicodeDecodeError("ascii", buffer(b"\xff"), 0, 1, "ouch")
UnicodeDecodeError("ascii", bytearray(b"\xff"), 0, 1, "ouch")
)
self.assertRaises(
TypeError,

View File

@ -99,7 +99,7 @@ class TestOneTrickPonyABCs(unittest.TestCase):
def test_Hashable(self):
# Check some non-hashables
non_samples = [buffer(), list(), set(), dict()]
non_samples = [bytearray(), list(), set(), dict()]
for x in non_samples:
self.failIf(isinstance(x, Hashable), repr(x))
self.failIf(issubclass(type(x), Hashable), repr(type(x)))

View File

@ -1093,7 +1093,7 @@ class TestDate(HarmlessMixedComparison, unittest.TestCase):
self.assertEqual(orig, derived)
def test_backdoor_resistance(self):
# For fast unpickling, the constructor accepts a pickle string.
# For fast unpickling, the constructor accepts a pickle byte string.
# This is a low-overhead backdoor. A user can (by intent or
# mistake) pass a string directly, which (if it's the right length)
# will get treated like a pickle, and bypass the normal sanity
@ -1101,17 +1101,17 @@ class TestDate(HarmlessMixedComparison, unittest.TestCase):
# The constructor doesn't want to burn the time to validate all
# fields, but does check the month field. This stops, e.g.,
# datetime.datetime('1995-03-25') from yielding an insane object.
base = '1995-03-25'
base = b'1995-03-25'
if not issubclass(self.theclass, datetime):
base = base[:4]
for month_byte in '9', chr(0), chr(13), '\xff':
for month_byte in b'9', b'\0', b'\r', b'\xff':
self.assertRaises(TypeError, self.theclass,
base[:2] + month_byte + base[3:])
for ord_byte in range(1, 13):
# This shouldn't blow up because of the month byte alone. If
# the implementation changes to do more-careful checking, it may
# blow up because other fields are insane.
self.theclass(buffer(base[:2] + chr(ord_byte) + base[3:], "ascii"))
self.theclass(base[:2] + bytes([ord_byte]) + base[3:])
#############################################################################
# datetime tests

View File

@ -253,9 +253,9 @@ class ExceptionTests(unittest.TestCase):
'ordinal not in range'),
'encoding' : 'ascii', 'object' : 'a',
'start' : 0, 'reason' : 'ordinal not in range'}),
(UnicodeDecodeError, ('ascii', buffer(b'\xff'), 0, 1,
(UnicodeDecodeError, ('ascii', bytearray(b'\xff'), 0, 1,
'ordinal not in range'),
{'args' : ('ascii', buffer(b'\xff'), 0, 1,
{'args' : ('ascii', bytearray(b'\xff'), 0, 1,
'ordinal not in range'),
'encoding' : 'ascii', 'object' : b'\xff',
'start' : 0, 'reason' : 'ordinal not in range'}),

View File

@ -40,14 +40,14 @@ class FormatFunctionsTestCase(unittest.TestCase):
'chicken', 'unknown')
BE_DOUBLE_INF = b'\x7f\xf0\x00\x00\x00\x00\x00\x00'
LE_DOUBLE_INF = bytes(reversed(buffer(BE_DOUBLE_INF)))
LE_DOUBLE_INF = bytes(reversed(BE_DOUBLE_INF))
BE_DOUBLE_NAN = b'\x7f\xf8\x00\x00\x00\x00\x00\x00'
LE_DOUBLE_NAN = bytes(reversed(buffer(BE_DOUBLE_NAN)))
LE_DOUBLE_NAN = bytes(reversed(BE_DOUBLE_NAN))
BE_FLOAT_INF = b'\x7f\x80\x00\x00'
LE_FLOAT_INF = bytes(reversed(buffer(BE_FLOAT_INF)))
LE_FLOAT_INF = bytes(reversed(BE_FLOAT_INF))
BE_FLOAT_NAN = b'\x7f\xc0\x00\x00'
LE_FLOAT_NAN = bytes(reversed(buffer(BE_FLOAT_NAN)))
LE_FLOAT_NAN = bytes(reversed(BE_FLOAT_NAN))
# on non-IEEE platforms, attempting to unpack a bit pattern
# representing an infinity or a NaN should raise an exception.

View File

@ -88,7 +88,7 @@ class IOTest(unittest.TestCase):
self.assertEqual(f.tell(), 6)
self.assertEqual(f.seek(-1, 1), 5)
self.assertEqual(f.tell(), 5)
self.assertEqual(f.write(buffer(b" world\n\n\n")), 9)
self.assertEqual(f.write(bytearray(b" world\n\n\n")), 9)
self.assertEqual(f.seek(0), 0)
self.assertEqual(f.write(b"h"), 1)
self.assertEqual(f.seek(-1, 2), 13)
@ -100,7 +100,7 @@ class IOTest(unittest.TestCase):
def read_ops(self, f, buffered=False):
data = f.read(5)
self.assertEqual(data, b"hello")
data = buffer(data)
data = bytearray(data)
self.assertEqual(f.readinto(data), 5)
self.assertEqual(data, b" worl")
self.assertEqual(f.readinto(data), 2)
@ -109,11 +109,11 @@ class IOTest(unittest.TestCase):
self.assertEqual(f.seek(0), 0)
self.assertEqual(f.read(20), b"hello world\n")
self.assertEqual(f.read(1), b"")
self.assertEqual(f.readinto(buffer(b"x")), 0)
self.assertEqual(f.readinto(bytearray(b"x")), 0)
self.assertEqual(f.seek(-6, 2), 6)
self.assertEqual(f.read(5), b"world")
self.assertEqual(f.read(0), b"")
self.assertEqual(f.readinto(buffer()), 0)
self.assertEqual(f.readinto(bytearray()), 0)
self.assertEqual(f.seek(-6, 1), 5)
self.assertEqual(f.read(5), b" worl")
self.assertEqual(f.tell(), 10)

View File

@ -39,7 +39,7 @@ class IntTestCase(unittest.TestCase, HelperMixin):
# we're running the test on a 32-bit box, of course.
def to_little_endian_string(value, nbytes):
b = buffer()
b = bytearray()
for i in range(nbytes):
b.append(value & 0xff)
value >>= 8

View File

@ -560,11 +560,11 @@ def test_unpack_from():
test_string = b'abcd01234'
fmt = '4s'
s = struct.Struct(fmt)
for cls in (buffer, bytes):
for cls in (bytes, bytearray):
if verbose:
print("test_unpack_from using", cls.__name__)
data = cls(test_string)
if not isinstance(data, (buffer, bytes)):
if not isinstance(data, (bytes, bytearray)):
bytes_data = bytes(data, 'latin1')
else:
bytes_data = data
@ -575,7 +575,7 @@ def test_unpack_from():
vereq(s.unpack_from(data, i), (bytes_data[i:i+4],))
for i in range(6, len(test_string) + 1):
simple_err(s.unpack_from, data, i)
for cls in (buffer, bytes):
for cls in (bytes, bytearray):
data = cls(test_string)
vereq(struct.unpack_from(fmt, data), (b'abcd',))
vereq(struct.unpack_from(fmt, data, 2), (b'cd01',))

View File

@ -218,8 +218,8 @@ class UnicodeTest(
warnings.simplefilter('ignore', BytesWarning)
self.assertEqual('abc' == b'abc', False)
self.assertEqual('abc' != b'abc', True)
self.assertEqual('abc' == buffer(b'abc'), False)
self.assertEqual('abc' != buffer(b'abc'), True)
self.assertEqual('abc' == bytearray(b'abc'), False)
self.assertEqual('abc' != bytearray(b'abc'), True)
def test_comparison(self):
# Comparisons:

View File

@ -177,7 +177,7 @@ class UnicodeFunctionsTest(UnicodeDatabaseTest):
def test_east_asian_width(self):
eaw = self.db.east_asian_width
self.assertRaises(TypeError, eaw, b'a')
self.assertRaises(TypeError, eaw, buffer())
self.assertRaises(TypeError, eaw, bytearray())
self.assertRaises(TypeError, eaw, '')
self.assertRaises(TypeError, eaw, 'ra')
self.assertEqual(eaw('\x1e'), 'N')

View File

@ -153,7 +153,7 @@ class UncompressedZipImportTestCase(ImportHooksBaseTestCase):
def testBadMagic(self):
# make pyc magic word invalid, forcing loading from .py
badmagic_pyc = buffer(test_pyc)
badmagic_pyc = bytearray(test_pyc)
badmagic_pyc[0] ^= 0x04 # flip an arbitrary bit
files = {TESTMOD + ".py": (NOW, test_src),
TESTMOD + pyc_ext: (NOW, badmagic_pyc)}
@ -161,7 +161,7 @@ class UncompressedZipImportTestCase(ImportHooksBaseTestCase):
def testBadMagic2(self):
# make pyc magic word invalid, causing an ImportError
badmagic_pyc = buffer(test_pyc)
badmagic_pyc = bytearray(test_pyc)
badmagic_pyc[0] ^= 0x04 # flip an arbitrary bit
files = {TESTMOD + pyc_ext: (NOW, badmagic_pyc)}
try:
@ -172,7 +172,7 @@ class UncompressedZipImportTestCase(ImportHooksBaseTestCase):
self.fail("expected ImportError; import from bad pyc")
def testBadMTime(self):
badtime_pyc = buffer(test_pyc)
badtime_pyc = bytearray(test_pyc)
badtime_pyc[7] ^= 0x02 # flip the second bit -- not the first as that one
# isn't stored in the .py's mtime in the zip archive.
files = {TESTMOD + ".py": (NOW, test_src),

View File

@ -234,7 +234,7 @@ class UUID(object):
@property
def bytes(self):
bytes = buffer()
bytes = bytearray()
for shift in range(0, 128, 8):
bytes.insert(0, (self.int >> shift) & 0xff)
return bytes

View File

@ -2186,15 +2186,15 @@ date_new(PyTypeObject *type, PyObject *args, PyObject *kw)
/* Check for invocation from pickle with __getstate__ state */
if (PyTuple_GET_SIZE(args) == 1 &&
PyBytes_Check(state = PyTuple_GET_ITEM(args, 0)) &&
PyBytes_GET_SIZE(state) == _PyDateTime_DATE_DATASIZE &&
MONTH_IS_SANE(PyBytes_AS_STRING(state)[2]))
PyString_Check(state = PyTuple_GET_ITEM(args, 0)) &&
PyString_GET_SIZE(state) == _PyDateTime_DATE_DATASIZE &&
MONTH_IS_SANE(PyString_AS_STRING(state)[2]))
{
PyDateTime_Date *me;
me = (PyDateTime_Date *) (type->tp_alloc(type, 0));
if (me != NULL) {
char *pdata = PyBytes_AS_STRING(state);
char *pdata = PyString_AS_STRING(state);
memcpy(me->data, pdata, _PyDateTime_DATE_DATASIZE);
me->hashcode = -1;
}
@ -2556,7 +2556,7 @@ date_hash(PyDateTime_Date *self)
if (self->hashcode == -1)
self->hashcode = generic_hash(
(unsigned char *)self->data, _PyDateTime_DATE_DATASIZE);
return self->hashcode;
}
@ -2582,8 +2582,8 @@ static PyObject *
date_getstate(PyDateTime_Date *self)
{
PyObject* field;
field = PyBytes_FromStringAndSize(
(char*)self->data, _PyDateTime_DATE_DATASIZE);
field = PyString_FromStringAndSize((char*)self->data,
_PyDateTime_DATE_DATASIZE);
return Py_BuildValue("(N)", field);
}
@ -3035,9 +3035,9 @@ time_new(PyTypeObject *type, PyObject *args, PyObject *kw)
/* Check for invocation from pickle with __getstate__ state */
if (PyTuple_GET_SIZE(args) >= 1 &&
PyTuple_GET_SIZE(args) <= 2 &&
PyBytes_Check(state = PyTuple_GET_ITEM(args, 0)) &&
PyBytes_GET_SIZE(state) == _PyDateTime_TIME_DATASIZE &&
((unsigned char) (PyBytes_AS_STRING(state)[0])) < 24)
PyString_Check(state = PyTuple_GET_ITEM(args, 0)) &&
PyString_GET_SIZE(state) == _PyDateTime_TIME_DATASIZE &&
((unsigned char) (PyString_AS_STRING(state)[0])) < 24)
{
PyDateTime_Time *me;
char aware;
@ -3053,7 +3053,7 @@ time_new(PyTypeObject *type, PyObject *args, PyObject *kw)
aware = (char)(tzinfo != Py_None);
me = (PyDateTime_Time *) (type->tp_alloc(type, aware));
if (me != NULL) {
char *pdata = PyBytes_AS_STRING(state);
char *pdata = PyString_AS_STRING(state);
memcpy(me->data, pdata, _PyDateTime_TIME_DATASIZE);
me->hashcode = -1;
@ -3385,7 +3385,7 @@ time_getstate(PyDateTime_Time *self)
PyObject *basestate;
PyObject *result = NULL;
basestate = PyBytes_FromStringAndSize((char *)self->data,
basestate = PyString_FromStringAndSize((char *)self->data,
_PyDateTime_TIME_DATASIZE);
if (basestate != NULL) {
if (! HASTZINFO(self) || self->tzinfo == Py_None)
@ -3569,9 +3569,9 @@ datetime_new(PyTypeObject *type, PyObject *args, PyObject *kw)
/* Check for invocation from pickle with __getstate__ state */
if (PyTuple_GET_SIZE(args) >= 1 &&
PyTuple_GET_SIZE(args) <= 2 &&
PyBytes_Check(state = PyTuple_GET_ITEM(args, 0)) &&
PyBytes_GET_SIZE(state) == _PyDateTime_DATETIME_DATASIZE &&
MONTH_IS_SANE(PyBytes_AS_STRING(state)[2]))
PyString_Check(state = PyTuple_GET_ITEM(args, 0)) &&
PyString_GET_SIZE(state) == _PyDateTime_DATETIME_DATASIZE &&
MONTH_IS_SANE(PyString_AS_STRING(state)[2]))
{
PyDateTime_DateTime *me;
char aware;
@ -3587,7 +3587,7 @@ datetime_new(PyTypeObject *type, PyObject *args, PyObject *kw)
aware = (char)(tzinfo != Py_None);
me = (PyDateTime_DateTime *) (type->tp_alloc(type , aware));
if (me != NULL) {
char *pdata = PyBytes_AS_STRING(state);
char *pdata = PyString_AS_STRING(state);
memcpy(me->data, pdata, _PyDateTime_DATETIME_DATASIZE);
me->hashcode = -1;
@ -4432,8 +4432,8 @@ datetime_getstate(PyDateTime_DateTime *self)
PyObject *basestate;
PyObject *result = NULL;
basestate = PyBytes_FromStringAndSize((char *)self->data,
_PyDateTime_DATETIME_DATASIZE);
basestate = PyString_FromStringAndSize((char *)self->data,
_PyDateTime_DATETIME_DATASIZE);
if (basestate != NULL) {
if (! HASTZINFO(self) || self->tzinfo == Py_None)
result = PyTuple_Pack(1, basestate);

View File

@ -1,4 +1,4 @@
/* Bytes object implementation */
/* PyBytes (bytearray) implementation */
#define PY_SSIZE_T_CLEAN
#include "Python.h"
@ -347,7 +347,7 @@ bytes_getitem(PyBytesObject *self, Py_ssize_t i)
if (i < 0)
i += Py_Size(self);
if (i < 0 || i >= Py_Size(self)) {
PyErr_SetString(PyExc_IndexError, "buffer index out of range");
PyErr_SetString(PyExc_IndexError, "bytearray index out of range");
return NULL;
}
return PyInt_FromLong((unsigned char)(self->ob_bytes[i]));
@ -366,7 +366,7 @@ bytes_subscript(PyBytesObject *self, PyObject *item)
i += PyBytes_GET_SIZE(self);
if (i < 0 || i >= Py_Size(self)) {
PyErr_SetString(PyExc_IndexError, "buffer index out of range");
PyErr_SetString(PyExc_IndexError, "bytearray index out of range");
return NULL;
}
return PyInt_FromLong((unsigned char)(self->ob_bytes[i]));
@ -403,7 +403,7 @@ bytes_subscript(PyBytesObject *self, PyObject *item)
}
}
else {
PyErr_SetString(PyExc_TypeError, "buffer indices must be integers");
PyErr_SetString(PyExc_TypeError, "bytearray indices must be integers");
return NULL;
}
}
@ -503,7 +503,7 @@ bytes_setitem(PyBytesObject *self, Py_ssize_t i, PyObject *value)
i += Py_Size(self);
if (i < 0 || i >= Py_Size(self)) {
PyErr_SetString(PyExc_IndexError, "buffer index out of range");
PyErr_SetString(PyExc_IndexError, "bytearray index out of range");
return -1;
}
@ -539,7 +539,7 @@ bytes_ass_subscript(PyBytesObject *self, PyObject *item, PyObject *values)
i += PyBytes_GET_SIZE(self);
if (i < 0 || i >= Py_Size(self)) {
PyErr_SetString(PyExc_IndexError, "buffer index out of range");
PyErr_SetString(PyExc_IndexError, "bytearray index out of range");
return -1;
}
@ -571,7 +571,7 @@ bytes_ass_subscript(PyBytesObject *self, PyObject *item, PyObject *values)
}
}
else {
PyErr_SetString(PyExc_TypeError, "buffer indices must be integer");
PyErr_SetString(PyExc_TypeError, "bytearray indices must be integer");
return -1;
}
@ -757,7 +757,7 @@ bytes_init(PyBytesObject *self, PyObject *args, PyObject *kwds)
return 0;
}
/* Use the modern buffer interface */
/* Use the buffer API */
if (PyObject_CheckBuffer(arg)) {
Py_ssize_t size;
Py_buffer view;
@ -835,15 +835,15 @@ static PyObject *
bytes_repr(PyBytesObject *self)
{
static const char *hexdigits = "0123456789abcdef";
const char *quote_prefix = "buffer(b";
const char *quote_prefix = "bytearray(b";
const char *quote_postfix = ")";
Py_ssize_t length = Py_Size(self);
/* 9 prefix + 2 postfix */
size_t newsize = 11 + 4 * length;
/* 14 == strlen(quote_prefix) + 2 + strlen(quote_postfix) */
size_t newsize = 14 + 4 * length;
PyObject *v;
if (newsize > PY_SSIZE_T_MAX || newsize / 4 - 2 != length) {
if (newsize > PY_SSIZE_T_MAX || newsize / 4 - 3 != length) {
PyErr_SetString(PyExc_OverflowError,
"buffer object is too large to make repr");
"bytearray object is too large to make repr");
return NULL;
}
v = PyUnicode_FromUnicode(NULL, newsize);
@ -921,7 +921,7 @@ bytes_str(PyObject *op)
{
if (Py_BytesWarningFlag) {
if (PyErr_WarnEx(PyExc_BytesWarning,
"str() on a buffer instance", 1))
"str() on a bytearray instance", 1))
return NULL;
}
return bytes_repr((PyBytesObject*)op);
@ -943,7 +943,7 @@ bytes_richcompare(PyObject *self, PyObject *other, int op)
PyObject_IsInstance(other, (PyObject*)&PyUnicode_Type)) {
if (Py_BytesWarningFlag && op == Py_EQ) {
if (PyErr_WarnEx(PyExc_BytesWarning,
"Comparsion between buffer and string", 1))
"Comparsion between bytearray and string", 1))
return NULL;
}
@ -1335,7 +1335,7 @@ bytes_endswith(PyBytesObject *self, PyObject *args)
PyDoc_STRVAR(translate__doc__,
"B.translate(table[, deletechars]) -> buffer\n\
"B.translate(table[, deletechars]) -> bytearray\n\
\n\
Return a copy of B, where all characters occurring in the\n\
optional argument deletechars are removed, and the remaining\n\
@ -2183,7 +2183,7 @@ split_whitespace(const char *s, Py_ssize_t len, Py_ssize_t maxcount)
}
PyDoc_STRVAR(split__doc__,
"B.split([sep[, maxsplit]]) -> list of buffer\n\
"B.split([sep[, maxsplit]]) -> list of bytearray\n\
\n\
Return a list of the sections in B, using sep as the delimiter.\n\
If sep is not given, B is split on ASCII whitespace characters\n\
@ -2292,7 +2292,7 @@ PyDoc_STRVAR(partition__doc__,
\n\
Searches for the separator sep in B, and returns the part before it,\n\
the separator itself, and the part after it. If the separator is not\n\
found, returns B and two empty buffer.");
found, returns B and two empty bytearray objects.");
static PyObject *
bytes_partition(PyBytesObject *self, PyObject *sep_obj)
@ -2320,7 +2320,7 @@ PyDoc_STRVAR(rpartition__doc__,
Searches for the separator sep in B, starting at the end of B,\n\
and returns the part before it, the separator itself, and the\n\
part after it. If the separator is not found, returns two empty\n\
buffer objects and B.");
bytearray objects and B.");
static PyObject *
bytes_rpartition(PyBytesObject *self, PyObject *sep_obj)
@ -2417,7 +2417,7 @@ rsplit_whitespace(const char *s, Py_ssize_t len, Py_ssize_t maxcount)
}
PyDoc_STRVAR(rsplit__doc__,
"B.rsplit(sep[, maxsplit]) -> list of buffer\n\
"B.rsplit(sep[, maxsplit]) -> list of bytearray\n\
\n\
Return a list of the sections in B, using sep as the delimiter,\n\
starting at the end of B and working to the front.\n\
@ -2530,7 +2530,7 @@ bytes_reverse(PyBytesObject *self, PyObject *unused)
PyDoc_STRVAR(insert__doc__,
"B.insert(index, int) -> None\n\
\n\
Insert a single item into the buffer before the given index.");
Insert a single item into the bytearray before the given index.");
static PyObject *
bytes_insert(PyBytesObject *self, PyObject *args)
{
@ -2677,7 +2677,7 @@ rstrip_helper(unsigned char *myptr, Py_ssize_t mysize,
}
PyDoc_STRVAR(strip__doc__,
"B.strip([bytes]) -> buffer\n\
"B.strip([bytes]) -> bytearray\n\
\n\
Strip leading and trailing bytes contained in the argument.\n\
If the argument is omitted, strip ASCII whitespace.");
@ -2713,7 +2713,7 @@ bytes_strip(PyBytesObject *self, PyObject *args)
}
PyDoc_STRVAR(lstrip__doc__,
"B.lstrip([bytes]) -> buffer\n\
"B.lstrip([bytes]) -> bytearray\n\
\n\
Strip leading bytes contained in the argument.\n\
If the argument is omitted, strip leading ASCII whitespace.");
@ -2746,7 +2746,7 @@ bytes_lstrip(PyBytesObject *self, PyObject *args)
}
PyDoc_STRVAR(rstrip__doc__,
"B.rstrip([bytes]) -> buffer\n\
"B.rstrip([bytes]) -> bytearray\n\
\n\
Strip trailing bytes contained in the argument.\n\
If the argument is omitted, strip trailing ASCII whitespace.");
@ -2815,7 +2815,7 @@ bytes_alloc(PyBytesObject *self)
PyDoc_STRVAR(join_doc,
"B.join(iterable_of_bytes) -> bytes\n\
\n\
Concatenates any number of buffer objects, with B in between each pair.");
Concatenates any number of bytearray objects, with B in between each pair.");
static PyObject *
bytes_join(PyBytesObject *self, PyObject *it)
@ -2888,11 +2888,11 @@ bytes_join(PyBytesObject *self, PyObject *it)
}
PyDoc_STRVAR(fromhex_doc,
"buffer.fromhex(string) -> buffer\n\
"bytearray.fromhex(string) -> bytearray\n\
\n\
Create a buffer object from a string of hexadecimal numbers.\n\
Create a bytearray object from a string of hexadecimal numbers.\n\
Spaces between two numbers are accepted.\n\
Example: buffer.fromhex('B9 01EF') -> buffer(b'\\xb9\\x01\\xef').");
Example: bytearray.fromhex('B9 01EF') -> bytearray(b'\\xb9\\x01\\xef').");
static int
hex_digit_to_int(Py_UNICODE c)
@ -3065,27 +3065,27 @@ bytes_methods[] = {
};
PyDoc_STRVAR(bytes_doc,
"buffer(iterable_of_ints) -> buffer.\n\
buffer(string, encoding[, errors]) -> buffer.\n\
buffer(bytes_or_buffer) -> mutable copy of bytes_or_buffer.\n\
buffer(memory_view) -> buffer.\n\
"bytearray(iterable_of_ints) -> bytearray.\n\
bytearray(string, encoding[, errors]) -> bytearray.\n\
bytearray(bytes_or_bytearray) -> mutable copy of bytes_or_bytearray.\n\
bytearray(memory_view) -> bytearray.\n\
\n\
Construct an mutable buffer object from:\n\
Construct an mutable bytearray object from:\n\
- an iterable yielding integers in range(256)\n\
- a text string encoded using the specified encoding\n\
- a bytes or a buffer object\n\
- a bytes or a bytearray object\n\
- any object implementing the buffer API.\n\
\n\
buffer(int) -> buffer.\n\
bytearray(int) -> bytearray.\n\
\n\
Construct a zero-initialized buffer of the given length.");
Construct a zero-initialized bytearray of the given length.");
static PyObject *bytes_iter(PyObject *seq);
PyTypeObject PyBytes_Type = {
PyVarObject_HEAD_INIT(&PyType_Type, 0)
"buffer",
"bytearray",
sizeof(PyBytesObject),
0,
(destructor)bytes_dealloc, /* tp_dealloc */
@ -3193,7 +3193,7 @@ static PyMethodDef bytesiter_methods[] = {
PyTypeObject PyBytesIter_Type = {
PyVarObject_HEAD_INIT(&PyType_Type, 0)
"bytesiterator", /* tp_name */
"bytearray_iterator", /* tp_name */
sizeof(bytesiterobject), /* tp_basicsize */
0, /* tp_itemsize */
/* methods */

View File

@ -3431,7 +3431,7 @@ static PyMethodDef striter_methods[] = {
PyTypeObject PyStringIter_Type = {
PyVarObject_HEAD_INIT(&PyType_Type, 0)
"striterator", /* tp_name */
"bytes_iterator", /* tp_name */
sizeof(striterobject), /* tp_basicsize */
0, /* tp_itemsize */
/* methods */

View File

@ -9233,7 +9233,7 @@ static PyMethodDef unicodeiter_methods[] = {
PyTypeObject PyUnicodeIter_Type = {
PyVarObject_HEAD_INIT(&PyType_Type, 0)
"unicodeiterator", /* tp_name */
"unicode_iterator", /* tp_name */
sizeof(unicodeiterobject), /* tp_basicsize */
0, /* tp_itemsize */
/* methods */

View File

@ -1879,7 +1879,7 @@ _PyBuiltin_Init(void)
SETBUILTIN("True", Py_True);
SETBUILTIN("bool", &PyBool_Type);
SETBUILTIN("memoryview", &PyMemoryView_Type);
SETBUILTIN("buffer", &PyBytes_Type);
SETBUILTIN("bytearray", &PyBytes_Type);
SETBUILTIN("bytes", &PyString_Type);
SETBUILTIN("classmethod", &PyClassMethod_Type);
#ifndef WITHOUT_COMPLEX