⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 arraymodule.c

📁 python s60 1.4.5版本的源代码
💻 C
📖 第 1 页 / 共 3 页
字号:
\n\
Read n objects from the file object f and append them to the end of the\n\
array.  Also called as read.";


static PyObject *
array_tofile(arrayobject *self, PyObject *args)
{
	PyObject *f;
	FILE *fp;
        if (!PyArg_ParseTuple(args, "O:tofile", &f))
		return NULL;
	fp = PyFile_AsFile(f);
	if (fp == NULL) {
		PyErr_SetString(PyExc_TypeError, "arg must be open file");
		return NULL;
	}
	if (self->ob_size > 0) {
		if (fwrite(self->ob_item, self->ob_descr->itemsize,
			   self->ob_size, fp) != (size_t)self->ob_size) {
			PyErr_SetFromErrno(PyExc_IOError);
			clearerr(fp);
			return NULL;
		}
	}
	Py_INCREF(Py_None);
	return Py_None;
}

static char tofile_doc [] =
"tofile(f)\n\
\n\
Write all items (as machine values) to the file object f.  Also called as\n\
write.";


static PyObject *
array_fromlist(arrayobject *self, PyObject *args)
{
	int n;
	PyObject *list;
	int itemsize = self->ob_descr->itemsize;
        if (!PyArg_ParseTuple(args, "O:fromlist", &list))
		return NULL;
	if (!PyList_Check(list)) {
		PyErr_SetString(PyExc_TypeError, "arg must be list");
		return NULL;
	}
	n = PyList_Size(list);
	if (n > 0) {
		char *item = self->ob_item;
		int i;
		PyMem_RESIZE(item, char, (self->ob_size + n) * itemsize);
		if (item == NULL) {
			PyErr_NoMemory();
			return NULL;
		}
		self->ob_item = item;
		self->ob_size += n;
		for (i = 0; i < n; i++) {
			PyObject *v = PyList_GetItem(list, i);
			if ((*self->ob_descr->setitem)(self,
					self->ob_size - n + i, v) != 0) {
				self->ob_size -= n;
				PyMem_RESIZE(item, char,
					          self->ob_size * itemsize);
				self->ob_item = item;
				return NULL;
			}
		}
	}
	Py_INCREF(Py_None);
	return Py_None;
}

static char fromlist_doc [] =
"fromlist(list)\n\
\n\
Append items to array from list.";


static PyObject *
array_tolist(arrayobject *self, PyObject *args)
{
	PyObject *list = PyList_New(self->ob_size);
	int i;
        if (!PyArg_ParseTuple(args, ":tolist"))
                return NULL;
	if (list == NULL)
		return NULL;
	for (i = 0; i < self->ob_size; i++) {
		PyObject *v = getarrayitem((PyObject *)self, i);
		if (v == NULL) {
			Py_DECREF(list);
			return NULL;
		}
		PyList_SetItem(list, i, v);
	}
	return list;
}

static char tolist_doc [] =
"tolist() -> list\n\
\n\
Convert array to an ordinary list with the same items.";


static PyObject *
array_fromstring(arrayobject *self, PyObject *args)
{
	char *str;
	int n;
	int itemsize = self->ob_descr->itemsize;
        if (!PyArg_ParseTuple(args, "s#:fromstring", &str, &n))
		return NULL;
	if (n % itemsize != 0) {
		PyErr_SetString(PyExc_ValueError,
			   "string length not a multiple of item size");
		return NULL;
	}
	n = n / itemsize;
	if (n > 0) {
		char *item = self->ob_item;
		PyMem_RESIZE(item, char, (self->ob_size + n) * itemsize);
		if (item == NULL) {
			PyErr_NoMemory();
			return NULL;
		}
		self->ob_item = item;
		self->ob_size += n;
		memcpy(item + (self->ob_size - n) * itemsize,
		       str, itemsize*n);
	}
	Py_INCREF(Py_None);
	return Py_None;
}

static char fromstring_doc [] =
"fromstring(string)\n\
\n\
Appends items from the string, interpreting it as an array of machine\n\
values,as if it had been read from a file using the fromfile() method).";


static PyObject *
array_tostring(arrayobject *self, PyObject *args)
{
	if (!PyArg_ParseTuple(args, ":tostring"))
		return NULL;
	return PyString_FromStringAndSize(self->ob_item,
				    self->ob_size * self->ob_descr->itemsize);
}

