Files
libucore/src/mbuf.c
T
2013-09-13 21:42:32 +02:00

122 lines
2.4 KiB
C

#include <string.h>
#include <stdlib.h>
#include "ucore/mbuf.h"
uint8_t *uc_mbuf_put(struct MBuf *mbuf, uint32_t size)
{
uint8_t *data = mbuf->tail;
if (uc_mbuf_tailroom(mbuf) < size) {
return NULL;
}
mbuf->tail += size;
return data;
}
uint8_t *uc_mbuf_push(struct MBuf *mbuf, uint32_t size)
{
if (uc_mbuf_headroom(mbuf) < size) {
return NULL;
}
mbuf->head -= size;
return mbuf->head;
}
uint8_t *uc_mbuf_pull(struct MBuf *mbuf, uint32_t size)
{
uint8_t *data = mbuf->head;
if (uc_mbuf_len(mbuf) < size) {
return NULL;
}
mbuf->head += size;
return data;
}
void uc_mbuf_init(struct MBuf *mbuf, uint8_t *buf, uint32_t len, uint32_t headroom, uint32_t flags)
{
mbuf->bufstart = buf;
mbuf->next = NULL;
mbuf->p1 = mbuf->p2 = mbuf->p3 = mbuf->p4 = NULL;
mbuf->cookie = NULL;
mbuf->flags = flags;
mbuf->allocated = len + headroom;
mbuf->head = mbuf->bufstart + headroom;
mbuf->tail = mbuf->head;
}
struct MBuf *uc_mbuf_new_hr(uint32_t len, uint32_t headroom)
{
struct MBuf *mbuf;
uint8_t *buf;
mbuf = malloc(sizeof *mbuf);
if (mbuf == NULL)
return mbuf;
buf = malloc(len + headroom);
if (buf == NULL) {
free(mbuf);
return NULL;
}
uc_mbuf_init(mbuf, buf, len, headroom, UC_MBUF_FL_MALLOC);
return mbuf;
}
struct MBuf *uc_mbuf_new_inline_hr(uint32_t len, uint32_t headroom)
{
struct MBuf *mbuf;
mbuf = malloc(sizeof *mbuf + len + headroom);
if (mbuf == NULL)
return mbuf;
uc_mbuf_init(mbuf, mbuf->inline_data, len, headroom, UC_MBUF_FL_MALLOC_INLINE);
return mbuf;
}
void uc_mbuf_free(struct MBuf *mbuf)
{
if (mbuf != NULL) {
if (mbuf->flags & (UC_MBUF_FL_MALLOC | UC_MBUF_FL_MALLOC_BUF))
free(mbuf->bufstart);
if (mbuf->flags & (UC_MBUF_FL_MALLOC | UC_MBUF_FL_MALLOC_INLINE))
free(mbuf);
}
}
void uc_mbuf_zero(struct MBuf *mbuf)
{
memset(mbuf->bufstart, 0, mbuf->allocated);
}
struct MBuf *uc_mbuf_copy_data(struct MBuf *mbuf)
{
uint32_t len;
struct MBuf *copy;
uint8_t *data;
len = uc_mbuf_len(mbuf);
copy = uc_mbuf_new_hr(len, uc_mbuf_headroom(mbuf));
if (copy == NULL) {
return NULL;
}
data = uc_mbuf_put(copy, len);
memcpy(data, mbuf->head, len);
return copy;
}