summaryrefslogtreecommitdiff
path: root/src/stream.c
blob: 1993df69b7e4a75fdc36a0e801e534ed98d7c4f4 (plain)
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
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
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;
}