static char tostring_doc [] =
"tostring() -> string\n\
\n\
Convert the array to an array of machine values and return the string\n\
representation.";

PyMethodDef array_methods[] = {
	{"append",	(PyCFunction)array_append,	METH_VARARGS,
	 append_doc},
	{"buffer_info", (PyCFunction)array_buffer_info, METH_VARARGS,
	 buffer_info_doc},
	{"byteswap",	(PyCFunction)array_byteswap,	METH_VARARGS,
	 byteswap_doc},
	{"count",	(PyCFunction)array_count,	METH_VARARGS,
	 count_doc},
	{"extend",      (PyCFunction)array_extend,	METH_VARARGS,
	 extend_doc},
	{"fromfile",	(PyCFunction)array_fromfile,	METH_VARARGS,
	 fromfile_doc},
	{"fromlist",	(PyCFunction)array_fromlist,	METH_VARARGS,
	 fromlist_doc},
	{"fromstring",	(PyCFunction)array_fromstring,	METH_VARARGS,
	 fromstring_doc},
	{"index",	(PyCFunction)array_index,	METH_VARARGS,
	 index_doc},
	{"insert",	(PyCFunction)array_insert,	METH_VARARGS,
	 insert_doc},
	{"pop",		(PyCFunction)array_pop,		METH_VARARGS,
	 pop_doc},
	{"read",	(PyCFunction)array_fromfile,	METH_VARARGS,
	 fromfile_doc},
	{"remove",	(PyCFunction)array_remove,	METH_VARARGS,
	 remove_doc},
	{"reverse",	(PyCFunction)array_reverse,	METH_VARARGS,
	 reverse_doc},
/*	{"sort",	(PyCFunction)array_sort,	METH_VARARGS,
	sort_doc},*/
	{"tofile",	(PyCFunction)array_tofile,	METH_VARARGS,
	 tofile_doc},
	{"tolist",	(PyCFunction)array_tolist,	METH_VARARGS,
	 tolist_doc},
	{"tostring",	(PyCFunction)array_tostring,	METH_VARARGS,
	 tostring_doc},
	{"write",	(PyCFunction)array_tofile,	METH_VARARGS,
	 tofile_doc},
	{NULL,		NULL}		/* sentinel */
};

static PyObject *
array_getattr(arrayobject *a, char *name)
{
	if (strcmp(name, "typecode") == 0) {
		char tc = a->ob_descr->typecode;
		return PyString_FromStringAndSize(&tc, 1);
	}
	if (strcmp(name, "itemsize") == 0) {
		return PyInt_FromLong((long)a->ob_descr->itemsize);
	}
	if (strcmp(name, "__members__") == 0) {
		PyObject *list = PyList_New(2);
		if (list) {
			PyList_SetItem(list, 0,
				       PyString_FromString("typecode"));
			PyList_SetItem(list, 1,
				       PyString_FromString("itemsize"));
			if (PyErr_Occurred()) {
				Py_DECREF(list);
				list = NULL;
			}
		}
		return list;
	}
	return Py_FindMethod(array_methods, (PyObject *)a, name);
}

static int
array_print(arrayobject *a, FILE *fp, int flags)
{
	int ok = 0;
	int i, len;
	PyObject *v;
	len = a->ob_size;
	if (len == 0) {
		fprintf(fp, "array('%c')", a->ob_descr->typecode);
		return ok;
	}
	if (a->ob_descr->typecode == 'c') {
		PyObject *t_empty = PyTuple_New(0);
		fprintf(fp, "array('c', ");
		v = array_tostring(a, t_empty);
		Py_DECREF(t_empty);
		ok = PyObject_Print(v, fp, 0);
		Py_XDECREF(v);
		fprintf(fp, ")");
		return ok;
	}
	fprintf(fp, "array('%c', [", a->ob_descr->typecode);
	for (i = 0; i < len && ok == 0; i++) {
		if (i > 0)
			fprintf(fp, ", ");
		v = (a->ob_descr->getitem)(a, i);
		ok = PyObject_Print(v, fp, 0);
		Py_XDECREF(v);
	}
	fprintf(fp, "])");
	return ok;
}

