Bug squashing.
[pyke] / util.c
1 /* -*-c-*-
2 *
3 * $Id$
4 *
5 * Miscellaneous utilities (not Catacomb-specific)
6 *
7 * (c) 2005 Straylight/Edgeware
8 */
9
10 /*----- Licensing notice --------------------------------------------------*
11 *
12 * This file is part of the Python interface to Catacomb.
13 *
14 * Catacomb/Python is free software; you can redistribute it and/or modify
15 * it under the terms of the GNU General Public License as published by
16 * the Free Software Foundation; either version 2 of the License, or
17 * (at your option) any later version.
18 *
19 * Catacomb/Python is distributed in the hope that it will be useful,
20 * but WITHOUT ANY WARRANTY; without even the implied warranty of
21 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
22 * GNU General Public License for more details.
23 *
24 * You should have received a copy of the GNU General Public License
25 * along with Catacomb/Python; if not, write to the Free Software Foundation,
26 * Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
27 */
28
29 /*----- Header files ------------------------------------------------------*/
30
31 #include "catacomb-python.h"
32
33 /*----- Conversions -------------------------------------------------------*/
34
35 #define GETU_(n) \
36 PyObject *getu##n(uint##n w) \
37 { \
38 if (w <= MASK##n) \
39 return (PyInt_FromLong(w)); \
40 else \
41 return (PyLong_FromUnsignedLong(w)); \
42 }
43 DOUINTSZ(GETU_)
44
45 PyObject *getbool(int b)
46 {
47 if (b) RETURN_TRUE;
48 else RETURN_FALSE;
49 }
50
51 PyObject *abstract_pynew(PyTypeObject *ty, PyObject *arg, PyObject *kw)
52 {
53 PyErr_SetString(PyExc_TypeError, "can't instantiate this class");
54 return (0);
55 }
56
57 int convulong(PyObject *o, void *pp)
58 {
59 long i;
60 unsigned long *p = pp;
61 PyObject *t;
62
63 if (PyInt_Check(o)) {
64 i = PyInt_AS_LONG(o);
65 if (i < 0) TYERR("must be nonnegative");
66 *p = i;
67 } else {
68 if ((t = PyNumber_Long(o)) == 0) goto end;
69 *p = PyLong_AsUnsignedLong(t);
70 Py_DECREF(t);
71 if (PyErr_Occurred()) goto end;
72 }
73 return (1);
74 end:
75 return (0);
76 }
77
78 #define CONVU_(n) \
79 int convu##n(PyObject *o, void *pp) \
80 { \
81 unsigned long u; \
82 uint##n *p = pp; \
83 \
84 if (!convulong(o, &u)) goto end; \
85 if (u > MASK##n) TYERR("out of range"); \
86 *p = u; \
87 return (1); \
88 end: \
89 return (0); \
90 }
91 DOUINTSZ(CONVU_)
92
93 int convuint(PyObject *o, void *pp)
94 {
95 unsigned long u;
96 unsigned *p = pp;
97
98 if (!convulong(o, &u)) goto end;
99 if (u > UINT_MAX) TYERR("out of range");
100 *p = u;
101 return (1);
102 end:
103 return (0);
104 }
105
106 int convmpw(PyObject *o, void *pp)
107 {
108 unsigned long u;
109 unsigned *p = pp;
110
111 if (!convulong(o, &u)) goto end;
112 if (u > MPW_MAX) TYERR("out of range");
113 *p = u;
114 return (1);
115 end:
116 return (0);
117 }
118
119 int convszt(PyObject *o, void *pp)
120 {
121 unsigned long u;
122 size_t *p = pp;
123
124 if (!convulong(o, &u)) goto end;
125 if (u > ~(size_t)0) TYERR("out of range");
126 *p = u;
127 return (1);
128 end:
129 return (0);
130 }
131
132 int convbool(PyObject *o, void *pp)
133 {
134 *(int *)pp = PyObject_IsTrue(o);
135 return (1);
136 }
137
138 /*----- Type messing ------------------------------------------------------*/
139
140 static const PyTypeObject emptytype = { 0 };
141
142 void *newtype(PyTypeObject *metaty,
143 const PyTypeObject *skel,
144 const char *name)
145 {
146 PyHeapTypeObject *ty =
147 (PyHeapTypeObject *)_PyObject_GC_Malloc(_PyObject_VAR_SIZE(metaty, 0));
148 if (!skel) skel = &emptytype;
149 memcpy(ty, skel, sizeof(*skel));
150 if (ty->type.tp_base) Py_INCREF(ty->type.tp_base);
151 #define COPY(blah) do { \
152 if (ty->type.tp_as_##blah) { \
153 memcpy(&ty->as_##blah, \
154 ty->type.tp_as_##blah, \
155 sizeof(ty->as_##blah)); \
156 ty->type.tp_as_##blah = &ty->as_##blah; \
157 } \
158 } while (0)
159 COPY(number);
160 COPY(sequence);
161 COPY(mapping);
162 COPY(buffer);
163 #undef COPY
164 if (name)
165 ty->name = PyString_FromString(name);
166 else if (ty->type.tp_name)
167 ty->name = PyString_FromString(ty->type.tp_name);
168 if (ty->name)
169 ty->type.tp_name = PyString_AS_STRING(ty->name);
170 PyObject_INIT(&ty->type, metaty);
171 Py_INCREF(metaty);
172 return (ty);
173 }
174
175 PyTypeObject *inittype(PyTypeObject *tyskel)
176 {
177 PyTypeObject *ty = newtype(&PyType_Type, tyskel, 0);
178 ty->tp_flags |= Py_TPFLAGS_HEAPTYPE;
179 PyType_Ready(ty);
180 return (ty);
181 }
182
183 /*----- Constants ---------------------------------------------------------*/
184
185 void setconstants(PyObject *mod, const struct nameval *c)
186 {
187 PyObject *x;
188
189 while (c->name) {
190 if (c->value > LONG_MAX)
191 x = PyLong_FromUnsignedLong(c->value);
192 else
193 x = PyInt_FromLong(c->value);
194 PyModule_AddObject(mod, (/*unconst*/ char *)c->name, x);
195 c++;
196 }
197 }
198
199 /*----- Building method tables --------------------------------------------*/
200
201 DA_DECL(method_v, PyMethodDef);
202 static method_v global_pymethods = DA_INIT;
203 void addmethods(const PyMethodDef *m)
204 {
205 size_t n;
206
207 for (n = 0; m[n].ml_name; n++);
208 DA_ENSURE(&global_pymethods, n);
209 memcpy(DA(&global_pymethods) + DA_LEN(&global_pymethods),
210 m, n * sizeof(*m));
211 DA_EXTEND(&global_pymethods, n);
212 }
213
214 PyMethodDef *donemethods(void)
215 {
216 static const PyMethodDef mzero = { 0 };
217 DA_PUSH(&global_pymethods, mzero);
218 return (DA(&global_pymethods));
219 }
220
221 /*----- Exceptions --------------------------------------------------------*/
222
223 PyObject * mkexc(PyObject *mod, PyObject *base,
224 const char *name, PyMethodDef *mm)
225 {
226 PyObject *nameobj = 0;
227 PyObject *dict = 0;
228 PyObject *exc = 0;
229 PyObject *func = 0;
230 PyObject *meth = 0;
231
232 if ((nameobj = PyString_FromFormat("%s.%s",
233 PyModule_GetName(mod),
234 name)) == 0 ||
235 (dict = PyDict_New()) == 0 ||
236 (exc = PyErr_NewException(PyString_AS_STRING(nameobj),
237 base, dict)) == 0)
238 goto fail;
239
240 if (mm) {
241 while (mm->ml_name) {
242 if ((func = PyCFunction_NewEx(mm, 0, mod)) == 0 ||
243 (meth = PyMethod_New(func, 0, exc)) == 0 ||
244 PyDict_SetItemString(dict, mm->ml_name, meth))
245 goto fail;
246 Py_DECREF(func); func = 0;
247 Py_DECREF(meth); meth = 0;
248 mm++;
249 }
250 }
251
252 done:
253 Py_XDECREF(nameobj);
254 Py_XDECREF(dict);
255 return (exc);
256
257 fail:
258 Py_XDECREF(exc);
259 Py_XDECREF(func);
260 Py_XDECREF(meth);
261 exc = 0;
262 goto done;
263 }
264
265 /*----- Generic dictionary methods ----------------------------------------*/
266
267 static PyTypeObject *itemiter_pytype, *valiter_pytype;
268
269 typedef struct iter_pyobj {
270 PyObject_HEAD
271 PyObject *map;
272 PyObject *i;
273 } iter_pyobj;
274 #define ITER_MAP(o) (((iter_pyobj *)(o))->map)
275 #define ITER_I(o) (((iter_pyobj *)(o))->i)
276
277 static void iter_pydealloc(PyObject *me)
278 { Py_DECREF(ITER_MAP(me)); Py_DECREF(ITER_I(me)); FREEOBJ(me); }
279
280 static PyObject *itemiter_pynext(PyObject *me)
281 {
282 PyObject *k = 0, *v = 0, *rc = 0;
283
284 if ((k = PyIter_Next(ITER_I(me))) != 0 &&
285 (v = PyObject_GetItem(ITER_MAP(me), k)) != 0)
286 rc = Py_BuildValue("(OO)", k, v);
287 Py_XDECREF(k); Py_XDECREF(v);
288 return (rc);
289 }
290
291 static PyTypeObject itemiter_pytype_skel = {
292 PyObject_HEAD_INIT(0) 0, /* Header */
293 "ItemIter", /* @tp_name@ */
294 sizeof(iter_pyobj), /* @tp_basicsize@ */
295 0, /* @tp_itemsize@ */
296
297 iter_pydealloc, /* @tp_dealloc@ */
298 0, /* @tp_print@ */
299 0, /* @tp_getattr@ */
300 0, /* @tp_setattr@ */
301 0, /* @tp_compare@ */
302 0, /* @tp_repr@ */
303 0, /* @tp_as_number@ */
304 0, /* @tp_as_sequence@ */
305 0, /* @tp_as_mapping@ */
306 0, /* @tp_hash@ */
307 0, /* @tp_call@ */
308 0, /* @tp_str@ */
309 0, /* @tp_getattro@ */
310 0, /* @tp_setattro@ */
311 0, /* @tp_as_buffer@ */
312 Py_TPFLAGS_DEFAULT | /* @tp_flags@ */
313 Py_TPFLAGS_BASETYPE,
314
315 /* @tp_doc@ */
316 "Iterates over the items of a mapping.",
317
318 0, /* @tp_traverse@ */
319 0, /* @tp_clear@ */
320 0, /* @tp_richcompare@ */
321 0, /* @tp_weaklistoffset@ */
322 PyObject_SelfIter, /* @tp_iter@ */
323 itemiter_pynext, /* @tp_iternext@ */
324 0, /* @tp_methods@ */
325 0, /* @tp_members@ */
326 0, /* @tp_getset@ */
327 0, /* @tp_base@ */
328 0, /* @tp_dict@ */
329 0, /* @tp_descr_get@ */
330 0, /* @tp_descr_set@ */
331 0, /* @tp_dictoffset@ */
332 0, /* @tp_init@ */
333 PyType_GenericAlloc, /* @tp_alloc@ */
334 abstract_pynew, /* @tp_new@ */
335 0, /* @tp_free@ */
336 0 /* @tp_is_gc@ */
337 };
338
339 static PyObject *valiter_pynext(PyObject *me)
340 {
341 PyObject *k = 0, *rc = 0;
342
343 if ((k = PyIter_Next(ITER_I(me))) != 0)
344 rc = PyObject_GetItem(ITER_MAP(me), k);
345 Py_XDECREF(k);
346 return (rc);
347 }
348
349 static PyTypeObject valiter_pytype_skel = {
350 PyObject_HEAD_INIT(0) 0, /* Header */
351 "ValueIter", /* @tp_name@ */
352 sizeof(iter_pyobj), /* @tp_basicsize@ */
353 0, /* @tp_itemsize@ */
354
355 iter_pydealloc, /* @tp_dealloc@ */
356 0, /* @tp_print@ */
357 0, /* @tp_getattr@ */
358 0, /* @tp_setattr@ */
359 0, /* @tp_compare@ */
360 0, /* @tp_repr@ */
361 0, /* @tp_as_number@ */
362 0, /* @tp_as_sequence@ */
363 0, /* @tp_as_mapping@ */
364 0, /* @tp_hash@ */
365 0, /* @tp_call@ */
366 0, /* @tp_str@ */
367 0, /* @tp_getattro@ */
368 0, /* @tp_setattro@ */
369 0, /* @tp_as_buffer@ */
370 Py_TPFLAGS_DEFAULT | /* @tp_flags@ */
371 Py_TPFLAGS_BASETYPE,
372
373 /* @tp_doc@ */
374 "Iterates over the items of a mapping.",
375
376 0, /* @tp_traverse@ */
377 0, /* @tp_clear@ */
378 0, /* @tp_richcompare@ */
379 0, /* @tp_weaklistoffset@ */
380 PyObject_SelfIter, /* @tp_iter@ */
381 valiter_pynext, /* @tp_iternext@ */
382 0, /* @tp_methods@ */
383 0, /* @tp_members@ */
384 0, /* @tp_getset@ */
385 0, /* @tp_base@ */
386 0, /* @tp_dict@ */
387 0, /* @tp_descr_get@ */
388 0, /* @tp_descr_set@ */
389 0, /* @tp_dictoffset@ */
390 0, /* @tp_init@ */
391 PyType_GenericAlloc, /* @tp_alloc@ */
392 abstract_pynew, /* @tp_new@ */
393 0, /* @tp_free@ */
394 0 /* @tp_is_gc@ */
395 };
396
397 PySequenceMethods gmap_pysequence = {
398 0, /* @sq_length@ */
399 0, /* @sq_concat@ */
400 0, /* @sq_repeat@ */
401 0, /* @sq_item@ */
402 0, /* @sq_slice@ */
403 0, /* @sq_ass_item@ */
404 0, /* @sq_ass_slice@ */
405 PyMapping_HasKey, /* @sq_contains@ */
406 0, /* @sq_inplace_concat@ */
407 0 /* @sq_inplace_repeat@ */
408 };
409
410 int gmap_pysize(PyObject *me)
411 {
412 PyObject *i = 0, *x = 0;
413 int rc = -1;
414 int n = 0;
415
416 if ((i = PyObject_GetIter(me)) == 0) goto done;
417 while ((x = PyIter_Next(i)) != 0) { n++; Py_DECREF(x); x = 0; }
418 if (PyErr_Occurred()) goto done;
419 rc = n;
420 done:
421 Py_XDECREF(i); Py_XDECREF(x);
422 return (rc);
423 }
424
425 PyObject *gmapmeth_has_key(PyObject *me, PyObject *arg)
426 {
427 PyObject *k;
428 if (!PyArg_ParseTuple(arg, "O:has_key", &k)) return (0);
429 return (getbool(PyMapping_HasKey(me, k)));
430 }
431
432 PyObject *gmapmeth_keys(PyObject *me, PyObject *arg)
433 {
434 PyObject *l = 0, *i = 0, *k, *rc = 0;
435 int err;
436
437 if (!PyArg_ParseTuple(arg, ":keys") ||
438 (l = PyList_New(0)) == 0 ||
439 (i = PyObject_GetIter(me)) == 0)
440 goto done;
441 while ((k = PyIter_Next(i)) != 0)
442 { err = PyList_Append(l, k); Py_DECREF(k); if (err) goto done; }
443 if (PyErr_Occurred()) goto done;
444 rc = l; l = 0;
445 done:
446 Py_XDECREF(l); Py_XDECREF(i);
447 return (rc);
448 }
449
450 PyObject *gmapmeth_values(PyObject *me, PyObject *arg)
451 {
452 PyObject *l = 0, *i = 0, *k, *v, *rc = 0;
453 int err = 0;
454
455 if (!PyArg_ParseTuple(arg, ":values") ||
456 (l = PyList_New(0)) == 0 ||
457 (i = PyObject_GetIter(me)) == 0)
458 goto done;
459 while ((k = PyIter_Next(i)) != 0) {
460 if ((v = PyObject_GetItem(me, k)) == 0 ||
461 PyList_Append(l, v))
462 err = -1;
463 Py_DECREF(k); Py_XDECREF(v);
464 if (err) goto done;
465 }
466 if (PyErr_Occurred()) goto done;
467 rc = l; l = 0;
468 done:
469 Py_XDECREF(l); Py_XDECREF(i);
470 return (rc);
471 }
472
473 PyObject *gmapmeth_items(PyObject *me, PyObject *arg)
474 {
475 PyObject *l = 0, *i = 0, *k, *v, *z, *rc = 0;
476 int err = 0;
477
478 if (!PyArg_ParseTuple(arg, ":items") ||
479 (l = PyList_New(0)) == 0 ||
480 (i = PyObject_GetIter(me)) == 0)
481 goto done;
482 while ((k = PyIter_Next(i)) != 0) {
483 z = 0;
484 if ((v = PyObject_GetItem(me, k)) == 0 ||
485 (z = Py_BuildValue("(OO)", k, v)) == 0 ||
486 PyList_Append(l, z))
487 err = -1;
488 Py_DECREF(k); Py_XDECREF(v); Py_XDECREF(z);
489 if (err) goto done;
490 }
491 if (PyErr_Occurred()) goto done;
492 rc = l; l = 0;
493 done:
494 Py_XDECREF(l); Py_XDECREF(i);
495 return (rc);
496 }
497
498 PyObject *gmapmeth_iterkeys(PyObject *me, PyObject *arg)
499 {
500 if (!PyArg_ParseTuple(arg, ":iterkeys")) return (0);
501 return (PyObject_GetIter(me));
502 }
503
504 PyObject *gmapmeth_itervalues(PyObject *me, PyObject *arg)
505 {
506 PyObject *i;
507 iter_pyobj *ii;
508
509 if (!PyArg_ParseTuple(arg, ":itervalues") ||
510 (i = PyObject_GetIter(me)) == 0)
511 return (0);
512 ii = PyObject_NEW(iter_pyobj, valiter_pytype);
513 ii->map = me; Py_INCREF(me);
514 ii->i = i;
515 return ((PyObject *)ii);
516 }
517
518 PyObject *gmapmeth_iteritems(PyObject *me, PyObject *arg)
519 {
520 PyObject *i;
521 iter_pyobj *ii;
522
523 if (!PyArg_ParseTuple(arg, ":iteritems") ||
524 (i = PyObject_GetIter(me)) == 0)
525 return (0);
526 ii = PyObject_NEW(iter_pyobj, itemiter_pytype);
527 ii->map = me; Py_INCREF(me);
528 ii->i = i;
529 return ((PyObject *)ii);
530 }
531
532 PyObject *gmapmeth_clear(PyObject *me, PyObject *arg)
533 {
534 PyObject *i = 0, *k = 0, *rc = 0;
535
536 if (!PyArg_ParseTuple(arg, ":clear") ||
537 (i = PyObject_GetIter(me)) == 0)
538 goto end;
539 while ((k = PyIter_Next(i)) != 0) {
540 PyObject_DelItem(me, k);
541 Py_DECREF(k);
542 }
543 if (PyErr_Occurred()) goto end;
544 rc = me; Py_INCREF(me);
545 end:
546 Py_XDECREF(i);
547 return (rc);
548 }
549
550 static char *def_kwlist[] = { "key", "default", 0 };
551
552 PyObject *gmapmeth_get(PyObject *me, PyObject *arg, PyObject *kw)
553 {
554 PyObject *k, *def = Py_None, *v;
555
556 if (!PyArg_ParseTupleAndKeywords(arg, kw, "OO:get", def_kwlist, &k, &def))
557 return (0);
558 if ((v = PyObject_GetItem(me, k)) != 0) return (v);
559 PyErr_Clear();
560 RETURN_OBJ(def);
561 }
562
563 PyObject *gmapmeth_setdefault(PyObject *me, PyObject *arg, PyObject *kw)
564 {
565 PyObject *k, *def = Py_None, *v;
566
567 if (!PyArg_ParseTupleAndKeywords(arg, kw, "OO:setdefault",
568 def_kwlist, &k, &def))
569 return (0);
570 if ((v = PyObject_GetItem(me, k)) != 0) return (v);
571 PyErr_Clear();
572 if (PyObject_SetItem(me, k, def)) return (0);
573 RETURN_OBJ(def);
574 }
575
576 PyObject *gmapmeth_pop(PyObject *me, PyObject *arg, PyObject *kw)
577 {
578 PyObject *k, *def = 0, *v;
579
580 if (!PyArg_ParseTupleAndKeywords(arg, kw, "OO:pop", def_kwlist, &k, &def))
581 return (0);
582 if ((v = PyObject_GetItem(me, k)) != 0) {
583 PyObject_DelItem(me, k);
584 return (v);
585 }
586 PyErr_Clear();
587 RETURN_OBJ(def);
588 }
589
590 PyObject *gmapmeth_update(PyObject *me, PyObject *arg)
591 {
592 PyObject *map, *i = 0, *k, *v, *rc = 0;
593 int err = 0;
594
595 if (!PyArg_ParseTuple(arg, "O:update", &map) ||
596 (i = PyObject_GetIter(map)) == 0)
597 goto end;
598 while ((k = PyIter_Next(i)) != 0) {
599 if ((v = PyObject_GetItem(map, k)) == 0 ||
600 PyObject_SetItem(me, k, v))
601 err = -1;
602 Py_DECREF(k); Py_XDECREF(v);
603 if (err) goto end;
604 }
605 if (PyErr_Occurred()) goto end;
606 rc = me; Py_INCREF(me);
607 end:
608 Py_XDECREF(i);
609 return (rc);
610 }
611
612 PyObject *gmapmeth_popitem(PyObject *me, PyObject *arg)
613 {
614 PyObject *i = 0, *k = 0, *v = 0, *rc = 0;
615
616 if (!PyArg_ParseTuple(arg, ":popitem") ||
617 (i = PyObject_GetIter(me)))
618 goto end;
619 if ((k = PyIter_Next(i)) == 0) {
620 if (!PyErr_Occurred()) VALERR("popitem(): mapping is empty");
621 goto end;
622 }
623 if ((v = PyObject_GetItem(me, k)) == 0 ||
624 PyObject_DelItem(me, k))
625 goto end;
626 rc = Py_BuildValue("(OO)", k, v);
627 end:
628 Py_XDECREF(i); Py_XDECREF(k); Py_XDECREF(v);
629 return (rc);
630 }
631
632 PyMethodDef gmap_pymethods[] = {
633 GMAP_METHODS
634 { 0 }
635 };
636
637 /*----- Initialization ----------------------------------------------------*/
638
639 void util_init(void)
640 {
641 INITTYPE(itemiter, root);
642 INITTYPE(valiter, root);
643 }
644
645 void util_insert(PyObject *mod)
646 {
647 INSERT("ItemIter", itemiter_pytype);
648 INSERT("ValueIter", valiter_pytype);
649 }
650
651 /*----- That's all, folks -------------------------------------------------*/