opensourcerouting / c-capnproto

C library/compiler for the Cap'n Proto serialization/RPC protocol
MIT License
118 stars 40 forks source link

Get expected size before writing in memory #26

Closed maxux closed 3 years ago

maxux commented 6 years ago

From what I see, in each example or project using c-capnproto, each time capn_write_mem is used, the target buffer is mostly everytime allocated on stack with small length (typically 4k or 8k).

If my object is (let assume) random amount of megabytes, how can I allocate a buffer large enough ? I don't see any function able to tell me the expected size of the output.

Is there any way possible to expect the final size to allocate it ?

detly commented 4 years ago

I've looked through the API and can't find anything to do this. Does it exist and I'm missing it?

detly commented 4 years ago

If you need this immediately, the function is arguably small enough to just be put in a header file (I called it capn_size.h) and used in an existing project:

#ifndef CAPN_SIZE_H
#define CAPN_SIZE_H

#include <capnp_c.h>

static inline int capn_size(struct capn *c)
{
    size_t headersz, datasz = 0;
    struct capn_ptr root;
    struct capn_segment *seg;
    int i;

    if (c->segnum == 0)
        return -1;

    root = capn_root(c);
    seg = root.seg;

    headersz = 8 * ((2 + c->segnum) / 2);

    for (i = 0; i < c->segnum; i++, seg = seg->next) {
        if (0 == seg)
            return -1;
        datasz += seg->len;
    }
    if (0 != seg)
        return -1;

    return (int) headersz+datasz;
}

#endif // CAPN_SIZE_H