Commits

Nick Coghlan committed 83c13c2

Add special casing in bytes() and bytearray()

Comments (0)

Files changed (3)

Lib/test/test_bytes.py

         b = self.type2test(b'hello')
         self.assertEqual(byte(b[0]), b'h')
         self.assertEqual(list(map(byte, b)), [b'h',b'e',b'l',b'l',b'o'])
+        self.assertEqual(bytes(b[0]), b'h')
+        self.assertEqual(list(map(bytes, b)), [b'h',b'e',b'l',b'l',b'o'])
+        self.assertEqual(bytearray(b[0]), bytearray(b'h'))
+        self.assertEqual(list(map(bytes, b)),
+                         list(map(bytearray, [b'h',b'e',b'l',b'l',b'o'])))
 
     def test_numeric_indexing_and_iteration(self):
         b = self.type2test(b'hello')

Objects/bytearrayobject.c

         PyErr_SetString(PyExc_ValueError, "negative count");
         return -1;
     }
+    else if (Py_TYPE(arg) == &_PyBytesLong_Type) {
+        /* We special case the type returned by bytes indexing & iteration */
+        if (count > 255) {
+            PyErr_SetString(PyExc_ValueError, "bytes value out of range");
+            return -1;
+        }
+        if (PyByteArray_Resize((PyObject *)self, 1))
+            return -1;
+        PyByteArray_AS_STRING(self)[0] = (char) (count & 0xFF);
+        return 0;
+    }
     else {
         if (count > 0) {
             if (PyByteArray_Resize((PyObject *)self, count))

Objects/bytesobject.c

         PyErr_SetString(PyExc_ValueError, "negative count");
         return NULL;
     }
+    else if (Py_TYPE(x) == &_PyBytesLong_Type) {
+        /* We special case the type returned by bytes indexing & iteration */
+        char *buf;
+        if (size > 255) {
+            PyErr_SetString(PyExc_ValueError, "bytes value out of range");
+            return NULL;
+        }
+        new = PyBytes_FromStringAndSize(NULL, 1);
+        if (new == NULL)
+            return NULL;
+        buf = PyBytes_AS_STRING(new);
+        buf[0] = (char) (size & 0xFF);
+        return new;
+    }
     else {
+        /* PEP 367 warning would go here... */
         new = _PyBytes_FromSize(size, 1);
         if (new == NULL)
             return NULL;