summaryrefslogtreecommitdiff
path: root/uncompress.c
blob: 3ef83ecb5367682f88a0163e2829244dc7e6bae0 (plain) (blame)
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
// SPDX-License-Identifier: LGPL-3.0-or-later

#include <stdio.h>
#include <stdint.h>

int main() {
	FILE *in = stdin;
	FILE *out = stdout;

	int c;
	uint8_t out_i = 0;
	char outbuf[256];
	while(1) {
		c = fgetc_unlocked(in);
		if(c < 0) goto end;
		uint8_t cmd = c;
		for(size_t i = 0; i < 8; i++) {
			if(cmd & 1) {
				c = fgetc_unlocked(in);
				if(c < 0) goto fail;
				uint8_t offset = c;
				offset += 1;
				c = fgetc_unlocked(in);
				if(c < 0) goto fail;
				uint8_t len = c;
				do {
					c = outbuf[(uint8_t)(out_i - offset)];
					outbuf[out_i++] = c;
					c = fputc_unlocked(c, out);
					if(c < 0) goto writefail;
				} while(len--);
			} else {
				c = fgetc_unlocked(in);
				if(c < 0) goto end;
				outbuf[out_i++] = c;
				c = fputc_unlocked(c, out);
				if(c < 0) goto writefail;
			}
			cmd >>= 1;
		}
	}

end:
	if(feof_unlocked(in)) return 0;
fail:
	fprintf(stderr, ferror_unlocked(in) ? "Read Error: %m\n" : "Unexpected EOF\n");
	return 1;
writefail:
	fprintf(stderr, "Write Error: %m\n");
	return 1;
}