Implemented capn_size() for dynamically calculating the required buffer size for capn_write_mem().

This commit is contained in:
Jason Heeris 2020-12-28 21:10:30 +08:00
parent 024dca615a
commit d29faccc64
3 changed files with 97 additions and 7 deletions

View file

@ -407,3 +407,29 @@ int capn_write_fd(struct capn *c, ssize_t (*write_fd)(int fd, const void *p, siz
return datasz;
}
int capn_size(struct capn *c)
{
uint32_t headerlen;
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;
header_calc(c, &headerlen, &headersz);
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;
}

View file

@ -276,6 +276,12 @@ void capn_init_malloc(struct capn *c);
int capn_init_fp(struct capn *c, FILE *f, int packed);
int capn_init_mem(struct capn *c, const uint8_t *p, size_t sz, int packed);
/* capn_size calculates the amount of memory required for the buffer passed to
* capn_write_mem. It does not calculate the size for packed serialization, but
* that will always be less than the unpacked size.
*/
int capn_size(struct capn *c);
/* capn_write_(fp|mem) writes segments to the file/memory buffer in
* serialized form and returns the number of bytes written.
*/