From a5bf532d53db37414d5e6b25f139ef237a854cc1 Mon Sep 17 00:00:00 2001 From: Jason Paryani Date: Mon, 4 May 2015 11:00:25 -0700 Subject: [PATCH] Add `init` method to lists --- capnp/lib/capnp.pxd | 2 ++ capnp/lib/capnp.pyx | 11 +++++++++++ test/addressbook.capnp | 3 +++ test/test_struct.py | 13 +++++++++++++ 4 files changed, 29 insertions(+) diff --git a/capnp/lib/capnp.pxd b/capnp/lib/capnp.pxd index d7e3360..4936dd7 100644 --- a/capnp/lib/capnp.pxd +++ b/capnp/lib/capnp.pxd @@ -115,6 +115,8 @@ cdef class _DynamicListBuilder: cpdef adopt(self, index, _DynamicOrphan orphan) cpdef disown(self, index) + cpdef init(self, index, size) + cdef to_python_reader(C_DynamicValue.Reader self, object parent) cdef to_python_builder(C_DynamicValue.Builder self, object parent) cdef _to_dict(msg, bint verbose, bint ordered) diff --git a/capnp/lib/capnp.pyx b/capnp/lib/capnp.pyx index 8b9f885..41f7b50 100644 --- a/capnp/lib/capnp.pyx +++ b/capnp/lib/capnp.pyx @@ -534,6 +534,17 @@ cdef class _DynamicListBuilder: """ 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 printListBuilder(self.thisptr).flatten().cStr() diff --git a/test/addressbook.capnp b/test/addressbook.capnp index b50b68b..576396c 100644 --- a/test/addressbook.capnp +++ b/test/addressbook.capnp @@ -37,3 +37,6 @@ struct AddressBook { people @0 :List(Person); } +struct NestedList { + list @0 :List(List(Int32)); +} diff --git a/test/test_struct.py b/test/test_struct.py index f0c3b45..563ba02 100644 --- a/test/test_struct.py +++ b/test/test_struct.py @@ -218,3 +218,16 @@ def test_to_dict_ordered(addressbook): else: with pytest.raises(Exception): person.to_dict(ordered=True) + +def test_nested_list(addressbook): + struct = addressbook.NestedList.new_message() + struct.init('list', 2) + + struct.list.init(0, 1) + struct.list.init(1, 2) + + struct.list[0][0] = 1 + struct.list[1][0] = 2 + struct.list[1][1] = 3 + + assert struct.to_dict()["list"] == [[1], [2,3]]