aboutsummaryrefslogtreecommitdiff
path: root/pack.c
blob: 50d72f1fb3588869bf5a9ba448fe3a4b073aeafd (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
99
100
101
102
103
104
105
106
107
108
109
#include <u.h>
#include <libc.h>
#include <draw.h>
#include "libgeometry/geometry.h"
#include "dat.h"
#include "fns.h"

static ulong
get4(uchar *p)
{
	return p[0]<<24 | p[1]<<16 | p[2]<<8 | p[3];
}

static void
put4(uchar *p, ulong u)
{
	p[0] = u>>24, p[1] = u>>16, p[2] = u>>8, p[3] = u;
}

static int
vpack(uchar *p, int n, char *fmt, va_list a)
{
	uchar *p0 = p, *e = p+n;
	FPdbleword d;
	Point2 P;

	for(;;){
		switch(*fmt++){
		case '\0':
			return p - p0;
		case 'd':
			d.x = va_arg(a, double);

			if(p+8 > e)
				goto err;

			put4(p, d.hi), p += 4;
			put4(p, d.lo), p += 4;

			break;
		case 'P':
			P = va_arg(a, Point2);

			if(p+3*8 > e)
				goto err;

			pack(p, n, "ddd", P.x, P.y, P.w), p += 3*8;
			break;
		}
	}
err:
	return -1;
}

static int
vunpack(uchar *p, int n, char *fmt, va_list a)
{
	uchar *p0 = p, *e = p+n;
	FPdbleword d;
	Point2 P;

	for(;;){
		switch(*fmt++){
		case '\0':
			return p - p0;
		case 'd':
			if(p+8 > e)
				goto err;

			d.hi = get4(p), p += 4;
			d.lo = get4(p), p += 4;
			*va_arg(a, double*) = d.x;

			break;
		case 'P':
			if(p+3*8 > e)
				goto err;

			unpack(p, n, "ddd", &P.x, &P.y, &P.w), p += 3*8;
			*va_arg(a, Point2*) = P;
		}
	}
err:
	return -1;
}

int
pack(uchar *p, int n, char *fmt, ...)
{
	va_list a;

	va_start(a, fmt);
	n = vpack(p, n, fmt, a);
	va_end(a);

	return n;
}

int
unpack(uchar *p, int n, char *fmt, ...)
{
	va_list a;

	va_start(a, fmt);
	n = vunpack(p, n, fmt, a);
	va_end(a);

	return n;
}