File: memorymodule.c

package info (click to toggle)
python-numarray 1.5.2-4
  • links: PTS
  • area: main
  • in suites: lenny
  • size: 8,668 kB
  • ctags: 11,384
  • sloc: ansic: 113,864; python: 22,422; makefile: 197; sh: 11
file content (445 lines) | stat: -rw-r--r-- 11,312 bytes parent folder | download | duplicates (2)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
#include <Python.h>
#include <stdio.h>
#include "arraybase.h"   /* For Int64 */
#include "nummacro.h"

#if defined(_MSC_VER)
#define SIZE_MAX 0x7CFFFFFFL
#elif defined(sun) || defined(__sgi)
#include <limits.h>
#elif defined(__IBMC__)
#include <limits.h>
#define SIZE_MAX ULONG_MAX
#else
#include <inttypes.h>
#endif

#ifndef SIZE_MAX
#define SIZE_MAX ULONG_MAX
#endif

staticforward PyTypeObject MemoryType;

static PyObject *memoryError;

typedef struct {
  PyObject_HEAD
  char     *ptr;
  char     *base;
  Int64     size;
  PyObject *master;
} MemoryObject;

static PyObject *
_new_memory(Int64 size)
{
	MemoryObject *memory;
	unsigned long base, align;

	if (size < 0)
		return PyErr_Format(
			PyExc_ValueError, 
			"new_memory: invalid region size.");
	if (size > SIZE_MAX)
		return PyErr_Format(
			PyExc_MemoryError,
			"new_memory: region size too large for size_t.");
	if (!(memory = PyObject_New(MemoryObject, &MemoryType))) 
		return NULL;

	memory->base = (char *) PyMem_New(
		double, size/sizeof(double) + (size%sizeof(double)!=0) + 1);
	if (!memory->base) {
		PyErr_Format(PyExc_MemoryError, "Couldn't allocate requested memory");
		return NULL;
	}
	base = ((unsigned long) memory->base) / sizeof(double);
	align = (((unsigned long) memory->base) % sizeof(double)) != 0;
	memory->ptr = (char *) ((base+align) * sizeof(double));
	memory->size = size;
	memory->master = NULL;
	return (PyObject *) memory;
}

static void
memory_dealloc(PyObject* self)
{
	MemoryObject *me = (MemoryObject  *) self;
	if (me->master) {
		Py_XDECREF(me->master);
	} else {
		PyMem_Free(me->base);
	}
	PyObject_Del(self);
}

static PyObject *
new_memory(PyObject* self, PyObject* args)
{
	Int64 size;
	if (!PyArg_ParseTuple(args,"L", &size)) 
		return NULL;
	return _new_memory(size);
}

static PyObject *
memory_buffer(PyObject *self, PyObject *args)  /* deprecated */
{
	return new_memory(self, args);
}

static PyObject *
memory_alias(PyObject *master, char *ptr, int size)
{
	MemoryObject *memory;
	if (size < 0)
		return PyErr_Format(
			PyExc_ValueError, "new_memory: invalid region size.");

	if (!(memory = PyObject_New(MemoryObject, &MemoryType)))
		return NULL;
	memory->base = memory->ptr = ptr;
	memory->size = size;
	memory->master = master;
	Py_INCREF(master);
	return (PyObject *) memory;
}

static PyObject *
writeable_buffer(PyObject *self, PyObject *args)
{
  PyObject *ob, *buf;
  int offset = 0;
  int size = Py_END_OF_BUFFER;
  
  if ( !PyArg_ParseTuple(args, "O|ii:writeable_buffer", &ob, &offset, &size) )
    return NULL;
  buf = PyBuffer_FromReadWriteObject(ob, offset, size);
  if (!buf) {
    PyErr_Clear();
    buf = PyObject_CallMethod(ob, "__buffer__", NULL);
    if (!buf) {
	    return PyErr_Format(PyExc_TypeError, 
				"couldn't get writeable buffer from object");
    }
  }
  return buf;
}

static PyObject *
memory_str(PyObject *self)
{
	MemoryObject *me = (MemoryObject *) self;
	return PyString_FromStringAndSize(me->ptr, me->size);
}

static PyObject * 
memory_repr(PyObject *self)
{
	MemoryObject *me = (MemoryObject *) self;
	char buffer[128];
	sprintf(buffer, 
		"<memory at 0x%08lx with size:0x%08lx held by object 0x%08lx aliasing object 0x%08lx>",
		(long) me->ptr, (long) me->size, (long) me, (long) me->master);
	return PyString_FromString(buffer);
}

/* Buffer methods */
static int
memory_getbuf(MemoryObject *self, int idx, void **pp)
{
	if ( idx != 0 ) {
		PyErr_SetString(memoryError,
				"memory objects only support one segment");
		return -1;
	}
	*pp = self->ptr;
	return self->size;
}

