File: cstruct.c

package info (click to toggle)
psyco-doc 1.6-1
  • links: PTS
  • area: contrib
  • in suites: lenny
  • size: 1,832 kB
  • ctags: 3,236
  • sloc: ansic: 23,895; python: 5,646; perl: 1,309; makefile: 153
file content (93 lines) | stat: -rw-r--r-- 2,104 bytes parent folder | download | duplicates (7)
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
#include "cstruct.h"


DEFINEFN
PyObject* PyCStruct_New(size_t size, destructor d)
{
	cstruct_header_t* cs;
	cs = (cstruct_header_t*) PyObject_Malloc(size);
	if (cs == NULL)
		OUT_OF_MEMORY();
	PyObject_INIT(cs, &PyCStruct_Type);
	cs->cs_destructor = d;
	cs->cs_key = NULL;
	return (PyObject*) cs;
}

static void cstruct_dealloc(cstruct_header_t* cs)
{
	if (cs->cs_destructor != NULL)
		cs->cs_destructor((PyObject*) cs);
	Py_XDECREF(cs->cs_key);
	PyObject_Del((PyObject*) cs);
}

static long cstruct_hash(cstruct_header_t* cs)
{
	/* loosing high bits is fine. This can't be -1 */
	if (cs->cs_key == NULL)
		return (long)cs;
	else
		return (long)cs->cs_key;
}

static PyObject* cstruct_richcmp(cstruct_header_t* o1, cstruct_header_t* o2,
				 int op)
{
	int c;
	PyObject* result;
	char* k1 = o1->cs_key ? (char*) o1->cs_key : (char*) o1;
	char* k2 = o2->cs_key ? (char*) o2->cs_key : (char*) o2;
	switch (op) {
	case Py_EQ:	c = k1 == k2;	break;
	case Py_NE:	c = k1 != k2;	break;
	case Py_LT:	c = k1 <  k2;	break;
	case Py_LE:	c = k1 <= k2;	break;
	case Py_GT:	c = k1 >  k2;	break;
	case Py_GE:	c = k1 >= k2;	break;
	default:
		Py_INCREF(Py_NotImplemented);
		return Py_NotImplemented;
	}
	result = c ? Py_True : Py_False;
	Py_INCREF(result);
	return result;
}


DEFINEVAR
PyTypeObject PyCStruct_Type = {
	PyObject_HEAD_INIT(NULL)
	0,					/*ob_size*/
	"CStruct",				/*tp_name*/
	sizeof(cstruct_header_t) /* + ??? */,	/*tp_basicsize*/
	0,					/*tp_itemsize*/
	/* methods */
	(destructor)cstruct_dealloc,		/*tp_dealloc*/
	0,					/*tp_print*/
	0,					/*tp_getattr*/
	0,					/*tp_setattr*/
	0,					/*tp_compare*/
	0,					/*tp_repr*/
	0,					/*tp_as_number*/
	0,					/*tp_as_sequence*/
	0,					/*tp_as_mapping*/
	(hashfunc)cstruct_hash,			/*tp_hash*/
	0,					/*tp_call*/
	0,					/*tp_str*/
	0,					/*tp_getattro*/
	0,					/*tp_setattro*/
	0,					/*tp_as_buffer*/
	Py_TPFLAGS_DEFAULT,			/*tp_flags*/
	0,					/*tp_doc*/
	0,					/*tp_traverse*/
	0,					/*tp_clear*/
	(richcmpfunc)cstruct_richcmp,		/*tp_richcompare*/
};


INITIALIZATIONFN
void psyco_cstruct_init(void)
{
	PyCStruct_Type.ob_type = &PyType_Type;
}