summaryrefslogtreecommitdiffstats
path: root/src/test.c
blob: 82da068cb29076d0229e12e9e7a140a8fbe02a2e (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
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
#include "slip.h"

#include <string.h>
#include <stdarg.h>
#include <stdio.h>

void
die(const char *fmt, ...)
{
	va_list ap;

	va_start(ap, fmt);
	fputs("libslip-test: ", stderr);
	vfprintf(stderr, fmt, ap);
	if (*fmt && fmt[strlen(fmt) - 1] == ':') {
		fputc(' ', stderr);
		perror(NULL);
	} else {
		fputc('\n', stderr);
	}
	va_end(ap);

	exit(1);
}

int
slip_realloc(void **buf, size_t size)
{
	*buf = realloc(*buf, size);
	if (!*buf) die("realloc:");

	return 0;
}

void
slip_restart(struct slip *slip, uint8_t b)
{
	printf("RESTART due to '%02x' byte\n", b);
}

void
slip_rx(struct slip *slip, uint8_t *data, size_t len, void *user)
{
	printf("PACKET %.*s\n", (int) len, data);
}

int
main(int argc, const char **argv)
{
	uint8_t iobuf[BUFSIZ];
	uint8_t encbuf[BUFSIZ * 2 + 2];
	struct slip slip = { 0 };
	size_t enclen, nread;
	int rc;

	slip.realloc = slip_realloc;
	slip.rx_packet = slip_rx;
	slip.rx_restart = slip_restart;
	slip.esc = '\\';
	slip.start = '<';
	slip.end = '>';
	slip.esc_active['\\'] = true;
	slip.esc_enc['\\'] = '\\';
	slip.esc_active['<'] = true;
	slip.esc_enc['<'] = '<';
	slip.esc_active['>'] = true;
	slip.esc_enc['>'] = '>';

	rc = slip_init(&slip);
	if (rc) die("slip_init");

	if (argc == 2 && !strcmp(argv[1], "-d")) {
		while ((nread = fread(iobuf, 1, sizeof(iobuf), stdin))) {
			rc = slip_decode(&slip, iobuf, nread);
			if (rc) die("slip_decode");
		}
	} else {
		while ((nread = fread(iobuf, 1, sizeof(iobuf), stdin))) {
			rc = slip_encode(&slip, encbuf, &enclen,
				sizeof(encbuf), iobuf, nread);
			if (rc) die("slip_encode");
			fwrite(encbuf, 1, enclen, stdout);
		}
	}

	slip_deinit(&slip);
}