static PyObject *
array_repr(arrayobject *a)
{
	char buf[256];
	PyObject *s, *t, *comma, *v;
	int i, len;
	len = a->ob_size;
	if (len == 0) {
		PyOS_snprintf(buf, sizeof(buf), "array('%c')",
			      a->ob_descr->typecode);
		return PyString_FromString(buf);
	}
	if (a->ob_descr->typecode == 'c') {
		PyObject *t_empty = PyTuple_New(0);
		PyOS_snprintf(buf, sizeof(buf), "array('c', ");
		s = PyString_FromString(buf);
		v = array_tostring(a, t_empty);
		Py_DECREF(t_empty);
		t = PyObject_Repr(v);
		Py_XDECREF(v);
		PyString_ConcatAndDel(&s, t);
		PyString_ConcatAndDel(&s, PyString_FromString(")"));
		return s;
	}
	PyOS_snprintf(buf, sizeof(buf), "array('%c', [", a->ob_descr->typecode);
	s = PyString_FromString(buf);
	comma = PyString_FromString(", ");
	for (i = 0; i < len && !PyErr_Occurred(); i++) {
		if (i > 0)
			PyString_Concat(&s, comma);
		v = (a->ob_descr->getitem)(a, i);
		t = PyObject_Repr(v);
		Py_XDECREF(v);
		PyString_ConcatAndDel(&s, t);
	}
	Py_XDECREF(comma);
	PyString_ConcatAndDel(&s, PyString_FromString("])"));
	return s;
}

static int
array_buffer_getreadbuf(arrayobject *self, int index, const void **ptr)
{
	if ( index != 0 ) {
		PyErr_SetString(PyExc_SystemError,
				"Accessing non-existent array segment");
		return -1;
	}
	*ptr = (void *)self->ob_item;
	return self->ob_size*self->ob_descr->itemsize;
}

static int
array_buffer_getwritebuf(arrayobject *self, int index, const void **ptr)
{
	if ( index != 0 ) {
		PyErr_SetString(PyExc_SystemError,
				"Accessing non-existent array segment");
		return -1;
	}
	*ptr = (void *)self->ob_item;
	return self->ob_size*self->ob_descr->itemsize;
}

static int
array_buffer_getsegcount(arrayobject *self, int *lenp)
{
	if ( lenp )
		*lenp = self->ob_size*self->ob_descr->itemsize;
	return 1;
}

static PySequenceMethods array_as_sequence = {
	(inquiry)array_length,		        /*sq_length*/
	(binaryfunc)array_concat,               /*sq_concat*/
	(intargfunc)array_repeat,		/*sq_repeat*/
	(intargfunc)array_item,		        /*sq_item*/
	(intintargfunc)array_slice,		/*sq_slice*/
	(intobjargproc)array_ass_item,		/*sq_ass_item*/
	(intintobjargproc)array_ass_slice,	/*sq_ass_slice*/
};

static PyBufferProcs array_as_buffer = {
	(getreadbufferproc)array_buffer_getreadbuf,
	(getwritebufferproc)array_buffer_getwritebuf,
	(getsegcountproc)array_buffer_getsegcount,
};

static PyObject *
a_array(PyObject *self, PyObject *args)
{
	char c;
	PyObject *initial = NULL;
	struct arraydescr *descr;
        if (!PyArg_ParseTuple(args, "c:array", &c)) {
		PyErr_Clear();
                if (!PyArg_ParseTuple(args, "cO:array", &c, &initial))
			return NULL;
		if (!PyList_Check(initial) && !PyString_Check(initial)) {
			PyErr_SetString(PyExc_TypeError,
				 "array initializer must be list or string");
			return NULL;
		}
	}
	for (descr = descriptors; descr->typecode != '\0'; descr++) {
		if (descr->typecode == c) {
			PyObject *a;
			int len;
			if (initial == NULL || !PyList_Check(initial))
				len = 0;
			else
				len = PyList_Size(initial);
			a = newarrayobject(len, descr);
			if (a == NULL)
				return NULL;
			if (len > 0) {
				int i;
				for (i = 0; i < len; i++) {
					PyObject *v =
					         PyList_GetItem(initial, i);
					if (setarrayitem(a, i, v) != 0) {
						Py_DECREF(a);
						return NULL;
					}
				}
			}
			if (initial != NULL && PyString_Check(initial)) {
				PyObject *t_initial = Py_BuildValue("(O)",
								    initial);
				PyObject *v =
					array_fromstring((arrayobject *)a,
							 t_initial);
                                Py_DECREF(t_initial);
				if (v == NULL) {
					Py_DECREF(a);
					return NULL;
				}
				Py_DECREF(v);
			}
			return a;
		}
	}
	PyErr_SetString(PyExc_ValueError,
		"bad typecode (must be c, b, B, h, H, i, I, l, L, f or d)");
	return NULL;
}

