forked from biopython/biopython
-
Notifications
You must be signed in to change notification settings - Fork 0
/
triemodule.c
661 lines (568 loc) · 15.9 KB
/
triemodule.c
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
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
#include <Python.h>
#include <marshal.h>
#include "trie.h"
#if PY_VERSION_HEX < 0x02050000
#define Py_ssize_t int
#endif
staticforward PyTypeObject Trie_Type;
typedef struct {
PyObject_HEAD
Trie trie;
} trieobject;
static PyObject*
trie_trie(PyObject* self, PyObject* args)
{
trieobject* trieobj;
Trie trie;
if (!PyArg_ParseTuple(args,":trie"))
return NULL;
if(!(trie = Trie_new()))
return PyErr_NoMemory();
if(!(trieobj = PyObject_New(trieobject, &Trie_Type)))
return NULL;
trieobj->trie = trie;
return (PyObject*)trieobj;
}
static void
_decref_objects(const unsigned char *key, const void *value, void *data)
{
Py_DECREF((PyObject *)value);
}
static void
trie_dealloc(PyObject* self)
{
trieobject *mp = (trieobject *)self;
Trie_iterate(mp->trie, _decref_objects, NULL);
Trie_del(mp->trie);
PyObject_Del(self);
}
static Py_ssize_t
trie_length(trieobject *mp)
{
return Trie_len(mp->trie);
}
static PyObject *
trie_subscript(trieobject *mp, PyObject *py_key)
{
unsigned char *key;
PyObject *py_value;
/* Make sure key is a string. */
if(!PyString_Check(py_key)) {
PyErr_SetString(PyExc_TypeError, "key must be a string");
return NULL;
}
key = (unsigned char *)PyString_AS_STRING(py_key);
py_value = (PyObject *)Trie_get(mp->trie, key);
if(py_value == NULL)
PyErr_SetString(PyExc_KeyError, (char *)key);
else
Py_INCREF(py_value);
return py_value;
}
static int
trie_ass_sub(trieobject *mp, PyObject *py_key, PyObject *py_value)
{
unsigned char *key;
PyObject *py_prev;
/* Make sure key is a string. */
if(!PyString_Check(py_key)) {
PyErr_SetString(PyExc_TypeError, "key must be a string");
return -1;
}
key = (unsigned char *)PyString_AS_STRING((char *)py_key);
/* Check to see whether something already exists at that key. If
there's already an object there, then I will have to remove it.
*/
py_prev = (PyObject *)Trie_get(mp->trie, key);
if(py_prev) {
Py_DECREF(py_prev);
}
/* The client wants to delete a key from a dictionary. The Trie
API doesn't support this, so I will just overwrite it with
NULL. */
if(!py_value) {
/* If the key doesn't exist, raise a KeyError. */
if(!py_prev) {
PyErr_SetString(PyExc_KeyError, (char *)key);
return -1;
}
Trie_set(mp->trie, key, NULL);
}
/* The client wants to set a key in the dictionary. */
else {
Py_INCREF(py_value);
if(Trie_set(mp->trie, key, py_value)) {
PyErr_SetString(PyExc_AssertionError, "error setting trie");
return -1;
}
}
return 0;
}
static char has_key__doc__[] =
"D.has_key(k) -> 1 if D has a key k, else 0";
static PyObject *
trie_has_key(trieobject *mp, PyObject *py_key)
{
unsigned char *key;
int has_key;
/* Make sure key is a string. */
if(!PyString_Check(py_key)) {
PyErr_SetString(PyExc_TypeError, "key must be a string");
return NULL;
}
key = (unsigned char *)PyString_AS_STRING(py_key);
has_key = Trie_has_key(mp->trie, key);
return PyInt_FromLong((long)has_key);
}
static PyObject *
trie_has_key_onearg(trieobject *mp, PyObject *py_args)
{
PyObject *py_arg;
if(!PyArg_ParseTuple(py_args, "O", &py_arg))
return NULL;
return trie_has_key(mp, py_arg);
}
static char has_prefix__doc__[] =
"D.has_prefix(k) -> 1 if D has a prefix k, else 0";
static PyObject *
trie_has_prefix(trieobject *mp, PyObject *py_prefix)
{
unsigned char *prefix;
int has_prefix;
/* Make sure prefix is a string. */
if(!PyString_Check(py_prefix)) {
PyErr_SetString(PyExc_TypeError, "k must be a string");
return NULL;
}
prefix = (unsigned char *)PyString_AS_STRING(py_prefix);
has_prefix = Trie_has_prefix(mp->trie, prefix);
return PyInt_FromLong((long)has_prefix);
}
static PyObject *
trie_has_prefix_onearg(trieobject *mp, PyObject *py_args)
{
PyObject *py_arg;
if(!PyArg_ParseTuple(py_args, "O", &py_arg))
return NULL;
return trie_has_prefix(mp, py_arg);
}
static char with_prefix__doc__[] =
"D.with_prefix(prefix) -> list of D's keys that begins with prefix";
static void
_trie_with_prefix_helper(const unsigned char *key, const void *value,
void *data)
{
PyObject *py_list = (PyObject *)data;
PyObject *py_key;
if(PyErr_Occurred())
return;
if(!(py_key = PyString_FromString((const char *)key)))
return;
PyList_Append(py_list, py_key);
Py_DECREF(py_key);
}
static PyObject *
trie_with_prefix(trieobject *mp, PyObject *py_prefix)
{
unsigned char *prefix;
PyObject *py_list;
/* Make sure prefix is a string. */
if(!PyString_Check(py_prefix)) {
PyErr_SetString(PyExc_TypeError, "k must be a string");
return NULL;
}
prefix = (unsigned char *)PyString_AS_STRING(py_prefix);
if(!(py_list = PyList_New(0)))
return NULL;
Trie_with_prefix(mp->trie, prefix,
_trie_with_prefix_helper, (void *)py_list);
if(PyErr_Occurred()) {
Py_DECREF(py_list);
return NULL;
}
return py_list;
}
static PyObject *
trie_with_prefix_onearg(trieobject *mp, PyObject *py_args)
{
PyObject *py_arg;
if(!PyArg_ParseTuple(py_args, "O", &py_arg))
return NULL;
return trie_with_prefix(mp, py_arg);
}
static char keys__doc__[] =
"D.keys() -> list of D's keys";
static void
_trie_keys_helper(const unsigned char *key, const void *value, void *data)
{
PyObject *py_list = (PyObject *)data;
PyObject *py_key;
if(PyErr_Occurred())
return;
if(!(py_key = PyString_FromString((char *)key)))
return;
PyList_Append(py_list, py_key);
Py_DECREF(py_key);
}
static PyObject *
trie_keys(trieobject *mp)
{
PyObject *py_list;
if(!(py_list = PyList_New(0)))
return NULL;
Trie_iterate(mp->trie, _trie_keys_helper, (void *)py_list);
if(PyErr_Occurred()) {
Py_DECREF(py_list);
return NULL;
}
return py_list;
}
static PyObject *
trie_keys_noargs(trieobject *mp, PyObject *py_args)
{
if(PyTuple_Size(py_args) != 0) {
PyErr_SetString(PyExc_ValueError, "no args expected");
return NULL;
}
return trie_keys(mp);
}
static char values__doc__[] =
"D.values() -> list of D's values";
static void
_trie_values_helper(const unsigned char *key, const void *value, void *data)
{
PyObject *py_list = (PyObject *)data;
if(PyErr_Occurred())
return;
PyList_Append(py_list, (PyObject *)value);
}
static PyObject *
trie_values(trieobject *mp)
{
PyObject *py_list;
if(!(py_list = PyList_New(0)))
return NULL;
Trie_iterate(mp->trie, _trie_values_helper, (void *)py_list);
if(PyErr_Occurred()) {
Py_DECREF(py_list);
return NULL;
}
return py_list;
}
static PyObject *
trie_values_noargs(trieobject *mp, PyObject *py_args)
{
if(PyTuple_Size(py_args) != 0) {
PyErr_SetString(PyExc_ValueError, "no args expected");
return NULL;
}
return trie_values(mp);
}
static char get__doc__[] =
"D.get(k[,d]) -> D[k] if D.has_key(k), else d. d defaults to None.";
static PyObject *
trie_get(trieobject *mp, PyObject *args)
{
unsigned char *key;
PyObject *py_value;
PyObject *py_failobj = Py_None;
if (!PyArg_ParseTuple(args, "s|O:get", &key, &py_failobj))
return NULL;
py_value = (PyObject *)Trie_get(mp->trie, key);
if(!py_value)
py_value = py_failobj;
Py_INCREF(py_value);
return py_value;
}
static char get_approximate__doc__[] =
"D.get_approximate(key, k) -> List of (key, value, mismatches) in D, allowing up to k mismatches in key.";
void
_trie_get_approximate_helper(const unsigned char *key, const void *value,
const int mismatches, void *data)
{
/* Append a tuple of (key, value) to data, which is a PyList. */
PyObject *py_list = (PyObject *)data,
*py_value = (PyObject *)value,
*py_key,
*py_tuple,
*py_mismatches;
if(PyErr_Occurred())
return;
if(!(py_key = PyString_FromString((const char *)key)))
return;
if(!(py_mismatches = PyInt_FromLong(mismatches))) {
Py_DECREF(py_key);
return;
}
Py_INCREF(py_value);
if(!(py_tuple = PyTuple_New(3))) {
Py_DECREF(py_key);
Py_DECREF(py_mismatches);
Py_DECREF(py_value);
return;
}
PyTuple_SetItem(py_tuple, 0, py_key);
PyTuple_SetItem(py_tuple, 1, py_value);
PyTuple_SetItem(py_tuple, 2, py_mismatches);
PyList_Append(py_list, py_tuple);
Py_DECREF(py_tuple);
}
static PyObject *
trie_get_approximate(trieobject *mp, PyObject *args)
{
unsigned char *key;
int k;
PyObject *py_list;
if (!PyArg_ParseTuple(args, "si:get_approximate", &key, &k))
return NULL;
if(!(py_list = PyList_New(0)))
return NULL;
Trie_get_approximate(mp->trie, key, k,
_trie_get_approximate_helper, (void *)py_list);
if(PyErr_Occurred()) {
Py_DECREF(py_list);
return NULL;
}
return py_list;
}
static long
trie_nohash(PyObject *self)
{
PyErr_SetString(PyExc_TypeError, "trie objects are unhashable");
return -1;
}
static PyMappingMethods trie_as_mapping = {
/* The first member of PyMappingMethods was redefined in Python 2.5. */
#if PY_VERSION_HEX < 0x02050000
(inquiry)trie_length, /*mp_length*/
#else
(lenfunc)trie_length, /*mp_length*/
#endif
(binaryfunc)trie_subscript, /*mp_subscript*/
(objobjargproc)trie_ass_sub /*mp_ass_subscript*/
};
static PyMethodDef trieobj_methods[] = {
/* METH_O and METH_NOARGS require Python 2.2.
{"has_key", (PyCFunction)trie_has_key, METH_O,
has_key__doc__},
{"has_prefix", (PyCFunction)trie_has_prefix, METH_O,
has_prefix__doc__},
{"with_prefix", (PyCFunction)trie_with_prefix, METH_O,
with_prefix__doc__},
{"keys", (PyCFunction)trie_keys, METH_NOARGS,
keys__doc__},
{"values", (PyCFunction)trie_values, METH_NOARGS,
values__doc__},
*/
{"has_key", (PyCFunction)trie_has_key_onearg, METH_VARARGS,
has_key__doc__},
{"has_prefix", (PyCFunction)trie_has_prefix_onearg, METH_VARARGS,
has_prefix__doc__},
{"with_prefix", (PyCFunction)trie_with_prefix_onearg, METH_VARARGS,
with_prefix__doc__},
{"keys", (PyCFunction)trie_keys_noargs, METH_VARARGS,
keys__doc__},
{"values", (PyCFunction)trie_values_noargs, METH_VARARGS,
values__doc__},
{"get", (PyCFunction)trie_get, METH_VARARGS,
get__doc__},
{"get_approximate", (PyCFunction)trie_get_approximate, METH_VARARGS,
get_approximate__doc__},
{NULL, NULL} /* sentinel */
};
static PyObject *trie_getattr(PyObject *obj, char *name)
{
return Py_FindMethod(trieobj_methods, (PyObject *)obj, name);
}
static PyTypeObject Trie_Type = {
PyObject_HEAD_INIT(NULL)
0,
"trie",
sizeof(trieobject),
0,
trie_dealloc, /*tp_dealloc*/
0, /*tp_print*/
trie_getattr, /*tp_getattr*/
0, /*tp_setattr*/
0, /*tp_compare*/
0, /*tp_repr*/
0, /*tp_as_number*/
0, /*tp_as_sequence*/
&trie_as_mapping, /*tp_as_mapping*/
trie_nohash, /*tp_hash */
};
static int
_write_to_handle(const void *towrite, const int length, void *handle)
{
PyObject *py_handle = (PyObject *)handle,
*py_retval = NULL;
int success = 0;
if(!length)
return 1;
if(!(py_retval = PyObject_CallMethod(py_handle, "write", "s#",
towrite, length)))
goto _write_to_handle_cleanup;
success = 1;
_write_to_handle_cleanup:
if(py_retval) {
Py_DECREF(py_retval);
}
return success;
}
int _write_value_to_handle(const void *value, void *handle)
{
PyObject *py_value = (PyObject *)value,
*py_marshalled = NULL;
char *marshalled;
Py_ssize_t length;
int success = 0;
#ifdef Py_MARSHAL_VERSION
if(!(py_marshalled =
PyMarshal_WriteObjectToString(py_value, Py_MARSHAL_VERSION)))
goto _write_value_to_handle_cleanup;
#else
if(!(py_marshalled = PyMarshal_WriteObjectToString(py_value)))
goto _write_value_to_handle_cleanup;
#endif
if(PyString_AsStringAndSize(py_marshalled, &marshalled, &length) == -1)
goto _write_value_to_handle_cleanup;
if(!_write_to_handle(&length, sizeof(length), handle))
goto _write_value_to_handle_cleanup;
if (length != (int)length)
goto _write_value_to_handle_cleanup;
if(!_write_to_handle(marshalled, (int)length, handle))
goto _write_value_to_handle_cleanup;
success = 1;
_write_value_to_handle_cleanup:
if(py_marshalled) {
Py_DECREF(py_marshalled);
}
return success;
}
static PyObject *
trie_save(PyObject *self, PyObject *args)
{
PyObject *py_handle,
*py_trie;
trieobject *mp;
if(!PyArg_ParseTuple(args, "OO:save", &py_handle, &py_trie))
return NULL;
mp = (trieobject *)py_trie;
if(!Trie_serialize(mp->trie, _write_to_handle, _write_value_to_handle,
(void *)py_handle)) {
if(!PyErr_Occurred())
PyErr_SetString(PyExc_RuntimeError,
"saving failed for some reason");
return NULL;
}
Py_INCREF(Py_None);
return Py_None;
}
static int
_read_from_handle(void *wasread, const int length, void *handle)
{
PyObject *py_handle = (PyObject *)handle,
*py_retval = NULL;
void *retval;
int success = 0;
PyBufferProcs *buffer;
int segment;
int bytes_read, bytes_left;
if(!length)
return 1;
if(!(py_retval = PyObject_CallMethod(py_handle, "read", "i", length)))
goto _read_from_handle_cleanup;
if(!py_retval->ob_type->tp_as_buffer) {
PyErr_SetString(PyExc_ValueError, "read method should return buffer");
goto _read_from_handle_cleanup;
}
if(!(py_retval->ob_type->tp_flags & Py_TPFLAGS_DEFAULT)) {
PyErr_SetString(PyExc_ValueError, "no bf_getcharbuffer slot");
goto _read_from_handle_cleanup;
}
buffer = py_retval->ob_type->tp_as_buffer;
if(!buffer->bf_getreadbuffer) {
PyErr_SetString(PyExc_ValueError, "no bf_getreadbuffer");
goto _read_from_handle_cleanup;
}
bytes_left = length;
segment = 0;
while(bytes_left > 0) {
if((bytes_read = buffer->bf_getreadbuffer(py_retval,
segment, &retval)) == -1)
goto _read_from_handle_cleanup;
memcpy(wasread, retval, bytes_read);
wasread = (void *)((char *)wasread + bytes_read);
bytes_left -= bytes_read;
segment += 1;
}
success = 1;
_read_from_handle_cleanup:
if(py_retval) {
Py_DECREF(py_retval);
}
return success;
}
#define MAX_KEY_LENGTH 2000
static void *
_read_value_from_handle(void *handle)
{
Py_ssize_t length;
char KEY[MAX_KEY_LENGTH];
if(!_read_from_handle((void *)&length, sizeof(length), (void *)handle))
return NULL;
if(length < 0 || length >= MAX_KEY_LENGTH)
return NULL;
if(!_read_from_handle((void *)KEY, length, (void *)handle))
return NULL;
return PyMarshal_ReadObjectFromString(KEY, length);
}
static PyObject *
trie_load(PyObject *self, PyObject *args)
{
PyObject *py_handle;
Trie trie;
trieobject *trieobj;
if(!PyArg_ParseTuple(args, "O:load", &py_handle))
return NULL;
if(!(trie = Trie_deserialize(_read_from_handle, _read_value_from_handle,
py_handle))) {
if(!PyErr_Occurred())
PyErr_SetString(PyExc_RuntimeError,
"loading failed for some reason");
return NULL;
}
if(!(trieobj = PyObject_New(trieobject, &Trie_Type))) {
Trie_del(trie);
return NULL;
}
trieobj->trie = trie;
return (PyObject *)trieobj;
}
static PyMethodDef trie_methods[] = {
{"trie", trie_trie, METH_VARARGS,
"trie() -> new Trie object."},
{"load", trie_load, METH_VARARGS,
"load(handle) -> trie object"},
{"save", trie_save, METH_VARARGS,
"save(handle, trie), save a trie object to a handle"},
{NULL, NULL, 0, NULL}
};
static char trie__doc__[] =
"\
This module implements a trie data structure. This allows an O(M)\n\
lookup of a string in a dictionary, where M is the length of the\n\
string. It also supports approximate matches.\n\
\n\
Functions:\n\
trie Create a new trie object.\n\
save Save a trie to a handle.\n\
load Load a trie from a handle.\n\
\n\
";
DL_EXPORT(void)
inittrie(void)
{
Trie_Type.ob_type = &PyType_Type;
(void) Py_InitModule3("trie", trie_methods, trie__doc__);
}