diff Modules/_struct.c @ 41812:50dafa22b8a4

Make test_zipfile pass. The zipfile module now does all I/O in binary mode using bytes. (Maybe we should support wrapping a TextIOWrapper around it when text mode reading is requested?) Even the password is a bytes array now. Had to fix py_compile.py to use bytes while I was at it. The _struct needed a patch to support bytes, str8 and str for the 's' and 'p' formats.
author Guido van Rossum <guido@python.org>
date Tue, 22 May 2007 01:29:33 +0000
parents 06145fbc7ab9
children 24b60622b944
line wrap: on
line diff
--- a/Modules/_struct.c	Tue May 22 00:12:45 2007 +0000
+++ b/Modules/_struct.c	Tue May 22 01:29:33 2007 +0000
@@ -1635,27 +1635,57 @@
 		const formatdef *e = code->fmtdef;
 		char *res = buf + code->offset;
 		if (e->format == 's') {
-			if (!PyString_Check(v)) {
+			int isstring;
+			void *p;
+			if (PyUnicode_Check(v)) {
+				v = _PyUnicode_AsDefaultEncodedString(v, NULL);
+				if (v == NULL)
+					return -1;
+			}
+			isstring = PyString_Check(v);
+			if (!isstring && !PyBytes_Check(v)) {
 				PyErr_SetString(StructError,
 						"argument for 's' must be a string");
 				return -1;
 			}
-			n = PyString_GET_SIZE(v);
+			if (isstring) {
+				n = PyString_GET_SIZE(v);
+				p = PyString_AS_STRING(v);
+			}
+			else {
+				n = PyBytes_GET_SIZE(v);
+				p = PyBytes_AS_STRING(v);
+			}
 			if (n > code->size)
 				n = code->size;
 			if (n > 0)
-				memcpy(res, PyString_AS_STRING(v), n);
+				memcpy(res, p, n);
 		} else if (e->format == 'p') {
-			if (!PyString_Check(v)) {
+			int isstring;
+			void *p;
+			if (PyUnicode_Check(v)) {
+				v = _PyUnicode_AsDefaultEncodedString(v, NULL);
+				if (v == NULL)
+					return -1;
+			}
+			isstring = PyString_Check(v);
+			if (!isstring && !PyBytes_Check(v)) {
 				PyErr_SetString(StructError,
 						"argument for 'p' must be a string");
 				return -1;
 			}
-			n = PyString_GET_SIZE(v);
+			if (isstring) {
+				n = PyString_GET_SIZE(v);
+				p = PyString_AS_STRING(v);
+			}
+			else {
+				n = PyBytes_GET_SIZE(v);
+				p = PyBytes_AS_STRING(v);
+			}
 			if (n > (code->size - 1))
 				n = code->size - 1;
 			if (n > 0)
-				memcpy(res + 1, PyString_AS_STRING(v), n);
+				memcpy(res + 1, p, n);
 			if (n > 255)
 				n = 255;
 			*res = Py_SAFE_DOWNCAST(n, Py_ssize_t, unsigned char);