forked from capnproto/pycapnp
-
Notifications
You must be signed in to change notification settings - Fork 0
/
capnp.pyx
4457 lines (3479 loc) · 162 KB
/
capnp.pyx
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
# capnp.pyx
# distutils: language = c++
# distutils: libraries = capnpc capnp-rpc capnp kj-async kj
# distutils: include_dirs = .
# cython: c_string_type = str
# cython: c_string_encoding = default
# cython: embedsignature = True
# cython: language_level = 2
cimport cython # noqa: E402
from capnp.helpers.helpers cimport init_capnp_api
from capnp.includes.capnp_cpp cimport AsyncIoStream, WaitScope, PyPromise, VoidPromise, EventPort, EventLoop, Canceler, PyAsyncIoStream, PromiseFulfiller, VoidPromiseFulfiller, tryReadMessage, writeMessage, makeException, PythonInterfaceDynamicImpl
from capnp.includes.schema_cpp cimport (MessageReader,)
from cpython cimport array, Py_buffer, PyObject_CheckBuffer, memoryview, buffer
from cpython.buffer cimport PyBUF_SIMPLE, PyBUF_WRITABLE
from cpython.exc cimport PyErr_Clear
from cython.operator cimport dereference as deref
from libc.stdlib cimport malloc, free
from libc.string cimport memcpy
from libcpp.utility cimport move
import array
import asyncio
import collections as _collections
import contextlib
import enum as _enum
import inspect as _inspect
import os as _os
import random as _random
import socket as _socket
import sys as _sys
import threading as _threading
import traceback as _traceback
import warnings as _warnings
import weakref as _weakref
import traceback as _traceback
from types import ModuleType as _ModuleType
from operator import attrgetter as _attrgetter
from functools import partial as _partial
from contextlib import asynccontextmanager as _asynccontextmanager
from importlib.machinery import ModuleSpec
_CAPNP_VERSION_MAJOR = capnp.CAPNP_VERSION_MAJOR
_CAPNP_VERSION_MINOR = capnp.CAPNP_VERSION_MINOR
_CAPNP_VERSION_MICRO = capnp.CAPNP_VERSION_MICRO
_CAPNP_VERSION = capnp.CAPNP_VERSION
cdef dict _type_registry = {}
def register_type(id, klass):
_type_registry[id] = klass
def deregister_all_types():
_type_registry = {}
# By making it public, we'll be able to call it from capabilityHelper.h
cdef api object wrap_dynamic_struct_reader(Response & r) with gil:
return _Response()._init_childptr(new Response(move(r)), None)
cdef _find_field_order(struct_node):
return [f.name for f in sorted(struct_node.fields, key=_attrgetter('codeOrder'))]
cdef class _VoidPromiseFulfiller:
cdef VoidPromiseFulfiller* fulfiller
cdef _init(self, VoidPromiseFulfiller* fulfiller):
self.fulfiller = fulfiller
return self
def void_task_done_callback(method_name, _VoidPromiseFulfiller fulfiller, task):
if fulfiller.fulfiller == NULL:
return
if task.cancelled():
fulfiller.fulfiller.reject(makeException(capnp.StringPtr(
f"Server task for method {method_name} was cancelled")))
return
exc = task.exception()
if exc is not None:
fulfiller.fulfiller.reject(makeException(capnp.StringPtr(''.join(
_traceback.format_exception(type(exc), exc, exc.__traceback__)))))
return
res = task.result()
if res is not None:
fulfiller.fulfiller.reject(makeException(capnp.StringPtr(
f"Async server function ({method_name}) returned a non-none value: return = {res}")))
else:
fulfiller.fulfiller.fulfill()
cdef api void promise_task_add_done_callback(object task, object callback, VoidPromiseFulfiller& fulfiller):
wrapper = _VoidPromiseFulfiller()._init(&fulfiller)
task.add_done_callback(_partial(callback, wrapper))
task._fulfiller = wrapper
cdef api void promise_task_cancel(object task):
(<_VoidPromiseFulfiller>task._fulfiller).fulfiller = NULL
task.cancel()
def fill_context(method_name, context, returned_data):
if returned_data is None:
return
if not isinstance(returned_data, tuple):
returned_data = (returned_data,)
names = _find_field_order(context.results.schema.node.struct)
if len(returned_data) > len(names):
raise KjException(
"Too many values returned from `{}`. Expected {} and got {}"
.format(method_name, len(names), len(returned_data)))
results = context.results
for arg_name, arg_val in zip(names, returned_data):
setattr(results, arg_name, arg_val)
cdef api VoidPromise * call_server_method(object server,
char * _method_name,
CallContext & _context,
object _kj_loop) except * with gil:
method_name = <object>_method_name
kj_loop = <_EventLoop>_kj_loop
kj_loop.check()
context = _CallContext()._init(_context) # TODO:MEMORY: invalidate this with promise chain
func = getattr(server, method_name+'_context', None)
if func is not None:
ret = func(context)
if not asyncio.iscoroutine(ret):
raise ValueError(
"Server function ({}) is not a coroutine"
.format(method_name, str(ret)))
task = asyncio.create_task(ret)
else:
async def finalize():
params = context.params
params_dict = {name: getattr(params, name) for name in params.schema.fieldnames}
params_dict['_context'] = context
func = getattr(server, method_name) # will raise if no function found
ret = func(**params_dict)
if not asyncio.iscoroutine(ret):
raise ValueError(
"Server function ({}) is not a coroutine"
.format(method_name, str(ret)))
fill_context(method_name, context, await ret)
task = asyncio.create_task(finalize())
kj_loop.active_tasks.add(task)
callback = _partial(void_task_done_callback, method_name)
return new VoidPromise(helpers.taskToPromise(
capnp.heap[PyRefCounter](<PyObject*>task),
<PyObject*>callback))
cdef extern from "<kj/string.h>" namespace " ::kj":
String strStructReader" ::kj::str"(C_DynamicStruct.Reader)
String strStructBuilder" ::kj::str"(DynamicStruct_Builder)
String strRequest" ::kj::str"(Request &)
String strListReader" ::kj::str"(C_DynamicList.Reader)
String strListBuilder" ::kj::str"(C_DynamicList.Builder)
String strException" ::kj::str"(capnp.Exception)
def _make_enum(enum_name, *sequential, **named):
enums = dict(zip(sequential, range(len(sequential))), **named)
reverse = dict((value, key) for key, value in enums.iteritems())
enums['reverse_mapping'] = reverse
return type(enum_name, (), enums)
_Type = _make_enum(
"_Type",
FAILED=0,
OVERLOADED=1,
DISCONNECTED=2,
UNIMPLEMENTED=3,
OTHER=4,
)
cdef class _KjExceptionWrapper:
cdef capnp.Exception * thisptr
cdef _init(self, capnp.Exception & other):
self.thisptr = new capnp.Exception(move(other))
return self
def __dealloc__(self):
del self.thisptr
property file:
def __get__(self):
return <char*>self.thisptr.getFile()
property line:
def __get__(self):
return self.thisptr.getLine()
property type:
def __get__(self):
cdef int temp = <int>self.thisptr.getType()
return _Type.reverse_mapping[temp]
property description:
def __get__(self):
return <char*>self.thisptr.getDescription().cStr()
def __str__(self):
return <char*>strException(deref(self.thisptr)).cStr()
# Extension classes can't inherit from Exception, so we're going to proxy wrap kj::Exception,
# and forward all calls to it from this Python class
class KjException(Exception):
"""KjException is a wrapper of the internal C++ exception type.
There is an enum named `Type` listed below, and a bunch of fields."""
Type = _make_enum("Type", **{x: x for x in _Type.reverse_mapping.values()})
def __init__(self, message=None, nature=None, durability=None, wrapper=None, type=None):
if wrapper is not None:
self.wrapper = wrapper
self.message = str(wrapper)
else:
self.wrapper = None
self.message = message
self.nature = nature
self.durability = durability
self._type = type
@property
def file(self):
return self.wrapper.file
@property
def line(self):
return self.wrapper.line
@property
def type(self):
if self.wrapper is not None:
return self.wrapper.type
else:
return self._type
@property
def description(self):
if self.wrapper is not None:
return self.wrapper.description
else:
return self.message
def __str__(self):
return self.message
def _to_python(self):
message = self.message
if self.wrapper.type == 'FAILED':
if 'has no such' in self.message:
return AttributeError(message)
return self
cdef api object wrap_kj_exception(capnp.Exception & exception) with gil:
PyErr_Clear()
wrapper = _KjExceptionWrapper()._init(exception)
ret = KjException(wrapper=wrapper)
return ret
cdef api object wrap_kj_exception_for_reraise(capnp.Exception & exception) with gil:
wrapper = _KjExceptionWrapper()._init(exception)
ret = KjException(wrapper=wrapper)
return ret
cdef api object get_exception_info(object exc_type, object exc_obj, object exc_tb) with gil:
try:
return (exc_tb.tb_frame.f_code.co_filename.encode(),
exc_tb.tb_lineno,
(repr(exc_type) + ":" + str(exc_obj)).encode())
except Exception:
return (b'', 0, b"Couldn't determine python exception")
cdef schema_cpp.ReaderOptions make_reader_opts(traversal_limit_in_words, nesting_limit) with gil:
cdef schema_cpp.ReaderOptions opts
if traversal_limit_in_words is not None:
opts.traversalLimitInWords = traversal_limit_in_words
if nesting_limit is not None:
opts.nestingLimit = nesting_limit
return opts
ctypedef fused _DynamicStructReaderOrBuilder:
_DynamicStructReader
_DynamicStructBuilder
ctypedef fused _DynamicSetterClasses:
C_DynamicList.Builder
DynamicStruct_Builder
cdef extern from "Python.h":
cdef int PyObject_GetBuffer(object, Py_buffer *view, int flags)
cdef void PyBuffer_Release(Py_buffer *view)
# Templated classes are weird in cython. I couldn't put it in a pxd header for some reason
cdef extern from "capnp/list.h" namespace " ::capnp":
cdef cppclass List[T]:
cppclass Reader:
T operator[](uint) except +reraise_kj_exception
uint size()
cppclass Builder:
T operator[](uint) except +reraise_kj_exception
uint size()
cdef extern from "<capnp/pretty-print.h>" namespace " ::capnp":
StringTree printStructReader" ::capnp::prettyPrint"(C_DynamicStruct.Reader) except +reraise_kj_exception
StringTree printStructBuilder" ::capnp::prettyPrint"(DynamicStruct_Builder) except +reraise_kj_exception
StringTree printRequest" ::capnp::prettyPrint"(Request &) except +reraise_kj_exception
StringTree printListReader" ::capnp::prettyPrint"(C_DynamicList.Reader) except +reraise_kj_exception
StringTree printListBuilder" ::capnp::prettyPrint"(C_DynamicList.Builder) except +reraise_kj_exception
cdef class _NodeReader:
cdef C_Node.Reader thisptr
cdef init(self, C_Node.Reader other):
self.thisptr = other
return self
property displayName:
def __get__(self):
return <char*>self.thisptr.getDisplayName().cStr()
property scopeId:
def __get__(self):
return self.thisptr.getScopeId()
property id:
def __get__(self):
return self.thisptr.getId()
property nestedNodes:
def __get__(self):
return _List_NestedNode_Reader()._init(self.thisptr.getNestedNodes())
property isStruct:
def __get__(self):
return self.thisptr.isStruct()
property isConst:
def __get__(self):
return self.thisptr.isConst()
property isInterface:
def __get__(self):
return self.thisptr.isInterface()
property isEnum:
def __get__(self):
return self.thisptr.isEnum()
property node:
"""A property that returns the NodeReader as a DynamicStructReader."""
def __get__(self):
return _DynamicStructReader()._init(self.thisptr, self)
cdef class _NestedNodeReader:
cdef C_Node.NestedNode.Reader thisptr
cdef init(self, C_Node.NestedNode.Reader other):
self.thisptr = other
return self
property name:
def __get__(self):
return <char*>self.thisptr.getName().cStr()
property id:
def __get__(self):
return self.thisptr.getId()
cdef class _DynamicListReader:
"""Class for reading Cap'n Proto Lists
This class thinly wraps the C++ Cap'n Proto DynamicList::Reader class. __getitem__ and __len__
have been defined properly, so you can treat this class mostly like any other iterable class::
...
person = addressbook.Person.read(file)
phones = person.phones # This returns a _DynamicListReader
phone = phones[0]
print phone.number
for phone in phones:
print phone.number
"""
cdef C_DynamicList.Reader thisptr
cdef public object _parent
cdef _init(self, C_DynamicList.Reader other, object parent):
self.thisptr = other
self._parent = parent
return self
cpdef _get(self, int64_t index):
return to_python_reader(self.thisptr[index], self._parent)
def __getitem__(self, int64_t index):
cdef uint size = self.thisptr.size()
if index >= size:
raise IndexError('Out of bounds')
index = index % size
return self._get(index)
def __len__(self):
return self.thisptr.size()
def __str__(self):
return <char*>printListReader(self.thisptr).flatten().cStr()
def __repr__(self):
# TODO: Print the list type.
return '<capnp list reader %s>' % <char*>strListReader(self.thisptr).cStr()
cdef class _DynamicResizableListBuilder:
"""Class for building growable Cap'n Proto Lists
.. warning:: You need to call :meth:`finish` on this object before serializing the Cap'n Proto message.
Failure to do so will cause your objects not to be written out as well as leaking orphan structs into your message.
This class works much like :class:`_DynamicListBuilder`, but it allows growing the list dynamically.
It is meant for lists of structs, since for primitive types like int or float, you're much better off
using a normal python list and then serializing straight to a Cap'n Proto list.
It has __getitem__ and __len__ defined, but not __setitem__::
...
person = addressbook.Person.new_message()
phones = person.init_resizable_list('phones') # This returns a _DynamicResizableListBuilder
phone = phones.add()
phone.number = 'foo'
phone = phones.add()
phone.number = 'bar'
phones.finish()
f = open('example', 'w')
person.write(f)
"""
cdef public object _parent, _message, _field, _schema
cdef public list _list
def __init__(self, parent, field, schema):
self._parent = parent
self._message = parent._parent
self._field = field
self._schema = schema
self._list = list()
cpdef add(self):
"""A method for adding a new struct to the list
This will return a struct, in which you can set fields that will be reflected in the serialized
Cap'n Proto message.
:rtype: :class:`_DynamicStructBuilder`
"""
orphan = self._message.new_orphan(self._schema)
orphan_val = orphan.get()
self._list.append((orphan, orphan_val))
return orphan_val
cpdef _get(self, index):
return self._list[index][1]
def __getitem__(self, index):
return self._list[index][1]
# def __setitem__(self, index, val):
# self._list[index] = val
def __len__(self):
return len(self._list)
def finish(self):
"""A method for closing this list and serializing all its members to the message
If you don't call this method, the items you previously added from this object will leak into the message,
ie. inaccessible but still taking up space.
"""
cdef int i = 0
new_list = self._parent.init(self._field, len(self))
for orphan, _ in self._list:
new_list.adopt(i, orphan)
i += 1
cdef class _DynamicListBuilder:
"""Class for building Cap'n Proto Lists
This class thinly wraps the C++ Cap'n Proto DynamicList::Bulder class. __getitem__, __setitem__, and __len__
have been defined properly, so you can treat this class mostly like any other iterable class::
...
person = addressbook.Person.new_message()
phones = person.init('phones', 2) # This returns a _DynamicListBuilder
phone = phones[0]
phone.number = 'foo'
phone = phones[1]
phone.number = 'bar'
for phone in phones:
print phone.number
"""
cdef _init(self, C_DynamicList.Builder other, object parent):
self.thisptr = other
self._parent = parent
return self
cpdef _get(self, int64_t index):
return to_python_builder(self.thisptr[index], self._parent)
def __getitem__(self, int64_t index):
cdef uint size = self.thisptr.size()
if index >= size:
raise IndexError('Out of bounds')
index = index % size
return self._get(index)
cpdef _set(self, index, value):
_setDynamicField(self.thisptr, index, value, self._parent)
def __setitem__(self, index, value):
size = self.thisptr.size()
if index >= size:
raise IndexError('Out of bounds')
index = index % size
_setDynamicField(self.thisptr, index, value, self._parent)
def __len__(self):
return self.thisptr.size()
cpdef adopt(self, index, _DynamicOrphan orphan):
"""A method for adopting Cap'n Proto orphans
Don't use this method unless you know what you're doing.
Orphans are useful for dynamically allocating objects for an unknown sized list.
:type index: int
:param index: The index of the element in the list to replace with the newly adopted object
:type orphan: :class:`_DynamicOrphan`
:param orphan: A Cap'n proto orphan to adopt. It will be unusable after this operation.
:rtype: void
"""
self.thisptr.adopt(index, orphan.move())
cpdef disown(self, index):
"""A method for disowning Cap'n Proto orphans
Don't use this method unless you know what you're doing.
:type index: int
:param index: The index of the element in the list to disown
:rtype: :class:`_DynamicOrphan`
"""
return _DynamicOrphan()._init(self.thisptr.disown(index), self._parent)
cpdef init(self, index, size):
"""A method for initializing an element in a list
:type index: int
:param index: The index of the element in the list
:type size: int
:param size: Size of the element to be initialized.
"""
return to_python_builder(self.thisptr.init(index, size), self._parent)
def __str__(self):
return <char*>printListBuilder(self.thisptr).flatten().cStr()
def __repr__(self):
# TODO: Print the list type.
return '<capnp list builder %s>' % <char*>strListBuilder(self.thisptr).cStr()
cdef class _List_NestedNode_Reader:
cdef C_Node.NestedNode.Reader.ListNestedNodeReader thisptr
cdef _init(self, List[C_Node.NestedNode].Reader other):
self.thisptr = <C_Node.NestedNode.Reader.ListNestedNodeReader>other
return self
def __getitem__(self, index):
size = self.thisptr.size()
if index >= size:
raise IndexError('Out of bounds')
index = index % size
return _NestedNodeReader().init(<C_Node.NestedNode.Reader>self.thisptr[index])
def __len__(self):
return self.thisptr.size()
# cdef to_python_pipeline(C_DynamicValue.Pipeline self, object parent):
# cdef int type = self.getType()
# if type == capnp.TYPE_CAPABILITY:
# return _DynamicCapabilityClient()._init(self.asCapability(), parent)
# # elif type == capnp.TYPE_STRUCT:
# # return _DynamicStructReader()._init(self.asStruct(), parent)
# elif type == capnp.TYPE_UNKNOWN:
# raise KjException("Cannot convert type to Python. Type is unknown by capnproto library")
# else:
# raise KjException("Cannot convert type to Python. Type is unhandled by capnproto library")
cdef to_python_reader(C_DynamicValue.Reader self, object parent):
cdef int type = self.getType()
if type == capnp.TYPE_BOOL:
return self.asBool()
elif type == capnp.TYPE_INT:
return self.asInt()
elif type == capnp.TYPE_UINT:
return self.asUint()
elif type == capnp.TYPE_FLOAT:
return self.asDouble()
elif type == capnp.TYPE_TEXT:
temp_text = self.asText()
return (<char*>temp_text.begin())[:temp_text.size()]
elif type == capnp.TYPE_DATA:
temp_data = self.asData()
return <bytes>((<char*>temp_data.begin())[:temp_data.size()])
elif type == capnp.TYPE_LIST:
return _DynamicListReader()._init(self.asList(), parent)
elif type == capnp.TYPE_STRUCT:
return _DynamicStructReader()._init(self.asStruct(), parent)
elif type == capnp.TYPE_ENUM:
return _DynamicEnum()._init(self.asEnum(), parent)
elif type == capnp.TYPE_VOID:
return None
elif type == capnp.TYPE_ANY_POINTER:
return _DynamicObjectReader()._init(self.asObject(), parent)
elif type == capnp.TYPE_CAPABILITY:
return _DynamicCapabilityClient()._init(self.asCapability(), parent)
elif type == capnp.TYPE_UNKNOWN:
raise KjException("Cannot convert type to Python. Type is unknown by capnproto library")
else:
raise KjException("Cannot convert type to Python. Type is unhandled by capnproto library")
cdef to_python_builder(C_DynamicValue.Builder self, object parent):
cdef int type = self.getType()
if type == capnp.TYPE_BOOL:
return self.asBool()
elif type == capnp.TYPE_INT:
return self.asInt()
elif type == capnp.TYPE_UINT:
return self.asUint()
elif type == capnp.TYPE_FLOAT:
return self.asDouble()
elif type == capnp.TYPE_TEXT:
temp_text = self.asText()
return (<char*>temp_text.begin())[:temp_text.size()]
elif type == capnp.TYPE_DATA:
temp_data = self.asData()
return <bytes>((<char*>temp_data.begin())[:temp_data.size()])
elif type == capnp.TYPE_LIST:
return _DynamicListBuilder()._init(self.asList(), parent)
elif type == capnp.TYPE_STRUCT:
return _DynamicStructBuilder()._init(self.asStruct(), parent)
elif type == capnp.TYPE_ENUM:
return _DynamicEnum()._init(self.asEnum(), parent)
elif type == capnp.TYPE_VOID:
return None
elif type == capnp.TYPE_ANY_POINTER:
return _DynamicObjectBuilder()._init(self.asObject(), parent)
elif type == capnp.TYPE_CAPABILITY:
return _DynamicCapabilityClient()._init(self.asCapability(), parent)
elif type == capnp.TYPE_UNKNOWN:
raise KjException("Cannot convert type to Python. Type is unknown by capnproto library")
else:
raise KjException("Cannot convert type to Python. Type is unhandled by capnproto library")
cdef C_DynamicValue.Reader _extract_dynamic_struct_builder(_DynamicStructBuilder value):
return C_DynamicValue.Reader(value.thisptr.asReader())
cdef C_DynamicValue.Reader _extract_dynamic_struct_reader(_DynamicStructReader value):
return C_DynamicValue.Reader(value.thisptr)
cdef C_DynamicValue.Reader _extract_dynamic_client(_DynamicCapabilityClient value):
return C_DynamicValue.Reader(value.thisptr)
cdef C_DynamicValue.Reader _extract_dynamic_server(object value):
cdef _InterfaceSchema schema = value.schema
kj_loop = C_DEFAULT_EVENT_LOOP_GETTER()
return C_DynamicValue.Reader(capnp.heap[PythonInterfaceDynamicImpl](
schema.thisptr,
capnp.heap[PyRefCounter](<PyObject*>value),
capnp.heap[PyRefCounter](<PyObject*>kj_loop)))
cdef C_DynamicValue.Reader _extract_dynamic_enum(_DynamicEnum value):
return C_DynamicValue.Reader(value.thisptr)
cdef C_DynamicValue.Reader _extract_any_pointer(_DynamicObjectReader value):
return C_DynamicValue.Reader(value.thisptr)
cdef C_DynamicValue.Reader _extract_any_pointer_builder(_DynamicObjectBuilder value):
return C_DynamicValue.Reader(value.thisptr.asReader())
cdef _setBytes(_DynamicSetterClasses thisptr, field, value):
cdef capnp.StringPtr temp_string = capnp.StringPtr(<char*>value, len(value))
cdef C_DynamicValue.Reader temp = C_DynamicValue.Reader(temp_string)
thisptr.set(field, temp)
cdef _setBaseString(_DynamicSetterClasses thisptr, field, value):
encoded_value = value.encode('utf-8')
cdef capnp.StringPtr temp_string = capnp.StringPtr(<char*>encoded_value, len(encoded_value))
cdef C_DynamicValue.Reader temp = C_DynamicValue.Reader(temp_string)
thisptr.set(field, temp)
cdef _setBytesField(DynamicStruct_Builder thisptr, _StructSchemaField field, value):
cdef capnp.StringPtr temp_string = capnp.StringPtr(<char*>value, len(value))
cdef C_DynamicValue.Reader temp = C_DynamicValue.Reader(temp_string)
thisptr.setByField(field.thisptr, temp)
cdef _setBaseStringField(DynamicStruct_Builder thisptr, _StructSchemaField field, value):
encoded_value = value.encode('utf-8')
cdef capnp.StringPtr temp_string = capnp.StringPtr(<char*>encoded_value, len(encoded_value))
cdef C_DynamicValue.Reader temp = C_DynamicValue.Reader(temp_string)
thisptr.setByField(field.thisptr, temp)
cdef _setDynamicField(_DynamicSetterClasses thisptr, field, value, parent):
cdef C_DynamicValue.Reader temp
value_type = type(value)
if value_type is int or value_type is long:
if value < 0:
temp = C_DynamicValue.Reader(<long long>value)
else:
temp = C_DynamicValue.Reader(<unsigned long long>value)
thisptr.set(field, temp)
elif value_type is float:
temp = C_DynamicValue.Reader(<double>value)
thisptr.set(field, temp)
elif value_type is bool:
temp = C_DynamicValue.Reader(<cbool>value)
thisptr.set(field, temp)
elif value_type is bytes:
_setBytes(thisptr, field, value)
elif isinstance(value, basestring):
_setBaseString(thisptr, field, value)
elif value_type is list:
builder = to_python_builder(thisptr.init(field, len(value)), parent)
_from_list(builder, value)
elif value_type is tuple:
builder = to_python_builder(thisptr.init(field, len(value)), parent)
_from_tuple(builder, value)
elif value_type is dict:
if _DynamicSetterClasses is DynamicStruct_Builder:
builder = to_python_builder(thisptr.get(field), parent)
builder.from_dict(value)
else:
builder = to_python_builder(thisptr[field], parent)
builder.from_dict(value)
elif value is None:
temp = C_DynamicValue.Reader(VOID)
thisptr.set(field, temp)
elif value_type is _DynamicStructBuilder:
thisptr.set(field, _extract_dynamic_struct_builder(value))
elif value_type is _DynamicStructReader:
thisptr.set(field, _extract_dynamic_struct_reader(value))
elif value_type is _DynamicCapabilityClient:
thisptr.set(field, _extract_dynamic_client(value))
elif isinstance(value, _DynamicCapabilityServer):
thisptr.set(field, _extract_dynamic_server(value))
elif value_type is _DynamicEnum:
thisptr.set(field, _extract_dynamic_enum(value))
elif value_type is _DynamicObjectReader:
thisptr.set(field, _extract_any_pointer(value))
elif value_type is _DynamicObjectBuilder:
thisptr.set(field, _extract_any_pointer_builder(value))
else:
raise KjException(
"Tried to set field: '{}' with a value of: '{}' which is an unsupported type: '{}'"
.format(field, str(value), str(type(value))))
cdef _setDynamicFieldWithField(DynamicStruct_Builder thisptr, _StructSchemaField field, value, parent):
cdef C_DynamicValue.Reader temp
value_type = type(value)
if value_type is int or value_type is long:
if value < 0:
temp = C_DynamicValue.Reader(<long long>value)
else:
temp = C_DynamicValue.Reader(<unsigned long long>value)
thisptr.setByField(field.thisptr, temp)
elif value_type is float:
temp = C_DynamicValue.Reader(<double>value)
thisptr.setByField(field.thisptr, temp)
elif value_type is bool:
temp = C_DynamicValue.Reader(<cbool>value)
thisptr.setByField(field.thisptr, temp)
elif value_type is bytes:
_setBytesField(thisptr, field, value)
elif isinstance(value, basestring):
_setBaseStringField(thisptr, field, value)
elif value_type is list:
builder = to_python_builder(thisptr.init(field.proto.name, len(value)), parent)
_from_list(builder, value)
elif value_type is dict:
builder = to_python_builder(thisptr.getByField(field.thisptr), parent)
builder.from_dict(value)
elif value is None:
temp = C_DynamicValue.Reader(VOID)
thisptr.setByField(field.thisptr, temp)
elif value_type is _DynamicStructBuilder:
thisptr.setByField(field.thisptr, _extract_dynamic_struct_builder(value))
elif value_type is _DynamicStructReader:
thisptr.setByField(field.thisptr, _extract_dynamic_struct_reader(value))
elif value_type is _DynamicCapabilityClient:
thisptr.setByField(field.thisptr, _extract_dynamic_client(value))
elif isinstance(value, _DynamicCapabilityServer):
thisptr.setByField(field.thisptr, _extract_dynamic_server(value))
elif value_type is _DynamicEnum:
thisptr.setByField(field.thisptr, _extract_dynamic_enum(value))
elif value_type is _DynamicObjectReader:
thisptr.set(field, _extract_any_pointer(value))
elif value_type is _DynamicObjectBuilder:
thisptr.set(field, _extract_any_pointer_builder(value))
else:
raise KjException(
"Tried to set field: '{}' with a value of: '{}' which is an unsupported type: '{}'"
.format(field, str(value), str(type(value))))
cdef _setDynamicFieldStatic(DynamicStruct_Builder thisptr, field, value, parent):
cdef C_DynamicValue.Reader temp
value_type = type(value)
if value_type is int or value_type is long:
if value < 0:
temp = C_DynamicValue.Reader(<long long>value)
else:
temp = C_DynamicValue.Reader(<unsigned long long>value)
thisptr.set(field, temp)
elif value_type is float:
temp = C_DynamicValue.Reader(<double>value)
thisptr.set(field, temp)
elif value_type is bool:
temp = C_DynamicValue.Reader(<cbool>value)
thisptr.set(field, temp)
elif value_type is bytes:
_setBytes(thisptr, field, value)
elif isinstance(value, basestring):
_setBaseString(thisptr, field, value)
elif value_type is list:
builder = to_python_builder(thisptr.init(field, len(value)), parent)
_from_list(builder, value)
elif value_type is dict:
builder = to_python_builder(thisptr.get(field), parent)
builder.from_dict(value)
elif value is None:
temp = C_DynamicValue.Reader(VOID)
thisptr.set(field, temp)
elif value_type is _DynamicStructBuilder:
thisptr.set(field, _extract_dynamic_struct_builder(value))
elif value_type is _DynamicStructReader:
thisptr.set(field, _extract_dynamic_struct_reader(value))
elif value_type is _DynamicCapabilityClient:
thisptr.set(field, _extract_dynamic_client(value))
elif isinstance(value, _DynamicCapabilityServer):
thisptr.set(field, _extract_dynamic_server(value))
elif value_type is _DynamicEnum:
thisptr.set(field, _extract_dynamic_enum(value))
elif value_type is _DynamicObjectReader:
thisptr.set(field, _extract_any_pointer(value))
elif value_type is _DynamicObjectBuilder:
thisptr.set(field, _extract_any_pointer_builder(value))
else:
raise KjException(
"Tried to set field: '{}' with a value of: '{}' which is an unsupported type: '{}'"
.format(field, str(value), str(type(value))))
cdef _DynamicListBuilder temp_list_b
cdef _DynamicListReader temp_list_r
cdef _DynamicResizableListBuilder temp_list_rb
cdef _DynamicStructBuilder temp_msg_b
cdef _DynamicStructReader temp_msg_r
cdef _to_dict(msg, bint verbose, bint ordered):
msg_type = type(msg)
if msg_type is _DynamicListBuilder:
temp_list_b = msg
return [_to_dict(temp_list_b._get(i), verbose, ordered) for i in range(len(msg))]
elif msg_type is _DynamicListReader:
temp_list_r = msg
return [_to_dict(temp_list_r._get(i), verbose, ordered) for i in range(len(msg))]
elif msg_type is _DynamicResizableListBuilder:
temp_list_rb = msg
return [_to_dict(temp_list_rb._get(i), verbose, ordered) for i in range(len(msg))]
if msg_type is _DynamicStructBuilder or isinstance(msg, _Request):
temp_msg_b = msg
if ordered:
ret = _collections.OrderedDict()
else:
ret = {}
try:
which = temp_msg_b.which()
ret[which] = _to_dict(temp_msg_b._get(which), verbose, ordered)
except KjException:
pass
for field in temp_msg_b.schema.non_union_fields:
if verbose or temp_msg_b._has(field):
ret[field] = _to_dict(temp_msg_b._get(field), verbose, ordered)
return ret
elif msg_type is _DynamicStructReader or isinstance(msg, _Response):
temp_msg_r = msg
if ordered:
ret = _collections.OrderedDict()
else:
ret = {}
try:
which = temp_msg_r.which()
ret[which] = _to_dict(temp_msg_r._get(which), verbose, ordered)
except KjException:
pass
for field in temp_msg_r.schema.non_union_fields:
if verbose or temp_msg_r._has(field):
ret[field] = _to_dict(temp_msg_r._get(field), verbose, ordered)
return ret
if isinstance(msg, (_DynamicStructBuilder, _DynamicStructReader)):
return msg.to_dict(verbose, ordered)
if msg_type is _DynamicEnum:
return str(msg)
return msg
cdef _from_list(_DynamicListBuilder msg, list d):
for i, x in enumerate(d):
msg._set(i, x)
cdef _from_tuple(_DynamicListBuilder msg, tuple d):
for i, x in enumerate(d):
msg._set(i, x)
cdef class _DynamicEnum:
cdef _init(self, capnp.DynamicEnum other, object parent):
self.thisptr = other
self._parent = parent
return self
cpdef _as_str(self) except +reraise_kj_exception:
return <char*>helpers.fixMaybe(self.thisptr.getEnumerant()).getProto().getName().cStr()
property raw:
"""A property that returns the raw int of the enum"""
def __get__(self):