diff options
Diffstat (limited to '')
-rw-r--r-- | src/stream.c | 98 |
1 files changed, 98 insertions, 0 deletions
diff --git a/src/stream.c b/src/stream.c new file mode 100644 index 0000000..1993df6 --- /dev/null +++ b/src/stream.c @@ -0,0 +1,98 @@ +#include "stream.h" +#include "lib.h" + +#include <netinet/in.h> +#include <stdio.h> +#include <stdlib.h> +#include <string.h> + +stream_t stream_open(char *path, char* mode) { + stream_t stream; + + if (strcmp("-", path) == 0) { + stream.__file = stdin; + stream.__alloc = false; + } + + stream.__file = fopen(path, mode); + stream.__alloc = true; + + if (stream.__file == NULL) { + perror_and_die("cannot read '%s'", path); + }; + + return stream; +} + +void stream_close(stream_t *stream) { + if (stream->__alloc) + fclose(stream->__file); +} + +bool stream_read(stream_t *stream, void *res, size_t amount) { + size_t read; + read = fread(res, 1, amount, stream->__file); + + if (read == 0) { + if (feof(stream->__file)) + return false; + else + perror_and_die("cannot read open stream"); + } + + return true; +} + +bool stream_read_i8(stream_t *stream, int8_t *res) { + if (stream_read(stream, res, 1) == false) + return false; + return true; +} + +bool stream_read_i16(stream_t *stream, int16_t *res) { + if (stream_read(stream, res, 2) == false) + return false; + *res = ntohs(*res); + return true; +} + +bool stream_read_i32(stream_t *stream, int32_t *res) { + if (stream_read(stream, res, 4) == false) + return false; + *res = ntohl(*res); + return true; +} + +static uint64_t ntohll(uint64_t ll) { + if (htons(20) == 20) + return ll; + + union { uint64_t ll; uint8_t c[8]; } out = {0}; + union { uint64_t ll; uint8_t c[8]; } in = {ll}; + + for (int i = 0; i < 8; i++) + out.c[7-i] = in.c[i]; + + return out.ll; +} + +bool stream_read_i64(stream_t *stream, int64_t *res) { + if (stream_read(stream, res, 8) == false) + return false; + *res = ntohll(*res); + return true; +} + +bool stream_read_u16(stream_t *stream, uint16_t *res) { + if (stream_read(stream, res, 2) == false) + return false; + *res = ntohs(*res); + return true; +} + +bool stream_read_u32(stream_t *stream, uint32_t *res) { + if (stream_read(stream, res, 4) == false) + return false; + *res = ntohl(*res); + return true; +} |