static int
memory_getsegcount(MemoryObject *self, int *lenp)
{
	if ( lenp )
		*lenp = self->size;
	return 1;
}

static long 
memory_length(MemoryObject *self)
{
	return self->size;
}

PyObject *
memory_from_string(PyObject *module, PyObject *args)
{
	int    size;
	char  *buffer;
	MemoryObject *memory;

	if (!PyArg_ParseTuple(args, "s#", &buffer, &size))
	  return NULL;

	memory = (MemoryObject *) _new_memory(size);
	if (!memory) return NULL;

	memcpy( memory->ptr, buffer, size);
	return (PyObject *) memory;
}

static PyObject *
memory_reduce(PyObject *self)
{
	PyObject *memory_module, *mdict, *factory, *string;
	MemoryObject *me = (MemoryObject *) self;
	if (!(memory_module = PyImport_ImportModule("numarray.memory")))
		return NULL;
	if (!(mdict = PyModule_GetDict(memory_module)))
		return NULL;
	if (!(factory = PyDict_GetItemString(mdict, "memory_from_string")))
		return PyErr_Format(memoryError, 
				    "can't find memory_from_string");
	if (!(string = PyString_FromStringAndSize(me->ptr, me->size)))
		return NULL;
	return Py_BuildValue("(O(N))", factory, string);
}

static PyObject *
memory_reduce_func(PyObject *module, PyObject *args)
{
  PyObject *memory;
  if (!PyArg_ParseTuple(args, "O", &memory))
    return NULL;
  return memory_reduce(memory);
}

static PyObject *
memory_sq_item(MemoryObject *self, int i)
{
	if (i < 0 || i >= self->size)
		return PyErr_Format(PyExc_IndexError, "index out of range");
	return PyInt_FromLong(self->ptr[i]);
}

/* slice is an alias of the region of the original buffer */
static PyObject *
memory_sq_slice(MemoryObject *self, int i, int j)
{
	if (i < 0) 
		i = 0;
	else if (i > self->size)
		i = self->size;
	if (j < i) 
		j = i;
	else if (j > self->size)
		j = self->size;
	return memory_alias((PyObject *) self, self->ptr+i,  j-i);
}

static int
memory_sq_ass_item(MemoryObject *self, int i, PyObject *obj)
{
	long value;
	
	if ((i < 0) || (i >= self->size)) {
		PyErr_Format(PyExc_IndexError, "index out of range");
		return -1;
	}
	if (PyInt_Check(obj)) {
		value = PyInt_AsLong(obj);
	} else if (PyString_Check(obj)) {
		if (PyString_Size(obj) > 1) {
			PyErr_Format(PyExc_IndexError, "can only assign single char strings");
			return -1;
		}
		value = *PyString_AsString(obj);
	} else {
		PyErr_Format(PyExc_TypeError, "argument must be an int or 1 char string.");
		return -1;
	}
	self->ptr[i] = value;
	return 0;
}

static int
memory_sq_ass_slice(MemoryObject *self, int i, int j, PyObject *obj)
{
	const char *source;

	if (i < 0) 
		i = 0;
	else if (i > self->size)
		i = self->size;
	if (j < i) 
		j = i;
	else if (j > self->size)
		j = self->size;

	if (PyObject_CheckReadBuffer(obj)) {
		int length;
		long rval = PyObject_AsReadBuffer(
			obj, (const void **) &source, &length);
		if (rval < 0)	return -1;
		if (length != j-i) {
			PyErr_Format(PyExc_ValueError, "buffer size mismatch");
			return -1;
		}
		memmove(self->ptr+i, source, length);
		return 0;
	}
	if (PySequence_Check(obj)) {
		long k, length = PySequence_Length(obj);
		if (length < 0) return -1;
		if (length != j-i) {
			PyErr_Format(PyExc_ValueError, "buffer size mismatch");
			return -1;
		}
		for(k=i; k<j; k++) { 
			PyObject *it = PySequence_GetItem(obj, k-i);
			if (!it) return -1;
			if (memory_sq_ass_item(self, k, it) < 0) return -1;
			Py_DECREF(it);
		}
		return 0;
	}
	PyErr_Format(PyExc_TypeError, 
		     "argument must support buffer protocol or be a sequence of ints or 1 char strings");
	return -1;
}

static PySequenceMethods memory_as_sequence = {
	(inquiry)memory_length, /*sq_length*/
	(binaryfunc)0, /*sq_concat*/
	(intargfunc)0, /*sq_repeat*/
	(intargfunc)      memory_sq_item,      /*sq_item*/
	(intintargfunc)   memory_sq_slice,     /*sq_slice*/
	(intobjargproc)   memory_sq_ass_item,  /*sq_ass_item*/
	(intintobjargproc)memory_sq_ass_slice, /*sq_ass_slice*/
};

