ludocode / mpack

MPack - A C encoder/decoder for the MessagePack serialization format / msgpack.org[C]
MIT License
521 stars 82 forks source link

question : open existing tree and modify values #62

Closed ad34 closed 5 years ago

ad34 commented 6 years ago

I'm trying to open an existing msgpack buffer and edit a specific field in the map , what is the best way to do this?

looks like mpack_tree_init & mpack_writer_init are two distinct concept

ludocode commented 6 years ago

Yep, MPack doesn't have any facilities for editing a parse tree. Everything parsed by the node API is immutable.

For something simple, your best bet would be to parse the tree, then walk over it to write it out, keeping track of where you are in the tree. This way you override whatever it is you want to change while writing.

If you want full dynamic editing capabilities you could build your own mutable tree. Each node in your mutable tree could be individually allocated and reference counted, and could contain an mpack_tag_t describing the node and a linked list of child nodes. This is sort of like how Jansson works for manipulating JSON. You could populate this tree from a reader (instead of using the node API) and write it out again with a writer in a few hundred lines of code. Just bear in mind that it will be very slow. That's why MPack doesn't implement it.

ad34 commented 6 years ago

Actually , I tried the simple solution you mentionned but did not find how can I write to a tree initialized with mpack_tree_init . my use case is really simple, I have a node in the root with a cstr value empty, and want to fill it with another cstr. should I open a mpack_writer with the existing binary buffer previously opened with mpack_writer_init and use mpack_write_kv ?

ludocode commented 6 years ago

Right, there's no way to modify a tree. You can't write into the existing buffer because changing the length of a string will move everything after it in the original message.

The only way to change something (at least with MPack) is to rewrite the entire message. You'll need to open a writer with a new buffer and write every element from the original tree except for the one you want to change.

ad34 commented 6 years ago

Thanks ! looks like the best option for my use case is to keep the writer opened until I get all the data to construct my message.