Move some common input stuff around.
[fjl] / input.c
1 #include <stdio.h>
2 #include <stdlib.h>
3 #include <assert.h>
4
5 #include "input.h"
6
7 void reliable_read(raw_input_func_t* input_func, void* userdata, uint8_t* buf, size_t len)
8 {
9         while (len > 0) {
10                 ssize_t bytes_read = input_func(userdata, buf, len);
11                 assert(bytes_read <= (ssize_t)len);
12
13                 // TODO: We need better error handling here. setjmp()/longjmp()
14                 // should hopefully do the trick, but we need to take care for
15                 // suspension.
16                 if (bytes_read == (ssize_t)-1) {
17                         fprintf(stderr, "Input function returned error\n");
18                         exit(1);
19                 }
20                 if (bytes_read == 0) {
21                         fprintf(stderr, "Premature EOF\n");
22                         exit(1);
23                 }
24
25                 buf += bytes_read;
26                 len -= bytes_read;
27         }
28 }
29
30 uint16_t read_length(raw_input_func_t* input_func, void* userdata)
31 {
32         uint8_t buf[2];
33         reliable_read(input_func, userdata, buf, 2);
34         return (buf[0] << 8) | buf[1];
35 }
36