-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathLengthFramer.c
More file actions
executable file
·55 lines (52 loc) · 1.68 KB
/
Copy pathLengthFramer.c
File metadata and controls
executable file
·55 lines (52 loc) · 1.68 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
//
// Created by tw on 2018/3/2.
//
#include <stdio.h>
#include <stdlib.h>
#include <stdint.h>
#include <netinet/in.h>
#include "Practical.h"
/**
* Read 2-byte length and place in big-endian order.
* Then read the indicated number of bytes.
* If the input buffer is too small for the date, truncate to fit and
* return the negation of the *indicated* length. Thus a negative return
* other than -1 indicate that the message was truncated.
* (Ambiguity is possiable only if the caller passses an empty buffer.)
* Input stream is always left empty.
*/
int GetNextMsg(FILE *in, uint8_t *buf, size_t bufSize) {
uint16_t mSize = 0;
uint16_t extra = 0;
if (fread(&mSize, sizeof(uint16_t), 1, in) != 1)
return -1;
mSize = ntohs(mSize);
if (mSize > bufSize) {
extra = mSize - bufSize;
mSize = bufSize;
}
if (fread(buf, sizeof(uint8_t), mSize, in) != mSize) {
fprintf(stderr, "Framing error: expected %d, read less\n", mSize);
return -1;
}
if (extra > 0) {
uint8_t waste[BUFSIZ];
fread(waste, sizeof(uint8_t), extra, in);
return -(mSize+extra);
} else
return mSize;
}
/**
* Write the given message to the output stream, followed by
* the delimiter. Precondidion: buf[] is at least msgSize.
* Returns -1 on any error.
*/
int PutMsg(uint8_t buf[], size_t msgSize, FILE *out) {
if (msgSize > UINT16_MAX)
return -1;
uint16_t payloadSize = htons(msgSize);
if ((fwrite(&payloadSize, sizeof(uint16_t), 1, out) != 1) || (fwrite(buf, sizeof(uint8_t), msgSize, out) != msgSize))
return -1;
fflush(out);
return msgSize;
}