static PyBufferProcs memory_as_buffer = {
	(getreadbufferproc)memory_getbuf,
	(getwritebufferproc)memory_getbuf,
	(getsegcountproc)memory_getsegcount,
	(getcharbufferproc)memory_getbuf,
};

static PyObject *
memory_copy(MemoryObject *self, PyObject *args)
{
	MemoryObject *other;

	if (!PyArg_ParseTuple(args, ":copy")) return NULL;

	other = (MemoryObject *) _new_memory(self->size);
	if (!other) return NULL;

	memcpy(other->ptr, self->ptr, self->size);

	return (PyObject *) other;
}

static PyObject *
memory_clear(MemoryObject *self, PyObject *args)
{
	if (!PyArg_ParseTuple(args, ":clear")) return NULL;
	memset(self->ptr, 0, self->size);
	Py_INCREF(Py_None);
	return Py_None;
}

static PyObject *
memory_tolist(MemoryObject *self, PyObject  *args)
{
	PyObject *l;
	int i;
	if (!PyArg_ParseTuple(args, ":tolist")) return NULL;
	l = PyList_New(self->size);
	if (!l) return NULL;
	for(i=0; i<self->size; i++) {
		PyObject *o = PyInt_FromLong(((unsigned char *)self->ptr)[i]);
		if (!o) { 
			Py_DECREF(l);
			return NULL;
		}
		if (PyList_SetItem(l, i, o) < 0) {
			Py_DECREF(l);
			return NULL;
		}
	}
	return l;
}

static PyMethodDef memory_methods[] = {
    {"__reduce__", (PyCFunction) memory_reduce, METH_VARARGS,
     "Reduces a memory buffer to (memory.memory_from_string, data_string)."},
    {"copy", (PyCFunction) memory_copy, METH_VARARGS,
     "Returns a copy of the memory buffer"},
    {"clear", (PyCFunction) memory_clear, METH_VARARGS,
     "Sets the contents of a buffer to 0"},
    {"tolist", (PyCFunction) memory_tolist, METH_VARARGS,
     "Returns a list of unsigned char values."},
    { NULL, NULL }   /* sentinel */
};

static PyObject *
memory_getattr(PyObject *obj, char *name)
{
    return Py_FindMethod(memory_methods, (PyObject *)obj, name);
}

static PyTypeObject MemoryType = {
    PyObject_HEAD_INIT(NULL)
    0,
    "numarray.memory.Memory",
    sizeof(MemoryObject),
    1,                           /* per item cost */
    memory_dealloc,              /* tp_dealloc */
    0,                           /* tp_print */
    memory_getattr,              /* tp_getattr */
    0,                           /* tp_setattr */
    0,                           /* tp_compare */
    memory_repr,                 /* tp_repr */
    0,                           /* tp_as_number */
    &memory_as_sequence,         /* tp_as_sequence */
    0,                           /* tp_as_mapping */
    0,                           /* tp_hash */
    0,                           /* tp_call */
    memory_str,                  /* tp_str */
    0,                           /* tp_getattro */
    0,                           /* tp_setattro */
    &memory_as_buffer,           /* tp_as_buffer */
    0,                           /* tp_flags */
    "allocates memory for use by numarray.",           /* tp_doc */
    0,    			 /* tp_traverse */
    0,				 /* tp_clear */
    0				 /* tp_richcompare */
};

static PyMethodDef module_methods[] = {
    {"new_memory", new_memory, METH_VARARGS,
     "Create a new Memory object."},
    {"memory_buffer", memory_buffer, METH_VARARGS,
     "Create a new buffer object based on a Memory object."},
    {"writeable_buffer", writeable_buffer, METH_VARARGS,
     "Create a writeable buffer object referencing another python object"},
    {"memory_from_string", memory_from_string, METH_VARARGS,
     "Factory function to restore a memory object from a string."},
    {"memory_reduce", memory_reduce_func, METH_VARARGS,
     "Function to convert memory into unpickling reduction tuple."},
    {NULL, NULL}    /* sentinel */
};

DL_EXPORT(void)
initmemory(void) 
{
	PyObject *d, *m;
	MemoryType.ob_type = &PyType_Type;
	m = Py_InitModule("memory", module_methods);
	d = PyModule_GetDict(m);
	memoryError = PyErr_NewException("numarray.memory.error", NULL, NULL);
	PyDict_SetItemString(d, "error", memoryError);
	PyDict_SetItemString(d, "MemoryType", (PyObject *) &MemoryType);
	ADD_VERSION(m);
}