[Python-3000-checkins] r58730 - in python/branches/py3k-pep3137: Lib/test/test_bytes.py Objects/stringobject.c

guido.van.rossum python-3000-checkins at python.org
Wed Oct 31 17:41:08 CET 2007


Author: guido.van.rossum
Date: Wed Oct 31 17:41:08 2007
New Revision: 58730

Modified:
   python/branches/py3k-pep3137/Lib/test/test_bytes.py
   python/branches/py3k-pep3137/Objects/stringobject.c
Log:
Patch 1365 by Christian Heimes.
Implement str8(N) -> s'\0'*N, and a unit test for bytes(N) behavior.


Modified: python/branches/py3k-pep3137/Lib/test/test_bytes.py
==============================================================================
--- python/branches/py3k-pep3137/Lib/test/test_bytes.py	(original)
+++ python/branches/py3k-pep3137/Lib/test/test_bytes.py	Wed Oct 31 17:41:08 2007
@@ -50,6 +50,15 @@
         self.assertRaises(ValueError, bytes, [C(-1)])
         self.assertRaises(ValueError, bytes, [C(256)])
 
+    def test_from_ssize(self):
+        self.assertEqual(bytes(0), b'')
+        self.assertEqual(bytes(1), b'\x00')
+        self.assertEqual(bytes(5), b'\x00\x00\x00\x00\x00')
+        self.assertRaises(ValueError, bytes, -1)
+
+        self.assertEqual(bytes('0', 'ascii'), b'0')
+        self.assertEqual(bytes(b'0'), b'0')
+
     def test_constructor_type_errors(self):
         self.assertRaises(TypeError, bytes, 0.0)
         class C:

Modified: python/branches/py3k-pep3137/Objects/stringobject.c
==============================================================================
--- python/branches/py3k-pep3137/Objects/stringobject.c	(original)
+++ python/branches/py3k-pep3137/Objects/stringobject.c	Wed Oct 31 17:41:08 2007
@@ -2909,6 +2909,26 @@
 		return NULL;
 	}
 
+	/* Is it an int? */
+	size = PyNumber_AsSsize_t(x, PyExc_ValueError);
+	if (size == -1 && PyErr_Occurred()) {
+		PyErr_Clear();
+	}
+	else {
+		if (size < 0) {
+			PyErr_SetString(PyExc_ValueError, "negative count");
+			return NULL;
+		}
+		new = PyString_FromStringAndSize(NULL, size);
+		if (new == NULL) {
+			return NULL;
+		}
+		if (size > 0) {
+			memset(((PyStringObject*)new)->ob_sval, 0, size);
+		}
+		return new;
+	}
+
 	/* Use the modern buffer interface */
 	if (PyObject_CheckBuffer(x)) {
 		Py_buffer view;


More information about the Python-3000-checkins mailing list