static char a_array_doc [] =
"array(typecode [, initializer]) -> array\n\
\n\
Return a new array whose items are restricted by typecode, and\n\
initialized from the optional initializer value, which must be a list\n\
or a string.";

static PyMethodDef a_methods[] = {
	{"array",	a_array, METH_VARARGS, a_array_doc},
	{NULL,		NULL}		/* sentinel */
};

static char module_doc [] =
"This module defines a new object type which can efficiently represent\n\
an array of basic values: characters, integers, floating point\n\
numbers.  Arrays are sequence types and behave very much like lists,\n\
except that the type of objects stored in them is constrained.  The\n\
type is specified at object creation time by using a type code, which\n\
is a single character.  The following type codes are defined:\n\
\n\
    Type code   C Type             Minimum size in bytes \n\
    'c'         character          1 \n\
    'b'         signed integer     1 \n\
    'B'         unsigned integer   1 \n\
    'h'         signed integer     2 \n\
    'H'         unsigned integer   2 \n\
    'i'         signed integer     2 \n\
    'I'         unsigned integer   2 \n\
    'l'         signed integer     4 \n\
    'L'         unsigned integer   4 \n\
    'f'         floating point     4 \n\
    'd'         floating point     8 \n\
\n\
Functions:\n\
\n\
array(typecode [, initializer]) -- create a new array\n\
\n\
Special Objects:\n\
\n\
ArrayType -- type object for array objects\n\
";

static char arraytype_doc [] =
"An array represents basic values and behave very much like lists, except\n\
the type of objects stored in them is constrained.\n\
\n\
Methods:\n\
\n\
append() -- append a new item to the end of the array\n\
buffer_info() -- return information giving the current memory info\n\
byteswap() -- byteswap all the items of the array\n\
count() -- return number of occurences of an object\n\
extend() -- extend array by appending array elements\n\
fromfile() -- read items from a file object\n\
fromlist() -- append items from the list\n\
fromstring() -- append items from the string\n\
index() -- return index of first occurence of an object\n\
insert() -- insert a new item into the array at a provided position\n\
pop() -- remove and return item (default last)\n\
read() -- DEPRECATED, use fromfile()\n\
remove() -- remove first occurence of an object\n\
reverse() -- reverse the order of the items in the array\n\
tofile() -- write all items to a file object\n\
tolist() -- return the array converted to an ordinary list\n\
tostring() -- return the array converted to a string\n\
write() -- DEPRECATED, use tofile()\n\
\n\
Variables:\n\
\n\
typecode -- the typecode character used to create the array\n\
itemsize -- the length in bytes of one array item\n\
";

statichere PyTypeObject Arraytype = {
	PyObject_HEAD_INIT(NULL)
	0,
	"array.array",
	sizeof(arrayobject),
	0,
	(destructor)array_dealloc,		/* tp_dealloc */
	(printfunc)array_print,			/* tp_print */
	(getattrfunc)array_getattr,		/* tp_getattr */
	0,					/* tp_setattr */
	0,					/* tp_compare */
	(reprfunc)array_repr,			/* tp_repr */
	0,					/* tp_as _number*/
	&array_as_sequence,			/* tp_as _sequence*/
	0,					/* tp_as _mapping*/
	0, 					/* tp_hash */
	0,					/* tp_call */
	0,					/* tp_str */
	0,					/* tp_getattro */
	0,					/* tp_setattro */
	&array_as_buffer,			/* tp_as_buffer*/
	Py_TPFLAGS_DEFAULT,			/* tp_flags */
	arraytype_doc,				/* tp_doc */
 	0,					/* tp_traverse */
	0,					/* tp_clear */
	array_richcompare,			/* tp_richcompare */
};

DL_EXPORT(void)
initarray(void)
{
	PyObject *m, *d;

        Arraytype.ob_type = &PyType_Type;
	m = Py_InitModule3("array", a_methods, module_doc);
	d = PyModule_GetDict(m);
	PyDict_SetItemString(d, "ArrayType", (PyObject *)&Arraytype);
	/* No need to check the error here, the caller will do that */
}

⌨️ 快捷键说明

复制代码 Ctrl + C
搜索代码 Ctrl + F
全屏模式 F11
切换主题 Ctrl + Shift + D
显示快捷键 ?
增大字号 Ctrl + =
减小字号 Ctrl + -