comment added
[sympyx.git] / csympy.pyx
bloba4840052f116ef521dbce596c1009cd0db356438
1 cdef extern from "stdlib.h":
2 ctypedef int size_t
3 void *malloc (size_t size)
5 cdef extern from "Python.h":
6 ctypedef void PyObject
7 void Py_INCREF(PyObject *x)
8 void Py_DECREF(PyObject *x)
10 cdef extern from "stdint.h":
11 ctypedef long long int64_t
12 ctypedef int64_t sympyint
14 cdef extern from "glib.h":
15 ctypedef unsigned guint
16 ctypedef void *gconstpointer
17 ctypedef void *gpointer
18 ctypedef int gboolean
19 guint g_int_hash(gconstpointer v)
20 guint g_str_hash(gconstpointer v)
22 ctypedef struct GHashTable
23 ctypedef struct GHashTableIter:
24 pass
25 #guint (*GHashFunc) (gconstpointer key)
26 #gboolean (*GEqualFunc) (gconstpointer a, gconstpointer b)
27 ctypedef void * GHashFunc
28 ctypedef void * GEqualFunc
30 GHashTable *g_hash_table_new(GHashFunc hash_func, GEqualFunc key_equal_func)
31 void g_hash_table_insert(GHashTable *hash_table,
32 gpointer key, gpointer value)
33 gpointer g_hash_table_lookup(GHashTable *hash_table, gconstpointer key)
34 guint g_hash_table_size(GHashTable *hash_table)
35 void g_hash_table_destroy(GHashTable *hash_table)
36 void g_hash_table_iter_init(GHashTableIter *iter, GHashTable *hash_table)
37 gboolean g_hash_table_iter_next(GHashTableIter *iter,
38 gpointer *key, gpointer *value)
40 def int_hash(int v):
41 return g_int_hash(&v)
43 def str_hash(char *v):
44 return g_str_hash(v)
46 cdef class Table:
47 cdef GHashTable *thisptr
49 def __init__(self):
50 self.thisptr = g_hash_table_new(NULL, NULL)
52 def __dealloc__(self):
53 g_hash_table_destroy(self.thisptr)
55 def __setitem__(self, x, y):
56 self.insert(x, y)
58 def __getitem__(self, x):
59 return self.get(x)
61 def __contains__(self, x):
62 try:
63 self.get(x)
64 except KeyError:
65 return False
66 return True
68 def __len__(self):
69 return g_hash_table_size(self.thisptr)
71 def insert(self, key, coeff):
72 g_hash_table_insert(self.thisptr, <gpointer>key, <gpointer>coeff)
73 # Without the following it sometimes segfaults, but maybe the INCREF
74 # should be put at some other place:
75 Py_INCREF(<PyObject *>key)
76 Py_INCREF(<PyObject *>coeff)
78 def get(self, key):
79 cdef gpointer value
80 value = g_hash_table_lookup(self.thisptr, <gconstpointer>key)
81 if value == NULL:
82 raise KeyError(key)
83 return <object>value
85 def iteritems(self):
86 cdef GHashTableIter iter
88 g_hash_table_iter_init (&iter, self.thisptr);
89 cdef gpointer key, value
91 a = []
92 while g_hash_table_iter_next(&iter, &key, &value):
93 a.append((<object>key, <object>value))
94 return a
96 cdef guint my_hash(gconstpointer v):
97 o= <object>v
98 return hash(o)
100 cdef gboolean my_equal(gconstpointer a, gconstpointer b):
101 o1 = <object>a
102 o2 = <object>b
103 return o1 == o2
106 cdef class HashTable(Table):
108 def __init__(self):
109 self.thisptr = g_hash_table_new(&my_hash, &my_equal)