-
Notifications
You must be signed in to change notification settings - Fork 3
/
PythonModule.cc
2723 lines (2308 loc) · 103 KB
/
PythonModule.cc
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
#define PY_SSIZE_T_CLEAN
#include <Python.h>
#include <marshal.h>
#if PY_MAJOR_VERSION < 3
#error "sharedstructures no longer supports Python 2"
#endif
#define __STDC_FORMAT_MACROS
#include <inttypes.h>
#include <utility>
#include "Pool.hh"
#include "Allocator.hh"
#include "SimpleAllocator.hh"
#include "LogarithmicAllocator.hh"
#include "HashTable.hh"
#include "PrefixTree.hh"
#include "IntVector.hh"
#include "Queue.hh"
#include "PriorityQueue.hh"
using namespace std;
using ResultValueType = sharedstructures::PrefixTree::ResultValueType;
using LookupResult = sharedstructures::PrefixTree::LookupResult;
// TODO: make sure long is supported everywhere int is supported
static const char* sharedstructures_doc =
"Dynamically-sized shared-memory data structure module.\n\
\n\
This module provides the HashTable, PrefixTree, Queue, PriorityQueue, and IntVector classes.";
// Helper functions
static shared_ptr<sharedstructures::Allocator> sharedstructures_internal_get_allocator(
const char* pool_name, const char* allocator_type) {
shared_ptr<sharedstructures::Pool> pool(new sharedstructures::Pool(pool_name));
shared_ptr<sharedstructures::Allocator> allocator;
if (!allocator_type || !strcmp(allocator_type, "simple")) {
allocator.reset(new sharedstructures::SimpleAllocator(pool));
} else if (!strcmp(allocator_type, "logarithmic")) {
allocator.reset(new sharedstructures::LogarithmicAllocator(pool));
} else {
throw out_of_range("unknown allocator type");
}
return allocator;
}
static pair<const char*, size_t> sharedstructures_internal_get_key(
PyObject* key) {
// key must be a bytes (not unicode!)
if (!PyBytes_Check(key)) {
PyErr_SetString(PyExc_TypeError, "sharedstructures keys must be strings");
return make_pair(nullptr, 0);
}
ssize_t key_size;
char* key_data;
if (PyBytes_AsStringAndSize(key, &key_data, &key_size) == -1) {
return make_pair(nullptr, 0);
}
return make_pair(key_data, key_size);
}
static PyObject* sharedstructures_internal_get_python_object_for_result(
const sharedstructures::PrefixTree::LookupResult& res) {
switch (res.type) {
case ResultValueType::Missing:
// This can't happen
PyErr_SetString(PyExc_NotImplementedError, "missing result returned");
return nullptr;
case ResultValueType::String:
if (res.as_string.empty()) {
return PyBytes_FromStringAndSize(nullptr, 0);
}
switch (res.as_string[0]) {
// The first byte tells what the format is
case 0: // Byte string
return PyBytes_FromStringAndSize(res.as_string.data() + 1, res.as_string.size() - 1);
case 1: // Unicode string
return PyUnicode_FromWideChar(
reinterpret_cast<const wchar_t*>(res.as_string.data() + 1),
(res.as_string.size() - 1) / sizeof(wchar_t));
case 2: // Marshalled object
return PyMarshal_ReadObjectFromString(
const_cast<char*>(res.as_string.data()) + 1,
res.as_string.size() - 1);
default:
PyErr_SetString(PyExc_TypeError, "unknown string format");
return nullptr;
}
case ResultValueType::Int:
return PyLong_FromLongLong(res.as_int);
case ResultValueType::Double:
return PyFloat_FromDouble(res.as_double);
case ResultValueType::Bool: {
PyObject* ret = res.as_bool ? Py_True : Py_False;
Py_INCREF(ret);
return ret;
}
case ResultValueType::Null:
Py_INCREF(Py_None);
return Py_None;
}
PyErr_SetString(PyExc_NotImplementedError, "result has unknown type");
return nullptr;
}
static LookupResult sharedstructures_internal_get_result_for_python_object(
PyObject* o) {
if (o == Py_None) {
return LookupResult();
} else if (o == Py_True) {
return LookupResult(true);
} else if (o == Py_False) {
return LookupResult(false);
} else if (PyFloat_Check(o)) {
double v = PyFloat_AsDouble(o);
if (v == -1.0 && PyErr_Occurred()) {
throw runtime_error("failed to convert python object to LookupResult");
}
return LookupResult(v);
} else if (PyLong_Check(o)) {
int64_t v = PyLong_AsLongLong(o);
if (v == -1 && PyErr_Occurred()) {
throw runtime_error("failed to convert python object to LookupResult");
}
return LookupResult(v);
} else if (PyBytes_Check(o)) {
LookupResult res("\x00", 1);
char* data;
Py_ssize_t size;
if (PyBytes_AsStringAndSize(o, &data, &size) == -1) {
throw runtime_error("failed to convert python object to LookupResult");
}
res.as_string.append(data, size);
return res;
} else if (PyUnicode_Check(o)) {
LookupResult res("\x01", 1);
Py_ssize_t count = PyUnicode_GetLength(o);
res.as_string.resize(res.as_string.size() + count * sizeof(wchar_t));
Py_ssize_t chars_copied = PyUnicode_AsWideChar(
o, reinterpret_cast<wchar_t*>(res.as_string.data() + 1), count);
if (chars_copied != count) {
throw runtime_error("failed to convert python object to LookupResult");
}
return res;
} else {
PyObject* marshalled_obj = PyMarshal_WriteObjectToString(o,
Py_MARSHAL_VERSION);
if (!marshalled_obj) {
// TODO: does PyMarshal_WriteObjectToString set an exception on failure?
// here we assume it does
throw runtime_error("failed to convert python object to LookupResult");
}
LookupResult res("\x02", 1);
char* data;
Py_ssize_t size;
if (PyBytes_AsStringAndSize(marshalled_obj, &data, &size) == -1) {
Py_DECREF(marshalled_obj);
throw runtime_error("failed to convert python object to LookupResult");
}
res.as_string.append(data, size);
Py_DECREF(marshalled_obj);
return res;
}
}
// HashTable, HashTableIterator, PrefixTree and PrefixTreeIterator definitions
static const char* sharedstructures_HashTable_doc =
"Shared-memory hash table object.\n\
\n\
sharedstructures.HashTable(pool_name[, allocator_type[, base_offset[, bits]]])\n\
\n\
Arguments:\n\
- pool_name: the name of the shared-memory pool to operate on.\n\
- allocator_type: 'simple' (default) or 'logarithmic' (see README.md).\n\
- base_offset: if given, opens a HashTable at this offset within the pool. If\n\
not given, opens a HashTable at the pool's base offset. If the pool's base\n\
offset is 0, creates a new HashTable and sets the pool's base offset to the\n\
new HashTable's offset.\n\
- bits: if a new HashTable is created, it will bave 2^bits buckets (default 8\n\
bits).";
typedef struct {
PyObject_HEAD
shared_ptr<sharedstructures::HashTable> table;
} sharedstructures_HashTable;
static const char* sharedstructures_HashTableIterator_doc =
"Shared-memory hash table iterator.";
typedef struct {
PyObject_HEAD
sharedstructures_HashTable* table_obj;
sharedstructures::HashTableIterator it;
bool return_keys;
bool return_values;
} sharedstructures_HashTableIterator;
static const char* sharedstructures_PrefixTree_doc =
"Shared-memory prefix tree object.\n\
\n\
sharedstructures.PrefixTree(pool_name[, allocator_type[, base_offset]])\n\
\n\
Arguments:\n\
- pool_name: the name of the shared-memory pool to operate on.\n\
- allocator_type: 'simple' (default) or 'logarithmic' (see README.md).\n\
- base_offset: if given, opens a PrefixTree at this offset within the pool. If\n\
not given, opens a PrefixTree at the pool's base offset. If the pool's base\n\
offset is 0, creates a new PrefixTree and sets the pool's base offset to the\n\
new PrefixTree's offset.";
typedef struct {
PyObject_HEAD
shared_ptr<sharedstructures::PrefixTree> table;
} sharedstructures_PrefixTree;
static const char* sharedstructures_PrefixTreeIterator_doc =
"Shared-memory prefix tree iterator.";
typedef struct {
PyObject_HEAD
sharedstructures_PrefixTree* tree_obj;
sharedstructures::PrefixTreeIterator it;
bool return_keys;
bool return_values;
} sharedstructures_PrefixTreeIterator;
static const char* sharedstructures_Queue_doc =
"Shared-memory doubly-linked list (queue) object.\n\
\n\
sharedstructures.Queue(pool_name[, allocator_type[, base_offset]])\n\
\n\
Arguments:\n\
- pool_name: the name of the shared-memory pool to operate on.\n\
- allocator_type: 'simple' (default) or 'logarithmic' (see README.md).\n\
- base_offset: if given, opens a Queue at this offset within the pool. If not\n\
given, opens a Queue at the pool's base offset. If the pool's base offset is\n\
0, creates a new Queue and sets the pool's base offset to the new Queue's\n\
offset.";
typedef struct {
PyObject_HEAD
shared_ptr<sharedstructures::Queue> q;
} sharedstructures_Queue;
static const char* sharedstructures_PriorityQueue_doc =
"Shared-memory heap (priority queue) object.\n\
\n\
sharedstructures.PriorityQueue(pool_name[, allocator_type[, base_offset]])\n\
\n\
Arguments:\n\
- pool_name: the name of the shared-memory pool to operate on.\n\
- allocator_type: 'simple' (default) or 'logarithmic' (see README.md).\n\
- base_offset: if given, opens a PriorityQueue at this offset within the pool.\n\
If not given, opens a PriorityQueue at the pool's base offset. If the pool's\n\
base offset is 0, creates a new PriorityQueue and sets the pool's base offset\n\
to the new PriorityQueue's offset.";
typedef struct {
PyObject_HEAD
shared_ptr<sharedstructures::PriorityQueue> q;
} sharedstructures_PriorityQueue;
static const char* sharedstructures_IntVector_doc =
"Shared-memory atomic integer array object.\n\
\n\
sharedstructures.IntVector(pool_name)\n\
\n\
Arguments:\n\
- pool_name: the name of the shared-memory pool to operate on.";
typedef struct {
PyObject_HEAD
shared_ptr<sharedstructures::IntVector> v;
} sharedstructures_IntVector;
// HashTableIterator object method definitions
static PyObject* sharedstructures_HashTableIterator_New(PyTypeObject* type,
PyObject* args, PyObject* kwargs) {
sharedstructures_HashTableIterator* self = (sharedstructures_HashTableIterator*)PyType_GenericNew(
type, args, kwargs);
if (!self) {
return nullptr;
}
// PyArg_ParseTupleAndKeywords takes a char** where it should take a const
// char** (this argument is never modified), so we have to const_cast it, sigh
static const char* kwarg_names[] = {"table_obj", "return_keys", "return_values", nullptr};
static char** kwarg_names_arg = const_cast<char**>(kwarg_names);
PyObject* return_keys_obj;
PyObject* return_values_obj;
if (!PyArg_ParseTupleAndKeywords(args, kwargs, "OOO", kwarg_names_arg,
&self->table_obj, &return_keys_obj, &return_values_obj)) {
return nullptr;
}
if (return_keys_obj == Py_True) {
self->return_keys = true;
} else if (return_keys_obj == Py_False) {
self->return_keys = false;
} else {
PyErr_SetString(PyExc_NotImplementedError, "iter() got non-bool return_keys");
return nullptr;
}
if (return_values_obj == Py_True) {
self->return_values = true;
} else if (return_values_obj == Py_False) {
self->return_values = false;
} else {
PyErr_SetString(PyExc_NotImplementedError, "iter() got non-bool return_values");
return nullptr;
}
if (!self->return_keys && !self->return_values) {
PyErr_SetString(PyExc_NotImplementedError, "iterators must return keys or values or both, not neither");
return nullptr;
}
Py_INCREF(self->table_obj);
new (&self->it) sharedstructures::HashTableIterator(self->table_obj->table->begin());
return (PyObject*)self;
}
static void sharedstructures_HashTableIterator_Dealloc(PyObject* py_self) {
sharedstructures_HashTableIterator* self = (sharedstructures_HashTableIterator*)py_self;
self->it.sharedstructures::HashTableIterator::~HashTableIterator();
Py_DECREF(self->table_obj);
Py_TYPE(self)->tp_free((PyObject*)self);
}
static PyObject* sharedstructures_HashTableIterator_Iter(PyObject* py_self) {
Py_INCREF(py_self);
return py_self;
}
static PyObject* sharedstructures_HashTableIterator_Next(PyObject* py_self) {
sharedstructures_HashTableIterator* self = (sharedstructures_HashTableIterator*)py_self;
sharedstructures_HashTable* table = (sharedstructures_HashTable*)self->table_obj;
if (self->it == table->table->end()) {
PyErr_SetNone(PyExc_StopIteration);
return nullptr;
}
auto res = *self->it;
self->it++;
// TODO: factor this out with PrefixTreeIterator
if (self->return_keys && self->return_values) {
// If both, return a tuple of the two items
PyObject* ret_key = PyBytes_FromStringAndSize(res.first.data(), res.first.size());
if (!ret_key) {
return nullptr;
}
PyObject* ret_value = PyMarshal_ReadObjectFromString(
const_cast<char*>(res.second.data()), res.second.size());
if (!ret_value) {
Py_DECREF(ret_key);
return nullptr;
}
PyObject* ret = PyTuple_Pack(2, ret_key, ret_value);
if (!ret) {
Py_DECREF(ret_key);
Py_DECREF(ret_value);
}
return ret;
}
if (self->return_keys) {
return PyBytes_FromStringAndSize(res.first.data(), res.first.size());
}
if (self->return_values) {
return PyMarshal_ReadObjectFromString(const_cast<char*>(res.second.data()),
res.second.size());
}
PyErr_SetString(PyExc_NotImplementedError, "iterators must return keys or values or both, not neither");
return nullptr;
}
static PyObject* sharedstructures_HashTableIterator_Repr(PyObject* py_self) {
return PyUnicode_FromFormat(
"<sharedstructures.HashTable.iterator at %p>", py_self);
}
static PyTypeObject sharedstructures_HashTableIteratorType = {
PyVarObject_HEAD_INIT(nullptr, 0)
"sharedstructures.HashTableIterator", // tp_name
sizeof(sharedstructures_HashTableIterator), // tp_basicsize
0, // tp_itemsize
(destructor)sharedstructures_HashTableIterator_Dealloc, // tp_dealloc
0, // tp_print
0, // tp_getattr
0, // tp_setattr
0, // tp_compare
sharedstructures_HashTableIterator_Repr, // tp_repr
0, // tp_as_number
0, // tp_as_sequence
0, // tp_as_mapping
0, // tp_hash
0, // tp_call
0, // tp_str
0, // tp_getattro
0, // tp_setattro
0, // tp_as_buffer
Py_TPFLAGS_DEFAULT, // tp_flag
sharedstructures_HashTableIterator_doc, // tp_doc
0, // tp_traverse
0, // tp_clear
0, // tp_richcompare
0, // tp_weaklistoffset
sharedstructures_HashTableIterator_Iter, // tp_iter
sharedstructures_HashTableIterator_Next, // tp_iternext
0, // tp_methods
0, // tp_members
0, // tp_getset
0, // tp_base
0, // tp_dict
0, // tp_descr_get
0, // tp_descr_set
0, // tp_dictoffset
0, // tp_init
0, // tp_alloc
sharedstructures_HashTableIterator_New, // tp_new
0, // tp_free
0, // tp_is_gc
0, // tp_bases
0, // tp_mro
0, // tp_cache
0, // tp_subclasses
0, // tp_weaklist
0, // tp_del
0, // tp_version_tag
0, // tp_finalize
0, // tp_vectorcall
};
// HashTable object method definitions
static PyObject* sharedstructures_HashTable_New(PyTypeObject* type,
PyObject* args, PyObject* kwargs) {
sharedstructures_HashTable* self = (sharedstructures_HashTable*)PyType_GenericNew(
type, args, kwargs);
if (!self) {
return nullptr;
}
// See comment in sharedstructures_HashTableIterator_New about const_cast
static const char* kwarg_names[] = {"pool_name", "allocator_type",
"base_offset", "bits", nullptr};
static char** kwarg_names_arg = const_cast<char**>(kwarg_names);
const char* pool_name;
Py_ssize_t base_offset = 0;
uint8_t bits = 8;
const char* allocator_type = nullptr;
if (!PyArg_ParseTupleAndKeywords(args, kwargs, "s|snb", kwarg_names_arg,
&pool_name, &allocator_type, &base_offset, &bits)) {
return nullptr;
}
// Try to construct the pool before filling in the python object
try {
auto allocator = sharedstructures_internal_get_allocator(pool_name,
allocator_type);
new (&self->table) shared_ptr<sharedstructures::HashTable>(
new sharedstructures::HashTable(allocator, base_offset, bits));
} catch (const exception& e) {
PyErr_Format(PyExc_RuntimeError, "failed to initialize hash table: %s", e.what());
return nullptr;
}
return (PyObject*)self;
}
static void sharedstructures_HashTable_Dealloc(PyObject* obj) {
sharedstructures_HashTable* self = (sharedstructures_HashTable*)obj;
self->table.~shared_ptr();
Py_TYPE(self)->tp_free((PyObject*)self);
}
static const char* sharedstructures_HashTable_verify_doc =
"Checks the internal state of the shared allocator.\n\
\n\
On success, returns None. Otherwise, returns a bytes object with a description\n\
of the error.";
static PyObject* sharedstructures_HashTable_verify(PyObject* py_self) {
sharedstructures_HashTable* self = (sharedstructures_HashTable*)py_self;
try {
self->table->get_allocator()->verify();
} catch (const exception& e) {
return PyBytes_FromStringAndSize(e.what(), strlen(e.what()));
}
Py_INCREF(Py_None);
return Py_None;
}
static Py_ssize_t sharedstructures_HashTable_Len(PyObject* py_self) {
sharedstructures_HashTable* self = (sharedstructures_HashTable*)py_self;
return self->table->size();
}
static int sharedstructures_HashTable_In(PyObject* py_self, PyObject* key) {
sharedstructures_HashTable* self = (sharedstructures_HashTable*)py_self;
auto k = sharedstructures_internal_get_key(key);
if (!k.first) {
return -1;
}
return self->table->exists(k.first, k.second);
}
static PyObject* sharedstructures_HashTable_GetItem(PyObject* py_self,
PyObject* key) {
sharedstructures_HashTable* self = (sharedstructures_HashTable*)py_self;
auto k = sharedstructures_internal_get_key(key);
if (!k.first) {
return nullptr;
}
try {
string res = self->table->at(k.first, k.second);
return PyMarshal_ReadObjectFromString(const_cast<char*>(res.data()),
res.size());
} catch (const out_of_range& e) {
PyErr_SetObject(PyExc_KeyError, key);
return nullptr;
}
}
static int sharedstructures_HashTable_SetItem(PyObject* py_self, PyObject* key,
PyObject* value) {
sharedstructures_HashTable* self = (sharedstructures_HashTable*)py_self;
auto k = sharedstructures_internal_get_key(key);
if (!k.first) {
return -1;
}
if (!value) {
if (!self->table->erase(k.first, k.second)) {
PyErr_SetObject(PyExc_KeyError, key);
return -1;
}
} else {
PyObject* marshalled_obj = PyMarshal_WriteObjectToString(value,
Py_MARSHAL_VERSION);
if (!marshalled_obj) {
// TODO: does PyMarshal_WriteObjectToString set an exception on failure?
// Here we assume it does
return -1;
}
char* data;
Py_ssize_t size;
if (PyBytes_AsStringAndSize(marshalled_obj, &data, &size) == -1) {
Py_DECREF(marshalled_obj);
return -1;
}
self->table->insert(k.first, k.second, data, size);
Py_DECREF(marshalled_obj);
}
return 0;
}
static PyObject* sharedstructures_HashTable_Repr(PyObject* py_self) {
sharedstructures_HashTable* self = (sharedstructures_HashTable*)py_self;
// PyBytes_FromFormat doesn't support e.g. PRIx64 so we pretend base_offset is
// a pointer instead
return PyUnicode_FromFormat(
"<sharedstructures.HashTable on %s:%p at %p>",
self->table->get_allocator()->get_pool()->get_name().c_str(),
(const void*)self->table->base(), py_self);
}
static const char* sharedstructures_HashTable_clear_doc =
"Deletes all entries in the table.";
static PyObject* sharedstructures_HashTable_clear(PyObject* py_self) {
sharedstructures_HashTable* self = (sharedstructures_HashTable*)py_self;
self->table->clear();
Py_INCREF(Py_None);
return Py_None;
}
static const char* sharedstructures_HashTable_check_and_set_doc =
"Conditionally sets a value if the check key\'s value matches the check value.\n\
\n\
HashTable.check_and_set(check_key, check_value, target_key[, target_value])\n\
-> bool\n\
\n\
Atomically checks if check_key exists and if its value matches check_value. If\n\
so, sets target_key to target_value. If target_value is not given, deletes\n\
target_key instead.\n\
\n\
Returns True if a set was performed or a key was deleted. Returns False if the\n\
check fails, or if target_key was going to be deleted but it already didn't\n\
exist.";
static PyObject* sharedstructures_HashTable_check_and_set(PyObject* py_self,
PyObject* args) {
sharedstructures_HashTable* self = (sharedstructures_HashTable*)py_self;
char* check_key;
Py_ssize_t check_key_size;
PyObject* check_value_object;
char* target_key;
Py_ssize_t target_key_size;
PyObject* target_value_object = nullptr;
if (!PyArg_ParseTuple(args, "s#Os#|O", &check_key, &check_key_size,
&check_value_object, &target_key, &target_key_size,
&target_value_object)) {
return nullptr;
}
PyObject* marshalled_check_value_obj = PyMarshal_WriteObjectToString(
check_value_object, Py_MARSHAL_VERSION);
if (!marshalled_check_value_obj) {
// TODO: does PyMarshal_WriteObjectToString set an exception on failure?
// Here we assume it does
return nullptr;
}
char* marshalled_check_value_data;
Py_ssize_t marshalled_check_value_size;
if (PyBytes_AsStringAndSize(marshalled_check_value_obj,
&marshalled_check_value_data, &marshalled_check_value_size) == -1) {
Py_DECREF(marshalled_check_value_obj);
return nullptr;
}
sharedstructures::HashTable::CheckRequest check(check_key, check_key_size,
marshalled_check_value_data, marshalled_check_value_size);
bool written;
if (target_value_object) {
PyObject* marshalled_target_value_obj = PyMarshal_WriteObjectToString(
target_value_object, Py_MARSHAL_VERSION);
if (!marshalled_target_value_obj) {
// TODO: does PyMarshal_WriteObjectToString set an exception on failure?
// Here we assume it does
Py_DECREF(marshalled_check_value_obj);
return nullptr;
}
char* marshalled_target_value_data;
Py_ssize_t marshalled_target_value_size;
if (PyBytes_AsStringAndSize(marshalled_target_value_obj,
&marshalled_target_value_data, &marshalled_target_value_size) == -1) {
Py_DECREF(marshalled_check_value_obj);
Py_DECREF(marshalled_target_value_obj);
return nullptr;
}
written = self->table->insert(target_key, target_key_size,
marshalled_target_value_data, marshalled_target_value_size, &check);
Py_DECREF(marshalled_target_value_obj);
} else {
written = self->table->erase(target_key, target_key_size, &check);
}
Py_DECREF(marshalled_check_value_obj);
PyObject* ret = written ? Py_True : Py_False;
Py_INCREF(ret);
return ret;
}
static const char* sharedstructures_HashTable_check_missing_and_set_doc =
"Conditionally sets a value if the check key does not exist.\n\
\n\
HashTable.check_missing_and_set(check_key, target_key[, target_value]) -> bool\n\
\n\
Atomically checks if check_key exists. If it doesn't exist, sets target_key to\n\
target_value. If target_value is not given, deletes target_key instead.\n\
\n\
Returns True if a set was performed or a key was deleted. Returns False if the\n\
check_key exists, or if target_key was going to be deleted but it already\n\
didn't exist.";
static PyObject* sharedstructures_HashTable_check_missing_and_set(
PyObject* py_self, PyObject* args) {
sharedstructures_HashTable* self = (sharedstructures_HashTable*)py_self;
char* check_key;
Py_ssize_t check_key_size;
char* target_key;
Py_ssize_t target_key_size;
PyObject* target_value_object = nullptr;
if (!PyArg_ParseTuple(args, "s#s#|O", &check_key, &check_key_size,
&target_key, &target_key_size, &target_value_object)) {
return nullptr;
}
sharedstructures::HashTable::CheckRequest check(check_key, check_key_size);
bool written;
if (target_value_object) {
PyObject* marshalled_target_value_obj = PyMarshal_WriteObjectToString(
target_value_object, Py_MARSHAL_VERSION);
if (!marshalled_target_value_obj) {
// TODO: does PyMarshal_WriteObjectToString set an exception on failure?
// Here we assume it does
return nullptr;
}
char* marshalled_target_value_data;
Py_ssize_t marshalled_target_value_size;
if (PyBytes_AsStringAndSize(marshalled_target_value_obj,
&marshalled_target_value_data, &marshalled_target_value_size) == -1) {
Py_DECREF(marshalled_target_value_obj);
return nullptr;
}
written = self->table->insert(target_key, target_key_size,
marshalled_target_value_data, marshalled_target_value_size, &check);
Py_DECREF(marshalled_target_value_obj);
} else {
written = self->table->erase(target_key, target_key_size, &check);
}
PyObject* ret = written ? Py_True : Py_False;
Py_INCREF(ret);
return ret;
}
static PyObject* sharedstructures_HashTable_iter_generic(PyObject* py_self,
bool return_keys, bool return_values) {
sharedstructures_HashTable* self = (sharedstructures_HashTable*)py_self;
// Args: table, return_keys, return_values
PyObject* args = Py_BuildValue("OOO", self, return_keys ? Py_True : Py_False,
return_values ? Py_True : Py_False);
if (!args) {
return nullptr;
}
PyObject* it = PyObject_CallObject(
(PyObject*)&sharedstructures_HashTableIteratorType, args);
Py_DECREF(args);
return it;
}
static const char* sharedstructures_HashTable_iterkeys_doc =
"Returns an iterator over all keys in the table.";
static PyObject* sharedstructures_HashTable_iterkeys(PyObject* py_self) {
return sharedstructures_HashTable_iter_generic(py_self, true, false);
}
static const char* sharedstructures_HashTable_itervalues_doc =
"Returns an iterator over all values in the table.";
static PyObject* sharedstructures_HashTable_itervalues(PyObject* py_self) {
return sharedstructures_HashTable_iter_generic(py_self, false, true);
}
static const char* sharedstructures_HashTable_iteritems_doc =
"Returns an iterator over all key/value pairs in the table.";
static PyObject* sharedstructures_HashTable_iteritems(PyObject* py_self) {
return sharedstructures_HashTable_iter_generic(py_self, true, true);
}
static PyObject* sharedstructures_HashTable_Iter(PyObject* py_self) {
return sharedstructures_HashTable_iterkeys(py_self);
}
static const char* sharedstructures_HashTable_bits_doc =
"Returns the hash bucket count factor.";
static PyObject* sharedstructures_HashTable_bits(PyObject* py_self) {
sharedstructures_HashTable* self = (sharedstructures_HashTable*)py_self;
return PyLong_FromLong(self->table->bits());
}
static const char* sharedstructures_HashTable_pool_bytes_doc =
"Returns the size of the underlying shared memory pool.";
static PyObject* sharedstructures_HashTable_pool_bytes(PyObject* py_self) {
sharedstructures_HashTable* self = (sharedstructures_HashTable*)py_self;
return PyLong_FromSize_t(self->table->get_allocator()->get_pool()->size());
}
static const char* sharedstructures_HashTable_pool_free_bytes_doc =
"Returns the amount of free space in the underlying shared memory pool.";
static PyObject* sharedstructures_HashTable_pool_free_bytes(PyObject* py_self) {
sharedstructures_HashTable* self = (sharedstructures_HashTable*)py_self;
return PyLong_FromSize_t(self->table->get_allocator()->bytes_free());
}
static const char* sharedstructures_HashTable_pool_allocated_bytes_doc =
"Returns the amount of allocated space in the underlying shared memory pool.";
static PyObject* sharedstructures_HashTable_pool_allocated_bytes(PyObject* py_self) {
sharedstructures_HashTable* self = (sharedstructures_HashTable*)py_self;
return PyLong_FromSize_t(self->table->get_allocator()->bytes_allocated());
}
static PyMethodDef sharedstructures_HashTable_methods[] = {
{"pool_bytes", (PyCFunction)sharedstructures_HashTable_pool_bytes, METH_NOARGS,
sharedstructures_HashTable_pool_bytes_doc},
{"pool_free_bytes", (PyCFunction)sharedstructures_HashTable_pool_free_bytes, METH_NOARGS,
sharedstructures_HashTable_pool_free_bytes_doc},
{"pool_allocated_bytes", (PyCFunction)sharedstructures_HashTable_pool_allocated_bytes, METH_NOARGS,
sharedstructures_HashTable_pool_allocated_bytes_doc},
{"check_and_set", (PyCFunction)sharedstructures_HashTable_check_and_set, METH_VARARGS,
sharedstructures_HashTable_check_and_set_doc},
{"check_missing_and_set", (PyCFunction)sharedstructures_HashTable_check_missing_and_set, METH_VARARGS,
sharedstructures_HashTable_check_missing_and_set_doc},
{"clear", (PyCFunction)sharedstructures_HashTable_clear, METH_NOARGS,
sharedstructures_HashTable_clear_doc},
{"bits", (PyCFunction)sharedstructures_HashTable_bits, METH_NOARGS,
sharedstructures_HashTable_bits_doc},
{"iterkeys", (PyCFunction)sharedstructures_HashTable_iterkeys, METH_NOARGS,
sharedstructures_HashTable_iterkeys_doc},
{"keys", (PyCFunction)sharedstructures_HashTable_iterkeys, METH_NOARGS,
sharedstructures_HashTable_iterkeys_doc},
{"itervalues", (PyCFunction)sharedstructures_HashTable_itervalues, METH_NOARGS,
sharedstructures_HashTable_itervalues_doc},
{"values", (PyCFunction)sharedstructures_HashTable_itervalues, METH_NOARGS,
sharedstructures_HashTable_itervalues_doc},
{"iteritems", (PyCFunction)sharedstructures_HashTable_iteritems, METH_NOARGS,
sharedstructures_HashTable_iteritems_doc},
{"items", (PyCFunction)sharedstructures_HashTable_iteritems, METH_NOARGS,
sharedstructures_HashTable_iteritems_doc},
{"verify", (PyCFunction)sharedstructures_HashTable_verify, METH_NOARGS,
sharedstructures_HashTable_verify_doc},
{nullptr, nullptr, 0, nullptr},
};
static PySequenceMethods sharedstructures_HashTable_sequencemethods = {
sharedstructures_HashTable_Len, // sq_length
0, // sq_concat
0, // sq_repeat
0, // sq_item (we implement GetItem via the mapping protocol instead)
0, // sq_slice
0, // sq_ass_item (we implement GetItem via the mapping protocol instead)
0, // sq_ass_slice
sharedstructures_HashTable_In, // sq_contains
0, // sq_inplace_concat
0, // sq_inplace_repeat
};
static PyMappingMethods sharedstructures_HashTable_mappingmethods = {
sharedstructures_HashTable_Len,
sharedstructures_HashTable_GetItem,
sharedstructures_HashTable_SetItem,
};
static PyTypeObject sharedstructures_HashTableType = {
PyVarObject_HEAD_INIT(nullptr, 0)
"sharedstructures.HashTable", // tp_name
sizeof(sharedstructures_HashTable), // tp_basicsize
0, // tp_itemsize
(destructor)sharedstructures_HashTable_Dealloc, // tp_dealloc
0, // tp_print
0, // tp_getattr
0, // tp_setattr
0, // tp_compare
sharedstructures_HashTable_Repr, // tp_repr
0, // tp_as_number
&sharedstructures_HashTable_sequencemethods, // tp_as_sequence
&sharedstructures_HashTable_mappingmethods, // tp_as_mapping
0, // tp_hash
0, // tp_call
0, // tp_str
0, // tp_getattro
0, // tp_setattro
0, // tp_as_buffer
Py_TPFLAGS_DEFAULT, // tp_flag
sharedstructures_HashTable_doc, // tp_doc
0, // tp_traverse
0, // tp_clear
0, // tp_richcompare
0, // tp_weaklistoffset
sharedstructures_HashTable_Iter, // tp_iter
0, // tp_iternext
sharedstructures_HashTable_methods, // tp_methods
0, // tp_members
0, // tp_getset
0, // tp_base
0, // tp_dict
0, // tp_descr_get
0, // tp_descr_set
0, // tp_dictoffset
0, // tp_init
0, // tp_alloc
sharedstructures_HashTable_New, // tp_new
0, // tp_free
0, // tp_is_gc
0, // tp_bases
0, // tp_mro
0, // tp_cache
0, // tp_subclasses
0, // tp_weaklist
0, // tp_del
0, // tp_version_tag
0, // tp_finalize
0, // tp_vectorcall
};
// PrefixTreeIterator object method definitions
static PyObject* sharedstructures_PrefixTreeIterator_New(PyTypeObject* type,
PyObject* args, PyObject* kwargs) {
sharedstructures_PrefixTreeIterator* self = (sharedstructures_PrefixTreeIterator*)PyType_GenericNew(
type, args, kwargs);
if (!self) {
return nullptr;
}
// See comment in sharedstructures_HashTableIterator_New about const_cast
static const char* kwarg_names[] = {"tree_obj", "return_keys", "return_values",
"prefix", nullptr};
static char** kwarg_names_arg = const_cast<char**>(kwarg_names);
PyObject* return_keys_obj = Py_True;
PyObject* return_values_obj = Py_True;
PyObject* prefix_obj = nullptr;
if (!PyArg_ParseTupleAndKeywords(args, kwargs, "O|OOO", kwarg_names_arg,
&self->tree_obj, &return_keys_obj, &return_values_obj, &prefix_obj)) {
return nullptr;
}
if (return_keys_obj == Py_True) {
self->return_keys = true;
} else if (return_keys_obj == Py_False) {
self->return_keys = false;
} else {
PyErr_SetString(PyExc_NotImplementedError, "iter() got non-bool return_keys");
return nullptr;
}
if (return_values_obj == Py_True) {
self->return_values = true;
} else if (return_values_obj == Py_False) {
self->return_values = false;
} else {
PyErr_SetString(PyExc_NotImplementedError, "iter() got non-bool return_values");
return nullptr;
}