-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathpytricia.c
More file actions
1252 lines (1117 loc) · 39.2 KB
/
pytricia.c
File metadata and controls
1252 lines (1117 loc) · 39.2 KB
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
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*
* This file is part of Pytricia.
* Joel Sommers <jsommers@colgate.edu>
*
* Pytricia is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Pytricia is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with Pytricia. If not, see <http://www.gnu.org/licenses/>.
*/
#include <Python.h>
#include "patricia.h"
#if defined(_WIN32) || defined(_WIN64)
#include <winsock2.h>
#include <ws2tcpip.h>
#pragma comment(lib, "Ws2_32.lib")
#else
#include <arpa/inet.h>
#endif
typedef struct {
PyObject_HEAD
patricia_tree_t *m_tree;
int m_family;
u_short m_raw_output;
} PyTricia;
typedef struct {
PyObject_HEAD
patricia_tree_t *m_tree;
patricia_node_t *m_Xnode;
patricia_node_t *m_Xhead;
patricia_node_t **m_Xstack;
patricia_node_t **m_Xsp;
patricia_node_t *m_Xrn;
PyTricia *m_parent;
} PyTriciaIter;
#if PY_MAJOR_VERSION == 3 && PY_MINOR_VERSION >= 4
static PyObject *ipaddr_module = NULL;
static PyObject *ipaddr_base = NULL;
static PyObject *ipnet_base = NULL;
static int _ipaddr_isset = 0;
#endif
#if PY_MAJOR_VERSION == 3 && PY_MINOR_VERSION >= 4
static void _set_ipaddr_refs(void) {
ipaddr_module = ipaddr_base = ipnet_base = NULL;
if (_ipaddr_isset) {
return;
}
_ipaddr_isset = 1;
// 3.4 introduced ipaddress module. get some static
// references to the module and a base class for type
// checking arguments to various methods.
ipaddr_module = PyImport_ImportModule("ipaddress");
if (ipaddr_module != NULL) {
ipaddr_base = PyObject_GetAttrString(ipaddr_module, "_BaseAddress");
ipnet_base = PyObject_GetAttrString(ipaddr_module, "_BaseNetwork");
if (ipaddr_base == NULL && ipnet_base == NULL) {
Py_DECREF(ipaddr_module);
ipaddr_module = NULL;
}
}
}
#endif
static int
_prefix_convert(int family, const char *addr, prefix_t* prefix) {
int prefixlen = -1;
char addrcopy[128];
if (strlen(addr) < 2) {
return 0;
}
strncpy(addrcopy, addr, 128);
char *slash = strchr(addrcopy, '/');
if (slash != NULL) {
*slash = '\0';
slash++;
if (strlen(slash) > 0) {
prefixlen = (int)strtol(slash, NULL, 10);
}
}
// if family isn't set, infer it
if (family == 0) {
if (strchr(addrcopy, ':')) {
family = AF_INET6;
} else {
family = AF_INET;
}
}
if (family == AF_INET) {
if (prefixlen == -1 || prefixlen < 0 || prefixlen > 32) {
prefixlen = 32;
}
struct in_addr sin;
if (inet_pton(AF_INET, addrcopy, &sin) != 1) {
return 0;
}
return New_Prefix(AF_INET, &sin, prefixlen, prefix);
} else if (family == AF_INET6) {
if (prefixlen == -1 || prefixlen < 0 || prefixlen > 128) {
prefixlen = 128;
}
struct in6_addr sin6;
if (inet_pton(AF_INET6, addrcopy, &sin6) != 1) {
return 0;
}
return New_Prefix(AF_INET6, &sin6, prefixlen, prefix);
} else {
return 0;
}
}
static int
_packed_addr_to_prefix(char *addrbuf, long len, prefix_t* pfx_rv) {
int ret_ok = 0;
if (len == 4) {
ret_ok = New_Prefix(AF_INET, addrbuf, 32, pfx_rv);
} else if (len == 16) {
ret_ok = New_Prefix(AF_INET6, addrbuf, 128, pfx_rv);
} else {
PyErr_SetString(PyExc_ValueError, "Address bytes must be of length 4 or 16");
}
return ret_ok;
}
#if PY_MAJOR_VERSION == 3
static int
_bytes_to_prefix(PyObject *key, prefix_t* pfx_rv) {
char *addrbuf = NULL;
Py_ssize_t len = 0;
if (PyBytes_AsStringAndSize(key, &addrbuf, &len) < 0) {
PyErr_SetString(PyExc_ValueError, "Error decoding bytes");
return 0;
}
return _packed_addr_to_prefix(addrbuf, len, pfx_rv);
}
#endif
static int
_key_object_to_prefix(PyObject *key, prefix_t* pfx_rv) {
int ret_ok = 0;
#if PY_MAJOR_VERSION == 3
#if PY_MINOR_VERSION >= 4
if (!_ipaddr_isset) {
_set_ipaddr_refs();
}
#endif
if (PyUnicode_Check(key)) {
int rv = PyUnicode_READY(key);
if (rv < 0) {
PyErr_SetString(PyExc_ValueError, "Error parsing string prefix");
return 0;
}
const char* temp = PyUnicode_AsUTF8(key);
if (temp == 0) {
PyErr_SetString(PyExc_ValueError, "Error parsing string prefix");
return 0;
}
if (strchr(temp, '.') || strchr(temp, ':')) {
ret_ok = _prefix_convert(0, temp, pfx_rv);
} else {
PyErr_SetString(PyExc_ValueError, "Invalid key type");
return 0;
}
} else if (PyLong_Check(key)) {
unsigned long packed_addr = htonl(PyLong_AsUnsignedLong(key));
ret_ok = New_Prefix(AF_INET, &packed_addr, 32, pfx_rv);
} else if (PyBytes_Check(key)) {
ret_ok = _bytes_to_prefix(key, pfx_rv);
} else if (PyTuple_Check(key)) {
PyObject* value = PyTuple_GetItem(key, 0);
PyObject* size = PyTuple_GetItem(key, 1);
if (!PyBytes_Check(value)) {
PyErr_SetString(PyExc_ValueError, "Invalid key tuple value type");
return 0;
}
Py_ssize_t slen = PyBytes_Size(value);
if (slen != 4 && slen != 16) {
PyErr_SetString(PyExc_ValueError, "Invalid key tuple value");
return 0;
}
ret_ok = _bytes_to_prefix(value, pfx_rv);
if (ret_ok) {
if (!PyLong_Check(size)) {
PyErr_SetString(PyExc_ValueError, "Invalid key tuple size type");
return 0;
}
unsigned long bitlen = PyLong_AsUnsignedLong(size);
if (bitlen < pfx_rv->bitlen)
pfx_rv->bitlen = bitlen;
}
}
#if PY_MINOR_VERSION >= 4
// do we have an IPv4/6Address or IPv4/6Network object (ipaddress
// module added in Python 3.4
else if (ipnet_base && PyObject_IsInstance(key, ipnet_base)) {
PyObject *netaddr = PyObject_GetAttrString(key, "network_address");
if (netaddr) {
PyObject *packed = PyObject_GetAttrString(netaddr, "packed");
if (packed && PyBytes_Check(packed)) {
ret_ok = _bytes_to_prefix(packed, pfx_rv);
PyObject *prefixlen = PyObject_GetAttrString(key, "prefixlen");
if (prefixlen && PyLong_Check(prefixlen)) {
long bitlen = PyLong_AsLong(prefixlen);
pfx_rv->bitlen = bitlen;
Py_DECREF(prefixlen);
}
Py_DECREF(packed);
} else {
PyErr_SetString(PyExc_ValueError, "Error getting raw representation of IPNetwork");
}
Py_DECREF(netaddr);
} else {
PyErr_SetString(PyExc_ValueError, "Couldn't get network address from IPNetwork");
}
} else if (ipaddr_base && PyObject_IsInstance(key, ipaddr_base)) {
PyObject *packed = PyObject_GetAttrString(key, "packed");
if (packed && PyBytes_Check(packed)) {
ret_ok = _bytes_to_prefix(packed, pfx_rv);
Py_DECREF(packed);
} else {
PyErr_SetString(PyExc_ValueError, "Error getting raw representation of IPAddress");
}
}
#endif
else {
PyErr_SetString(PyExc_ValueError, "Invalid key type");
}
#else //python2
if (PyString_Check(key)) {
char* temp = PyString_AsString(key);
Py_ssize_t slen = PyString_Size(key);
if (strchr(temp, '.') || strchr(temp, ':')) {
ret_ok = _prefix_convert(0, temp, pfx_rv);
} else if (slen == 4 || slen == 16) {
ret_ok = _packed_addr_to_prefix(temp, slen, pfx_rv);
} else {
PyErr_SetString(PyExc_ValueError, "Invalid key type");
}
} else if (PyLong_Check(key) || PyInt_Check(key)) {
unsigned long packed_addr = htonl(PyInt_AsUnsignedLongMask(key));
ret_ok = New_Prefix(AF_INET, &packed_addr, 32, pfx_rv);
} else if (PyTuple_Check(key)) {
PyObject* value = PyTuple_GetItem(key, 0);
PyObject* size = PyTuple_GetItem(key, 1);
if (!PyString_Check(value)) {
PyErr_SetString(PyExc_ValueError, "Invalid key tuple value type");
return 0;
}
Py_ssize_t slen = PyString_Size(value);
if (slen != 4 && slen != 16) {
PyErr_SetString(PyExc_ValueError, "Invalid key tuple value");
return 0;
}
char* temp = PyString_AsString(value);
ret_ok = _packed_addr_to_prefix(temp, slen, pfx_rv);
if (pfx_rv) {
if (!PyLong_Check(size) && !PyInt_Check(size)) {
PyErr_SetString(PyExc_ValueError, "Invalid key tuple size type");
return 0;
}
unsigned long bitlen = PyInt_AsLong(size);
if (bitlen < pfx_rv->bitlen)
pfx_rv->bitlen = bitlen;
}
} else {
PyErr_SetString(PyExc_ValueError, "Invalid key type");
}
#endif
return ret_ok;
}
static PyObject *
_prefix_to_key_object(prefix_t* prefix, int raw_output) {
if (raw_output) {
int addr_size;
char *addr = (char*) prefix_touchar(prefix);
if (prefix->family == AF_INET6) {
addr_size = 16;
} else {
addr_size = 4;
}
PyObject* value;
#if PY_MAJOR_VERSION == 3
value = PyBytes_FromStringAndSize(addr, addr_size);
#else
value = PyString_FromStringAndSize(addr, addr_size);
#endif
PyObject* tuple;
tuple = Py_BuildValue("(Oi)", value, prefix->bitlen);
Py_XDECREF(value);
return tuple;
}
char buffer[64];
prefix_toa2x(prefix, buffer, 1);
return Py_BuildValue("s", buffer);
}
static void
pytricia_xdecref(void *data) {
Py_XDECREF((PyObject*)data);
}
static void
pytricia_dealloc(PyTricia* self) {
if (self) {
Destroy_Patricia(self->m_tree, pytricia_xdecref);
Py_TYPE(self)->tp_free((PyObject*)self);
}
}
static PyObject *
pytricia_new(PyTypeObject *type, PyObject *args, PyObject *kwds) {
PyTricia *self;
self = (PyTricia*)type->tp_alloc(type, 0);
if (self != NULL) {
self->m_tree = NULL;
}
return (PyObject *)self;
}
static int
pytricia_init(PyTricia *self, PyObject *args, PyObject *kwds) {
int prefixlen = 32;
int family = AF_INET;
PyObject* raw_output = NULL;
if (!PyArg_ParseTuple(args, "|iiO", &prefixlen, &family, &raw_output)) {
self->m_tree = New_Patricia(1); // need to have *something* to dealloc
PyErr_SetString(PyExc_ValueError, "Error parsing prefix length or address family");
return -1;
}
if (prefixlen < 0 || prefixlen > PATRICIA_MAXBITS) {
self->m_tree = New_Patricia(1); // need to have *something* to dealloc
PyErr_SetString(PyExc_ValueError, "Invalid number of maximum bits; must be between 0 and 128, inclusive");
return -1;
}
if (!(family == AF_INET || family == AF_INET6)) {
self->m_tree = New_Patricia(1); // need to have *something* to dealloc
PyErr_SetString(PyExc_ValueError, "Invalid address family; must be AF_INET (2) or AF_INET6 (30)");
return -1;
}
self->m_tree = New_Patricia(prefixlen);
self->m_family = family;
self->m_raw_output = raw_output && PyObject_IsTrue(raw_output);
if (self->m_tree == NULL) {
return -1;
}
return 0;
}
static Py_ssize_t
pytricia_length(PyTricia *self)
{
patricia_node_t *node = NULL;
Py_ssize_t count = 0;
PATRICIA_WALK (self->m_tree->head, node) {
count += 1;
} PATRICIA_WALK_END;
return count;
}
static PyObject*
pytricia_subscript(PyTricia *self, PyObject *key) {
prefix_t prefix; memset(&prefix, 0, sizeof(prefix));
int ret_ok = _key_object_to_prefix(key, &prefix);
if (!ret_ok) {
PyErr_SetString(PyExc_ValueError, "Invalid prefix.");
return NULL;
}
patricia_node_t* node = patricia_search_best(self->m_tree, &prefix);
if (!node) {
PyErr_SetString(PyExc_KeyError, "Prefix not found.");
return NULL;
}
PyObject* data = (PyObject*)node->data;
Py_INCREF(data);
return data;
}
static int
pytricia_internal_delete(PyTricia *self, PyObject *key) {
if (self->m_tree->frozen) {
PyErr_SetString(PyExc_ValueError, "can not modify a frozen pytricia! Thaw?");
return -1;
}
prefix_t prefix; memset(&prefix, 0, sizeof(prefix));
int ret_ok = _key_object_to_prefix(key, &prefix);
if (!ret_ok) {
PyErr_SetString(PyExc_ValueError, "Invalid prefix.");
return -1;
}
patricia_node_t* node = patricia_search_exact(self->m_tree, &prefix);
if (!node) {
PyErr_SetString(PyExc_KeyError, "Prefix doesn't exist.");
return -1;
}
// decrement ref count on data referred to by key, if it exists
PyObject* data = (PyObject*)node->data;
Py_XDECREF(data);
patricia_remove(self->m_tree, node);
return 0;
}
static int
_pytricia_assign_subscript_internal(PyTricia *self, PyObject *key, PyObject *value, long prefixlen) {
if (!value) {
return pytricia_internal_delete(self, key);
}
if (self->m_tree->frozen) {
PyErr_SetString(PyExc_ValueError, "can not modify a frozen pytricia! Thaw?");
return -1;
}
prefix_t prefix; memset(&prefix, 0, sizeof(prefix));
int ret_ok = _key_object_to_prefix(key, &prefix);
if (!ret_ok) {
return -1;
}
// if prefixlen > -1, it should override (possibly) parsed prefix len in key
if (prefixlen != -1) {
prefix.bitlen = prefixlen;
}
patricia_node_t *node = patricia_lookup(self->m_tree, &prefix);
if (!node) {
PyErr_SetString(PyExc_ValueError, "Error inserting into patricia tree");
return -1;
}
// node already existed, lower ref count on old data
if (node->data) {
PyObject* data = (PyObject*)node->data;
Py_DECREF(data);
}
Py_INCREF(value);
node->data = value;
return 0;
}
static int
pytricia_assign_subscript(PyTricia *self, PyObject *key, PyObject *value) {
return _pytricia_assign_subscript_internal(self, key, value, -1);
}
static PyObject*
pytricia_insert(PyTricia *self, PyObject *args) {
PyObject *key = NULL;
PyObject *value1 = NULL;
PyObject *value2 = NULL;
PyObject *rhs = NULL;
if (!PyArg_ParseTuple(args, "O|OO", &key, &value1, &value2)) {
PyErr_SetString(PyExc_ValueError, "Invalid argument(s) to insert");
return NULL;
}
if (value1) {
long prefixlen = -1;
if (value2 == NULL) {
rhs = value1;
} else {
rhs = value2;
#if PY_MAJOR_VERSION == 3
if (PyLong_Check(value1)) {
prefixlen = PyLong_AsLong(value1);
}
#else // python2
if (PyLong_Check(value1) || PyInt_Check(value1)) {
prefixlen = PyInt_AsLong(value1);
}
#endif
}
int rv = _pytricia_assign_subscript_internal(self, key, rhs, prefixlen);
if (rv == -1) {
PyErr_SetString(PyExc_ValueError, "Invalid key.");
return NULL;
}
} else {
PyErr_SetString(PyExc_ValueError, "Missing argument(s) to insert");
return NULL;
}
Py_RETURN_NONE;
}
static PyObject*
pytricia_delitem(PyTricia *self, PyObject *args) {
PyObject *key = NULL;
if (!PyArg_ParseTuple(args, "O", &key)) {
return NULL;
}
int rv = pytricia_internal_delete(self, key);
if (rv < 0) {
return NULL;
}
Py_RETURN_NONE;
}
static PyObject *
pytricia_get(register PyTricia *obj, PyObject *args) {
PyObject *key = NULL;
PyObject *defvalue = NULL;
if (!PyArg_ParseTuple(args, "O|O:get", &key, &defvalue)) {
return NULL;
}
prefix_t prefix; memset(&prefix, 0, sizeof(prefix));
int ret_ok = _key_object_to_prefix(key, &prefix);
if (!ret_ok) {
PyErr_SetString(PyExc_ValueError, "Invalid prefix.");
return NULL;
}
patricia_node_t* node = patricia_search_best(obj->m_tree, &prefix);
if (!node) {
if (defvalue) {
Py_INCREF(defvalue);
return defvalue;
}
Py_RETURN_NONE;
}
PyObject* data = (PyObject*)node->data;
Py_INCREF(data);
return data;
}
static PyObject *
pytricia_get_key(register PyTricia *obj, PyObject *args) {
PyObject *key = NULL;
if (!PyArg_ParseTuple(args, "O", &key)) {
return NULL;
}
prefix_t prefix; memset(&prefix, 0, sizeof(prefix));
int ret_ok = _key_object_to_prefix(key, &prefix);
if (!ret_ok) {
PyErr_SetString(PyExc_ValueError, "Invalid prefix.");
return NULL;
}
patricia_node_t* node = patricia_search_best(obj->m_tree, &prefix);
if (!node) {
Py_RETURN_NONE;
}
return _prefix_to_key_object(&node->prefix, obj->m_raw_output);
}
static int
pytricia_contains(PyTricia *self, PyObject *key) {
prefix_t prefix; memset(&prefix, 0, sizeof(prefix));
int ret_ok = _key_object_to_prefix(key, &prefix);
if (!ret_ok) {
return -1;
}
patricia_node_t* node = patricia_search_best(self->m_tree, &prefix);
if (node) {
return 1;
}
return 0;
}
static PyObject*
pytricia_has_key(PyTricia *self, PyObject *args) {
PyObject *key = NULL;
if (!PyArg_ParseTuple(args, "O", &key))
return NULL;
prefix_t prefix; memset(&prefix, 0, sizeof(prefix));
int ret_ok = _key_object_to_prefix(key, &prefix);
if (!ret_ok) {
PyErr_SetString(PyExc_ValueError, "Invalid prefix.");
return NULL;
}
patricia_node_t* node = patricia_search_exact(self->m_tree, &prefix);
if (node) {
Py_RETURN_TRUE;
}
Py_RETURN_FALSE;
}
static PyObject*
pytricia_keys(register PyTricia *self, PyObject *unused) {
register PyObject *rvlist = PyList_New(0);
if (!rvlist) {
return NULL;
}
patricia_node_t *node = NULL;
int err = 0;
PATRICIA_WALK (self->m_tree->head, node) {
PyObject *item = _prefix_to_key_object(&node->prefix, self->m_raw_output);
if (!item) {
Py_DECREF(rvlist);
return NULL;
}
err = PyList_Append(rvlist, item);
Py_DECREF(item);
if (err != 0) {
Py_DECREF(rvlist);
return NULL;
}
} PATRICIA_WALK_END;
return rvlist;
}
static PyObject*
pytricia_children(register PyTricia *self, PyObject *args) {
PyObject *key = NULL;
if (!PyArg_ParseTuple(args, "O", &key)) {
return NULL;
}
prefix_t prefix; memset(&prefix, 0, sizeof(prefix));
int ret_ok = _key_object_to_prefix(key, &prefix);
if (!ret_ok) {
PyErr_SetString(PyExc_ValueError, "Invalid prefix.");
return NULL;
}
register PyObject *rvlist = PyList_New(0);
if (!rvlist) {
return NULL;
}
patricia_node_t* base_node = patricia_search_exact(self->m_tree, &prefix);
if (!base_node) {
PyErr_SetString(PyExc_KeyError, "Prefix doesn't exist.");
Py_DECREF(rvlist);
return NULL;
}
patricia_node_t* node = NULL;
int err = 0;
PATRICIA_WALK (base_node, node) {
/* Discard first prefix (we want strict children) */
if (node != base_node) {
PyObject *item = _prefix_to_key_object(&node->prefix, self->m_raw_output);
if (!item) {
Py_DECREF(rvlist);
return NULL;
}
err = PyList_Append(rvlist, item);
Py_DECREF(item);
if (err != 0) {
Py_DECREF(rvlist);
return NULL;
}
}
} PATRICIA_WALK_END;
return rvlist;
}
static PyObject*
pytricia_parent(register PyTricia *self, PyObject *args) {
PyObject *key = NULL;
if (!PyArg_ParseTuple(args, "O", &key)) {
return NULL;
}
prefix_t prefix; memset(&prefix, 0, sizeof(prefix));
int ret_ok = _key_object_to_prefix(key, &prefix);
if (!ret_ok) {
PyErr_SetString(PyExc_ValueError, "Invalid prefix.");
return NULL;
}
patricia_node_t* node = patricia_search_exact(self->m_tree, &prefix);
if (!node) {
PyErr_SetString(PyExc_KeyError, "Prefix doesn't exist.");
return NULL;
}
patricia_node_t* parent_node = patricia_search_best2(self->m_tree, &node->prefix, 0);
if (!parent_node) {
Py_RETURN_NONE;
}
return _prefix_to_key_object(&parent_node->prefix, self->m_raw_output);
}
static PyObject*
pytricia_freeze(register PyTricia *self, PyObject *unused) {
if (self->m_tree->frozen) {
Py_RETURN_NONE;
}
patricia_node_t *node = NULL;
// Get count of all nodes
size_t count = 0;
PATRICIA_WALK_ALL (self->m_tree->head, node) {
count += 1;
} PATRICIA_WALK_END;
// allocate contiguous space for all nodes
patricia_node_t* new_node = calloc(count, sizeof(patricia_node_t));
// copy all nodes to new array and discard originals
size_t idx = 0;
patricia_node_t** free_list = calloc(count, sizeof(patricia_node_t*));
PATRICIA_WALK_ALL (self->m_tree->head, node) {
new_node[idx] = *node;
if(node->l)
node->l->parent = &(new_node[idx]);
if(node->r)
node->r->parent = &(new_node[idx]);
if(node->parent == NULL) {
assert (self->m_tree->head == node);
self->m_tree->head = new_node;
}
else if (node->parent->r == node) {
node->parent->r = &(new_node[idx]);
}
else {
node->parent->l = &(new_node[idx]);
}
free_list[idx] = node;
idx++;
} PATRICIA_WALK_END;
// clearing via free_list because otherise PATRICIA_WALK_END
// will illegally reference items from node to determine next steps
for(size_t i=0; i<count; i++) {
free(free_list[i]);
}
free(free_list);
// mark as frozen
self->m_tree->frozen = 1;
Py_RETURN_NONE;
}
static PyObject*
pytricia_thaw(register PyTricia *self, PyObject *unused) {
if (!self->m_tree->frozen) {
Py_RETURN_NONE; // already thaw'd
}
if (self->m_tree->head == NULL) {
self->m_tree->frozen = 0;
Py_RETURN_NONE;
}
patricia_node_t* original_head = self->m_tree->head;
// walk all nodes, allocating heap space for individual
// nodes and re-linking
patricia_node_t *node = NULL;
PATRICIA_WALK_ALL (self->m_tree->head, node) {
patricia_node_t* new_node = calloc(1, sizeof(patricia_node_t));
*new_node = *node;
if(node->l)
node->l->parent = new_node;
if(node->r)
node->r->parent = new_node;
if(node->parent == NULL) {
assert (self->m_tree->head == node);
self->m_tree->head = new_node;
}
else if (node->parent->r == node) {
node->parent->r = new_node;
}
else {
node->parent->l = new_node;
}
} PATRICIA_WALK_END;
free(original_head);
// mark as NOT frozen
self->m_tree->frozen = 0;
Py_RETURN_NONE;
}
// forward declaration
static PyTypeObject PyTriciaType;
static PyObject* pytricia_reduce(PyTricia *self, PyObject *Py_UNUSED(ignored)) {
if (!self->m_tree->frozen) {
PyErr_SetString(PyExc_RuntimeError, "pytri must be frozen before attempting to pickle!");
return NULL;
}
PyObject *args = PyTuple_New(1);
if (!args) {
return NULL;
}
PyTuple_SET_ITEM(args, 0, PyLong_FromLong(self->m_tree->maxbits));
// setup the extra dictionary info for setstate
PyObject* dict = PyDict_New();
PyObject* bytes = PyBytes_FromStringAndSize((const char*)self->m_tree, sizeof(patricia_tree_t));
if (!dict || !bytes) {
PyErr_SetString(PyExc_MemoryError, "unable to allocate space for tri");
Py_XDECREF(dict);
Py_XDECREF(bytes);
return NULL;
}
int ret_err = PyDict_SetItemString(dict, "tree", bytes);
Py_DECREF(bytes); // dictionary now owns the reference
if(ret_err) {
PyErr_SetString(PyExc_MemoryError, "error writing tree_t to dictionary");
Py_DECREF(dict);
return NULL;
}
// Now set nodes internal block
patricia_node_t *node = NULL;
size_t count = 0;
PATRICIA_WALK_ALL (self->m_tree->head, node) {
count += 1;
} PATRICIA_WALK_END;
bytes = PyBytes_FromStringAndSize((const char*)self->m_tree->head, sizeof(patricia_node_t)*count);
ret_err = PyDict_SetItemString(dict, "nodes", bytes);
Py_DECREF(bytes); // dictionary now owns the reference
if(ret_err) {
PyErr_SetString(PyExc_MemoryError, "error writing nodes to dictionary");
Py_DECREF(dict);
return NULL;
}
PyObject* list = PyList_New(count);
if (!list) {
PyErr_SetString(PyExc_MemoryError, "error allocating data list");
return NULL;
}
count = 0;
if (self->m_tree->head) {
PATRICIA_WALK_ALL (self->m_tree->head, node) {
// some nodes may be glued in middle and will have prefix, but not data
// In case of no data, we'll leave the list entry as default (None)
if(node->data) {
// SET_ITEM steal reference so increment in advance to keep original
Py_INCREF(node->data);
PyList_SET_ITEM(list, count, node->data);
}
else {
Py_INCREF(Py_None);
PyList_SET_ITEM(list, count, Py_None);
}
count += 1;
} PATRICIA_WALK_END;
}
ret_err = PyDict_SetItemString(dict, "data", list);
Py_DECREF(list); // dictionary now owns the reference
if(ret_err) {
PyErr_SetString(PyExc_MemoryError, "error writing data list to dictionary");
Py_DECREF(dict);
return NULL;
}
PyObject* out_tuple = PyTuple_Pack(3, (PyObject*)Py_TYPE(self), args, dict);
Py_DECREF(args);
Py_DECREF(dict);
return out_tuple;
}
static PyObject* pytricia_setstate(PyTricia *self, PyObject *args) {
PyObject *state;
if (!PyArg_ParseTuple(args, "O", &state)) {
return NULL;
}
if (!PyDict_Check(state)) {
PyErr_SetString(PyExc_TypeError, "__setstate__ argument must be a dictionary");
return NULL;
}
PyObject* bytes = PyDict_GetItemString(state, "tree");
if (!bytes || !PyBytes_Check(bytes) || PyBytes_Size(bytes) != sizeof(patricia_tree_t)) {
PyErr_SetString(PyExc_TypeError, "__setstate__ failed tree type checking");
return NULL;
}
memcpy(self->m_tree, PyBytes_AsString(bytes), sizeof(patricia_tree_t));
// restore head/node data
PyObject* nodebytes = PyDict_GetItemString(state, "nodes");
if (!PyBytes_Check(nodebytes)) {
PyErr_SetString(PyExc_TypeError, "__setstate__ failed nodes type checking");
return NULL;
}
if (PyBytes_Size(nodebytes)) {
patricia_node_t* original_head = self->m_tree->head;
self->m_tree->head = calloc(1, PyBytes_Size(nodebytes));
ssize_t offset_bytes = (char*)self->m_tree->head - (char*)original_head;
size_t num_nodes = PyBytes_Size(nodebytes) / sizeof(patricia_node_t);
if(self->m_tree->head == NULL) {
PyErr_SetString(PyExc_MemoryError, "__setstate__ error allocating space for nodes");
return NULL;
}
memcpy(self->m_tree->head, PyBytes_AsString(nodebytes), PyBytes_Size(nodebytes));
// Now re-write the links relative to the start of the contiguous memory block
patricia_node_t *node = self->m_tree->head;
for(size_t i=0; i<num_nodes; i++) {
if(node->parent) {
node->parent = (patricia_node_t*)((char*)node->parent + offset_bytes);
}
if(node->l) {
node->l = (patricia_node_t*)((char*)node->l + offset_bytes);
}
if(node->r) {
node->r = (patricia_node_t*)((char*)node->r + offset_bytes);
}
node++;
}
}
// Restore node data items
PyObject* list = PyDict_GetItemString(state, "data");
if (!PyList_Check(list)) {
PyErr_SetString(PyExc_TypeError, "__setstate__ data is not list as expected!");
return NULL;
}
else {
Py_ssize_t list_len = PyList_Size(list);
if (list_len * (Py_ssize_t)sizeof(patricia_node_t) != PyBytes_Size(nodebytes)) {
PyErr_SetString(PyExc_TypeError, "__setstate__ node and data list sizes inconsistent!");
return NULL;
}
}
patricia_node_t *node = NULL;
size_t count = 0;
if (self->m_tree->head) {
PATRICIA_WALK_ALL (self->m_tree->head, node) {
node->data = PyList_GET_ITEM(list, count);
Py_INCREF(node->data); // make our own reference
// in special case of glue node with data value of None
// we'll want to remove python None and instead use NULL
if (node->data == Py_None) {
Py_DECREF(node->data);
node->data = NULL;
}
count += 1;
} PATRICIA_WALK_END;
}
Py_RETURN_NONE;
}
static PyMappingMethods pytricia_as_mapping = {
(lenfunc)pytricia_length,
(binaryfunc)pytricia_subscript,
(objobjargproc)pytricia_assign_subscript
};
static PySequenceMethods pytricia_as_sequence = {
(lenfunc)pytricia_length, /*sq_length*/
0, /*sq_concat*/
0, /*sq_repeat*/
0, /*sq_item*/
0, /*sq_slice*/
0, /*sq_ass_item*/
0, /*sq_ass_slice*/
(objobjproc)pytricia_contains, /*sq_contains*/
0, /*sq_inplace_concat*/
0 /*sq_inplace_repeat*/
};