In the old times when decoding some messages in the socket using `read`.
Code:
ssize_t read( int fd, void *buf, size_t count );
The senior programmers would get angry if you set count to 1. They would advocate to bulk read a chunk of data into a buffer and move the pointer along when decoding the buffer. This is what I have believed in up to this very date.
If the socket data is structured, I would simply define the struct and cast over the buffer.
Code:
typedef struct certain_data {
int32_t a;
int32_t b;
} certain_data_t;
Hooray! This is efficient enough.
However when the socket data is unstructured and breaks the byte-alignment, the old time method does not work?
For example, the protocol is something like this:
Code:
int32_t time;
uint8_t cType;
uint16_t len;
char name[len];
Things get nasty:
1) a single byte 'cType' is inserted which breaks the byte-alignment in my own data struct. I cannot simply cast the buffer.
2) the socket protocol adopts a variable length field. I cannot simply read the 'name' field without looking at 'len'.
Eventually I'll have to do a lot of expensive memcpy.
What would you suggest to tackle efficiently?