Add uc_mbuf_extend_headroom function, for growing an mbuf

This commit is contained in:
Nils O. Selåsdal
2013-11-25 23:28:13 +01:00
parent 306a3d2a90
commit dbe2f174a8
3 changed files with 146 additions and 2 deletions
+79
View File
@@ -1,4 +1,5 @@
#include <string.h>
#include <assert.h>
#include <stdlib.h>
#include "ucore/mbuf.h"
@@ -119,3 +120,81 @@ struct MBuf *uc_mbuf_copy_data(struct MBuf *mbuf)
return copy;
}
int uc_mbuf_extend_tailroom(struct MBuf *mbuf, uint32_t len)
{
uint32_t tot_len;
uint32_t headroom_len;
uint32_t data_len;
uint32_t tailroom_len;
uint8_t *new_data;
uint32_t p1_off;
uint32_t p2_off;
uint32_t p3_off;
uint32_t p4_off;
if ((mbuf->flags & (UC_MBUF_FL_MALLOC | UC_MBUF_FL_MALLOC_BUF)) == 0) {
return -1;
}
headroom_len = uc_mbuf_headroom(mbuf);
data_len = uc_mbuf_len(mbuf);
tailroom_len = uc_mbuf_tailroom(mbuf);
tot_len = headroom_len +
data_len +
tailroom_len;
if (tot_len + len < tot_len) {
//overflowed
return -2;
}
tot_len += len;
//need to re-adjust p1-p4 after the realloc
//This assumes the user controlled p1-p4 really are
//set to point into the data, but we document they have
//to be.
if (mbuf->p1 != NULL) {
p1_off = (uint32_t)(mbuf->p1 - mbuf->bufstart);
}
if (mbuf->p2 != NULL) {
p2_off = (uint32_t)(mbuf->p2 - mbuf->bufstart);
}
if (mbuf->p3 != NULL) {
p3_off = (uint32_t)(mbuf->p3 - mbuf->bufstart);
}
if (mbuf->p4 != NULL) {
p4_off = (uint32_t)(mbuf->p4 - mbuf->bufstart);
}
assert(tot_len >= mbuf->allocated);
new_data = realloc(mbuf->bufstart, tot_len);
if (new_data == NULL) {
return -3;
}
mbuf->allocated = tot_len;
mbuf->bufstart = new_data;
mbuf->head = mbuf->bufstart + headroom_len;
mbuf->tail = mbuf->bufstart + headroom_len + data_len;
assert(uc_mbuf_len(mbuf) == data_len);
assert(uc_mbuf_tailroom(mbuf) >= tailroom_len);
if (mbuf->p1 != NULL) {
mbuf->p1 = mbuf->bufstart + p1_off;
}
if (mbuf->p2 != NULL) {
mbuf->p2 = mbuf->bufstart + p2_off;
}
if (mbuf->p3 != NULL) {
mbuf->p3 = mbuf->bufstart + p3_off;
}
if (mbuf->p4 != NULL) {
mbuf->p4 = mbuf->bufstart + p4_off;
}
return 0;
}