chiark / gitweb /
Release 1.1.1.
[mLib-python] / sym.pyx
1 ### -*-pyrex-*-
2 ###
3 ### Symbol table, using universal hashing
4 ###
5 ### (c) 2005 Straylight/Edgeware
6 ###
7
8 ###----- Licensing notice ---------------------------------------------------
9 ###
10 ### This file is part of the Python interface to mLib.
11 ###
12 ### mLib/Python is free software; you can redistribute it and/or modify
13 ### it under the terms of the GNU General Public License as published by
14 ### the Free Software Foundation; either version 2 of the License, or
15 ### (at your option) any later version.
16 ###
17 ### mLib/Python is distributed in the hope that it will be useful,
18 ### but WITHOUT ANY WARRANTY; without even the implied warranty of
19 ### MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
20 ### GNU General Public License for more details.
21 ###
22 ### You should have received a copy of the GNU General Public License
23 ### along with mLib/Python; if not, write to the Free Software Foundation,
24 ### Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
25
26 cdef struct _sym_entry:
27   sym_base _b
28   PyObject *v
29
30 cdef class SymTable (Mapping):
31   """
32   SymTable([DICT], **KW)
33
34   A mapping keyed by strings.
35   """
36   cdef sym_table _t
37   cdef int _init(me) except -1:
38     sym_create(&me._t)
39     return 0
40   cdef void *_find(me, object key, unsigned *f) except NULL:
41     cdef void *p
42     cdef Py_ssize_t n
43     cdef _sym_entry *e
44     PyObject_AsReadBuffer(key, <cvp *>&p, &n)
45     if f:
46       f[0] = 0
47       e = <_sym_entry *>sym_find(&me._t, <char *>p, n, PSIZEOF(e), f)
48       if not f[0]:
49         e.v = NULL
50     else:
51       e = <_sym_entry *>sym_find(&me._t, <char *>p, n, 0, NULL)
52     return <void *>e
53   cdef object _key(me, void *e):
54     return PyString_FromStringAndSize(SYM_NAME(e), SYM_LEN(e))
55   cdef object _value(me, void *e):
56     cdef _sym_entry *ee
57     ee = <_sym_entry *>e
58     Py_INCREF(ee.v)
59     return <object>ee.v
60   cdef void _setval(me, void *e, object val):
61     cdef _sym_entry *ee
62     ee = <_sym_entry *>e
63     if ee.v:
64       Py_DECREF(ee.v)
65     ee.v = <PyObject *>v
66     Py_INCREF(ee.v)
67   cdef void _del(me, void *e):
68     cdef _sym_entry *ee
69     ee = <_sym_entry *>e
70     if ee.v:
71       Py_DECREF(ee.v)
72     sym_remove(&me._t, <void *>ee)
73   cdef _MapIterator _iter(me):
74     return _SymIter(me)
75
76 cdef class _SymIter (_MapIterator):
77   cdef SymTable t
78   cdef sym_iter i
79   def __cinit__(me, SymTable t not None):
80     me.t = t
81     sym_mkiter(&me.i, &me.t._t)
82   cdef void *_next(me):
83     return sym_next(&me.i)
84
85 ###----- That's all, folks --------------------------------------------------