]> git.sesse.net Git - fjl/blobdiff - input.c
Move some common input stuff around.
[fjl] / input.c
diff --git a/input.c b/input.c
new file mode 100644 (file)
index 0000000..2d80457
--- /dev/null
+++ b/input.c
@@ -0,0 +1,36 @@
+#include <stdio.h>
+#include <stdlib.h>
+#include <assert.h>
+
+#include "input.h"
+
+void reliable_read(raw_input_func_t* input_func, void* userdata, uint8_t* buf, size_t len)
+{
+       while (len > 0) {
+               ssize_t bytes_read = input_func(userdata, buf, len);
+               assert(bytes_read <= (ssize_t)len);
+
+               // TODO: We need better error handling here. setjmp()/longjmp()
+               // should hopefully do the trick, but we need to take care for
+               // suspension.
+               if (bytes_read == (ssize_t)-1) {
+                       fprintf(stderr, "Input function returned error\n");
+                       exit(1);
+               }
+               if (bytes_read == 0) {
+                       fprintf(stderr, "Premature EOF\n");
+                       exit(1);
+               }
+
+               buf += bytes_read;
+               len -= bytes_read;
+       }
+}
+
+uint16_t read_length(raw_input_func_t* input_func, void* userdata)
+{
+       uint8_t buf[2];
+       reliable_read(input_func, userdata, buf, 2);
+       return (buf[0] << 8) | buf[1];
+}
+