--- libelwix/src/pack.c 2014/02/11 01:06:21 1.6 +++ libelwix/src/pack.c 2014/02/13 15:06:44 1.6.2.3 @@ -3,7 +3,7 @@ * by Michael Pounov * * $Author: misho $ -* $Id: pack.c,v 1.6 2014/02/11 01:06:21 misho Exp $ +* $Id: pack.c,v 1.6.2.3 2014/02/13 15:06:44 misho Exp $ * ************************************************************************** The ELWIX and AITNET software is distributed under the following @@ -100,6 +100,77 @@ rpack_destroy(rpack_t ** __restrict rp) } /* + * rpack_attach() - Attach dynamic allocating buffer at packet + * + * @rp = raw packet; + * @len = allocate bytes + * return: -1 error or 0 ok, should be detached with rpack_detach() + * before call rpack_destroy() after use! + */ +int +rpack_attach(rpack_t * __restrict rp, size_t len) +{ + if (!rp) + return -1; + + rp->r_buf = e_malloc(len); + if (!rp->r_buf) { + RPACK_FREE(rp); + return -1; + } else + rp->r_len = len; + rp->r_next = rp->r_buf; + + return 0; +} + +/* + * rpack_resize() - Resize dynamic allocated buffer at packet + * + * @rp = raw packet + * @newlen = resize buffer to bytes + * return: -1 error or 0 ok, should be detached with rpack_detach() + * before call rpack_destroy() after use! + */ +int +rpack_resize(rpack_t * __restrict rp, size_t newlen) +{ + void *buf = NULL; + + if (!rp) + return -1; + + buf = e_realloc(rp->r_buf, newlen); + if (!buf) + return -1; + else { + rp->r_buf = buf; + rp->r_len = newlen; + } + + if (rp->r_next > (rp->r_buf + rp->r_len)) + rp->r_next = rp->r_buf; + + return 0; +} + +/* + * rpack_detach() - Detach and free dynamic allocated buffer from packet + * + * @rp = raw packet + * return: none + */ +void +rpack_detach(rpack_t * __restrict rp) +{ + if (!rp) + return; + + e_free(rp->r_buf); + RPACK_FREE(rp); +} + +/* * rpack_align_and_reserve() - Align & reserve space * * @rp = raw buffer @@ -432,4 +503,52 @@ rpack_ruint64(rpack_t * __restrict rp, uint64_t * __re rp->r_next += sizeof(uint64_t); return u; +} + +/* + * rpack_next() - Get and set current position + * + * @rp = raw packet + * @after_len = move aligned current position after length + * return: NULL error or current position + */ +uint8_t * +rpack_next(rpack_t * __restrict rp, size_t after_len) +{ + uint8_t *cur = NULL, *next = NULL; + + if (!RPACK_SANITY(rp)) + return NULL; + /* No space left */ + if (!(next = rpack_align_and_reserve(rp, after_len))) + return NULL; + + cur = rp->r_next; + + rp->r_next = next + after_len; + return cur; +} + +/* + * rpack_rnext() - Get and set raw current position + * + * @rp = raw packet + * @after_len = !=0 move current position after length + * return: NULL error or raw current position + */ +uint8_t * +rpack_rnext(rpack_t * __restrict rp, size_t after_len) +{ + uint8_t *next = NULL; + + if (!RPACK_SANITY(rp)) + return NULL; + /* No space left */ + if (after_len + rp->r_next - rp->r_buf > rp->r_len) + return NULL; + + next = rp->r_next; + + rp->r_next += after_len; + return next; }