Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions include/packet.h
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,7 @@ typedef struct {
int size; /* the size for all valid characters in data buffer */
int cap; /* the capacity (1 << cap) of the data buffer */
int end_pos; /* the end position of the first packet in data buffer */
int start;
uint8_t *data;
} pktbuf_t;

Expand Down
21 changes: 12 additions & 9 deletions src/packet.c
Original file line number Diff line number Diff line change
Expand Up @@ -7,13 +7,15 @@ static void pktbuf_clear(pktbuf_t *pktbuf)
{
pktbuf->end_pos = -1;
pktbuf->size = 0;
pktbuf->start = 0;
}

#define DEFAULT_CAP (10)
bool pktbuf_init(pktbuf_t *pktbuf)
{
pktbuf->cap = DEFAULT_CAP;
pktbuf->data = calloc(1, (1 << pktbuf->cap) * sizeof(uint8_t));
pktbuf->start = 0;
pktbuf_clear(pktbuf);

return true;
Expand Down Expand Up @@ -46,7 +48,7 @@ bool pktbuf_is_complete(pktbuf_t *pktbuf)

/* skip to the head of next packet */
for (int i = 0; i < pktbuf->size; i++) {
if (pktbuf->data[i] == '$') {
if (pktbuf->data[pktbuf->start + i] == '$') {
head = i;
break;
}
Expand All @@ -59,21 +61,23 @@ bool pktbuf_is_complete(pktbuf_t *pktbuf)

if (head > 0) {
/* moving memory for a valid packet */
memmove(pktbuf->data, pktbuf->data + head, pktbuf->size - head);
// memmove(pktbuf->data, pktbuf->data + head, pktbuf->size - head);
// pktbuf->size -= head;
pktbuf->start += head;
pktbuf->size -= head;
}

/* check the end of the buffer */
uint8_t *end_pos_ptr = memchr(pktbuf->data, '#', pktbuf->size);
uint8_t *end_pos_ptr =
memchr(pktbuf->data + pktbuf->start, '#', pktbuf->size);
if (end_pos_ptr == NULL)
return false;

int end_pos = (end_pos_ptr - pktbuf->data) + CSUM_SIZE;
if (end_pos > pktbuf->size)
int end_pos = (end_pos_ptr - (pktbuf->data + pktbuf->start)) + CSUM_SIZE;
if (end_pos >= pktbuf->size)
return false;

pktbuf->end_pos = end_pos;

return true;
}

Expand All @@ -85,12 +89,11 @@ packet_t *pktbuf_pop_packet(pktbuf_t *pktbuf)

int old_pkt_size = pktbuf->end_pos + 1;
packet_t *pkt = calloc(1, sizeof(packet_t) + old_pkt_size + 1);
memcpy(pkt->data, pktbuf->data, old_pkt_size);
memcpy(pkt->data, pktbuf->data + pktbuf->start, old_pkt_size);
pkt->end_pos = pktbuf->end_pos;
pkt->data[old_pkt_size] = 0;

memmove(pktbuf->data, pktbuf->data + old_pkt_size + 1,
pktbuf->size - old_pkt_size);
pktbuf->start += old_pkt_size + 1;
pktbuf->size -= old_pkt_size;
pktbuf->end_pos = -1;
return pkt;
Expand Down